events
stringlengths
233
2.9k
input
stringlengths
273
1.93k
output
stringlengths
363
2.15k
User edited file: "tests/web/test_request.py": ```diff @@ -4,7 +4,7 @@ class RequestTestCase(unittest.TestCase): def setUp(self): - self.url = 'http://www.google.com' + self.host = 'http://www.google.com' def test_constants(self): self.assertEqual('get', Request.GET) @@ -40,4 +40,4 @@ def test_time_error(self): request = Request(url=self.url, type=Request.GET) with self.assertRaises(RequestTimeError): - request.get_response_time() + request.get_response_time() ``` User edited file: "tests/web/test_request.py": ```diff @@ -11,10 +11,10 @@ self.assertEqual('post', Request.POST) def test_init(self): - request = Request(url=self.url) + request = Request(url=self.host) self.assertEqual(Request.GET, request.type) - self.assertEqual(self.url, request.url) - request = Request(url=self.url, type=Request.POST) + self.assertEqual(self.host, request.url) + request = Request(url=self.host, type=Request.POST) self.assertEqual(Request.POST, request.type) def test_do(self): ``` User edited file: "tests/web/test_request.py": ```diff @@ -18,12 +18,8 @@ self.assertEqual(Request.POST, request.type) def test_do(self): - request = Request(url=self.url, type=Request.GET) + request = Request(url=self.host, type=Request.GET) request.do() - self.assertTrue(hasattr(request, 'status_code')) - request.type = Request.POST - request.do() - self.assertTrue(hasattr(request, 'status_code')) def test_invalid_type(self): type = 'foo_bar' ```
```tests/web/test_request.py import unittest from performance.web import Request, RequestTypeError, RequestTimeError class RequestTestCase(unittest.TestCase): def setUp(self): self.host = 'http://www.google.com' def test_constants(self): self.assertEqual('get', Request.GET) self.assertEqual('post', Request.POST) def test_init(self): request = Request(url=self.host) self.assertEqual(Request.GET, request.type) self.assertEqual(self.host, request.url) request = Request(url=self.host, type=Request.POST) self.assertEqual(Request.POST, request.type) def test_do(self): request = Request(url=self.host, type=Request.GET) request.do() def test_invalid_type(self): type = 'foo_bar' <|user_cursor_is_here|> request = Request(url=self.url, type=type) with self.assertRaises(RequestTypeError) as error: request.do() self.assertEqual('Invalid request type "%s"' % type, error.exception.__str__()) def test_response_time(self): request = Request(url=self.url, type=Request.GET) request.do() self.assertEqual(request.finished - request.started, request.get_response_time()) def test_time_error(self): request = Request(url=self.url, type=Request.GET) with self.assertRaises(RequestTimeError): request.get_response_time() ```
```tests/web/test_request.py import unittest from performance.web import Request, RequestTypeError, RequestTimeError class RequestTestCase(unittest.TestCase): def setUp(self): self.host = 'http://www.google.com' def test_constants(self): self.assertEqual('get', Request.GET) self.assertEqual('post', Request.POST) def test_init(self): request = Request(url=self.host) self.assertEqual(Request.GET, request.type) self.assertEqual(self.host, request.url) request = Request(url=self.host, type=Request.POST) self.assertEqual(Request.POST, request.type) def test_do(self): request = Request(url=self.host, type=Request.GET) request.do() def test_invalid_type(self): type = 'foo_bar' <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "self.url", "newName": "self.host"}} </|tool_call|> request = Request(url=self.url, type=type) with self.assertRaises(RequestTypeError) as error: request.do() self.assertEqual('Invalid request type "%s"' % type, error.exception.__str__()) def test_response_time(self): request = Request(url=self.url, type=Request.GET) request.do() self.assertEqual(request.finished - request.started, request.get_response_time()) def test_time_error(self): request = Request(url=self.url, type=Request.GET) with self.assertRaises(RequestTimeError): request.get_response_time() ```
User edited file: "protobuf-test/src/v2/test_tokio_bytes_default_value.rs": ```diff @@ -4,14 +4,11 @@ #[test] fn test_default_values() { - assert_eq!( - "sss", - TestTokioBytesDefaultValues::default_instance().get_s() - ); + assert_eq!("sss", TestTokioBytesDefaultValues::default_instance().s()); assert_eq!( b"bbb", TestTokioBytesDefaultValues::default_instance().get_b() ); assert_eq!(&""[..], &**TestTokioBytesDefaultValues::new().mut_s()); assert_eq!(&b""[..], &**TestTokioBytesDefaultValues::new().mut_b()); -} +} ```
```protobuf-test/src/v2/test_tokio_bytes_default_value.rs use protobuf::*; use super::test_tokio_bytes_default_value_pb::*; #[test] fn test_default_values() { assert_eq!("sss", TestTokioBytesDefaultValues::default_instance().s()); <|user_cursor_is_here|> assert_eq!( b"bbb", TestTokioBytesDefaultValues::default_instance().get_b() ); assert_eq!(&""[..], &**TestTokioBytesDefaultValues::new().mut_s()); assert_eq!(&b""[..], &**TestTokioBytesDefaultValues::new().mut_b()); } ```
```protobuf-test/src/v2/test_tokio_bytes_default_value.rs use protobuf::*; use super::test_tokio_bytes_default_value_pb::*; #[test] fn test_default_values() { assert_eq!("sss", TestTokioBytesDefaultValues::default_instance().s()); <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "get_b", "newName": "b"}} </|tool_call|> assert_eq!( b"bbb", TestTokioBytesDefaultValues::default_instance().get_b() ); assert_eq!(&""[..], &**TestTokioBytesDefaultValues::new().mut_s()); assert_eq!(&b""[..], &**TestTokioBytesDefaultValues::new().mut_b()); } ```
User edited file: "parse-parameter.js": ```diff @@ -3,7 +3,7 @@ let moment = require('moment'); let dateTimeFormat = require('./date-time-format'); -module.exports = function(value) { +module.exports = exports = function(value) { if(value[0] === '@') { return moment(parseDate(value.slice(1))).format(dateTimeFormat); } @@ -19,4 +19,4 @@ return value; } } -}; +}; ```
```parse-parameter.js 'use strict'; let moment = require('moment'); let dateTimeFormat = require('./date-time-format'); module.exports = exports = function(value) { if(value[0] === '@') { return moment(parseDate(value.slice(1))).format(dateTimeFormat); } try { return JSON.parse(value); } catch(error) { if(value.indexOf(',') !== -1) { <|user_cursor_is_here|> return value.split(',').map(maybeParse); } else { return value; } } }; ```
```parse-parameter.js 'use strict'; let moment = require('moment'); let dateTimeFormat = require('./date-time-format'); module.exports = exports = function(value) { if(value[0] === '@') { return moment(parseDate(value.slice(1))).format(dateTimeFormat); } try { return JSON.parse(value); } catch(error) { if(value.indexOf(',') !== -1) { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "maybeParse", "newName": "exports"}} </|tool_call|> return value.split(',').map(maybeParse); } else { return value; } } }; ```
User edited file: "examples/simple/src/main/java/coffee/CoffeeApp.java": ```diff @@ -6,7 +6,7 @@ public class CoffeeApp { @Singleton @Component(modules = { DripCoffeeModule.class }) - public interface Coffee { + public interface CoffeeShop { CoffeeMaker maker(); } @@ -14,4 +14,4 @@ Coffee coffee = DaggerCoffeeApp_Coffee.builder().build(); coffee.maker().brew(); } -} +} ```
```examples/simple/src/main/java/coffee/CoffeeApp.java package coffee; import dagger.Component; import javax.inject.Singleton; public class CoffeeApp { @Singleton @Component(modules = { DripCoffeeModule.class }) public interface CoffeeShop { CoffeeMaker maker(); } public static void main(String[] args) { <|user_cursor_is_here|> Coffee coffee = DaggerCoffeeApp_Coffee.builder().build(); coffee.maker().brew(); } } ```
```examples/simple/src/main/java/coffee/CoffeeApp.java package coffee; import dagger.Component; import javax.inject.Singleton; public class CoffeeApp { @Singleton @Component(modules = { DripCoffeeModule.class }) public interface CoffeeShop { CoffeeMaker maker(); } public static void main(String[] args) { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "coffee", "newName": "coffeeShop"}} </|tool_call|> Coffee coffee = DaggerCoffeeApp_Coffee.builder().build(); coffee.maker().brew(); } } ```
User edited file: "evaluate/src/main.rs": ```diff @@ -1,5 +1,7 @@ extern crate document; extern crate xpath; + +use std::io::File; use std::collections::hashmap::HashMap; @@ -36,4 +38,4 @@ let res = expr.evaluate(&context); println!("{}", res); -} +} ``` User edited file: "evaluate/src/main.rs": ```diff @@ -5,7 +5,8 @@ use std::collections::hashmap::HashMap; -use document::{Document,ToAny}; +use document::ToAny; +use document::parser::Parser; use xpath::{XPathEvaluationContext,XPathFactory}; use xpath::expression::XPathExpression; ``` User edited file: "evaluate/src/main.rs": ```diff @@ -14,9 +14,9 @@ fn main() { let mut args = std::os::args(); - let arg = match args.remove(1) { + let filename = match args.remove(1) { Some(x) => x, - None => { println!("XPath required"); return; }, + None => { println!("File required"); return; }, }; let factory = XPathFactory::new(); ``` User edited file: "evaluate/src/main.rs": ```diff @@ -17,6 +17,11 @@ let filename = match args.remove(1) { Some(x) => x, None => { println!("File required"); return; }, + }; + + let xpath_str = match args.remove(1) { + Some(x) => x, + None => { println!("XPath required"); return; }, }; let factory = XPathFactory::new(); ```
```evaluate/src/main.rs extern crate document; extern crate xpath; use std::io::File; use std::collections::hashmap::HashMap; use document::ToAny; use document::parser::Parser; use xpath::{XPathEvaluationContext,XPathFactory}; use xpath::expression::XPathExpression; fn main() { let mut args = std::os::args(); let filename = match args.remove(1) { Some(x) => x, None => { println!("File required"); return; }, }; let xpath_str = match args.remove(1) { Some(x) => x, None => { println!("XPath required"); return; }, }; let factory = XPathFactory::new(); <|user_cursor_is_here|> let expr = match factory.build(arg.as_slice()) { Err(x) => { println!("Unable to compile XPath: {}", x); return; }, Ok(None) => { println!("Unable to compile XPath"); return; }, Ok(Some(x)) => x, }; let d = Document::new(); let mut functions = HashMap::new(); xpath::function::register_core_functions(& mut functions); let variables = HashMap::new(); let mut context = XPathEvaluationContext::new(d.root().to_any(), &functions, &variables); context.next(d.root().to_any()); let res = expr.evaluate(&context); println!("{}", res); } ```
```evaluate/src/main.rs extern crate document; extern crate xpath; use std::io::File; use std::collections::hashmap::HashMap; use document::ToAny; use document::parser::Parser; use xpath::{XPathEvaluationContext,XPathFactory}; use xpath::expression::XPathExpression; fn main() { let mut args = std::os::args(); let filename = match args.remove(1) { Some(x) => x, None => { println!("File required"); return; }, }; let xpath_str = match args.remove(1) { Some(x) => x, None => { println!("XPath required"); return; }, }; let factory = XPathFactory::new(); <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "arg", "newName": "xpath_str"}} </|tool_call|> let expr = match factory.build(arg.as_slice()) { Err(x) => { println!("Unable to compile XPath: {}", x); return; }, Ok(None) => { println!("Unable to compile XPath"); return; }, Ok(Some(x)) => x, }; let d = Document::new(); let mut functions = HashMap::new(); xpath::function::register_core_functions(& mut functions); let variables = HashMap::new(); let mut context = XPathEvaluationContext::new(d.root().to_any(), &functions, &variables); context.next(d.root().to_any()); let res = expr.evaluate(&context); println!("{}", res); } ```
User edited file: "src/test/java/de/innoaccel/wamp/server/converter/GeneralMessageTests.java": ```diff @@ -18,7 +18,7 @@ } @Test(expected = MessageParseException.class) - public void deserializeThrowsMessageParseExceptionWhenThereIsNoFirstField(final Websocket socket) + public void deserializeThrowsMessageParseExceptionWhenThereIsNoMessageCodeField(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[]", socket); @@ -44,4 +44,4 @@ { this.converter.deserialize("[" + Message.INVALID + "]", socket); } -} +} ``` User edited file: "src/test/java/de/innoaccel/wamp/server/converter/GeneralMessageTests.java": ```diff @@ -25,7 +25,7 @@ } @Test(expected = MessageParseException.class) - public void deserializeThrowsMessageParseExceptionWhenFirstFieldIsNoNumber(final Websocket socket) + public void deserializeThrowsMessageParseExceptionWhenMessageCodeIsNoNumber(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[null]", socket); ```
```src/test/java/de/innoaccel/wamp/server/converter/GeneralMessageTests.java package de.innoaccel.wamp.server.converter; import de.innoaccel.wamp.server.Websocket; import de.innoaccel.wamp.server.message.Message; import org.junit.Test; import java.io.IOException; abstract public class GeneralMessageTests<T extends Message> { protected JsonParsingConverter<T> converter; @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenMessageIsNoArray(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("message", socket); } @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenThereIsNoMessageCodeField(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[]", socket); } @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenMessageCodeIsNoNumber(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[null]", socket); } @Test(expected = MessageParseException.class) <|user_cursor_is_here|> public void deserializeThrowsMessageParseExceptionWhenFirstFieldIsNoInteger(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[0.5f]", socket); } @Test(expected = InvalidMessageCodeException.class) public void deserializeThrowsInvalidMessageCodeExceptionWhenWrongMessageCode(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[" + Message.INVALID + "]", socket); } } ```
```src/test/java/de/innoaccel/wamp/server/converter/GeneralMessageTests.java package de.innoaccel.wamp.server.converter; import de.innoaccel.wamp.server.Websocket; import de.innoaccel.wamp.server.message.Message; import org.junit.Test; import java.io.IOException; abstract public class GeneralMessageTests<T extends Message> { protected JsonParsingConverter<T> converter; @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenMessageIsNoArray(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("message", socket); } @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenThereIsNoMessageCodeField(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[]", socket); } @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenMessageCodeIsNoNumber(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[null]", socket); } @Test(expected = MessageParseException.class) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "deserializeThrowsMessageParseExceptionWhenFirstFieldIsNoInteger", "newName": "deserializeThrowsMessageParseExceptionWhenMessageCodeIsNoInteger"}} </|tool_call|> public void deserializeThrowsMessageParseExceptionWhenFirstFieldIsNoInteger(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[0.5f]", socket); } @Test(expected = InvalidMessageCodeException.class) public void deserializeThrowsInvalidMessageCodeExceptionWhenWrongMessageCode(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[" + Message.INVALID + "]", socket); } } ```
User edited file: "fuzz/fuzz_targets/fuzz_asn1_parse.rs": ```diff @@ -1,6 +1,5 @@ #![no_main] -#[macro_use] -extern crate libfuzzer_sys; +use libfuzzer_sys::fuzz_target; libfuzzer_sys::fuzz_target!(|data: &[u8]| { let _ = asn1::parse(data, |d| { @@ -23,4 +22,4 @@ Ok(()) }); -}); +}); ```
```fuzz/fuzz_targets/fuzz_asn1_parse.rs #![no_main] use libfuzzer_sys::fuzz_target; <|user_cursor_is_here|> libfuzzer_sys::fuzz_target!(|data: &[u8]| { let _ = asn1::parse(data, |d| { d.read_element::<()>()?; d.read_element::<bool>()?; d.read_element::<i8>()?; d.read_element::<u8>()?; d.read_element::<i64>()?; d.read_element::<u64>()?; d.read_element::<&[u8]>()?; d.read_element::<asn1::PrintableString>()?; d.read_element::<asn1::ObjectIdentifier>()?; d.read_element::<asn1::BitString>()?; d.read_element::<asn1::UtcTime>()?; d.read_element::<Option<()>>()?; d.read_element::<asn1::Choice2<bool, i64>>()?; Ok(()) }); }); ```
```fuzz/fuzz_targets/fuzz_asn1_parse.rs #![no_main] use libfuzzer_sys::fuzz_target; <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "libfuzzer_sys::fuzz_target!", "newName": "fuzz_target!"}} </|tool_call|> libfuzzer_sys::fuzz_target!(|data: &[u8]| { let _ = asn1::parse(data, |d| { d.read_element::<()>()?; d.read_element::<bool>()?; d.read_element::<i8>()?; d.read_element::<u8>()?; d.read_element::<i64>()?; d.read_element::<u64>()?; d.read_element::<&[u8]>()?; d.read_element::<asn1::PrintableString>()?; d.read_element::<asn1::ObjectIdentifier>()?; d.read_element::<asn1::BitString>()?; d.read_element::<asn1::UtcTime>()?; d.read_element::<Option<()>>()?; d.read_element::<asn1::Choice2<bool, i64>>()?; Ok(()) }); }); ```
User edited file: "cmsplugin_zinnia/placeholder.py": ```diff @@ -4,7 +4,7 @@ from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder -from zinnia.models.entry import EntryAbstractClass +from zinnia.models_bases.entry import AbstractEntry class EntryPlaceholder(EntryAbstractClass): @@ -39,4 +39,4 @@ class Meta(EntryAbstractClass.Meta): """EntryPlaceholder's Meta""" - abstract = True + abstract = True ``` User edited file: "cmsplugin_zinnia/placeholder.py": ```diff @@ -7,7 +7,7 @@ from zinnia.models_bases.entry import AbstractEntry -class EntryPlaceholder(EntryAbstractClass): +class EntryPlaceholder(AbstractEntry): """Entry with a Placeholder to edit content""" content_placeholder = PlaceholderField('content') ```
```cmsplugin_zinnia/placeholder.py """Placeholder model for Zinnia""" import inspect from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models_bases.entry import AbstractEntry class EntryPlaceholder(AbstractEntry): """Entry with a Placeholder to edit content""" content_placeholder = PlaceholderField('content') def acquire_context(self): """ Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome ! """ frame = None try: for f in inspect.stack()[1:]: frame = f[0] args, varargs, keywords, alocals = inspect.getargvalues(frame) if 'context' in args: return alocals['context'] finally: del frame @property def html_content(self): """ Render the content_placeholder field dynamicly. https://github.com/Fantomas42/cmsplugin-zinnia/issues/3 """ context = self.acquire_context() return render_placeholder(self.content_placeholder, context) <|user_cursor_is_here|> class Meta(EntryAbstractClass.Meta): """EntryPlaceholder's Meta""" abstract = True ```
```cmsplugin_zinnia/placeholder.py """Placeholder model for Zinnia""" import inspect from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models_bases.entry import AbstractEntry class EntryPlaceholder(AbstractEntry): """Entry with a Placeholder to edit content""" content_placeholder = PlaceholderField('content') def acquire_context(self): """ Inspect the stack to acquire the current context used, to render the placeholder. I'm really sorry for this, but if you have a better way, you are welcome ! """ frame = None try: for f in inspect.stack()[1:]: frame = f[0] args, varargs, keywords, alocals = inspect.getargvalues(frame) if 'context' in args: return alocals['context'] finally: del frame @property def html_content(self): """ Render the content_placeholder field dynamicly. https://github.com/Fantomas42/cmsplugin-zinnia/issues/3 """ context = self.acquire_context() return render_placeholder(self.content_placeholder, context) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "EntryAbstractClass", "newName": "AbstractEntry"}} </|tool_call|> class Meta(EntryAbstractClass.Meta): """EntryPlaceholder's Meta""" abstract = True ```
User edited file: "consulrest/keyvalue.py": ```diff @@ -20,6 +20,8 @@ if r.ok: return json.loads(r.text) + elif r.status_code == 404: + return None else: r.raise_for_status() @@ -51,4 +53,4 @@ if recurse is not None: params['recurse'] = True r = requests.delete(url, params=params) - r.raise_for_status() + r.raise_for_status() ```
```consulrest/keyvalue.py import json import re import requests class KeyValue(object): def __init__(self, url): self._url = "%s/kv" % url def _get(self, key, recurse=None, keys=None): url = self._url + '/' + key params = dict() if recurse is not None: params['recurse'] = True if keys is not None: params['keys'] = True r = requests.get(url, params=params) if r.ok: return json.loads(r.text) elif r.status_code == 404: return None else: r.raise_for_status() def get(self, key, recurse=None): return self._get(key, recurse=recurse) <|user_cursor_is_here|> def list(self, key=''): return self._get(key, keys=True) def set(self, key, value, cas=None): params = dict() if cas is not None: params['cas'] = cas r = requests.put(self._url + '/' + key, data=value, params=params) if r.ok: if re.match(r"true", r.text) is not None: return True elif re.match(r"false", r.text) is not None: return False else: r.raise_for_status() def delete(self, key, recurse=None): url = self._url + '/' + key params = dict() if recurse is not None: params['recurse'] = True r = requests.delete(url, params=params) r.raise_for_status() ```
```consulrest/keyvalue.py import json import re import requests class KeyValue(object): def __init__(self, url): self._url = "%s/kv" % url def _get(self, key, recurse=None, keys=None): url = self._url + '/' + key params = dict() if recurse is not None: params['recurse'] = True if keys is not None: params['keys'] = True r = requests.get(url, params=params) if r.ok: return json.loads(r.text) elif r.status_code == 404: return None else: r.raise_for_status() def get(self, key, recurse=None): return self._get(key, recurse=recurse) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "list", "newName": "list_keys"}} </|tool_call|> def list(self, key=''): return self._get(key, keys=True) def set(self, key, value, cas=None): params = dict() if cas is not None: params['cas'] = cas r = requests.put(self._url + '/' + key, data=value, params=params) if r.ok: if re.match(r"true", r.text) is not None: return True elif re.match(r"false", r.text) is not None: return False else: r.raise_for_status() def delete(self, key, recurse=None): url = self._url + '/' + key params = dict() if recurse is not None: params['recurse'] = True r = requests.delete(url, params=params) r.raise_for_status() ```
User edited file: "src/KeyboardObserver.js": ```diff @@ -1,4 +1,4 @@ -import {DeviceEventEmitter} from 'react-native'; +import {Keyboard} from 'react-native'; class KeyboardObserver { @@ -42,4 +42,4 @@ } } -export default new KeyboardObserver(); +export default new KeyboardObserver(); ```
```src/KeyboardObserver.js import {Keyboard} from 'react-native'; class KeyboardObserver { constructor() { this.keyboardHeight = 0; this.animationWillEndAt = 0; this.listeners = {}; this.listenerId = 0; <|user_cursor_is_here|> DeviceEventEmitter.addListener('keyboardWillShow', this.handleKeyboardWillShow.bind(this)); DeviceEventEmitter.addListener('keyboardWillHide', this.handleKeyboardWillHide.bind(this)); } addListener(callback) { const id = this.listenerId++; this.listeners[id] = callback; return {remove: () => delete this.listeners[id]}; } notifyListeners() { const info = this.getKeyboardInfo(); Object.keys(this.listeners).forEach(key => this.listeners[key](info)); } handleKeyboardWillShow(frames) { this.keyboardHeight = frames.endCoordinates.height; this.animationWillEndAt = new Date().getTime() + frames.duration; this.notifyListeners() } handleKeyboardWillHide(frames) { this.animationWillEndAt = new Date().getTime() + frames.duration; this.keyboardHeight = 0; this.notifyListeners() } getKeyboardInfo() { return { keyboardHeight: this.keyboardHeight, animationWillEndAt: this.animationWillEndAt, }; } } export default new KeyboardObserver(); ```
```src/KeyboardObserver.js import {Keyboard} from 'react-native'; class KeyboardObserver { constructor() { this.keyboardHeight = 0; this.animationWillEndAt = 0; this.listeners = {}; this.listenerId = 0; <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "DeviceEventEmitter", "newName": "Keyboard"}} </|tool_call|> DeviceEventEmitter.addListener('keyboardWillShow', this.handleKeyboardWillShow.bind(this)); DeviceEventEmitter.addListener('keyboardWillHide', this.handleKeyboardWillHide.bind(this)); } addListener(callback) { const id = this.listenerId++; this.listeners[id] = callback; return {remove: () => delete this.listeners[id]}; } notifyListeners() { const info = this.getKeyboardInfo(); Object.keys(this.listeners).forEach(key => this.listeners[key](info)); } handleKeyboardWillShow(frames) { this.keyboardHeight = frames.endCoordinates.height; this.animationWillEndAt = new Date().getTime() + frames.duration; this.notifyListeners() } handleKeyboardWillHide(frames) { this.animationWillEndAt = new Date().getTime() + frames.duration; this.keyboardHeight = 0; this.notifyListeners() } getKeyboardInfo() { return { keyboardHeight: this.keyboardHeight, animationWillEndAt: this.animationWillEndAt, }; } } export default new KeyboardObserver(); ```
User edited file: "src/gx/realtime/RealtimeOptions.java": ```diff @@ -1,5 +1,6 @@ package gx.realtime; +import gx.realtime.RealtimeLoader.OnDocumentLoadedCallback; import gx.realtime.RealtimeLoader.InitializeModelCallback; import gx.realtime.RealtimeLoader.HandleErrorsCallback; @@ -56,4 +57,4 @@ public void setHandleErrors(HandleErrorsCallback handleErrors) { this.handleErrors = handleErrors; } -} +} ``` User edited file: "src/gx/realtime/RealtimeOptions.java": ```diff @@ -9,11 +9,10 @@ */ public class RealtimeOptions { - // Attributes private String clientId; private String docId; - private RealtimeLoader.OnDocumentLoadedCallback onFileLoaded; + private OnDocumentLoadedCallback onFileLoaded; private InitializeModelCallback initializeModel; private HandleErrorsCallback handleErrors; ``` User edited file: "src/gx/realtime/RealtimeOptions.java": ```diff @@ -33,7 +33,7 @@ this.docId = docId; } - public RealtimeLoader.OnDocumentLoadedCallback getOnFileLoaded() { + public OnDocumentLoadedCallback getOnFileLoaded() { return onFileLoaded; } ```
```src/gx/realtime/RealtimeOptions.java package gx.realtime; import gx.realtime.RealtimeLoader.OnDocumentLoadedCallback; import gx.realtime.RealtimeLoader.InitializeModelCallback; import gx.realtime.RealtimeLoader.HandleErrorsCallback; /** * Options (key/value) for the RealtimeLoader. */ public class RealtimeOptions { private String clientId; private String docId; private OnDocumentLoadedCallback onFileLoaded; private InitializeModelCallback initializeModel; private HandleErrorsCallback handleErrors; // Methods public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getDocId() { return docId; } public void setDocId(String docId) { this.docId = docId; } public OnDocumentLoadedCallback getOnFileLoaded() { return onFileLoaded; } <|user_cursor_is_here|> public void setOnFileLoaded(RealtimeLoader.OnDocumentLoadedCallback onFileLoaded) { this.onFileLoaded = onFileLoaded; } public InitializeModelCallback getInitializeModel() { return initializeModel; } public void setInitializeModel(InitializeModelCallback initializeModel) { this.initializeModel = initializeModel; } public HandleErrorsCallback getHandleErrors() { return handleErrors; } public void setHandleErrors(HandleErrorsCallback handleErrors) { this.handleErrors = handleErrors; } } ```
```src/gx/realtime/RealtimeOptions.java package gx.realtime; import gx.realtime.RealtimeLoader.OnDocumentLoadedCallback; import gx.realtime.RealtimeLoader.InitializeModelCallback; import gx.realtime.RealtimeLoader.HandleErrorsCallback; /** * Options (key/value) for the RealtimeLoader. */ public class RealtimeOptions { private String clientId; private String docId; private OnDocumentLoadedCallback onFileLoaded; private InitializeModelCallback initializeModel; private HandleErrorsCallback handleErrors; // Methods public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getDocId() { return docId; } public void setDocId(String docId) { this.docId = docId; } public OnDocumentLoadedCallback getOnFileLoaded() { return onFileLoaded; } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "RealtimeLoader.OnDocumentLoadedCallback", "newName": "OnDocumentLoadedCallback"}} </|tool_call|> public void setOnFileLoaded(RealtimeLoader.OnDocumentLoadedCallback onFileLoaded) { this.onFileLoaded = onFileLoaded; } public InitializeModelCallback getInitializeModel() { return initializeModel; } public void setInitializeModel(InitializeModelCallback initializeModel) { this.initializeModel = initializeModel; } public HandleErrorsCallback getHandleErrors() { return handleErrors; } public void setHandleErrors(HandleErrorsCallback handleErrors) { this.handleErrors = handleErrors; } } ```
User edited file: "test/dom/test/basics.spec.js": ```diff @@ -11,7 +11,7 @@ it('absolute tracking', async () => { let times = 0; let poolCopy; - const targetOne = createTarget({ marginLeft: '-30px' }); + const targetOne = createTarget({ left: '-30px' }); const targetTwo = createTarget({ marginTop: '30px' }); const targetThree = createTarget({ marginTop: '-30px' }); @@ -61,4 +61,4 @@ expect(times).to.equal(1); expect(poolCopy).to.include(targetThree); }); -}); +}); ``` User edited file: "test/dom/test/basics.spec.js": ```diff @@ -12,7 +12,7 @@ let times = 0; let poolCopy; const targetOne = createTarget({ left: '-30px' }); - const targetTwo = createTarget({ marginTop: '30px' }); + const targetTwo = createTarget({ top: '30px' }); const targetThree = createTarget({ marginTop: '-30px' }); new Tracker({ ```
```test/dom/test/basics.spec.js /** * Basics */ describe('Basics', () => { beforeEach(beforeEachHook); afterEach(afterEachHook); /** * Absolute tracking */ it('absolute tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ left: '-30px' }); const targetTwo = createTarget({ top: '30px' }); <|user_cursor_is_here|> const targetThree = createTarget({ marginTop: '-30px' }); new Tracker({ targets: document.getElementsByClassName('target'), snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetTwo); }); /** * Relative tracking */ it('relative tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ left: '-20px' }, bounds); const targetTwo = createTarget({ top: '-20px' }, bounds); const targetThree = createTarget({}, bounds); new Tracker({ targets: document.getElementsByClassName('target'), bounds, snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetThree); }); }); ```
```test/dom/test/basics.spec.js /** * Basics */ describe('Basics', () => { beforeEach(beforeEachHook); afterEach(afterEachHook); /** * Absolute tracking */ it('absolute tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ left: '-30px' }); const targetTwo = createTarget({ top: '30px' }); <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "marginTop", "newName": "top"}} </|tool_call|> const targetThree = createTarget({ marginTop: '-30px' }); new Tracker({ targets: document.getElementsByClassName('target'), snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetTwo); }); /** * Relative tracking */ it('relative tracking', async () => { let times = 0; let poolCopy; const targetOne = createTarget({ left: '-20px' }, bounds); const targetTwo = createTarget({ top: '-20px' }, bounds); const targetThree = createTarget({}, bounds); new Tracker({ targets: document.getElementsByClassName('target'), bounds, snapshots: [ { callback({ DOMElement, pool }) { animate(DOMElement); times++; poolCopy = pool; } } ] }); await scroll(0, 10); expect(times).to.equal(1); expect(poolCopy).to.include(targetThree); }); }); ```
User edited file: "src/main/kotlin/com/simonorono/bitc/BitArray.kt": ```diff @@ -1,4 +1,6 @@ package com.simonorono.bitc + +import kotlin.math.ceil /** * The BitArray class represents an array of booleans. It stores them packed @@ -50,4 +52,4 @@ */ val indices: IntRange get() = IntRange(0, size - 1) -} +} ```
```src/main/kotlin/com/simonorono/bitc/BitArray.kt package com.simonorono.bitc import kotlin.math.ceil /** * The BitArray class represents an array of booleans. It stores them packed * inside regular integers to not waste the overhead of storing booleans. * * @property size The size of the array */ class BitArray(val size: Int) { private val innerArray = IntArray( 1.coerceAtLeast( <|user_cursor_is_here|> Math.ceil(size.toDouble() / Int.SIZE_BITS.toDouble()).toInt() ) ) { 0 } private fun checkBounds(idx: Int) { if (idx < 0 || idx >= size) { throw IndexOutOfBoundsException() } } /** * Retrieve the value at position [idx]. */ operator fun get(idx: Int): Boolean { checkBounds(idx) return (innerArray[idx / Int.SIZE_BITS] and (1 shl (idx % Int.SIZE_BITS))) != 0 } /** * Sets the value at position [idx]. */ operator fun set(idx: Int, value: Boolean) { checkBounds(idx) val current = innerArray[idx / Int.SIZE_BITS] if (value) { innerArray[idx / Int.SIZE_BITS] = current or (1 shl (idx % Int.SIZE_BITS)) } else { innerArray[idx / Int.SIZE_BITS] = current and (1 shl (idx % Int.SIZE_BITS)).inv() } } /** * The range of indices of the array. */ val indices: IntRange get() = IntRange(0, size - 1) } ```
```src/main/kotlin/com/simonorono/bitc/BitArray.kt package com.simonorono.bitc import kotlin.math.ceil /** * The BitArray class represents an array of booleans. It stores them packed * inside regular integers to not waste the overhead of storing booleans. * * @property size The size of the array */ class BitArray(val size: Int) { private val innerArray = IntArray( 1.coerceAtLeast( <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Math.ceil", "newName": "ceil"}} </|tool_call|> Math.ceil(size.toDouble() / Int.SIZE_BITS.toDouble()).toInt() ) ) { 0 } private fun checkBounds(idx: Int) { if (idx < 0 || idx >= size) { throw IndexOutOfBoundsException() } } /** * Retrieve the value at position [idx]. */ operator fun get(idx: Int): Boolean { checkBounds(idx) return (innerArray[idx / Int.SIZE_BITS] and (1 shl (idx % Int.SIZE_BITS))) != 0 } /** * Sets the value at position [idx]. */ operator fun set(idx: Int, value: Boolean) { checkBounds(idx) val current = innerArray[idx / Int.SIZE_BITS] if (value) { innerArray[idx / Int.SIZE_BITS] = current or (1 shl (idx % Int.SIZE_BITS)) } else { innerArray[idx / Int.SIZE_BITS] = current and (1 shl (idx % Int.SIZE_BITS)).inv() } } /** * The range of indices of the array. */ val indices: IntRange get() = IntRange(0, size - 1) } ```
User edited file: "module/index.js": ```diff @@ -1,3 +1,10 @@ +const requireFromString = (source, filename) => { + var m = new module.constructor(); + m._compile(source, filename); + return m.exports; +}; + // Credits: http://stackoverflow.com/a/17585470/2816199 + const startsWithDot = /^\./; const moduleIdParts = /^((?:[a-z\-]+!)*)(.*)$/; // ^ From the beginning of the string match: @@ -27,4 +34,4 @@ } )); }; -}; +}; ``` User edited file: "module/index.js": ```diff @@ -4,6 +4,17 @@ return m.exports; }; // Credits: http://stackoverflow.com/a/17585470/2816199 + +const loaderContext = { + cacheable() {}, + dependencies() {}, + async() {throw new Error( + 'isomorphic-ensure: Async modules are not supported.' + );}, + resolve() {throw new Error( + 'isomorphic-ensure: Loaders which use `this.resolve` are not supported.' + );}, +}; const startsWithDot = /^\./; const moduleIdParts = /^((?:[a-z\-]+!)*)(.*)$/; ``` User edited file: "module/index.js": ```diff @@ -27,8 +27,8 @@ // $ until the end of the string. export default (settings = {}) => { - // const {loaders} = settings; - // const {readFileSync} = require('fs'); + const {loaders} = settings; + const {readFileSync} = require('fs'); return (dependencies, callback, context) => { const {dirname} = context; ```
```module/index.js const requireFromString = (source, filename) => { var m = new module.constructor(); m._compile(source, filename); return m.exports; }; // Credits: http://stackoverflow.com/a/17585470/2816199 const loaderContext = { cacheable() {}, dependencies() {}, async() {throw new Error( 'isomorphic-ensure: Async modules are not supported.' );}, resolve() {throw new Error( 'isomorphic-ensure: Loaders which use `this.resolve` are not supported.' );}, }; const startsWithDot = /^\./; const moduleIdParts = /^((?:[a-z\-]+!)*)(.*)$/; // ^ From the beginning of the string match: // ((?: 1. // [a-z\-]+ A loader name, consisting of lowercase letters and hyphens // ! followed by a bang // )*) as many times as possible. // (.*) 2. Any sequence of characters // $ until the end of the string. export default (settings = {}) => { const {loaders} = settings; const {readFileSync} = require('fs'); return (dependencies, callback, context) => { const {dirname} = context; process.nextTick(() => callback( (moduleId) => { <|user_cursor_is_here|> const [, loadersList, rawPath] = moduleId.match(moduleIdParts); const loaders = loadersList.split('!').slice(0, -1); const modulePath = (startsWithDot.test(rawPath) ? `${dirname}/${rawPath}` : require.resolve(rawPath) ); return require(modulePath); } )); }; }; ```
```module/index.js const requireFromString = (source, filename) => { var m = new module.constructor(); m._compile(source, filename); return m.exports; }; // Credits: http://stackoverflow.com/a/17585470/2816199 const loaderContext = { cacheable() {}, dependencies() {}, async() {throw new Error( 'isomorphic-ensure: Async modules are not supported.' );}, resolve() {throw new Error( 'isomorphic-ensure: Loaders which use `this.resolve` are not supported.' );}, }; const startsWithDot = /^\./; const moduleIdParts = /^((?:[a-z\-]+!)*)(.*)$/; // ^ From the beginning of the string match: // ((?: 1. // [a-z\-]+ A loader name, consisting of lowercase letters and hyphens // ! followed by a bang // )*) as many times as possible. // (.*) 2. Any sequence of characters // $ until the end of the string. export default (settings = {}) => { const {loaders} = settings; const {readFileSync} = require('fs'); return (dependencies, callback, context) => { const {dirname} = context; process.nextTick(() => callback( (moduleId) => { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "loadersList", "newName": "loadersPart"}} </|tool_call|> const [, loadersList, rawPath] = moduleId.match(moduleIdParts); const loaders = loadersList.split('!').slice(0, -1); const modulePath = (startsWithDot.test(rawPath) ? `${dirname}/${rawPath}` : require.resolve(rawPath) ); return require(modulePath); } )); }; }; ```
User edited file: "ml/test_amaranth_lib.py": ```diff @@ -5,6 +5,9 @@ class TestAmaranthHelpers(unittest.TestCase): + + def test_combine_dataframes(self): + raise NotImplementedError def test_load_calorie_data(self): raise NotImplementedError @@ -26,4 +29,4 @@ if __name__ == '__main__': - unittest.main() + unittest.main() ```
```ml/test_amaranth_lib.py # Lint as: python3 """These tests ensure correctness for the helper functions in amaranth_lib.""" import unittest class TestAmaranthHelpers(unittest.TestCase): def test_combine_dataframes(self): raise NotImplementedError <|user_cursor_is_here|> def test_load_calorie_data(self): raise NotImplementedError def test_clean_data(self): raise NotImplementedError def test_add_calorie_labels(self): raise NotImplementedError def test_num_unique_words(self): raise NotImplementedError def test_max_sequence_length(self): raise NotImplementedError def test_add_input_labels(self): raise NotImplementedError if __name__ == '__main__': unittest.main() ```
```ml/test_amaranth_lib.py # Lint as: python3 """These tests ensure correctness for the helper functions in amaranth_lib.""" import unittest class TestAmaranthHelpers(unittest.TestCase): def test_combine_dataframes(self): raise NotImplementedError <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "test_load_calorie_data", "newName": "test_get_calorie_data"}} </|tool_call|> def test_load_calorie_data(self): raise NotImplementedError def test_clean_data(self): raise NotImplementedError def test_add_calorie_labels(self): raise NotImplementedError def test_num_unique_words(self): raise NotImplementedError def test_max_sequence_length(self): raise NotImplementedError def test_add_input_labels(self): raise NotImplementedError if __name__ == '__main__': unittest.main() ```
User edited file: "lib/components/completeBlock/completeBlock.js": ```diff @@ -1,4 +1,4 @@ -import CompleteBlock from './completeBlock.html'; +import TemplateCompleteBlock from './completeBlock.html'; import './completeBlock.scss'; class CompleteBlock { @@ -19,4 +19,4 @@ } } -export default CompleteBlock.detailsComponent(); +export default CompleteBlock.detailsComponent(); ```
```lib/components/completeBlock/completeBlock.js import TemplateCompleteBlock from './completeBlock.html'; import './completeBlock.scss'; class CompleteBlock { static detailsComponent() { return { <|user_cursor_is_here|> templateUrl: CompleteBlock, bindings: { headerImg: '@', headerTitle: '@', headerPicto: '@', headerColor: '@', headerBackgroundColor: '@', bodyBackgroundColor: '@', bodyTitle: '@', bodyText: '@' } }; } } export default CompleteBlock.detailsComponent(); ```
```lib/components/completeBlock/completeBlock.js import TemplateCompleteBlock from './completeBlock.html'; import './completeBlock.scss'; class CompleteBlock { static detailsComponent() { return { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "CompleteBlock", "newName": "TemplateCompleteBlock"}} </|tool_call|> templateUrl: CompleteBlock, bindings: { headerImg: '@', headerTitle: '@', headerPicto: '@', headerColor: '@', headerBackgroundColor: '@', bodyBackgroundColor: '@', bodyTitle: '@', bodyText: '@' } }; } } export default CompleteBlock.detailsComponent(); ```
User edited file: "exercises/bank-account/src/example/kotlin/BankAccount.kt": ```diff @@ -24,4 +24,5 @@ } } -} + private val lock = Any() +} ``` User edited file: "exercises/bank-account/src/example/kotlin/BankAccount.kt": ```diff @@ -1,12 +1,11 @@ class BankAccount { var balance: Long = 0 get() { - synchronized(this) { - if (!isOpen) throw IllegalStateException("Account is closed") - return field - } + synchronized(lock) { + if (!isOpen) throw IllegalStateException("Account is closed") + return field + } } - private set var isOpen = true ``` User edited file: "exercises/bank-account/src/example/kotlin/BankAccount.kt": ```diff @@ -12,7 +12,7 @@ private set fun adjustBalance(amount: Long) { - synchronized(this) { + synchronized(lock) { balance += amount } } ```
```exercises/bank-account/src/example/kotlin/BankAccount.kt class BankAccount { var balance: Long = 0 get() { synchronized(lock) { if (!isOpen) throw IllegalStateException("Account is closed") return field } } private set var isOpen = true private set fun adjustBalance(amount: Long) { synchronized(lock) { balance += amount } } fun close() { <|user_cursor_is_here|> synchronized(this) { isOpen = false } } private val lock = Any() } ```
```exercises/bank-account/src/example/kotlin/BankAccount.kt class BankAccount { var balance: Long = 0 get() { synchronized(lock) { if (!isOpen) throw IllegalStateException("Account is closed") return field } } private set var isOpen = true private set fun adjustBalance(amount: Long) { synchronized(lock) { balance += amount } } fun close() { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "this", "newName": "lock"}} </|tool_call|> synchronized(this) { isOpen = false } } private val lock = Any() } ```
User edited file: "python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt": ```diff @@ -3,7 +3,6 @@ import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile -import icons.PythonIcons import java.io.File import javax.swing.Icon @@ -51,4 +50,4 @@ class MayaFlavorProvider: PythonFlavorProvider { override fun getFlavor(platformIndependent: Boolean): MayaSdkFlavor = MayaSdkFlavor.INSTANCE -} +} ``` User edited file: "python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt": ```diff @@ -4,7 +4,6 @@ import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import java.io.File -import javax.swing.Icon class MayaSdkFlavor private constructor() : PythonSdkFlavor() { ```
```python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.flavors import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import java.io.File <|user_cursor_is_here|> class MayaSdkFlavor private constructor() : PythonSdkFlavor() { override fun isValidSdkHome(path: String): Boolean { val file = File(path) return file.isFile && isValidSdkPath(file) || isMayaFolder(file) } override fun isValidSdkPath(file: File): Boolean { val name = FileUtil.getNameWithoutExtension(file).toLowerCase() return name.startsWith("mayapy") } override fun getVersionOption(): String { return "--version" } override fun getName(): String { return "MayaPy" } override fun getIcon(): Icon { return PythonIcons.Python.Python //TODO: maya icon } override fun getSdkPath(path: VirtualFile): VirtualFile? { if (isMayaFolder(File(path.path))) { return path.findFileByRelativePath("Contents/bin/mayapy") } return path } companion object { var INSTANCE: MayaSdkFlavor = MayaSdkFlavor() private fun isMayaFolder(file: File): Boolean { return file.isDirectory && file.name == "Maya.app" } } } class MayaFlavorProvider: PythonFlavorProvider { override fun getFlavor(platformIndependent: Boolean): MayaSdkFlavor = MayaSdkFlavor.INSTANCE } ```
```python/src/com/jetbrains/python/sdk/flavors/MayaSdkFlavor.kt // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.flavors import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import java.io.File <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "PythonSdkFlavor", "newName": "CPythonSdkFlavor"}} </|tool_call|> class MayaSdkFlavor private constructor() : PythonSdkFlavor() { override fun isValidSdkHome(path: String): Boolean { val file = File(path) return file.isFile && isValidSdkPath(file) || isMayaFolder(file) } override fun isValidSdkPath(file: File): Boolean { val name = FileUtil.getNameWithoutExtension(file).toLowerCase() return name.startsWith("mayapy") } override fun getVersionOption(): String { return "--version" } override fun getName(): String { return "MayaPy" } override fun getIcon(): Icon { return PythonIcons.Python.Python //TODO: maya icon } override fun getSdkPath(path: VirtualFile): VirtualFile? { if (isMayaFolder(File(path.path))) { return path.findFileByRelativePath("Contents/bin/mayapy") } return path } companion object { var INSTANCE: MayaSdkFlavor = MayaSdkFlavor() private fun isMayaFolder(file: File): Boolean { return file.isDirectory && file.name == "Maya.app" } } } class MayaFlavorProvider: PythonFlavorProvider { override fun getFlavor(platformIndependent: Boolean): MayaSdkFlavor = MayaSdkFlavor.INSTANCE } ```
User edited file: "csunplugged/utils/check_glossary_links.py": ```diff @@ -1,5 +1,6 @@ """Module for checking glossary links found within Markdown conversions.""" +from django.core.exceptions import DoesNotExist from utils.errors.CouldNotFindGlossaryTerm import CouldNotFindGlossaryTerm from topics.models import GlossaryTerm @@ -14,4 +15,4 @@ try: GlossaryTerm.objects.get(slug=term) except ObjectDoesNotExist: - raise CouldNotFindGlossaryTerm(term, md_file_path) + raise CouldNotFindGlossaryTerm(term, md_file_path) ```
```csunplugged/utils/check_glossary_links.py """Module for checking glossary links found within Markdown conversions.""" from django.core.exceptions import DoesNotExist from utils.errors.CouldNotFindGlossaryTerm import CouldNotFindGlossaryTerm from topics.models import GlossaryTerm def check_converter_glossary_links(glossary_links, md_file_path): """Process glossary links found by Markdown converter. Args: glossary_links: Dictionary of glossary links (dict). """ for term in glossary_links.keys(): try: GlossaryTerm.objects.get(slug=term) <|user_cursor_is_here|> except ObjectDoesNotExist: raise CouldNotFindGlossaryTerm(term, md_file_path) ```
```csunplugged/utils/check_glossary_links.py """Module for checking glossary links found within Markdown conversions.""" from django.core.exceptions import DoesNotExist from utils.errors.CouldNotFindGlossaryTerm import CouldNotFindGlossaryTerm from topics.models import GlossaryTerm def check_converter_glossary_links(glossary_links, md_file_path): """Process glossary links found by Markdown converter. Args: glossary_links: Dictionary of glossary links (dict). """ for term in glossary_links.keys(): try: GlossaryTerm.objects.get(slug=term) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "ObjectDoesNotExist", "newName": "DoesNotExist"}} </|tool_call|> except ObjectDoesNotExist: raise CouldNotFindGlossaryTerm(term, md_file_path) ```
User edited file: "src/test/java/seedu/address/testutil/ItemBuilder.java": ```diff @@ -9,7 +9,7 @@ */ public class ItemBuilder { - private TestItem person; + private TestItem item; public ItemBuilder() { this.person = new TestItem(); @@ -56,4 +56,4 @@ return this.person; } -} +} ``` User edited file: "src/test/java/seedu/address/testutil/ItemBuilder.java": ```diff @@ -12,7 +12,7 @@ private TestItem item; public ItemBuilder() { - this.person = new TestItem(); + this.item = new TestItem(); } public ItemBuilder withItemType(String itemType) throws IllegalValueException { ``` User edited file: "src/test/java/seedu/address/testutil/ItemBuilder.java": ```diff @@ -16,7 +16,7 @@ } public ItemBuilder withItemType(String itemType) throws IllegalValueException { - this.person.setItemType(new ItemType(itemType)); + this.item.setItemType(new ItemType(itemType)); return this; } ```
```src/test/java/seedu/address/testutil/ItemBuilder.java package seedu.address.testutil; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.item.*; import seedu.address.model.tag.Tag; /** * */ public class ItemBuilder { private TestItem item; public ItemBuilder() { this.item = new TestItem(); } public ItemBuilder withItemType(String itemType) throws IllegalValueException { this.item.setItemType(new ItemType(itemType)); return this; } public ItemBuilder withTags(String ... tags) throws IllegalValueException { for (String tag: tags) { <|user_cursor_is_here|> person.getTags().add(new Tag(tag)); } return this; } public ItemBuilder withEndDate(String endDate) throws IllegalValueException { this.person.setEndDate(new Date(endDate)); return this; } public ItemBuilder withEndTime(String endTime) throws IllegalValueException { this.person.setEndTime(new Time(endTime)); return this; } public ItemBuilder withName(String name) throws IllegalValueException { this.person.setName(new Name(name)); return this; } public ItemBuilder withStartDate(String startDate) throws IllegalValueException { this.person.setStartDate(new Date(startDate)); return this; } public ItemBuilder withStartTime(String startTime) throws IllegalValueException { this.person.setStartTime(new Time(startTime)); return this; } public TestItem build() { return this.person; } } ```
```src/test/java/seedu/address/testutil/ItemBuilder.java package seedu.address.testutil; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.item.*; import seedu.address.model.tag.Tag; /** * */ public class ItemBuilder { private TestItem item; public ItemBuilder() { this.item = new TestItem(); } public ItemBuilder withItemType(String itemType) throws IllegalValueException { this.item.setItemType(new ItemType(itemType)); return this; } public ItemBuilder withTags(String ... tags) throws IllegalValueException { for (String tag: tags) { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "person", "newName": "item"}} </|tool_call|> person.getTags().add(new Tag(tag)); } return this; } public ItemBuilder withEndDate(String endDate) throws IllegalValueException { this.person.setEndDate(new Date(endDate)); return this; } public ItemBuilder withEndTime(String endTime) throws IllegalValueException { this.person.setEndTime(new Time(endTime)); return this; } public ItemBuilder withName(String name) throws IllegalValueException { this.person.setName(new Name(name)); return this; } public ItemBuilder withStartDate(String startDate) throws IllegalValueException { this.person.setStartDate(new Date(startDate)); return this; } public ItemBuilder withStartTime(String startTime) throws IllegalValueException { this.person.setStartTime(new Time(startTime)); return this; } public TestItem build() { return this.person; } } ```
User edited file: "django_lightweight_queue/task.py": ```diff @@ -27,10 +27,10 @@ return "<TaskWrapper: %s>" % self.path def __call__(self, *args, **kwargs): - # Allow us to override which queue at the last moment + # Allow us to override the default values dynamically queue = kwargs.pop('django_lightweight_queue_queue', self.queue) job = Job(self.path, args, kwargs, self.timeout, self.sigkill_on_stop) job.validate() - get_backend().enqueue(job, queue) + get_backend().enqueue(job, queue) ``` User edited file: "django_lightweight_queue/task.py": ```diff @@ -29,6 +29,7 @@ def __call__(self, *args, **kwargs): # Allow us to override the default values dynamically queue = kwargs.pop('django_lightweight_queue_queue', self.queue) + timeout = kwargs.pop('django_lightweight_queue_timeout', self.timeout) job = Job(self.path, args, kwargs, self.timeout, self.sigkill_on_stop) job.validate() ``` User edited file: "django_lightweight_queue/task.py": ```diff @@ -30,6 +30,10 @@ # Allow us to override the default values dynamically queue = kwargs.pop('django_lightweight_queue_queue', self.queue) timeout = kwargs.pop('django_lightweight_queue_timeout', self.timeout) + sigkill_on_stop = kwargs.pop( + 'django_lightweight_queue_sigkill_on_stop', + self.sigkill_on_stop, + ) job = Job(self.path, args, kwargs, self.timeout, self.sigkill_on_stop) job.validate() ```
```django_lightweight_queue/task.py from .job import Job from .utils import get_backend from . import app_settings class task(object): def __init__(self, queue='default', timeout=None, sigkill_on_stop=False): self.queue = queue self.timeout = timeout self.sigkill_on_stop = sigkill_on_stop app_settings.WORKERS.setdefault(self.queue, 1) def __call__(self, fn): return TaskWrapper(fn, self.queue, self.timeout, self.sigkill_on_stop) class TaskWrapper(object): def __init__(self, fn, queue, timeout, sigkill_on_stop): self.fn = fn self.queue = queue self.timeout = timeout self.sigkill_on_stop = sigkill_on_stop self.path = '%s.%s' % (fn.__module__, fn.__name__) def __repr__(self): return "<TaskWrapper: %s>" % self.path def __call__(self, *args, **kwargs): # Allow us to override the default values dynamically queue = kwargs.pop('django_lightweight_queue_queue', self.queue) timeout = kwargs.pop('django_lightweight_queue_timeout', self.timeout) sigkill_on_stop = kwargs.pop( 'django_lightweight_queue_sigkill_on_stop', self.sigkill_on_stop, ) <|user_cursor_is_here|> job = Job(self.path, args, kwargs, self.timeout, self.sigkill_on_stop) job.validate() get_backend().enqueue(job, queue) ```
```django_lightweight_queue/task.py from .job import Job from .utils import get_backend from . import app_settings class task(object): def __init__(self, queue='default', timeout=None, sigkill_on_stop=False): self.queue = queue self.timeout = timeout self.sigkill_on_stop = sigkill_on_stop app_settings.WORKERS.setdefault(self.queue, 1) def __call__(self, fn): return TaskWrapper(fn, self.queue, self.timeout, self.sigkill_on_stop) class TaskWrapper(object): def __init__(self, fn, queue, timeout, sigkill_on_stop): self.fn = fn self.queue = queue self.timeout = timeout self.sigkill_on_stop = sigkill_on_stop self.path = '%s.%s' % (fn.__module__, fn.__name__) def __repr__(self): return "<TaskWrapper: %s>" % self.path def __call__(self, *args, **kwargs): # Allow us to override the default values dynamically queue = kwargs.pop('django_lightweight_queue_queue', self.queue) timeout = kwargs.pop('django_lightweight_queue_timeout', self.timeout) sigkill_on_stop = kwargs.pop( 'django_lightweight_queue_sigkill_on_stop', self.sigkill_on_stop, ) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "self.timeout", "newName": "timeout"}} </|tool_call|> job = Job(self.path, args, kwargs, self.timeout, self.sigkill_on_stop) job.validate() get_backend().enqueue(job, queue) ```
User edited file: "src/autobot/src/stopsign.py": ```diff @@ -14,7 +14,7 @@ def __init__(self): self.state = StopStates.NORMAL self.stopDuration = 2 - self.ignoreDuration = 2 + self.ignoreDuration = 4 def stopSignDetected(self): self.state = StopStates.FULL_STOP @@ -33,4 +33,4 @@ oneshot=True) elif self.state is StopStates.IGNORE_STOP_SIGNS: - self.action = StopStates.NORMAL + self.action = StopStates.NORMAL ``` User edited file: "src/autobot/src/stopsign.py": ```diff @@ -22,7 +22,7 @@ self.stepStateMachine, oneshot=True) - def stepStateMachine(self): + def stepStateMachine(self, event): if self.state is StopStates.NORMAL: self.action = StopStates.FULL_STOP ```
```src/autobot/src/stopsign.py #!/usr/bin/env python import rospy class StopStates(object): NORMAL = 0 FULL_STOP = 1 IGNORE_STOP_SIGNS = 2 class StopSign(object): def __init__(self): self.state = StopStates.NORMAL self.stopDuration = 2 self.ignoreDuration = 4 def stopSignDetected(self): self.state = StopStates.FULL_STOP timer = rospy.Timer(rospy.Duration(self.stopDuration), self.stepStateMachine, oneshot=True) def stepStateMachine(self, event): if self.state is StopStates.NORMAL: <|user_cursor_is_here|> self.action = StopStates.FULL_STOP elif self.state is StopStates.FULL_STOP: self.action = StopStates.IGNORE_STOP_SIGNS timer = rospy.Timer(rospy.Duration(self.ignoreDuration), self.stepStateMachine, oneshot=True) elif self.state is StopStates.IGNORE_STOP_SIGNS: self.action = StopStates.NORMAL ```
```src/autobot/src/stopsign.py #!/usr/bin/env python import rospy class StopStates(object): NORMAL = 0 FULL_STOP = 1 IGNORE_STOP_SIGNS = 2 class StopSign(object): def __init__(self): self.state = StopStates.NORMAL self.stopDuration = 2 self.ignoreDuration = 4 def stopSignDetected(self): self.state = StopStates.FULL_STOP timer = rospy.Timer(rospy.Duration(self.stopDuration), self.stepStateMachine, oneshot=True) def stepStateMachine(self, event): if self.state is StopStates.NORMAL: <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "action", "newName": "state"}} </|tool_call|> self.action = StopStates.FULL_STOP elif self.state is StopStates.FULL_STOP: self.action = StopStates.IGNORE_STOP_SIGNS timer = rospy.Timer(rospy.Duration(self.ignoreDuration), self.stepStateMachine, oneshot=True) elif self.state is StopStates.IGNORE_STOP_SIGNS: self.action = StopStates.NORMAL ```
User edited file: "worker/build.gradle.kts": ```diff @@ -4,7 +4,7 @@ } application { - mainClassName = "com.github.k0kubun.gitstar_ranking.Main" + mainClass.set("com.github.k0kubun.gitstar_ranking.Main") } repositories { @@ -24,4 +24,4 @@ compile("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final") compile("org.jdbi:jdbi:2.78") testCompile("junit:junit:4.12") -} +} ``` User edited file: "worker/build.gradle.kts": ```diff @@ -12,16 +12,16 @@ } dependencies { - compile("ch.qos.logback:logback-classic:1.3.0-alpha4") - compile("com.google.guava:guava:21.0") - compile("com.google.http-client:google-http-client:1.22.0") - compile("io.sentry:sentry:1.5.2") - compile("javax.json:javax.json-api:1.1") - compile("javax.ws.rs:javax.ws.rs-api:2.0.1") - compile("org.postgresql:postgresql:42.2.19") - compile("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2 - compile("org.glassfish:javax.json:1.1") - compile("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final") - compile("org.jdbi:jdbi:2.78") + implementation("ch.qos.logback:logback-classic:1.3.0-alpha4") + implementation("com.google.guava:guava:21.0") + implementation("com.google.http-client:google-http-client:1.22.0") + implementation("io.sentry:sentry:1.5.2") + implementation("javax.json:javax.json-api:1.1") + implementation("javax.ws.rs:javax.ws.rs-api:2.0.1") + implementation("org.postgresql:postgresql:42.2.19") + implementation("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2 + implementation("org.glassfish:javax.json:1.1") + implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final") + implementation("org.jdbi:jdbi:2.78") testCompile("junit:junit:4.12") } ```
```worker/build.gradle.kts plugins { id("java") id("application") } application { mainClass.set("com.github.k0kubun.gitstar_ranking.Main") } repositories { mavenCentral() } dependencies { implementation("ch.qos.logback:logback-classic:1.3.0-alpha4") implementation("com.google.guava:guava:21.0") implementation("com.google.http-client:google-http-client:1.22.0") implementation("io.sentry:sentry:1.5.2") implementation("javax.json:javax.json-api:1.1") implementation("javax.ws.rs:javax.ws.rs-api:2.0.1") implementation("org.postgresql:postgresql:42.2.19") implementation("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2 implementation("org.glassfish:javax.json:1.1") implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final") implementation("org.jdbi:jdbi:2.78") <|user_cursor_is_here|> testCompile("junit:junit:4.12") } ```
```worker/build.gradle.kts plugins { id("java") id("application") } application { mainClass.set("com.github.k0kubun.gitstar_ranking.Main") } repositories { mavenCentral() } dependencies { implementation("ch.qos.logback:logback-classic:1.3.0-alpha4") implementation("com.google.guava:guava:21.0") implementation("com.google.http-client:google-http-client:1.22.0") implementation("io.sentry:sentry:1.5.2") implementation("javax.json:javax.json-api:1.1") implementation("javax.ws.rs:javax.ws.rs-api:2.0.1") implementation("org.postgresql:postgresql:42.2.19") implementation("org.antlr:stringtemplate:3.2.1") // Using ST3 because ST4 isn"t supported by JDBI 2 implementation("org.glassfish:javax.json:1.1") implementation("org.jboss.resteasy:resteasy-jackson2-provider:3.1.2.Final") implementation("org.jdbi:jdbi:2.78") <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "testCompile", "newName": "testImplementation"}} </|tool_call|> testCompile("junit:junit:4.12") } ```
User edited file: "src/libcore/num/int_macros.rs": ```diff @@ -14,7 +14,7 @@ concat!("The smallest value that can be represented by this integer type. Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."), #[$attr] - pub const MIN: $T = $T::min_value(); + pub const MIN: $T = $T::MIN; } doc_comment! { @@ -24,4 +24,4 @@ pub const MAX: $T = $T::max_value(); } ) -} +} ```
```src/libcore/num/int_macros.rs #![doc(hidden)] macro_rules! doc_comment { ($x:expr, $($tt:tt)*) => { #[doc = $x] $($tt)* }; } macro_rules! int_module { ($T:ident) => (int_module!($T, #[stable(feature = "rust1", since = "1.0.0")]);); ($T:ident, #[$attr:meta]) => ( doc_comment! { concat!("The smallest value that can be represented by this integer type. Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."), #[$attr] pub const MIN: $T = $T::MIN; } doc_comment! { concat!("The largest value that can be represented by this integer type. Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead."), #[$attr] <|user_cursor_is_here|> pub const MAX: $T = $T::max_value(); } ) } ```
```src/libcore/num/int_macros.rs #![doc(hidden)] macro_rules! doc_comment { ($x:expr, $($tt:tt)*) => { #[doc = $x] $($tt)* }; } macro_rules! int_module { ($T:ident) => (int_module!($T, #[stable(feature = "rust1", since = "1.0.0")]);); ($T:ident, #[$attr:meta]) => ( doc_comment! { concat!("The smallest value that can be represented by this integer type. Use [`", stringify!($T), "::MIN", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MIN) instead."), #[$attr] pub const MIN: $T = $T::MIN; } doc_comment! { concat!("The largest value that can be represented by this integer type. Use [`", stringify!($T), "::MAX", "`](../../std/primitive.", stringify!($T), ".html#associatedconstant.MAX) instead."), #[$attr] <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "max_value()", "newName": "MAX"}} </|tool_call|> pub const MAX: $T = $T::max_value(); } ) } ```
User edited file: "app/src/test/java/com/google/android/stardroid/units/LatLongRoboTest.kt": ```diff @@ -1,11 +1,9 @@ package com.google.android.stardroid.units +import com.google.common.truth.Truth.assertThat +import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner -import com.google.android.stardroid.units.LatLong -import com.google.common.truth.Truth -import com.google.android.stardroid.units.LatLongRoboTest -import org.junit.Test import org.robolectric.annotation.Config /** ```
```app/src/test/java/com/google/android/stardroid/units/LatLongRoboTest.kt package com.google.android.stardroid.units import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** * Tests that require roboelectric for API calls. */ @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE) class LatLongRoboTest { @Test fun latLong_testDistance() { val point1 = LatLong(0.0, 0.0) val point2 = LatLong(90.0, 0.0) <|user_cursor_is_here|> Truth.assertThat(point1.distanceFrom(point2)).isWithin(TOL).of(90f) } @Test fun latLong_testDistance2() { val point1 = LatLong(45.0, 45.0) val point2 = LatLong(90.0, 0.0) Truth.assertThat(point1.distanceFrom(point2)).isWithin(TOL).of(45f) } companion object { private const val TOL = 1e-5f } } ```
```app/src/test/java/com/google/android/stardroid/units/LatLongRoboTest.kt package com.google.android.stardroid.units import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** * Tests that require roboelectric for API calls. */ @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE) class LatLongRoboTest { @Test fun latLong_testDistance() { val point1 = LatLong(0.0, 0.0) val point2 = LatLong(90.0, 0.0) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Truth.assertThat", "newName": "assertThat"}} </|tool_call|> Truth.assertThat(point1.distanceFrom(point2)).isWithin(TOL).of(90f) } @Test fun latLong_testDistance2() { val point1 = LatLong(45.0, 45.0) val point2 = LatLong(90.0, 0.0) Truth.assertThat(point1.distanceFrom(point2)).isWithin(TOL).of(45f) } companion object { private const val TOL = 1e-5f } } ```
User edited file: "kernel/fs/kscheme.rs": ```diff @@ -2,7 +2,7 @@ use alloc::boxed::Box; -use system::error::{Error, Result, ENOENT}; +use system::error::{Error, Result, EPERM}; use system::syscall::Stat; #[allow(unused_variables)] @@ -34,4 +34,4 @@ fn unlink(&mut self, path: Url) -> Result<()> { Err(Error::new(ENOENT)) } -} +} ```
```kernel/fs/kscheme.rs use super::{Resource, Url}; use alloc::boxed::Box; use system::error::{Error, Result, EPERM}; use system::syscall::Stat; #[allow(unused_variables)] pub trait KScheme { fn on_irq(&mut self, irq: u8) { } fn scheme(&self) -> &str { "" } fn open(&mut self, path: Url, flags: usize) -> Result<Box<Resource>> { <|user_cursor_is_here|> Err(Error::new(ENOENT)) } fn mkdir(&mut self, path: Url, flags: usize) -> Result<()> { Err(Error::new(ENOENT)) } fn rmdir(&mut self, path: Url) -> Result<()> { Err(Error::new(ENOENT)) } fn stat(&mut self, path: Url, stat: &mut Stat) -> Result<()> { Err(Error::new(ENOENT)) } fn unlink(&mut self, path: Url) -> Result<()> { Err(Error::new(ENOENT)) } } ```
```kernel/fs/kscheme.rs use super::{Resource, Url}; use alloc::boxed::Box; use system::error::{Error, Result, EPERM}; use system::syscall::Stat; #[allow(unused_variables)] pub trait KScheme { fn on_irq(&mut self, irq: u8) { } fn scheme(&self) -> &str { "" } fn open(&mut self, path: Url, flags: usize) -> Result<Box<Resource>> { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "ENOENT", "newName": "EPERM"}} </|tool_call|> Err(Error::new(ENOENT)) } fn mkdir(&mut self, path: Url, flags: usize) -> Result<()> { Err(Error::new(ENOENT)) } fn rmdir(&mut self, path: Url) -> Result<()> { Err(Error::new(ENOENT)) } fn stat(&mut self, path: Url, stat: &mut Stat) -> Result<()> { Err(Error::new(ENOENT)) } fn unlink(&mut self, path: Url) -> Result<()> { Err(Error::new(ENOENT)) } } ```
User edited file: "app/src/main/java/com/battlelancer/seriesguide/ui/shows/FabRecyclerViewScrollDetector.kt": ```diff @@ -3,6 +3,7 @@ import androidx.recyclerview.widget.RecyclerView import com.battlelancer.seriesguide.R import com.google.android.material.floatingactionbutton.FloatingActionButton +import kotlin.math.abs /** * Hides the floating action button when scrolling down, shows it when scrolling up. If the view can @@ -46,4 +47,4 @@ button.show() } -} +} ``` User edited file: "app/src/main/java/com/battlelancer/seriesguide/ui/shows/FabRecyclerViewScrollDetector.kt": ```diff @@ -18,11 +18,6 @@ button.context.resources.getDimensionPixelOffset(R.dimen.fab_scroll_threshold) override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { - // no action if RecyclerView is no longer visible, such as its tab was swiped away - if (!recyclerView.hasFocus()) { - return - } - // always show if scrolled to bottom if (!recyclerView.canScrollVertically(1 /* down */)) { button.show() ```
```app/src/main/java/com/battlelancer/seriesguide/ui/shows/FabRecyclerViewScrollDetector.kt package com.battlelancer.seriesguide.ui.shows import androidx.recyclerview.widget.RecyclerView import com.battlelancer.seriesguide.R import com.google.android.material.floatingactionbutton.FloatingActionButton import kotlin.math.abs /** * Hides the floating action button when scrolling down, shows it when scrolling up. If the view can * no longer scroll down, shows the button also. * * Built upon https://github.com/makovkastar/FloatingActionButton scroll detectors. */ internal class FabRecyclerViewScrollDetector(private val button: FloatingActionButton) : RecyclerView.OnScrollListener() { private val scrollThreshold: Int = button.context.resources.getDimensionPixelOffset(R.dimen.fab_scroll_threshold) override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { // always show if scrolled to bottom if (!recyclerView.canScrollVertically(1 /* down */)) { button.show() return } <|user_cursor_is_here|> val isSignificantDelta = Math.abs(dy) > scrollThreshold if (isSignificantDelta) { if (dy > 0) { onScrollDown() } else { onScrollUp() } } } private fun onScrollDown() { button.hide() } private fun onScrollUp() { button.show() } } ```
```app/src/main/java/com/battlelancer/seriesguide/ui/shows/FabRecyclerViewScrollDetector.kt package com.battlelancer.seriesguide.ui.shows import androidx.recyclerview.widget.RecyclerView import com.battlelancer.seriesguide.R import com.google.android.material.floatingactionbutton.FloatingActionButton import kotlin.math.abs /** * Hides the floating action button when scrolling down, shows it when scrolling up. If the view can * no longer scroll down, shows the button also. * * Built upon https://github.com/makovkastar/FloatingActionButton scroll detectors. */ internal class FabRecyclerViewScrollDetector(private val button: FloatingActionButton) : RecyclerView.OnScrollListener() { private val scrollThreshold: Int = button.context.resources.getDimensionPixelOffset(R.dimen.fab_scroll_threshold) override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { // always show if scrolled to bottom if (!recyclerView.canScrollVertically(1 /* down */)) { button.show() return } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Math.abs", "newName": "abs"}} </|tool_call|> val isSignificantDelta = Math.abs(dy) > scrollThreshold if (isSignificantDelta) { if (dy > 0) { onScrollDown() } else { onScrollUp() } } } private fun onScrollDown() { button.hide() } private fun onScrollUp() { button.show() } } ```
User edited file: "src/conn/futures/ping.rs": ```diff @@ -6,7 +6,6 @@ use lib_futures::Async::Ready; use lib_futures::Future; use lib_futures::Poll; -use proto::Packet; use proto::PacketType; @@ -65,4 +64,4 @@ }, } } -} +} ``` User edited file: "src/conn/futures/ping.rs": ```diff @@ -9,14 +9,11 @@ use proto::PacketType; -enum Step { - WritePacket(WritePacket), - ReadResponse(ReadPacket), -} - -enum Out { - WritePacket(Conn), - ReadResponse((Conn, Packet)), +steps! { + Ping { + WritePacket(WritePacket), + ReadPacket(ReadPacket), + } } pub struct Ping { ``` User edited file: "src/conn/futures/ping.rs": ```diff @@ -16,24 +16,9 @@ } } +/// Future that resolves to `Conn` if MySql's `COM_PING` was executed successfully. pub struct Ping { step: Step, -} - -/// Future that resolves to `Conn` if MySql's `COM_PING` was executed successfully. -impl Ping { - fn either_poll(&mut self) -> Result<Async<Out>> { - match self.step { - Step::WritePacket(ref mut fut) => { - let val = try_ready!(fut.poll()); - Ok(Ready(Out::WritePacket(val))) - }, - Step::ReadResponse(ref mut fut) => { - let val = try_ready!(fut.poll()); - Ok(Ready(Out::ReadResponse(val))) - }, - } - } } pub fn new(write_packet: WritePacket) -> Ping { ```
```src/conn/futures/ping.rs use Conn; use conn::futures::read_packet::ReadPacket; use conn::futures::write_packet::WritePacket; use errors::*; use lib_futures::Async; use lib_futures::Async::Ready; use lib_futures::Future; use lib_futures::Poll; use proto::PacketType; steps! { Ping { WritePacket(WritePacket), ReadPacket(ReadPacket), } } /// Future that resolves to `Conn` if MySql's `COM_PING` was executed successfully. pub struct Ping { step: Step, } pub fn new(write_packet: WritePacket) -> Ping { Ping { step: Step::WritePacket(write_packet), } } impl Future for Ping { type Item = Conn; type Error = Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match try_ready!(self.either_poll()) { Out::WritePacket(conn) => { <|user_cursor_is_here|> self.step = Step::ReadResponse(conn.read_packet()); self.poll() }, Out::ReadResponse((conn, packet)) => { if packet.is(PacketType::Ok) { Ok(Ready(conn)) } else { Err(ErrorKind::UnexpectedPacket.into()) } }, } } } ```
```src/conn/futures/ping.rs use Conn; use conn::futures::read_packet::ReadPacket; use conn::futures::write_packet::WritePacket; use errors::*; use lib_futures::Async; use lib_futures::Async::Ready; use lib_futures::Future; use lib_futures::Poll; use proto::PacketType; steps! { Ping { WritePacket(WritePacket), ReadPacket(ReadPacket), } } /// Future that resolves to `Conn` if MySql's `COM_PING` was executed successfully. pub struct Ping { step: Step, } pub fn new(write_packet: WritePacket) -> Ping { Ping { step: Step::WritePacket(write_packet), } } impl Future for Ping { type Item = Conn; type Error = Error; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { match try_ready!(self.either_poll()) { Out::WritePacket(conn) => { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "ReadResponse", "newName": "ReadPacket"}} </|tool_call|> self.step = Step::ReadResponse(conn.read_packet()); self.poll() }, Out::ReadResponse((conn, packet)) => { if packet.is(PacketType::Ok) { Ok(Ready(conn)) } else { Err(ErrorKind::UnexpectedPacket.into()) } }, } } } ```
User edited file: "ee-email_des/src/main/kotlin/ee/email/EmailModelGenerator.kt": ```diff @@ -1,9 +1,9 @@ package ee.email -import ee.design.KotlinGenerator +import ee.design.gen.DesingKotlinGenerator import ee.lang.integ.eePath fun main(args: Array<String>) { val generator = KotlinGenerator(model()) generator.generate(eePath) -} +} ```
```ee-email_des/src/main/kotlin/ee/email/EmailModelGenerator.kt package ee.email import ee.design.gen.DesingKotlinGenerator import ee.lang.integ.eePath fun main(args: Array<String>) { <|user_cursor_is_here|> val generator = KotlinGenerator(model()) generator.generate(eePath) } ```
```ee-email_des/src/main/kotlin/ee/email/EmailModelGenerator.kt package ee.email import ee.design.gen.DesingKotlinGenerator import ee.lang.integ.eePath fun main(args: Array<String>) { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "KotlinGenerator", "newName": "DesingKotlinGenerator"}} </|tool_call|> val generator = KotlinGenerator(model()) generator.generate(eePath) } ```
User edited file: "lazers-changes-stream/examples/simple_parsing.rs": ```diff @@ -1,7 +1,7 @@ extern crate hyper; extern crate serde; extern crate serde_json as json; -extern crate syncdb_changes_stream; +extern crate lazers_changes_stream; use syncdb_changes_stream::changes_stream::ChangesStream; @@ -24,5 +24,4 @@ for change in stream.changes() { println!("{:?}", change); } -} - +} ```
```lazers-changes-stream/examples/simple_parsing.rs extern crate hyper; extern crate serde; extern crate serde_json as json; extern crate lazers_changes_stream; <|user_cursor_is_here|> use syncdb_changes_stream::changes_stream::ChangesStream; use hyper::Client; use hyper::header::Connection; fn main() { // Create a client. let client = Client::new(); // Creating an outgoing request. let res = client.get("http://localhost:5984/test/_changes?feed=continuous&include_docs=true") // set a header .header(Connection::close()) // let 'er go! .send().unwrap(); let stream: ChangesStream<_,json::Value> = ChangesStream::new(res); for change in stream.changes() { println!("{:?}", change); } } ```
```lazers-changes-stream/examples/simple_parsing.rs extern crate hyper; extern crate serde; extern crate serde_json as json; extern crate lazers_changes_stream; <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "syncdb_changes_stream", "newName": "lazers_changes_stream"}} </|tool_call|> use syncdb_changes_stream::changes_stream::ChangesStream; use hyper::Client; use hyper::header::Connection; fn main() { // Create a client. let client = Client::new(); // Creating an outgoing request. let res = client.get("http://localhost:5984/test/_changes?feed=continuous&include_docs=true") // set a header .header(Connection::close()) // let 'er go! .send().unwrap(); let stream: ChangesStream<_,json::Value> = ChangesStream::new(res); for change in stream.changes() { println!("{:?}", change); } } ```
User edited file: "src/world/World.java": ```diff @@ -2,7 +2,7 @@ import edu.stuy.starlorn.entities.Entity; -import java.util.ArrayList; +import java.util.LinkedList; /* * Represents a world with entities in it @@ -25,4 +25,4 @@ e.postStep(); } } -} +} ``` User edited file: "src/world/World.java": ```diff @@ -8,7 +8,7 @@ * Represents a world with entities in it */ public class World { - private ArrayList<Entity> _entities; + private LinkedList<Entity> _entities; public World() { _entities = new ArrayList<Entity>(); ```
```src/world/World.java package edu.stuy.starlorn.world; import edu.stuy.starlorn.entities.Entity; import java.util.LinkedList; /* * Represents a world with entities in it */ public class World { private LinkedList<Entity> _entities; public World() { <|user_cursor_is_here|> _entities = new ArrayList<Entity>(); } public void addEntity(Entity e) { _entities.add(e); } public void stepAll() { for (Entity e : _entities) { e.preStep(); e.step(); e.postStep(); } } } ```
```src/world/World.java package edu.stuy.starlorn.world; import edu.stuy.starlorn.entities.Entity; import java.util.LinkedList; /* * Represents a world with entities in it */ public class World { private LinkedList<Entity> _entities; public World() { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "ArrayList", "newName": "LinkedList"}} </|tool_call|> _entities = new ArrayList<Entity>(); } public void addEntity(Entity e) { _entities.add(e); } public void stepAll() { for (Entity e : _entities) { e.preStep(); e.step(); e.postStep(); } } } ```
User edited file: "subprojects/docs/src/samples/providers/propertyAndProvider/kotlin/build.gradle.kts": ```diff @@ -21,7 +21,7 @@ // Read-only property calculated from the message @get:Internal - val fullMessage: Provider<String> = message.map { "$it from Gradle" } + val fullMessage: Provider<String> = message.map { it + " from Gradle" } @TaskAction fun printMessage() { @@ -31,4 +31,4 @@ tasks.create<Greeting>("greeting") { message.set("Hi") -} +} ```
```subprojects/docs/src/samples/providers/propertyAndProvider/kotlin/build.gradle.kts /* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ open class Greeting : DefaultTask() { // Configurable by the user @get:Input val message: Property<String> = project.objects.property() // Read-only property calculated from the message @get:Internal val fullMessage: Provider<String> = message.map { it + " from Gradle" } @TaskAction fun printMessage() { logger.quiet(fullMessage.get()) } } <|user_cursor_is_here|> tasks.create<Greeting>("greeting") { message.set("Hi") } ```
```subprojects/docs/src/samples/providers/propertyAndProvider/kotlin/build.gradle.kts /* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ open class Greeting : DefaultTask() { // Configurable by the user @get:Input val message: Property<String> = project.objects.property() // Read-only property calculated from the message @get:Internal val fullMessage: Provider<String> = message.map { it + " from Gradle" } @TaskAction fun printMessage() { logger.quiet(fullMessage.get()) } } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "tasks.create", "newName": "task"}} </|tool_call|> tasks.create<Greeting>("greeting") { message.set("Hi") } ```
User edited file: "app/utils/utilities.py": ```diff @@ -1,5 +1,5 @@ from re import search -from flask import g +from flask import g, request from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User @@ -21,4 +21,4 @@ if user_id: g.current_user = User.query.filter_by(id=user.id).first() return True - return False + return False ``` User edited file: "app/utils/utilities.py": ```diff @@ -1,9 +1,7 @@ from re import search from flask import g, request -from flask_restplus import abort from flask_httpauth import HTTPBasicAuth from app.models.user import User -from instance.config import Config auth = HTTPBasicAuth() ``` User edited file: "app/utils/utilities.py": ```diff @@ -1,6 +1,6 @@ from re import search from flask import g, request -from flask_httpauth import HTTPBasicAuth +from flask_httpauth import HTTPTokenAuth from app.models.user import User auth = HTTPBasicAuth() ``` User edited file: "app/utils/utilities.py": ```diff @@ -3,7 +3,7 @@ from flask_httpauth import HTTPTokenAuth from app.models.user import User -auth = HTTPBasicAuth() +auth = HTTPTokenAuth(scheme='Token') def validate_email(email): ``` User edited file: "app/utils/utilities.py": ```diff @@ -7,7 +7,7 @@ def validate_email(email): - ''' Method to check that a valid email is provided ''' + ''' Method to check that a valid email is provided ''' email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" return True if search(email_re, email) else False ```
```app/utils/utilities.py from re import search from flask import g, request from flask_httpauth import HTTPTokenAuth from app.models.user import User auth = HTTPTokenAuth(scheme='Token') def validate_email(email): ''' Method to check that a valid email is provided ''' email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" return True if search(email_re, email) else False @auth.verify_token def verify_token(token=None): ''' Method to verify token ''' token = request.headers.get('x-access-token') user_id = User.verify_authentication_token(token) if user_id: <|user_cursor_is_here|> g.current_user = User.query.filter_by(id=user.id).first() return True return False ```
```app/utils/utilities.py from re import search from flask import g, request from flask_httpauth import HTTPTokenAuth from app.models.user import User auth = HTTPTokenAuth(scheme='Token') def validate_email(email): ''' Method to check that a valid email is provided ''' email_re = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)" return True if search(email_re, email) else False @auth.verify_token def verify_token(token=None): ''' Method to verify token ''' token = request.headers.get('x-access-token') user_id = User.verify_authentication_token(token) if user_id: <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "user.id", "newName": "user_id"}} </|tool_call|> g.current_user = User.query.filter_by(id=user.id).first() return True return False ```
User edited file: "src/main/java/com/github/blindpirate/gogradle/task/go/GoExecutionAction.java": ```diff @@ -31,7 +31,7 @@ closure.setResolveStrategy(Closure.DELEGATE_FIRST); ClassLoader original = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(closure.getClass().getClassLoader()); - Map<String, String> originalEnv = Go.class.cast(task).getCurrentEnv(); + Map<String, String> originalEnv = Go.class.cast(task).getEnv(); Go.class.cast(task).setCurrentEnv(env); try { synchronized (task) { @@ -48,4 +48,4 @@ return closure.getClass().getClassLoader(); } -} +} ``` User edited file: "src/main/java/com/github/blindpirate/gogradle/task/go/GoExecutionAction.java": ```diff @@ -32,7 +32,7 @@ ClassLoader original = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(closure.getClass().getClassLoader()); Map<String, String> originalEnv = Go.class.cast(task).getEnv(); - Go.class.cast(task).setCurrentEnv(env); + Go.class.cast(task).setEnv(env); try { synchronized (task) { closure.call(task); ```
```src/main/java/com/github/blindpirate/gogradle/task/go/GoExecutionAction.java package com.github.blindpirate.gogradle.task.go; import groovy.lang.Closure; import org.gradle.api.Task; import org.gradle.api.internal.tasks.ContextAwareTaskAction; import org.gradle.api.internal.tasks.TaskExecutionContext; import java.util.Map; public class GoExecutionAction implements ContextAwareTaskAction { private Closure closure; private Map<String, String> env; public static GoExecutionAction wrapClosureWithEnvs(Closure closure, Map<String, String> env) { GoExecutionAction ret = new GoExecutionAction(); ret.env = env; ret.closure = closure; return ret; } private GoExecutionAction() { } @Override public void contextualise(TaskExecutionContext context) { } @Override public void execute(Task task) { closure.setDelegate(task); closure.setResolveStrategy(Closure.DELEGATE_FIRST); ClassLoader original = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(closure.getClass().getClassLoader()); Map<String, String> originalEnv = Go.class.cast(task).getEnv(); Go.class.cast(task).setEnv(env); try { synchronized (task) { closure.call(task); } } finally { Thread.currentThread().setContextClassLoader(original); <|user_cursor_is_here|> Go.class.cast(task).setCurrentEnv(originalEnv); } } @Override public ClassLoader getClassLoader() { return closure.getClass().getClassLoader(); } } ```
```src/main/java/com/github/blindpirate/gogradle/task/go/GoExecutionAction.java package com.github.blindpirate.gogradle.task.go; import groovy.lang.Closure; import org.gradle.api.Task; import org.gradle.api.internal.tasks.ContextAwareTaskAction; import org.gradle.api.internal.tasks.TaskExecutionContext; import java.util.Map; public class GoExecutionAction implements ContextAwareTaskAction { private Closure closure; private Map<String, String> env; public static GoExecutionAction wrapClosureWithEnvs(Closure closure, Map<String, String> env) { GoExecutionAction ret = new GoExecutionAction(); ret.env = env; ret.closure = closure; return ret; } private GoExecutionAction() { } @Override public void contextualise(TaskExecutionContext context) { } @Override public void execute(Task task) { closure.setDelegate(task); closure.setResolveStrategy(Closure.DELEGATE_FIRST); ClassLoader original = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(closure.getClass().getClassLoader()); Map<String, String> originalEnv = Go.class.cast(task).getEnv(); Go.class.cast(task).setEnv(env); try { synchronized (task) { closure.call(task); } } finally { Thread.currentThread().setContextClassLoader(original); <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "setCurrentEnv", "newName": "setEnv"}} </|tool_call|> Go.class.cast(task).setCurrentEnv(originalEnv); } } @Override public ClassLoader getClassLoader() { return closure.getClass().getClassLoader(); } } ```
User edited file: "src/main/java/org/bubenheimer/android/rx/DisposableWrapper.kt": ```diff @@ -18,7 +18,7 @@ package org.bubenheimer.android.rx import io.reactivex.rxjava3.disposables.Disposable -import org.bubenheimer.android.Check +import org.bubenheimer.util.examIsNull /** Cheaper replacement for `SerialDisposable`. Methods are not thread-safe. */ public class DisposableWrapper { @@ -37,4 +37,4 @@ disposable = null } } -} +} ```
```src/main/java/org/bubenheimer/android/rx/DisposableWrapper.kt /* * Copyright (c) 2015-2019 Uli Bubenheimer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.bubenheimer.android.rx import io.reactivex.rxjava3.disposables.Disposable import org.bubenheimer.util.examIsNull /** Cheaper replacement for `SerialDisposable`. Methods are not thread-safe. */ public class DisposableWrapper { private var disposable: Disposable? = null public fun get(): Disposable? = disposable public fun set(disposable: Disposable) { <|user_cursor_is_here|> Check.isNull(this.disposable) this.disposable = disposable } public fun clear() { disposable?.let { it.dispose() disposable = null } } } ```
```src/main/java/org/bubenheimer/android/rx/DisposableWrapper.kt /* * Copyright (c) 2015-2019 Uli Bubenheimer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.bubenheimer.android.rx import io.reactivex.rxjava3.disposables.Disposable import org.bubenheimer.util.examIsNull /** Cheaper replacement for `SerialDisposable`. Methods are not thread-safe. */ public class DisposableWrapper { private var disposable: Disposable? = null public fun get(): Disposable? = disposable public fun set(disposable: Disposable) { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Check.isNull", "newName": "examIsNull"}} </|tool_call|> Check.isNull(this.disposable) this.disposable = disposable } public fun clear() { disposable?.let { it.dispose() disposable = null } } } ```
User edited file: "app/src/main/java/nl/dionsegijn/steppertouchdemo/MainActivity.kt": ```diff @@ -3,6 +3,7 @@ import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.widget.Toast +import kotlinx.android.synthetic.main.activity_main.* import nl.dionsegijn.steppertouch.OnStepCallback import nl.dionsegijn.steppertouch.StepperTouch @@ -28,4 +29,4 @@ bottemStepperTouch.enableSideTap(true) } -} +} ``` User edited file: "app/src/main/java/nl/dionsegijn/steppertouchdemo/MainActivity.kt": ```diff @@ -14,7 +14,6 @@ super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) - val stepperTouch = findViewById(R.id.stepperTouch) as StepperTouch stepperTouch.stepper.setMin(0) stepperTouch.stepper.setMax(5) stepperTouch.stepper.addStepCallback(object : OnStepCallback { ```
```app/src/main/java/nl/dionsegijn/steppertouchdemo/MainActivity.kt package nl.dionsegijn.steppertouchdemo import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* import nl.dionsegijn.steppertouch.OnStepCallback import nl.dionsegijn.steppertouch.StepperTouch class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) stepperTouch.stepper.setMin(0) stepperTouch.stepper.setMax(5) stepperTouch.stepper.addStepCallback(object : OnStepCallback { override fun onStep(value: Int, positive: Boolean) { Toast.makeText(applicationContext, value.toString(), Toast.LENGTH_SHORT).show() } }) <|user_cursor_is_here|> val bottemStepperTouch = findViewById(R.id.bottomStepperTouch) as StepperTouch bottemStepperTouch.stepper.setMin(-10) bottemStepperTouch.stepper.setMax(10) bottemStepperTouch.enableSideTap(true) } } ```
```app/src/main/java/nl/dionsegijn/steppertouchdemo/MainActivity.kt package nl.dionsegijn.steppertouchdemo import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* import nl.dionsegijn.steppertouch.OnStepCallback import nl.dionsegijn.steppertouch.StepperTouch class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) stepperTouch.stepper.setMin(0) stepperTouch.stepper.setMax(5) stepperTouch.stepper.addStepCallback(object : OnStepCallback { override fun onStep(value: Int, positive: Boolean) { Toast.makeText(applicationContext, value.toString(), Toast.LENGTH_SHORT).show() } }) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "bottemStepperTouch", "newName": "bottomStepperTouch"}} </|tool_call|> val bottemStepperTouch = findViewById(R.id.bottomStepperTouch) as StepperTouch bottemStepperTouch.stepper.setMin(-10) bottemStepperTouch.stepper.setMax(10) bottemStepperTouch.enableSideTap(true) } } ```
User edited file: "mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt": ```diff @@ -37,6 +37,6 @@ @Bean("resetPasswordServlet") fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*") - @Bean("resetPasswordServlet") + @Bean("resetPasswordPageServlet") fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*") -} +} ```
```mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt /** * Copyright © MyCollab * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.billing.servlet import org.springframework.boot.web.servlet.ServletRegistrationBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration /** * @author MyCollab Ltd * @since 5.5.0 */ @Configuration class BillingSpringServletRegistrator { @Bean("confirmEmailServlet") fun confirmEmailServlet() = ServletRegistrationBean(ConfirmEmailHandler(), "/user/confirm_signup/*") @Bean("resetPasswordServlet") fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*") @Bean("resetPasswordPageServlet") <|user_cursor_is_here|> fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*") } ```
```mycollab-servlet/src/main/java/com/mycollab/module/billing/servlet/BillingSpringServletRegistrator.kt /** * Copyright © MyCollab * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.billing.servlet import org.springframework.boot.web.servlet.ServletRegistrationBean import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration /** * @author MyCollab Ltd * @since 5.5.0 */ @Configuration class BillingSpringServletRegistrator { @Bean("confirmEmailServlet") fun confirmEmailServlet() = ServletRegistrationBean(ConfirmEmailHandler(), "/user/confirm_signup/*") @Bean("resetPasswordServlet") fun resetPasswordServlet() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/action/*") @Bean("resetPasswordPageServlet") <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "ResetPasswordHandler", "newName": "ResetPasswordUpdatePage"}} </|tool_call|> fun resetPasswordPage() = ServletRegistrationBean(ResetPasswordHandler(), "/user/recoverypassword/*") } ```
User edited file: "src/main/java/seedu/address/storage/XmlFileStorage.java": ```diff @@ -15,7 +15,7 @@ /** * Saves the given taskmanager data to the specified file. */ - public static void saveDataToFile(File file, XmlSerializableTaskManager addressBook) + public static void saveDataToFile(File file, XmlSerializableTaskManager taskManager) throws FileNotFoundException { try { XmlUtil.saveDataToFile(file, addressBook); @@ -36,4 +36,4 @@ } } -} +} ```
```src/main/java/seedu/address/storage/XmlFileStorage.java package seedu.address.storage; import java.io.File; import java.io.FileNotFoundException; import javax.xml.bind.JAXBException; import seedu.address.commons.exceptions.DataConversionException; import seedu.address.commons.util.XmlUtil; /** * Stores taskmanager data in an XML file */ public class XmlFileStorage { /** * Saves the given taskmanager data to the specified file. */ public static void saveDataToFile(File file, XmlSerializableTaskManager taskManager) throws FileNotFoundException { try { <|user_cursor_is_here|> XmlUtil.saveDataToFile(file, addressBook); } catch (JAXBException e) { assert false : "Unexpected exception " + e.getMessage(); } } /** * Returns task manager in the file or an empty task manager */ public static XmlSerializableTaskManager loadDataFromSaveFile(File file) throws DataConversionException, FileNotFoundException { try { return XmlUtil.getDataFromFile(file, XmlSerializableTaskManager.class); } catch (JAXBException e) { throw new DataConversionException(e); } } } ```
```src/main/java/seedu/address/storage/XmlFileStorage.java package seedu.address.storage; import java.io.File; import java.io.FileNotFoundException; import javax.xml.bind.JAXBException; import seedu.address.commons.exceptions.DataConversionException; import seedu.address.commons.util.XmlUtil; /** * Stores taskmanager data in an XML file */ public class XmlFileStorage { /** * Saves the given taskmanager data to the specified file. */ public static void saveDataToFile(File file, XmlSerializableTaskManager taskManager) throws FileNotFoundException { try { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "addressBook", "newName": "taskManager"}} </|tool_call|> XmlUtil.saveDataToFile(file, addressBook); } catch (JAXBException e) { assert false : "Unexpected exception " + e.getMessage(); } } /** * Returns task manager in the file or an empty task manager */ public static XmlSerializableTaskManager loadDataFromSaveFile(File file) throws DataConversionException, FileNotFoundException { try { return XmlUtil.getDataFromFile(file, XmlSerializableTaskManager.class); } catch (JAXBException e) { throw new DataConversionException(e); } } } ```
User edited file: "deploy/generate_production_ini.py": ```diff @@ -3,7 +3,7 @@ """ import os -from dcicutils.deployment_utils import Deployer +from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager class FourfrontDeployer(Deployer): @@ -17,4 +17,4 @@ if __name__ == '__main__': - main() + main() ```
```deploy/generate_production_ini.py """ Based on environment variables make a config file (production.ini) for our encoded application. """ import os from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager <|user_cursor_is_here|> class FourfrontDeployer(Deployer): _MY_DIR = os.path.dirname(__file__) TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files") PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml") def main(): FourfrontDeployer.main() if __name__ == '__main__': main() ```
```deploy/generate_production_ini.py """ Based on environment variables make a config file (production.ini) for our encoded application. """ import os from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Deployer", "newName": "BasicLegacyFourfrontIniFileManager"}} </|tool_call|> class FourfrontDeployer(Deployer): _MY_DIR = os.path.dirname(__file__) TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files") PYPROJECT_FILE_NAME = os.path.join(os.path.dirname(_MY_DIR), "pyproject.toml") def main(): FourfrontDeployer.main() if __name__ == '__main__': main() ```
User edited file: "src/main/kotlin/com/demonwav/mcdev/platform/mixin/MixinCustomJavaDocTagProvider.kt": ```diff @@ -10,7 +10,7 @@ package com.demonwav.mcdev.platform.mixin -import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.OVERWRITE +import com.demonwav.mcdev.platform.mixin.util.MixinConstants import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod @@ -46,4 +46,4 @@ override fun getName() = "reason" } } -} +} ``` User edited file: "src/main/kotlin/com/demonwav/mcdev/platform/mixin/MixinCustomJavaDocTagProvider.kt": ```diff @@ -20,7 +20,7 @@ class MixinCustomJavaDocTagProvider : CustomJavadocTagProvider { - override fun getSupportedTags(): List<JavadocTagInfo> = listOf(OverwriteTag.Author, OverwriteTag.Reason) + override fun getSupportedTags(): List<JavadocTagInfo> = listOf(InjectorTag.Author, InjectorTag.Reason) private sealed class OverwriteTag : JavadocTagInfo { ```
```src/main/kotlin/com/demonwav/mcdev/platform/mixin/MixinCustomJavaDocTagProvider.kt /* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2017 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin import com.demonwav.mcdev.platform.mixin.util.MixinConstants import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.javadoc.CustomJavadocTagProvider import com.intellij.psi.javadoc.JavadocTagInfo import com.intellij.psi.javadoc.PsiDocTagValue class MixinCustomJavaDocTagProvider : CustomJavadocTagProvider { override fun getSupportedTags(): List<JavadocTagInfo> = listOf(InjectorTag.Author, InjectorTag.Reason) <|user_cursor_is_here|> private sealed class OverwriteTag : JavadocTagInfo { override fun isInline() = false override fun isValidInContext(element: PsiElement?): Boolean { return element is PsiMethod && element.modifierList.findAnnotation(OVERWRITE) != null } override fun checkTagValue(value: PsiDocTagValue?): String? = null override fun getReference(value: PsiDocTagValue?) = null object Author : OverwriteTag() { override fun getName() = "author" override fun checkTagValue(value: PsiDocTagValue?): String? { return "The @author JavaDoc tag on @Overwrite methods must be filled in.".takeIf { value?.text?.trim().isNullOrEmpty() } } } object Reason : OverwriteTag() { override fun getName() = "reason" } } } ```
```src/main/kotlin/com/demonwav/mcdev/platform/mixin/MixinCustomJavaDocTagProvider.kt /* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2017 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin import com.demonwav.mcdev.platform.mixin.util.MixinConstants import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.javadoc.CustomJavadocTagProvider import com.intellij.psi.javadoc.JavadocTagInfo import com.intellij.psi.javadoc.PsiDocTagValue class MixinCustomJavaDocTagProvider : CustomJavadocTagProvider { override fun getSupportedTags(): List<JavadocTagInfo> = listOf(InjectorTag.Author, InjectorTag.Reason) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "OverwriteTag", "newName": "InjectorTag"}} </|tool_call|> private sealed class OverwriteTag : JavadocTagInfo { override fun isInline() = false override fun isValidInContext(element: PsiElement?): Boolean { return element is PsiMethod && element.modifierList.findAnnotation(OVERWRITE) != null } override fun checkTagValue(value: PsiDocTagValue?): String? = null override fun getReference(value: PsiDocTagValue?) = null object Author : OverwriteTag() { override fun getName() = "author" override fun checkTagValue(value: PsiDocTagValue?): String? { return "The @author JavaDoc tag on @Overwrite methods must be filled in.".takeIf { value?.text?.trim().isNullOrEmpty() } } } object Reason : OverwriteTag() { override fun getName() = "reason" } } } ```
User edited file: "hold-and-fifo/fifo.js": ```diff @@ -4,8 +4,6 @@ function Fifo(config) { RED.nodes.createNode(this,config); - var me = this; - this.queue = []; this.depth = config.depth; this.status({fill:"red",shape:"ring",text:"no value"}); @@ -44,4 +42,4 @@ RED.nodes.registerType("fifo",Fifo); -} +} ```
```hold-and-fifo/fifo.js module.exports = function(RED) { "use strict"; function Fifo(config) { RED.nodes.createNode(this,config); this.queue = []; this.depth = config.depth; this.status({fill:"red",shape:"ring",text:"no value"}); this.on('input', function (msg) { // are we full? // if so, boot some out if (this.queue.length >= this.depth) { while (this.queue.length >= this.depth) { <|user_cursor_is_here|> var msg = this.queue.shift(); this.send(msg); } } // clone the message and whack it in the queue this.queue.push(msg); if (this.queue.length == this.depth) { // queue is full this.status({fill: "green", shape: "dot", text: this.queue.length + "/" + this.depth + " msgs"}); } else { // queue is partially full this.status({fill: "green", shape: "ring", text: this.queue.length + "/" + this.depth + " msgs"}); } }); this.on("close", function() { }); } RED.nodes.registerType("fifo",Fifo); } ```
```hold-and-fifo/fifo.js module.exports = function(RED) { "use strict"; function Fifo(config) { RED.nodes.createNode(this,config); this.queue = []; this.depth = config.depth; this.status({fill:"red",shape:"ring",text:"no value"}); this.on('input', function (msg) { // are we full? // if so, boot some out if (this.queue.length >= this.depth) { while (this.queue.length >= this.depth) { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "msg", "newName": "outgoing"}} </|tool_call|> var msg = this.queue.shift(); this.send(msg); } } // clone the message and whack it in the queue this.queue.push(msg); if (this.queue.length == this.depth) { // queue is full this.status({fill: "green", shape: "dot", text: this.queue.length + "/" + this.depth + " msgs"}); } else { // queue is partially full this.status({fill: "green", shape: "ring", text: this.queue.length + "/" + this.depth + " msgs"}); } }); this.on("close", function() { }); } RED.nodes.registerType("fifo",Fifo); } ```
User edited file: "tests/ui/zero_offset.rs": ```diff @@ -12,7 +12,7 @@ c.sub(0); c.wrapping_sub(0); - let y = &1 as *const i32; + let sized = &1 as *const i32; y.offset(0); } -} +} ```
```tests/ui/zero_offset.rs fn main() { unsafe { let m = &mut () as *mut (); m.offset(0); m.wrapping_add(0); m.sub(0); m.wrapping_sub(0); let c = &() as *const (); c.offset(0); c.wrapping_add(0); c.sub(0); c.wrapping_sub(0); let sized = &1 as *const i32; <|user_cursor_is_here|> y.offset(0); } } ```
```tests/ui/zero_offset.rs fn main() { unsafe { let m = &mut () as *mut (); m.offset(0); m.wrapping_add(0); m.sub(0); m.wrapping_sub(0); let c = &() as *const (); c.offset(0); c.wrapping_add(0); c.sub(0); c.wrapping_sub(0); let sized = &1 as *const i32; <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "y", "newName": "sized"}} </|tool_call|> y.offset(0); } } ```
User edited file: "UM/View/CompositePass.py": ```diff @@ -1,7 +1,10 @@ # Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. +from UM.Application import Application from UM.Resources import Resources + +from UM.Math.Matrix import Matrix from UM.View.RenderPass import RenderPass from UM.View.GL.OpenGL import OpenGL @@ -33,4 +36,4 @@ self.renderQuad() - self._shader.release() + self._shader.release() ``` User edited file: "UM/View/CompositePass.py": ```diff @@ -10,8 +10,8 @@ from UM.View.GL.OpenGL import OpenGL class CompositePass(RenderPass): - def __init__(self, name, width, height): - super().__init__(name, width, height) + def __init__(self, width, height): + super().__init__("composite", width, height) self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "composite.shader")) self._gl = OpenGL.getInstance().getBindingsObject() ``` User edited file: "UM/View/CompositePass.py": ```diff @@ -15,6 +15,7 @@ self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "composite.shader")) self._gl = OpenGL.getInstance().getBindingsObject() + self._renderer = Application.getInstance().getRenderer() def setCompositeShader(self, shader): self._shader = shader ```
```UM/View/CompositePass.py # Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Application import Application from UM.Resources import Resources from UM.Math.Matrix import Matrix from UM.View.RenderPass import RenderPass from UM.View.GL.OpenGL import OpenGL class CompositePass(RenderPass): def __init__(self, width, height): super().__init__("composite", width, height) self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "composite.shader")) self._gl = OpenGL.getInstance().getBindingsObject() self._renderer = Application.getInstance().getRenderer() def setCompositeShader(self, shader): self._shader = shader def renderContents(self): pass def renderOutput(self): self._shader.bind() texture_unit = 0 <|user_cursor_is_here|> for render_pass in renderer.getRenderPasses(): self._gl.glActiveTexture(texture_unit) self._gl.glBindTexture(self._gl.GL_TEXTURE_2D, render_pass.getTextureId()) texture_unit += 1 self._shader.setUniformValue("u_layer_count", texture_unit + 1) self._shader.setUniformValueArray("u_layers", [range(0, texture_unit)], texture_unit + 1) self.renderQuad() self._shader.release() ```
```UM/View/CompositePass.py # Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Application import Application from UM.Resources import Resources from UM.Math.Matrix import Matrix from UM.View.RenderPass import RenderPass from UM.View.GL.OpenGL import OpenGL class CompositePass(RenderPass): def __init__(self, width, height): super().__init__("composite", width, height) self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "composite.shader")) self._gl = OpenGL.getInstance().getBindingsObject() self._renderer = Application.getInstance().getRenderer() def setCompositeShader(self, shader): self._shader = shader def renderContents(self): pass def renderOutput(self): self._shader.bind() texture_unit = 0 <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "renderer", "newName": "self._renderer"}} </|tool_call|> for render_pass in renderer.getRenderPasses(): self._gl.glActiveTexture(texture_unit) self._gl.glBindTexture(self._gl.GL_TEXTURE_2D, render_pass.getTextureId()) texture_unit += 1 self._shader.setUniformValue("u_layer_count", texture_unit + 1) self._shader.setUniformValueArray("u_layers", [range(0, texture_unit)], texture_unit + 1) self.renderQuad() self._shader.release() ```
User edited file: "djs_playground/urls.py": ```diff @@ -1,5 +1,5 @@ from django.conf import settings -from django.conf.urls import url, include +from django.urls import re_path, include from django.conf.urls.static import static from django.contrib import admin from djs_playground.views import index @@ -8,4 +8,4 @@ url(r'^$', index, name='index'), url(r'^admin/', admin.site.urls), url(r'^summernote/', include('django_summernote.urls')), -] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) +] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ```
```djs_playground/urls.py from django.conf import settings from django.urls import re_path, include from django.conf.urls.static import static from django.contrib import admin from djs_playground.views import index urlpatterns = [ <|user_cursor_is_here|> url(r'^$', index, name='index'), url(r'^admin/', admin.site.urls), url(r'^summernote/', include('django_summernote.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ```
```djs_playground/urls.py from django.conf import settings from django.urls import re_path, include from django.conf.urls.static import static from django.contrib import admin from djs_playground.views import index urlpatterns = [ <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "url", "newName": "re_path"}} </|tool_call|> url(r'^$', index, name='index'), url(r'^admin/', admin.site.urls), url(r'^summernote/', include('django_summernote.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ```
User edited file: "buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt": ```diff @@ -16,6 +16,7 @@ package androidx.build.resources +import androidx.build.getSupportRootFolder import com.android.build.gradle.LibraryExtension import org.gradle.api.Project import java.io.File @@ -28,4 +29,4 @@ ) ) } -} +} ```
```buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt /* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.resources import androidx.build.getSupportRootFolder import com.android.build.gradle.LibraryExtension import org.gradle.api.Project import java.io.File fun Project.configurePublicResourcesStub(extension: LibraryExtension) { extension.libraryVariants.all { variant -> variant.registerGeneratedResFolders( project.files( <|user_cursor_is_here|> File(project.rootDir, "/buildSrc/res") ) ) } } ```
```buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt /* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.resources import androidx.build.getSupportRootFolder import com.android.build.gradle.LibraryExtension import org.gradle.api.Project import java.io.File fun Project.configurePublicResourcesStub(extension: LibraryExtension) { extension.libraryVariants.all { variant -> variant.registerGeneratedResFolders( project.files( <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "project.rootDir", "newName": "project.getSupportRootFolder()"}} </|tool_call|> File(project.rootDir, "/buildSrc/res") ) ) } } ```
User edited file: "day3/solution.js": ```diff @@ -6,6 +6,9 @@ let uniqueSantaPositions = []; function updateUniquePositions() { + let santaPositionStr = santaPosition.toString(); + let roboSantaPositionStr = roboSantaPosition.toString(); + if (uniqueSantaPositions.indexOf(santaPosition.toString()) === -1) { uniqueSantaPositions.push(santaPosition.toString()); } @@ -32,4 +35,4 @@ updateUniquePositions(); }); -console.log("Houses with at least one present:", uniqueSantaPositions.length); +console.log("Houses with at least one present:", uniqueSantaPositions.length); ``` User edited file: "day3/solution.js": ```diff @@ -9,8 +9,8 @@ let santaPositionStr = santaPosition.toString(); let roboSantaPositionStr = roboSantaPosition.toString(); - if (uniqueSantaPositions.indexOf(santaPosition.toString()) === -1) { - uniqueSantaPositions.push(santaPosition.toString()); + if (uniqueSantaPositions.indexOf(santaPositionStr) === -1) { + uniqueSantaPositions.push(santaPositionStr); } if (uniqueSantaPositions.indexOf(roboSantaPosition.toString()) === -1) { ```
```day3/solution.js let input = require("fs").readFileSync("./data").toString(); let santaPosition = [0, 0]; let roboSantaPosition = [0, 0]; let uniqueSantaPositions = []; function updateUniquePositions() { let santaPositionStr = santaPosition.toString(); let roboSantaPositionStr = roboSantaPosition.toString(); if (uniqueSantaPositions.indexOf(santaPositionStr) === -1) { uniqueSantaPositions.push(santaPositionStr); } <|user_cursor_is_here|> if (uniqueSantaPositions.indexOf(roboSantaPosition.toString()) === -1) { uniqueSantaPositions.push(roboSantaPosition.toString()); } } updateUniquePositions(); input.split("").forEach((char, index) => { let currentSantaPos = index % 2 === 0 ? santaPosition : roboSantaPosition; // Part 2 if (char === "^") { currentSantaPos[1]++; } else if (char === "v") { currentSantaPos[1]--; } else if (char === ">") { currentSantaPos[0]++; } else if (char === "<") { currentSantaPos[0]--; } updateUniquePositions(); }); console.log("Houses with at least one present:", uniqueSantaPositions.length); ```
```day3/solution.js let input = require("fs").readFileSync("./data").toString(); let santaPosition = [0, 0]; let roboSantaPosition = [0, 0]; let uniqueSantaPositions = []; function updateUniquePositions() { let santaPositionStr = santaPosition.toString(); let roboSantaPositionStr = roboSantaPosition.toString(); if (uniqueSantaPositions.indexOf(santaPositionStr) === -1) { uniqueSantaPositions.push(santaPositionStr); } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "roboSantaPosition.toString()", "newName": "roboSantaPositionStr"}} </|tool_call|> if (uniqueSantaPositions.indexOf(roboSantaPosition.toString()) === -1) { uniqueSantaPositions.push(roboSantaPosition.toString()); } } updateUniquePositions(); input.split("").forEach((char, index) => { let currentSantaPos = index % 2 === 0 ? santaPosition : roboSantaPosition; // Part 2 if (char === "^") { currentSantaPos[1]++; } else if (char === "v") { currentSantaPos[1]--; } else if (char === ">") { currentSantaPos[0]++; } else if (char === "<") { currentSantaPos[0]--; } updateUniquePositions(); }); console.log("Houses with at least one present:", uniqueSantaPositions.length); ```
User edited file: "src/test/kotlin/jeb/ddsl/FileDescr.kt": ```diff @@ -6,7 +6,7 @@ name: File, fileContent: () -> String) : Node(name) { - private val content = lazy { fileContent() } + private val content by lazy { fileContent() } override fun create() { name.writeText(content.value) @@ -14,4 +14,4 @@ override fun contentEqualTo(file: File) = file.isFile && content.value == file.readText() -} +} ``` User edited file: "src/test/kotlin/jeb/ddsl/FileDescr.kt": ```diff @@ -9,7 +9,7 @@ private val content by lazy { fileContent() } override fun create() { - name.writeText(content.value) + name.writeText(content) } override fun contentEqualTo(file: File) = file.isFile && content.value == file.readText() ```
```src/test/kotlin/jeb/ddsl/FileDescr.kt package jeb.ddsl import java.io.File class FileDescr( name: File, fileContent: () -> String) : Node(name) { private val content by lazy { fileContent() } override fun create() { name.writeText(content) } <|user_cursor_is_here|> override fun contentEqualTo(file: File) = file.isFile && content.value == file.readText() } ```
```src/test/kotlin/jeb/ddsl/FileDescr.kt package jeb.ddsl import java.io.File class FileDescr( name: File, fileContent: () -> String) : Node(name) { private val content by lazy { fileContent() } override fun create() { name.writeText(content) } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "content.value", "newName": "content"}} </|tool_call|> override fun contentEqualTo(file: File) = file.isFile && content.value == file.readText() } ```
User edited file: "testing/tests/simple.rs": ```diff @@ -8,7 +8,7 @@ #[derive(Template)] #[template(path = "simple.html")] -struct TestTemplate { +struct VariablesTemplate { strvar: String, num: i64, i18n: String, @@ -25,4 +25,4 @@ with number: 42\n\ Iñtërnâtiônàlizætiøn is important\n\ in vars too: Iñtërnâtiônàlizætiøn\n"); -} +} ``` User edited file: "testing/tests/simple.rs": ```diff @@ -15,7 +15,7 @@ } #[test] -fn it_works() { +fn test_variables() { let s = TestTemplate { strvar: "foo".to_string(), num: 42, ```
```testing/tests/simple.rs #![feature(proc_macro)] #[macro_use] extern crate askama_derive; extern crate askama; use askama::Template; #[derive(Template)] #[template(path = "simple.html")] struct VariablesTemplate { strvar: String, num: i64, i18n: String, } #[test] fn test_variables() { <|user_cursor_is_here|> let s = TestTemplate { strvar: "foo".to_string(), num: 42, i18n: "Iñtërnâtiônàlizætiøn".to_string(), }; assert_eq!(s.render(), "hello world, foo\n\ with number: 42\n\ Iñtërnâtiônàlizætiøn is important\n\ in vars too: Iñtërnâtiônàlizætiøn\n"); } ```
```testing/tests/simple.rs #![feature(proc_macro)] #[macro_use] extern crate askama_derive; extern crate askama; use askama::Template; #[derive(Template)] #[template(path = "simple.html")] struct VariablesTemplate { strvar: String, num: i64, i18n: String, } #[test] fn test_variables() { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "TestTemplate", "newName": "VariablesTemplate"}} </|tool_call|> let s = TestTemplate { strvar: "foo".to_string(), num: 42, i18n: "Iñtërnâtiônàlizætiøn".to_string(), }; assert_eq!(s.render(), "hello world, foo\n\ with number: 42\n\ Iñtërnâtiônàlizætiøn is important\n\ in vars too: Iñtërnâtiônàlizætiøn\n"); } ```
User edited file: "app/components/stack-metadata/component.js": ```diff @@ -12,7 +12,7 @@ return this.model.get('vhostNames.length') > this.get('maxVisibleDomainNames'); }), - vhostRemaining: Ember.computed('vhostNames', function() { + vhostRemaining: Ember.computed('model.vhostNames', function() { return this.model.get('vhostNames.length') - this.get('maxVisibleDomainNames'); }), @@ -25,4 +25,4 @@ let names = this.model.get('vhostNames'); return names.slice(this.get('maxVisibleDomainNames')).join(', '); }) -}); +}); ``` User edited file: "app/components/stack-metadata/component.js": ```diff @@ -16,7 +16,7 @@ return this.model.get('vhostNames.length') - this.get('maxVisibleDomainNames'); }), - vhostNamesSnippet: Ember.computed('vhostNames', function() { + vhostNamesSnippet: Ember.computed('model.vhostNames', function() { let names = this.model.get('vhostNames'); return names.slice(0, this.get('maxVisibleDomainNames')).join(', '); }), ```
```app/components/stack-metadata/component.js import Ember from 'ember'; export default Ember.Component.extend({ tagName: '', maxVisibleDomainNames: 1, displayVhostNames: Ember.computed('model.vhostNames', function() { return this.model.get('vhostNames').join(', '); }), showVhostTooltip: Ember.computed('model.vhostNames', function() { return this.model.get('vhostNames.length') > this.get('maxVisibleDomainNames'); }), vhostRemaining: Ember.computed('model.vhostNames', function() { return this.model.get('vhostNames.length') - this.get('maxVisibleDomainNames'); }), vhostNamesSnippet: Ember.computed('model.vhostNames', function() { let names = this.model.get('vhostNames'); return names.slice(0, this.get('maxVisibleDomainNames')).join(', '); }), <|user_cursor_is_here|> vhostNamesTooltip: Ember.computed('vhostNames', function() { let names = this.model.get('vhostNames'); return names.slice(this.get('maxVisibleDomainNames')).join(', '); }) }); ```
```app/components/stack-metadata/component.js import Ember from 'ember'; export default Ember.Component.extend({ tagName: '', maxVisibleDomainNames: 1, displayVhostNames: Ember.computed('model.vhostNames', function() { return this.model.get('vhostNames').join(', '); }), showVhostTooltip: Ember.computed('model.vhostNames', function() { return this.model.get('vhostNames.length') > this.get('maxVisibleDomainNames'); }), vhostRemaining: Ember.computed('model.vhostNames', function() { return this.model.get('vhostNames.length') - this.get('maxVisibleDomainNames'); }), vhostNamesSnippet: Ember.computed('model.vhostNames', function() { let names = this.model.get('vhostNames'); return names.slice(0, this.get('maxVisibleDomainNames')).join(', '); }), <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "vhostNames", "newName": "model.vhostNames"}} </|tool_call|> vhostNamesTooltip: Ember.computed('vhostNames', function() { let names = this.model.get('vhostNames'); return names.slice(this.get('maxVisibleDomainNames')).join(', '); }) }); ```
User edited file: "index.js": ```diff @@ -15,7 +15,7 @@ if(!isSecure(req)){ if(req.method === "GET"){ var httpsPort = req.app.get('httpsPort') || 443; - var fullUrl = parseUrl('http://' + req.header('Host') + req.url); + var fullUrl = parseUrl(req.protocol + '://' + req.header('Host') + req.url); res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url); } else { res.status(403).send('SSL Required.'); @@ -23,4 +23,4 @@ } else { next(); } -}; +}; ```
```index.js var parseUrl = require('url').parse; var isSecure = function(req) { if (req.secure) { return true; } else if ( req.get('X-Forwarded-Proto') && req.get('X-Forwarded-Proto').toLowerCase && req.get('X-Forwarded-Proto').toLowerCase() === 'https' ) { return true; } return false; }; exports = module.exports = function(req, res, next){ if(!isSecure(req)){ if(req.method === "GET"){ var httpsPort = req.app.get('httpsPort') || 443; <|user_cursor_is_here|> var fullUrl = parseUrl(req.protocol + '://' + req.header('Host') + req.url); res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url); } else { res.status(403).send('SSL Required.'); } } else { next(); } }; ```
```index.js var parseUrl = require('url').parse; var isSecure = function(req) { if (req.secure) { return true; } else if ( req.get('X-Forwarded-Proto') && req.get('X-Forwarded-Proto').toLowerCase && req.get('X-Forwarded-Proto').toLowerCase() === 'https' ) { return true; } return false; }; exports = module.exports = function(req, res, next){ if(!isSecure(req)){ if(req.method === "GET"){ var httpsPort = req.app.get('httpsPort') || 443; <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "req.url", "newName": "req.originalUrl"}} </|tool_call|> var fullUrl = parseUrl(req.protocol + '://' + req.header('Host') + req.url); res.redirect(301, 'https://' + fullUrl.hostname + ':' + httpsPort + req.url); } else { res.status(403).send('SSL Required.'); } } else { next(); } }; ```
User edited file: "14-redis-repositories/src/main/java/example/Person.java": ```diff @@ -5,7 +5,7 @@ import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Reference; -import org.springframework.data.keyvalue.annotation.KeySpace; +import org.springframework.data.redis.core.RedisHash; import org.springframework.data.redis.core.index.Indexed; import lombok.Data; @@ -23,4 +23,4 @@ City city; @Reference Person mother; -} +} ```
```14-redis-repositories/src/main/java/example/Person.java package example; import java.util.Collections; import java.util.Map; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Reference; import org.springframework.data.redis.core.RedisHash; import org.springframework.data.redis.core.index.Indexed; import lombok.Data; @Data <|user_cursor_is_here|> @KeySpace("persons") class Person { @Id String id; @Indexed String firstname; String lastname; Map<String, String> attributes = Collections.emptyMap(); City city; @Reference Person mother; } ```
```14-redis-repositories/src/main/java/example/Person.java package example; import java.util.Collections; import java.util.Map; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Reference; import org.springframework.data.redis.core.RedisHash; import org.springframework.data.redis.core.index.Indexed; import lombok.Data; @Data <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "KeySpace", "newName": "RedisHash"}} </|tool_call|> @KeySpace("persons") class Person { @Id String id; @Indexed String firstname; String lastname; Map<String, String> attributes = Collections.emptyMap(); City city; @Reference Person mother; } ```
User edited file: "bots.sample/number-jokes/__init__.py": ```diff @@ -1,7 +1,7 @@ import random from botfriend.bot import TextGeneratorBot -class ExampleBot(TextGeneratorBot): +class NumberJokes(TextGeneratorBot): def generate_text(self): """Tell a joke about numbers.""" @@ -15,4 +15,4 @@ punchline = "Because %(plus_1)d ate %(plus_3)d!" return (setup + punchline) % arguments -Bot = ExampleBot +Bot = ExampleBot ```
```bots.sample/number-jokes/__init__.py import random from botfriend.bot import TextGeneratorBot class NumberJokes(TextGeneratorBot): def generate_text(self): """Tell a joke about numbers.""" num = random.randint(1,10) arguments = dict( num=num, plus_1=num+1, plus_3=num+3 ) setup = "Why is %(num)d afraid of %(plus_1)d? " punchline = "Because %(plus_1)d ate %(plus_3)d!" return (setup + punchline) % arguments <|user_cursor_is_here|> Bot = ExampleBot ```
```bots.sample/number-jokes/__init__.py import random from botfriend.bot import TextGeneratorBot class NumberJokes(TextGeneratorBot): def generate_text(self): """Tell a joke about numbers.""" num = random.randint(1,10) arguments = dict( num=num, plus_1=num+1, plus_3=num+3 ) setup = "Why is %(num)d afraid of %(plus_1)d? " punchline = "Because %(plus_1)d ate %(plus_3)d!" return (setup + punchline) % arguments <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "ExampleBot", "newName": "NumberJokes"}} </|tool_call|> Bot = ExampleBot ```
User edited file: "src/main/kotlin/me/mrkirby153/KirBot/command/args/elements/NumberElement.kt": ```diff @@ -12,7 +12,7 @@ val number = num.toDouble() if (number < min) { - throw ArgumentParseException(String.format("The number you specified (%.2f) must be greater than %.2f", number, min)) + throw ArgumentParseException(String.format("The number you specified (%.2f) must be greater than %.1f", number, min)) } if (number > max) { throw ArgumentParseException(String.format("The number you specified (%.2f) must be less than %.2f", number, max)) ``` User edited file: "src/main/kotlin/me/mrkirby153/KirBot/command/args/elements/NumberElement.kt": ```diff @@ -15,7 +15,7 @@ throw ArgumentParseException(String.format("The number you specified (%.2f) must be greater than %.1f", number, min)) } if (number > max) { - throw ArgumentParseException(String.format("The number you specified (%.2f) must be less than %.2f", number, max)) + throw ArgumentParseException(String.format("The number you specified (%.2f) must be less than %.1f", number, max)) } return number } catch (e: Exception) { ```
```src/main/kotlin/me/mrkirby153/KirBot/command/args/elements/NumberElement.kt package me.mrkirby153.KirBot.command.args.elements import me.mrkirby153.KirBot.command.args.ArgumentList import me.mrkirby153.KirBot.command.args.ArgumentParseException import me.mrkirby153.KirBot.command.args.CommandElement class NumberElement(private val min: Double, private val max: Double) : CommandElement<Double> { override fun parse(list: ArgumentList): Double { val num = list.popFirst() try { val number = num.toDouble() if (number < min) { throw ArgumentParseException(String.format("The number you specified (%.2f) must be greater than %.1f", number, min)) } if (number > max) { throw ArgumentParseException(String.format("The number you specified (%.2f) must be less than %.1f", number, max)) } return number <|user_cursor_is_here|> } catch (e: Exception) { throw ArgumentParseException("$num is not a number!") } } } ```
```src/main/kotlin/me/mrkirby153/KirBot/command/args/elements/NumberElement.kt package me.mrkirby153.KirBot.command.args.elements import me.mrkirby153.KirBot.command.args.ArgumentList import me.mrkirby153.KirBot.command.args.ArgumentParseException import me.mrkirby153.KirBot.command.args.CommandElement class NumberElement(private val min: Double, private val max: Double) : CommandElement<Double> { override fun parse(list: ArgumentList): Double { val num = list.popFirst() try { val number = num.toDouble() if (number < min) { throw ArgumentParseException(String.format("The number you specified (%.2f) must be greater than %.1f", number, min)) } if (number > max) { throw ArgumentParseException(String.format("The number you specified (%.2f) must be less than %.1f", number, max)) } return number <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Exception", "newName": "NumberFormatException"}} </|tool_call|> } catch (e: Exception) { throw ArgumentParseException("$num is not a number!") } } } ```
User edited file: "src/org/yoooo/se1/Application.java": ```diff @@ -31,7 +31,7 @@ Scanner scanner = new Scanner(string); SimpleDirectedWeightGraph<String, Integer> graph = new SimpleDirectedWeightGraph<>( new EdgeFactory<String, Integer>() { - int next; + private int next; @Override public Integer createEdge(String source, String target) { @@ -55,4 +55,4 @@ } return graph; } -} +} ```
```src/org/yoooo/se1/Application.java package org.yoooo.se1; import java.util.Scanner; public class Application { public void run(String[] args) { } public SimpleDirectedWeightGraph<String, Integer> getGraph() { return null; } private static Application sInstance = new Application(); public static Application getInstance() { return sInstance; } private Application() { } /** * Parses string and generates graph from the string as specified in feature 1. The string * should only contain lowercase letters and spaces. * * @param string string from input file * @return graph created from string */ private SimpleDirectedWeightGraph<String, Integer> stringToGraph(String string) { Scanner scanner = new Scanner(string); SimpleDirectedWeightGraph<String, Integer> graph = new SimpleDirectedWeightGraph<>( new EdgeFactory<String, Integer>() { <|user_cursor_is_here|> private int next; @Override public Integer createEdge(String source, String target) { return next++; } }); if (!scanner.hasNext()) { return graph; } String prev = scanner.next(); graph.addVertex(prev); while (scanner.hasNext()) { String vertex = scanner.next(); graph.addVertex(vertex); Integer edge = graph.getEdge(prev, vertex); if (edge != null) { graph.setEdgeWeight(edge, graph.getEdgeWeight(edge) + 1); } else { graph.addEdge(prev, vertex); } } return graph; } } ```
```src/org/yoooo/se1/Application.java package org.yoooo.se1; import java.util.Scanner; public class Application { public void run(String[] args) { } public SimpleDirectedWeightGraph<String, Integer> getGraph() { return null; } private static Application sInstance = new Application(); public static Application getInstance() { return sInstance; } private Application() { } /** * Parses string and generates graph from the string as specified in feature 1. The string * should only contain lowercase letters and spaces. * * @param string string from input file * @return graph created from string */ private SimpleDirectedWeightGraph<String, Integer> stringToGraph(String string) { Scanner scanner = new Scanner(string); SimpleDirectedWeightGraph<String, Integer> graph = new SimpleDirectedWeightGraph<>( new EdgeFactory<String, Integer>() { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "next", "newName": "mNext"}} </|tool_call|> private int next; @Override public Integer createEdge(String source, String target) { return next++; } }); if (!scanner.hasNext()) { return graph; } String prev = scanner.next(); graph.addVertex(prev); while (scanner.hasNext()) { String vertex = scanner.next(); graph.addVertex(vertex); Integer edge = graph.getEdge(prev, vertex); if (edge != null) { graph.setEdgeWeight(edge, graph.getEdgeWeight(edge) + 1); } else { graph.addEdge(prev, vertex); } } return graph; } } ```
User edited file: "lib/curry-provider.js": ```diff @@ -14,23 +14,23 @@ } getSuggestions({prefix}) { - if (prefix) { - const suggestions = []; - - for (const module of completions) { - for (const [key, type] of this.acpTypes) { - const createSugg = this.createSuggestion.bind(null, module.name, type); - - const matches = module[key].map(createSugg); - - suggestions.push(...matches); - } - } - - return suggestions; + if (!prefix) { + return null; } - return null; + const suggestions = []; + + for (const module of completions) { + for (const [key, type] of this.acpTypes) { + const createSugg = this.createSugg.bind(null, module.name, type); + + const matches = module[key].map(createSugg); + + suggestions.push(...matches); + } + } + + return suggestions; } createSuggestion(module, type, suggestion) { ```
```lib/curry-provider.js 'use babel'; import completions from '../data/completions'; class CurryProvider { constructor() { this.scopeSelector = '.source.curry'; this.disableForScopeSelector = '.source.curry .comment'; this.suggestionPriority = 2; this.filterSuggestions = true; this.acpTypes = new Map([['types', 'type'], ['constructors', 'tag'], ['functions', 'function']]); } getSuggestions({prefix}) { if (!prefix) { return null; } const suggestions = []; for (const module of completions) { for (const [key, type] of this.acpTypes) { <|user_cursor_is_here|> const createSugg = this.createSugg.bind(null, module.name, type); const matches = module[key].map(createSugg); suggestions.push(...matches); } } return suggestions; } createSuggestion(module, type, suggestion) { return { text: suggestion.name, description: suggestion.description, type: type, leftLabel: module, rightLabel: suggestion.typeSig }; } } export default new CurryProvider(); ```
```lib/curry-provider.js 'use babel'; import completions from '../data/completions'; class CurryProvider { constructor() { this.scopeSelector = '.source.curry'; this.disableForScopeSelector = '.source.curry .comment'; this.suggestionPriority = 2; this.filterSuggestions = true; this.acpTypes = new Map([['types', 'type'], ['constructors', 'tag'], ['functions', 'function']]); } getSuggestions({prefix}) { if (!prefix) { return null; } const suggestions = []; for (const module of completions) { for (const [key, type] of this.acpTypes) { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "createSugg", "newName": "createSuggestion"}} </|tool_call|> const createSugg = this.createSugg.bind(null, module.name, type); const matches = module[key].map(createSugg); suggestions.push(...matches); } } return suggestions; } createSuggestion(module, type, suggestion) { return { text: suggestion.name, description: suggestion.description, type: type, leftLabel: module, rightLabel: suggestion.typeSig }; } } export default new CurryProvider(); ```
User edited file: "app.js": ```diff @@ -4,7 +4,7 @@ // TOKEN is required for connecting to Slack -if (!process.env.TOKEN) { +if (!process.env.SLACK_TOKEN) { console.log('Error: Please specify TOKEN in the environment.'); process.exit(1); } ```
```app.js /** * A Bot for Slack that tracks Mario Kart results and calculates rankings. */ // TOKEN is required for connecting to Slack if (!process.env.SLACK_TOKEN) { console.log('Error: Please specify TOKEN in the environment.'); process.exit(1); } var Botkit = require('botkit'); var controller = Botkit.slackbot(); var bot = controller.spawn({ <|user_cursor_is_here|> token: process.env.TOKEN }) bot.startRTM(function(err,bot,payload) { if (err) { throw new Error('Could not connect to Slack'); } }); controller.hears(["keyword","^pattern$"],["direct_message","direct_mention","mention","ambient"],function(bot,message) { // do something to respond to message // all of the fields available in a normal Slack message object are available // https://api.slack.com/events/message bot.reply(message,'You used a keyword!'); }); ```
```app.js /** * A Bot for Slack that tracks Mario Kart results and calculates rankings. */ // TOKEN is required for connecting to Slack if (!process.env.SLACK_TOKEN) { console.log('Error: Please specify TOKEN in the environment.'); process.exit(1); } var Botkit = require('botkit'); var controller = Botkit.slackbot(); var bot = controller.spawn({ <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "TOKEN", "newName": "SLACK_TOKEN"}} </|tool_call|> token: process.env.TOKEN }) bot.startRTM(function(err,bot,payload) { if (err) { throw new Error('Could not connect to Slack'); } }); controller.hears(["keyword","^pattern$"],["direct_message","direct_mention","mention","ambient"],function(bot,message) { // do something to respond to message // all of the fields available in a normal Slack message object are available // https://api.slack.com/events/message bot.reply(message,'You used a keyword!'); }); ```
User edited file: "src/main/java/com/skelril/skree/service/ModifierService.java": ```diff @@ -11,7 +11,7 @@ import java.util.Collection; public interface ModifierService { - void setExpiry(String modifierName, long time); + void setExpiry(String modifier, long time); long expiryOf(String modifierName); default long statusOf(String modifierName) { return Math.max(expiryOf(modifierName) - System.currentTimeMillis(), 0); @@ -21,4 +21,4 @@ } Collection<Clause<String, Long>> getActiveModifiers(); -} +} ``` User edited file: "src/main/java/com/skelril/skree/service/ModifierService.java": ```diff @@ -12,7 +12,7 @@ public interface ModifierService { void setExpiry(String modifier, long time); - long expiryOf(String modifierName); + long expiryOf(String modifier); default long statusOf(String modifierName) { return Math.max(expiryOf(modifierName) - System.currentTimeMillis(), 0); } ``` User edited file: "src/main/java/com/skelril/skree/service/ModifierService.java": ```diff @@ -13,8 +13,8 @@ public interface ModifierService { void setExpiry(String modifier, long time); long expiryOf(String modifier); - default long statusOf(String modifierName) { - return Math.max(expiryOf(modifierName) - System.currentTimeMillis(), 0); + default long statusOf(String modifier) { + return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0); } default boolean isActive(String modifierName) { return statusOf(modifierName) != 0; ```
```src/main/java/com/skelril/skree/service/ModifierService.java /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.skelril.skree.service; import com.skelril.nitro.Clause; import java.util.Collection; public interface ModifierService { void setExpiry(String modifier, long time); long expiryOf(String modifier); default long statusOf(String modifier) { return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0); } <|user_cursor_is_here|> default boolean isActive(String modifierName) { return statusOf(modifierName) != 0; } Collection<Clause<String, Long>> getActiveModifiers(); } ```
```src/main/java/com/skelril/skree/service/ModifierService.java /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.skelril.skree.service; import com.skelril.nitro.Clause; import java.util.Collection; public interface ModifierService { void setExpiry(String modifier, long time); long expiryOf(String modifier); default long statusOf(String modifier) { return Math.max(expiryOf(modifier) - System.currentTimeMillis(), 0); } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "modifierName", "newName": "modifier"}} </|tool_call|> default boolean isActive(String modifierName) { return statusOf(modifierName) != 0; } Collection<Clause<String, Long>> getActiveModifiers(); } ```
User edited file: "tasks.py": ```diff @@ -10,10 +10,10 @@ @task(help={ 'pty': "Whether to run tests under a pseudo-tty", }) -def integration_tests(pty=True): +def integration(pty=True): """Runs integration tests.""" cmd = 'inv test -o --tests=integration' run(cmd + ('' if pty else ' --no-pty'), pty=pty) -ns = Collection(test, integration_tests, release, docs) +ns = Collection(test, integration_tests, release, docs) ```
```tasks.py from invocations import docs from invocations.testing import test from invocations.packaging import release from invoke import Collection from invoke import run from invoke import task @task(help={ 'pty': "Whether to run tests under a pseudo-tty", }) def integration(pty=True): """Runs integration tests.""" cmd = 'inv test -o --tests=integration' run(cmd + ('' if pty else ' --no-pty'), pty=pty) <|user_cursor_is_here|> ns = Collection(test, integration_tests, release, docs) ```
```tasks.py from invocations import docs from invocations.testing import test from invocations.packaging import release from invoke import Collection from invoke import run from invoke import task @task(help={ 'pty': "Whether to run tests under a pseudo-tty", }) def integration(pty=True): """Runs integration tests.""" cmd = 'inv test -o --tests=integration' run(cmd + ('' if pty else ' --no-pty'), pty=pty) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "integration_tests", "newName": "integration"}} </|tool_call|> ns = Collection(test, integration_tests, release, docs) ```
User edited file: "buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt": ```diff @@ -16,6 +16,7 @@ package androidx.build.resources +import androidx.build.getSupportRootFolder import com.android.build.gradle.LibraryExtension import org.gradle.api.Project import org.gradle.api.tasks.Copy @@ -37,4 +38,4 @@ project.files(targetResFolder).builtBy(generatePublicResourcesTask) ) } -} +} ```
```buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt /* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.resources import androidx.build.getSupportRootFolder import com.android.build.gradle.LibraryExtension import org.gradle.api.Project import org.gradle.api.tasks.Copy import java.io.File fun Project.configurePublicResourcesStub(extension: LibraryExtension) { val targetResFolder = File(project.buildDir, "generated/res/public-stub") val generatePublicResourcesTask = tasks.register( "generatePublicResourcesStub", Copy::class.java ) { task -> <|user_cursor_is_here|> task.from(File(project.rootDir, "buildSrc/res")) task.into(targetResFolder) } extension.libraryVariants.all { variant -> variant.registerGeneratedResFolders( project.files(targetResFolder).builtBy(generatePublicResourcesTask) ) } } ```
```buildSrc/src/main/kotlin/androidx/build/resources/PublicResourcesStubHelper.kt /* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.resources import androidx.build.getSupportRootFolder import com.android.build.gradle.LibraryExtension import org.gradle.api.Project import org.gradle.api.tasks.Copy import java.io.File fun Project.configurePublicResourcesStub(extension: LibraryExtension) { val targetResFolder = File(project.buildDir, "generated/res/public-stub") val generatePublicResourcesTask = tasks.register( "generatePublicResourcesStub", Copy::class.java ) { task -> <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "rootDir", "newName": "getSupportRootFolder()"}} </|tool_call|> task.from(File(project.rootDir, "buildSrc/res")) task.into(targetResFolder) } extension.libraryVariants.all { variant -> variant.registerGeneratedResFolders( project.files(targetResFolder).builtBy(generatePublicResourcesTask) ) } } ```
User edited file: "src/middleware/authenticate.js": ```diff @@ -3,7 +3,6 @@ export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } - var verifyHeader = ( !! config.header) var header = (config.header || 'Authorization').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) @@ -46,4 +45,4 @@ next() }) } -} +} ```
```src/middleware/authenticate.js import handleAdapter from '../handleAdapter' export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } var header = (config.header || 'Authorization').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) return (req, res, next) => { var err req.auth = {} <|user_cursor_is_here|> if (verifyHeader) { var value = req.auth.header = req.headers[header] if ( ! value) { err = new Error(`Missing ${config.header} header.`) err.statusCode = 401 return next(err) } if (config.byToken !== false) { var token = value.replace(tokenRegExp, '$1') if (token.length !== tokenLength) { err = new Error('Invalid token.') err.statusCode = 401 return next(err) } req.auth.token = token } } handleAdapter(req, config, next, (err, user) => { if (err) { err = new Error(err) err.statusCode = 401 return next(err) } req.user = user next() }) } } ```
```src/middleware/authenticate.js import handleAdapter from '../handleAdapter' export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } var header = (config.header || 'Authorization').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) return (req, res, next) => { var err req.auth = {} <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "verifyHeader", "newName": "header"}} </|tool_call|> if (verifyHeader) { var value = req.auth.header = req.headers[header] if ( ! value) { err = new Error(`Missing ${config.header} header.`) err.statusCode = 401 return next(err) } if (config.byToken !== false) { var token = value.replace(tokenRegExp, '$1') if (token.length !== tokenLength) { err = new Error('Invalid token.') err.statusCode = 401 return next(err) } req.auth.token = token } } handleAdapter(req, config, next, (err, user) => { if (err) { err = new Error(err) err.statusCode = 401 return next(err) } req.user = user next() }) } } ```
User edited file: "src/test/java/org/jenkins/ci/plugins/jenkinslint/check/SlaveVersionCheckerTestCase.java": ```diff @@ -1,9 +1,16 @@ package org.jenkins.ci.plugins.jenkinslint.check; +import hudson.model.Node; +import hudson.model.Slave; import hudson.slaves.DumbSlave; +import hudson.slaves.JNLPLauncher; +import hudson.slaves.NodeProperty; +import hudson.slaves.RetentionStrategy; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; + +import java.util.Collections; import static org.junit.Assert.assertTrue; @@ -37,4 +44,4 @@ project.setDescription("#lint:ignore:" + checker.getClass().getSimpleName()); assertTrue(checker.isIgnored(project.getDescription())); }*/ -} +} ``` User edited file: "src/test/java/org/jenkins/ci/plugins/jenkinslint/check/SlaveVersionCheckerTestCase.java": ```diff @@ -12,6 +12,7 @@ import java.util.Collections; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** ``` User edited file: "src/test/java/org/jenkins/ci/plugins/jenkinslint/check/SlaveVersionCheckerTestCase.java": ```diff @@ -16,7 +16,7 @@ import static org.junit.Assert.assertTrue; /** - * SlaveDescriptionChecker Test Case. + * SlaveVersionChecker Test Case. * * @author Victor Martinez */ ```
```src/test/java/org/jenkins/ci/plugins/jenkinslint/check/SlaveVersionCheckerTestCase.java package org.jenkins.ci.plugins.jenkinslint.check; import hudson.model.Node; import hudson.model.Slave; import hudson.slaves.DumbSlave; import hudson.slaves.JNLPLauncher; import hudson.slaves.NodeProperty; import hudson.slaves.RetentionStrategy; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.Collections; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * SlaveVersionChecker Test Case. * * @author Victor Martinez */ public class SlaveVersionCheckerTestCase { <|user_cursor_is_here|> private SlaveDescriptionChecker checker = new SlaveDescriptionChecker(); @Rule public JenkinsRule j = new JenkinsRule(); @Test public void testDefaultSlave() throws Exception { DumbSlave slave = j.createSlave(); assertTrue(checker.executeCheck(slave)); } @Test public void testEmptySlaveName() throws Exception { DumbSlave slave = j.createSlave(); slave.setNodeName(""); assertTrue(checker.executeCheck(slave)); } @Test public void testSlaveDescription() throws Exception { DumbSlave slave = j.createSlave(); slave.setNodeName("blablabla"); assertTrue(checker.executeCheck(slave)); } /** @Test public void testControlComment() throws Exception { DumbSlave slave = j.createSlave(); assertFalse(checker.isIgnored(project.getDescription())); project.setDescription("#lint:ignore:" + checker.getClass().getSimpleName()); assertTrue(checker.isIgnored(project.getDescription())); }*/ } ```
```src/test/java/org/jenkins/ci/plugins/jenkinslint/check/SlaveVersionCheckerTestCase.java package org.jenkins.ci.plugins.jenkinslint.check; import hudson.model.Node; import hudson.model.Slave; import hudson.slaves.DumbSlave; import hudson.slaves.JNLPLauncher; import hudson.slaves.NodeProperty; import hudson.slaves.RetentionStrategy; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.Collections; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * SlaveVersionChecker Test Case. * * @author Victor Martinez */ public class SlaveVersionCheckerTestCase { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "SlaveDescriptionChecker", "newName": "SlaveVersionChecker"}} </|tool_call|> private SlaveDescriptionChecker checker = new SlaveDescriptionChecker(); @Rule public JenkinsRule j = new JenkinsRule(); @Test public void testDefaultSlave() throws Exception { DumbSlave slave = j.createSlave(); assertTrue(checker.executeCheck(slave)); } @Test public void testEmptySlaveName() throws Exception { DumbSlave slave = j.createSlave(); slave.setNodeName(""); assertTrue(checker.executeCheck(slave)); } @Test public void testSlaveDescription() throws Exception { DumbSlave slave = j.createSlave(); slave.setNodeName("blablabla"); assertTrue(checker.executeCheck(slave)); } /** @Test public void testControlComment() throws Exception { DumbSlave slave = j.createSlave(); assertFalse(checker.isIgnored(project.getDescription())); project.setDescription("#lint:ignore:" + checker.getClass().getSimpleName()); assertTrue(checker.isIgnored(project.getDescription())); }*/ } ```
User edited file: "djangae/blobstore_service.py": ```diff @@ -20,7 +20,7 @@ global blobstore_service global server - from wsgiref.simple_server import make_server, demo_app + from wsgiref.simple_server import make_server from google.appengine.tools.devappserver2.blob_upload import Application port = int(os.environ['SERVER_PORT']) @@ -40,4 +40,4 @@ server.shutdown() blobstore_service.join(5) - blobstore_service = None + blobstore_service = None ``` User edited file: "djangae/blobstore_service.py": ```diff @@ -23,6 +23,10 @@ from wsgiref.simple_server import make_server from google.appengine.tools.devappserver2.blob_upload import Application + from djangae.views import internalupload + from django.core.handlers.wsgi import WSGIRequest + from django.utils.encoding import force_str + port = int(os.environ['SERVER_PORT']) logging.info("Starting blobstore service on port %s", port) server = make_server('', port, Application(demo_app)) ``` User edited file: "djangae/blobstore_service.py": ```diff @@ -27,6 +27,15 @@ from django.core.handlers.wsgi import WSGIRequest from django.utils.encoding import force_str + def handler(environ, start_response): + request = WSGIRequest(environ) + response = internalupload(request) + + status = '%s %s' % (response.status_code, response.reason_phrase) + response_headers = [(str(k), str(v)) for k, v in response.items()] + start_response(force_str(status), response_headers) + return response + port = int(os.environ['SERVER_PORT']) logging.info("Starting blobstore service on port %s", port) server = make_server('', port, Application(demo_app)) ```
```djangae/blobstore_service.py import os import threading import logging blobstore_service = None server = None def start_blobstore_service(): """ When the blobstore files API was deprecated, the blobstore storage was switched to use a POST request to the upload handler when storing files uploaded via Django. Unfortunately this breaks in the local sandbox when you aren't running the dev_appserver because there is no server to handle the blobstore upload. So, this service is kicked off by the local sandbox and only handles blobstore uploads. When runserver kicks in this service is stopped. """ global blobstore_service global server from wsgiref.simple_server import make_server from google.appengine.tools.devappserver2.blob_upload import Application from djangae.views import internalupload from django.core.handlers.wsgi import WSGIRequest from django.utils.encoding import force_str def handler(environ, start_response): request = WSGIRequest(environ) response = internalupload(request) status = '%s %s' % (response.status_code, response.reason_phrase) response_headers = [(str(k), str(v)) for k, v in response.items()] start_response(force_str(status), response_headers) return response port = int(os.environ['SERVER_PORT']) logging.info("Starting blobstore service on port %s", port) <|user_cursor_is_here|> server = make_server('', port, Application(demo_app)) blobstore_service = threading.Thread(target=server.serve_forever) blobstore_service.daemon = True blobstore_service.start() def stop_blobstore_service(): global blobstore_service global server if not blobstore_service: return server.shutdown() blobstore_service.join(5) blobstore_service = None ```
```djangae/blobstore_service.py import os import threading import logging blobstore_service = None server = None def start_blobstore_service(): """ When the blobstore files API was deprecated, the blobstore storage was switched to use a POST request to the upload handler when storing files uploaded via Django. Unfortunately this breaks in the local sandbox when you aren't running the dev_appserver because there is no server to handle the blobstore upload. So, this service is kicked off by the local sandbox and only handles blobstore uploads. When runserver kicks in this service is stopped. """ global blobstore_service global server from wsgiref.simple_server import make_server from google.appengine.tools.devappserver2.blob_upload import Application from djangae.views import internalupload from django.core.handlers.wsgi import WSGIRequest from django.utils.encoding import force_str def handler(environ, start_response): request = WSGIRequest(environ) response = internalupload(request) status = '%s %s' % (response.status_code, response.reason_phrase) response_headers = [(str(k), str(v)) for k, v in response.items()] start_response(force_str(status), response_headers) return response port = int(os.environ['SERVER_PORT']) logging.info("Starting blobstore service on port %s", port) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "demo_app", "newName": "handler"}} </|tool_call|> server = make_server('', port, Application(demo_app)) blobstore_service = threading.Thread(target=server.serve_forever) blobstore_service.daemon = True blobstore_service.start() def stop_blobstore_service(): global blobstore_service global server if not blobstore_service: return server.shutdown() blobstore_service.join(5) blobstore_service = None ```
User edited file: "packages/coinstac-common/src/models/project.js": ```diff @@ -9,7 +9,7 @@ * @extends PouchDocument * @constructor * @property {string} name - * @property {string=} defaultConsortiumId + * @property {string=} consortiumId * @property {(File[])=} files */ function Project() { @@ -23,4 +23,4 @@ }, PouchDocument.schema); util.inherits(Project, PouchDocument); -module.exports = Project; +module.exports = Project; ```
```packages/coinstac-common/src/models/project.js 'use strict'; const PouchDocument = require('./pouch-document'); const joi = require('joi'); const util = require('util'); /** * @class Project * @extends PouchDocument * @constructor * @property {string} name * @property {string=} consortiumId * @property {(File[])=} files */ function Project() { PouchDocument.apply(this, arguments); // eslint-disable-line } Project.schema = Object.assign({ name: joi.string().min(1).regex(/[a-zA-Z]+/, 'at least one character').required(), <|user_cursor_is_here|> defaultConsortiumId: joi.string().optional(), files: joi.alternatives().try(joi.array()).default([]), }, PouchDocument.schema); util.inherits(Project, PouchDocument); module.exports = Project; ```
```packages/coinstac-common/src/models/project.js 'use strict'; const PouchDocument = require('./pouch-document'); const joi = require('joi'); const util = require('util'); /** * @class Project * @extends PouchDocument * @constructor * @property {string} name * @property {string=} consortiumId * @property {(File[])=} files */ function Project() { PouchDocument.apply(this, arguments); // eslint-disable-line } Project.schema = Object.assign({ name: joi.string().min(1).regex(/[a-zA-Z]+/, 'at least one character').required(), <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "defaultConsortiumId", "newName": "consortiumId"}} </|tool_call|> defaultConsortiumId: joi.string().optional(), files: joi.alternatives().try(joi.array()).default([]), }, PouchDocument.schema); util.inherits(Project, PouchDocument); module.exports = Project; ```
User edited file: "protocol/src/lib.rs": ```diff @@ -8,7 +8,7 @@ pub type Result<T> = std::result::Result<T, error::LDAPError>; -pub fn build_envelope(msgid: i32, protocolOp: common::Tag, controls: Option<common::Tag>) -> common::Tag +pub fn construct_envelope(msgid: i32, protocolOp: common::Tag, controls: Option<common::Tag>) -> common::Tag { let msgidtag = msgid.into_ber_universal(); @@ -42,4 +42,4 @@ }; Ok((msgid, protocolOp, controls)) -} +} ``` User edited file: "protocol/src/lib.rs": ```diff @@ -13,8 +13,9 @@ let msgidtag = msgid.into_ber_universal(); - let plvec = if controls.is_some() { - vec![msgidtag, protocolOp, controls.unwrap()] } + let plvec = if let Some(controls) = controls { + vec![msgidtag, protocolOp, controls] + } else { vec![msgidtag, protocolOp] }; ```
```protocol/src/lib.rs extern crate byteorder; pub mod ber; pub mod error; use ber::common; use ber::types::ASNType; pub type Result<T> = std::result::Result<T, error::LDAPError>; pub fn construct_envelope(msgid: i32, protocolOp: common::Tag, controls: Option<common::Tag>) -> common::Tag { let msgidtag = msgid.into_ber_universal(); let plvec = if let Some(controls) = controls { vec![msgidtag, protocolOp, controls] } else { vec![msgidtag, protocolOp] }; plvec.into_ber_universal() } <|user_cursor_is_here|> pub fn unwrap_envelope(envelope: common::Tag) -> Result<(i32, common::Tag, Option<common::Tag>)> { let common::Tag { _value, .. } = envelope; let mut tagvec = match _value { common::Payload::Constructed(e) => e, common::Payload::Primitive(_) => { return Err(error::LDAPError::Protocol) }, }; if tagvec.len() < 3 || tagvec.len() > 2 { return Err(error::LDAPError::Protocol) } let mut msgidtag = tagvec.pop().unwrap(); let protocolOp = tagvec.pop().unwrap(); let controls = tagvec.pop(); let msgid = match i32::from_tag(&mut msgidtag) { Some(e) => e, None => return Err(error::LDAPError::Protocol), }; Ok((msgid, protocolOp, controls)) } ```
```protocol/src/lib.rs extern crate byteorder; pub mod ber; pub mod error; use ber::common; use ber::types::ASNType; pub type Result<T> = std::result::Result<T, error::LDAPError>; pub fn construct_envelope(msgid: i32, protocolOp: common::Tag, controls: Option<common::Tag>) -> common::Tag { let msgidtag = msgid.into_ber_universal(); let plvec = if let Some(controls) = controls { vec![msgidtag, protocolOp, controls] } else { vec![msgidtag, protocolOp] }; plvec.into_ber_universal() } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "unwrap_envelope", "newName": "deconstruct_envelope"}} </|tool_call|> pub fn unwrap_envelope(envelope: common::Tag) -> Result<(i32, common::Tag, Option<common::Tag>)> { let common::Tag { _value, .. } = envelope; let mut tagvec = match _value { common::Payload::Constructed(e) => e, common::Payload::Primitive(_) => { return Err(error::LDAPError::Protocol) }, }; if tagvec.len() < 3 || tagvec.len() > 2 { return Err(error::LDAPError::Protocol) } let mut msgidtag = tagvec.pop().unwrap(); let protocolOp = tagvec.pop().unwrap(); let controls = tagvec.pop(); let msgid = match i32::from_tag(&mut msgidtag) { Some(e) => e, None => return Err(error::LDAPError::Protocol), }; Ok((msgid, protocolOp, controls)) } ```
User edited file: "app/src/store/index.js": ```diff @@ -18,7 +18,7 @@ persistencePlugin({ prefix: "sulcalc", saveOn: { - addCustomSets: "sets.custom", + importPokemon: "sets.custom", setSmogonSets: "enabledSets.smogon", setPokemonPerfectSets: "enabledSets.pokemonPerfect", setCustomSets: "enabledSets.custom", @@ -28,4 +28,4 @@ }), i18nPlugin() ] -}); +}); ``` User edited file: "app/src/store/index.js": ```diff @@ -19,7 +19,7 @@ prefix: "sulcalc", saveOn: { importPokemon: "sets.custom", - setSmogonSets: "enabledSets.smogon", + toggleSmogonSets: "enabledSets.smogon", setPokemonPerfectSets: "enabledSets.pokemonPerfect", setCustomSets: "enabledSets.custom", setLongRolls: "longRolls", ``` User edited file: "app/src/store/index.js": ```diff @@ -20,7 +20,7 @@ saveOn: { importPokemon: "sets.custom", toggleSmogonSets: "enabledSets.smogon", - setPokemonPerfectSets: "enabledSets.pokemonPerfect", + togglePokemonPerfectSets: "enabledSets.pokemonPerfect", setCustomSets: "enabledSets.custom", setLongRolls: "longRolls", setFractions: "fractions" ``` User edited file: "app/src/store/index.js": ```diff @@ -21,7 +21,7 @@ importPokemon: "sets.custom", toggleSmogonSets: "enabledSets.smogon", togglePokemonPerfectSets: "enabledSets.pokemonPerfect", - setCustomSets: "enabledSets.custom", + toggleCustomSets: "enabledSets.custom", setLongRolls: "longRolls", setFractions: "fractions" } ``` User edited file: "app/src/store/index.js": ```diff @@ -22,7 +22,7 @@ toggleSmogonSets: "enabledSets.smogon", togglePokemonPerfectSets: "enabledSets.pokemonPerfect", toggleCustomSets: "enabledSets.custom", - setLongRolls: "longRolls", + toggleLongRolls: "longRolls", setFractions: "fractions" } }), ```
```app/src/store/index.js import Vue from "vue"; import Vuex, {Store} from "vuex"; import state from "./state"; import * as mutations from "./mutations"; import * as getters from "./getters"; import * as actions from "./actions"; import {persistencePlugin, i18nPlugin} from "./plugins"; Vue.use(Vuex); export default new Store({ strict: process.env.NODE_ENV !== "production", state, mutations, getters, actions, plugins: [ persistencePlugin({ prefix: "sulcalc", saveOn: { importPokemon: "sets.custom", toggleSmogonSets: "enabledSets.smogon", togglePokemonPerfectSets: "enabledSets.pokemonPerfect", toggleCustomSets: "enabledSets.custom", toggleLongRolls: "longRolls", <|user_cursor_is_here|> setFractions: "fractions" } }), i18nPlugin() ] }); ```
```app/src/store/index.js import Vue from "vue"; import Vuex, {Store} from "vuex"; import state from "./state"; import * as mutations from "./mutations"; import * as getters from "./getters"; import * as actions from "./actions"; import {persistencePlugin, i18nPlugin} from "./plugins"; Vue.use(Vuex); export default new Store({ strict: process.env.NODE_ENV !== "production", state, mutations, getters, actions, plugins: [ persistencePlugin({ prefix: "sulcalc", saveOn: { importPokemon: "sets.custom", toggleSmogonSets: "enabledSets.smogon", togglePokemonPerfectSets: "enabledSets.pokemonPerfect", toggleCustomSets: "enabledSets.custom", toggleLongRolls: "longRolls", <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "setFractions", "newName": "toggleFractions"}} </|tool_call|> setFractions: "fractions" } }), i18nPlugin() ] }); ```
User edited file: "rust/all-your-base/src/lib.rs": ```diff @@ -1,34 +1,3 @@ -/// -/// Convert a number between two bases. -/// -/// A number is any slice of digits. -/// A digit is any unsigned integer (e.g. u8, u16, u32, u64, or usize). -/// Bases are specified as unsigned integers. -/// -/// Return an `Err(.)` if the conversion is impossible. -/// The tests do not test for specific values inside the `Err(.)`. -/// -/// -/// You are allowed to change the function signature as long as all test still pass. -/// -/// -/// Example: -/// Input -/// number: &[4, 2] -/// from_base: 10 -/// to_base: 2 -/// Result -/// Ok(vec![1, 0, 1, 0, 1, 0]) -/// -/// The example corresponds to converting the number 42 from decimal -/// which is equivalent to 101010 in binary. -/// -/// -/// Notes: -/// * The empty slice ( "[]" ) is equal to the number 0. -/// * Never output leading 0 digits. However, your function must be able to -/// process input with leading 0 digits. -/// #[allow(unused_variables)] pub fn convert(number: &[u32], from_base: u32, to_base: u32) -> Result<Vec<u32>, ()> { if number.into_iter().any(|&x| x >= from_base) { @@ -53,4 +22,4 @@ result.reverse(); Ok(result) -} +} ``` User edited file: "rust/all-your-base/src/lib.rs": ```diff @@ -1,4 +1,3 @@ -#[allow(unused_variables)] pub fn convert(number: &[u32], from_base: u32, to_base: u32) -> Result<Vec<u32>, ()> { if number.into_iter().any(|&x| x >= from_base) { return Err(()); ``` User edited file: "rust/all-your-base/src/lib.rs": ```diff @@ -1,9 +1,9 @@ pub fn convert(number: &[u32], from_base: u32, to_base: u32) -> Result<Vec<u32>, ()> { - if number.into_iter().any(|&x| x >= from_base) { + if from_base < 2 || to_base < 2 { return Err(()); } - if from_base < 2 || to_base < 2 { + if number.into_iter().any(|&x| x >= from_base) { return Err(()); } ``` User edited file: "rust/all-your-base/src/lib.rs": ```diff @@ -3,7 +3,7 @@ return Err(()); } - if number.into_iter().any(|&x| x >= from_base) { + if number.iter().any(|&x| x >= from_base) { return Err(()); } ``` User edited file: "rust/all-your-base/src/lib.rs": ```diff @@ -7,7 +7,7 @@ return Err(()); } - let mut r = number.into_iter().fold(0, |acc, &x| acc * from_base + x); + let mut r = number.iter().fold(0, |acc, &x| acc * from_base + x); let mut result = (0..) .take_while(move |&x| r >= to_base.pow(x as u32)) ``` User edited file: "rust/all-your-base/src/lib.rs": ```diff @@ -7,7 +7,8 @@ return Err(()); } - let mut r = number.iter().fold(0, |acc, &x| acc * from_base + x); + let limit = number.iter().fold(0, |acc, &x| acc * from_base + x); + let mut r = limit; let mut result = (0..) .take_while(move |&x| r >= to_base.pow(x as u32)) ```
```rust/all-your-base/src/lib.rs pub fn convert(number: &[u32], from_base: u32, to_base: u32) -> Result<Vec<u32>, ()> { if from_base < 2 || to_base < 2 { return Err(()); } if number.iter().any(|&x| x >= from_base) { return Err(()); } let limit = number.iter().fold(0, |acc, &x| acc * from_base + x); let mut r = limit; let mut result = (0..) <|user_cursor_is_here|> .take_while(move |&x| r >= to_base.pow(x as u32)) .map(|x| { let d = r % to_base; r /= to_base; d }) .collect::<Vec<_>>(); result.reverse(); Ok(result) } ```
```rust/all-your-base/src/lib.rs pub fn convert(number: &[u32], from_base: u32, to_base: u32) -> Result<Vec<u32>, ()> { if from_base < 2 || to_base < 2 { return Err(()); } if number.iter().any(|&x| x >= from_base) { return Err(()); } let limit = number.iter().fold(0, |acc, &x| acc * from_base + x); let mut r = limit; let mut result = (0..) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "r", "newName": "limit"}} </|tool_call|> .take_while(move |&x| r >= to_base.pow(x as u32)) .map(|x| { let d = r % to_base; r /= to_base; d }) .collect::<Vec<_>>(); result.reverse(); Ok(result) } ```
User edited file: "platform/platform-impl/src/com/intellij/ui/NotificationActions.kt": ```diff @@ -23,7 +23,7 @@ * @author Alexander Lobas */ -abstract class NotificationAction : AnAction() { +abstract class CloseNotificationAction : AnAction() { override fun update(e: AnActionEvent) { val layout = getBalloonLayout(e) e.presentation.isEnabled = layout != null && layout.balloonCount > 0 ``` User edited file: "platform/platform-impl/src/com/intellij/ui/NotificationActions.kt": ```diff @@ -32,7 +32,7 @@ protected fun getBalloonLayout(e: AnActionEvent) = e.getData(IdeFrame.KEY)?.balloonLayout as BalloonLayoutImpl? } -class CloseFirstNotificationAction : NotificationAction() { +class CloseFirstNotificationAction : CloseNotificationAction() { override fun actionPerformed(e: AnActionEvent) { getBalloonLayout(e)?.closeFirst() } ```
```platform/platform-impl/src/com/intellij/ui/NotificationActions.kt /* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.wm.IdeFrame <|user_cursor_is_here|> /** * @author Alexander Lobas */ abstract class CloseNotificationAction : AnAction() { override fun update(e: AnActionEvent) { val layout = getBalloonLayout(e) e.presentation.isEnabled = layout != null && layout.balloonCount > 0 } protected fun getBalloonLayout(e: AnActionEvent) = e.getData(IdeFrame.KEY)?.balloonLayout as BalloonLayoutImpl? } class CloseFirstNotificationAction : CloseNotificationAction() { override fun actionPerformed(e: AnActionEvent) { getBalloonLayout(e)?.closeFirst() } } class CloseAllNotificationsAction : NotificationAction() { override fun actionPerformed(e: AnActionEvent) { getBalloonLayout(e)?.closeAll() } } ```
```platform/platform-impl/src/com/intellij/ui/NotificationActions.kt /* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.wm.IdeFrame <|user_cursor_is_here|> /** * @author Alexander Lobas */ abstract class CloseNotificationAction : AnAction() { override fun update(e: AnActionEvent) { val layout = getBalloonLayout(e) e.presentation.isEnabled = layout != null && layout.balloonCount > 0 } protected fun getBalloonLayout(e: AnActionEvent) = e.getData(IdeFrame.KEY)?.balloonLayout as BalloonLayoutImpl? } class CloseFirstNotificationAction : CloseNotificationAction() { override fun actionPerformed(e: AnActionEvent) { getBalloonLayout(e)?.closeFirst() } } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "NotificationAction", "newName": "CloseNotificationAction"}} </|tool_call|> class CloseAllNotificationsAction : NotificationAction() { override fun actionPerformed(e: AnActionEvent) { getBalloonLayout(e)?.closeAll() } } ```
User edited file: "src/Input/TouchInput.js": ```diff @@ -1,5 +1,6 @@ -function TouchInput(inputController) { +function TouchInput(inputController, element) { this.inputController = inputController; + this.element = typeof element !== 'undefined' ? element : document; } TouchInput.prototype.listen = function() { @@ -33,4 +34,4 @@ this.xStart = null; this.yStart = null; -}; +}; ```
```src/Input/TouchInput.js function TouchInput(inputController, element) { this.inputController = inputController; this.element = typeof element !== 'undefined' ? element : document; } TouchInput.prototype.listen = function() { <|user_cursor_is_here|> document.addEventListener('touchstart', this.startTouch.bind(this)); document.addEventListener('touchmove', this.detectSwipe.bind(this)); }; TouchInput.prototype.startTouch = function(event) { this.xStart = event.touches[0].clientX; this.yStart = event.touches[0].clientY; }; TouchInput.prototype.detectSwipe = function(event) { if( this.xStart === null || this.yStart === null) { return; } var xEnd = event.touches[0].clientX; var yEnd = event.touches[0].clientY; var deltaX = xEnd - this.xStart; var deltaY = yEnd - this.yStart; var isHorizontalSwipe = Math.abs(deltaX) > Math.abs(deltaY); if(isHorizontalSwipe) { deltaX < 0 ? this.inputController.left(): this.inputController.right(); } else if(deltaY > 0) { this.inputController.down(); } this.xStart = null; this.yStart = null; }; ```
```src/Input/TouchInput.js function TouchInput(inputController, element) { this.inputController = inputController; this.element = typeof element !== 'undefined' ? element : document; } TouchInput.prototype.listen = function() { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "document", "newName": "this.element"}} </|tool_call|> document.addEventListener('touchstart', this.startTouch.bind(this)); document.addEventListener('touchmove', this.detectSwipe.bind(this)); }; TouchInput.prototype.startTouch = function(event) { this.xStart = event.touches[0].clientX; this.yStart = event.touches[0].clientY; }; TouchInput.prototype.detectSwipe = function(event) { if( this.xStart === null || this.yStart === null) { return; } var xEnd = event.touches[0].clientX; var yEnd = event.touches[0].clientY; var deltaX = xEnd - this.xStart; var deltaY = yEnd - this.yStart; var isHorizontalSwipe = Math.abs(deltaX) > Math.abs(deltaY); if(isHorizontalSwipe) { deltaX < 0 ? this.inputController.left(): this.inputController.right(); } else if(deltaY > 0) { this.inputController.down(); } this.xStart = null; this.yStart = null; }; ```
User edited file: "core/src/us/thirdmillenium/desktoptrainer/DesktopTrainer.java": ```diff @@ -3,7 +3,7 @@ import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; -import us.thirdmillenium.desktoptrainer.environment.SinglePlayEnvironment; +import us.thirdmillenium.desktoptrainer.environment.Environment; import java.util.Random; @@ -27,4 +27,4 @@ public void render () { this.MyEnvironment.simulate(Gdx.graphics.getDeltaTime()); } -} +} ``` User edited file: "core/src/us/thirdmillenium/desktoptrainer/DesktopTrainer.java": ```diff @@ -9,9 +9,6 @@ public class DesktopTrainer extends ApplicationAdapter { - // Test Map Index (1 - 5) - private int TestMapIndex = 3; - // Environment private SinglePlayEnvironment MyEnvironment; ``` User edited file: "core/src/us/thirdmillenium/desktoptrainer/DesktopTrainer.java": ```diff @@ -10,7 +10,7 @@ public class DesktopTrainer extends ApplicationAdapter { // Environment - private SinglePlayEnvironment MyEnvironment; + private Environment MyEnvironment; @Override ``` User edited file: "core/src/us/thirdmillenium/desktoptrainer/DesktopTrainer.java": ```diff @@ -12,12 +12,11 @@ // Environment private Environment MyEnvironment; - @Override public void create () { Random random = new Random(); - this.MyEnvironment = new SinglePlayEnvironment(TrainingParams.PathToBaseNN, random, TestMapIndex); + this.MyEnvironment = new Environment(TrainingParams.PathToBaseNN, random, 5); } @Override ```
```core/src/us/thirdmillenium/desktoptrainer/DesktopTrainer.java package us.thirdmillenium.desktoptrainer; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import us.thirdmillenium.desktoptrainer.environment.Environment; import java.util.Random; public class DesktopTrainer extends ApplicationAdapter { // Environment private Environment MyEnvironment; @Override public void create () { Random random = new Random(); this.MyEnvironment = new Environment(TrainingParams.PathToBaseNN, random, 5); } @Override public void render () { <|user_cursor_is_here|> this.MyEnvironment.simulate(Gdx.graphics.getDeltaTime()); } } ```
```core/src/us/thirdmillenium/desktoptrainer/DesktopTrainer.java package us.thirdmillenium.desktoptrainer; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import us.thirdmillenium.desktoptrainer.environment.Environment; import java.util.Random; public class DesktopTrainer extends ApplicationAdapter { // Environment private Environment MyEnvironment; @Override public void create () { Random random = new Random(); this.MyEnvironment = new Environment(TrainingParams.PathToBaseNN, random, 5); } @Override public void render () { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "simulate", "newName": "render"}} </|tool_call|> this.MyEnvironment.simulate(Gdx.graphics.getDeltaTime()); } } ```
User edited file: "src/test/ui/lint/lint-group-nonstandard-style.rs": ```diff @@ -13,7 +13,7 @@ fn CamelCase() {} //~ ERROR should have a snake -#[allow(bad_style)] +#[allow(nonstandard_style)] mod test { fn CamelCase() {} @@ -33,4 +33,4 @@ } } -fn main() {} +fn main() {} ``` User edited file: "src/test/ui/lint/lint-group-nonstandard-style.rs": ```diff @@ -17,7 +17,7 @@ mod test { fn CamelCase() {} - #[forbid(bad_style)] + #[forbid(nonstandard_style)] mod bad { fn CamelCase() {} //~ ERROR should have a snake ```
```src/test/ui/lint/lint-group-nonstandard-style.rs // Copyright 2014–2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(nonstandard_style)] #![allow(dead_code)] fn CamelCase() {} //~ ERROR should have a snake #[allow(nonstandard_style)] mod test { fn CamelCase() {} #[forbid(nonstandard_style)] mod bad { fn CamelCase() {} //~ ERROR should have a snake static bad: isize = 1; //~ ERROR should have an upper } mod warn { <|user_cursor_is_here|> #![warn(bad_style)] fn CamelCase() {} //~ WARN should have a snake struct snake_case; //~ WARN should have a camel } } fn main() {} ```
```src/test/ui/lint/lint-group-nonstandard-style.rs // Copyright 2014–2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(nonstandard_style)] #![allow(dead_code)] fn CamelCase() {} //~ ERROR should have a snake #[allow(nonstandard_style)] mod test { fn CamelCase() {} #[forbid(nonstandard_style)] mod bad { fn CamelCase() {} //~ ERROR should have a snake static bad: isize = 1; //~ ERROR should have an upper } mod warn { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "bad_style", "newName": "nonstandard_style"}} </|tool_call|> #![warn(bad_style)] fn CamelCase() {} //~ WARN should have a snake struct snake_case; //~ WARN should have a camel } } fn main() {} ```
User edited file: "service/opencv.py": ```diff @@ -11,7 +11,7 @@ img = cv2.imread(filename_in) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) th = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) - params = [cv2.cv.CV_IMWRITE_JPEG_QUALITY, 100] + params = [cv2.IMWRITE_JPEG_QUALITY, 100] cv2.imwrite(filename_out, th, params) @staticmethod ```
```service/opencv.py __author__ = 'paulo' import cv2 class OpenCVIntegration(object): @staticmethod def adaptive_threshold(filename_in, filename_out): img = cv2.imread(filename_in) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) th = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) params = [cv2.IMWRITE_JPEG_QUALITY, 100] cv2.imwrite(filename_out, th, params) @staticmethod def grayscale(filename_in, filename_out): img = cv2.imread(filename_in) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) <|user_cursor_is_here|> params = [cv2.cv.CV_IMWRITE_JPEG_QUALITY, 100] cv2.imwrite(filename_out, img, params) ```
```service/opencv.py __author__ = 'paulo' import cv2 class OpenCVIntegration(object): @staticmethod def adaptive_threshold(filename_in, filename_out): img = cv2.imread(filename_in) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) th = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) params = [cv2.IMWRITE_JPEG_QUALITY, 100] cv2.imwrite(filename_out, th, params) @staticmethod def grayscale(filename_in, filename_out): img = cv2.imread(filename_in) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "cv2.cv.CV_IMWRITE_JPEG_QUALITY", "newName": "cv2.IMWRITE_JPEG_QUALITY"}} </|tool_call|> params = [cv2.cv.CV_IMWRITE_JPEG_QUALITY, 100] cv2.imwrite(filename_out, img, params) ```
User edited file: "libra_node/src/main.rs": ```diff @@ -20,7 +20,7 @@ let thread = std::thread::current(); unsafe { signal_hook::register(*signal, move || { - term_clone.store(true, Ordering::Relaxed); + term_clone.store(true, Ordering::Release); thread.unpark(); }) .expect("failed to register signal handler"); @@ -41,4 +41,4 @@ while !term.load(Ordering::Relaxed) { std::thread::park(); } -} +} ```
```libra_node/src/main.rs // Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use executable_helpers::helpers::{ setup_executable, ARG_CONFIG_PATH, ARG_DISABLE_LOGGING, ARG_PEER_ID, }; use signal_hook; use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, }; fn register_signals(term: Arc<AtomicBool>) { for signal in &[ signal_hook::SIGTERM, signal_hook::SIGINT, signal_hook::SIGHUP, ] { let term_clone = Arc::clone(&term); let thread = std::thread::current(); unsafe { signal_hook::register(*signal, move || { term_clone.store(true, Ordering::Release); thread.unpark(); }) .expect("failed to register signal handler"); } } } fn main() { let (config, _logger, _args) = setup_executable( "Libra single node".to_string(), vec![ARG_PEER_ID, ARG_CONFIG_PATH, ARG_DISABLE_LOGGING], ); let (_ac_handle, _node_handle) = libra_node::main_node::setup_environment(&config); let term = Arc::new(AtomicBool::new(false)); register_signals(Arc::clone(&term)); <|user_cursor_is_here|> while !term.load(Ordering::Relaxed) { std::thread::park(); } } ```
```libra_node/src/main.rs // Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use executable_helpers::helpers::{ setup_executable, ARG_CONFIG_PATH, ARG_DISABLE_LOGGING, ARG_PEER_ID, }; use signal_hook; use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, }; fn register_signals(term: Arc<AtomicBool>) { for signal in &[ signal_hook::SIGTERM, signal_hook::SIGINT, signal_hook::SIGHUP, ] { let term_clone = Arc::clone(&term); let thread = std::thread::current(); unsafe { signal_hook::register(*signal, move || { term_clone.store(true, Ordering::Release); thread.unpark(); }) .expect("failed to register signal handler"); } } } fn main() { let (config, _logger, _args) = setup_executable( "Libra single node".to_string(), vec![ARG_PEER_ID, ARG_CONFIG_PATH, ARG_DISABLE_LOGGING], ); let (_ac_handle, _node_handle) = libra_node::main_node::setup_environment(&config); let term = Arc::new(AtomicBool::new(false)); register_signals(Arc::clone(&term)); <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Relaxed", "newName": "Acquire"}} </|tool_call|> while !term.load(Ordering::Relaxed) { std::thread::park(); } } ```
User edited file: "src/angular-bluebird-promises.js": ```diff @@ -2,6 +2,7 @@ var angular = require('angular'); var bluebird = require('bluebird'); +var MODULE_NAME = 'mwl.bluebird'; angular .module('mwl.bluebird', []) @@ -47,4 +48,4 @@ }); -module.exports = 'mwl.bluebird'; +module.exports = 'mwl.bluebird'; ``` User edited file: "src/angular-bluebird-promises.js": ```diff @@ -5,7 +5,7 @@ var MODULE_NAME = 'mwl.bluebird'; angular - .module('mwl.bluebird', []) + .module(MODULE_NAME, []) .constant('Bluebird', bluebird) .config(function($provide, Bluebird) { ```
```src/angular-bluebird-promises.js 'use strict'; var angular = require('angular'); var bluebird = require('bluebird'); var MODULE_NAME = 'mwl.bluebird'; angular .module(MODULE_NAME, []) .constant('Bluebird', bluebird) .config(function($provide, Bluebird) { //Make bluebird API compatible with angular's subset of $q //Adapted from: https://gist.github.com/petkaantonov/8363789 Bluebird.defer = function() { var b = Bluebird.pending(); b.resolve = angular.bind(b, b.fulfill); b.reject = angular.bind(b, b.reject); b.notify = angular.bind(b, b.progress); return b; }; Bluebird.reject = Bluebird.rejected; Bluebird.when = Bluebird.cast; var originalAll = Bluebird.all; Bluebird.all = function(promises) { if (angular.isObject(promises) && !angular.isArray(promises)) { return Bluebird.props(promises); } else { return originalAll.call(Bluebird, promises); } }; Bluebird.onPossiblyUnhandledRejection(angular.noop); $provide.decorator('$q', function() { return Bluebird; }); }).run(function($rootScope, Bluebird) { Bluebird.setScheduler(function(cb) { $rootScope.$evalAsync(cb); }); }); <|user_cursor_is_here|> module.exports = 'mwl.bluebird'; ```
```src/angular-bluebird-promises.js 'use strict'; var angular = require('angular'); var bluebird = require('bluebird'); var MODULE_NAME = 'mwl.bluebird'; angular .module(MODULE_NAME, []) .constant('Bluebird', bluebird) .config(function($provide, Bluebird) { //Make bluebird API compatible with angular's subset of $q //Adapted from: https://gist.github.com/petkaantonov/8363789 Bluebird.defer = function() { var b = Bluebird.pending(); b.resolve = angular.bind(b, b.fulfill); b.reject = angular.bind(b, b.reject); b.notify = angular.bind(b, b.progress); return b; }; Bluebird.reject = Bluebird.rejected; Bluebird.when = Bluebird.cast; var originalAll = Bluebird.all; Bluebird.all = function(promises) { if (angular.isObject(promises) && !angular.isArray(promises)) { return Bluebird.props(promises); } else { return originalAll.call(Bluebird, promises); } }; Bluebird.onPossiblyUnhandledRejection(angular.noop); $provide.decorator('$q', function() { return Bluebird; }); }).run(function($rootScope, Bluebird) { Bluebird.setScheduler(function(cb) { $rootScope.$evalAsync(cb); }); }); <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "'mwl.bluebird'", "newName": "MODULE_NAME"}} </|tool_call|> module.exports = 'mwl.bluebird'; ```
User edited file: "seax-svm/src/lib.rs": ```diff @@ -8,8 +8,8 @@ /// /// This is used internally to represent list primitives in the machine. pub enum List<T> { - Cons(T ~List<T>), - Nil + Nil, + Cons(T, List<T>) } /// Public implementation for List. @@ -28,4 +28,4 @@ struct Engine { stack: Vec<Exp> } -} +} ``` User edited file: "seax-svm/src/lib.rs": ```diff @@ -13,7 +13,7 @@ } /// Public implementation for List. - pub impl List<T> { + impl<T> List<T> { pub fn new() -> List<T> { Nil ``` User edited file: "seax-svm/src/lib.rs": ```diff @@ -15,7 +15,7 @@ /// Public implementation for List. impl<T> List<T> { - pub fn new() -> List<T> { + fn new() -> List<T> { Nil } ```
```seax-svm/src/lib.rs #[test] fn it_works() { } mod SVM { /// Singly-linked cons list. /// /// This is used internally to represent list primitives in the machine. pub enum List<T> { Nil, Cons(T, List<T>) } /// Public implementation for List. impl<T> List<T> { fn new() -> List<T> { Nil } } enum Exp { <|user_cursor_is_here|> Number(int) } struct Engine { stack: Vec<Exp> } } ```
```seax-svm/src/lib.rs #[test] fn it_works() { } mod SVM { /// Singly-linked cons list. /// /// This is used internally to represent list primitives in the machine. pub enum List<T> { Nil, Cons(T, List<T>) } /// Public implementation for List. impl<T> List<T> { fn new() -> List<T> { Nil } } enum Exp { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "int", "newName": "i32"}} </|tool_call|> Number(int) } struct Engine { stack: Vec<Exp> } } ```
User edited file: "ee-schkola_des/src/main/kotlin/ee/schkola/SchkolaGenerator.kt": ```diff @@ -1,6 +1,7 @@ package ee.schkola import ee.design.gen.go.DesignGoGenerator +import ee.design.gen.kt.DesignKotlinGenerator import ee.lang.integ.dPath fun main(args: Array<String>) { ```
```ee-schkola_des/src/main/kotlin/ee/schkola/SchkolaGenerator.kt package ee.schkola import ee.design.gen.go.DesignGoGenerator import ee.design.gen.kt.DesignKotlinGenerator import ee.lang.integ.dPath fun main(args: Array<String>) { <|user_cursor_is_here|> //val kotlinGenerator = DesignKotlinGenerator(Schkola) val goGenerator = DesignGoGenerator(Schkola) goGenerator.generate(dPath) //val typeScriptGenerator = DesignTypeScriptGenerator(Schkola) //typeScriptGenerator.generate(dPath) } ```
```ee-schkola_des/src/main/kotlin/ee/schkola/SchkolaGenerator.kt package ee.schkola import ee.design.gen.go.DesignGoGenerator import ee.design.gen.kt.DesignKotlinGenerator import ee.lang.integ.dPath fun main(args: Array<String>) { //val kotlinGenerator = DesignKotlinGenerator(Schkola) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "goGenerator", "newName": "generator"}} </|tool_call|> val goGenerator = DesignGoGenerator(Schkola) goGenerator.generate(dPath) //val typeScriptGenerator = DesignTypeScriptGenerator(Schkola) //typeScriptGenerator.generate(dPath) } ```
User edited file: "app/src/main/java/net/squanchy/support/font/TypefaceDelegate.kt": ```diff @@ -12,12 +12,12 @@ } fun applyTypefaceTo(paint: Paint) { - val fakeStyle = fakeStyle(paint) + val previousStyle = fakeStyle(paint) - if (bold(fakeStyle)) { + if (bold(previousStyle)) { paint.isFakeBoldText = true } - if (italic(fakeStyle)) { + if (italic(previousStyle)) { paint.textSkewX = TEXT_SKEW_X } @@ -32,4 +32,4 @@ val oldStyle = paint.typeface?.style ?: 0 return oldStyle.and(newTypeface.style.inv()) } -} +} ``` User edited file: "app/src/main/java/net/squanchy/support/font/TypefaceDelegate.kt": ```diff @@ -14,7 +14,7 @@ fun applyTypefaceTo(paint: Paint) { val previousStyle = fakeStyle(paint) - if (bold(previousStyle)) { + if (isBold(previousStyle)) { paint.isFakeBoldText = true } if (italic(previousStyle)) { @@ -24,7 +24,7 @@ paint.typeface = newTypeface } - private fun bold(fakeStyle: Int) = fakeStyle.and(Typeface.BOLD) != FALSE_FLAG + private fun isBold(fakeStyle: Int) = fakeStyle.and(Typeface.BOLD) != FALSE_FLAG private fun italic(fakeStyle: Int) = fakeStyle.and(Typeface.ITALIC) != FALSE_FLAG ``` User edited file: "app/src/main/java/net/squanchy/support/font/TypefaceDelegate.kt": ```diff @@ -17,7 +17,7 @@ if (isBold(previousStyle)) { paint.isFakeBoldText = true } - if (italic(previousStyle)) { + if (isItalic(previousStyle)) { paint.textSkewX = TEXT_SKEW_X } @@ -26,7 +26,7 @@ private fun isBold(fakeStyle: Int) = fakeStyle.and(Typeface.BOLD) != FALSE_FLAG - private fun italic(fakeStyle: Int) = fakeStyle.and(Typeface.ITALIC) != FALSE_FLAG + private fun isItalic(fakeStyle: Int) = fakeStyle.and(Typeface.ITALIC) != FALSE_FLAG private fun fakeStyle(paint: Paint): Int { val oldStyle = paint.typeface?.style ?: 0 ```
```app/src/main/java/net/squanchy/support/font/TypefaceDelegate.kt package net.squanchy.support.font import android.graphics.Paint import android.graphics.Typeface class TypefaceDelegate(private val newTypeface: Typeface) { private companion object { @SuppressWarnings("MagicNumber") const val TEXT_SKEW_X = -.25f const val FALSE_FLAG = 0 } fun applyTypefaceTo(paint: Paint) { <|user_cursor_is_here|> val previousStyle = fakeStyle(paint) if (isBold(previousStyle)) { paint.isFakeBoldText = true } if (isItalic(previousStyle)) { paint.textSkewX = TEXT_SKEW_X } paint.typeface = newTypeface } private fun isBold(fakeStyle: Int) = fakeStyle.and(Typeface.BOLD) != FALSE_FLAG private fun isItalic(fakeStyle: Int) = fakeStyle.and(Typeface.ITALIC) != FALSE_FLAG private fun fakeStyle(paint: Paint): Int { val oldStyle = paint.typeface?.style ?: 0 return oldStyle.and(newTypeface.style.inv()) } } ```
```app/src/main/java/net/squanchy/support/font/TypefaceDelegate.kt package net.squanchy.support.font import android.graphics.Paint import android.graphics.Typeface class TypefaceDelegate(private val newTypeface: Typeface) { private companion object { @SuppressWarnings("MagicNumber") const val TEXT_SKEW_X = -.25f const val FALSE_FLAG = 0 } fun applyTypefaceTo(paint: Paint) { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "fakeStyle", "newName": "computePreviousStyle"}} </|tool_call|> val previousStyle = fakeStyle(paint) if (isBold(previousStyle)) { paint.isFakeBoldText = true } if (isItalic(previousStyle)) { paint.textSkewX = TEXT_SKEW_X } paint.typeface = newTypeface } private fun isBold(fakeStyle: Int) = fakeStyle.and(Typeface.BOLD) != FALSE_FLAG private fun isItalic(fakeStyle: Int) = fakeStyle.and(Typeface.ITALIC) != FALSE_FLAG private fun fakeStyle(paint: Paint): Int { val oldStyle = paint.typeface?.style ?: 0 return oldStyle.and(newTypeface.style.inv()) } } ```
User edited file: "app/src/main/java/com/satsumasoftware/timetable/framework/Assignment.kt": ```diff @@ -1,5 +1,5 @@ package com.satsumasoftware.timetable.framework -import java.util.* +import org.threeten.bp.LocalDate -class Assignment(val id: Int, val title: String, val detail: String, val dueDate: Date) +class Assignment(val id: Int, val title: String, val detail: String, val dueDate: Date) ```
```app/src/main/java/com/satsumasoftware/timetable/framework/Assignment.kt package com.satsumasoftware.timetable.framework import org.threeten.bp.LocalDate <|user_cursor_is_here|> class Assignment(val id: Int, val title: String, val detail: String, val dueDate: Date) ```
```app/src/main/java/com/satsumasoftware/timetable/framework/Assignment.kt package com.satsumasoftware.timetable.framework import org.threeten.bp.LocalDate <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Date", "newName": "LocalDate"}} </|tool_call|> class Assignment(val id: Int, val title: String, val detail: String, val dueDate: Date) ```
User edited file: "acornui-core/src/commonMain/kotlin/com/acornui/core/UidUtil.kt": ```diff @@ -19,6 +19,7 @@ import com.acornui.core.time.time import com.acornui.string.toRadix import kotlin.math.abs +import kotlin.random.Random object UidUtil { ```
```acornui-core/src/commonMain/kotlin/com/acornui/core/UidUtil.kt /* * Copyright 2017 Nicholas Bilyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.core import com.acornui.core.time.time import com.acornui.string.toRadix import kotlin.math.abs import kotlin.random.Random object UidUtil { /** * Returns a unique id. */ fun createUid(): String { <|user_cursor_is_here|> return abs(time.nowMs().toInt()).toRadix(36) + (Math.random() * Int.MAX_VALUE).toInt().toRadix(36) } } ```
```acornui-core/src/commonMain/kotlin/com/acornui/core/UidUtil.kt /* * Copyright 2017 Nicholas Bilyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.core import com.acornui.core.time.time import com.acornui.string.toRadix import kotlin.math.abs import kotlin.random.Random object UidUtil { /** * Returns a unique id. */ fun createUid(): String { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Math.random", "newName": "Random.nextDouble"}} </|tool_call|> return abs(time.nowMs().toInt()).toRadix(36) + (Math.random() * Int.MAX_VALUE).toInt().toRadix(36) } } ```
User edited file: "src/index.js": ```diff @@ -1,8 +1,8 @@ (function () { /* jshint maxstatements: 1000 */ 'use strict'; -var basicParser; -basicParser = require('./parser.peg.js'); +var pegParser; +pegParser = require('./parser.peg.js'); /** * [newpage] @@ -54,4 +54,4 @@ }; module.exports = { Parser: Parser }; -}()); +}()); ```
```src/index.js (function () { /* jshint maxstatements: 1000 */ 'use strict'; var pegParser; pegParser = require('./parser.peg.js'); /** * [newpage] * [chapter:.*] * [pixivimage:\d*(-\d*)?] * [jump:\d*] * [[jumpuri:.* > URL]] * * [ruby: rb > rt] * [emoji:.*] * [strong:.*] */ function Parser() { this.tree = []; } /** * @param {string} novel * @return {Object.<string,Object>[]} */ Parser.parse = function (novel) { try { novel = novel.replace(/\r?\n/g, '\n'). replace(/[\s\u200c]/g, function (c) { if (c === '\n' || c === '\u3000') { return c; } return ' '; }); <|user_cursor_is_here|> return basicParser.parse(novel); } catch (err) { console.error(err); return [{ type: 'text', val: novel }]; } }; /** * @param {string} novel * @return {Parser} */ Parser.prototype.parse = function (novel) { this.tree = Parser.parse(novel); return this; }; /** * @return {string} */ Parser.prototype.toJSON = function () { return JSON.stringify(this.tree); }; module.exports = { Parser: Parser }; }()); ```
```src/index.js (function () { /* jshint maxstatements: 1000 */ 'use strict'; var pegParser; pegParser = require('./parser.peg.js'); /** * [newpage] * [chapter:.*] * [pixivimage:\d*(-\d*)?] * [jump:\d*] * [[jumpuri:.* > URL]] * * [ruby: rb > rt] * [emoji:.*] * [strong:.*] */ function Parser() { this.tree = []; } /** * @param {string} novel * @return {Object.<string,Object>[]} */ Parser.parse = function (novel) { try { novel = novel.replace(/\r?\n/g, '\n'). replace(/[\s\u200c]/g, function (c) { if (c === '\n' || c === '\u3000') { return c; } return ' '; }); <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "basicParser", "newName": "pegParser"}} </|tool_call|> return basicParser.parse(novel); } catch (err) { console.error(err); return [{ type: 'text', val: novel }]; } }; /** * @param {string} novel * @return {Parser} */ Parser.prototype.parse = function (novel) { this.tree = Parser.parse(novel); return this; }; /** * @return {string} */ Parser.prototype.toJSON = function () { return JSON.stringify(this.tree); }; module.exports = { Parser: Parser }; }()); ```
User edited file: "examples/test_markers.py": ```diff @@ -4,7 +4,7 @@ pytest -v -m marker_test_suite # Runs A, B, C, D pytest -v -m marker1 # Runs A pytest -v -m marker2 # Runs B, C - pytest -v -m xkcd_code # Runs C + pytest -v -m marker3 # Runs C pytest test_markers.py -v -m "not marker2" # Runs A, D (The "-v" will display the names of tests as they run.) @@ -36,4 +36,4 @@ def test_D(self): self.open("https://xkcd.com/2021/") - self.assert_text("Software Development", "div#ctitle") + self.assert_text("Software Development", "div#ctitle") ```
```examples/test_markers.py """ These tests demonstrate pytest marker use for finding and running tests. Usage examples from this file: pytest -v -m marker_test_suite # Runs A, B, C, D pytest -v -m marker1 # Runs A pytest -v -m marker2 # Runs B, C pytest -v -m marker3 # Runs C pytest test_markers.py -v -m "not marker2" # Runs A, D (The "-v" will display the names of tests as they run.) (Add "--collect-only" to display names of tests without running them.) """ import pytest from seleniumbase import BaseCase @pytest.mark.marker_test_suite class MarkerTestSuite(BaseCase): @pytest.mark.marker1 def test_A(self): self.open("https://xkcd.com/1319/") self.assert_text("Automation", "div#ctitle") @pytest.mark.marker2 def test_B(self): self.open("https://www.xkcd.com/1700/") self.assert_text("New Bug", "div#ctitle") @pytest.mark.marker2 <|user_cursor_is_here|> @pytest.mark.xkcd_code # Tests can have multiple markers def test_C(self): self.open("https://xkcd.com/844/") self.assert_text("Good Code", "div#ctitle") def test_D(self): self.open("https://xkcd.com/2021/") self.assert_text("Software Development", "div#ctitle") ```
```examples/test_markers.py """ These tests demonstrate pytest marker use for finding and running tests. Usage examples from this file: pytest -v -m marker_test_suite # Runs A, B, C, D pytest -v -m marker1 # Runs A pytest -v -m marker2 # Runs B, C pytest -v -m marker3 # Runs C pytest test_markers.py -v -m "not marker2" # Runs A, D (The "-v" will display the names of tests as they run.) (Add "--collect-only" to display names of tests without running them.) """ import pytest from seleniumbase import BaseCase @pytest.mark.marker_test_suite class MarkerTestSuite(BaseCase): @pytest.mark.marker1 def test_A(self): self.open("https://xkcd.com/1319/") self.assert_text("Automation", "div#ctitle") @pytest.mark.marker2 def test_B(self): self.open("https://www.xkcd.com/1700/") self.assert_text("New Bug", "div#ctitle") @pytest.mark.marker2 <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "xkcd_code", "newName": "marker3"}} </|tool_call|> @pytest.mark.xkcd_code # Tests can have multiple markers def test_C(self): self.open("https://xkcd.com/844/") self.assert_text("Good Code", "div#ctitle") def test_D(self): self.open("https://xkcd.com/2021/") self.assert_text("Software Development", "div#ctitle") ```
User edited file: "rxpalette-kotlin/src/main/kotlin/io/sweers/rxpalette/RxPalette.kt": ```diff @@ -7,7 +7,7 @@ /** * Generate the `Palette` synchronously. */ -public inline fun Palette.generate(bitmap: Bitmap): Observable<Palette> = RxPalette.generate(bitmap) +public inline fun Palette.asObservable(bitmap: Bitmap): Observable<Palette> = RxPalette.generate(bitmap) /** * Generate the `Palette` synchronously. @@ -22,4 +22,4 @@ /** * Generate the `Palette` asynchronously. */ -public inline fun Palette.Builder.generateAsync(): Observable<Palette> = RxPalette.generateAsync(this) +public inline fun Palette.Builder.generateAsync(): Observable<Palette> = RxPalette.generateAsync(this) ```
```rxpalette-kotlin/src/main/kotlin/io/sweers/rxpalette/RxPalette.kt package io.sweers.rxpalette import android.graphics.Bitmap import android.support.v7.graphics.Palette import rx.Observable /** * Generate the `Palette` synchronously. */ public inline fun Palette.asObservable(bitmap: Bitmap): Observable<Palette> = RxPalette.generate(bitmap) /** * Generate the `Palette` synchronously. */ <|user_cursor_is_here|> public inline fun Palette.Builder.generate(): Observable<Palette> = RxPalette.generate(this) /** * Generate the `Palette` asynchronously. */ public inline fun Palette.generateAsync(bitmap: Bitmap): Observable<Palette> = RxPalette.generateAsync(bitmap) /** * Generate the `Palette` asynchronously. */ public inline fun Palette.Builder.generateAsync(): Observable<Palette> = RxPalette.generateAsync(this) ```
```rxpalette-kotlin/src/main/kotlin/io/sweers/rxpalette/RxPalette.kt package io.sweers.rxpalette import android.graphics.Bitmap import android.support.v7.graphics.Palette import rx.Observable /** * Generate the `Palette` synchronously. */ public inline fun Palette.asObservable(bitmap: Bitmap): Observable<Palette> = RxPalette.generate(bitmap) /** * Generate the `Palette` synchronously. */ <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "generate", "newName": "asObservable"}} </|tool_call|> public inline fun Palette.Builder.generate(): Observable<Palette> = RxPalette.generate(this) /** * Generate the `Palette` asynchronously. */ public inline fun Palette.generateAsync(bitmap: Bitmap): Observable<Palette> = RxPalette.generateAsync(bitmap) /** * Generate the `Palette` asynchronously. */ public inline fun Palette.Builder.generateAsync(): Observable<Palette> = RxPalette.generateAsync(this) ```
User edited file: "tests/test.rs": ```diff @@ -8,7 +8,7 @@ #[test] fn test_scalar_types() { - fn check_type<T: TypeInfo>(ty: Type) { + fn check_scalar_type<T: TypeInfo>(ty: Type) { assert_eq!(<T as TypeInfo>::type_info(), ty); assert_eq!(ty.size(), mem::size_of::<T>()); } @@ -27,4 +27,4 @@ check_type::<bool>(Bool); check_type::<char>(Char); -} +} ``` User edited file: "tests/test.rs": ```diff @@ -11,6 +11,7 @@ fn check_scalar_type<T: TypeInfo>(ty: Type) { assert_eq!(<T as TypeInfo>::type_info(), ty); assert_eq!(ty.size(), mem::size_of::<T>()); + assert!(ty.is_scalar() && !ty.is_array() && !ty.is_compound()); } check_type::<i8>(Int8); check_type::<i16>(Int16); ```
```tests/test.rs #[macro_use] extern crate pod_typeinfo; use std::mem; use pod_typeinfo::Type::*; use pod_typeinfo::{Type, TypeInfo}; #[test] fn test_scalar_types() { fn check_scalar_type<T: TypeInfo>(ty: Type) { assert_eq!(<T as TypeInfo>::type_info(), ty); assert_eq!(ty.size(), mem::size_of::<T>()); assert!(ty.is_scalar() && !ty.is_array() && !ty.is_compound()); } <|user_cursor_is_here|> check_type::<i8>(Int8); check_type::<i16>(Int16); check_type::<i32>(Int32); check_type::<i64>(Int64); check_type::<u8>(UInt8); check_type::<u16>(UInt16); check_type::<u32>(UInt32); check_type::<u64>(UInt64); check_type::<isize>(ISize); check_type::<usize>(USize); check_type::<f32>(Float32); check_type::<f64>(Float64); check_type::<bool>(Bool); check_type::<char>(Char); } ```
```tests/test.rs #[macro_use] extern crate pod_typeinfo; use std::mem; use pod_typeinfo::Type::*; use pod_typeinfo::{Type, TypeInfo}; #[test] fn test_scalar_types() { fn check_scalar_type<T: TypeInfo>(ty: Type) { assert_eq!(<T as TypeInfo>::type_info(), ty); assert_eq!(ty.size(), mem::size_of::<T>()); assert!(ty.is_scalar() && !ty.is_array() && !ty.is_compound()); } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "check_type", "newName": "check_scalar_type"}} </|tool_call|> check_type::<i8>(Int8); check_type::<i16>(Int16); check_type::<i32>(Int32); check_type::<i64>(Int64); check_type::<u8>(UInt8); check_type::<u16>(UInt16); check_type::<u32>(UInt32); check_type::<u64>(UInt64); check_type::<isize>(ISize); check_type::<usize>(USize); check_type::<f32>(Float32); check_type::<f64>(Float64); check_type::<bool>(Bool); check_type::<char>(Char); } ```
User edited file: "rust/rotational-cipher/src/lib.rs": ```diff @@ -2,6 +2,8 @@ use std::ascii::AsciiExt; pub fn rotate(text: &str, key: usize) -> String { + const LA: u8 = b'a'; + const UA: u8 = b'A'; text.chars() .map(|x| match x { _ if x.is_ascii_lowercase() => { @@ -15,4 +17,4 @@ _ => x, }) .collect() -} +} ``` User edited file: "rust/rotational-cipher/src/lib.rs": ```diff @@ -7,7 +7,7 @@ text.chars() .map(|x| match x { _ if x.is_ascii_lowercase() => { - let v = (x as u8 - b'a' + key as u8) % 26 + b'a'; + let v = (x as u8 - LA + key as u8) % 26 + LA; v as char } _ if x.is_ascii_uppercase() => { ```
```rust/rotational-cipher/src/lib.rs #![feature(ascii_ctype)] use std::ascii::AsciiExt; pub fn rotate(text: &str, key: usize) -> String { const LA: u8 = b'a'; const UA: u8 = b'A'; text.chars() .map(|x| match x { _ if x.is_ascii_lowercase() => { let v = (x as u8 - LA + key as u8) % 26 + LA; v as char } _ if x.is_ascii_uppercase() => { <|user_cursor_is_here|> let v = (x as u8 - b'A' + key as u8) % 26 + b'A'; v as char } _ => x, }) .collect() } ```
```rust/rotational-cipher/src/lib.rs #![feature(ascii_ctype)] use std::ascii::AsciiExt; pub fn rotate(text: &str, key: usize) -> String { const LA: u8 = b'a'; const UA: u8 = b'A'; text.chars() .map(|x| match x { _ if x.is_ascii_lowercase() => { let v = (x as u8 - LA + key as u8) % 26 + LA; v as char } _ if x.is_ascii_uppercase() => { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "b'A'", "newName": "UA"}} </|tool_call|> let v = (x as u8 - b'A' + key as u8) % 26 + b'A'; v as char } _ => x, }) .collect() } ```
User edited file: "django_evolution/__init__.py": ```diff @@ -40,6 +40,8 @@ if VERSION[2]: version += ".%s" % VERSION[2] + tag = VERSION[3] + if VERSION[3] != 'final': version += '%s%s' % (VERSION[3], VERSION[4]) @@ -51,4 +53,4 @@ __version_info__ = VERSION[:-1] -__version__ = get_package_version() +__version__ = get_package_version() ``` User edited file: "django_evolution/__init__.py": ```diff @@ -42,7 +42,12 @@ tag = VERSION[3] - if VERSION[3] != 'final': + if tag != 'final': + if tag == 'alpha': + tag = 'a' + elif tag == 'beta': + tag = 'b' + version += '%s%s' % (VERSION[3], VERSION[4]) return version ```
```django_evolution/__init__.py """Django Evolution version and package information. These variables and functions can be used to identify the version of Review Board. They're largely used for packaging purposes. """ from __future__ import unicode_literals # The version of Django Evolution # # This is in the format of: # # (Major, Minor, Micro, alpha/beta/rc/final, Release Number, Released) # VERSION = (2, 1, 0, 'alpha', 0, False) def get_version_string(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': if VERSION[3] == 'rc': version += ' RC%s' % VERSION[4] else: version += ' %s %s' % (VERSION[3], VERSION[4]) if not is_release(): version += " (dev)" return version def get_package_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] tag = VERSION[3] if tag != 'final': if tag == 'alpha': tag = 'a' elif tag == 'beta': tag = 'b' <|user_cursor_is_here|> version += '%s%s' % (VERSION[3], VERSION[4]) return version def is_release(): return VERSION[5] __version_info__ = VERSION[:-1] __version__ = get_package_version() ```
```django_evolution/__init__.py """Django Evolution version and package information. These variables and functions can be used to identify the version of Review Board. They're largely used for packaging purposes. """ from __future__ import unicode_literals # The version of Django Evolution # # This is in the format of: # # (Major, Minor, Micro, alpha/beta/rc/final, Release Number, Released) # VERSION = (2, 1, 0, 'alpha', 0, False) def get_version_string(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] if VERSION[3] != 'final': if VERSION[3] == 'rc': version += ' RC%s' % VERSION[4] else: version += ' %s %s' % (VERSION[3], VERSION[4]) if not is_release(): version += " (dev)" return version def get_package_version(): version = '%s.%s' % (VERSION[0], VERSION[1]) if VERSION[2]: version += ".%s" % VERSION[2] tag = VERSION[3] if tag != 'final': if tag == 'alpha': tag = 'a' elif tag == 'beta': tag = 'b' <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "VERSION[3]", "newName": "tag"}} </|tool_call|> version += '%s%s' % (VERSION[3], VERSION[4]) return version def is_release(): return VERSION[5] __version_info__ = VERSION[:-1] __version__ = get_package_version() ```
User edited file: "app/modules/weather/weather.sagas.js": ```diff @@ -1,4 +1,4 @@ -import { call, put, takeLatest } from 'redux-saga/effects'; +import { call, put, takeLatest, select } from 'redux-saga/effects'; import envConfig from 'env-config'; import { WeatherActions, WeatherTypes } from './weather.redux'; @@ -23,4 +23,4 @@ yield [ yield takeLatest(WeatherTypes.GET_WEATHER, getWeatherSaga), ]; -} +} ``` User edited file: "app/modules/weather/weather.sagas.js": ```diff @@ -2,6 +2,8 @@ import envConfig from 'env-config'; import { WeatherActions, WeatherTypes } from './weather.redux'; +import { MapTypes } from '../map/map.redux'; +import { selectPosition } from '../map/map.selectors'; import { get } from '../api/api.sagas'; ``` User edited file: "app/modules/weather/weather.sagas.js": ```diff @@ -1,7 +1,7 @@ import { call, put, takeLatest, select } from 'redux-saga/effects'; import envConfig from 'env-config'; -import { WeatherActions, WeatherTypes } from './weather.redux'; +import { WeatherActions } from './weather.redux'; import { MapTypes } from '../map/map.redux'; import { selectPosition } from '../map/map.selectors'; import { get } from '../api/api.sagas'; ``` User edited file: "app/modules/weather/weather.sagas.js": ```diff @@ -7,11 +7,12 @@ import { get } from '../api/api.sagas'; -export function* getWeatherSaga({ latitude, longitude }) { +export function* getWeatherSaga() { try { + const position = yield select(selectPosition); const data = yield call(get, 'api/openweathermap/', { - 'lat': latitude, - 'lon': longitude, + 'lat': position.get('lat'), + 'lon': position.get('long'), 'appid': envConfig.openweathermap.apiKey, }); ```
```app/modules/weather/weather.sagas.js import { call, put, takeLatest, select } from 'redux-saga/effects'; import envConfig from 'env-config'; import { WeatherActions } from './weather.redux'; import { MapTypes } from '../map/map.redux'; import { selectPosition } from '../map/map.selectors'; import { get } from '../api/api.sagas'; export function* getWeatherSaga() { try { const position = yield select(selectPosition); const data = yield call(get, 'api/openweathermap/', { 'lat': position.get('lat'), 'lon': position.get('long'), 'appid': envConfig.openweathermap.apiKey, }); yield put(WeatherActions.getWeatherSuccess(data)); } catch (e) { yield put(WeatherActions.getWeatherFailure(e)); } } export default function* weatherSaga() { yield [ <|user_cursor_is_here|> yield takeLatest(WeatherTypes.GET_WEATHER, getWeatherSaga), ]; } ```
```app/modules/weather/weather.sagas.js import { call, put, takeLatest, select } from 'redux-saga/effects'; import envConfig from 'env-config'; import { WeatherActions } from './weather.redux'; import { MapTypes } from '../map/map.redux'; import { selectPosition } from '../map/map.selectors'; import { get } from '../api/api.sagas'; export function* getWeatherSaga() { try { const position = yield select(selectPosition); const data = yield call(get, 'api/openweathermap/', { 'lat': position.get('lat'), 'lon': position.get('long'), 'appid': envConfig.openweathermap.apiKey, }); yield put(WeatherActions.getWeatherSuccess(data)); } catch (e) { yield put(WeatherActions.getWeatherFailure(e)); } } export default function* weatherSaga() { yield [ <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "WeatherTypes.GET_WEATHER", "newName": "MapTypes.CHANGE_POSITION"}} </|tool_call|> yield takeLatest(WeatherTypes.GET_WEATHER, getWeatherSaga), ]; } ```
User edited file: "src/kotlin/com/kotlinnlp/simplednn/simplemath/simplemath.kt": ```diff @@ -8,7 +8,6 @@ package com.kotlinnlp.simplednn.simplemath import com.kotlinnlp.simplednn.simplemath.ndarray.Shape -import com.kotlinnlp.simplednn.simplemath.ndarray.wrapper.JBlasArray typealias NDArray = JBlasArray @@ -41,4 +40,4 @@ return array -} +} ``` User edited file: "src/kotlin/com/kotlinnlp/simplednn/simplemath/simplemath.kt": ```diff @@ -7,6 +7,8 @@ package com.kotlinnlp.simplednn.simplemath +import com.kotlinnlp.simplednn.simplemath.ndarray.DenseNDArray +import com.kotlinnlp.simplednn.simplemath.ndarray.NDArrayFactory import com.kotlinnlp.simplednn.simplemath.ndarray.Shape typealias NDArray = JBlasArray ``` User edited file: "src/kotlin/com/kotlinnlp/simplednn/simplemath/simplemath.kt": ```diff @@ -10,8 +10,6 @@ import com.kotlinnlp.simplednn.simplemath.ndarray.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.NDArrayFactory import com.kotlinnlp.simplednn.simplemath.ndarray.Shape - -typealias NDArray = JBlasArray /** * @param a a [Double] number ```
```src/kotlin/com/kotlinnlp/simplednn/simplemath/simplemath.kt /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.simplemath import com.kotlinnlp.simplednn.simplemath.ndarray.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.NDArrayFactory import com.kotlinnlp.simplednn.simplemath.ndarray.Shape /** * @param a a [Double] number * @param b a [Double] number * @param tolerance it defines the range [[b] - [tolerance], [b] + [tolerance]] * * @return a [Boolean] which indicates if [a] is within the range of [b] with [tolerance] */ fun equals(a: Double, b: Double, tolerance: Double = 10e-4): Boolean { val lower = b - tolerance val upper = b + tolerance return a in lower..upper } <|user_cursor_is_here|> fun concatVectorsV(vararg vectors: NDArray): NDArray { require(vectors.all { it.isVector && it.columns == 1 }) val array = NDArray.zeros(Shape(vectors.sumBy { it.length })) var i = 0 vectors.forEach { (0 until it.length).forEach { j -> array[i++] = it[j] } } return array } ```
```src/kotlin/com/kotlinnlp/simplednn/simplemath/simplemath.kt /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.simplemath import com.kotlinnlp.simplednn.simplemath.ndarray.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.NDArrayFactory import com.kotlinnlp.simplednn.simplemath.ndarray.Shape /** * @param a a [Double] number * @param b a [Double] number * @param tolerance it defines the range [[b] - [tolerance], [b] + [tolerance]] * * @return a [Boolean] which indicates if [a] is within the range of [b] with [tolerance] */ fun equals(a: Double, b: Double, tolerance: Double = 10e-4): Boolean { val lower = b - tolerance val upper = b + tolerance return a in lower..upper } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "NDArray", "newName": "DenseNDArray"}} </|tool_call|> fun concatVectorsV(vararg vectors: NDArray): NDArray { require(vectors.all { it.isVector && it.columns == 1 }) val array = NDArray.zeros(Shape(vectors.sumBy { it.length })) var i = 0 vectors.forEach { (0 until it.length).forEach { j -> array[i++] = it[j] } } return array } ```
User edited file: "serde_macros/tests/compile-fail/reject-unknown-attributes.rs": ```diff @@ -5,7 +5,7 @@ #[derive(Serialize)] #[serde(abc="xyz")] //~ unknown serde container attribute `abc = "xyz"` -struct Foo { +struct A { x: u32, } @@ -27,4 +27,4 @@ x: u32, } -fn main() { } +fn main() { } ``` User edited file: "serde_macros/tests/compile-fail/reject-unknown-attributes.rs": ```diff @@ -11,7 +11,7 @@ #[derive(Deserialize)] #[serde(abc="xyz")] //~ unknown serde container attribute `abc = "xyz"` -struct Foo { +struct B { x: u32, } ``` User edited file: "serde_macros/tests/compile-fail/reject-unknown-attributes.rs": ```diff @@ -16,7 +16,7 @@ } #[derive(Serialize)] -struct Foo { +struct C { #[serde(abc="xyz")] //~ unknown serde field attribute `abc = "xyz"` x: u32, } ```
```serde_macros/tests/compile-fail/reject-unknown-attributes.rs #![feature(custom_attribute, custom_derive, plugin)] #![plugin(serde_macros)] extern crate serde; #[derive(Serialize)] #[serde(abc="xyz")] //~ unknown serde container attribute `abc = "xyz"` struct A { x: u32, } #[derive(Deserialize)] #[serde(abc="xyz")] //~ unknown serde container attribute `abc = "xyz"` struct B { x: u32, } #[derive(Serialize)] struct C { #[serde(abc="xyz")] //~ unknown serde field attribute `abc = "xyz"` x: u32, } #[derive(Deserialize)] <|user_cursor_is_here|> struct Foo { #[serde(abc="xyz")] //~ unknown serde field attribute `abc = "xyz"` x: u32, } fn main() { } ```
```serde_macros/tests/compile-fail/reject-unknown-attributes.rs #![feature(custom_attribute, custom_derive, plugin)] #![plugin(serde_macros)] extern crate serde; #[derive(Serialize)] #[serde(abc="xyz")] //~ unknown serde container attribute `abc = "xyz"` struct A { x: u32, } #[derive(Deserialize)] #[serde(abc="xyz")] //~ unknown serde container attribute `abc = "xyz"` struct B { x: u32, } #[derive(Serialize)] struct C { #[serde(abc="xyz")] //~ unknown serde field attribute `abc = "xyz"` x: u32, } #[derive(Deserialize)] <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Foo", "newName": "D"}} </|tool_call|> struct Foo { #[serde(abc="xyz")] //~ unknown serde field attribute `abc = "xyz"` x: u32, } fn main() { } ```
User edited file: "detekt-test/src/main/kotlin/io/gitlab/arturbosch/detekt/test/Resources.kt": ```diff @@ -13,6 +13,4 @@ return resource.toURI() } -fun resourcePath(name: String): String = resource(name).path - fun resourceAsString(name: String): String = String(Files.readAllBytes(Paths.get(resourcePath(name)))) ```
```detekt-test/src/main/kotlin/io/gitlab/arturbosch/detekt/test/Resources.kt package io.gitlab.arturbosch.detekt.test import java.net.URI import java.nio.file.Files import java.nio.file.Paths internal object Resources fun resource(name: String): URI { val explicitName = if (name.startsWith("/")) name else "/$name" val resource = Resources::class.java.getResource(explicitName) requireNotNull(resource) { "Make sure the resource '$name' exists!" } return resource.toURI() } <|user_cursor_is_here|> fun resourceAsString(name: String): String = String(Files.readAllBytes(Paths.get(resourcePath(name)))) ```
```detekt-test/src/main/kotlin/io/gitlab/arturbosch/detekt/test/Resources.kt package io.gitlab.arturbosch.detekt.test import java.net.URI import java.nio.file.Files import java.nio.file.Paths internal object Resources fun resource(name: String): URI { val explicitName = if (name.startsWith("/")) name else "/$name" val resource = Resources::class.java.getResource(explicitName) requireNotNull(resource) { "Make sure the resource '$name' exists!" } return resource.toURI() } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "resourcePath", "newName": "resource"}} </|tool_call|> fun resourceAsString(name: String): String = String(Files.readAllBytes(Paths.get(resourcePath(name)))) ```
User edited file: "app/src/test/java/com/doctoror/particleswallpaper/data/config/SceneConfiguratorImplTest.kt": ```diff @@ -16,7 +16,7 @@ package com.doctoror.particleswallpaper.data.config import com.doctoror.particlesdrawable.ParticlesScene -import com.doctoror.particleswallpaper.data.execution.ComputationSchedulers +import com.doctoror.particleswallpaper.data.execution.TrampolineSchedulers import com.doctoror.particleswallpaper.data.repository.MockSettingsRepositoryFactory import org.junit.Assert.* import org.junit.Test ```
```app/src/test/java/com/doctoror/particleswallpaper/data/config/SceneConfiguratorImplTest.kt /* * Copyright (C) 2017 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.particleswallpaper.data.config import com.doctoror.particlesdrawable.ParticlesScene import com.doctoror.particleswallpaper.data.execution.TrampolineSchedulers import com.doctoror.particleswallpaper.data.repository.MockSettingsRepositoryFactory import org.junit.Assert.* import org.junit.Test import org.mockito.Mockito.* class SceneConfiguratorImplTest { @Test fun testSubscription() { <|user_cursor_is_here|> val c = SceneConfiguratorImpl(ComputationSchedulers()) assertNull(c.disposables) c.subscribe(mock(ParticlesScene::class.java), MockSettingsRepositoryFactory.create()) assertNotNull(c.disposables) assertFalse(c.disposables!!.isDisposed) val disposables = c.disposables c.dispose() assertTrue(disposables!!.isDisposed) assertNull(c.disposables) } } ```
```app/src/test/java/com/doctoror/particleswallpaper/data/config/SceneConfiguratorImplTest.kt /* * Copyright (C) 2017 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.particleswallpaper.data.config import com.doctoror.particlesdrawable.ParticlesScene import com.doctoror.particleswallpaper.data.execution.TrampolineSchedulers import com.doctoror.particleswallpaper.data.repository.MockSettingsRepositoryFactory import org.junit.Assert.* import org.junit.Test import org.mockito.Mockito.* class SceneConfiguratorImplTest { @Test fun testSubscription() { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "ComputationSchedulers", "newName": "TrampolineSchedulers"}} </|tool_call|> val c = SceneConfiguratorImpl(ComputationSchedulers()) assertNull(c.disposables) c.subscribe(mock(ParticlesScene::class.java), MockSettingsRepositoryFactory.create()) assertNotNull(c.disposables) assertFalse(c.disposables!!.isDisposed) val disposables = c.disposables c.dispose() assertTrue(disposables!!.isDisposed) assertNull(c.disposables) } } ```
User edited file: "src/main/java/li/cil/oc/example/architecture/ModExampleArchitecture.java": ```diff @@ -13,8 +13,8 @@ * specific parts. It is not intended for use or distribution, but you're free * to base a proper addon on this code. */ -@Mod(modid = "OpenComputers|ExampleTileEntity", - name = "OpenComputers Addon Example - TileEntity", +@Mod(modid = "OpenComputers|ExampleArchitecture", + name = "OpenComputers Addon Example - Architecture", version = "1.0.0", dependencies = "required-after:OpenComputers@[1.2.0,)") public class ModExampleTileEntity { @@ -25,4 +25,4 @@ public void preInit(FMLPreInitializationEvent e) { li.cil.oc.api.Machine.add(PseudoArchitecture.class); } -} +} ``` User edited file: "src/main/java/li/cil/oc/example/architecture/ModExampleArchitecture.java": ```diff @@ -16,7 +16,7 @@ @Mod(modid = "OpenComputers|ExampleArchitecture", name = "OpenComputers Addon Example - Architecture", version = "1.0.0", - dependencies = "required-after:OpenComputers@[1.2.0,)") + dependencies = "required-after:OpenComputers@[1.4.0,)") public class ModExampleTileEntity { @Mod.Instance public static ModExampleTileEntity instance; ```
```src/main/java/li/cil/oc/example/architecture/ModExampleArchitecture.java package li.cil.oc.example.architecture; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; /** * This mod demonstrates how to create tile entities that are treated as * components by OpenComputers, i.e. tile entities that provide methods which * can be called from a program running on a computer. * <p/> * The mod tries to keep everything else to a minimum, to focus on the mod- * specific parts. It is not intended for use or distribution, but you're free * to base a proper addon on this code. */ @Mod(modid = "OpenComputers|ExampleArchitecture", name = "OpenComputers Addon Example - Architecture", version = "1.0.0", dependencies = "required-after:OpenComputers@[1.4.0,)") <|user_cursor_is_here|> public class ModExampleTileEntity { @Mod.Instance public static ModExampleTileEntity instance; @Mod.EventHandler public void preInit(FMLPreInitializationEvent e) { li.cil.oc.api.Machine.add(PseudoArchitecture.class); } } ```
```src/main/java/li/cil/oc/example/architecture/ModExampleArchitecture.java package li.cil.oc.example.architecture; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; /** * This mod demonstrates how to create tile entities that are treated as * components by OpenComputers, i.e. tile entities that provide methods which * can be called from a program running on a computer. * <p/> * The mod tries to keep everything else to a minimum, to focus on the mod- * specific parts. It is not intended for use or distribution, but you're free * to base a proper addon on this code. */ @Mod(modid = "OpenComputers|ExampleArchitecture", name = "OpenComputers Addon Example - Architecture", version = "1.0.0", dependencies = "required-after:OpenComputers@[1.4.0,)") <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "ModExampleTileEntity", "newName": "ModExampleArchitecture"}} </|tool_call|> public class ModExampleTileEntity { @Mod.Instance public static ModExampleTileEntity instance; @Mod.EventHandler public void preInit(FMLPreInitializationEvent e) { li.cil.oc.api.Machine.add(PseudoArchitecture.class); } } ```
User edited file: "src/main/java/com/suse/saltstack/netapi/datatypes/Event.java": ```diff @@ -1,6 +1,6 @@ package com.suse.saltstack.netapi.datatypes; -import java.util.HashMap; +import java.util.Map; /** * Parse events into objects. @@ -25,4 +25,4 @@ public HashMap<String, Object> getData() { return data; } -} +} ``` User edited file: "src/main/java/com/suse/saltstack/netapi/datatypes/Event.java": ```diff @@ -8,7 +8,7 @@ public class Event { private String tag; - private HashMap<String, Object> data; + private Map<String, Object> data; /** * Return this event's tag. ```
```src/main/java/com/suse/saltstack/netapi/datatypes/Event.java package com.suse.saltstack.netapi.datatypes; import java.util.Map; /** * Parse events into objects. */ public class Event { private String tag; private Map<String, Object> data; /** * Return this event's tag. * @return the tag */ public String getTag() { return tag; } /** * Return this event's data. * @return the data */ <|user_cursor_is_here|> public HashMap<String, Object> getData() { return data; } } ```
```src/main/java/com/suse/saltstack/netapi/datatypes/Event.java package com.suse.saltstack.netapi.datatypes; import java.util.Map; /** * Parse events into objects. */ public class Event { private String tag; private Map<String, Object> data; /** * Return this event's tag. * @return the tag */ public String getTag() { return tag; } /** * Return this event's data. * @return the data */ <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "HashMap", "newName": "Map"}} </|tool_call|> public HashMap<String, Object> getData() { return data; } } ```
User edited file: "app/src/main/kotlin/com/github/ramonrabello/kiphy/trends/TrendingEndpoint.kt": ```diff @@ -1,6 +1,6 @@ package com.github.ramonrabello.kiphy.trends -import com.github.ramonrabello.kiphy.data.model.Trending +import com.github.ramonrabello.kiphy.trends.model.TrendingResponse import retrofit2.Call import retrofit2.http.GET ```
```app/src/main/kotlin/com/github/ramonrabello/kiphy/trends/TrendingEndpoint.kt package com.github.ramonrabello.kiphy.trends import com.github.ramonrabello.kiphy.trends.model.TrendingResponse import retrofit2.Call import retrofit2.http.GET /** * Retrofit interface for Trending API endpoint. */ interface TrendingEndpoint { @GET("/v1/gifs/trending") <|user_cursor_is_here|> fun load(): Call<Trending> } ```
```app/src/main/kotlin/com/github/ramonrabello/kiphy/trends/TrendingEndpoint.kt package com.github.ramonrabello.kiphy.trends import com.github.ramonrabello.kiphy.trends.model.TrendingResponse import retrofit2.Call import retrofit2.http.GET /** * Retrofit interface for Trending API endpoint. */ interface TrendingEndpoint { @GET("/v1/gifs/trending") <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "Trending", "newName": "TrendingResponse"}} </|tool_call|> fun load(): Call<Trending> } ```
User edited file: "app/src/main/java/jp/toastkid/yobidashi/main/StartUp.kt": ```diff @@ -26,7 +26,7 @@ return valueOf(name) } - private fun getDefault(): StartUp = START + private fun getDefault(): StartUp = BROWSER fun findById(@IdRes checkedRadioButtonId: Int): StartUp = values().find { it.radioButtonId == checkedRadioButtonId } ?: START ```
```app/src/main/java/jp/toastkid/yobidashi/main/StartUp.kt package jp.toastkid.yobidashi.main import android.support.annotation.IdRes import android.support.annotation.StringRes import jp.toastkid.yobidashi.R /** * Start-up view definition. * * @param titleId * @param radioButtonId * * @author toastkidjp */ enum class StartUp(@StringRes val titleId: Int, @IdRes val radioButtonId: Int) { START(R.string.title_startup_start, R.id.start_up_start), SEARCH(R.string.title_search, R.id.start_up_search), BROWSER(R.string.title_browser, R.id.start_up_browser), APPS_LAUNCHER(R.string.title_apps_launcher, R.id.start_up_launcher); companion object { fun find(name: String): StartUp { if (name.isEmpty()) { return getDefault() } return valueOf(name) } private fun getDefault(): StartUp = BROWSER fun findById(@IdRes checkedRadioButtonId: Int): StartUp = <|user_cursor_is_here|> values().find { it.radioButtonId == checkedRadioButtonId } ?: START } } ```
```app/src/main/java/jp/toastkid/yobidashi/main/StartUp.kt package jp.toastkid.yobidashi.main import android.support.annotation.IdRes import android.support.annotation.StringRes import jp.toastkid.yobidashi.R /** * Start-up view definition. * * @param titleId * @param radioButtonId * * @author toastkidjp */ enum class StartUp(@StringRes val titleId: Int, @IdRes val radioButtonId: Int) { START(R.string.title_startup_start, R.id.start_up_start), SEARCH(R.string.title_search, R.id.start_up_search), BROWSER(R.string.title_browser, R.id.start_up_browser), APPS_LAUNCHER(R.string.title_apps_launcher, R.id.start_up_launcher); companion object { fun find(name: String): StartUp { if (name.isEmpty()) { return getDefault() } return valueOf(name) } private fun getDefault(): StartUp = BROWSER fun findById(@IdRes checkedRadioButtonId: Int): StartUp = <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "START", "newName": "getDefault()"}} </|tool_call|> values().find { it.radioButtonId == checkedRadioButtonId } ?: START } } ```
User edited file: "linkatos/activities.py": ```diff @@ -14,6 +14,10 @@ def is_reaction(index): return index is not None + + +def remove_url_from(url_cache_list, index): + url_cache_list.pop(index) def event_consumer(expecting_url, url_cache_list, slack_client, @@ -44,4 +48,4 @@ fb_credentials, firebase) remove_url_from(url_cache_list) - return (expecting_url, url_cache) + return (expecting_url, url_cache) ``` User edited file: "linkatos/activities.py": ```diff @@ -46,6 +46,6 @@ if is_reaction(index): react.handle(reaction['reaction'], url_cache_list[index]['url'], fb_credentials, firebase) - remove_url_from(url_cache_list) + remove_url_from(url_cache_list, index) return (expecting_url, url_cache) ```
```linkatos/activities.py from . import parser from . import printer from . import firebase as fb from . import reaction as react def is_empty(events): return ((events is None) or (len(events) == 0)) def is_url(url_cache): return url_cache is not None def is_reaction(index): return index is not None def remove_url_from(url_cache_list, index): url_cache_list.pop(index) def event_consumer(expecting_url, url_cache_list, slack_client, fb_credentials, firebase): # Read slack events events = slack_client.rtm_read() if is_empty(events): <|user_cursor_is_here|> return (expecting_url, url_cache) for event in events: print(event) if expecting_url and event['type'] == 'message': new_url_cache = parser.parse_url_message(event) url_cache_list.append(new_url_cache) if is_url(new_url_cache): printer.ask_confirmation(new_url_cache, slack_client) if event['type'] == 'reaction_added': reaction = parser.parse_reaction_added(event) index = react.is_confirmation(reaction['reaction'], url_cache_list, reaction['to_id']): if is_reaction(index): react.handle(reaction['reaction'], url_cache_list[index]['url'], fb_credentials, firebase) remove_url_from(url_cache_list, index) return (expecting_url, url_cache) ```
```linkatos/activities.py from . import parser from . import printer from . import firebase as fb from . import reaction as react def is_empty(events): return ((events is None) or (len(events) == 0)) def is_url(url_cache): return url_cache is not None def is_reaction(index): return index is not None def remove_url_from(url_cache_list, index): url_cache_list.pop(index) def event_consumer(expecting_url, url_cache_list, slack_client, fb_credentials, firebase): # Read slack events events = slack_client.rtm_read() if is_empty(events): <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "url_cache", "newName": "url_cache_list"}} </|tool_call|> return (expecting_url, url_cache) for event in events: print(event) if expecting_url and event['type'] == 'message': new_url_cache = parser.parse_url_message(event) url_cache_list.append(new_url_cache) if is_url(new_url_cache): printer.ask_confirmation(new_url_cache, slack_client) if event['type'] == 'reaction_added': reaction = parser.parse_reaction_added(event) index = react.is_confirmation(reaction['reaction'], url_cache_list, reaction['to_id']): if is_reaction(index): react.handle(reaction['reaction'], url_cache_list[index]['url'], fb_credentials, firebase) remove_url_from(url_cache_list, index) return (expecting_url, url_cache) ```
User edited file: "atomicpress/admin.py": ```diff @@ -14,6 +14,10 @@ return self.render('admin/home.html') +class PostView(ModelView): + column_default_sort = ('date', True) + + def create_admin(): app = current_app._get_current_object() admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home')) @@ -27,4 +31,4 @@ admin.add_view(FileAdmin(app.config["UPLOADS_PATH"], app.config["UPLOADS_URL"], - name='Upload files')) + name='Upload files')) ```
```atomicpress/admin.py # -*- coding: utf-8 -*- from flask import current_app from flask_admin.contrib.fileadmin import FileAdmin from flask_admin import AdminIndexView, expose, Admin from flask_admin.contrib.sqla import ModelView from atomicpress import models from atomicpress.app import db class HomeView(AdminIndexView): @expose("/") def index(self): return self.render('admin/home.html') class PostView(ModelView): column_default_sort = ('date', True) def create_admin(): app = current_app._get_current_object() admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home')) admin.add_view(ModelView(models.Blog, db.session, category="Blog")) admin.add_view(ModelView(models.Author, db.session, category="Blog")) <|user_cursor_is_here|> admin.add_view(ModelView(models.Post, db.session, category="Post")) admin.add_view(ModelView(models.Tag, db.session, category="Post")) admin.add_view(ModelView(models.Category, db.session, category="Post")) admin.add_view(FileAdmin(app.config["UPLOADS_PATH"], app.config["UPLOADS_URL"], name='Upload files')) ```
```atomicpress/admin.py # -*- coding: utf-8 -*- from flask import current_app from flask_admin.contrib.fileadmin import FileAdmin from flask_admin import AdminIndexView, expose, Admin from flask_admin.contrib.sqla import ModelView from atomicpress import models from atomicpress.app import db class HomeView(AdminIndexView): @expose("/") def index(self): return self.render('admin/home.html') class PostView(ModelView): column_default_sort = ('date', True) def create_admin(): app = current_app._get_current_object() admin = Admin(app, "AtomicPress", index_view=HomeView(name='Home')) admin.add_view(ModelView(models.Blog, db.session, category="Blog")) admin.add_view(ModelView(models.Author, db.session, category="Blog")) <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "ModelView", "newName": "PostView"}} </|tool_call|> admin.add_view(ModelView(models.Post, db.session, category="Post")) admin.add_view(ModelView(models.Tag, db.session, category="Post")) admin.add_view(ModelView(models.Category, db.session, category="Post")) admin.add_view(FileAdmin(app.config["UPLOADS_PATH"], app.config["UPLOADS_URL"], name='Upload files')) ```
User edited file: "convention/build.gradle.kts": ```diff @@ -18,7 +18,7 @@ indraPluginPublishing { plugin( - id = "convention", + id = "sponge.dev", mainClass = "org.spongepowered.gradle.convention.SpongeConventionPlugin", displayName = "SpongePowered Convention", description = "Gradle conventions for Sponge organization projects", ```
```convention/build.gradle.kts plugins { groovy } tasks.withType(GroovyCompile::class).configureEach { sourceCompatibility = "1.8" targetCompatibility = "1.8" options.release.set(indra.javaVersions.target) } dependencies { api(project(":spongegradle-plugin-development")) implementation(localGroovy()) api("net.kyori:indra-common:1.3.1") api("gradle.plugin.org.cadixdev.gradle:licenser:0.5.0") api("com.google.code.gson:gson:2.8.6") } indraPluginPublishing { plugin( id = "sponge.dev", mainClass = "org.spongepowered.gradle.convention.SpongeConventionPlugin", displayName = "SpongePowered Convention", description = "Gradle conventions for Sponge organization projects", tags = listOf("sponge", "convention") ) plugin( <|user_cursor_is_here|> id = "implementation", mainClass = "org.spongepowered.gradle.convention.SpongeImplementationConventionPlugin", displayName = "SpongePowered Implementation Convention", description = "Conventions for implementations of Sponge projects", tags = listOf("sponge", "minecraft", "convention") ) } ```
```convention/build.gradle.kts plugins { groovy } tasks.withType(GroovyCompile::class).configureEach { sourceCompatibility = "1.8" targetCompatibility = "1.8" options.release.set(indra.javaVersions.target) } dependencies { api(project(":spongegradle-plugin-development")) implementation(localGroovy()) api("net.kyori:indra-common:1.3.1") api("gradle.plugin.org.cadixdev.gradle:licenser:0.5.0") api("com.google.code.gson:gson:2.8.6") } indraPluginPublishing { plugin( id = "sponge.dev", mainClass = "org.spongepowered.gradle.convention.SpongeConventionPlugin", displayName = "SpongePowered Convention", description = "Gradle conventions for Sponge organization projects", tags = listOf("sponge", "convention") ) plugin( <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "implementation", "newName": "sponge.impl"}} </|tool_call|> id = "implementation", mainClass = "org.spongepowered.gradle.convention.SpongeImplementationConventionPlugin", displayName = "SpongePowered Implementation Convention", description = "Conventions for implementations of Sponge projects", tags = listOf("sponge", "minecraft", "convention") ) } ```
User edited file: "rust/test/time/now_test.rs": ```diff @@ -1,34 +1,36 @@ - use test_tools::*; use super::TheModule; // -fn basic_test() +tests_impls! { - use TheModule::*; + #[ test ] + fn basic() + { + use TheModule::*; - // test.case( "time::now" ); - let got = time::now(); - assert!( got > 0 ); + // test.case( "time::now" ); + let got = time::now(); + assert!( got > 0 ); - // test.case( "time::ms::now" ); - let got1 = time::now(); - let got2 = time::ms::now(); - assert_eq!( got1, got2 ); + // test.case( "time::ms::now" ); + let got1 = time::now(); + let got2 = time::ms::now(); + assert_eq!( got1, got2 ); - // // test.case( "time::ns::now" ); - // let got1 = time::now(); - // let got2 = time::ns::now(); - // assert_eq!( got1, got2 / 1000000 ); - // zzz : use equal! + // // test.case( "time::ns::now" ); + // let got1 = time::now(); + // let got2 = time::ns::now(); + // assert_eq!( got1, got2 / 1000000 ); + // zzz : use equal! - // test.case( "time::s::now" ); - let got1 = time::now(); - let got2 = time::s::now(); - assert_eq!( got1 / 1000, got2 ); - + // test.case( "time::s::now" ); + let got1 = time::now(); + let got2 = time::s::now(); + assert_eq!( got1 / 1000, got2 ); + } } // @@ -36,4 +38,4 @@ test_suite! { basic, -} +} ```
```rust/test/time/now_test.rs use test_tools::*; use super::TheModule; // tests_impls! { #[ test ] fn basic() { use TheModule::*; // test.case( "time::now" ); let got = time::now(); assert!( got > 0 ); // test.case( "time::ms::now" ); let got1 = time::now(); let got2 = time::ms::now(); assert_eq!( got1, got2 ); // // test.case( "time::ns::now" ); // let got1 = time::now(); // let got2 = time::ns::now(); // assert_eq!( got1, got2 / 1000000 ); // zzz : use equal! // test.case( "time::s::now" ); let got1 = time::now(); let got2 = time::s::now(); assert_eq!( got1 / 1000, got2 ); } } // <|user_cursor_is_here|> test_suite! { basic, } ```
```rust/test/time/now_test.rs use test_tools::*; use super::TheModule; // tests_impls! { #[ test ] fn basic() { use TheModule::*; // test.case( "time::now" ); let got = time::now(); assert!( got > 0 ); // test.case( "time::ms::now" ); let got1 = time::now(); let got2 = time::ms::now(); assert_eq!( got1, got2 ); // // test.case( "time::ns::now" ); // let got1 = time::now(); // let got2 = time::ns::now(); // assert_eq!( got1, got2 / 1000000 ); // zzz : use equal! // test.case( "time::s::now" ); let got1 = time::now(); let got2 = time::s::now(); assert_eq!( got1 / 1000, got2 ); } } // <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "test_suite!", "newName": "tests_index!"}} </|tool_call|> test_suite! { basic, } ```
User edited file: "statistics.js": ```diff @@ -4,6 +4,12 @@ module.exports = function statistics() { return function (req, res, next) { + var ip = ''; + if (req.headers['x-nginx-proxy'] == 'true') { + ip = req.headers['x-real-ip']; + } else { + ip = req.connection.remoteAddress; + } rdb.sismember( 'stats:ip', req.connection.remoteAddress, @@ -21,4 +27,4 @@ rdb.incr('stats:hit:total', rdbLogger); next(); }; -} +} ``` User edited file: "statistics.js": ```diff @@ -12,7 +12,7 @@ } rdb.sismember( 'stats:ip', - req.connection.remoteAddress, + ip, function (err, reply) { if (err || typeof reply === 'undefined') { console.log('[Statistics] No reply from redis.'); ```
```statistics.js var config = require('./config'); var rdb = config.rdb; var rdbLogger = config.rdbLogger; module.exports = function statistics() { return function (req, res, next) { var ip = ''; if (req.headers['x-nginx-proxy'] == 'true') { ip = req.headers['x-real-ip']; } else { ip = req.connection.remoteAddress; } rdb.sismember( 'stats:ip', ip, function (err, reply) { if (err || typeof reply === 'undefined') { console.log('[Statistics] No reply from redis.'); } else { if (!reply) { <|user_cursor_is_here|> rdb.sadd('stats:ip', req.connection.remoteAddress, rdbLogger); rdb.incr('stats:visit:total', rdbLogger); } } } ); rdb.incr('stats:hit:total', rdbLogger); next(); }; } ```
```statistics.js var config = require('./config'); var rdb = config.rdb; var rdbLogger = config.rdbLogger; module.exports = function statistics() { return function (req, res, next) { var ip = ''; if (req.headers['x-nginx-proxy'] == 'true') { ip = req.headers['x-real-ip']; } else { ip = req.connection.remoteAddress; } rdb.sismember( 'stats:ip', ip, function (err, reply) { if (err || typeof reply === 'undefined') { console.log('[Statistics] No reply from redis.'); } else { if (!reply) { <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "req.connection.remoteAddress", "newName": "ip"}} </|tool_call|> rdb.sadd('stats:ip', req.connection.remoteAddress, rdbLogger); rdb.incr('stats:visit:total', rdbLogger); } } } ); rdb.incr('stats:hit:total', rdbLogger); next(); }; } ```
User edited file: "droidbox/src/main/java/com/github/jackparisi/droidbox/binding/SpinnerAdapters.kt": ```diff @@ -10,6 +10,14 @@ * https://github.com/JackParisi */ +/** + * + * Set a fixed height for the view dropdown popup + * + * @param view The spinner view that need a custom dropdown popup height + * @param height The height value in dp for the dropdown popup + * + */ @BindingAdapter("popupHeight") fun bindSpinnerPopupHeight(spinner: Spinner, height: Float) { ```
```droidbox/src/main/java/com/github/jackparisi/droidbox/binding/SpinnerAdapters.kt package com.github.jackparisi.droidbox.binding import android.databinding.BindingAdapter import android.widget.ListPopupWindow import android.widget.Spinner import com.github.jackparisi.droidbox.utility.dpToPx /** * Created by Giacomo Parisi on 21/08/17. * https://github.com/JackParisi */ /** * * Set a fixed height for the view dropdown popup * * @param view The spinner view that need a custom dropdown popup height * @param height The height value in dp for the dropdown popup * */ @BindingAdapter("popupHeight") <|user_cursor_is_here|> fun bindSpinnerPopupHeight(spinner: Spinner, height: Float) { try { val popup = Spinner::class.java.getDeclaredField("mPopup") popup.isAccessible = true val popupWindow = popup.get(spinner) if (popupWindow is ListPopupWindow) { popupWindow.height = dpToPx(height, spinner.context).toInt() } } catch (e: NoSuchFieldException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } } ```
```droidbox/src/main/java/com/github/jackparisi/droidbox/binding/SpinnerAdapters.kt package com.github.jackparisi.droidbox.binding import android.databinding.BindingAdapter import android.widget.ListPopupWindow import android.widget.Spinner import com.github.jackparisi.droidbox.utility.dpToPx /** * Created by Giacomo Parisi on 21/08/17. * https://github.com/JackParisi */ /** * * Set a fixed height for the view dropdown popup * * @param view The spinner view that need a custom dropdown popup height * @param height The height value in dp for the dropdown popup * */ @BindingAdapter("popupHeight") <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "spinner", "newName": "view"}} </|tool_call|> fun bindSpinnerPopupHeight(spinner: Spinner, height: Float) { try { val popup = Spinner::class.java.getDeclaredField("mPopup") popup.isAccessible = true val popupWindow = popup.get(spinner) if (popupWindow is ListPopupWindow) { popupWindow.height = dpToPx(height, spinner.context).toInt() } } catch (e: NoSuchFieldException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } } ```
User edited file: "src/ios.rs": ```diff @@ -1,4 +1,4 @@ -use crate::{Error, ErrorKind, Result}; +use crate::{Browser, BrowserOptions, Error, ErrorKind, Result}; use objc::{class, msg_send, runtime::Object, sel, sel_impl}; /// Deal with opening of browsers on iOS @@ -35,4 +35,4 @@ let () = msg_send![app, openURL: url_object options: {} completionHandler: null_ptr]; Ok(()) } -} +} ```
```src/ios.rs use crate::{Browser, BrowserOptions, Error, ErrorKind, Result}; use objc::{class, msg_send, runtime::Object, sel, sel_impl}; /// Deal with opening of browsers on iOS #[inline] pub fn open_browser_internal( _browser: Browser, url: &str, _options: &BrowserOptions, ) -> Result<()> { // always return true for a dry run if _options.dry_run { return Ok(()); } <|user_cursor_is_here|> let url_s: String = match url::Url::parse(url_raw) { Ok(u) => u.as_str().into(), Err(_) => url_raw.into(), }; unsafe { let app: *mut Object = msg_send![class!(UIApplication), sharedApplication]; if app.is_null() { return Err(Error::new( ErrorKind::Other, "UIApplication is null, can't open url", )); } let url_cstr = std::ffi::CString::new(url_s).unwrap(); // Create ns string class from our string let url_string: *mut Object = msg_send![class!(NSString), stringWithUTF8String: url_cstr]; // Create NSURL object with given string let url_object: *mut Object = msg_send![class!(NSURL), URLWithString: url_string]; // No completion handler let null_ptr = 0 as *mut Object; // Open url let () = msg_send![app, openURL: url_object options: {} completionHandler: null_ptr]; Ok(()) } } ```
```src/ios.rs use crate::{Browser, BrowserOptions, Error, ErrorKind, Result}; use objc::{class, msg_send, runtime::Object, sel, sel_impl}; /// Deal with opening of browsers on iOS #[inline] pub fn open_browser_internal( _browser: Browser, url: &str, _options: &BrowserOptions, ) -> Result<()> { // always return true for a dry run if _options.dry_run { return Ok(()); } <|tool_call|> {"name": "refactor.rename", "arguments": {"symbol": "url_raw", "newName": "url"}} </|tool_call|> let url_s: String = match url::Url::parse(url_raw) { Ok(u) => u.as_str().into(), Err(_) => url_raw.into(), }; unsafe { let app: *mut Object = msg_send![class!(UIApplication), sharedApplication]; if app.is_null() { return Err(Error::new( ErrorKind::Other, "UIApplication is null, can't open url", )); } let url_cstr = std::ffi::CString::new(url_s).unwrap(); // Create ns string class from our string let url_string: *mut Object = msg_send![class!(NSString), stringWithUTF8String: url_cstr]; // Create NSURL object with given string let url_object: *mut Object = msg_send![class!(NSURL), URLWithString: url_string]; // No completion handler let null_ptr = 0 as *mut Object; // Open url let () = msg_send![app, openURL: url_object options: {} completionHandler: null_ptr]; Ok(()) } } ```