commit
stringlengths 40
40
| old_file
stringlengths 4
234
| new_file
stringlengths 4
234
| old_contents
stringlengths 10
3.01k
| new_contents
stringlengths 19
3.38k
| subject
stringlengths 16
736
| message
stringlengths 17
2.63k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
82.6k
| config
stringclasses 4
values | content
stringlengths 134
4.41k
| fuzzy_diff
stringlengths 29
3.44k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
96b06d80f6108997fab44ac1e6042fcae93cc82a
|
server.py
|
server.py
|
import json
import tornado.ioloop
import tornado.web
import Adafruit_BMP.BMP085 as BMP085
class SensorAccess(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps(self.read_sensor()))
self.finish()
def read_sensor(self):
pass
class TempSensorAccess(SensorAccess):
def read_sensor(self):
sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
return {
'temperature': sensor.read_temperature(),
'pressure': sensor.read_pressure(),
}
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps({
'inde': 'pitools service'
}))
def start_server():
application = tornado.web.Application([
(r"/", IndexHandler),
(r"/sensors/env", TempSensorAccess),
])
application.listen(9876)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
start_server()
|
import json
import tornado.ioloop
import tornado.web
import Adafruit_BMP.BMP085 as BMP085
class SensorAccess(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps(self.read_sensor()))
self.finish()
def read_sensor(self):
pass
class TempSensorAccess(SensorAccess):
def read_sensor(self):
sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
return {
'temperature': sensor.read_temperature(),
'pressure': sensor.read_pressure(),
}
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps({
'index': 'pitools service'
}))
self.finish()
def start_server():
application = tornado.web.Application([
(r"/", IndexHandler),
(r"/sensors/env", TempSensorAccess),
])
application.listen(9876)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
start_server()
|
Fix typo; Fix request never finish
|
Fix typo; Fix request never finish
|
Python
|
bsd-2-clause
|
JokerQyou/pitools
|
python
|
## Code Before:
import json
import tornado.ioloop
import tornado.web
import Adafruit_BMP.BMP085 as BMP085
class SensorAccess(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps(self.read_sensor()))
self.finish()
def read_sensor(self):
pass
class TempSensorAccess(SensorAccess):
def read_sensor(self):
sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
return {
'temperature': sensor.read_temperature(),
'pressure': sensor.read_pressure(),
}
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps({
'inde': 'pitools service'
}))
def start_server():
application = tornado.web.Application([
(r"/", IndexHandler),
(r"/sensors/env", TempSensorAccess),
])
application.listen(9876)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
start_server()
## Instruction:
Fix typo; Fix request never finish
## Code After:
import json
import tornado.ioloop
import tornado.web
import Adafruit_BMP.BMP085 as BMP085
class SensorAccess(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps(self.read_sensor()))
self.finish()
def read_sensor(self):
pass
class TempSensorAccess(SensorAccess):
def read_sensor(self):
sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
return {
'temperature': sensor.read_temperature(),
'pressure': sensor.read_pressure(),
}
class IndexHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write(json.dumps({
'index': 'pitools service'
}))
self.finish()
def start_server():
application = tornado.web.Application([
(r"/", IndexHandler),
(r"/sensors/env", TempSensorAccess),
])
application.listen(9876)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
start_server()
|
...
@tornado.web.asynchronous
def get(self):
self.write(json.dumps({
'index': 'pitools service'
}))
self.finish()
def start_server():
...
|
ff12421cc6c3067bac11ece75cf4a16d11859ed0
|
tests/test_envs.py
|
tests/test_envs.py
|
import gym
import pytest
# Import for side-effect of registering environment
import imitation.examples.airl_envs # noqa: F401
import imitation.examples.model_envs # noqa: F401
ENV_NAMES = [env_spec.id for env_spec in gym.envs.registration.registry.all()
if env_spec.id.startswith('imitation/')]
@pytest.mark.parametrize("env_name", ENV_NAMES)
def test_envs(env_name): # pragma: no cover
"""Check that our custom environments don't crash on `step`, and `reset`."""
try:
env = gym.make(env_name)
except gym.error.DependencyNotInstalled as e:
if e.args[0].find('mujoco_py') != -1:
pytest.skip("Requires `mujoco_py`, which isn't installed.")
else:
raise
env.reset()
obs_space = env.observation_space
for _ in range(4):
act = env.action_space.sample()
obs, rew, done, info = env.step(act)
assert obs in obs_space
|
import gym
import pytest
# Import for side-effect of registering environment
import imitation.examples.airl_envs # noqa: F401
import imitation.examples.model_envs # noqa: F401
ENV_NAMES = [env_spec.id for env_spec in gym.envs.registration.registry.all()
if env_spec.id.startswith('imitation/')]
@pytest.mark.parametrize("env_name", ENV_NAMES)
def test_envs(env_name):
"""Check that our custom environments don't crash on `step`, and `reset`."""
try:
env = gym.make(env_name)
except gym.error.DependencyNotInstalled as e: # pragma: nocover
if e.args[0].find('mujoco_py') != -1:
pytest.skip("Requires `mujoco_py`, which isn't installed.")
else:
raise
env.reset()
obs_space = env.observation_space
for _ in range(4):
act = env.action_space.sample()
obs, rew, done, info = env.step(act)
assert obs in obs_space
|
Move the pragma: nocover to except block
|
Move the pragma: nocover to except block
|
Python
|
mit
|
HumanCompatibleAI/imitation,humancompatibleai/imitation,humancompatibleai/imitation,HumanCompatibleAI/imitation
|
python
|
## Code Before:
import gym
import pytest
# Import for side-effect of registering environment
import imitation.examples.airl_envs # noqa: F401
import imitation.examples.model_envs # noqa: F401
ENV_NAMES = [env_spec.id for env_spec in gym.envs.registration.registry.all()
if env_spec.id.startswith('imitation/')]
@pytest.mark.parametrize("env_name", ENV_NAMES)
def test_envs(env_name): # pragma: no cover
"""Check that our custom environments don't crash on `step`, and `reset`."""
try:
env = gym.make(env_name)
except gym.error.DependencyNotInstalled as e:
if e.args[0].find('mujoco_py') != -1:
pytest.skip("Requires `mujoco_py`, which isn't installed.")
else:
raise
env.reset()
obs_space = env.observation_space
for _ in range(4):
act = env.action_space.sample()
obs, rew, done, info = env.step(act)
assert obs in obs_space
## Instruction:
Move the pragma: nocover to except block
## Code After:
import gym
import pytest
# Import for side-effect of registering environment
import imitation.examples.airl_envs # noqa: F401
import imitation.examples.model_envs # noqa: F401
ENV_NAMES = [env_spec.id for env_spec in gym.envs.registration.registry.all()
if env_spec.id.startswith('imitation/')]
@pytest.mark.parametrize("env_name", ENV_NAMES)
def test_envs(env_name):
"""Check that our custom environments don't crash on `step`, and `reset`."""
try:
env = gym.make(env_name)
except gym.error.DependencyNotInstalled as e: # pragma: nocover
if e.args[0].find('mujoco_py') != -1:
pytest.skip("Requires `mujoco_py`, which isn't installed.")
else:
raise
env.reset()
obs_space = env.observation_space
for _ in range(4):
act = env.action_space.sample()
obs, rew, done, info = env.step(act)
assert obs in obs_space
|
# ... existing code ...
@pytest.mark.parametrize("env_name", ENV_NAMES)
def test_envs(env_name):
"""Check that our custom environments don't crash on `step`, and `reset`."""
try:
env = gym.make(env_name)
except gym.error.DependencyNotInstalled as e: # pragma: nocover
if e.args[0].find('mujoco_py') != -1:
pytest.skip("Requires `mujoco_py`, which isn't installed.")
else:
# ... rest of the code ...
|
1749fe077f151e6d2923f56a0797e1ba5c7efe68
|
app/src/test/java/io/github/droidkaigi/confsched2017/util/AssetsUtilTest.kt
|
app/src/test/java/io/github/droidkaigi/confsched2017/util/AssetsUtilTest.kt
|
package io.github.droidkaigi.confsched2017.util
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.lang.reflect.InvocationTargetException
@RunWith(RobolectricTestRunner::class)
class AssetsUtilTest {
@Test
@Throws(Exception::class)
fun ctor() {
try {
val ctor = AssetsUtil::class.java.getDeclaredConstructor()
ctor.isAccessible = true
ctor.newInstance()
} catch (e: InvocationTargetException) {
if (e.cause !is AssertionError)
fail()
}
}
}
|
package io.github.droidkaigi.confsched2017.util
import com.google.firebase.FirebaseApp
import com.taroid.knit.should
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import java.lang.reflect.InvocationTargetException
@RunWith(RobolectricTestRunner::class)
class AssetsUtilTest {
@Test
@Throws(Exception::class)
fun ctor() {
try {
val ctor = AssetsUtil::class.java.getDeclaredConstructor()
ctor.isAccessible = true
ctor.newInstance()
} catch (e: InvocationTargetException) {
if (e.cause !is AssertionError)
fail()
}
}
@Test
@Throws(Exception::class)
fun loadJSONFromAsset_succseedsWhenFileExists() {
val context = RuntimeEnvironment.application
context.assets.list("json").forEach {
val expect = context.assets.open("json/" + it)
.reader(charset = Charsets.UTF_8)
.use { it.readText() }
val actual = AssetsUtil.loadJSONFromAsset(context, it)
actual.should be expect
}
}
@Test
@Throws(Exception::class)
fun loadJSONFromAsset_failsWhenFileNotExists() {
FirebaseApp.initializeApp(RuntimeEnvironment.application)
AssetsUtil.loadJSONFromAsset(RuntimeEnvironment.application, "NonExistsFile.json").should be null
}
}
|
Add succeed and fail tests
|
Add succeed and fail tests
|
Kotlin
|
apache-2.0
|
futabooo/conference-app-2017,ogapants/conference-app-2017,hironytic/conference-app-2017,kaelaela/conference-app-2017,wakwak3125/conference-app-2017,kgmyshin/conference-app-2017,futabooo/conference-app-2017,k-kagurazaka/conference-app-2017,chibatching/conference-app-2017,u-nation/conference-app-2017,kikuchy/conference-app-2017,k-kagurazaka/conference-app-2017,chibatching/conference-app-2017,DroidKaigi/conference-app-2017,k-kagurazaka/conference-app-2017,shaunkawano/conference-app-2017,sys1yagi/conference-app-2017,ogapants/conference-app-2017,kobakei/conference-app-2017,futabooo/conference-app-2017,u-nation/conference-app-2017,kobakei/conference-app-2017,u-nation/conference-app-2017,hironytic/conference-app-2017,kgmyshin/conference-app-2017,eyedol/conference-app-2017,kitwtnb/conference-app-2017,sys1yagi/conference-app-2017,ogapants/conference-app-2017,hironytic/conference-app-2017,kobakei/conference-app-2017,u-nation/conference-app-2017,shaunkawano/conference-app-2017,kaelaela/conference-app-2017,horie1024/conference-app-2017,sys1yagi/conference-app-2017,kaelaela/conference-app-2017,kitwtnb/conference-app-2017,DroidKaigi/conference-app-2017,kgmyshin/conference-app-2017,kikuchy/conference-app-2017,kitwtnb/conference-app-2017,DroidKaigi/conference-app-2017,ogapants/conference-app-2017,kobakei/conference-app-2017,k-kagurazaka/conference-app-2017,DroidKaigi/conference-app-2017,kobakei/conference-app-2017,kitwtnb/conference-app-2017,kaelaela/conference-app-2017,shaunkawano/conference-app-2017,wakwak3125/conference-app-2017,chibatching/conference-app-2017,eyedol/conference-app-2017,shaunkawano/conference-app-2017,kikuchy/conference-app-2017,wakwak3125/conference-app-2017,ogapants/conference-app-2017,horie1024/conference-app-2017,sys1yagi/conference-app-2017,futabooo/conference-app-2017,k-kagurazaka/conference-app-2017,kikuchy/conference-app-2017,DroidKaigi/conference-app-2017,hironytic/conference-app-2017,wakwak3125/conference-app-2017,hironytic/conference-app-2017,futabooo/conference-app-2017,wakwak3125/conference-app-2017,chibatching/conference-app-2017,chibatching/conference-app-2017,sys1yagi/conference-app-2017,eyedol/conference-app-2017,u-nation/conference-app-2017,eyedol/conference-app-2017,kgmyshin/conference-app-2017,kaelaela/conference-app-2017,horie1024/conference-app-2017,eyedol/conference-app-2017,kitwtnb/conference-app-2017,horie1024/conference-app-2017,kgmyshin/conference-app-2017,horie1024/conference-app-2017,shaunkawano/conference-app-2017,kikuchy/conference-app-2017
|
kotlin
|
## Code Before:
package io.github.droidkaigi.confsched2017.util
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.lang.reflect.InvocationTargetException
@RunWith(RobolectricTestRunner::class)
class AssetsUtilTest {
@Test
@Throws(Exception::class)
fun ctor() {
try {
val ctor = AssetsUtil::class.java.getDeclaredConstructor()
ctor.isAccessible = true
ctor.newInstance()
} catch (e: InvocationTargetException) {
if (e.cause !is AssertionError)
fail()
}
}
}
## Instruction:
Add succeed and fail tests
## Code After:
package io.github.droidkaigi.confsched2017.util
import com.google.firebase.FirebaseApp
import com.taroid.knit.should
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import java.lang.reflect.InvocationTargetException
@RunWith(RobolectricTestRunner::class)
class AssetsUtilTest {
@Test
@Throws(Exception::class)
fun ctor() {
try {
val ctor = AssetsUtil::class.java.getDeclaredConstructor()
ctor.isAccessible = true
ctor.newInstance()
} catch (e: InvocationTargetException) {
if (e.cause !is AssertionError)
fail()
}
}
@Test
@Throws(Exception::class)
fun loadJSONFromAsset_succseedsWhenFileExists() {
val context = RuntimeEnvironment.application
context.assets.list("json").forEach {
val expect = context.assets.open("json/" + it)
.reader(charset = Charsets.UTF_8)
.use { it.readText() }
val actual = AssetsUtil.loadJSONFromAsset(context, it)
actual.should be expect
}
}
@Test
@Throws(Exception::class)
fun loadJSONFromAsset_failsWhenFileNotExists() {
FirebaseApp.initializeApp(RuntimeEnvironment.application)
AssetsUtil.loadJSONFromAsset(RuntimeEnvironment.application, "NonExistsFile.json").should be null
}
}
|
...
package io.github.droidkaigi.confsched2017.util
import com.google.firebase.FirebaseApp
import com.taroid.knit.should
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import java.lang.reflect.InvocationTargetException
@RunWith(RobolectricTestRunner::class)
...
fail()
}
}
@Test
@Throws(Exception::class)
fun loadJSONFromAsset_succseedsWhenFileExists() {
val context = RuntimeEnvironment.application
context.assets.list("json").forEach {
val expect = context.assets.open("json/" + it)
.reader(charset = Charsets.UTF_8)
.use { it.readText() }
val actual = AssetsUtil.loadJSONFromAsset(context, it)
actual.should be expect
}
}
@Test
@Throws(Exception::class)
fun loadJSONFromAsset_failsWhenFileNotExists() {
FirebaseApp.initializeApp(RuntimeEnvironment.application)
AssetsUtil.loadJSONFromAsset(RuntimeEnvironment.application, "NonExistsFile.json").should be null
}
}
...
|
0416c04f5931a1437dce3a190bfe7e9feb48858e
|
sli/api/src/main/java/org/slc/sli/api/resources/config/CustomJacksonContextResolver.java
|
sli/api/src/main/java/org/slc/sli/api/resources/config/CustomJacksonContextResolver.java
|
package org.slc.sli.api.resources.config;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.springframework.stereotype.Component;
import org.slc.sli.api.resources.Resource;
/**
* Provides a Jackson context resolver that Jersey uses for serializing to JSON.
*
* @author Sean Melody <[email protected]>
*
*/
@Provider
@Component
@Produces({ Resource.JSON_MEDIA_TYPE, Resource.SLC_JSON_MEDIA_TYPE })
public class CustomJacksonContextResolver implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper = new ObjectMapper();
public CustomJacksonContextResolver() {
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
}
@Override
public ObjectMapper getContext(Class<?> cl) {
return mapper;
}
}
|
package org.slc.sli.api.resources.config;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.springframework.stereotype.Component;
import org.slc.sli.api.resources.Resource;
/**
* Provides a Jackson context resolver that Jersey uses for serializing to JSON or XML.
*
* @author Sean Melody <[email protected]>
*
*/
@Provider
@Component
@Produces({ Resource.JSON_MEDIA_TYPE, Resource.SLC_JSON_MEDIA_TYPE, Resource.XML_MEDIA_TYPE, Resource.SLC_XML_MEDIA_TYPE })
public class CustomJacksonContextResolver implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper = new ObjectMapper();
public CustomJacksonContextResolver() {
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
}
@Override
public ObjectMapper getContext(Class<?> cl) {
return mapper;
}
}
|
Add XML to @produces for ContextResolver
|
Add XML to @produces for ContextResolver
|
Java
|
apache-2.0
|
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
|
java
|
## Code Before:
package org.slc.sli.api.resources.config;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.springframework.stereotype.Component;
import org.slc.sli.api.resources.Resource;
/**
* Provides a Jackson context resolver that Jersey uses for serializing to JSON.
*
* @author Sean Melody <[email protected]>
*
*/
@Provider
@Component
@Produces({ Resource.JSON_MEDIA_TYPE, Resource.SLC_JSON_MEDIA_TYPE })
public class CustomJacksonContextResolver implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper = new ObjectMapper();
public CustomJacksonContextResolver() {
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
}
@Override
public ObjectMapper getContext(Class<?> cl) {
return mapper;
}
}
## Instruction:
Add XML to @produces for ContextResolver
## Code After:
package org.slc.sli.api.resources.config;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.springframework.stereotype.Component;
import org.slc.sli.api.resources.Resource;
/**
* Provides a Jackson context resolver that Jersey uses for serializing to JSON or XML.
*
* @author Sean Melody <[email protected]>
*
*/
@Provider
@Component
@Produces({ Resource.JSON_MEDIA_TYPE, Resource.SLC_JSON_MEDIA_TYPE, Resource.XML_MEDIA_TYPE, Resource.SLC_XML_MEDIA_TYPE })
public class CustomJacksonContextResolver implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper = new ObjectMapper();
public CustomJacksonContextResolver() {
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
}
@Override
public ObjectMapper getContext(Class<?> cl) {
return mapper;
}
}
|
...
import org.slc.sli.api.resources.Resource;
/**
* Provides a Jackson context resolver that Jersey uses for serializing to JSON or XML.
*
* @author Sean Melody <[email protected]>
*
...
@Provider
@Component
@Produces({ Resource.JSON_MEDIA_TYPE, Resource.SLC_JSON_MEDIA_TYPE, Resource.XML_MEDIA_TYPE, Resource.SLC_XML_MEDIA_TYPE })
public class CustomJacksonContextResolver implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper = new ObjectMapper();
...
|
13291e4862ef48a3de3615e8eef5704c6bfff628
|
importlib_metadata/__init__.py
|
importlib_metadata/__init__.py
|
import os
import sys
import glob
class Distribution:
def __init__(self, path):
"""
Construct a distribution from a path to the metadata dir
"""
self.path = path
@classmethod
def for_name(cls, name, path=sys.path):
for path_item in path:
glob_spec = os.path.join(path_item, f'{name}-*.dist-info')
match = next(glob.iglob(glob_spec))
return cls(os.path.join(path_item, match))
@classmethod
def for_module(cls, mod):
return cls.for_name(cls.dist_name_for_module(mod))
@staticmethod
def name_for_module(mod):
return getattr(mod, '__dist_name__', mod.__name__)
|
import os
import sys
import glob
import email
import itertools
import contextlib
class Distribution:
def __init__(self, path):
"""
Construct a distribution from a path to the metadata dir
"""
self.path = path
@classmethod
def for_name(cls, name, path=sys.path):
for path_item in path:
glob_specs = (
os.path.join(path_item, f'{name}-*.*-info'),
os.path.join(path_item, f'{name}.*-info'),
)
globs = itertools.chain.from_iterable(map(glob.iglob, glob_specs))
match = next(globs)
return cls(os.path.join(path_item, match))
@classmethod
def for_module(cls, mod):
return cls.for_name(cls.name_for_module(mod))
@staticmethod
def name_for_module(mod):
return getattr(mod, '__dist_name__', mod.__name__)
@property
def metadata(self):
return email.message_from_string(
self.load_metadata('METADATA') or self.load_metadata('PKG-INFO')
)
def load_metadata(self, name):
fn = os.path.join(self.path, name)
with contextlib.suppress(FileNotFoundError):
with open(fn, encoding='utf-8') as strm:
return strm.read()
@property
def version(self):
return self.metadata['Version']
|
Implement metadata loading and version retrieval
|
Implement metadata loading and version retrieval
|
Python
|
apache-2.0
|
python/importlib_metadata
|
python
|
## Code Before:
import os
import sys
import glob
class Distribution:
def __init__(self, path):
"""
Construct a distribution from a path to the metadata dir
"""
self.path = path
@classmethod
def for_name(cls, name, path=sys.path):
for path_item in path:
glob_spec = os.path.join(path_item, f'{name}-*.dist-info')
match = next(glob.iglob(glob_spec))
return cls(os.path.join(path_item, match))
@classmethod
def for_module(cls, mod):
return cls.for_name(cls.dist_name_for_module(mod))
@staticmethod
def name_for_module(mod):
return getattr(mod, '__dist_name__', mod.__name__)
## Instruction:
Implement metadata loading and version retrieval
## Code After:
import os
import sys
import glob
import email
import itertools
import contextlib
class Distribution:
def __init__(self, path):
"""
Construct a distribution from a path to the metadata dir
"""
self.path = path
@classmethod
def for_name(cls, name, path=sys.path):
for path_item in path:
glob_specs = (
os.path.join(path_item, f'{name}-*.*-info'),
os.path.join(path_item, f'{name}.*-info'),
)
globs = itertools.chain.from_iterable(map(glob.iglob, glob_specs))
match = next(globs)
return cls(os.path.join(path_item, match))
@classmethod
def for_module(cls, mod):
return cls.for_name(cls.name_for_module(mod))
@staticmethod
def name_for_module(mod):
return getattr(mod, '__dist_name__', mod.__name__)
@property
def metadata(self):
return email.message_from_string(
self.load_metadata('METADATA') or self.load_metadata('PKG-INFO')
)
def load_metadata(self, name):
fn = os.path.join(self.path, name)
with contextlib.suppress(FileNotFoundError):
with open(fn, encoding='utf-8') as strm:
return strm.read()
@property
def version(self):
return self.metadata['Version']
|
...
import os
import sys
import glob
import email
import itertools
import contextlib
class Distribution:
...
@classmethod
def for_name(cls, name, path=sys.path):
for path_item in path:
glob_specs = (
os.path.join(path_item, f'{name}-*.*-info'),
os.path.join(path_item, f'{name}.*-info'),
)
globs = itertools.chain.from_iterable(map(glob.iglob, glob_specs))
match = next(globs)
return cls(os.path.join(path_item, match))
@classmethod
def for_module(cls, mod):
return cls.for_name(cls.name_for_module(mod))
@staticmethod
def name_for_module(mod):
return getattr(mod, '__dist_name__', mod.__name__)
@property
def metadata(self):
return email.message_from_string(
self.load_metadata('METADATA') or self.load_metadata('PKG-INFO')
)
def load_metadata(self, name):
fn = os.path.join(self.path, name)
with contextlib.suppress(FileNotFoundError):
with open(fn, encoding='utf-8') as strm:
return strm.read()
@property
def version(self):
return self.metadata['Version']
...
|
1b70aee665720ce10e2e0437fb462745adbd6799
|
changes/api/serializer/models/task.py
|
changes/api/serializer/models/task.py
|
from changes.api.serializer import Serializer, register
from changes.models import Task
@register(Task)
class TaskSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'objectID': instance.task_id,
'parentObjectID': instance.parent_id,
'name': instance.task_name,
'args': instance.data.get('kwargs') or {},
'attempts': instance.num_retries + 1,
'status': instance.status,
'result': instance.result,
'dateCreated': instance.date_created,
'dateStarted': instance.date_started,
'dateFinished': instance.date_finished,
'dateModified': instance.date_modified,
}
|
from changes.api.serializer import Serializer, register
from changes.models import Task
@register(Task)
class TaskSerializer(Serializer):
def serialize(self, instance, attrs):
if instance.data:
args = instance.data.get('kwargs') or {}
else:
args = {}
return {
'id': instance.id.hex,
'objectID': instance.task_id,
'parentObjectID': instance.parent_id,
'name': instance.task_name,
'args': args,
'attempts': instance.num_retries + 1,
'status': instance.status,
'result': instance.result,
'dateCreated': instance.date_created,
'dateStarted': instance.date_started,
'dateFinished': instance.date_finished,
'dateModified': instance.date_modified,
}
|
Fix args when Task.data is empty
|
Fix args when Task.data is empty
|
Python
|
apache-2.0
|
bowlofstew/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes
|
python
|
## Code Before:
from changes.api.serializer import Serializer, register
from changes.models import Task
@register(Task)
class TaskSerializer(Serializer):
def serialize(self, instance, attrs):
return {
'id': instance.id.hex,
'objectID': instance.task_id,
'parentObjectID': instance.parent_id,
'name': instance.task_name,
'args': instance.data.get('kwargs') or {},
'attempts': instance.num_retries + 1,
'status': instance.status,
'result': instance.result,
'dateCreated': instance.date_created,
'dateStarted': instance.date_started,
'dateFinished': instance.date_finished,
'dateModified': instance.date_modified,
}
## Instruction:
Fix args when Task.data is empty
## Code After:
from changes.api.serializer import Serializer, register
from changes.models import Task
@register(Task)
class TaskSerializer(Serializer):
def serialize(self, instance, attrs):
if instance.data:
args = instance.data.get('kwargs') or {}
else:
args = {}
return {
'id': instance.id.hex,
'objectID': instance.task_id,
'parentObjectID': instance.parent_id,
'name': instance.task_name,
'args': args,
'attempts': instance.num_retries + 1,
'status': instance.status,
'result': instance.result,
'dateCreated': instance.date_created,
'dateStarted': instance.date_started,
'dateFinished': instance.date_finished,
'dateModified': instance.date_modified,
}
|
# ... existing code ...
@register(Task)
class TaskSerializer(Serializer):
def serialize(self, instance, attrs):
if instance.data:
args = instance.data.get('kwargs') or {}
else:
args = {}
return {
'id': instance.id.hex,
'objectID': instance.task_id,
'parentObjectID': instance.parent_id,
'name': instance.task_name,
'args': args,
'attempts': instance.num_retries + 1,
'status': instance.status,
'result': instance.result,
# ... rest of the code ...
|
114e25d71248081a0837e2f6d68116e1f1ce8ee0
|
codenvy-ext-datasource-core/src/main/java/com/codenvy/ide/ext/datasource/client/sqllauncher/SqlLauncherEditorProvider.java
|
codenvy-ext-datasource-core/src/main/java/com/codenvy/ide/ext/datasource/client/sqllauncher/SqlLauncherEditorProvider.java
|
package com.codenvy.ide.ext.datasource.client.sqllauncher;
import com.codenvy.ide.api.editor.EditorPartPresenter;
import com.codenvy.ide.api.editor.EditorProvider;
import com.codenvy.ide.api.notification.NotificationManager;
import com.codenvy.ide.api.preferences.PreferencesManager;
import com.codenvy.ide.dto.DtoFactory;
import com.codenvy.ide.ext.datasource.client.DatasourceClientService;
import com.codenvy.ide.ext.datasource.client.DatasourceManager;
import com.codenvy.ide.ext.datasource.client.sqleditor.SqlEditorProvider;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
public class SqlLauncherEditorProvider implements EditorProvider {
private final NotificationManager notificationManager;
private final SqlEditorProvider sqlEditorProvider;
private SqlRequestLauncherConstants constants;
private PreferencesManager preferencesManager;
private DatasourceManager datasourceManager;
private EventBus eventBus;
private DatasourceClientService service;
private DtoFactory dtoFactory;
private SqlRequestLauncherFactory sqlRequestLauncherFactory;
@Inject
public SqlLauncherEditorProvider(final NotificationManager notificationManager,
final SqlEditorProvider sqlEditorProvider,
final SqlRequestLauncherConstants constants,
final PreferencesManager preferencesManager,
final DatasourceManager datasourceManager,
final EventBus eventBus,
final DatasourceClientService service,
final DtoFactory dtoFactory,
final SqlRequestLauncherFactory sqlRequestLauncherFactory) {
this.notificationManager = notificationManager;
this.sqlEditorProvider = sqlEditorProvider;
this.constants = constants;
this.preferencesManager = preferencesManager;
this.datasourceManager = datasourceManager;
this.eventBus = eventBus;
this.service = service;
this.dtoFactory = dtoFactory;
this.sqlRequestLauncherFactory = sqlRequestLauncherFactory;
}
@Override
public EditorPartPresenter getEditor() {
return new SqlRequestLauncherAdapter(sqlRequestLauncherFactory.createSqlRequestLauncherView(),
constants,
preferencesManager,
sqlEditorProvider,
service,
notificationManager,
datasourceManager,
eventBus,
dtoFactory);
}
}
|
package com.codenvy.ide.ext.datasource.client.sqllauncher;
import com.codenvy.ide.api.editor.EditorPartPresenter;
import com.codenvy.ide.api.editor.EditorProvider;
import com.codenvy.ide.util.loging.Log;
import com.google.inject.Inject;
public class SqlLauncherEditorProvider implements EditorProvider {
private SqlRequestLauncherFactory sqlRequestLauncherFactory;
@Inject
public SqlLauncherEditorProvider(final SqlRequestLauncherFactory sqlRequestLauncherFactory) {
this.sqlRequestLauncherFactory = sqlRequestLauncherFactory;
}
@Override
public EditorPartPresenter getEditor() {
Log.info(SqlLauncherEditorProvider.class, "New instance of SQL launcher editor requested.");
return sqlRequestLauncherFactory.createSqlRequestLauncherPresenter();
}
}
|
Simplify the SQL launcher editor provider
|
Simplify the SQL launcher editor provider
|
Java
|
epl-1.0
|
codenvy/plugin-datasource,codenvy/plugin-datasource
|
java
|
## Code Before:
package com.codenvy.ide.ext.datasource.client.sqllauncher;
import com.codenvy.ide.api.editor.EditorPartPresenter;
import com.codenvy.ide.api.editor.EditorProvider;
import com.codenvy.ide.api.notification.NotificationManager;
import com.codenvy.ide.api.preferences.PreferencesManager;
import com.codenvy.ide.dto.DtoFactory;
import com.codenvy.ide.ext.datasource.client.DatasourceClientService;
import com.codenvy.ide.ext.datasource.client.DatasourceManager;
import com.codenvy.ide.ext.datasource.client.sqleditor.SqlEditorProvider;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
public class SqlLauncherEditorProvider implements EditorProvider {
private final NotificationManager notificationManager;
private final SqlEditorProvider sqlEditorProvider;
private SqlRequestLauncherConstants constants;
private PreferencesManager preferencesManager;
private DatasourceManager datasourceManager;
private EventBus eventBus;
private DatasourceClientService service;
private DtoFactory dtoFactory;
private SqlRequestLauncherFactory sqlRequestLauncherFactory;
@Inject
public SqlLauncherEditorProvider(final NotificationManager notificationManager,
final SqlEditorProvider sqlEditorProvider,
final SqlRequestLauncherConstants constants,
final PreferencesManager preferencesManager,
final DatasourceManager datasourceManager,
final EventBus eventBus,
final DatasourceClientService service,
final DtoFactory dtoFactory,
final SqlRequestLauncherFactory sqlRequestLauncherFactory) {
this.notificationManager = notificationManager;
this.sqlEditorProvider = sqlEditorProvider;
this.constants = constants;
this.preferencesManager = preferencesManager;
this.datasourceManager = datasourceManager;
this.eventBus = eventBus;
this.service = service;
this.dtoFactory = dtoFactory;
this.sqlRequestLauncherFactory = sqlRequestLauncherFactory;
}
@Override
public EditorPartPresenter getEditor() {
return new SqlRequestLauncherAdapter(sqlRequestLauncherFactory.createSqlRequestLauncherView(),
constants,
preferencesManager,
sqlEditorProvider,
service,
notificationManager,
datasourceManager,
eventBus,
dtoFactory);
}
}
## Instruction:
Simplify the SQL launcher editor provider
## Code After:
package com.codenvy.ide.ext.datasource.client.sqllauncher;
import com.codenvy.ide.api.editor.EditorPartPresenter;
import com.codenvy.ide.api.editor.EditorProvider;
import com.codenvy.ide.util.loging.Log;
import com.google.inject.Inject;
public class SqlLauncherEditorProvider implements EditorProvider {
private SqlRequestLauncherFactory sqlRequestLauncherFactory;
@Inject
public SqlLauncherEditorProvider(final SqlRequestLauncherFactory sqlRequestLauncherFactory) {
this.sqlRequestLauncherFactory = sqlRequestLauncherFactory;
}
@Override
public EditorPartPresenter getEditor() {
Log.info(SqlLauncherEditorProvider.class, "New instance of SQL launcher editor requested.");
return sqlRequestLauncherFactory.createSqlRequestLauncherPresenter();
}
}
|
...
import com.codenvy.ide.api.editor.EditorPartPresenter;
import com.codenvy.ide.api.editor.EditorProvider;
import com.codenvy.ide.util.loging.Log;
import com.google.inject.Inject;
public class SqlLauncherEditorProvider implements EditorProvider {
private SqlRequestLauncherFactory sqlRequestLauncherFactory;
@Inject
public SqlLauncherEditorProvider(final SqlRequestLauncherFactory sqlRequestLauncherFactory) {
this.sqlRequestLauncherFactory = sqlRequestLauncherFactory;
}
@Override
public EditorPartPresenter getEditor() {
Log.info(SqlLauncherEditorProvider.class, "New instance of SQL launcher editor requested.");
return sqlRequestLauncherFactory.createSqlRequestLauncherPresenter();
}
}
...
|
6cc24cca0253056c4b5e84d7734e0559b69016ba
|
app/src/main/java/com/hewgill/android/nzsldict/DownloadReceiver.java
|
app/src/main/java/com/hewgill/android/nzsldict/DownloadReceiver.java
|
package com.hewgill.android.nzsldict;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
Intent startIntent = new Intent(context, FavouritesActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(startIntent);
}
}
}
|
package com.hewgill.android.nzsldict;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
Intent startIntent = new Intent(context, FavouritesActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(startIntent);
return;
}
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Toast.makeText(context, "Download completed?", Toast.LENGTH_SHORT).show();
}
}
}
|
Add stub to indicate that the download has completed; this needs to be raised to the favourites activity
|
Add stub to indicate that the download has completed; this needs to be raised to the favourites activity
|
Java
|
mit
|
rabid/nzsl-dictionary-android,rabid/nzsl-dictionary-android
|
java
|
## Code Before:
package com.hewgill.android.nzsldict;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
Intent startIntent = new Intent(context, FavouritesActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(startIntent);
}
}
}
## Instruction:
Add stub to indicate that the download has completed; this needs to be raised to the favourites activity
## Code After:
package com.hewgill.android.nzsldict;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
Intent startIntent = new Intent(context, FavouritesActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(startIntent);
return;
}
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Toast.makeText(context, "Download completed?", Toast.LENGTH_SHORT).show();
}
}
}
|
# ... existing code ...
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class DownloadReceiver extends BroadcastReceiver {
# ... modified code ...
Intent startIntent = new Intent(context, FavouritesActivity.class);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(startIntent);
return;
}
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Toast.makeText(context, "Download completed?", Toast.LENGTH_SHORT).show();
}
}
}
# ... rest of the code ...
|
dfaf3d1461a25ca26ed7562831373603010d2f29
|
xml_json_import/__init__.py
|
xml_json_import/__init__.py
|
from django.conf import settings
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
|
from django.conf import settings
from os import path
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
|
Throw exception for not existing XSLT_FILES_DIR path
|
Throw exception for not existing XSLT_FILES_DIR path
|
Python
|
mit
|
lev-veshnyakov/django-import-data,lev-veshnyakov/django-import-data
|
python
|
## Code Before:
from django.conf import settings
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
## Instruction:
Throw exception for not existing XSLT_FILES_DIR path
## Code After:
from django.conf import settings
from os import path
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
|
# ... existing code ...
from django.conf import settings
from os import path
class XmlJsonImportModuleException(Exception):
pass
# ... modified code ...
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
# ... rest of the code ...
|
fb2f66adf5ba60d2cda934ef27125ce84057367e
|
PCbuild/rmpyc.py
|
PCbuild/rmpyc.py
|
def deltree(root):
import os
def rm(path):
os.unlink(path)
npyc = npyo = 0
dirs = [root]
while dirs:
dir = dirs.pop()
for short in os.listdir(dir):
full = os.path.join(dir, short)
if os.path.isdir(full):
dirs.append(full)
elif short.endswith(".pyc"):
npyc += 1
rm(full)
elif short.endswith(".pyo"):
npyo += 1
rm(full)
return npyc, npyo
npyc, npyo = deltree("../Lib")
print npyc, ".pyc deleted,", npyo, ".pyo deleted"
|
def deltree(root):
import os
from os.path import join
npyc = npyo = 0
for root, dirs, files in os.walk(root):
for name in files:
delete = False
if name.endswith('.pyc'):
delete = True
npyc += 1
elif name.endswith('.pyo'):
delete = True
npyo += 1
if delete:
os.remove(join(root, name))
return npyc, npyo
npyc, npyo = deltree("../Lib")
print npyc, ".pyc deleted,", npyo, ".pyo deleted"
|
Use os.walk() to find files to delete.
|
Use os.walk() to find files to delete.
|
Python
|
mit
|
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
|
python
|
## Code Before:
def deltree(root):
import os
def rm(path):
os.unlink(path)
npyc = npyo = 0
dirs = [root]
while dirs:
dir = dirs.pop()
for short in os.listdir(dir):
full = os.path.join(dir, short)
if os.path.isdir(full):
dirs.append(full)
elif short.endswith(".pyc"):
npyc += 1
rm(full)
elif short.endswith(".pyo"):
npyo += 1
rm(full)
return npyc, npyo
npyc, npyo = deltree("../Lib")
print npyc, ".pyc deleted,", npyo, ".pyo deleted"
## Instruction:
Use os.walk() to find files to delete.
## Code After:
def deltree(root):
import os
from os.path import join
npyc = npyo = 0
for root, dirs, files in os.walk(root):
for name in files:
delete = False
if name.endswith('.pyc'):
delete = True
npyc += 1
elif name.endswith('.pyo'):
delete = True
npyo += 1
if delete:
os.remove(join(root, name))
return npyc, npyo
npyc, npyo = deltree("../Lib")
print npyc, ".pyc deleted,", npyo, ".pyo deleted"
|
...
def deltree(root):
import os
from os.path import join
npyc = npyo = 0
for root, dirs, files in os.walk(root):
for name in files:
delete = False
if name.endswith('.pyc'):
delete = True
npyc += 1
elif name.endswith('.pyo'):
delete = True
npyo += 1
if delete:
os.remove(join(root, name))
return npyc, npyo
npyc, npyo = deltree("../Lib")
...
|
7ef053749f4bfbcf7c2007a57d16139cfea09588
|
jsonapi_requests/configuration.py
|
jsonapi_requests/configuration.py
|
from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
return self._config_dict['API_ROOT']
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
|
from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
url = self._config_dict['API_ROOT']
if not url.endswith('/'):
url += '/'
return url
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
|
Append slash to API root if needed.
|
Append slash to API root if needed.
|
Python
|
bsd-3-clause
|
socialwifi/jsonapi-requests
|
python
|
## Code Before:
from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
return self._config_dict['API_ROOT']
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
## Instruction:
Append slash to API root if needed.
## Code After:
from collections import namedtuple
Configuration = namedtuple(
'Configuration',
['API_ROOT', 'AUTH', 'VALIDATE_SSL', 'TIMEOUT', 'APPEND_SLASH']
)
class Factory:
def __init__(self, config_dict):
self._config_dict = config_dict
def create(self) -> Configuration:
return Configuration(
API_ROOT=self.API_ROOT,
AUTH=self.AUTH,
VALIDATE_SSL=self.VALIDATE_SSL,
TIMEOUT=self.TIMEOUT,
APPEND_SLASH=self.APPEND_SLASH,
)
@property
def API_ROOT(self):
url = self._config_dict['API_ROOT']
if not url.endswith('/'):
url += '/'
return url
@property
def AUTH(self):
return self._config_dict.get('AUTH', None)
@property
def VALIDATE_SSL(self):
return self._config_dict.get('VALIDATE_SSL', True)
@property
def TIMEOUT(self):
return self._config_dict.get('TIMEOUT', 1)
@property
def APPEND_SLASH(self):
return self._config_dict.get('APPEND_SLASH', True)
|
...
@property
def API_ROOT(self):
url = self._config_dict['API_ROOT']
if not url.endswith('/'):
url += '/'
return url
@property
def AUTH(self):
...
|
e4ee7034291fbeda48efa0d1c617be8a20eb49bd
|
algorithms/python/496_next_greater_element.py
|
algorithms/python/496_next_greater_element.py
|
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
results = []
for findNum in findNums:
index = nums.index(findNum)
result = index + 1
for candidate in nums[index + 1:]:
if candidate > findNum:
results.append(candidate)
break
else:
result += 1
if result >= len(nums):
results.append(-1)
return results
|
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
results = []
for findNum in findNums:
index = nums.index(findNum)
result = index + 1
for candidate in nums[index + 1:]:
if candidate > findNum:
results.append(candidate)
break
else:
result += 1
if result >= len(nums):
results.append(-1)
return results
# Solution 2
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
result_hash = {}
stack = []
for num in nums:
while stack and num > stack[-1]:
result_hash[stack.pop()] = num
stack.append(num)
return [result_hash.get(x, -1) for x in findNums]
|
Add another solution for 496 next greater element
|
Add another solution for 496 next greater element
|
Python
|
mit
|
ruichao-factual/leetcode
|
python
|
## Code Before:
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
results = []
for findNum in findNums:
index = nums.index(findNum)
result = index + 1
for candidate in nums[index + 1:]:
if candidate > findNum:
results.append(candidate)
break
else:
result += 1
if result >= len(nums):
results.append(-1)
return results
## Instruction:
Add another solution for 496 next greater element
## Code After:
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
results = []
for findNum in findNums:
index = nums.index(findNum)
result = index + 1
for candidate in nums[index + 1:]:
if candidate > findNum:
results.append(candidate)
break
else:
result += 1
if result >= len(nums):
results.append(-1)
return results
# Solution 2
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
result_hash = {}
stack = []
for num in nums:
while stack and num > stack[-1]:
result_hash[stack.pop()] = num
stack.append(num)
return [result_hash.get(x, -1) for x in findNums]
|
...
results.append(-1)
return results
# Solution 2
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
result_hash = {}
stack = []
for num in nums:
while stack and num > stack[-1]:
result_hash[stack.pop()] = num
stack.append(num)
return [result_hash.get(x, -1) for x in findNums]
...
|
01b357ec14e0d8ef60bf12e297c347230fb8da63
|
src/UIViewController+IDPExtensions.h
|
src/UIViewController+IDPExtensions.h
|
//
// UIViewController+IDPExtensions.h
// ClipIt
//
// Created by Vadim Lavrov Viktorovich on 2/20/13.
// Copyright (c) 2013 IDAP Group. All rights reserved.
//
#import <UIKit/UIKit.h>
#define IDPViewControllerViewOfClassGetterSynthesize(theClass, getterName) \
- (theClass *)getterName { \
if ([self.view isKindOfClass:[theClass class]]) { \
return (theClass *)self.view; \
} \
return nil; \
}
@interface UIViewController (IDPExtensions)
@property (nonatomic, retain, readonly) UITableView *tableView;
@end
|
//
// UIViewController+IDPExtensions.h
// ClipIt
//
// Created by Vadim Lavrov Viktorovich on 2/20/13.
// Copyright (c) 2013 IDAP Group. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIViewController (IDPExtensions)
@property (nonatomic, retain, readonly) UITableView *tableView;
@end
|
Move IDPViewControllerViewOfClassGetterSynthesize to CommonKit -> IDPPropertyMacros.h
|
Move IDPViewControllerViewOfClassGetterSynthesize to CommonKit -> IDPPropertyMacros.h
|
C
|
bsd-3-clause
|
idapgroup/UIKit,idapgroup/UIKit,idapgroup/UIKit,idapgroup/UIKit
|
c
|
## Code Before:
//
// UIViewController+IDPExtensions.h
// ClipIt
//
// Created by Vadim Lavrov Viktorovich on 2/20/13.
// Copyright (c) 2013 IDAP Group. All rights reserved.
//
#import <UIKit/UIKit.h>
#define IDPViewControllerViewOfClassGetterSynthesize(theClass, getterName) \
- (theClass *)getterName { \
if ([self.view isKindOfClass:[theClass class]]) { \
return (theClass *)self.view; \
} \
return nil; \
}
@interface UIViewController (IDPExtensions)
@property (nonatomic, retain, readonly) UITableView *tableView;
@end
## Instruction:
Move IDPViewControllerViewOfClassGetterSynthesize to CommonKit -> IDPPropertyMacros.h
## Code After:
//
// UIViewController+IDPExtensions.h
// ClipIt
//
// Created by Vadim Lavrov Viktorovich on 2/20/13.
// Copyright (c) 2013 IDAP Group. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIViewController (IDPExtensions)
@property (nonatomic, retain, readonly) UITableView *tableView;
@end
|
// ... existing code ...
#import <UIKit/UIKit.h>
@interface UIViewController (IDPExtensions)
@property (nonatomic, retain, readonly) UITableView *tableView;
// ... rest of the code ...
|
30c3300bd6b8478e6b4f3512a975f0c366e9ca1a
|
app/src/main/java/ee/shy/core/Remote.java
|
app/src/main/java/ee/shy/core/Remote.java
|
package ee.shy.core;
import ee.shy.io.Jsonable;
import ee.shy.io.Validated;
import java.net.URI;
import java.util.Objects;
/**
* Class representing a remote repository's URI.
*/
public class Remote implements Jsonable, Validated {
/**
* Repository's URI.
*/
private final URI remote;
/**
* Constructs a remote with given URI.
* @param remote remote URI for repository
*/
public Remote(URI remote) {
this.remote = remote;
assertValid();
}
public URI getURI() {
return this.remote;
}
@Override
public void assertValid() {
Objects.requireNonNull(remote, "repository has no URI");
}
}
|
package ee.shy.core;
import ee.shy.io.Jsonable;
import ee.shy.io.Validated;
import java.net.URI;
import java.util.Objects;
/**
* Class representing a remote repository's URI.
*/
public class Remote implements Jsonable, Validated {
/**
* Repository's URI.
*/
private final URI uri;
/**
* Constructs a remote with given URI.
* @param uri remote URI for repository
*/
public Remote(URI uri) {
this.uri = uri;
assertValid();
}
public URI getURI() {
return this.uri;
}
@Override
public void assertValid() {
Objects.requireNonNull(uri, "repository has no URI");
}
}
|
Rename remote field to uri.
|
Rename remote field to uri.
|
Java
|
mit
|
sim642/shy,sim642/shy
|
java
|
## Code Before:
package ee.shy.core;
import ee.shy.io.Jsonable;
import ee.shy.io.Validated;
import java.net.URI;
import java.util.Objects;
/**
* Class representing a remote repository's URI.
*/
public class Remote implements Jsonable, Validated {
/**
* Repository's URI.
*/
private final URI remote;
/**
* Constructs a remote with given URI.
* @param remote remote URI for repository
*/
public Remote(URI remote) {
this.remote = remote;
assertValid();
}
public URI getURI() {
return this.remote;
}
@Override
public void assertValid() {
Objects.requireNonNull(remote, "repository has no URI");
}
}
## Instruction:
Rename remote field to uri.
## Code After:
package ee.shy.core;
import ee.shy.io.Jsonable;
import ee.shy.io.Validated;
import java.net.URI;
import java.util.Objects;
/**
* Class representing a remote repository's URI.
*/
public class Remote implements Jsonable, Validated {
/**
* Repository's URI.
*/
private final URI uri;
/**
* Constructs a remote with given URI.
* @param uri remote URI for repository
*/
public Remote(URI uri) {
this.uri = uri;
assertValid();
}
public URI getURI() {
return this.uri;
}
@Override
public void assertValid() {
Objects.requireNonNull(uri, "repository has no URI");
}
}
|
...
/**
* Repository's URI.
*/
private final URI uri;
/**
* Constructs a remote with given URI.
* @param uri remote URI for repository
*/
public Remote(URI uri) {
this.uri = uri;
assertValid();
}
public URI getURI() {
return this.uri;
}
@Override
public void assertValid() {
Objects.requireNonNull(uri, "repository has no URI");
}
}
...
|
09a54e7a09b362b48bde21dad25b14e73cf72c98
|
main.py
|
main.py
|
import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# First most frequent sub-sequence
result = subseq[OccurrenceNb.index(max(OccurrenceNb))]
return result
|
import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
import numpy as np
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# Most frequent sub-sequence
OccurrenceNb = np.array(OccurrenceNb)
subseq = np.array(subseq)
result = list(subseq[OccurrenceNb == OccurrenceNb.max()])
return result
|
Return all most frequent subsequences
|
Return all most frequent subsequences
|
Python
|
mit
|
kir0ul/dna
|
python
|
## Code Before:
import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# First most frequent sub-sequence
result = subseq[OccurrenceNb.index(max(OccurrenceNb))]
return result
## Instruction:
Return all most frequent subsequences
## Code After:
import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
import numpy as np
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# Most frequent sub-sequence
OccurrenceNb = np.array(OccurrenceNb)
subseq = np.array(subseq)
result = list(subseq[OccurrenceNb == OccurrenceNb.max()])
return result
|
# ... existing code ...
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
import numpy as np
# Create a set of every possible unique subsequence
subseq = set()
i = 0
# ... modified code ...
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# Most frequent sub-sequence
OccurrenceNb = np.array(OccurrenceNb)
subseq = np.array(subseq)
result = list(subseq[OccurrenceNb == OccurrenceNb.max()])
return result
# ... rest of the code ...
|
ca4b4732b4eacb6e1ac0e70bbc384982007d92de
|
custos/notify/http.py
|
custos/notify/http.py
|
import logging
import requests
from .base import Notifier
log = logging.getLogger(__name__)
class HTTPNotifier(Notifier):
''' A Notifier that sends http post request to a given url '''
def __init__(self, auth=None, json=True, **kwargs):
'''
Create a new HTTPNotifier
:param auth: If given, auth is handed over to request.post
:param recipients: The urls to post to.
:param json: If True, send message as json payload, else use an url query string
:type json: bool
:type recipients: Iterable of recipients or dict mapping categories to recipients
:param categories: The message categories this Notifier should relay
:type categories: Iterable
:param level: The minimum level for messages to be relayed
:type level: int
'''
self.auth = auth
self.json = json
super().__init__(**kwargs)
def notify(self, recipient, msg):
try:
params = msg.to_dict()
params.pop('image', None)
if self.json is True:
params['timestamp'] = str(params['timestamp'])
params['uuid'] = str(params['uuid'])
ret = requests.post(recipient, json=params, auth=self.auth)
else:
ret = requests.post(recipient, params=params, auth=self.auth)
ret.raise_for_status()
except ConnectionError:
except:
log.exception('Could not post message')
|
import logging
import requests
from .base import Notifier
log = logging.getLogger(__name__)
class HTTPNotifier(Notifier):
''' A Notifier that sends http post request to a given url '''
def __init__(self, auth=None, json=True, **kwargs):
'''
Create a new HTTPNotifier
:param auth: If given, auth is handed over to request.post
:param recipients: The urls to post to.
:param json: If True, send message as json payload, else use an url query string
:type json: bool
:type recipients: Iterable of recipients or dict mapping categories to recipients
:param categories: The message categories this Notifier should relay
:type categories: Iterable
:param level: The minimum level for messages to be relayed
:type level: int
'''
self.auth = auth
self.json = json
super().__init__(**kwargs)
def notify(self, recipient, msg):
try:
params = msg.to_dict()
params.pop('image', None)
if self.json is True:
params['timestamp'] = str(params['timestamp'])
params['uuid'] = str(params['uuid'])
ret = requests.post(recipient, json=params, auth=self.auth)
else:
ret = requests.post(recipient, params=params, auth=self.auth)
ret.raise_for_status()
except ConnectionError:
# traceback of requests connection errors are really long for
# such a simple thing
log.error('No connection to {}'.format(recipient))
except:
log.exception('Could not post message')
|
Fix exception handling in HTTPNotifier
|
Fix exception handling in HTTPNotifier
|
Python
|
mit
|
fact-project/pycustos
|
python
|
## Code Before:
import logging
import requests
from .base import Notifier
log = logging.getLogger(__name__)
class HTTPNotifier(Notifier):
''' A Notifier that sends http post request to a given url '''
def __init__(self, auth=None, json=True, **kwargs):
'''
Create a new HTTPNotifier
:param auth: If given, auth is handed over to request.post
:param recipients: The urls to post to.
:param json: If True, send message as json payload, else use an url query string
:type json: bool
:type recipients: Iterable of recipients or dict mapping categories to recipients
:param categories: The message categories this Notifier should relay
:type categories: Iterable
:param level: The minimum level for messages to be relayed
:type level: int
'''
self.auth = auth
self.json = json
super().__init__(**kwargs)
def notify(self, recipient, msg):
try:
params = msg.to_dict()
params.pop('image', None)
if self.json is True:
params['timestamp'] = str(params['timestamp'])
params['uuid'] = str(params['uuid'])
ret = requests.post(recipient, json=params, auth=self.auth)
else:
ret = requests.post(recipient, params=params, auth=self.auth)
ret.raise_for_status()
except ConnectionError:
except:
log.exception('Could not post message')
## Instruction:
Fix exception handling in HTTPNotifier
## Code After:
import logging
import requests
from .base import Notifier
log = logging.getLogger(__name__)
class HTTPNotifier(Notifier):
''' A Notifier that sends http post request to a given url '''
def __init__(self, auth=None, json=True, **kwargs):
'''
Create a new HTTPNotifier
:param auth: If given, auth is handed over to request.post
:param recipients: The urls to post to.
:param json: If True, send message as json payload, else use an url query string
:type json: bool
:type recipients: Iterable of recipients or dict mapping categories to recipients
:param categories: The message categories this Notifier should relay
:type categories: Iterable
:param level: The minimum level for messages to be relayed
:type level: int
'''
self.auth = auth
self.json = json
super().__init__(**kwargs)
def notify(self, recipient, msg):
try:
params = msg.to_dict()
params.pop('image', None)
if self.json is True:
params['timestamp'] = str(params['timestamp'])
params['uuid'] = str(params['uuid'])
ret = requests.post(recipient, json=params, auth=self.auth)
else:
ret = requests.post(recipient, params=params, auth=self.auth)
ret.raise_for_status()
except ConnectionError:
# traceback of requests connection errors are really long for
# such a simple thing
log.error('No connection to {}'.format(recipient))
except:
log.exception('Could not post message')
|
# ... existing code ...
ret.raise_for_status()
except ConnectionError:
# traceback of requests connection errors are really long for
# such a simple thing
log.error('No connection to {}'.format(recipient))
except:
log.exception('Could not post message')
# ... rest of the code ...
|
daf3a9e2f0ecaca59542decfacacca851264b92f
|
xmas3.c
|
xmas3.c
|
int main(int argc, char*argv[])
{
int length = 8;
for (int i = 0;i<length;i++)
{
for (int j = 0;j<=i;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
|
/*Build: gcc -std=c99 -o xmas3 xmas3.c*/
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char*argv[])
{
if (argc != 2)
{
printf("USAGE: %s [length]\n", argv[0]);
exit(-1);
}
int length = atoi(argv[1]);
for (int i = 0;i<length;i++)
{
for (int j = 0;j<=i;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
|
Add length as a parameter in command line.
|
Add length as a parameter in command line.
|
C
|
mit
|
svagionitis/xmas-tree
|
c
|
## Code Before:
int main(int argc, char*argv[])
{
int length = 8;
for (int i = 0;i<length;i++)
{
for (int j = 0;j<=i;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
## Instruction:
Add length as a parameter in command line.
## Code After:
/*Build: gcc -std=c99 -o xmas3 xmas3.c*/
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char*argv[])
{
if (argc != 2)
{
printf("USAGE: %s [length]\n", argv[0]);
exit(-1);
}
int length = atoi(argv[1]);
for (int i = 0;i<length;i++)
{
for (int j = 0;j<=i;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
|
# ... existing code ...
/*Build: gcc -std=c99 -o xmas3 xmas3.c*/
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char*argv[])
{
if (argc != 2)
{
printf("USAGE: %s [length]\n", argv[0]);
exit(-1);
}
int length = atoi(argv[1]);
for (int i = 0;i<length;i++)
{
# ... modified code ...
}
printf("\n");
}
return 0;
}
# ... rest of the code ...
|
b5e887b938263fc4094fe46043d4fd9a4e83a49e
|
src/main/java/edu/hm/hafner/shareit/util/AssertionFailedException.java
|
src/main/java/edu/hm/hafner/shareit/util/AssertionFailedException.java
|
package edu.hm.hafner.shareit.util;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
/**
* Thrown to indicate that a contract assertion check has been failed.
*
* @author Ulli Hafner
*/
public final class AssertionFailedException extends RuntimeException {
private static final long serialVersionUID = -7033759120346380864L;
/**
* Constructs an {@link AssertionFailedException} with the specified
* detail message.
*
* @param message
* the detail error message.
*/
AssertionFailedException(@CheckForNull final String message) {
super(message);
log(this);
}
/**
* Constructs an {@link AssertionFailedException} with the specified
* detail message and cause.
*
* @param message
* the detail error message.
* @param cause the cause (which is saved for later retrieval by the
* {@link Throwable#getCause()} method). (A <tt>null</tt> value
* is permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
AssertionFailedException(@CheckForNull final String message, @CheckForNull final Throwable cause) {
super(message, cause);
log(cause);
}
private static void log(final Throwable exception) {
LOGGER.log(Level.WARNING, "Assertion failed.", exception);
}
private static final Logger LOGGER = Logger.getLogger(AssertionFailedException.class.getName());
}
|
package edu.hm.hafner.shareit.util;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
/**
* Thrown to indicate that a contract assertion check has been failed.
*
* @author Ulli Hafner
*/
public final class AssertionFailedException extends IllegalArgumentException {
private static final long serialVersionUID = -7033759120346380864L;
/**
* Constructs an {@link AssertionFailedException} with the specified
* detail message.
*
* @param message
* the detail error message.
*/
AssertionFailedException(@CheckForNull final String message) {
super(message);
log(this);
}
/**
* Constructs an {@link AssertionFailedException} with the specified
* detail message and cause.
*
* @param message
* the detail error message.
* @param cause the cause (which is saved for later retrieval by the
* {@link Throwable#getCause()} method). (A <tt>null</tt> value
* is permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
AssertionFailedException(@CheckForNull final String message, @CheckForNull final Throwable cause) {
super(message, cause);
log(cause);
}
private static void log(final Throwable exception) {
LOGGER.log(Level.WARNING, "Assertion failed.", exception);
}
private static final Logger LOGGER = Logger.getLogger(AssertionFailedException.class.getName());
}
|
Make AFE sub type of IAE.
|
Make AFE sub type of IAE.
|
Java
|
mit
|
uhafner/shareit
|
java
|
## Code Before:
package edu.hm.hafner.shareit.util;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
/**
* Thrown to indicate that a contract assertion check has been failed.
*
* @author Ulli Hafner
*/
public final class AssertionFailedException extends RuntimeException {
private static final long serialVersionUID = -7033759120346380864L;
/**
* Constructs an {@link AssertionFailedException} with the specified
* detail message.
*
* @param message
* the detail error message.
*/
AssertionFailedException(@CheckForNull final String message) {
super(message);
log(this);
}
/**
* Constructs an {@link AssertionFailedException} with the specified
* detail message and cause.
*
* @param message
* the detail error message.
* @param cause the cause (which is saved for later retrieval by the
* {@link Throwable#getCause()} method). (A <tt>null</tt> value
* is permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
AssertionFailedException(@CheckForNull final String message, @CheckForNull final Throwable cause) {
super(message, cause);
log(cause);
}
private static void log(final Throwable exception) {
LOGGER.log(Level.WARNING, "Assertion failed.", exception);
}
private static final Logger LOGGER = Logger.getLogger(AssertionFailedException.class.getName());
}
## Instruction:
Make AFE sub type of IAE.
## Code After:
package edu.hm.hafner.shareit.util;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
/**
* Thrown to indicate that a contract assertion check has been failed.
*
* @author Ulli Hafner
*/
public final class AssertionFailedException extends IllegalArgumentException {
private static final long serialVersionUID = -7033759120346380864L;
/**
* Constructs an {@link AssertionFailedException} with the specified
* detail message.
*
* @param message
* the detail error message.
*/
AssertionFailedException(@CheckForNull final String message) {
super(message);
log(this);
}
/**
* Constructs an {@link AssertionFailedException} with the specified
* detail message and cause.
*
* @param message
* the detail error message.
* @param cause the cause (which is saved for later retrieval by the
* {@link Throwable#getCause()} method). (A <tt>null</tt> value
* is permitted, and indicates that the cause is nonexistent or
* unknown.)
*/
AssertionFailedException(@CheckForNull final String message, @CheckForNull final Throwable cause) {
super(message, cause);
log(cause);
}
private static void log(final Throwable exception) {
LOGGER.log(Level.WARNING, "Assertion failed.", exception);
}
private static final Logger LOGGER = Logger.getLogger(AssertionFailedException.class.getName());
}
|
# ... existing code ...
*
* @author Ulli Hafner
*/
public final class AssertionFailedException extends IllegalArgumentException {
private static final long serialVersionUID = -7033759120346380864L;
/**
# ... rest of the code ...
|
98552a4cb683e25ec9af53024e58644c04b55872
|
molly/external_media/views.py
|
molly/external_media/views.py
|
from email.utils import formatdate
from datetime import datetime, timedelta
from time import mktime
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, Http404
from molly.utils.views import BaseView
from molly.utils.breadcrumbs import NullBreadcrumb
from models import ExternalImageSized
class IndexView(BaseView):
breadcrumb = NullBreadcrumb
def handle_GET(self, request, context):
raise Http404
class ExternalImageView(BaseView):
breadcrumb = NullBreadcrumb
def handle_GET(self, request, context, slug):
eis = get_object_or_404(ExternalImageSized, slug=slug)
response = HttpResponse(open(eis.get_filename(), 'rb').read(), mimetype=eis.content_type.encode('ascii'))
response['ETag'] = slug
response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple()))
response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple()))
return response
|
from email.utils import formatdate
from datetime import datetime, timedelta
from time import mktime
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, Http404
from molly.utils.views import BaseView
from molly.utils.breadcrumbs import NullBreadcrumb
from models import ExternalImageSized
class IndexView(BaseView):
breadcrumb = NullBreadcrumb
def handle_GET(self, request, context):
raise Http404
class ExternalImageView(BaseView):
breadcrumb = NullBreadcrumb
def handle_GET(self, request, context, slug):
eis = get_object_or_404(ExternalImageSized, slug=slug)
try:
response = HttpResponse(open(eis.get_filename(), 'rb').read(),
mimetype=eis.content_type.encode('ascii'))
except IOError:
eis.delete()
raise Http404()
response['ETag'] = slug
response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple()))
response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple()))
return response
|
Handle missing external files gracefully
|
MOX-182: Handle missing external files gracefully
|
Python
|
apache-2.0
|
mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject
|
python
|
## Code Before:
from email.utils import formatdate
from datetime import datetime, timedelta
from time import mktime
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, Http404
from molly.utils.views import BaseView
from molly.utils.breadcrumbs import NullBreadcrumb
from models import ExternalImageSized
class IndexView(BaseView):
breadcrumb = NullBreadcrumb
def handle_GET(self, request, context):
raise Http404
class ExternalImageView(BaseView):
breadcrumb = NullBreadcrumb
def handle_GET(self, request, context, slug):
eis = get_object_or_404(ExternalImageSized, slug=slug)
response = HttpResponse(open(eis.get_filename(), 'rb').read(), mimetype=eis.content_type.encode('ascii'))
response['ETag'] = slug
response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple()))
response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple()))
return response
## Instruction:
MOX-182: Handle missing external files gracefully
## Code After:
from email.utils import formatdate
from datetime import datetime, timedelta
from time import mktime
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, Http404
from molly.utils.views import BaseView
from molly.utils.breadcrumbs import NullBreadcrumb
from models import ExternalImageSized
class IndexView(BaseView):
breadcrumb = NullBreadcrumb
def handle_GET(self, request, context):
raise Http404
class ExternalImageView(BaseView):
breadcrumb = NullBreadcrumb
def handle_GET(self, request, context, slug):
eis = get_object_or_404(ExternalImageSized, slug=slug)
try:
response = HttpResponse(open(eis.get_filename(), 'rb').read(),
mimetype=eis.content_type.encode('ascii'))
except IOError:
eis.delete()
raise Http404()
response['ETag'] = slug
response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple()))
response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple()))
return response
|
# ... existing code ...
def handle_GET(self, request, context, slug):
eis = get_object_or_404(ExternalImageSized, slug=slug)
try:
response = HttpResponse(open(eis.get_filename(), 'rb').read(),
mimetype=eis.content_type.encode('ascii'))
except IOError:
eis.delete()
raise Http404()
response['ETag'] = slug
response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple()))
# ... rest of the code ...
|
9145be89c1a5ba1a2c47bfeef571d40b9eb060bc
|
test/integration/test_user_args.py
|
test/integration/test_user_args.py
|
from . import *
class TestUserArgs(IntegrationTest):
def __init__(self, *args, **kwargs):
IntegrationTest.__init__(
self, os.path.join(examples_dir, '10_custom_args'),
configure=False, *args, **kwargs
)
def test_build_default(self):
self.configure()
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from unnamed!\n')
def test_build_with_args(self):
self.configure(extra_args=['--name=foo'])
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from foo!\n')
|
from six import assertRegex
from . import *
class TestUserArgs(IntegrationTest):
def __init__(self, *args, **kwargs):
IntegrationTest.__init__(
self, os.path.join(examples_dir, '10_custom_args'),
configure=False, *args, **kwargs
)
def test_build_default(self):
self.configure()
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from unnamed!\n')
def test_build_with_args(self):
self.configure(extra_args=['--name=foo'])
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from foo!\n')
def test_help(self):
os.chdir(self.srcdir)
output = self.assertPopen(
['bfg9000', 'help', 'configure']
)
assertRegex(self, output, r'(?m)^project-defined arguments:$')
assertRegex(self, output,
r'(?m)^\s+--name NAME\s+set the name to greet$')
def test_help_explicit_srcdir(self):
output = self.assertPopen(
['bfg9000', 'help', 'configure', self.srcdir]
)
assertRegex(self, output, r'(?m)^project-defined arguments:$')
assertRegex(self, output,
r'(?m)^\s+--name NAME\s+set the name to greet$')
|
Add integration test for user-args help
|
Add integration test for user-args help
|
Python
|
bsd-3-clause
|
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
|
python
|
## Code Before:
from . import *
class TestUserArgs(IntegrationTest):
def __init__(self, *args, **kwargs):
IntegrationTest.__init__(
self, os.path.join(examples_dir, '10_custom_args'),
configure=False, *args, **kwargs
)
def test_build_default(self):
self.configure()
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from unnamed!\n')
def test_build_with_args(self):
self.configure(extra_args=['--name=foo'])
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from foo!\n')
## Instruction:
Add integration test for user-args help
## Code After:
from six import assertRegex
from . import *
class TestUserArgs(IntegrationTest):
def __init__(self, *args, **kwargs):
IntegrationTest.__init__(
self, os.path.join(examples_dir, '10_custom_args'),
configure=False, *args, **kwargs
)
def test_build_default(self):
self.configure()
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from unnamed!\n')
def test_build_with_args(self):
self.configure(extra_args=['--name=foo'])
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from foo!\n')
def test_help(self):
os.chdir(self.srcdir)
output = self.assertPopen(
['bfg9000', 'help', 'configure']
)
assertRegex(self, output, r'(?m)^project-defined arguments:$')
assertRegex(self, output,
r'(?m)^\s+--name NAME\s+set the name to greet$')
def test_help_explicit_srcdir(self):
output = self.assertPopen(
['bfg9000', 'help', 'configure', self.srcdir]
)
assertRegex(self, output, r'(?m)^project-defined arguments:$')
assertRegex(self, output,
r'(?m)^\s+--name NAME\s+set the name to greet$')
|
# ... existing code ...
from six import assertRegex
from . import *
# ... modified code ...
self.configure(extra_args=['--name=foo'])
self.build(executable('simple'))
self.assertOutput([executable('simple')], 'hello from foo!\n')
def test_help(self):
os.chdir(self.srcdir)
output = self.assertPopen(
['bfg9000', 'help', 'configure']
)
assertRegex(self, output, r'(?m)^project-defined arguments:$')
assertRegex(self, output,
r'(?m)^\s+--name NAME\s+set the name to greet$')
def test_help_explicit_srcdir(self):
output = self.assertPopen(
['bfg9000', 'help', 'configure', self.srcdir]
)
assertRegex(self, output, r'(?m)^project-defined arguments:$')
assertRegex(self, output,
r'(?m)^\s+--name NAME\s+set the name to greet$')
# ... rest of the code ...
|
441cccc340afeb205da75762ce6e145215a858b3
|
src/zephyr/delayed_stream.py
|
src/zephyr/delayed_stream.py
|
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, delay):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.delay = delay
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
delayed_current_time = zephyr.time() - self.delay
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
|
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.default_delay = default_delay
self.specific_delays = specific_delays
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
now = zephyr.time()
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
delay = self.specific_delays.get(signal_stream_name, self.default_delay)
delayed_current_time = now - delay
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
|
Split delay configuration into default_delay and specific_delays
|
Split delay configuration into default_delay and specific_delays
|
Python
|
bsd-2-clause
|
jpaalasm/zephyr-bt
|
python
|
## Code Before:
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, delay):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.delay = delay
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
delayed_current_time = zephyr.time() - self.delay
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
## Instruction:
Split delay configuration into default_delay and specific_delays
## Code After:
import threading
import collections
import itertools
import time
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.default_delay = default_delay
self.specific_delays = specific_delays
self.stream_output_positions = collections.defaultdict(lambda: 0)
self.terminate_requested = False
def add_callback(self, callback):
self.callbacks.append(callback)
def terminate(self):
self.terminate_requested = True
def run(self):
while not self.terminate_requested:
now = zephyr.time()
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
delay = self.specific_delays.get(signal_stream_name, self.default_delay)
delayed_current_time = now - delay
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
for callback in self.callbacks:
callback(signal_stream_name, sample)
time.sleep(0.01)
|
...
import zephyr
class DelayedRealTimeStream(threading.Thread):
def __init__(self, signal_collector, callbacks, default_delay, specific_delays={}):
threading.Thread.__init__(self)
self.signal_collector = signal_collector
self.callbacks = callbacks
self.default_delay = default_delay
self.specific_delays = specific_delays
self.stream_output_positions = collections.defaultdict(lambda: 0)
...
def run(self):
while not self.terminate_requested:
now = zephyr.time()
all_streams = itertools.chain(self.signal_collector.iterate_signal_stream_histories(),
self.signal_collector.iterate_event_streams())
for signal_stream_name, signal_stream_history in all_streams:
delay = self.specific_delays.get(signal_stream_name, self.default_delay)
delayed_current_time = now - delay
from_sample = self.stream_output_positions[signal_stream_name]
for sample in signal_stream_history.iterate_samples(from_sample, delayed_current_time):
self.stream_output_positions[signal_stream_name] += 1
...
|
8aba5772afe0e409e2e6d52131433b0a79188f3a
|
include/response.h
|
include/response.h
|
namespace cpr {
class Response {
public:
Response(const long& status_code, const std::string& text, const Header& header, const Url& url,
const double& elapsed)
: status_code{status_code}, text{text}, header{header}, url{url}, elapsed{elapsed} {};
Response(const long& status_code, const std::string& text, const Header& header, const Url& url,
const double& elapsed, const Cookies& cookies)
: status_code{status_code}, text{text}, header{header}, url{url}, elapsed{elapsed},
cookies{cookies} {};
Response() = default;
long status_code;
std::string text;
Header header;
Url url;
double elapsed;
Cookies cookies;
};
}
#endif
|
namespace cpr {
class Response {
public:
Response() = default;
Response(const long& status_code, const std::string& text, const Header& header, const Url& url,
const double& elapsed)
: status_code{status_code}, text{text}, header{header}, url{url}, elapsed{elapsed} {};
Response(const long& status_code, const std::string& text, const Header& header, const Url& url,
const double& elapsed, const Cookies& cookies)
: status_code{status_code}, text{text}, header{header}, url{url}, elapsed{elapsed},
cookies{cookies} {};
long status_code;
std::string text;
Header header;
Url url;
double elapsed;
Cookies cookies;
};
}
#endif
|
Put the default constructor first
|
Put the default constructor first
|
C
|
mit
|
whoshuu/cpr,SuperV1234/cpr,SuperV1234/cpr,msuvajac/cpr,skystrife/cpr,skystrife/cpr,whoshuu/cpr,msuvajac/cpr,whoshuu/cpr,SuperV1234/cpr,msuvajac/cpr,skystrife/cpr
|
c
|
## Code Before:
namespace cpr {
class Response {
public:
Response(const long& status_code, const std::string& text, const Header& header, const Url& url,
const double& elapsed)
: status_code{status_code}, text{text}, header{header}, url{url}, elapsed{elapsed} {};
Response(const long& status_code, const std::string& text, const Header& header, const Url& url,
const double& elapsed, const Cookies& cookies)
: status_code{status_code}, text{text}, header{header}, url{url}, elapsed{elapsed},
cookies{cookies} {};
Response() = default;
long status_code;
std::string text;
Header header;
Url url;
double elapsed;
Cookies cookies;
};
}
#endif
## Instruction:
Put the default constructor first
## Code After:
namespace cpr {
class Response {
public:
Response() = default;
Response(const long& status_code, const std::string& text, const Header& header, const Url& url,
const double& elapsed)
: status_code{status_code}, text{text}, header{header}, url{url}, elapsed{elapsed} {};
Response(const long& status_code, const std::string& text, const Header& header, const Url& url,
const double& elapsed, const Cookies& cookies)
: status_code{status_code}, text{text}, header{header}, url{url}, elapsed{elapsed},
cookies{cookies} {};
long status_code;
std::string text;
Header header;
Url url;
double elapsed;
Cookies cookies;
};
}
#endif
|
// ... existing code ...
namespace cpr {
class Response {
public:
Response() = default;
Response(const long& status_code, const std::string& text, const Header& header, const Url& url,
const double& elapsed)
: status_code{status_code}, text{text}, header{header}, url{url}, elapsed{elapsed} {};
// ... modified code ...
const double& elapsed, const Cookies& cookies)
: status_code{status_code}, text{text}, header{header}, url{url}, elapsed{elapsed},
cookies{cookies} {};
long status_code;
std::string text;
// ... rest of the code ...
|
b4fa43b85a162fa9bef3cb67c2dd523f25707b4d
|
mo/cli.py
|
mo/cli.py
|
from argparse import ArgumentParser
import yaml
from .runner import Runner
def parse_variables(args):
variables = {}
if args is not None:
for variable in args:
tokens = variable.split('=')
name = tokens[0]
value = '='.join(tokens[1:])
variables[name] = value
return variables
def main():
parser = ArgumentParser()
parser.add_argument('-f', '--file', default='mo.yaml')
parser.add_argument('-v', '--var', dest='variables', nargs='*')
parser.add_argument('tasks', metavar='task', nargs='+')
args = parser.parse_args()
with open(args.file) as file:
configuration = yaml.load(file.read())
variables = parse_variables(args.variables)
runner = Runner(configuration, variables)
for task in args.tasks:
runner.run_task(task)
|
from argparse import ArgumentParser
import yaml
from .runner import Runner
def parse_variables(args):
variables = {}
if args is not None:
for variable in args:
tokens = variable.split('=')
name = tokens[0]
value = '='.join(tokens[1:])
variables[name] = value
return variables
def main():
parser = ArgumentParser()
parser.add_argument('-f', '--file', default='mo.yaml')
parser.add_argument('-v', '--var', dest='variables', nargs='*')
parser.add_argument('tasks', metavar='task', nargs='*')
args = parser.parse_args()
with open(args.file) as file:
configuration = yaml.load(file.read())
variables = parse_variables(args.variables)
runner = Runner(configuration, variables)
if args.tasks is None:
for task in args.tasks:
runner.run_task(task)
else:
print()
for task in runner.tasks.values():
print('', task.name, '-', task.description)
|
Add a way of listing commands
|
Add a way of listing commands
|
Python
|
mit
|
thomasleese/mo
|
python
|
## Code Before:
from argparse import ArgumentParser
import yaml
from .runner import Runner
def parse_variables(args):
variables = {}
if args is not None:
for variable in args:
tokens = variable.split('=')
name = tokens[0]
value = '='.join(tokens[1:])
variables[name] = value
return variables
def main():
parser = ArgumentParser()
parser.add_argument('-f', '--file', default='mo.yaml')
parser.add_argument('-v', '--var', dest='variables', nargs='*')
parser.add_argument('tasks', metavar='task', nargs='+')
args = parser.parse_args()
with open(args.file) as file:
configuration = yaml.load(file.read())
variables = parse_variables(args.variables)
runner = Runner(configuration, variables)
for task in args.tasks:
runner.run_task(task)
## Instruction:
Add a way of listing commands
## Code After:
from argparse import ArgumentParser
import yaml
from .runner import Runner
def parse_variables(args):
variables = {}
if args is not None:
for variable in args:
tokens = variable.split('=')
name = tokens[0]
value = '='.join(tokens[1:])
variables[name] = value
return variables
def main():
parser = ArgumentParser()
parser.add_argument('-f', '--file', default='mo.yaml')
parser.add_argument('-v', '--var', dest='variables', nargs='*')
parser.add_argument('tasks', metavar='task', nargs='*')
args = parser.parse_args()
with open(args.file) as file:
configuration = yaml.load(file.read())
variables = parse_variables(args.variables)
runner = Runner(configuration, variables)
if args.tasks is None:
for task in args.tasks:
runner.run_task(task)
else:
print()
for task in runner.tasks.values():
print('', task.name, '-', task.description)
|
...
parser = ArgumentParser()
parser.add_argument('-f', '--file', default='mo.yaml')
parser.add_argument('-v', '--var', dest='variables', nargs='*')
parser.add_argument('tasks', metavar='task', nargs='*')
args = parser.parse_args()
with open(args.file) as file:
...
runner = Runner(configuration, variables)
if args.tasks is None:
for task in args.tasks:
runner.run_task(task)
else:
print()
for task in runner.tasks.values():
print('', task.name, '-', task.description)
...
|
17d66bad1fd2ad75294dde5cbf0c1b5c694ae54c
|
bin/get_templates.py
|
bin/get_templates.py
|
import json
import os
from lib.functional import multi_map
from engine import types, consts
template_dir = os.path.join(os.environ['PORTER'], 'templates')
structs = (
(types.new_unit, "Tank", (consts.RED,)),
(types.new_attack, "RegularCannon", ()),
(types.new_armor, "WeakMetal", ()),
(types.new_movement, "Treads", ()),
)
def without_trailing_whitespace(string):
def remove_trailing_whitespace(line):
return line.rstrip()
return '\n'.join(map(remove_trailing_whitespace, string.split('\n')))
def generate_template(new_, name, args):
with open(os.path.join(template_dir, '%s.json' % (name,)), 'w') as f:
f.write(
without_trailing_whitespace(
json.dumps(
json.loads(
repr(
new_(name, *args))),
indent=4)))
def main():
if not os.path.exists(template_dir):
os.mkdir(template_dir)
multi_map(generate_template, structs)
if __name__ == '__main__':
main()
|
import json
import os
from lib.functional import multi_map
from engine import types, consts
template_dir = os.path.join(os.environ['PORTER'], 'templates')
structs = (
(types.new_unit, "Tank", (consts.RED,)),
(types.new_attack, "RegularCannon", ()),
(types.new_armor, "WeakMetal", ()),
(types.new_movement, "Treads", ()),
)
def without_trailing_whitespace(string):
def remove_trailing_whitespace(line):
return line.rstrip()
return '\n'.join(map(remove_trailing_whitespace, string.split('\n')))
def delete_all_templates():
do_delete = raw_input('Print remove contents of %s? (y/n) ' % (template_dir,))
if do_delete == 'y':
multi_map(delete_template, structs)
os.rmdir(template_dir)
else:
print 'Aborting on user request'
def delete_template(new_, name, args):
os.remove(os.path.join(template_dir, '%s.json' % (name,)))
def generate_template(new_, name, args):
with open(os.path.join(template_dir, '%s.json' % (name,)), 'w') as f:
f.write(
without_trailing_whitespace(
json.dumps(
json.loads(
repr(
new_(name, *args))),
indent=4)))
def main():
if not os.path.exists(template_dir):
os.mkdir(template_dir)
multi_map(generate_template, structs)
if __name__ == '__main__':
main()
|
Add functionality to delete all templates
|
Add functionality to delete all templates
|
Python
|
mit
|
Tactique/game_engine,Tactique/game_engine
|
python
|
## Code Before:
import json
import os
from lib.functional import multi_map
from engine import types, consts
template_dir = os.path.join(os.environ['PORTER'], 'templates')
structs = (
(types.new_unit, "Tank", (consts.RED,)),
(types.new_attack, "RegularCannon", ()),
(types.new_armor, "WeakMetal", ()),
(types.new_movement, "Treads", ()),
)
def without_trailing_whitespace(string):
def remove_trailing_whitespace(line):
return line.rstrip()
return '\n'.join(map(remove_trailing_whitespace, string.split('\n')))
def generate_template(new_, name, args):
with open(os.path.join(template_dir, '%s.json' % (name,)), 'w') as f:
f.write(
without_trailing_whitespace(
json.dumps(
json.loads(
repr(
new_(name, *args))),
indent=4)))
def main():
if not os.path.exists(template_dir):
os.mkdir(template_dir)
multi_map(generate_template, structs)
if __name__ == '__main__':
main()
## Instruction:
Add functionality to delete all templates
## Code After:
import json
import os
from lib.functional import multi_map
from engine import types, consts
template_dir = os.path.join(os.environ['PORTER'], 'templates')
structs = (
(types.new_unit, "Tank", (consts.RED,)),
(types.new_attack, "RegularCannon", ()),
(types.new_armor, "WeakMetal", ()),
(types.new_movement, "Treads", ()),
)
def without_trailing_whitespace(string):
def remove_trailing_whitespace(line):
return line.rstrip()
return '\n'.join(map(remove_trailing_whitespace, string.split('\n')))
def delete_all_templates():
do_delete = raw_input('Print remove contents of %s? (y/n) ' % (template_dir,))
if do_delete == 'y':
multi_map(delete_template, structs)
os.rmdir(template_dir)
else:
print 'Aborting on user request'
def delete_template(new_, name, args):
os.remove(os.path.join(template_dir, '%s.json' % (name,)))
def generate_template(new_, name, args):
with open(os.path.join(template_dir, '%s.json' % (name,)), 'w') as f:
f.write(
without_trailing_whitespace(
json.dumps(
json.loads(
repr(
new_(name, *args))),
indent=4)))
def main():
if not os.path.exists(template_dir):
os.mkdir(template_dir)
multi_map(generate_template, structs)
if __name__ == '__main__':
main()
|
// ... existing code ...
return '\n'.join(map(remove_trailing_whitespace, string.split('\n')))
def delete_all_templates():
do_delete = raw_input('Print remove contents of %s? (y/n) ' % (template_dir,))
if do_delete == 'y':
multi_map(delete_template, structs)
os.rmdir(template_dir)
else:
print 'Aborting on user request'
def delete_template(new_, name, args):
os.remove(os.path.join(template_dir, '%s.json' % (name,)))
def generate_template(new_, name, args):
with open(os.path.join(template_dir, '%s.json' % (name,)), 'w') as f:
f.write(
// ... rest of the code ...
|
8a7bc41d4ec357a6718b89c86616d243bcc2beee
|
kbp-events2014-scorer/src/main/java/com/bbn/kbp/events2014/assessmentDiff/observers/AETObserver.java
|
kbp-events2014-scorer/src/main/java/com/bbn/kbp/events2014/assessmentDiff/observers/AETObserver.java
|
package com.bbn.kbp.events2014.assessmentDiff.observers;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.kbp.events2014.Response;
import com.bbn.kbp.events2014.ResponseAssessment;
import com.bbn.kbp.events2014.assessmentDiff.observers.ConfusionMatrixAssessmentPairObserver;
public class AETObserver extends ConfusionMatrixAssessmentPairObserver {
@Override
protected boolean filter(Response response, ResponseAssessment left, ResponseAssessment right) {
return true;
}
@Override
protected Symbol toKey(ResponseAssessment assessment) {
return Symbol.from(assessment.justificationSupportsEventType().toString());
}
}
|
package com.bbn.kbp.events2014.assessmentDiff.observers;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.kbp.events2014.Response;
import com.bbn.kbp.events2014.ResponseAssessment;
import com.bbn.kbp.events2014.assessmentDiff.observers.ConfusionMatrixAssessmentPairObserver;
public class AETObserver extends ConfusionMatrixAssessmentPairObserver {
@Override
protected boolean filter(Response response, ResponseAssessment left, ResponseAssessment right) {
return left.justificationSupportsEventType().isPresent() && right.justificationSupportsEventType().isPresent();
}
@Override
protected Symbol toKey(ResponseAssessment assessment) {
return Symbol.from(assessment.justificationSupportsEventType().get().toString());
}
}
|
Update AET diff observer for possibility AET is absent
|
Update AET diff observer for possibility AET is absent
|
Java
|
mit
|
isi-nlp/tac-kbp-eal,isi-nlp/tac-kbp-eal,BBN-E/tac-kbp-eal,BBN-E/tac-kbp-eal,rgabbard-bbn/kbp-2014-event-arguments,rgabbard-bbn/kbp-2014-event-arguments
|
java
|
## Code Before:
package com.bbn.kbp.events2014.assessmentDiff.observers;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.kbp.events2014.Response;
import com.bbn.kbp.events2014.ResponseAssessment;
import com.bbn.kbp.events2014.assessmentDiff.observers.ConfusionMatrixAssessmentPairObserver;
public class AETObserver extends ConfusionMatrixAssessmentPairObserver {
@Override
protected boolean filter(Response response, ResponseAssessment left, ResponseAssessment right) {
return true;
}
@Override
protected Symbol toKey(ResponseAssessment assessment) {
return Symbol.from(assessment.justificationSupportsEventType().toString());
}
}
## Instruction:
Update AET diff observer for possibility AET is absent
## Code After:
package com.bbn.kbp.events2014.assessmentDiff.observers;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.kbp.events2014.Response;
import com.bbn.kbp.events2014.ResponseAssessment;
import com.bbn.kbp.events2014.assessmentDiff.observers.ConfusionMatrixAssessmentPairObserver;
public class AETObserver extends ConfusionMatrixAssessmentPairObserver {
@Override
protected boolean filter(Response response, ResponseAssessment left, ResponseAssessment right) {
return left.justificationSupportsEventType().isPresent() && right.justificationSupportsEventType().isPresent();
}
@Override
protected Symbol toKey(ResponseAssessment assessment) {
return Symbol.from(assessment.justificationSupportsEventType().get().toString());
}
}
|
// ... existing code ...
@Override
protected boolean filter(Response response, ResponseAssessment left, ResponseAssessment right) {
return left.justificationSupportsEventType().isPresent() && right.justificationSupportsEventType().isPresent();
}
@Override
protected Symbol toKey(ResponseAssessment assessment) {
return Symbol.from(assessment.justificationSupportsEventType().get().toString());
}
}
// ... rest of the code ...
|
59a717588c9f0e76d532516a0c38624042527291
|
testing/plot_test_data.py
|
testing/plot_test_data.py
|
import zephyr.util
from zephyr.collector import MeasurementCollector
from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler
from zephyr.message import MessagePayloadParser
from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial
from zephyr.protocol import Protocol
def main():
zephyr.util.DISABLE_CLOCK_DIFFERENCE_ESTIMATION = True
collector = MeasurementCollector()
rr_signal_analysis = BioHarnessSignalAnalysis([], [collector.handle_event])
signal_packet_handlers = [collector.handle_signal, rr_signal_analysis.handle_signal]
signal_packet_handler = BioHarnessPacketHandler(signal_packet_handlers, [collector.handle_event])
payload_parser = MessagePayloadParser([signal_packet_handler.handle_packet])
ser = VirtualSerial(test_data_dir + "/120-second-bt-stream.dat")
protocol = Protocol(ser, payload_parser.handle_message)
try:
protocol.run()
except EOFError:
pass
visualize_measurements(collector)
if __name__ == "__main__":
main()
|
import zephyr.util
from zephyr.collector import MeasurementCollector
from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler
from zephyr.message import MessagePayloadParser
from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial
from zephyr.protocol import Protocol, MessageFrameParser
def main():
zephyr.util.DISABLE_CLOCK_DIFFERENCE_ESTIMATION = True
collector = MeasurementCollector()
rr_signal_analysis = BioHarnessSignalAnalysis([], [collector.handle_event])
signal_packet_handlers = [collector.handle_signal, rr_signal_analysis.handle_signal]
signal_packet_handler = BioHarnessPacketHandler(signal_packet_handlers, [collector.handle_event])
payload_parser = MessagePayloadParser([signal_packet_handler.handle_packet])
message_parser = MessageFrameParser(payload_parser.handle_message)
ser = VirtualSerial(test_data_dir + "/120-second-bt-stream.dat")
protocol = Protocol(ser, [message_parser.parse_data])
try:
protocol.run()
except EOFError:
pass
visualize_measurements(collector)
if __name__ == "__main__":
main()
|
Fix test data plotting to use the changed interfaces
|
Fix test data plotting to use the changed interfaces
|
Python
|
bsd-2-clause
|
jpaalasm/zephyr-bt
|
python
|
## Code Before:
import zephyr.util
from zephyr.collector import MeasurementCollector
from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler
from zephyr.message import MessagePayloadParser
from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial
from zephyr.protocol import Protocol
def main():
zephyr.util.DISABLE_CLOCK_DIFFERENCE_ESTIMATION = True
collector = MeasurementCollector()
rr_signal_analysis = BioHarnessSignalAnalysis([], [collector.handle_event])
signal_packet_handlers = [collector.handle_signal, rr_signal_analysis.handle_signal]
signal_packet_handler = BioHarnessPacketHandler(signal_packet_handlers, [collector.handle_event])
payload_parser = MessagePayloadParser([signal_packet_handler.handle_packet])
ser = VirtualSerial(test_data_dir + "/120-second-bt-stream.dat")
protocol = Protocol(ser, payload_parser.handle_message)
try:
protocol.run()
except EOFError:
pass
visualize_measurements(collector)
if __name__ == "__main__":
main()
## Instruction:
Fix test data plotting to use the changed interfaces
## Code After:
import zephyr.util
from zephyr.collector import MeasurementCollector
from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler
from zephyr.message import MessagePayloadParser
from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial
from zephyr.protocol import Protocol, MessageFrameParser
def main():
zephyr.util.DISABLE_CLOCK_DIFFERENCE_ESTIMATION = True
collector = MeasurementCollector()
rr_signal_analysis = BioHarnessSignalAnalysis([], [collector.handle_event])
signal_packet_handlers = [collector.handle_signal, rr_signal_analysis.handle_signal]
signal_packet_handler = BioHarnessPacketHandler(signal_packet_handlers, [collector.handle_event])
payload_parser = MessagePayloadParser([signal_packet_handler.handle_packet])
message_parser = MessageFrameParser(payload_parser.handle_message)
ser = VirtualSerial(test_data_dir + "/120-second-bt-stream.dat")
protocol = Protocol(ser, [message_parser.parse_data])
try:
protocol.run()
except EOFError:
pass
visualize_measurements(collector)
if __name__ == "__main__":
main()
|
...
from zephyr.bioharness import BioHarnessSignalAnalysis, BioHarnessPacketHandler
from zephyr.message import MessagePayloadParser
from zephyr.testing import visualize_measurements, test_data_dir, VirtualSerial
from zephyr.protocol import Protocol, MessageFrameParser
def main():
...
payload_parser = MessagePayloadParser([signal_packet_handler.handle_packet])
message_parser = MessageFrameParser(payload_parser.handle_message)
ser = VirtualSerial(test_data_dir + "/120-second-bt-stream.dat")
protocol = Protocol(ser, [message_parser.parse_data])
try:
protocol.run()
...
|
11bc6af107d98dd34721afadf175339c98398923
|
jrt_test/src/tests/mockup-invoke/MockupInvoke.java
|
jrt_test/src/tests/mockup-invoke/MockupInvoke.java
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import com.yahoo.jrt.*;
public class MockupInvoke {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("error: Wrong number of parameters");
System.exit(0);
}
Transport transport = new Transport();
Supervisor orb = new Supervisor(transport);
Spec spec = new Spec(args[0]);
Request req = new Request("concat");
req.parameters().add(new StringValue(args[1]));
req.parameters().add(new StringValue(args[2]));
orb.invokeBatch(spec, req, 60.0);
if (req.isError()) {
System.out.println("error: " + req.errorCode()
+ ": " + req.errorMessage());
System.exit(0);
}
if (req.returnValues().size() != 1
|| req.returnValues().get(0).type() != 's') {
System.out.println("error: Wrong return values");
System.exit(0);
}
System.out.println("result: '"
+ req.returnValues().get(0).asString()
+ "'");
}
}
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import com.yahoo.jrt.*;
public class MockupInvoke {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("error: Wrong number of parameters");
System.exit(0);
}
Transport transport = new Transport();
Supervisor orb = new Supervisor(transport);
Spec spec = new Spec(args[0]);
Request req = new Request("concat");
req.parameters().add(new StringValue(args[1]));
req.parameters().add(new StringValue(args[2]));
Target target = orb.connect(spec);
try {
target.invokeSync(req, 60.0);
} finally {
target.close();
}
if (req.isError()) {
System.out.println("error: " + req.errorCode()
+ ": " + req.errorMessage());
System.exit(0);
}
if (req.returnValues().size() != 1
|| req.returnValues().get(0).type() != 's') {
System.out.println("error: Wrong return values");
System.exit(0);
}
System.out.println("result: '"
+ req.returnValues().get(0).asString()
+ "'");
}
}
|
Update test that is built directly in test.
|
Update test that is built directly in test.
|
Java
|
apache-2.0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
java
|
## Code Before:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import com.yahoo.jrt.*;
public class MockupInvoke {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("error: Wrong number of parameters");
System.exit(0);
}
Transport transport = new Transport();
Supervisor orb = new Supervisor(transport);
Spec spec = new Spec(args[0]);
Request req = new Request("concat");
req.parameters().add(new StringValue(args[1]));
req.parameters().add(new StringValue(args[2]));
orb.invokeBatch(spec, req, 60.0);
if (req.isError()) {
System.out.println("error: " + req.errorCode()
+ ": " + req.errorMessage());
System.exit(0);
}
if (req.returnValues().size() != 1
|| req.returnValues().get(0).type() != 's') {
System.out.println("error: Wrong return values");
System.exit(0);
}
System.out.println("result: '"
+ req.returnValues().get(0).asString()
+ "'");
}
}
## Instruction:
Update test that is built directly in test.
## Code After:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import com.yahoo.jrt.*;
public class MockupInvoke {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("error: Wrong number of parameters");
System.exit(0);
}
Transport transport = new Transport();
Supervisor orb = new Supervisor(transport);
Spec spec = new Spec(args[0]);
Request req = new Request("concat");
req.parameters().add(new StringValue(args[1]));
req.parameters().add(new StringValue(args[2]));
Target target = orb.connect(spec);
try {
target.invokeSync(req, 60.0);
} finally {
target.close();
}
if (req.isError()) {
System.out.println("error: " + req.errorCode()
+ ": " + req.errorMessage());
System.exit(0);
}
if (req.returnValues().size() != 1
|| req.returnValues().get(0).type() != 's') {
System.out.println("error: Wrong return values");
System.exit(0);
}
System.out.println("result: '"
+ req.returnValues().get(0).asString()
+ "'");
}
}
|
# ... existing code ...
Request req = new Request("concat");
req.parameters().add(new StringValue(args[1]));
req.parameters().add(new StringValue(args[2]));
Target target = orb.connect(spec);
try {
target.invokeSync(req, 60.0);
} finally {
target.close();
}
if (req.isError()) {
System.out.println("error: " + req.errorCode()
+ ": " + req.errorMessage());
System.exit(0);
# ... rest of the code ...
|
384eab108578d372c9755cf1a1a22738f7cd3dea
|
app/utils/__init__.py
|
app/utils/__init__.py
|
from utils.log import get_log
BASE_PATH = '/var/www/images/kernel-ci'
LOG = get_log()
|
from utils.log import get_log
BASE_PATH = '/var/www/images/kernel-ci'
LOG = get_log()
def is_hidden(value):
"""Verify if a file name or dir name is hidden (starts with .).
:param value: The value to verify.
:return True or False.
"""
hidden = False
if value.startswith('.'):
hidden = True
return hidden
|
Create function to test hidden files/dirs.
|
Create function to test hidden files/dirs.
Change-Id: I67e8d69fc85dfe58e4f127007c73f6888deff3e0
|
Python
|
agpl-3.0
|
joyxu/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend,joyxu/kernelci-backend,kernelci/kernelci-backend
|
python
|
## Code Before:
from utils.log import get_log
BASE_PATH = '/var/www/images/kernel-ci'
LOG = get_log()
## Instruction:
Create function to test hidden files/dirs.
Change-Id: I67e8d69fc85dfe58e4f127007c73f6888deff3e0
## Code After:
from utils.log import get_log
BASE_PATH = '/var/www/images/kernel-ci'
LOG = get_log()
def is_hidden(value):
"""Verify if a file name or dir name is hidden (starts with .).
:param value: The value to verify.
:return True or False.
"""
hidden = False
if value.startswith('.'):
hidden = True
return hidden
|
...
BASE_PATH = '/var/www/images/kernel-ci'
LOG = get_log()
def is_hidden(value):
"""Verify if a file name or dir name is hidden (starts with .).
:param value: The value to verify.
:return True or False.
"""
hidden = False
if value.startswith('.'):
hidden = True
return hidden
...
|
4c95c238cd198779b7019a72b412ce20ddf865bd
|
alg_gcd.py
|
alg_gcd.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def gcd(m, n):
"""Greatest Common Divisor (GCD) by Euclid's Algorithm.
Time complexity: O(m%n).
Space complexity: O(1).
"""
while n != 0:
m, n = n, m % n
return m
def main():
print('gcd(4, 2): {}'.format(gcd(4, 2)))
print('gcd(2, 4): {}'.format(gcd(2, 4)))
print('gcd(10, 4): {}'.format(gcd(10, 4)))
print('gcd(4, 10): {}'.format(gcd(4, 10)))
print('gcd(3, 4): {}'.format(gcd(3, 4)))
print('gcd(4, 3): {}'.format(gcd(4, 3)))
if __name__ == '__main__':
main()
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def gcd_recur(m, n):
"""Greatest Common Divisor (GCD) by Euclid's Algorithm.
Time complexity: O(m%n).
Space complexity: O(m%n).
"""
if n == 0:
return m
return gcd_recur(n, m % n)
def gcd_iter(m, n):
"""Greatest Common Divisor (GCD) by Euclid's Algorithm.
Time complexity: O(m%n).
Space complexity: O(1).
"""
while n != 0:
m, n = n, m % n
return m
def main():
import time
start_time = time.time()
print('gcd_recur(4, 2): {}'.format(gcd_recur(4, 2)))
print('gcd_recur(2, 4): {}'.format(gcd_recur(2, 4)))
print('gcd_recur(10, 4): {}'.format(gcd_recur(10, 4)))
print('gcd_recur(4, 10): {}'.format(gcd_recur(4, 10)))
print('gcd_recur(3, 4): {}'.format(gcd_recur(3, 4)))
print('gcd_recur(4, 3): {}'.format(gcd_recur(4, 3)))
print('Time:', time.time() - start_time)
start_time = time.time()
print('gcd_iter(4, 2): {}'.format(gcd_iter(4, 2)))
print('gcd_iter(2, 4): {}'.format(gcd_iter(2, 4)))
print('gcd_iter(10, 4): {}'.format(gcd_iter(10, 4)))
print('gcd_iter(4, 10): {}'.format(gcd_iter(4, 10)))
print('gcd_iter(3, 4): {}'.format(gcd_iter(3, 4)))
print('gcd_iter(4, 3): {}'.format(gcd_iter(4, 3)))
print('Time:', time.time() - start_time)
if __name__ == '__main__':
main()
|
Complete gcd recur sol w/ time/space complexity
|
Complete gcd recur sol w/ time/space complexity
|
Python
|
bsd-2-clause
|
bowen0701/algorithms_data_structures
|
python
|
## Code Before:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def gcd(m, n):
"""Greatest Common Divisor (GCD) by Euclid's Algorithm.
Time complexity: O(m%n).
Space complexity: O(1).
"""
while n != 0:
m, n = n, m % n
return m
def main():
print('gcd(4, 2): {}'.format(gcd(4, 2)))
print('gcd(2, 4): {}'.format(gcd(2, 4)))
print('gcd(10, 4): {}'.format(gcd(10, 4)))
print('gcd(4, 10): {}'.format(gcd(4, 10)))
print('gcd(3, 4): {}'.format(gcd(3, 4)))
print('gcd(4, 3): {}'.format(gcd(4, 3)))
if __name__ == '__main__':
main()
## Instruction:
Complete gcd recur sol w/ time/space complexity
## Code After:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def gcd_recur(m, n):
"""Greatest Common Divisor (GCD) by Euclid's Algorithm.
Time complexity: O(m%n).
Space complexity: O(m%n).
"""
if n == 0:
return m
return gcd_recur(n, m % n)
def gcd_iter(m, n):
"""Greatest Common Divisor (GCD) by Euclid's Algorithm.
Time complexity: O(m%n).
Space complexity: O(1).
"""
while n != 0:
m, n = n, m % n
return m
def main():
import time
start_time = time.time()
print('gcd_recur(4, 2): {}'.format(gcd_recur(4, 2)))
print('gcd_recur(2, 4): {}'.format(gcd_recur(2, 4)))
print('gcd_recur(10, 4): {}'.format(gcd_recur(10, 4)))
print('gcd_recur(4, 10): {}'.format(gcd_recur(4, 10)))
print('gcd_recur(3, 4): {}'.format(gcd_recur(3, 4)))
print('gcd_recur(4, 3): {}'.format(gcd_recur(4, 3)))
print('Time:', time.time() - start_time)
start_time = time.time()
print('gcd_iter(4, 2): {}'.format(gcd_iter(4, 2)))
print('gcd_iter(2, 4): {}'.format(gcd_iter(2, 4)))
print('gcd_iter(10, 4): {}'.format(gcd_iter(10, 4)))
print('gcd_iter(4, 10): {}'.format(gcd_iter(4, 10)))
print('gcd_iter(3, 4): {}'.format(gcd_iter(3, 4)))
print('gcd_iter(4, 3): {}'.format(gcd_iter(4, 3)))
print('Time:', time.time() - start_time)
if __name__ == '__main__':
main()
|
...
from __future__ import print_function
def gcd_recur(m, n):
"""Greatest Common Divisor (GCD) by Euclid's Algorithm.
Time complexity: O(m%n).
Space complexity: O(m%n).
"""
if n == 0:
return m
return gcd_recur(n, m % n)
def gcd_iter(m, n):
"""Greatest Common Divisor (GCD) by Euclid's Algorithm.
Time complexity: O(m%n).
...
def main():
import time
start_time = time.time()
print('gcd_recur(4, 2): {}'.format(gcd_recur(4, 2)))
print('gcd_recur(2, 4): {}'.format(gcd_recur(2, 4)))
print('gcd_recur(10, 4): {}'.format(gcd_recur(10, 4)))
print('gcd_recur(4, 10): {}'.format(gcd_recur(4, 10)))
print('gcd_recur(3, 4): {}'.format(gcd_recur(3, 4)))
print('gcd_recur(4, 3): {}'.format(gcd_recur(4, 3)))
print('Time:', time.time() - start_time)
start_time = time.time()
print('gcd_iter(4, 2): {}'.format(gcd_iter(4, 2)))
print('gcd_iter(2, 4): {}'.format(gcd_iter(2, 4)))
print('gcd_iter(10, 4): {}'.format(gcd_iter(10, 4)))
print('gcd_iter(4, 10): {}'.format(gcd_iter(4, 10)))
print('gcd_iter(3, 4): {}'.format(gcd_iter(3, 4)))
print('gcd_iter(4, 3): {}'.format(gcd_iter(4, 3)))
print('Time:', time.time() - start_time)
if __name__ == '__main__':
...
|
2538ca440620de8ed08510e0ae902c82184a9daa
|
consts/auth_type.py
|
consts/auth_type.py
|
class AuthType(object):
"""
An auth type defines what write privileges an authenticated agent has.
"""
MATCH_VIDEO = 0
EVENT_TEAMS = 1
EVENT_MATCHES = 2
EVENT_RANKINGS = 3
EVENT_ALLIANCES = 4
EVENT_AWARDS = 5
type_names = {
MATCH_VIDEO: "match video",
EVENT_TEAMS: "event teams",
EVENT_MATCHES: "event matches",
EVENT_RANKINGS: "event rankings",
EVENT_ALLIANCES: "event alliances",
EVENT_AWARDS: "event awrads"
}
|
class AuthType(object):
"""
An auth type defines what write privileges an authenticated agent has.
"""
EVENT_DATA = 0
MATCH_VIDEO = 1
EVENT_TEAMS = 2
EVENT_MATCHES = 3
EVENT_RANKINGS = 4
EVENT_ALLIANCES = 5
EVENT_AWARDS = 6
type_names = {
EVENT_DATA: "event data",
MATCH_VIDEO: "match video",
EVENT_TEAMS: "event teams",
EVENT_MATCHES: "event matches",
EVENT_RANKINGS: "event rankings",
EVENT_ALLIANCES: "event alliances",
EVENT_AWARDS: "event awrads"
}
|
Revert "Remove AuthType.EVENT_DATA and renumber"
|
Revert "Remove AuthType.EVENT_DATA and renumber"
This reverts commit 38248941eb47a04b82fe52e1adca7387dafcf7f3.
|
Python
|
mit
|
phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance,synth3tk/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,verycumbersome/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,bvisness/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance
|
python
|
## Code Before:
class AuthType(object):
"""
An auth type defines what write privileges an authenticated agent has.
"""
MATCH_VIDEO = 0
EVENT_TEAMS = 1
EVENT_MATCHES = 2
EVENT_RANKINGS = 3
EVENT_ALLIANCES = 4
EVENT_AWARDS = 5
type_names = {
MATCH_VIDEO: "match video",
EVENT_TEAMS: "event teams",
EVENT_MATCHES: "event matches",
EVENT_RANKINGS: "event rankings",
EVENT_ALLIANCES: "event alliances",
EVENT_AWARDS: "event awrads"
}
## Instruction:
Revert "Remove AuthType.EVENT_DATA and renumber"
This reverts commit 38248941eb47a04b82fe52e1adca7387dafcf7f3.
## Code After:
class AuthType(object):
"""
An auth type defines what write privileges an authenticated agent has.
"""
EVENT_DATA = 0
MATCH_VIDEO = 1
EVENT_TEAMS = 2
EVENT_MATCHES = 3
EVENT_RANKINGS = 4
EVENT_ALLIANCES = 5
EVENT_AWARDS = 6
type_names = {
EVENT_DATA: "event data",
MATCH_VIDEO: "match video",
EVENT_TEAMS: "event teams",
EVENT_MATCHES: "event matches",
EVENT_RANKINGS: "event rankings",
EVENT_ALLIANCES: "event alliances",
EVENT_AWARDS: "event awrads"
}
|
...
"""
An auth type defines what write privileges an authenticated agent has.
"""
EVENT_DATA = 0
MATCH_VIDEO = 1
EVENT_TEAMS = 2
EVENT_MATCHES = 3
EVENT_RANKINGS = 4
EVENT_ALLIANCES = 5
EVENT_AWARDS = 6
type_names = {
EVENT_DATA: "event data",
MATCH_VIDEO: "match video",
EVENT_TEAMS: "event teams",
EVENT_MATCHES: "event matches",
...
|
722e975e8819b59d9d2f53627a5d37550ea09c55
|
tests/test_clean.py
|
tests/test_clean.py
|
from mergepurge import clean
import pandas as pd
import numpy as np
t_data = pd.Series({'name': 'Timothy Testerosa III'})
t_parsed = (np.nan, 'Timothy', 'Testerosa', 'Timothy Testerosa')
# FIXME - load a csv file with a name column and the 4 correctly parsed name parts as 4 other cols
# Then, iterate over the names
def test_clean_contact_name():
assert clean.parse_contact_name(t_data, ['name'], False) == t_parsed
|
from mergepurge import clean
import pandas as pd
import numpy as np
complete = pd.read_csv('complete_parsed.tsv',
sep='\t', encoding='utf-8',
dtype={'aa_streetnum': str, 'aa_zip': str, 'zipcode': str})
COMP_LOC_COLS = ['address', 'city', 'state', 'zipcode']
COMP_CONTACT_COLS = ['first', 'last']
COMP_COMPANY_COLS = ['company']
BUILT_COLS = [col for col in complete.columns if col.startswith('aa_')]
partial = pd.read_csv('./incomplete.tsv',
sep='\t', encoding='utf-8',
dtype={'aa_streetnum': str, 'aa_zip': str, 'zipcode': str})
def test_clean_contact_name():
# Re-parse approx 100 records
for _, test_record in complete.iterrows():
known = (test_record.get('aa_title', np.nan), test_record.get('aa_firstname', np.nan),
test_record.get('aa_lastname', np.nan), test_record.get('aa_fullname', np.nan))
parsed = clean.parse_contact_name(test_record, COMP_CONTACT_COLS, strict=False)
assert parsed == known
def test_parse_location_cols():
for _, test_record in complete.iterrows():
known = (test_record.get('aa_streetnum', np.nan), test_record.get('aa_street', np.nan),
test_record.get('aa_city', np.nan), test_record.get('aa_state', np.nan),
test_record.get('aa_zip', np.nan), test_record.get('aa_fulladdy', np.nan))
parsed = clean.parse_location_cols(test_record, COMP_LOC_COLS, strict=False)
assert parsed == known
def test_parse_business_name():
for _, test_record in complete.iterrows():
known = test_record.get('aa_company', np.nan)
parsed = clean.parse_business_name(test_record, COMP_COMPANY_COLS, strict=False)
assert parsed == known
def test_build_matching_cols():
known = complete[BUILT_COLS].head(10).copy()
built = clean.build_matching_cols(complete.head(10).copy(),
COMP_LOC_COLS,
COMP_CONTACT_COLS,
COMP_COMPANY_COLS)
assert all(built[BUILT_COLS] == known)
|
Add tests for most functions in clean module
|
Add tests for most functions in clean module
Iterate over the complete and parsed test data and confirm we can still
produce the excepted output for most functions in clean.py.
|
Python
|
mit
|
mikecunha/mergepurge
|
python
|
## Code Before:
from mergepurge import clean
import pandas as pd
import numpy as np
t_data = pd.Series({'name': 'Timothy Testerosa III'})
t_parsed = (np.nan, 'Timothy', 'Testerosa', 'Timothy Testerosa')
# FIXME - load a csv file with a name column and the 4 correctly parsed name parts as 4 other cols
# Then, iterate over the names
def test_clean_contact_name():
assert clean.parse_contact_name(t_data, ['name'], False) == t_parsed
## Instruction:
Add tests for most functions in clean module
Iterate over the complete and parsed test data and confirm we can still
produce the excepted output for most functions in clean.py.
## Code After:
from mergepurge import clean
import pandas as pd
import numpy as np
complete = pd.read_csv('complete_parsed.tsv',
sep='\t', encoding='utf-8',
dtype={'aa_streetnum': str, 'aa_zip': str, 'zipcode': str})
COMP_LOC_COLS = ['address', 'city', 'state', 'zipcode']
COMP_CONTACT_COLS = ['first', 'last']
COMP_COMPANY_COLS = ['company']
BUILT_COLS = [col for col in complete.columns if col.startswith('aa_')]
partial = pd.read_csv('./incomplete.tsv',
sep='\t', encoding='utf-8',
dtype={'aa_streetnum': str, 'aa_zip': str, 'zipcode': str})
def test_clean_contact_name():
# Re-parse approx 100 records
for _, test_record in complete.iterrows():
known = (test_record.get('aa_title', np.nan), test_record.get('aa_firstname', np.nan),
test_record.get('aa_lastname', np.nan), test_record.get('aa_fullname', np.nan))
parsed = clean.parse_contact_name(test_record, COMP_CONTACT_COLS, strict=False)
assert parsed == known
def test_parse_location_cols():
for _, test_record in complete.iterrows():
known = (test_record.get('aa_streetnum', np.nan), test_record.get('aa_street', np.nan),
test_record.get('aa_city', np.nan), test_record.get('aa_state', np.nan),
test_record.get('aa_zip', np.nan), test_record.get('aa_fulladdy', np.nan))
parsed = clean.parse_location_cols(test_record, COMP_LOC_COLS, strict=False)
assert parsed == known
def test_parse_business_name():
for _, test_record in complete.iterrows():
known = test_record.get('aa_company', np.nan)
parsed = clean.parse_business_name(test_record, COMP_COMPANY_COLS, strict=False)
assert parsed == known
def test_build_matching_cols():
known = complete[BUILT_COLS].head(10).copy()
built = clean.build_matching_cols(complete.head(10).copy(),
COMP_LOC_COLS,
COMP_CONTACT_COLS,
COMP_COMPANY_COLS)
assert all(built[BUILT_COLS] == known)
|
# ... existing code ...
import pandas as pd
import numpy as np
complete = pd.read_csv('complete_parsed.tsv',
sep='\t', encoding='utf-8',
dtype={'aa_streetnum': str, 'aa_zip': str, 'zipcode': str})
COMP_LOC_COLS = ['address', 'city', 'state', 'zipcode']
COMP_CONTACT_COLS = ['first', 'last']
COMP_COMPANY_COLS = ['company']
BUILT_COLS = [col for col in complete.columns if col.startswith('aa_')]
partial = pd.read_csv('./incomplete.tsv',
sep='\t', encoding='utf-8',
dtype={'aa_streetnum': str, 'aa_zip': str, 'zipcode': str})
def test_clean_contact_name():
# Re-parse approx 100 records
for _, test_record in complete.iterrows():
known = (test_record.get('aa_title', np.nan), test_record.get('aa_firstname', np.nan),
test_record.get('aa_lastname', np.nan), test_record.get('aa_fullname', np.nan))
parsed = clean.parse_contact_name(test_record, COMP_CONTACT_COLS, strict=False)
assert parsed == known
def test_parse_location_cols():
for _, test_record in complete.iterrows():
known = (test_record.get('aa_streetnum', np.nan), test_record.get('aa_street', np.nan),
test_record.get('aa_city', np.nan), test_record.get('aa_state', np.nan),
test_record.get('aa_zip', np.nan), test_record.get('aa_fulladdy', np.nan))
parsed = clean.parse_location_cols(test_record, COMP_LOC_COLS, strict=False)
assert parsed == known
def test_parse_business_name():
for _, test_record in complete.iterrows():
known = test_record.get('aa_company', np.nan)
parsed = clean.parse_business_name(test_record, COMP_COMPANY_COLS, strict=False)
assert parsed == known
def test_build_matching_cols():
known = complete[BUILT_COLS].head(10).copy()
built = clean.build_matching_cols(complete.head(10).copy(),
COMP_LOC_COLS,
COMP_CONTACT_COLS,
COMP_COMPANY_COLS)
assert all(built[BUILT_COLS] == known)
# ... rest of the code ...
|
ad0859f2e7b6f659fe964f786277ea2ad3fdf787
|
src/listener.py
|
src/listener.py
|
import logging
import socket
import threading
from connection import Connection
import shared
class Listener(threading.Thread):
def __init__(self, host, port, family=socket.AF_INET):
super().__init__(name='Listener')
self.host = host
self.port = port
self.family = family
self.s = socket.socket(self.family, socket.SOCK_STREAM)
self.s.bind((self.host, self.port))
def run(self):
self.s.listen(1)
self.s.settimeout(1)
while True:
try:
conn, addr = self.s.accept()
logging.info('Incoming connection from: {}:{}'.format(addr[0], addr[1]))
with shared.connections_lock:
c = Connection(addr[0], addr[1], conn)
c.start()
shared.connections.add(c)
except socket.timeout:
pass
|
import logging
import socket
import threading
from connection import Connection
import shared
class Listener(threading.Thread):
def __init__(self, host, port, family=socket.AF_INET):
super().__init__(name='Listener')
self.host = host
self.port = port
self.family = family
self.s = socket.socket(self.family, socket.SOCK_STREAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.s.bind((self.host, self.port))
def run(self):
self.s.listen(1)
self.s.settimeout(1)
while True:
try:
conn, addr = self.s.accept()
logging.info('Incoming connection from: {}:{}'.format(addr[0], addr[1]))
with shared.connections_lock:
c = Connection(addr[0], addr[1], conn)
c.start()
shared.connections.add(c)
except socket.timeout:
pass
|
Add SO_REUSEADDR to socket options
|
Add SO_REUSEADDR to socket options
|
Python
|
mit
|
TheKysek/MiNode,TheKysek/MiNode
|
python
|
## Code Before:
import logging
import socket
import threading
from connection import Connection
import shared
class Listener(threading.Thread):
def __init__(self, host, port, family=socket.AF_INET):
super().__init__(name='Listener')
self.host = host
self.port = port
self.family = family
self.s = socket.socket(self.family, socket.SOCK_STREAM)
self.s.bind((self.host, self.port))
def run(self):
self.s.listen(1)
self.s.settimeout(1)
while True:
try:
conn, addr = self.s.accept()
logging.info('Incoming connection from: {}:{}'.format(addr[0], addr[1]))
with shared.connections_lock:
c = Connection(addr[0], addr[1], conn)
c.start()
shared.connections.add(c)
except socket.timeout:
pass
## Instruction:
Add SO_REUSEADDR to socket options
## Code After:
import logging
import socket
import threading
from connection import Connection
import shared
class Listener(threading.Thread):
def __init__(self, host, port, family=socket.AF_INET):
super().__init__(name='Listener')
self.host = host
self.port = port
self.family = family
self.s = socket.socket(self.family, socket.SOCK_STREAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.s.bind((self.host, self.port))
def run(self):
self.s.listen(1)
self.s.settimeout(1)
while True:
try:
conn, addr = self.s.accept()
logging.info('Incoming connection from: {}:{}'.format(addr[0], addr[1]))
with shared.connections_lock:
c = Connection(addr[0], addr[1], conn)
c.start()
shared.connections.add(c)
except socket.timeout:
pass
|
// ... existing code ...
self.port = port
self.family = family
self.s = socket.socket(self.family, socket.SOCK_STREAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.s.bind((self.host, self.port))
def run(self):
// ... rest of the code ...
|
c974c7a73e8ef48ea4fb1436b397f2973d8048c7
|
{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/apps/users/adapter.py
|
{{cookiecutter.project_name}}/{{cookiecutter.project_name}}/apps/users/adapter.py
|
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
class AccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request):
return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
class SocialAccountAdapter(DefaultSocialAccountAdapter):
def is_open_for_signup(self, request):
return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
|
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
class AccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request):
return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
class SocialAccountAdapter(DefaultSocialAccountAdapter):
def is_open_for_signup(self, request, sociallogin):
return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
|
Modify is_open_for_signup to receive 3 arguments
|
Modify is_open_for_signup to receive 3 arguments
SocialAccountAdapter expects a sociallogin argument.
|
Python
|
mit
|
LucianU/bud,LucianU/bud,LucianU/bud
|
python
|
## Code Before:
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
class AccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request):
return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
class SocialAccountAdapter(DefaultSocialAccountAdapter):
def is_open_for_signup(self, request):
return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
## Instruction:
Modify is_open_for_signup to receive 3 arguments
SocialAccountAdapter expects a sociallogin argument.
## Code After:
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
class AccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request):
return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
class SocialAccountAdapter(DefaultSocialAccountAdapter):
def is_open_for_signup(self, request, sociallogin):
return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
|
...
class SocialAccountAdapter(DefaultSocialAccountAdapter):
def is_open_for_signup(self, request, sociallogin):
return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True)
...
|
4cb1b6b8656d4e3893b3aa8fe5766b507afa6d24
|
cmsplugin_rt/button/cms_plugins.py
|
cmsplugin_rt/button/cms_plugins.py
|
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
|
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
text_enabled = True
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
|
Make Button plugin usable inside Text plugin
|
Make Button plugin usable inside Text plugin
|
Python
|
bsd-3-clause
|
RacingTadpole/cmsplugin-rt
|
python
|
## Code Before:
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
## Instruction:
Make Button plugin usable inside Text plugin
## Code After:
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from cms.models.pluginmodel import CMSPlugin
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from models import *
bootstrap_module_name = _("Widgets")
layout_module_name = _("Layout elements")
generic_module_name = _("Generic")
meta_module_name = _("Meta elements")
class ButtonPlugin(CMSPluginBase):
model = ButtonPluginModel
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
text_enabled = True
def render(self, context, instance, placeholder):
context['instance'] = instance
if instance.page_link:
context['link'] = instance.page_link.get_absolute_url()
else:
context['link'] = instance.button_link
return context
plugin_pool.register_plugin(ButtonPlugin)
|
...
name = _("Button")
#module = bootstrap_module_name
render_template = "button_plugin.html"
text_enabled = True
def render(self, context, instance, placeholder):
context['instance'] = instance
...
|
79e30537dfeed2cbdc46cc64d71c422b4ddfbbeb
|
src/main/java/abra/NativeSemiGlobalAligner.java
|
src/main/java/abra/NativeSemiGlobalAligner.java
|
package abra;
import abra.SemiGlobalAligner.Result;
public class NativeSemiGlobalAligner {
private native String align(String seq1, String seq2, int match, int mismatch, int gapOpen, int gapExtend);
private int match = 8;
private int mismatch = -32;
private int gapOpen = -48;
private int gapExtend = -1;
public NativeSemiGlobalAligner(int match, int mismatch, int gapOpen, int gapExtend) {
this.match = match;
this.mismatch = mismatch;
this.gapOpen = gapOpen;
this.gapExtend = gapExtend;
}
public Result align(String seq1, String seq2) {
// Result returned in format score:secondBest:pos:endPos:cigar
// 789:741:611:734:52M108I71M
String res = align(seq1, seq2, match, mismatch, gapOpen, gapExtend);
String[] results = res.split(":");
Result result = new Result(Integer.valueOf(results[0]), Integer.valueOf(results[1]),
Integer.valueOf(results[2]), Integer.valueOf(results[3]), results[4]);
return result;
}
}
|
package abra;
import abra.SemiGlobalAligner.Result;
public class NativeSemiGlobalAligner {
private native String align(String seq1, String seq2, int match, int mismatch, int gapOpen, int gapExtend);
private int match = 8;
private int mismatch = -32;
private int gapOpen = -48;
private int gapExtend = -1;
private static final int MAX_CONTIG_LEN = 1998;
private static final int MAX_REF_LEN = 4998;
public NativeSemiGlobalAligner(int match, int mismatch, int gapOpen, int gapExtend) {
this.match = match;
this.mismatch = mismatch;
this.gapOpen = gapOpen;
this.gapExtend = gapExtend;
}
public Result align(String seq1, String seq2) {
if (seq1.length() > MAX_CONTIG_LEN) {
throw new IllegalArgumentException("Contig too long");
}
if (seq2.length() > MAX_REF_LEN) {
throw new IllegalArgumentException("Ref too long");
}
// Result returned in format score:secondBest:pos:endPos:cigar
// 789:741:611:734:52M108I71M
String res = align(seq1, seq2, match, mismatch, gapOpen, gapExtend);
String[] results = res.split(":");
Result result = new Result(Integer.valueOf(results[0]), Integer.valueOf(results[1]),
Integer.valueOf(results[2]), Integer.valueOf(results[3]), results[4]);
return result;
}
}
|
Add length guard around native SG aligner input.
|
Add length guard around native SG aligner input.
|
Java
|
mit
|
mozack/abra2,mozack/abra2,mozack/abra2,mozack/abra2
|
java
|
## Code Before:
package abra;
import abra.SemiGlobalAligner.Result;
public class NativeSemiGlobalAligner {
private native String align(String seq1, String seq2, int match, int mismatch, int gapOpen, int gapExtend);
private int match = 8;
private int mismatch = -32;
private int gapOpen = -48;
private int gapExtend = -1;
public NativeSemiGlobalAligner(int match, int mismatch, int gapOpen, int gapExtend) {
this.match = match;
this.mismatch = mismatch;
this.gapOpen = gapOpen;
this.gapExtend = gapExtend;
}
public Result align(String seq1, String seq2) {
// Result returned in format score:secondBest:pos:endPos:cigar
// 789:741:611:734:52M108I71M
String res = align(seq1, seq2, match, mismatch, gapOpen, gapExtend);
String[] results = res.split(":");
Result result = new Result(Integer.valueOf(results[0]), Integer.valueOf(results[1]),
Integer.valueOf(results[2]), Integer.valueOf(results[3]), results[4]);
return result;
}
}
## Instruction:
Add length guard around native SG aligner input.
## Code After:
package abra;
import abra.SemiGlobalAligner.Result;
public class NativeSemiGlobalAligner {
private native String align(String seq1, String seq2, int match, int mismatch, int gapOpen, int gapExtend);
private int match = 8;
private int mismatch = -32;
private int gapOpen = -48;
private int gapExtend = -1;
private static final int MAX_CONTIG_LEN = 1998;
private static final int MAX_REF_LEN = 4998;
public NativeSemiGlobalAligner(int match, int mismatch, int gapOpen, int gapExtend) {
this.match = match;
this.mismatch = mismatch;
this.gapOpen = gapOpen;
this.gapExtend = gapExtend;
}
public Result align(String seq1, String seq2) {
if (seq1.length() > MAX_CONTIG_LEN) {
throw new IllegalArgumentException("Contig too long");
}
if (seq2.length() > MAX_REF_LEN) {
throw new IllegalArgumentException("Ref too long");
}
// Result returned in format score:secondBest:pos:endPos:cigar
// 789:741:611:734:52M108I71M
String res = align(seq1, seq2, match, mismatch, gapOpen, gapExtend);
String[] results = res.split(":");
Result result = new Result(Integer.valueOf(results[0]), Integer.valueOf(results[1]),
Integer.valueOf(results[2]), Integer.valueOf(results[3]), results[4]);
return result;
}
}
|
...
private int gapOpen = -48;
private int gapExtend = -1;
private static final int MAX_CONTIG_LEN = 1998;
private static final int MAX_REF_LEN = 4998;
public NativeSemiGlobalAligner(int match, int mismatch, int gapOpen, int gapExtend) {
this.match = match;
this.mismatch = mismatch;
...
}
public Result align(String seq1, String seq2) {
if (seq1.length() > MAX_CONTIG_LEN) {
throw new IllegalArgumentException("Contig too long");
}
if (seq2.length() > MAX_REF_LEN) {
throw new IllegalArgumentException("Ref too long");
}
// Result returned in format score:secondBest:pos:endPos:cigar
// 789:741:611:734:52M108I71M
...
|
12254ea15b1f761ad63095ed7244f347d42e4c85
|
file_encryptor/__init__.py
|
file_encryptor/__init__.py
|
from file_encryptor import (convergence, key_generators)
|
from file_encryptor import (convergence, key_generators)
__version__ = '0.2.0'
|
Add copyright, license and version information.
|
Add copyright, license and version information.
|
Python
|
mit
|
Storj/file-encryptor
|
python
|
## Code Before:
from file_encryptor import (convergence, key_generators)
## Instruction:
Add copyright, license and version information.
## Code After:
from file_encryptor import (convergence, key_generators)
__version__ = '0.2.0'
|
# ... existing code ...
from file_encryptor import (convergence, key_generators)
__version__ = '0.2.0'
# ... rest of the code ...
|
fb5705e8b3d834575c47fe0d070c06bf4d02cd11
|
gremlin-core/src/main/java/com/tinkerpop/gremlin/structure/io/graphson/GraphSONObjectMapper.java
|
gremlin-core/src/main/java/com/tinkerpop/gremlin/structure/io/graphson/GraphSONObjectMapper.java
|
package com.tinkerpop.gremlin.structure.io.graphson;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import java.util.Optional;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class GraphSONObjectMapper extends ObjectMapper {
public GraphSONObjectMapper() {
this(null);
}
public GraphSONObjectMapper(final SimpleModule custom) {
disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// this provider toStrings all unknown classes and converts keys in Map objects that are Object to String.
final DefaultSerializerProvider provider = new GraphSONSerializerProvider();
provider.setDefaultKeySerializer(new GraphSONModule.GraphSONKeySerializer());
setSerializerProvider(provider);
registerModule(new GraphSONModule());
Optional.ofNullable(custom).ifPresent(this::registerModule);
// plugin external serialization modules
findAndRegisterModules();
}
}
|
package com.tinkerpop.gremlin.structure.io.graphson;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import java.util.Optional;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class GraphSONObjectMapper extends ObjectMapper {
public GraphSONObjectMapper() {
this(null, false);
}
public GraphSONObjectMapper(final SimpleModule custom) {
this(custom, false);
}
public GraphSONObjectMapper(final SimpleModule custom, final boolean loadExternalModules) {
disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// this provider toStrings all unknown classes and converts keys in Map objects that are Object to String.
final DefaultSerializerProvider provider = new GraphSONSerializerProvider();
provider.setDefaultKeySerializer(new GraphSONModule.GraphSONKeySerializer());
setSerializerProvider(provider);
registerModule(new GraphSONModule());
Optional.ofNullable(custom).ifPresent(this::registerModule);
// plugin external serialization modules
if (loadExternalModules)
findAndRegisterModules();
}
}
|
Configure dynamic serializer loader for GraphSON
|
Configure dynamic serializer loader for GraphSON
|
Java
|
apache-2.0
|
apache/tinkerpop,pluradj/incubator-tinkerpop,apache/incubator-tinkerpop,krlohnes/tinkerpop,n-tran/incubator-tinkerpop,jorgebay/tinkerpop,robertdale/tinkerpop,gdelafosse/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,robertdale/tinkerpop,vtslab/incubator-tinkerpop,Lab41/tinkerpop3,edgarRd/incubator-tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,apache/tinkerpop,edgarRd/incubator-tinkerpop,n-tran/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,artem-aliev/tinkerpop,Lab41/tinkerpop3,artem-aliev/tinkerpop,BrynCooke/incubator-tinkerpop,velo/incubator-tinkerpop,samiunn/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,jorgebay/tinkerpop,robertdale/tinkerpop,velo/incubator-tinkerpop,rmagen/incubator-tinkerpop,apache/tinkerpop,samiunn/incubator-tinkerpop,artem-aliev/tinkerpop,jorgebay/tinkerpop,rmagen/incubator-tinkerpop,vtslab/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,rmagen/incubator-tinkerpop,vtslab/incubator-tinkerpop,artem-aliev/tinkerpop,artem-aliev/tinkerpop,apache/incubator-tinkerpop,newkek/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,krlohnes/tinkerpop,jorgebay/tinkerpop,velo/incubator-tinkerpop,newkek/incubator-tinkerpop,pluradj/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,pluradj/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,newkek/incubator-tinkerpop,samiunn/incubator-tinkerpop,dalaro/incubator-tinkerpop,n-tran/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,apache/tinkerpop,gdelafosse/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,edgarRd/incubator-tinkerpop,dalaro/incubator-tinkerpop,mpollmeier/tinkerpop3,krlohnes/tinkerpop,mike-tr-adamson/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,robertdale/tinkerpop,apache/incubator-tinkerpop,dalaro/incubator-tinkerpop,robertdale/tinkerpop,mpollmeier/tinkerpop3
|
java
|
## Code Before:
package com.tinkerpop.gremlin.structure.io.graphson;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import java.util.Optional;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class GraphSONObjectMapper extends ObjectMapper {
public GraphSONObjectMapper() {
this(null);
}
public GraphSONObjectMapper(final SimpleModule custom) {
disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// this provider toStrings all unknown classes and converts keys in Map objects that are Object to String.
final DefaultSerializerProvider provider = new GraphSONSerializerProvider();
provider.setDefaultKeySerializer(new GraphSONModule.GraphSONKeySerializer());
setSerializerProvider(provider);
registerModule(new GraphSONModule());
Optional.ofNullable(custom).ifPresent(this::registerModule);
// plugin external serialization modules
findAndRegisterModules();
}
}
## Instruction:
Configure dynamic serializer loader for GraphSON
## Code After:
package com.tinkerpop.gremlin.structure.io.graphson;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import java.util.Optional;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class GraphSONObjectMapper extends ObjectMapper {
public GraphSONObjectMapper() {
this(null, false);
}
public GraphSONObjectMapper(final SimpleModule custom) {
this(custom, false);
}
public GraphSONObjectMapper(final SimpleModule custom, final boolean loadExternalModules) {
disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// this provider toStrings all unknown classes and converts keys in Map objects that are Object to String.
final DefaultSerializerProvider provider = new GraphSONSerializerProvider();
provider.setDefaultKeySerializer(new GraphSONModule.GraphSONKeySerializer());
setSerializerProvider(provider);
registerModule(new GraphSONModule());
Optional.ofNullable(custom).ifPresent(this::registerModule);
// plugin external serialization modules
if (loadExternalModules)
findAndRegisterModules();
}
}
|
// ... existing code ...
*/
public class GraphSONObjectMapper extends ObjectMapper {
public GraphSONObjectMapper() {
this(null, false);
}
public GraphSONObjectMapper(final SimpleModule custom) {
this(custom, false);
}
public GraphSONObjectMapper(final SimpleModule custom, final boolean loadExternalModules) {
disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// this provider toStrings all unknown classes and converts keys in Map objects that are Object to String.
// ... modified code ...
Optional.ofNullable(custom).ifPresent(this::registerModule);
// plugin external serialization modules
if (loadExternalModules)
findAndRegisterModules();
}
}
// ... rest of the code ...
|
cf3596ee93eabf425c7d42c15fc07b11f7741158
|
humblemedia/causes/models.py
|
humblemedia/causes/models.py
|
from django.db import models
class Cause(models.Model):
title = models.CharField(max_length=64)
description = models.TextField()
creator = models.ForeignKey('auth.User', related_name='causes')
target = models.PositiveIntegerField(null=True, blank=True)
url = models.URLField(null=True, blank=True)
is_verified = models.BooleanField(default=False)
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
|
from django.db import models
class Cause(models.Model):
title = models.CharField(max_length=64)
description = models.TextField()
creator = models.ForeignKey('auth.User', related_name='causes')
organization = models.ForeignKey('organizations.Organization', related_name='causes', null=True, blank=True)
target = models.PositiveIntegerField(null=True, blank=True)
url = models.URLField(null=True, blank=True)
is_verified = models.BooleanField(default=False)
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
|
Add organization to cause model
|
Add organization to cause model
|
Python
|
mit
|
vladimiroff/humble-media,vladimiroff/humble-media
|
python
|
## Code Before:
from django.db import models
class Cause(models.Model):
title = models.CharField(max_length=64)
description = models.TextField()
creator = models.ForeignKey('auth.User', related_name='causes')
target = models.PositiveIntegerField(null=True, blank=True)
url = models.URLField(null=True, blank=True)
is_verified = models.BooleanField(default=False)
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
## Instruction:
Add organization to cause model
## Code After:
from django.db import models
class Cause(models.Model):
title = models.CharField(max_length=64)
description = models.TextField()
creator = models.ForeignKey('auth.User', related_name='causes')
organization = models.ForeignKey('organizations.Organization', related_name='causes', null=True, blank=True)
target = models.PositiveIntegerField(null=True, blank=True)
url = models.URLField(null=True, blank=True)
is_verified = models.BooleanField(default=False)
is_published = models.BooleanField(default=False)
def __str__(self):
return self.title
|
# ... existing code ...
title = models.CharField(max_length=64)
description = models.TextField()
creator = models.ForeignKey('auth.User', related_name='causes')
organization = models.ForeignKey('organizations.Organization', related_name='causes', null=True, blank=True)
target = models.PositiveIntegerField(null=True, blank=True)
url = models.URLField(null=True, blank=True)
is_verified = models.BooleanField(default=False)
# ... rest of the code ...
|
41e426457c93fc5e0a785614c090a24aaf2e37f5
|
py/foxgami/user.py
|
py/foxgami/user.py
|
from . import db
class Users(object):
@classmethod
def get_current(cls):
return {
'data': {
'id': 1,
'type': 'user',
'name': 'Albert Sheu',
'short_name': 'Albert',
'profile_image_url': 'https://google.com'
}
}
|
from . import db
class Users(object):
@classmethod
def get_current(cls):
return {
'data': {
'id': 1,
'type': 'user',
'name': 'Albert Sheu',
'short_name': 'Albert',
'profile_image_url': 'http://flubstep.com/images/sunglasses.jpg'
}
}
|
Make stub image url a real one
|
Make stub image url a real one
|
Python
|
mit
|
flubstep/foxgami.com,flubstep/foxgami.com
|
python
|
## Code Before:
from . import db
class Users(object):
@classmethod
def get_current(cls):
return {
'data': {
'id': 1,
'type': 'user',
'name': 'Albert Sheu',
'short_name': 'Albert',
'profile_image_url': 'https://google.com'
}
}
## Instruction:
Make stub image url a real one
## Code After:
from . import db
class Users(object):
@classmethod
def get_current(cls):
return {
'data': {
'id': 1,
'type': 'user',
'name': 'Albert Sheu',
'short_name': 'Albert',
'profile_image_url': 'http://flubstep.com/images/sunglasses.jpg'
}
}
|
...
'type': 'user',
'name': 'Albert Sheu',
'short_name': 'Albert',
'profile_image_url': 'http://flubstep.com/images/sunglasses.jpg'
}
}
...
|
c76474a6500f0c601a225a1ae42a3c80f5735de6
|
src/main/java/net/kleinhaneveld/fn/validations/Validations.java
|
src/main/java/net/kleinhaneveld/fn/validations/Validations.java
|
package net.kleinhaneveld.fn.validations;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
public abstract class Validations {
public static <T> T notNull(@CheckForNull T item) {
if (item == null) {
throw new NullPointerException();
}
return item;
}
public static <T> T notNull(@CheckForNull T item, @Nonnull String message) {
if (item == null) {
throw new NullPointerException(message);
}
return item;
}
}
|
package net.kleinhaneveld.fn.validations;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
public abstract class Validations {
public static <T> T notNull(@CheckForNull T item) {
if (item == null) {
throw new NullPointerException();
}
return item;
}
public static <T> T notNull(@CheckForNull T item, @Nonnull String message, @Nonnull String... args) {
if (item == null) {
throw new NullPointerException(String.format(message, args));
}
return item;
}
}
|
Allow formatting of error message for null check.
|
Allow formatting of error message for null check.
|
Java
|
mit
|
peterpaul/fn
|
java
|
## Code Before:
package net.kleinhaneveld.fn.validations;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
public abstract class Validations {
public static <T> T notNull(@CheckForNull T item) {
if (item == null) {
throw new NullPointerException();
}
return item;
}
public static <T> T notNull(@CheckForNull T item, @Nonnull String message) {
if (item == null) {
throw new NullPointerException(message);
}
return item;
}
}
## Instruction:
Allow formatting of error message for null check.
## Code After:
package net.kleinhaneveld.fn.validations;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
public abstract class Validations {
public static <T> T notNull(@CheckForNull T item) {
if (item == null) {
throw new NullPointerException();
}
return item;
}
public static <T> T notNull(@CheckForNull T item, @Nonnull String message, @Nonnull String... args) {
if (item == null) {
throw new NullPointerException(String.format(message, args));
}
return item;
}
}
|
# ... existing code ...
return item;
}
public static <T> T notNull(@CheckForNull T item, @Nonnull String message, @Nonnull String... args) {
if (item == null) {
throw new NullPointerException(String.format(message, args));
}
return item;
}
# ... rest of the code ...
|
41f74597752b259f7abf24b766e9b66b0d8449d0
|
genomics/sparkcaller/src/main/java/com/github/sparkcaller/preprocessing/BamIndexer.java
|
genomics/sparkcaller/src/main/java/com/github/sparkcaller/preprocessing/BamIndexer.java
|
package com.github.sparkcaller.preprocessing;
import htsjdk.samtools.BAMIndexer;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.apache.spark.api.java.function.Function;
import java.io.File;
public class BamIndexer implements Function<File, File> {
// Create an index (.bai) file for the given BAM file.
public File call(File bamFile) throws Exception {
final SamReader bamReader = SamReaderFactory.makeDefault()
.enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS)
.open(bamFile);
BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai"));
return bamFile;
}
}
|
package com.github.sparkcaller.preprocessing;
import htsjdk.samtools.BAMIndexer;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import java.io.File;
public class BamIndexer implements Function<File, File> {
// Create an index (.bai) file for the given BAM file.
public static void indexBam(File bamFile) throws Exception {
final SamReader bamReader = SamReaderFactory.makeDefault()
.enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS)
.open(bamFile);
BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai"));
}
@Override
public File call(File inputBAM) throws Exception {
BamIndexer.indexBam(inputBAM);
return inputBAM;
}
}
|
Make it easier to run the SAM indexer on a single file.
|
[Genomics]: Make it easier to run the SAM indexer on a single file.
|
Java
|
mit
|
UNINETT/daas-apps,UNINETT/daas-apps
|
java
|
## Code Before:
package com.github.sparkcaller.preprocessing;
import htsjdk.samtools.BAMIndexer;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.apache.spark.api.java.function.Function;
import java.io.File;
public class BamIndexer implements Function<File, File> {
// Create an index (.bai) file for the given BAM file.
public File call(File bamFile) throws Exception {
final SamReader bamReader = SamReaderFactory.makeDefault()
.enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS)
.open(bamFile);
BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai"));
return bamFile;
}
}
## Instruction:
[Genomics]: Make it easier to run the SAM indexer on a single file.
## Code After:
package com.github.sparkcaller.preprocessing;
import htsjdk.samtools.BAMIndexer;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import java.io.File;
public class BamIndexer implements Function<File, File> {
// Create an index (.bai) file for the given BAM file.
public static void indexBam(File bamFile) throws Exception {
final SamReader bamReader = SamReaderFactory.makeDefault()
.enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS)
.open(bamFile);
BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai"));
}
@Override
public File call(File inputBAM) throws Exception {
BamIndexer.indexBam(inputBAM);
return inputBAM;
}
}
|
# ... existing code ...
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import java.io.File;
public class BamIndexer implements Function<File, File> {
// Create an index (.bai) file for the given BAM file.
public static void indexBam(File bamFile) throws Exception {
final SamReader bamReader = SamReaderFactory.makeDefault()
.enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS)
.open(bamFile);
BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai"));
}
@Override
public File call(File inputBAM) throws Exception {
BamIndexer.indexBam(inputBAM);
return inputBAM;
}
}
# ... rest of the code ...
|
e392998022ec41b82276464ffecbd859d5e13c63
|
src/models/facility_monitoring.py
|
src/models/facility_monitoring.py
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class facility(object):
""" A Facility currently under monitoring
"""
def __init__(self , data) :
self.validated_data = data
def monitor_new_report(self) :
out = np.random.choice(['Validate' , 'Supervise - Data' , 'Supervise - Services' , 'Supervise - Data and Quality'])
return out
u = facility('a')
u.monitor_new_report()
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from reports_monitoring import *
store = pd.HDFStore('../../data/processed/orbf_benin.h5')
data_orbf = store['data']
store.close()
class facility(object):
""" A Facility currently under monitoring
"""
def __init__(self , data) :
self.validated_data = data
def monitor_new_report(self) :
out = np.random.choice(['Validate' , 'Supervise - Data' , 'Supervise - Services' , 'Supervise - Data and Quality'])
return out
def make_reports(self):
reports = {}
for month in list(data.date.unique()) :
reports[str(month)[:7]] = report(data[data.date == month])
self.reports = reports
return reports
|
Add report making for facility
|
Add report making for facility
|
Python
|
mit
|
grlurton/orbf_data_validation,grlurton/orbf_data_validation
|
python
|
## Code Before:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class facility(object):
""" A Facility currently under monitoring
"""
def __init__(self , data) :
self.validated_data = data
def monitor_new_report(self) :
out = np.random.choice(['Validate' , 'Supervise - Data' , 'Supervise - Services' , 'Supervise - Data and Quality'])
return out
u = facility('a')
u.monitor_new_report()
## Instruction:
Add report making for facility
## Code After:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from reports_monitoring import *
store = pd.HDFStore('../../data/processed/orbf_benin.h5')
data_orbf = store['data']
store.close()
class facility(object):
""" A Facility currently under monitoring
"""
def __init__(self , data) :
self.validated_data = data
def monitor_new_report(self) :
out = np.random.choice(['Validate' , 'Supervise - Data' , 'Supervise - Services' , 'Supervise - Data and Quality'])
return out
def make_reports(self):
reports = {}
for month in list(data.date.unique()) :
reports[str(month)[:7]] = report(data[data.date == month])
self.reports = reports
return reports
|
# ... existing code ...
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from reports_monitoring import *
store = pd.HDFStore('../../data/processed/orbf_benin.h5')
data_orbf = store['data']
store.close()
class facility(object):
""" A Facility currently under monitoring
# ... modified code ...
out = np.random.choice(['Validate' , 'Supervise - Data' , 'Supervise - Services' , 'Supervise - Data and Quality'])
return out
def make_reports(self):
reports = {}
for month in list(data.date.unique()) :
reports[str(month)[:7]] = report(data[data.date == month])
self.reports = reports
return reports
# ... rest of the code ...
|
12ec1cf9084789b9e2022eb0d1d55b553db06cb5
|
tests/test_util.py
|
tests/test_util.py
|
import util
from nose.tools import assert_equal
class TestPick():
def check(self, filenames, expected, k, randomized):
result = util.pick(filenames, k, randomized)
assert_equal(result, expected)
def test_all_sequential(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
expected = ['e-0.txt', 'd-1.txt', 'b-2.txt', 'c-3.txt', 'a-4.txt']
self.check(filenames, expected, k=None, randomized=False)
|
import util
from nose.tools import assert_equal, assert_true, raises
class TestPick():
def test_all_sequential(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
expected = ['e-0.txt', 'd-1.txt', 'b-2.txt', 'c-3.txt', 'a-4.txt']
result = util.pick(filenames, randomized=False)
assert_equal(result, expected)
def test_k_sequential(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
expected = ['e-0.txt', 'd-1.txt', 'b-2.txt']
result = util.pick(filenames, k=3, randomized=False)
assert_equal(result, expected)
def test_all_random(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
result = util.pick(filenames)
assert_equal(sorted(filenames), sorted(result))
def test_k_random(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
result = util.pick(filenames, k=3)
for r in result:
assert_true(r in filenames)
@raises(ValueError)
def test_negative_k(self):
util.pick([], k=-2)
|
Fix unit test for util.py
|
Fix unit test for util.py
|
Python
|
mit
|
kemskems/otdet
|
python
|
## Code Before:
import util
from nose.tools import assert_equal
class TestPick():
def check(self, filenames, expected, k, randomized):
result = util.pick(filenames, k, randomized)
assert_equal(result, expected)
def test_all_sequential(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
expected = ['e-0.txt', 'd-1.txt', 'b-2.txt', 'c-3.txt', 'a-4.txt']
self.check(filenames, expected, k=None, randomized=False)
## Instruction:
Fix unit test for util.py
## Code After:
import util
from nose.tools import assert_equal, assert_true, raises
class TestPick():
def test_all_sequential(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
expected = ['e-0.txt', 'd-1.txt', 'b-2.txt', 'c-3.txt', 'a-4.txt']
result = util.pick(filenames, randomized=False)
assert_equal(result, expected)
def test_k_sequential(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
expected = ['e-0.txt', 'd-1.txt', 'b-2.txt']
result = util.pick(filenames, k=3, randomized=False)
assert_equal(result, expected)
def test_all_random(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
result = util.pick(filenames)
assert_equal(sorted(filenames), sorted(result))
def test_k_random(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
result = util.pick(filenames, k=3)
for r in result:
assert_true(r in filenames)
@raises(ValueError)
def test_negative_k(self):
util.pick([], k=-2)
|
...
import util
from nose.tools import assert_equal, assert_true, raises
class TestPick():
def test_all_sequential(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
expected = ['e-0.txt', 'd-1.txt', 'b-2.txt', 'c-3.txt', 'a-4.txt']
result = util.pick(filenames, randomized=False)
assert_equal(result, expected)
def test_k_sequential(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
expected = ['e-0.txt', 'd-1.txt', 'b-2.txt']
result = util.pick(filenames, k=3, randomized=False)
assert_equal(result, expected)
def test_all_random(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
result = util.pick(filenames)
assert_equal(sorted(filenames), sorted(result))
def test_k_random(self):
filenames = ['a-4.txt', 'b-2.txt', 'c-3.txt', 'd-1.txt', 'e-0.txt']
result = util.pick(filenames, k=3)
for r in result:
assert_true(r in filenames)
@raises(ValueError)
def test_negative_k(self):
util.pick([], k=-2)
...
|
51caae36a10cf5616982c78506c5dcec593259a3
|
test_suite.py
|
test_suite.py
|
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
from django.core import management
apps = [
'test',
'core',
'exporting',
'formatters',
'lexicon',
'events',
'history',
'models',
'query',
'sets',
'stats',
'search',
'subcommands',
'validation',
]
management.call_command(*apps)
|
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
from django.core import management
apps = sys.argv[1:]
if not apps:
apps = [
'core',
'exporting',
'formatters',
'lexicon',
'events',
'history',
'models',
'query',
'sets',
'stats',
'search',
'subcommands',
'validation',
]
management.call_command('test', *apps)
|
Allow apps to be specified from the command line
|
Allow apps to be specified from the command line
|
Python
|
bsd-2-clause
|
murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado
|
python
|
## Code Before:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
from django.core import management
apps = [
'test',
'core',
'exporting',
'formatters',
'lexicon',
'events',
'history',
'models',
'query',
'sets',
'stats',
'search',
'subcommands',
'validation',
]
management.call_command(*apps)
## Instruction:
Allow apps to be specified from the command line
## Code After:
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
from django.core import management
apps = sys.argv[1:]
if not apps:
apps = [
'core',
'exporting',
'formatters',
'lexicon',
'events',
'history',
'models',
'query',
'sets',
'stats',
'search',
'subcommands',
'validation',
]
management.call_command('test', *apps)
|
# ... existing code ...
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
from django.core import management
apps = sys.argv[1:]
if not apps:
apps = [
'core',
'exporting',
'formatters',
'lexicon',
'events',
'history',
'models',
'query',
'sets',
'stats',
'search',
'subcommands',
'validation',
]
management.call_command('test', *apps)
# ... rest of the code ...
|
234de60b643c9cdd37bd650df20f123d32187e86
|
aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecAudioSpan.kt
|
aztec/src/main/kotlin/org/wordpress/aztec/spans/AztecAudioSpan.kt
|
package org.wordpress.aztec.spans
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.view.Gravity
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.AztecText
class AztecAudioSpan(context: Context, drawable: Drawable?, override var nestingLevel: Int,
attributes: AztecAttributes = AztecAttributes(),
var onAudioTappedListener: AztecText.OnAudioTappedListener? = null,
editor: AztecText? = null) :
AztecMediaSpan(context, drawable, attributes, editor), IAztecFullWidthImageSpan, IAztecSpan {
override val TAG: String = "audio"
init {
setOverlay(0, ContextCompat.getDrawable(context, android.R.drawable.ic_menu_call), Gravity.CENTER)
}
override fun onClick() {
onAudioTappedListener?.onAudioTapped(attributes)
}
}
|
package org.wordpress.aztec.spans
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.view.Gravity
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.AztecText
class AztecAudioSpan(context: Context, drawable: Drawable?, override var nestingLevel: Int,
attributes: AztecAttributes = AztecAttributes(),
var onAudioTappedListener: AztecText.OnAudioTappedListener? = null,
editor: AztecText? = null) :
AztecMediaSpan(context, drawable, attributes, editor), IAztecFullWidthImageSpan, IAztecSpan {
override val TAG: String = "audio"
init {
setOverlay(0, ContextCompat.getDrawable(context, android.R.drawable.ic_lock_silent_mode_off), Gravity.CENTER)
}
override fun onClick() {
onAudioTappedListener?.onAudioTapped(attributes)
}
}
|
Use better audio span overlay icon
|
Use better audio span overlay icon
|
Kotlin
|
mpl-2.0
|
wordpress-mobile/AztecEditor-Android,wordpress-mobile/AztecEditor-Android,wordpress-mobile/AztecEditor-Android
|
kotlin
|
## Code Before:
package org.wordpress.aztec.spans
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.view.Gravity
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.AztecText
class AztecAudioSpan(context: Context, drawable: Drawable?, override var nestingLevel: Int,
attributes: AztecAttributes = AztecAttributes(),
var onAudioTappedListener: AztecText.OnAudioTappedListener? = null,
editor: AztecText? = null) :
AztecMediaSpan(context, drawable, attributes, editor), IAztecFullWidthImageSpan, IAztecSpan {
override val TAG: String = "audio"
init {
setOverlay(0, ContextCompat.getDrawable(context, android.R.drawable.ic_menu_call), Gravity.CENTER)
}
override fun onClick() {
onAudioTappedListener?.onAudioTapped(attributes)
}
}
## Instruction:
Use better audio span overlay icon
## Code After:
package org.wordpress.aztec.spans
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.view.Gravity
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.AztecText
class AztecAudioSpan(context: Context, drawable: Drawable?, override var nestingLevel: Int,
attributes: AztecAttributes = AztecAttributes(),
var onAudioTappedListener: AztecText.OnAudioTappedListener? = null,
editor: AztecText? = null) :
AztecMediaSpan(context, drawable, attributes, editor), IAztecFullWidthImageSpan, IAztecSpan {
override val TAG: String = "audio"
init {
setOverlay(0, ContextCompat.getDrawable(context, android.R.drawable.ic_lock_silent_mode_off), Gravity.CENTER)
}
override fun onClick() {
onAudioTappedListener?.onAudioTapped(attributes)
}
}
|
...
override val TAG: String = "audio"
init {
setOverlay(0, ContextCompat.getDrawable(context, android.R.drawable.ic_lock_silent_mode_off), Gravity.CENTER)
}
override fun onClick() {
...
|
2ed4f3281764476a7a4ddeb44059b563ba19655b
|
src/main/java/backend/controller/EventController.kt
|
src/main/java/backend/controller/EventController.kt
|
package backend.controller
import backend.model.event.EventService
import backend.model.misc.Coords
import backend.view.EventView
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
import java.time.ZoneOffset
import kotlin.collections.map
@RestController
@RequestMapping("/event")
class EventController {
val eventService: EventService
@Autowired
constructor(eventService: EventService) {
this.eventService = eventService
}
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.POST),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun createEvent(@RequestBody body: EventView): EventView {
val event = eventService.createEvent(
title = body.title!!,
date = LocalDateTime.ofEpochSecond(body.date!!, 0, ZoneOffset.UTC),
city = body.city!!,
duration = body.duration,
startingLocation = Coords(body.startingLocation!!.latitude!!, body.startingLocation!!.longitude!!))
return EventView(event)
}
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.GET),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun getAllEvents(): Iterable<EventView> {
return eventService.findAll().map { EventView(it) }
}
}
|
package backend.controller
import backend.model.event.EventService
import backend.model.misc.Coords
import backend.view.EventView
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
import java.time.ZoneOffset
import javax.validation.Valid
import kotlin.collections.map
@RestController
@RequestMapping("/event")
class EventController {
val eventService: EventService
@Autowired
constructor(eventService: EventService) {
this.eventService = eventService
}
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.POST),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun createEvent(@Valid @RequestBody body: EventView): EventView {
val event = eventService.createEvent(
title = body.title!!,
date = LocalDateTime.ofEpochSecond(body.date!!, 0, ZoneOffset.UTC),
city = body.city!!,
duration = body.duration,
startingLocation = Coords(body.startingLocation!!.latitude!!, body.startingLocation!!.longitude!!))
return EventView(event)
}
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.GET),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun getAllEvents(): Iterable<EventView> {
return eventService.findAll().map { EventView(it) }
}
}
|
Validate Body of API Request for creating events
|
Validate Body of API Request for creating events
|
Kotlin
|
agpl-3.0
|
BreakOutEvent/breakout-backend,BreakOutEvent/breakout-backend,BreakOutEvent/breakout-backend
|
kotlin
|
## Code Before:
package backend.controller
import backend.model.event.EventService
import backend.model.misc.Coords
import backend.view.EventView
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
import java.time.ZoneOffset
import kotlin.collections.map
@RestController
@RequestMapping("/event")
class EventController {
val eventService: EventService
@Autowired
constructor(eventService: EventService) {
this.eventService = eventService
}
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.POST),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun createEvent(@RequestBody body: EventView): EventView {
val event = eventService.createEvent(
title = body.title!!,
date = LocalDateTime.ofEpochSecond(body.date!!, 0, ZoneOffset.UTC),
city = body.city!!,
duration = body.duration,
startingLocation = Coords(body.startingLocation!!.latitude!!, body.startingLocation!!.longitude!!))
return EventView(event)
}
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.GET),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun getAllEvents(): Iterable<EventView> {
return eventService.findAll().map { EventView(it) }
}
}
## Instruction:
Validate Body of API Request for creating events
## Code After:
package backend.controller
import backend.model.event.EventService
import backend.model.misc.Coords
import backend.view.EventView
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
import java.time.ZoneOffset
import javax.validation.Valid
import kotlin.collections.map
@RestController
@RequestMapping("/event")
class EventController {
val eventService: EventService
@Autowired
constructor(eventService: EventService) {
this.eventService = eventService
}
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.POST),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun createEvent(@Valid @RequestBody body: EventView): EventView {
val event = eventService.createEvent(
title = body.title!!,
date = LocalDateTime.ofEpochSecond(body.date!!, 0, ZoneOffset.UTC),
city = body.city!!,
duration = body.duration,
startingLocation = Coords(body.startingLocation!!.latitude!!, body.startingLocation!!.longitude!!))
return EventView(event)
}
@RequestMapping(
value = "/",
method = arrayOf(RequestMethod.GET),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun getAllEvents(): Iterable<EventView> {
return eventService.findAll().map { EventView(it) }
}
}
|
# ... existing code ...
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
import java.time.ZoneOffset
import javax.validation.Valid
import kotlin.collections.map
@RestController
# ... modified code ...
value = "/",
method = arrayOf(RequestMethod.POST),
produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
fun createEvent(@Valid @RequestBody body: EventView): EventView {
val event = eventService.createEvent(
title = body.title!!,
# ... rest of the code ...
|
c7ee376f947ec1d3e81d49e2c4a81adf1c292c1d
|
libc/sysdeps/linux/common/getrusage.c
|
libc/sysdeps/linux/common/getrusage.c
|
/* vi: set sw=4 ts=4: */
/*
* getrusage() for uClibc
*
* Copyright (C) 2000-2004 by Erik Andersen <[email protected]>
*
* GNU Library General Public License (LGPL) version 2 or later.
*/
#include "syscalls.h"
#include <unistd.h>
#include <wait.h>
_syscall2(int, getrusage, int, who, struct rusage *, usage);
|
/* vi: set sw=4 ts=4: */
/*
* getrusage() for uClibc
*
* Copyright (C) 2000-2004 by Erik Andersen <[email protected]>
*
* GNU Library General Public License (LGPL) version 2 or later.
*/
#include "syscalls.h"
#include <unistd.h>
#include <wait.h>
_syscall2(int, getrusage, __rusage_who_t, who, struct rusage *, usage);
|
Correct type, gcc-3.4.5 fails, thanks nitinkg for reporting/testing
|
Correct type, gcc-3.4.5 fails, thanks nitinkg for reporting/testing
|
C
|
lgpl-2.1
|
foss-for-synopsys-dwc-arc-processors/uClibc,ChickenRunjyd/klee-uclibc,ysat0/uClibc,foss-for-synopsys-dwc-arc-processors/uClibc,brgl/uclibc-ng,ChickenRunjyd/klee-uclibc,ysat0/uClibc,kraj/uClibc,ndmsystems/uClibc,wbx-github/uclibc-ng,majek/uclibc-vx32,hjl-tools/uClibc,mephi42/uClibc,hwoarang/uClibc,ndmsystems/uClibc,czankel/xtensa-uclibc,hwoarang/uClibc,OpenInkpot-archive/iplinux-uclibc,ChickenRunjyd/klee-uclibc,hwoarang/uClibc,hjl-tools/uClibc,atgreen/uClibc-moxie,ffainelli/uClibc,ddcc/klee-uclibc-0.9.33.2,hwoarang/uClibc,kraj/uclibc-ng,czankel/xtensa-uclibc,waweber/uclibc-clang,klee/klee-uclibc,foss-xtensa/uClibc,ffainelli/uClibc,groundwater/uClibc,foss-xtensa/uClibc,kraj/uClibc,skristiansson/uClibc-or1k,kraj/uclibc-ng,wbx-github/uclibc-ng,waweber/uclibc-clang,foss-xtensa/uClibc,skristiansson/uClibc-or1k,gittup/uClibc,atgreen/uClibc-moxie,ysat0/uClibc,hjl-tools/uClibc,wbx-github/uclibc-ng,kraj/uClibc,klee/klee-uclibc,klee/klee-uclibc,hjl-tools/uClibc,OpenInkpot-archive/iplinux-uclibc,ddcc/klee-uclibc-0.9.33.2,kraj/uclibc-ng,majek/uclibc-vx32,foss-for-synopsys-dwc-arc-processors/uClibc,ffainelli/uClibc,m-labs/uclibc-lm32,ndmsystems/uClibc,majek/uclibc-vx32,groundwater/uClibc,mephi42/uClibc,brgl/uclibc-ng,groundwater/uClibc,kraj/uclibc-ng,gittup/uClibc,atgreen/uClibc-moxie,czankel/xtensa-uclibc,m-labs/uclibc-lm32,ddcc/klee-uclibc-0.9.33.2,hjl-tools/uClibc,kraj/uClibc,waweber/uclibc-clang,brgl/uclibc-ng,groundwater/uClibc,m-labs/uclibc-lm32,waweber/uclibc-clang,ffainelli/uClibc,ffainelli/uClibc,foss-xtensa/uClibc,OpenInkpot-archive/iplinux-uclibc,czankel/xtensa-uclibc,gittup/uClibc,brgl/uclibc-ng,gittup/uClibc,skristiansson/uClibc-or1k,m-labs/uclibc-lm32,foss-for-synopsys-dwc-arc-processors/uClibc,skristiansson/uClibc-or1k,atgreen/uClibc-moxie,majek/uclibc-vx32,groundwater/uClibc,OpenInkpot-archive/iplinux-uclibc,ChickenRunjyd/klee-uclibc,ddcc/klee-uclibc-0.9.33.2,ysat0/uClibc,klee/klee-uclibc,wbx-github/uclibc-ng,mephi42/uClibc,ndmsystems/uClibc,mephi42/uClibc
|
c
|
## Code Before:
/* vi: set sw=4 ts=4: */
/*
* getrusage() for uClibc
*
* Copyright (C) 2000-2004 by Erik Andersen <[email protected]>
*
* GNU Library General Public License (LGPL) version 2 or later.
*/
#include "syscalls.h"
#include <unistd.h>
#include <wait.h>
_syscall2(int, getrusage, int, who, struct rusage *, usage);
## Instruction:
Correct type, gcc-3.4.5 fails, thanks nitinkg for reporting/testing
## Code After:
/* vi: set sw=4 ts=4: */
/*
* getrusage() for uClibc
*
* Copyright (C) 2000-2004 by Erik Andersen <[email protected]>
*
* GNU Library General Public License (LGPL) version 2 or later.
*/
#include "syscalls.h"
#include <unistd.h>
#include <wait.h>
_syscall2(int, getrusage, __rusage_who_t, who, struct rusage *, usage);
|
...
#include "syscalls.h"
#include <unistd.h>
#include <wait.h>
_syscall2(int, getrusage, __rusage_who_t, who, struct rusage *, usage);
...
|
45e7904ad73a41660e38b2a5553e3a24fc1d1d06
|
Classes/EPSPlayerViewModel.h
|
Classes/EPSPlayerViewModel.h
|
//
// EPSPlayerViewModel.h
// ReactiveAudioPlayer
//
// Created by Peter Stuart on 4/24/14.
// Copyright (c) 2014 Electric Peel, LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
@interface EPSPlayerViewModel : NSObject
@property (nonatomic) NSURL *audioURL;
@property (readonly) NSTimeInterval duration;
@property (readonly) NSTimeInterval currentTime;
@property (readonly) NSString *elapsedTimeString;
@property (readonly) NSString *remainingTimeString;
@property (readonly, getter = isPlaying) BOOL playing;
// Commands
@property (readonly) RACCommand *playCommand;
@property (readonly) RACCommand *pauseCommand;
@property (readonly) RACCommand *togglePlayPauseCommand;
@property (nonatomic, getter = isSeeking) BOOL seeking;
- (void)seekToTime:(NSTimeInterval)time;
@end
|
//
// EPSPlayerViewModel.h
// ReactiveAudioPlayer
//
// Created by Peter Stuart on 4/24/14.
// Copyright (c) 2014 Electric Peel, LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
#import <AVFoundation/AVFoundation.h>
@interface EPSPlayerViewModel : NSObject
@property (nonatomic) NSURL *audioURL;
@property (readonly) AVPlayer *player;
@property (readonly) NSTimeInterval duration;
@property (readonly) NSTimeInterval currentTime;
@property (readonly) NSString *elapsedTimeString;
@property (readonly) NSString *remainingTimeString;
@property (readonly, getter = isPlaying) BOOL playing;
// Commands
@property (readonly) RACCommand *playCommand;
@property (readonly) RACCommand *pauseCommand;
@property (readonly) RACCommand *togglePlayPauseCommand;
@property (nonatomic, getter = isSeeking) BOOL seeking;
- (void)seekToTime:(NSTimeInterval)time;
@end
|
Make the audio player a public property.
|
Make the audio player a public property.
|
C
|
mit
|
ElectricPeelSoftware/EPSReactiveAudioPlayer
|
c
|
## Code Before:
//
// EPSPlayerViewModel.h
// ReactiveAudioPlayer
//
// Created by Peter Stuart on 4/24/14.
// Copyright (c) 2014 Electric Peel, LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
@interface EPSPlayerViewModel : NSObject
@property (nonatomic) NSURL *audioURL;
@property (readonly) NSTimeInterval duration;
@property (readonly) NSTimeInterval currentTime;
@property (readonly) NSString *elapsedTimeString;
@property (readonly) NSString *remainingTimeString;
@property (readonly, getter = isPlaying) BOOL playing;
// Commands
@property (readonly) RACCommand *playCommand;
@property (readonly) RACCommand *pauseCommand;
@property (readonly) RACCommand *togglePlayPauseCommand;
@property (nonatomic, getter = isSeeking) BOOL seeking;
- (void)seekToTime:(NSTimeInterval)time;
@end
## Instruction:
Make the audio player a public property.
## Code After:
//
// EPSPlayerViewModel.h
// ReactiveAudioPlayer
//
// Created by Peter Stuart on 4/24/14.
// Copyright (c) 2014 Electric Peel, LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
#import <AVFoundation/AVFoundation.h>
@interface EPSPlayerViewModel : NSObject
@property (nonatomic) NSURL *audioURL;
@property (readonly) AVPlayer *player;
@property (readonly) NSTimeInterval duration;
@property (readonly) NSTimeInterval currentTime;
@property (readonly) NSString *elapsedTimeString;
@property (readonly) NSString *remainingTimeString;
@property (readonly, getter = isPlaying) BOOL playing;
// Commands
@property (readonly) RACCommand *playCommand;
@property (readonly) RACCommand *pauseCommand;
@property (readonly) RACCommand *togglePlayPauseCommand;
@property (nonatomic, getter = isSeeking) BOOL seeking;
- (void)seekToTime:(NSTimeInterval)time;
@end
|
// ... existing code ...
#import <Foundation/Foundation.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
#import <AVFoundation/AVFoundation.h>
@interface EPSPlayerViewModel : NSObject
@property (nonatomic) NSURL *audioURL;
@property (readonly) AVPlayer *player;
@property (readonly) NSTimeInterval duration;
// ... rest of the code ...
|
2d5152e72e1813ee7bf040f4033d369d60a44cc2
|
pipeline/compute_rpp/compute_rpp.py
|
pipeline/compute_rpp/compute_rpp.py
|
import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path = sys.argv[2]
# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
for file in files:
if file.endswith('.fit'):
filenames.append(os.path.join(root, file))
max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
# Open the file
power_ride = load_power_from_fit(filename)
# Fit the ride
rpp_rider.fit(power_ride)
# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
os.makedirs(storage_path)
# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)
|
import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.restoration import denoise
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path = sys.argv[2]
# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
for file in files:
if file.endswith('.fit'):
filenames.append(os.path.join(root, file))
max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
# Open the file
power_ride = load_power_from_fit(filename)
# Reject the outliers using thresholding method
power_ride = denoise.outliers_rejection(power_ride)
# Fit the ride
rpp_rider.fit(power_ride)
# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
os.makedirs(storage_path)
# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)
|
Update the pipeline to take into account the outlier rejection method to compute the RPP
|
Update the pipeline to take into account the outlier rejection method to compute the RPP
|
Python
|
mit
|
glemaitre/power-profile,glemaitre/power-profile,clemaitre58/power-profile,clemaitre58/power-profile
|
python
|
## Code Before:
import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path = sys.argv[2]
# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
for file in files:
if file.endswith('.fit'):
filenames.append(os.path.join(root, file))
max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
# Open the file
power_ride = load_power_from_fit(filename)
# Fit the ride
rpp_rider.fit(power_ride)
# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
os.makedirs(storage_path)
# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)
## Instruction:
Update the pipeline to take into account the outlier rejection method to compute the RPP
## Code After:
import sys
import os
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.restoration import denoise
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
data_path = sys.argv[1]
# The second input argument is the storage directory
storage_path = sys.argv[2]
# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
for file in files:
if file.endswith('.fit'):
filenames.append(os.path.join(root, file))
max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
# Open the file
power_ride = load_power_from_fit(filename)
# Reject the outliers using thresholding method
power_ride = denoise.outliers_rejection(power_ride)
# Fit the ride
rpp_rider.fit(power_ride)
# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
os.makedirs(storage_path)
# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)
|
# ... existing code ...
import numpy as np
from skcycling.utils import load_power_from_fit
from skcycling.restoration import denoise
from skcycling.power_profile import Rpp
# The first input argument corresponding to the data path
# ... modified code ...
print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
# Open the file
power_ride = load_power_from_fit(filename)
# Reject the outliers using thresholding method
power_ride = denoise.outliers_rejection(power_ride)
# Fit the ride
rpp_rider.fit(power_ride)
# ... rest of the code ...
|
2e54c8050f994646e7cbf9f18c9ab557341ec3f5
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name="IIS",
version="0.0",
long_description=__doc__,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
"Flask>=0.11.1,<0.12.0",
"Flask-Bootstrap>=3.3.7.0,<4.0.0.0",
"Flask-Login>=0.3.2,<0.4.0",
"Flask-Mail>=0.9.1,<0.10.0",
"Flask-SQLAlchemy>=2.1,<3.0",
"Flask-User>=0.6.8,<0.7.0",
"Flask-WTF>=0.12,<0.13.0",
"Flask-Migrate>=2.0.0,<3.0.0",
"Flask-Testing>=0.6.1,<0.7.0"
],
extras_require={
'dev': [
'mypy-lang>=0.4.4,<0.5.0'
]
}
)
|
from setuptools import setup, find_packages
setup(
name="IIS",
version="0.0",
long_description=__doc__,
packages=find_packages(exclude=["tests.*", "tests"]),
include_package_data=True,
zip_safe=False,
install_requires=[
"Flask>=0.11.1,<0.12.0",
"Flask-Bootstrap>=3.3.7.0,<4.0.0.0",
"Flask-Login>=0.3.2,<0.4.0",
"Flask-Mail>=0.9.1,<0.10.0",
"Flask-SQLAlchemy>=2.1,<3.0",
"Flask-User>=0.6.8,<0.7.0",
"Flask-WTF>=0.12,<0.13.0",
"Flask-Migrate>=2.0.0,<3.0.0",
"Flask-Testing>=0.6.1,<0.7.0"
],
extras_require={
'dev': [
'mypy-lang>=0.4.4,<0.5.0'
]
}
)
|
Exclude tests from installed packages
|
Exclude tests from installed packages
|
Python
|
agpl-3.0
|
interactomix/iis,interactomix/iis
|
python
|
## Code Before:
from setuptools import setup, find_packages
setup(
name="IIS",
version="0.0",
long_description=__doc__,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
"Flask>=0.11.1,<0.12.0",
"Flask-Bootstrap>=3.3.7.0,<4.0.0.0",
"Flask-Login>=0.3.2,<0.4.0",
"Flask-Mail>=0.9.1,<0.10.0",
"Flask-SQLAlchemy>=2.1,<3.0",
"Flask-User>=0.6.8,<0.7.0",
"Flask-WTF>=0.12,<0.13.0",
"Flask-Migrate>=2.0.0,<3.0.0",
"Flask-Testing>=0.6.1,<0.7.0"
],
extras_require={
'dev': [
'mypy-lang>=0.4.4,<0.5.0'
]
}
)
## Instruction:
Exclude tests from installed packages
## Code After:
from setuptools import setup, find_packages
setup(
name="IIS",
version="0.0",
long_description=__doc__,
packages=find_packages(exclude=["tests.*", "tests"]),
include_package_data=True,
zip_safe=False,
install_requires=[
"Flask>=0.11.1,<0.12.0",
"Flask-Bootstrap>=3.3.7.0,<4.0.0.0",
"Flask-Login>=0.3.2,<0.4.0",
"Flask-Mail>=0.9.1,<0.10.0",
"Flask-SQLAlchemy>=2.1,<3.0",
"Flask-User>=0.6.8,<0.7.0",
"Flask-WTF>=0.12,<0.13.0",
"Flask-Migrate>=2.0.0,<3.0.0",
"Flask-Testing>=0.6.1,<0.7.0"
],
extras_require={
'dev': [
'mypy-lang>=0.4.4,<0.5.0'
]
}
)
|
...
name="IIS",
version="0.0",
long_description=__doc__,
packages=find_packages(exclude=["tests.*", "tests"]),
include_package_data=True,
zip_safe=False,
install_requires=[
...
|
45d442cfe9c737332ca75e68e1488667937015ed
|
src/repository/models.py
|
src/repository/models.py
|
from django.db import models
import git, os
class Github (models.Model):
username = models.CharField(max_length=39)
repository = models.CharField(max_length=100)
def __str__(self):
return self.repository
def clone_repository(self):
DIR_NAME = self.repository
REMOTE_URL = "https://github.com/{0}/{1}.git".format(self.username, self.repository)
os.mkdir(DIR_NAME)
repo = git.Repo.init(DIR_NAME)
origin = repo.create_remote('origin', REMOTE_URL)
origin.fetch()
origin.pull(origin.refs[0].remote_head)
def save(self, *args, **kwargs):
self.clone_repository()
super(Github, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = "projects"
|
from django.db import models
from django.conf import settings
import git, os
class Github (models.Model):
username = models.CharField(max_length=39)
repository = models.CharField(max_length=100)
def __str__(self):
return self.repository
def clone_repository(self):
DIR_NAME = os.path.join(settings.PLAYBOOK_DIR, self.repository)
REMOTE_URL = "https://github.com/{0}/{1}.git".format(self.username, self.repository)
os.mkdir(os.path.join(DIR_NAME))
repo = git.Repo.init(DIR_NAME)
origin = repo.create_remote('origin', REMOTE_URL)
origin.fetch()
origin.pull(origin.refs[0].remote_head)
def save(self, *args, **kwargs):
self.clone_repository()
super(Github, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = "projects"
|
Clone repository to playbooks directory
|
Clone repository to playbooks directory
|
Python
|
bsd-3-clause
|
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
|
python
|
## Code Before:
from django.db import models
import git, os
class Github (models.Model):
username = models.CharField(max_length=39)
repository = models.CharField(max_length=100)
def __str__(self):
return self.repository
def clone_repository(self):
DIR_NAME = self.repository
REMOTE_URL = "https://github.com/{0}/{1}.git".format(self.username, self.repository)
os.mkdir(DIR_NAME)
repo = git.Repo.init(DIR_NAME)
origin = repo.create_remote('origin', REMOTE_URL)
origin.fetch()
origin.pull(origin.refs[0].remote_head)
def save(self, *args, **kwargs):
self.clone_repository()
super(Github, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = "projects"
## Instruction:
Clone repository to playbooks directory
## Code After:
from django.db import models
from django.conf import settings
import git, os
class Github (models.Model):
username = models.CharField(max_length=39)
repository = models.CharField(max_length=100)
def __str__(self):
return self.repository
def clone_repository(self):
DIR_NAME = os.path.join(settings.PLAYBOOK_DIR, self.repository)
REMOTE_URL = "https://github.com/{0}/{1}.git".format(self.username, self.repository)
os.mkdir(os.path.join(DIR_NAME))
repo = git.Repo.init(DIR_NAME)
origin = repo.create_remote('origin', REMOTE_URL)
origin.fetch()
origin.pull(origin.refs[0].remote_head)
def save(self, *args, **kwargs):
self.clone_repository()
super(Github, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = "projects"
|
# ... existing code ...
from django.db import models
from django.conf import settings
import git, os
class Github (models.Model):
# ... modified code ...
return self.repository
def clone_repository(self):
DIR_NAME = os.path.join(settings.PLAYBOOK_DIR, self.repository)
REMOTE_URL = "https://github.com/{0}/{1}.git".format(self.username, self.repository)
os.mkdir(os.path.join(DIR_NAME))
repo = git.Repo.init(DIR_NAME)
origin = repo.create_remote('origin', REMOTE_URL)
# ... rest of the code ...
|
0f8c4cd71bff68860d0a18f8680eda9a690f0959
|
sqlstr/exception.py
|
sqlstr/exception.py
|
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
:message str:
'''
Exception.__init__(self, message)
|
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
|
Update docstring with parameter listing
|
Update docstring with parameter listing
|
Python
|
mit
|
GochoMugo/sql-string-templating
|
python
|
## Code Before:
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
:message str:
'''
Exception.__init__(self, message)
## Instruction:
Update docstring with parameter listing
## Code After:
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
|
# ... existing code ...
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
# ... rest of the code ...
|
9fb8b0a72740ba155c76a5812706612b656980f4
|
openprocurement/auctions/flash/constants.py
|
openprocurement/auctions/flash/constants.py
|
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
"openprocurement.auctions.core.plugins",
]
|
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
]
|
Add view_locations for plugins in core
|
Add view_locations for plugins in core
|
Python
|
apache-2.0
|
openprocurement/openprocurement.auctions.flash
|
python
|
## Code Before:
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
"openprocurement.auctions.core.plugins",
]
## Instruction:
Add view_locations for plugins in core
## Code After:
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
]
|
// ... existing code ...
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
]
// ... rest of the code ...
|
cfabcbe0e729eeb3281c4f4b7d6182a29d35f37e
|
ixprofile_client/fetchers.py
|
ixprofile_client/fetchers.py
|
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import inspect
import sys
import urllib.request
from openid.fetchers import Urllib2Fetcher
class SettingsAwareFetcher(Urllib2Fetcher):
"""
An URL fetcher for python-openid to verify the certificates against
SSL_CA_FILE in Django settings.
"""
@staticmethod
def urlopen(*args, **kwargs):
"""
Provide urlopen with the trusted certificate path.
"""
# Old versions of urllib2 cannot verify certificates
if sys.version_info >= (3, 0) or \
'cafile' in inspect.getargspec(urllib.request.urlopen).args:
from django.conf import settings
if hasattr(settings, 'SSL_CA_FILE'):
kwargs['cafile'] = settings.SSL_CA_FILE
return urllib.request.urlopen(*args, **kwargs)
|
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import inspect
import sys
PY3 = sys.version_info >= (3, 0)
# Important: python3-open uses urllib.request, whereas (python2) openid uses
# urllib2. You cannot use the compatibility layer here.
if PY3:
from urllib.request import urlopen
else:
from urllib2 import urlopen
from openid.fetchers import Urllib2Fetcher
class SettingsAwareFetcher(Urllib2Fetcher):
"""
An URL fetcher for python-openid to verify the certificates against
SSL_CA_FILE in Django settings.
"""
@staticmethod
def urlopen(*args, **kwargs):
"""
Provide urlopen with the trusted certificate path.
"""
# Old versions of urllib2 cannot verify certificates
if PY3 or 'cafile' in inspect.getargspec(urlopen).args:
from django.conf import settings
if hasattr(settings, 'SSL_CA_FILE'):
kwargs['cafile'] = settings.SSL_CA_FILE
return urlopen(*args, **kwargs)
|
Use the correct urllib for the openid we're using
|
Use the correct urllib for the openid we're using
|
Python
|
mit
|
infoxchange/ixprofile-client,infoxchange/ixprofile-client
|
python
|
## Code Before:
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import inspect
import sys
import urllib.request
from openid.fetchers import Urllib2Fetcher
class SettingsAwareFetcher(Urllib2Fetcher):
"""
An URL fetcher for python-openid to verify the certificates against
SSL_CA_FILE in Django settings.
"""
@staticmethod
def urlopen(*args, **kwargs):
"""
Provide urlopen with the trusted certificate path.
"""
# Old versions of urllib2 cannot verify certificates
if sys.version_info >= (3, 0) or \
'cafile' in inspect.getargspec(urllib.request.urlopen).args:
from django.conf import settings
if hasattr(settings, 'SSL_CA_FILE'):
kwargs['cafile'] = settings.SSL_CA_FILE
return urllib.request.urlopen(*args, **kwargs)
## Instruction:
Use the correct urllib for the openid we're using
## Code After:
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import inspect
import sys
PY3 = sys.version_info >= (3, 0)
# Important: python3-open uses urllib.request, whereas (python2) openid uses
# urllib2. You cannot use the compatibility layer here.
if PY3:
from urllib.request import urlopen
else:
from urllib2 import urlopen
from openid.fetchers import Urllib2Fetcher
class SettingsAwareFetcher(Urllib2Fetcher):
"""
An URL fetcher for python-openid to verify the certificates against
SSL_CA_FILE in Django settings.
"""
@staticmethod
def urlopen(*args, **kwargs):
"""
Provide urlopen with the trusted certificate path.
"""
# Old versions of urllib2 cannot verify certificates
if PY3 or 'cafile' in inspect.getargspec(urlopen).args:
from django.conf import settings
if hasattr(settings, 'SSL_CA_FILE'):
kwargs['cafile'] = settings.SSL_CA_FILE
return urlopen(*args, **kwargs)
|
# ... existing code ...
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import inspect
import sys
PY3 = sys.version_info >= (3, 0)
# Important: python3-open uses urllib.request, whereas (python2) openid uses
# urllib2. You cannot use the compatibility layer here.
if PY3:
from urllib.request import urlopen
else:
from urllib2 import urlopen
from openid.fetchers import Urllib2Fetcher
# ... modified code ...
"""
# Old versions of urllib2 cannot verify certificates
if PY3 or 'cafile' in inspect.getargspec(urlopen).args:
from django.conf import settings
if hasattr(settings, 'SSL_CA_FILE'):
kwargs['cafile'] = settings.SSL_CA_FILE
return urlopen(*args, **kwargs)
# ... rest of the code ...
|
37f07d9a6bcd16b9f3f461eeb1a4acdfd8643cc5
|
src/util/strext.h
|
src/util/strext.h
|
// Copyright 2015 Ben Trask
// MIT licensed (see LICENSE for details)
#include <stdarg.h>
char *vaasprintf(char const *const fmt, va_list ap);
char *aasprintf(char const *const fmt, ...) __attribute__((format(printf, 1, 2)));
int time_iso8601(char *const out, size_t const max);
void valogf(char const *const fmt, va_list ap);
void alogf(char const *const fmt, ...);
|
// Copyright 2015 Ben Trask
// MIT licensed (see LICENSE for details)
#include <stdarg.h>
char *vaasprintf(char const *const fmt, va_list ap);
char *aasprintf(char const *const fmt, ...) __attribute__((format(printf, 1, 2)));
int time_iso8601(char *const out, size_t const max);
void valogf(char const *const fmt, va_list ap);
void alogf(char const *const fmt, ...) __attribute__((format(printf, 1, 2)));
|
Add printf __attribute__ to log function.
|
Add printf __attribute__ to log function.
|
C
|
mit
|
btrask/stronglink,Ryezhang/stronglink,btrask/stronglink,Ryezhang/stronglink,Ryezhang/stronglink,btrask/stronglink,btrask/stronglink
|
c
|
## Code Before:
// Copyright 2015 Ben Trask
// MIT licensed (see LICENSE for details)
#include <stdarg.h>
char *vaasprintf(char const *const fmt, va_list ap);
char *aasprintf(char const *const fmt, ...) __attribute__((format(printf, 1, 2)));
int time_iso8601(char *const out, size_t const max);
void valogf(char const *const fmt, va_list ap);
void alogf(char const *const fmt, ...);
## Instruction:
Add printf __attribute__ to log function.
## Code After:
// Copyright 2015 Ben Trask
// MIT licensed (see LICENSE for details)
#include <stdarg.h>
char *vaasprintf(char const *const fmt, va_list ap);
char *aasprintf(char const *const fmt, ...) __attribute__((format(printf, 1, 2)));
int time_iso8601(char *const out, size_t const max);
void valogf(char const *const fmt, va_list ap);
void alogf(char const *const fmt, ...) __attribute__((format(printf, 1, 2)));
|
...
int time_iso8601(char *const out, size_t const max);
void valogf(char const *const fmt, va_list ap);
void alogf(char const *const fmt, ...) __attribute__((format(printf, 1, 2)));
...
|
96a5388fcb8f1164db4612f4049d41a72e81ea09
|
zerver/lib/mandrill_client.py
|
zerver/lib/mandrill_client.py
|
import mandrill
from django.conf import settings
MAIL_CLIENT = None
from typing import Optional
def get_mandrill_client():
# type: () -> Optional[mandrill.Mandrill]
if settings.MANDRILL_API_KEY == '' or settings.DEVELOPMENT or settings.VOYAGER:
return None
global MAIL_CLIENT
if not MAIL_CLIENT:
MAIL_CLIENT = mandrill.Mandrill(settings.MANDRILL_API_KEY)
return MAIL_CLIENT
|
import mandrill
from django.conf import settings
MAIL_CLIENT = None
from typing import Optional
def get_mandrill_client():
# type: () -> Optional[mandrill.Mandrill]
if settings.MANDRILL_API_KEY == '' or settings.DEVELOPMENT:
return None
global MAIL_CLIENT
if not MAIL_CLIENT:
MAIL_CLIENT = mandrill.Mandrill(settings.MANDRILL_API_KEY)
return MAIL_CLIENT
|
Fix hardcoded check for settings.VOYAGER.
|
mandrill: Fix hardcoded check for settings.VOYAGER.
Since this delayed sending feature is the only thing
settings.MANDRILL_API_KEY is used for, it seems reasonable for that to
be the gate as to whether we actually use Mandrill.
|
Python
|
apache-2.0
|
jainayush975/zulip,tommyip/zulip,ahmadassaf/zulip,kou/zulip,SmartPeople/zulip,dawran6/zulip,sonali0901/zulip,arpith/zulip,dhcrzf/zulip,ahmadassaf/zulip,arpith/zulip,aakash-cr7/zulip,kou/zulip,sup95/zulip,sharmaeklavya2/zulip,jrowan/zulip,grave-w-grave/zulip,SmartPeople/zulip,aakash-cr7/zulip,jainayush975/zulip,eeshangarg/zulip,niftynei/zulip,krtkmj/zulip,dattatreya303/zulip,souravbadami/zulip,amanharitsh123/zulip,hackerkid/zulip,amanharitsh123/zulip,zulip/zulip,Galexrt/zulip,amyliu345/zulip,timabbott/zulip,reyha/zulip,sup95/zulip,PhilSk/zulip,Galexrt/zulip,grave-w-grave/zulip,punchagan/zulip,dattatreya303/zulip,souravbadami/zulip,mahim97/zulip,peguin40/zulip,rht/zulip,arpith/zulip,andersk/zulip,isht3/zulip,rht/zulip,Juanvulcano/zulip,blaze225/zulip,jphilipsen05/zulip,Jianchun1/zulip,sonali0901/zulip,TigorC/zulip,dhcrzf/zulip,calvinleenyc/zulip,krtkmj/zulip,reyha/zulip,souravbadami/zulip,dhcrzf/zulip,paxapy/zulip,synicalsyntax/zulip,rishig/zulip,sup95/zulip,JPJPJPOPOP/zulip,hackerkid/zulip,dhcrzf/zulip,calvinleenyc/zulip,Galexrt/zulip,Diptanshu8/zulip,verma-varsha/zulip,zacps/zulip,paxapy/zulip,timabbott/zulip,andersk/zulip,tommyip/zulip,vikas-parashar/zulip,krtkmj/zulip,timabbott/zulip,shubhamdhama/zulip,vaidap/zulip,showell/zulip,TigorC/zulip,blaze225/zulip,jainayush975/zulip,verma-varsha/zulip,vaidap/zulip,AZtheAsian/zulip,vabs22/zulip,andersk/zulip,timabbott/zulip,rishig/zulip,hackerkid/zulip,vikas-parashar/zulip,SmartPeople/zulip,j831/zulip,brainwane/zulip,grave-w-grave/zulip,Juanvulcano/zulip,jrowan/zulip,grave-w-grave/zulip,Diptanshu8/zulip,TigorC/zulip,showell/zulip,eeshangarg/zulip,zulip/zulip,kou/zulip,rishig/zulip,brockwhittaker/zulip,synicalsyntax/zulip,arpith/zulip,vabs22/zulip,susansls/zulip,samatdav/zulip,susansls/zulip,PhilSk/zulip,niftynei/zulip,christi3k/zulip,mahim97/zulip,zulip/zulip,jainayush975/zulip,JPJPJPOPOP/zulip,j831/zulip,punchagan/zulip,vikas-parashar/zulip,showell/zulip,zacps/zulip,dattatreya303/zulip,aakash-cr7/zulip,dawran6/zulip,mohsenSy/zulip,ahmadassaf/zulip,blaze225/zulip,dhcrzf/zulip,hackerkid/zulip,reyha/zulip,brainwane/zulip,TigorC/zulip,andersk/zulip,susansls/zulip,Juanvulcano/zulip,showell/zulip,sonali0901/zulip,sup95/zulip,brockwhittaker/zulip,showell/zulip,vaidap/zulip,sup95/zulip,AZtheAsian/zulip,rht/zulip,brainwane/zulip,sonali0901/zulip,Juanvulcano/zulip,isht3/zulip,eeshangarg/zulip,andersk/zulip,dhcrzf/zulip,ryanbackman/zulip,christi3k/zulip,Juanvulcano/zulip,andersk/zulip,shubhamdhama/zulip,mahim97/zulip,punchagan/zulip,KingxBanana/zulip,isht3/zulip,KingxBanana/zulip,vaidap/zulip,jackrzhang/zulip,PhilSk/zulip,brockwhittaker/zulip,tommyip/zulip,vabs22/zulip,rishig/zulip,umkay/zulip,AZtheAsian/zulip,kou/zulip,andersk/zulip,jackrzhang/zulip,showell/zulip,peguin40/zulip,vikas-parashar/zulip,krtkmj/zulip,timabbott/zulip,jphilipsen05/zulip,jrowan/zulip,brockwhittaker/zulip,ahmadassaf/zulip,sup95/zulip,dattatreya303/zulip,SmartPeople/zulip,joyhchen/zulip,JPJPJPOPOP/zulip,zacps/zulip,Galexrt/zulip,hackerkid/zulip,jackrzhang/zulip,j831/zulip,brainwane/zulip,rishig/zulip,Diptanshu8/zulip,SmartPeople/zulip,arpith/zulip,amyliu345/zulip,shubhamdhama/zulip,synicalsyntax/zulip,rishig/zulip,niftynei/zulip,Jianchun1/zulip,Jianchun1/zulip,dawran6/zulip,jphilipsen05/zulip,ryanbackman/zulip,Diptanshu8/zulip,punchagan/zulip,ryanbackman/zulip,ryanbackman/zulip,samatdav/zulip,jackrzhang/zulip,shubhamdhama/zulip,tommyip/zulip,cosmicAsymmetry/zulip,grave-w-grave/zulip,sonali0901/zulip,dawran6/zulip,brainwane/zulip,niftynei/zulip,jackrzhang/zulip,sonali0901/zulip,mahim97/zulip,brainwane/zulip,Juanvulcano/zulip,zacps/zulip,aakash-cr7/zulip,calvinleenyc/zulip,sharmaeklavya2/zulip,shubhamdhama/zulip,vaidap/zulip,umkay/zulip,dawran6/zulip,zulip/zulip,punchagan/zulip,dhcrzf/zulip,synicalsyntax/zulip,peguin40/zulip,Galexrt/zulip,verma-varsha/zulip,JPJPJPOPOP/zulip,tommyip/zulip,reyha/zulip,joyhchen/zulip,grave-w-grave/zulip,vikas-parashar/zulip,souravbadami/zulip,arpith/zulip,verma-varsha/zulip,synicalsyntax/zulip,cosmicAsymmetry/zulip,paxapy/zulip,blaze225/zulip,rht/zulip,susansls/zulip,j831/zulip,susansls/zulip,joyhchen/zulip,umkay/zulip,eeshangarg/zulip,umkay/zulip,vabs22/zulip,samatdav/zulip,aakash-cr7/zulip,Jianchun1/zulip,mohsenSy/zulip,rht/zulip,mahim97/zulip,calvinleenyc/zulip,vabs22/zulip,amanharitsh123/zulip,amanharitsh123/zulip,jrowan/zulip,joyhchen/zulip,paxapy/zulip,PhilSk/zulip,rishig/zulip,synicalsyntax/zulip,peguin40/zulip,vabs22/zulip,cosmicAsymmetry/zulip,zulip/zulip,mohsenSy/zulip,cosmicAsymmetry/zulip,KingxBanana/zulip,jrowan/zulip,mohsenSy/zulip,brockwhittaker/zulip,punchagan/zulip,joyhchen/zulip,AZtheAsian/zulip,tommyip/zulip,PhilSk/zulip,vikas-parashar/zulip,peguin40/zulip,jphilipsen05/zulip,ahmadassaf/zulip,samatdav/zulip,hackerkid/zulip,rht/zulip,j831/zulip,peguin40/zulip,tommyip/zulip,PhilSk/zulip,timabbott/zulip,amyliu345/zulip,jphilipsen05/zulip,shubhamdhama/zulip,ahmadassaf/zulip,souravbadami/zulip,ahmadassaf/zulip,sharmaeklavya2/zulip,jrowan/zulip,JPJPJPOPOP/zulip,amanharitsh123/zulip,AZtheAsian/zulip,zacps/zulip,umkay/zulip,kou/zulip,synicalsyntax/zulip,ryanbackman/zulip,sharmaeklavya2/zulip,verma-varsha/zulip,amyliu345/zulip,Galexrt/zulip,Jianchun1/zulip,christi3k/zulip,krtkmj/zulip,aakash-cr7/zulip,dawran6/zulip,AZtheAsian/zulip,jainayush975/zulip,Jianchun1/zulip,hackerkid/zulip,isht3/zulip,Diptanshu8/zulip,reyha/zulip,brockwhittaker/zulip,umkay/zulip,reyha/zulip,calvinleenyc/zulip,ryanbackman/zulip,sharmaeklavya2/zulip,jphilipsen05/zulip,eeshangarg/zulip,paxapy/zulip,dattatreya303/zulip,vaidap/zulip,brainwane/zulip,JPJPJPOPOP/zulip,isht3/zulip,shubhamdhama/zulip,cosmicAsymmetry/zulip,rht/zulip,niftynei/zulip,krtkmj/zulip,showell/zulip,samatdav/zulip,TigorC/zulip,mohsenSy/zulip,samatdav/zulip,verma-varsha/zulip,mohsenSy/zulip,blaze225/zulip,jackrzhang/zulip,amyliu345/zulip,kou/zulip,souravbadami/zulip,kou/zulip,KingxBanana/zulip,dattatreya303/zulip,zulip/zulip,amyliu345/zulip,christi3k/zulip,TigorC/zulip,zulip/zulip,zacps/zulip,christi3k/zulip,cosmicAsymmetry/zulip,niftynei/zulip,jainayush975/zulip,timabbott/zulip,calvinleenyc/zulip,Galexrt/zulip,blaze225/zulip,KingxBanana/zulip,krtkmj/zulip,joyhchen/zulip,jackrzhang/zulip,mahim97/zulip,SmartPeople/zulip,isht3/zulip,christi3k/zulip,j831/zulip,eeshangarg/zulip,Diptanshu8/zulip,susansls/zulip,punchagan/zulip,paxapy/zulip,sharmaeklavya2/zulip,amanharitsh123/zulip,KingxBanana/zulip,umkay/zulip,eeshangarg/zulip
|
python
|
## Code Before:
import mandrill
from django.conf import settings
MAIL_CLIENT = None
from typing import Optional
def get_mandrill_client():
# type: () -> Optional[mandrill.Mandrill]
if settings.MANDRILL_API_KEY == '' or settings.DEVELOPMENT or settings.VOYAGER:
return None
global MAIL_CLIENT
if not MAIL_CLIENT:
MAIL_CLIENT = mandrill.Mandrill(settings.MANDRILL_API_KEY)
return MAIL_CLIENT
## Instruction:
mandrill: Fix hardcoded check for settings.VOYAGER.
Since this delayed sending feature is the only thing
settings.MANDRILL_API_KEY is used for, it seems reasonable for that to
be the gate as to whether we actually use Mandrill.
## Code After:
import mandrill
from django.conf import settings
MAIL_CLIENT = None
from typing import Optional
def get_mandrill_client():
# type: () -> Optional[mandrill.Mandrill]
if settings.MANDRILL_API_KEY == '' or settings.DEVELOPMENT:
return None
global MAIL_CLIENT
if not MAIL_CLIENT:
MAIL_CLIENT = mandrill.Mandrill(settings.MANDRILL_API_KEY)
return MAIL_CLIENT
|
...
def get_mandrill_client():
# type: () -> Optional[mandrill.Mandrill]
if settings.MANDRILL_API_KEY == '' or settings.DEVELOPMENT:
return None
global MAIL_CLIENT
...
|
5d5e9ff082eb6f277270045618812c4b2c49daab
|
31-trinity/tf-31.py
|
31-trinity/tf-31.py
|
import sys, re, operator, collections
#
# Model
#
class WordFrequenciesModel:
""" Models the data. In this case, we're only interested
in words and their frequencies as an end result """
freqs = {}
def __init__(self, path_to_file):
stopwords = set(open('../stop_words.txt').read().split(','))
words = re.findall('[a-z]{2,}', open(path_to_file).read().lower())
self.freqs = collections.Counter(w for w in words if w not in stopwords)
#
# View
#
class WordFrequenciesView:
def __init__(self, model):
self._model = model
def render(self):
sorted_freqs = sorted(self._model.freqs.iteritems(), key=operator.itemgetter(1), reverse=True)
for (w, c) in sorted_freqs[:25]:
print w, '-', c
#
# Controller
#
class WordFrequencyController:
def __init__(self, model, view):
self._model = model
self._view = view
view.render()
#
# Main
#
m = WordFrequenciesModel(sys.argv[1])
v = WordFrequenciesView(m)
c = WordFrequencyController(m, v)
|
import sys, re, operator, collections
class WordFrequenciesModel:
""" Models the data. In this case, we're only interested
in words and their frequencies as an end result """
freqs = {}
def __init__(self, path_to_file):
self.update(path_to_file)
def update(self, path_to_file):
try:
stopwords = set(open('../stop_words.txt').read().split(','))
words = re.findall('[a-z]{2,}', open(path_to_file).read().lower())
self.freqs = collections.Counter(w for w in words if w not in stopwords)
except IOError:
print "File not found"
self.freqs = {}
class WordFrequenciesView:
def __init__(self, model):
self._model = model
def render(self):
sorted_freqs = sorted(self._model.freqs.iteritems(), key=operator.itemgetter(1), reverse=True)
for (w, c) in sorted_freqs[:25]:
print w, '-', c
class WordFrequencyController:
def __init__(self, model, view):
self._model, self._view = model, view
view.render()
def run(self):
while True:
print "Next file: "
sys.stdout.flush()
filename = sys.stdin.readline().strip()
self._model.update(filename)
self._view.render()
m = WordFrequenciesModel(sys.argv[1])
v = WordFrequenciesView(m)
c = WordFrequencyController(m, v)
c.run()
|
Make the mvc example interactive
|
Make the mvc example interactive
|
Python
|
mit
|
alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style
|
python
|
## Code Before:
import sys, re, operator, collections
#
# Model
#
class WordFrequenciesModel:
""" Models the data. In this case, we're only interested
in words and their frequencies as an end result """
freqs = {}
def __init__(self, path_to_file):
stopwords = set(open('../stop_words.txt').read().split(','))
words = re.findall('[a-z]{2,}', open(path_to_file).read().lower())
self.freqs = collections.Counter(w for w in words if w not in stopwords)
#
# View
#
class WordFrequenciesView:
def __init__(self, model):
self._model = model
def render(self):
sorted_freqs = sorted(self._model.freqs.iteritems(), key=operator.itemgetter(1), reverse=True)
for (w, c) in sorted_freqs[:25]:
print w, '-', c
#
# Controller
#
class WordFrequencyController:
def __init__(self, model, view):
self._model = model
self._view = view
view.render()
#
# Main
#
m = WordFrequenciesModel(sys.argv[1])
v = WordFrequenciesView(m)
c = WordFrequencyController(m, v)
## Instruction:
Make the mvc example interactive
## Code After:
import sys, re, operator, collections
class WordFrequenciesModel:
""" Models the data. In this case, we're only interested
in words and their frequencies as an end result """
freqs = {}
def __init__(self, path_to_file):
self.update(path_to_file)
def update(self, path_to_file):
try:
stopwords = set(open('../stop_words.txt').read().split(','))
words = re.findall('[a-z]{2,}', open(path_to_file).read().lower())
self.freqs = collections.Counter(w for w in words if w not in stopwords)
except IOError:
print "File not found"
self.freqs = {}
class WordFrequenciesView:
def __init__(self, model):
self._model = model
def render(self):
sorted_freqs = sorted(self._model.freqs.iteritems(), key=operator.itemgetter(1), reverse=True)
for (w, c) in sorted_freqs[:25]:
print w, '-', c
class WordFrequencyController:
def __init__(self, model, view):
self._model, self._view = model, view
view.render()
def run(self):
while True:
print "Next file: "
sys.stdout.flush()
filename = sys.stdin.readline().strip()
self._model.update(filename)
self._view.render()
m = WordFrequenciesModel(sys.argv[1])
v = WordFrequenciesView(m)
c = WordFrequencyController(m, v)
c.run()
|
# ... existing code ...
import sys, re, operator, collections
class WordFrequenciesModel:
""" Models the data. In this case, we're only interested
in words and their frequencies as an end result """
freqs = {}
def __init__(self, path_to_file):
self.update(path_to_file)
def update(self, path_to_file):
try:
stopwords = set(open('../stop_words.txt').read().split(','))
words = re.findall('[a-z]{2,}', open(path_to_file).read().lower())
self.freqs = collections.Counter(w for w in words if w not in stopwords)
except IOError:
print "File not found"
self.freqs = {}
class WordFrequenciesView:
def __init__(self, model):
self._model = model
# ... modified code ...
for (w, c) in sorted_freqs[:25]:
print w, '-', c
class WordFrequencyController:
def __init__(self, model, view):
self._model, self._view = model, view
view.render()
def run(self):
while True:
print "Next file: "
sys.stdout.flush()
filename = sys.stdin.readline().strip()
self._model.update(filename)
self._view.render()
m = WordFrequenciesModel(sys.argv[1])
v = WordFrequenciesView(m)
c = WordFrequencyController(m, v)
c.run()
# ... rest of the code ...
|
2ad9cf280ee1743f1ad542d3c0c8d8365caea11e
|
condatestall.py
|
condatestall.py
|
from __future__ import print_function
import itertools
import subprocess
import os
import sys
NPY = '16', '17'
PY = '26', '27', '33'
RECIPE_DIR = "./buildscripts/condarecipe.local"
def main():
failfast = '-v' in sys.argv[1:]
args = "conda build %s --no-binstar-upload" % RECIPE_DIR
failures = []
for py, npy in itertools.product(PY, NPY):
if py == '33' and npy == '16':
# Skip python3 + numpy16
continue
os.environ['CONDA_PY'] = py
os.environ['CONDA_NPY'] = npy
try:
subprocess.check_call(args.split())
except subprocess.CalledProcessError as e:
failures.append((py, npy, e))
if failfast:
break
print("=" * 80)
if failures:
for py, npy, err in failures:
print("Test failed for python %s numpy %s" % (py, npy))
print(err)
else:
print("All Passed")
if __name__ == '__main__':
main()
|
from __future__ import print_function
import itertools
import subprocess
import os
import sys
if '-q' in sys.argv[1:]:
NPY = '18',
else:
NPY = '16', '17', '18'
PY = '26', '27', '33'
RECIPE_DIR = "./buildscripts/condarecipe.local"
def main():
failfast = '-v' in sys.argv[1:]
args = "conda build %s --no-binstar-upload" % RECIPE_DIR
failures = []
for py, npy in itertools.product(PY, NPY):
if py == '33' and npy == '16':
# Skip python3 + numpy16
continue
os.environ['CONDA_PY'] = py
os.environ['CONDA_NPY'] = npy
try:
subprocess.check_call(args.split())
except subprocess.CalledProcessError as e:
failures.append((py, npy, e))
if failfast:
break
print("=" * 80)
if failures:
for py, npy, err in failures:
print("Test failed for python %s numpy %s" % (py, npy))
print(err)
else:
print("All Passed")
if __name__ == '__main__':
main()
|
Add option for quick test on all python version
|
Add option for quick test on all python version
|
Python
|
bsd-2-clause
|
pitrou/numba,GaZ3ll3/numba,pombredanne/numba,GaZ3ll3/numba,stuartarchibald/numba,numba/numba,cpcloud/numba,gmarkall/numba,cpcloud/numba,gdementen/numba,ssarangi/numba,seibert/numba,sklam/numba,gdementen/numba,jriehl/numba,gmarkall/numba,IntelLabs/numba,pombredanne/numba,stuartarchibald/numba,jriehl/numba,stuartarchibald/numba,gmarkall/numba,gmarkall/numba,gdementen/numba,stuartarchibald/numba,pombredanne/numba,pombredanne/numba,cpcloud/numba,numba/numba,ssarangi/numba,seibert/numba,cpcloud/numba,numba/numba,IntelLabs/numba,IntelLabs/numba,pitrou/numba,jriehl/numba,numba/numba,gmarkall/numba,jriehl/numba,ssarangi/numba,gdementen/numba,stonebig/numba,sklam/numba,gdementen/numba,IntelLabs/numba,seibert/numba,seibert/numba,stefanseefeld/numba,stefanseefeld/numba,IntelLabs/numba,GaZ3ll3/numba,stefanseefeld/numba,pombredanne/numba,jriehl/numba,ssarangi/numba,sklam/numba,numba/numba,GaZ3ll3/numba,stefanseefeld/numba,sklam/numba,ssarangi/numba,stonebig/numba,stuartarchibald/numba,stefanseefeld/numba,stonebig/numba,stonebig/numba,GaZ3ll3/numba,pitrou/numba,cpcloud/numba,stonebig/numba,seibert/numba,sklam/numba,pitrou/numba,pitrou/numba
|
python
|
## Code Before:
from __future__ import print_function
import itertools
import subprocess
import os
import sys
NPY = '16', '17'
PY = '26', '27', '33'
RECIPE_DIR = "./buildscripts/condarecipe.local"
def main():
failfast = '-v' in sys.argv[1:]
args = "conda build %s --no-binstar-upload" % RECIPE_DIR
failures = []
for py, npy in itertools.product(PY, NPY):
if py == '33' and npy == '16':
# Skip python3 + numpy16
continue
os.environ['CONDA_PY'] = py
os.environ['CONDA_NPY'] = npy
try:
subprocess.check_call(args.split())
except subprocess.CalledProcessError as e:
failures.append((py, npy, e))
if failfast:
break
print("=" * 80)
if failures:
for py, npy, err in failures:
print("Test failed for python %s numpy %s" % (py, npy))
print(err)
else:
print("All Passed")
if __name__ == '__main__':
main()
## Instruction:
Add option for quick test on all python version
## Code After:
from __future__ import print_function
import itertools
import subprocess
import os
import sys
if '-q' in sys.argv[1:]:
NPY = '18',
else:
NPY = '16', '17', '18'
PY = '26', '27', '33'
RECIPE_DIR = "./buildscripts/condarecipe.local"
def main():
failfast = '-v' in sys.argv[1:]
args = "conda build %s --no-binstar-upload" % RECIPE_DIR
failures = []
for py, npy in itertools.product(PY, NPY):
if py == '33' and npy == '16':
# Skip python3 + numpy16
continue
os.environ['CONDA_PY'] = py
os.environ['CONDA_NPY'] = npy
try:
subprocess.check_call(args.split())
except subprocess.CalledProcessError as e:
failures.append((py, npy, e))
if failfast:
break
print("=" * 80)
if failures:
for py, npy, err in failures:
print("Test failed for python %s numpy %s" % (py, npy))
print(err)
else:
print("All Passed")
if __name__ == '__main__':
main()
|
...
import os
import sys
if '-q' in sys.argv[1:]:
NPY = '18',
else:
NPY = '16', '17', '18'
PY = '26', '27', '33'
RECIPE_DIR = "./buildscripts/condarecipe.local"
...
|
e9eb29d300d4072a32d824d4f588ff76a905bb89
|
gunicorn_settings.py
|
gunicorn_settings.py
|
bind = '127.0.0.1:8001'
workers = 2
worker_class = 'gevent'
timeout = 30
keepalive = 2
errorlog = '-'
|
workers = 2
worker_class = 'gevent'
timeout = 30
keepalive = 2
errorlog = '-'
|
Use IP and PORT environment variables if set
|
Use IP and PORT environment variables if set
|
Python
|
apache-2.0
|
notapresent/rbm2m,notapresent/rbm2m
|
python
|
## Code Before:
bind = '127.0.0.1:8001'
workers = 2
worker_class = 'gevent'
timeout = 30
keepalive = 2
errorlog = '-'
## Instruction:
Use IP and PORT environment variables if set
## Code After:
workers = 2
worker_class = 'gevent'
timeout = 30
keepalive = 2
errorlog = '-'
|
// ... existing code ...
workers = 2
worker_class = 'gevent'
timeout = 30
// ... rest of the code ...
|
3f296b1f7b3a7aad3643a7d925676909658cabe4
|
src/main/kotlin/ee/mcdimus/matewp/service/FileSystemService.kt
|
src/main/kotlin/ee/mcdimus/matewp/service/FileSystemService.kt
|
package ee.mcdimus.matewp.service
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
/**
* @author Dmitri Maksimov
*/
class FileSystemService {
companion object {
private const val HOME = "HOME"
}
fun getHomeDirectory(): Path {
val homeDirectoryPath = System.getenv()
.getOrElse(HOME, { throw IllegalStateException("environment variable $HOME is no defined") })
return Paths.get(homeDirectoryPath)
}
fun getImagesDirectory(): Path {
val imagesDirectory = getHomeDirectory().resolve("Pictures/mate-wp")
if (Files.notExists(imagesDirectory)) {
return Files.createDirectories(imagesDirectory)
}
return imagesDirectory
}
fun getConfigsDirectory(): Path {
val configsDirectory = getImagesDirectory().resolve("configs")
if (Files.notExists(configsDirectory)) {
return Files.createDirectories(configsDirectory)
}
return configsDirectory
}
fun saveProperties(propertiesPath: Path, propertyMap: Map<String, String>): Path {
val properties = Properties()
for ((key, value) in propertyMap) {
properties.setProperty(key, value)
}
Files.newOutputStream(propertiesPath).use {
properties.store(it, null)
}
return propertiesPath
}
fun loadProperties(propertiesPath: Path): Properties {
val properties = Properties()
Files.newInputStream(propertiesPath).use {
properties.load(it)
}
return properties
}
}
|
package ee.mcdimus.matewp.service
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
/**
* @author Dmitri Maksimov
*/
class FileSystemService {
companion object {
private const val USER_HOME = "user.home"
}
fun getHomeDirectory(): Path {
val homeDirectoryPath = System.getProperty(USER_HOME)
?: throw IllegalStateException("system property $USER_HOME is not defined")
return Paths.get(homeDirectoryPath)
}
fun getImagesDirectory(): Path {
val imagesDirectory = getHomeDirectory().resolve("Pictures/mate-wp")
if (Files.notExists(imagesDirectory)) {
return Files.createDirectories(imagesDirectory)
}
return imagesDirectory
}
fun getConfigsDirectory(): Path {
val configsDirectory = getImagesDirectory().resolve("configs")
if (Files.notExists(configsDirectory)) {
return Files.createDirectories(configsDirectory)
}
return configsDirectory
}
fun saveProperties(propertiesPath: Path, propertyMap: Map<String, String>): Path {
val properties = Properties()
for ((key, value) in propertyMap) {
properties.setProperty(key, value)
}
Files.newOutputStream(propertiesPath).use {
properties.store(it, null)
}
return propertiesPath
}
fun loadProperties(propertiesPath: Path): Properties {
val properties = Properties()
Files.newInputStream(propertiesPath).use {
properties.load(it)
}
return properties
}
}
|
Use system property 'user.home' instead of environment variable HOME, which is available only on Linux.
|
Use system property 'user.home' instead of environment variable HOME, which is available only on Linux.
|
Kotlin
|
mit
|
mcdimus/mate-wp,mcdimus/mate-wp
|
kotlin
|
## Code Before:
package ee.mcdimus.matewp.service
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
/**
* @author Dmitri Maksimov
*/
class FileSystemService {
companion object {
private const val HOME = "HOME"
}
fun getHomeDirectory(): Path {
val homeDirectoryPath = System.getenv()
.getOrElse(HOME, { throw IllegalStateException("environment variable $HOME is no defined") })
return Paths.get(homeDirectoryPath)
}
fun getImagesDirectory(): Path {
val imagesDirectory = getHomeDirectory().resolve("Pictures/mate-wp")
if (Files.notExists(imagesDirectory)) {
return Files.createDirectories(imagesDirectory)
}
return imagesDirectory
}
fun getConfigsDirectory(): Path {
val configsDirectory = getImagesDirectory().resolve("configs")
if (Files.notExists(configsDirectory)) {
return Files.createDirectories(configsDirectory)
}
return configsDirectory
}
fun saveProperties(propertiesPath: Path, propertyMap: Map<String, String>): Path {
val properties = Properties()
for ((key, value) in propertyMap) {
properties.setProperty(key, value)
}
Files.newOutputStream(propertiesPath).use {
properties.store(it, null)
}
return propertiesPath
}
fun loadProperties(propertiesPath: Path): Properties {
val properties = Properties()
Files.newInputStream(propertiesPath).use {
properties.load(it)
}
return properties
}
}
## Instruction:
Use system property 'user.home' instead of environment variable HOME, which is available only on Linux.
## Code After:
package ee.mcdimus.matewp.service
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
/**
* @author Dmitri Maksimov
*/
class FileSystemService {
companion object {
private const val USER_HOME = "user.home"
}
fun getHomeDirectory(): Path {
val homeDirectoryPath = System.getProperty(USER_HOME)
?: throw IllegalStateException("system property $USER_HOME is not defined")
return Paths.get(homeDirectoryPath)
}
fun getImagesDirectory(): Path {
val imagesDirectory = getHomeDirectory().resolve("Pictures/mate-wp")
if (Files.notExists(imagesDirectory)) {
return Files.createDirectories(imagesDirectory)
}
return imagesDirectory
}
fun getConfigsDirectory(): Path {
val configsDirectory = getImagesDirectory().resolve("configs")
if (Files.notExists(configsDirectory)) {
return Files.createDirectories(configsDirectory)
}
return configsDirectory
}
fun saveProperties(propertiesPath: Path, propertyMap: Map<String, String>): Path {
val properties = Properties()
for ((key, value) in propertyMap) {
properties.setProperty(key, value)
}
Files.newOutputStream(propertiesPath).use {
properties.store(it, null)
}
return propertiesPath
}
fun loadProperties(propertiesPath: Path): Properties {
val properties = Properties()
Files.newInputStream(propertiesPath).use {
properties.load(it)
}
return properties
}
}
|
// ... existing code ...
class FileSystemService {
companion object {
private const val USER_HOME = "user.home"
}
fun getHomeDirectory(): Path {
val homeDirectoryPath = System.getProperty(USER_HOME)
?: throw IllegalStateException("system property $USER_HOME is not defined")
return Paths.get(homeDirectoryPath)
}
// ... rest of the code ...
|
3e6e485443a901660a461dbbc8b324bfe4c19c8f
|
tests/v5/conftest.py
|
tests/v5/conftest.py
|
import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_GENERATORS
|
import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
|
Add fixture for exemplar primitive generators
|
Add fixture for exemplar primitive generators
|
Python
|
mit
|
maxalbert/tohu
|
python
|
## Code Before:
import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_GENERATORS
## Instruction:
Add fixture for exemplar primitive generators
## Code After:
import pytest
from .context import tohu
from tohu.v5.primitive_generators import *
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
@pytest.fixture
def exemplar_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
|
# ... existing code ...
from tohu.v5.primitive_generators import *
EXEMPLAR_PRIMITIVE_GENERATORS = [
Constant("quux"),
Boolean(p=0.3),
]
# ... modified code ...
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
@pytest.fixture
def exemplar_primitive_generators():
"""
Return a list of generators which contains an example
for each type of generator supported by tohu.
"""
return EXEMPLAR_PRIMITIVE_GENERATORS
# ... rest of the code ...
|
685365af5126c6e83db468eef24b008fc1526462
|
tools/game_utils.py
|
tools/game_utils.py
|
import scipy.misc
import scipy.special
def get_num_hole_card_combinations(game):
num_players = game.get_num_players()
num_hole_cards = game.get_num_hole_cards()
num_cards = game.get_num_suits() * game.get_num_ranks()
num_total_hole_cards = num_players * num_hole_cards
return scipy.misc.comb(num_cards, num_total_hole_cards, exact=True) \
* scipy.special.perm(num_total_hole_cards, num_total_hole_cards, exact=True)
|
import numpy as np
import scipy.misc
import scipy.special
from tools.walk_tree import walk_tree
from tools.game_tree.nodes import ActionNode
def get_num_hole_card_combinations(game):
num_players = game.get_num_players()
num_hole_cards = game.get_num_hole_cards()
num_cards = game.get_num_suits() * game.get_num_ranks()
num_total_hole_cards = num_players * num_hole_cards
return scipy.misc.comb(num_cards, num_total_hole_cards, exact=True) \
* scipy.special.perm(num_total_hole_cards, num_total_hole_cards, exact=True)
def is_correct_strategy(strategy_tree):
correct = True
def on_node(node):
if isinstance(node, ActionNode):
nonlocal correct
strategy_sum = np.sum(node.strategy)
if strategy_sum != 1:
correct = False
walk_tree(strategy_tree, on_node)
return correct
|
Add method to verify that all strategy probabilities add to 1
|
Add method to verify that all strategy probabilities add to 1
|
Python
|
mit
|
JakubPetriska/poker-cfr,JakubPetriska/poker-cfr
|
python
|
## Code Before:
import scipy.misc
import scipy.special
def get_num_hole_card_combinations(game):
num_players = game.get_num_players()
num_hole_cards = game.get_num_hole_cards()
num_cards = game.get_num_suits() * game.get_num_ranks()
num_total_hole_cards = num_players * num_hole_cards
return scipy.misc.comb(num_cards, num_total_hole_cards, exact=True) \
* scipy.special.perm(num_total_hole_cards, num_total_hole_cards, exact=True)
## Instruction:
Add method to verify that all strategy probabilities add to 1
## Code After:
import numpy as np
import scipy.misc
import scipy.special
from tools.walk_tree import walk_tree
from tools.game_tree.nodes import ActionNode
def get_num_hole_card_combinations(game):
num_players = game.get_num_players()
num_hole_cards = game.get_num_hole_cards()
num_cards = game.get_num_suits() * game.get_num_ranks()
num_total_hole_cards = num_players * num_hole_cards
return scipy.misc.comb(num_cards, num_total_hole_cards, exact=True) \
* scipy.special.perm(num_total_hole_cards, num_total_hole_cards, exact=True)
def is_correct_strategy(strategy_tree):
correct = True
def on_node(node):
if isinstance(node, ActionNode):
nonlocal correct
strategy_sum = np.sum(node.strategy)
if strategy_sum != 1:
correct = False
walk_tree(strategy_tree, on_node)
return correct
|
...
import numpy as np
import scipy.misc
import scipy.special
from tools.walk_tree import walk_tree
from tools.game_tree.nodes import ActionNode
def get_num_hole_card_combinations(game):
...
num_total_hole_cards = num_players * num_hole_cards
return scipy.misc.comb(num_cards, num_total_hole_cards, exact=True) \
* scipy.special.perm(num_total_hole_cards, num_total_hole_cards, exact=True)
def is_correct_strategy(strategy_tree):
correct = True
def on_node(node):
if isinstance(node, ActionNode):
nonlocal correct
strategy_sum = np.sum(node.strategy)
if strategy_sum != 1:
correct = False
walk_tree(strategy_tree, on_node)
return correct
...
|
9249dc161e9fdd64e15a42f644232c43cb6875b2
|
src/dependenpy/plugins.py
|
src/dependenpy/plugins.py
|
"""dependenpy plugins module."""
try:
from archan import Provider, Argument, DSM as ArchanDSM
from .dsm import DSM as DependenpyDSM
from .helpers import guess_depth
class InternalDependencies(Provider):
"""Dependenpy provider for Archan."""
identifier = 'dependenpy.InternalDependencies'
name = 'Internal Dependencies'
description = 'Provide matrix data about internal dependencies ' \
'in a set of packages.'
arguments = (
Argument('packages', list, 'The list of packages to check for.'),
Argument('enforce_init', bool, default=True,
description='Whether to assert presence of '
'__init__.py files in directories.'),
Argument('depth', int, 'The depth of the matrix to generate.'),
)
def get_dsm(self, packages, enforce_init=True, depth=None):
"""
Provide matrix data for internal dependencies in a set of packages.
Args:
*packages (list): the list of packages to check for.
enforce_init (bool):
whether to assert presence of __init__.py files
in directories.
depth (int): the depth of the matrix to generate.
Returns:
archan.DSM: instance of archan DSM.
"""
dsm = DependenpyDSM(*packages, enforce_init=enforce_init)
if depth is None:
depth = guess_depth(packages)
matrix = dsm.as_matrix(depth=depth)
return ArchanDSM(data=matrix.data, entities=matrix.keys)
except ImportError:
class InternalDependencies(object):
"""Empty dependenpy provider."""
|
"""dependenpy plugins module."""
try:
from archan import Provider, Argument, DesignStructureMatrix as ArchanDSM
from .dsm import DSM as DependenpyDSM
from .helpers import guess_depth
class InternalDependencies(Provider):
"""Dependenpy provider for Archan."""
identifier = 'dependenpy.InternalDependencies'
name = 'Internal Dependencies'
description = 'Provide matrix data about internal dependencies ' \
'in a set of packages.'
argument_list = (
Argument('packages', list, 'The list of packages to check for.'),
Argument('enforce_init', bool, default=True,
description='Whether to assert presence of '
'__init__.py files in directories.'),
Argument('depth', int, 'The depth of the matrix to generate.'),
)
def get_data(self, packages, enforce_init=True, depth=None):
"""
Provide matrix data for internal dependencies in a set of packages.
Args:
*packages (list): the list of packages to check for.
enforce_init (bool):
whether to assert presence of __init__.py files
in directories.
depth (int): the depth of the matrix to generate.
Returns:
archan.DSM: instance of archan DSM.
"""
dsm = DependenpyDSM(*packages, enforce_init=enforce_init)
if depth is None:
depth = guess_depth(packages)
matrix = dsm.as_matrix(depth=depth)
return ArchanDSM(data=matrix.data, entities=matrix.keys)
except ImportError:
class InternalDependencies(object):
"""Empty dependenpy provider."""
|
Update archan provider for archan 3.0
|
Update archan provider for archan 3.0
|
Python
|
isc
|
Pawamoy/dependenpy,Pawamoy/dependenpy
|
python
|
## Code Before:
"""dependenpy plugins module."""
try:
from archan import Provider, Argument, DSM as ArchanDSM
from .dsm import DSM as DependenpyDSM
from .helpers import guess_depth
class InternalDependencies(Provider):
"""Dependenpy provider for Archan."""
identifier = 'dependenpy.InternalDependencies'
name = 'Internal Dependencies'
description = 'Provide matrix data about internal dependencies ' \
'in a set of packages.'
arguments = (
Argument('packages', list, 'The list of packages to check for.'),
Argument('enforce_init', bool, default=True,
description='Whether to assert presence of '
'__init__.py files in directories.'),
Argument('depth', int, 'The depth of the matrix to generate.'),
)
def get_dsm(self, packages, enforce_init=True, depth=None):
"""
Provide matrix data for internal dependencies in a set of packages.
Args:
*packages (list): the list of packages to check for.
enforce_init (bool):
whether to assert presence of __init__.py files
in directories.
depth (int): the depth of the matrix to generate.
Returns:
archan.DSM: instance of archan DSM.
"""
dsm = DependenpyDSM(*packages, enforce_init=enforce_init)
if depth is None:
depth = guess_depth(packages)
matrix = dsm.as_matrix(depth=depth)
return ArchanDSM(data=matrix.data, entities=matrix.keys)
except ImportError:
class InternalDependencies(object):
"""Empty dependenpy provider."""
## Instruction:
Update archan provider for archan 3.0
## Code After:
"""dependenpy plugins module."""
try:
from archan import Provider, Argument, DesignStructureMatrix as ArchanDSM
from .dsm import DSM as DependenpyDSM
from .helpers import guess_depth
class InternalDependencies(Provider):
"""Dependenpy provider for Archan."""
identifier = 'dependenpy.InternalDependencies'
name = 'Internal Dependencies'
description = 'Provide matrix data about internal dependencies ' \
'in a set of packages.'
argument_list = (
Argument('packages', list, 'The list of packages to check for.'),
Argument('enforce_init', bool, default=True,
description='Whether to assert presence of '
'__init__.py files in directories.'),
Argument('depth', int, 'The depth of the matrix to generate.'),
)
def get_data(self, packages, enforce_init=True, depth=None):
"""
Provide matrix data for internal dependencies in a set of packages.
Args:
*packages (list): the list of packages to check for.
enforce_init (bool):
whether to assert presence of __init__.py files
in directories.
depth (int): the depth of the matrix to generate.
Returns:
archan.DSM: instance of archan DSM.
"""
dsm = DependenpyDSM(*packages, enforce_init=enforce_init)
if depth is None:
depth = guess_depth(packages)
matrix = dsm.as_matrix(depth=depth)
return ArchanDSM(data=matrix.data, entities=matrix.keys)
except ImportError:
class InternalDependencies(object):
"""Empty dependenpy provider."""
|
// ... existing code ...
"""dependenpy plugins module."""
try:
from archan import Provider, Argument, DesignStructureMatrix as ArchanDSM
from .dsm import DSM as DependenpyDSM
from .helpers import guess_depth
// ... modified code ...
name = 'Internal Dependencies'
description = 'Provide matrix data about internal dependencies ' \
'in a set of packages.'
argument_list = (
Argument('packages', list, 'The list of packages to check for.'),
Argument('enforce_init', bool, default=True,
description='Whether to assert presence of '
...
Argument('depth', int, 'The depth of the matrix to generate.'),
)
def get_data(self, packages, enforce_init=True, depth=None):
"""
Provide matrix data for internal dependencies in a set of packages.
// ... rest of the code ...
|
74adefcad1fe411b596981da7d124cda2f8e936d
|
mopidy/backends/local/__init__.py
|
mopidy/backends/local/__init__.py
|
from __future__ import unicode_literals
import mopidy
from mopidy import ext
__doc__ = """A backend for playing music from a local music archive.
This backend handles URIs starting with ``file:``.
See :ref:`music-from-local-storage` for further instructions on using this
backend.
**Issues:**
https://github.com/mopidy/mopidy/issues?labels=Local+backend
**Dependencies:**
- None
**Settings:**
- :attr:`mopidy.settings.LOCAL_MUSIC_PATH`
- :attr:`mopidy.settings.LOCAL_PLAYLIST_PATH`
- :attr:`mopidy.settings.LOCAL_TAG_CACHE_FILE`
"""
class Extension(ext.Extension):
name = 'Mopidy-Local'
version = mopidy.__version__
def get_default_config(self):
return '[ext.local]'
def validate_config(self, config):
pass
def validate_environment(self):
pass
def get_backend_classes(self):
from .actor import LocalBackend
return [LocalBackend]
|
from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.utils import config, formatting
default_config = """
[ext.local]
# If the local extension should be enabled or not
enabled = true
# Path to folder with local music
music_path = $XDG_MUSIC_DIR
# Path to playlist folder with m3u files for local music
playlist_path = $XDG_DATA_DIR/mopidy/playlists
# Path to tag cache for local music
tag_cache_file = $XDG_DATA_DIR/mopidy/tag_cache
"""
__doc__ = """A backend for playing music from a local music archive.
This backend handles URIs starting with ``file:``.
See :ref:`music-from-local-storage` for further instructions on using this
backend.
**Issues:**
https://github.com/mopidy/mopidy/issues?labels=Local+backend
**Dependencies:**
- None
**Default config:**
.. code-block:: ini
%(config)s
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Local'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['music_path'] = config.String()
schema['playlist_path'] = config.String()
schema['tag_cache_file'] = config.String()
def validate_environment(self):
pass
def get_backend_classes(self):
from .actor import LocalBackend
return [LocalBackend]
|
Add default config and config schema
|
local: Add default config and config schema
|
Python
|
apache-2.0
|
jmarsik/mopidy,jmarsik/mopidy,jodal/mopidy,rawdlite/mopidy,ali/mopidy,SuperStarPL/mopidy,jcass77/mopidy,adamcik/mopidy,pacificIT/mopidy,diandiankan/mopidy,tkem/mopidy,swak/mopidy,diandiankan/mopidy,bacontext/mopidy,mokieyue/mopidy,pacificIT/mopidy,swak/mopidy,ZenithDK/mopidy,vrs01/mopidy,bencevans/mopidy,bacontext/mopidy,quartz55/mopidy,abarisain/mopidy,hkariti/mopidy,tkem/mopidy,mopidy/mopidy,hkariti/mopidy,dbrgn/mopidy,SuperStarPL/mopidy,SuperStarPL/mopidy,ZenithDK/mopidy,mokieyue/mopidy,abarisain/mopidy,quartz55/mopidy,ali/mopidy,priestd09/mopidy,dbrgn/mopidy,kingosticks/mopidy,swak/mopidy,dbrgn/mopidy,glogiotatidis/mopidy,hkariti/mopidy,bencevans/mopidy,bacontext/mopidy,quartz55/mopidy,SuperStarPL/mopidy,diandiankan/mopidy,glogiotatidis/mopidy,hkariti/mopidy,priestd09/mopidy,jmarsik/mopidy,woutervanwijk/mopidy,dbrgn/mopidy,jmarsik/mopidy,woutervanwijk/mopidy,bencevans/mopidy,diandiankan/mopidy,jcass77/mopidy,priestd09/mopidy,bacontext/mopidy,ZenithDK/mopidy,ZenithDK/mopidy,vrs01/mopidy,mopidy/mopidy,bencevans/mopidy,mokieyue/mopidy,adamcik/mopidy,liamw9534/mopidy,tkem/mopidy,quartz55/mopidy,rawdlite/mopidy,adamcik/mopidy,ali/mopidy,glogiotatidis/mopidy,rawdlite/mopidy,rawdlite/mopidy,liamw9534/mopidy,jcass77/mopidy,swak/mopidy,tkem/mopidy,mokieyue/mopidy,kingosticks/mopidy,jodal/mopidy,mopidy/mopidy,ali/mopidy,kingosticks/mopidy,pacificIT/mopidy,pacificIT/mopidy,vrs01/mopidy,vrs01/mopidy,jodal/mopidy,glogiotatidis/mopidy
|
python
|
## Code Before:
from __future__ import unicode_literals
import mopidy
from mopidy import ext
__doc__ = """A backend for playing music from a local music archive.
This backend handles URIs starting with ``file:``.
See :ref:`music-from-local-storage` for further instructions on using this
backend.
**Issues:**
https://github.com/mopidy/mopidy/issues?labels=Local+backend
**Dependencies:**
- None
**Settings:**
- :attr:`mopidy.settings.LOCAL_MUSIC_PATH`
- :attr:`mopidy.settings.LOCAL_PLAYLIST_PATH`
- :attr:`mopidy.settings.LOCAL_TAG_CACHE_FILE`
"""
class Extension(ext.Extension):
name = 'Mopidy-Local'
version = mopidy.__version__
def get_default_config(self):
return '[ext.local]'
def validate_config(self, config):
pass
def validate_environment(self):
pass
def get_backend_classes(self):
from .actor import LocalBackend
return [LocalBackend]
## Instruction:
local: Add default config and config schema
## Code After:
from __future__ import unicode_literals
import mopidy
from mopidy import ext
from mopidy.utils import config, formatting
default_config = """
[ext.local]
# If the local extension should be enabled or not
enabled = true
# Path to folder with local music
music_path = $XDG_MUSIC_DIR
# Path to playlist folder with m3u files for local music
playlist_path = $XDG_DATA_DIR/mopidy/playlists
# Path to tag cache for local music
tag_cache_file = $XDG_DATA_DIR/mopidy/tag_cache
"""
__doc__ = """A backend for playing music from a local music archive.
This backend handles URIs starting with ``file:``.
See :ref:`music-from-local-storage` for further instructions on using this
backend.
**Issues:**
https://github.com/mopidy/mopidy/issues?labels=Local+backend
**Dependencies:**
- None
**Default config:**
.. code-block:: ini
%(config)s
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
name = 'Mopidy-Local'
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['music_path'] = config.String()
schema['playlist_path'] = config.String()
schema['tag_cache_file'] = config.String()
def validate_environment(self):
pass
def get_backend_classes(self):
from .actor import LocalBackend
return [LocalBackend]
|
...
import mopidy
from mopidy import ext
from mopidy.utils import config, formatting
default_config = """
[ext.local]
# If the local extension should be enabled or not
enabled = true
# Path to folder with local music
music_path = $XDG_MUSIC_DIR
# Path to playlist folder with m3u files for local music
playlist_path = $XDG_DATA_DIR/mopidy/playlists
# Path to tag cache for local music
tag_cache_file = $XDG_DATA_DIR/mopidy/tag_cache
"""
__doc__ = """A backend for playing music from a local music archive.
...
- None
**Default config:**
.. code-block:: ini
%(config)s
""" % {'config': formatting.indent(default_config)}
class Extension(ext.Extension):
...
version = mopidy.__version__
def get_default_config(self):
return default_config
def get_config_schema(self):
schema = config.ExtensionConfigSchema()
schema['music_path'] = config.String()
schema['playlist_path'] = config.String()
schema['tag_cache_file'] = config.String()
def validate_environment(self):
pass
...
|
2bd14f768ce7d82f7ef84d1e67d61afda5044581
|
st2common/st2common/constants/logging.py
|
st2common/st2common/constants/logging.py
|
import os
__all__ = [
'DEFAULT_LOGGING_CONF_PATH'
]
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
DEFAULT_LOGGING_CONF_PATH = os.path.join(BASE_PATH, '../conf/base.logging.conf')
DEFAULT_LOGGING_CONF_PATH = os.path.abspath(DEFAULT_LOGGING_CONF_PATH)
|
import os
__all__ = [
'DEFAULT_LOGGING_CONF_PATH'
]
BASE_PATH = os.path.dirname(os.path.abspath((__file__)))
DEFAULT_LOGGING_CONF_PATH = os.path.join(BASE_PATH, '../conf/base.logging.conf')
DEFAULT_LOGGING_CONF_PATH = os.path.abspath(DEFAULT_LOGGING_CONF_PATH)
|
Use the correct base path.
|
Use the correct base path.
|
Python
|
apache-2.0
|
punalpatel/st2,lakshmi-kannan/st2,Plexxi/st2,jtopjian/st2,Plexxi/st2,grengojbo/st2,emedvedev/st2,punalpatel/st2,peak6/st2,dennybaa/st2,alfasin/st2,Plexxi/st2,Itxaka/st2,pinterb/st2,StackStorm/st2,nzlosh/st2,grengojbo/st2,nzlosh/st2,Itxaka/st2,pixelrebel/st2,Plexxi/st2,tonybaloney/st2,peak6/st2,StackStorm/st2,jtopjian/st2,lakshmi-kannan/st2,Itxaka/st2,StackStorm/st2,alfasin/st2,emedvedev/st2,grengojbo/st2,pinterb/st2,pixelrebel/st2,pixelrebel/st2,dennybaa/st2,StackStorm/st2,nzlosh/st2,tonybaloney/st2,armab/st2,lakshmi-kannan/st2,armab/st2,nzlosh/st2,pinterb/st2,jtopjian/st2,punalpatel/st2,dennybaa/st2,peak6/st2,emedvedev/st2,alfasin/st2,tonybaloney/st2,armab/st2
|
python
|
## Code Before:
import os
__all__ = [
'DEFAULT_LOGGING_CONF_PATH'
]
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
DEFAULT_LOGGING_CONF_PATH = os.path.join(BASE_PATH, '../conf/base.logging.conf')
DEFAULT_LOGGING_CONF_PATH = os.path.abspath(DEFAULT_LOGGING_CONF_PATH)
## Instruction:
Use the correct base path.
## Code After:
import os
__all__ = [
'DEFAULT_LOGGING_CONF_PATH'
]
BASE_PATH = os.path.dirname(os.path.abspath((__file__)))
DEFAULT_LOGGING_CONF_PATH = os.path.join(BASE_PATH, '../conf/base.logging.conf')
DEFAULT_LOGGING_CONF_PATH = os.path.abspath(DEFAULT_LOGGING_CONF_PATH)
|
...
'DEFAULT_LOGGING_CONF_PATH'
]
BASE_PATH = os.path.dirname(os.path.abspath((__file__)))
DEFAULT_LOGGING_CONF_PATH = os.path.join(BASE_PATH, '../conf/base.logging.conf')
DEFAULT_LOGGING_CONF_PATH = os.path.abspath(DEFAULT_LOGGING_CONF_PATH)
...
|
acaacbea4fbfdcc0f1f0c5e0aa9a837dee439d08
|
saau/sections/image_provider.py
|
saau/sections/image_provider.py
|
import json
import inspect
from os.path import join, exists
def not_implemented():
frame_info = inspect.currentframe().f_back
msg = ''
if 'self' in frame_info.f_locals:
self = frame_info.f_locals['self']
try:
msg += self.__name__ + '#' # for static/class methods
except AttributeError:
msg += self.__class__.__name__ + '.'
msg += frame_info.f_code.co_name + '()'
return NotImplementedError(msg)
class RequiresData:
def __init__(self, data_dir, services):
self.data_dir = data_dir
self.services = services
def has_required_data(self):
raise not_implemented()
def obtain_data(self):
raise not_implemented()
def data_dir_exists(self, name):
return exists(self.data_dir_join(name))
def data_dir_join(self, name):
return join(self.data_dir, name)
def save_json(self, name, data):
with open(self.data_dir_join(name), 'w') as fh:
json.dump(data, fh, indent=4)
return True
def load_json(self, name):
with open(self.data_dir_join(name)) as fh:
return json.load(fh)
class ImageProvider(RequiresData):
def build_image(self):
raise not_implemented()
|
import inspect
import json
from os.path import exists, join
from pathlib import Path
from typing import Any, Union
from ..services import Services
PathOrStr = Union[str,Path]
def not_implemented():
frame_info = inspect.currentframe().f_back
msg = ''
if 'self' in frame_info.f_locals:
self = frame_info.f_locals['self']
try:
msg += self.__name__ + '#' # for static/class methods
except AttributeError:
msg += self.__class__.__name__ + '.'
msg += frame_info.f_code.co_name + '()'
return NotImplementedError(msg)
class RequiresData:
def __init__(self, data_dir: Path, services: Services) -> None:
self.data_dir = data_dir
self.services = services
def has_required_data(self) -> bool:
raise not_implemented()
def obtain_data(self) -> bool:
raise not_implemented()
def data_dir_exists(self, name: PathOrStr) -> bool:
return exists(self.data_dir_join(name))
def data_dir_join(self, name: PathOrStr) -> str:
return join(self.data_dir, name)
def save_json(self, name: PathOrStr, data: Any) -> bool:
with open(self.data_dir_join(name), 'w') as fh:
json.dump(data, fh, indent=4)
return True
def load_json(self, name: PathOrStr) -> Any:
with open(self.data_dir_join(name)) as fh:
return json.load(fh)
class ImageProvider(RequiresData):
def build_image(self) -> str:
raise not_implemented()
|
Add types to ImageProvider and RequiresData
|
Add types to ImageProvider and RequiresData
|
Python
|
mit
|
Mause/statistical_atlas_of_au
|
python
|
## Code Before:
import json
import inspect
from os.path import join, exists
def not_implemented():
frame_info = inspect.currentframe().f_back
msg = ''
if 'self' in frame_info.f_locals:
self = frame_info.f_locals['self']
try:
msg += self.__name__ + '#' # for static/class methods
except AttributeError:
msg += self.__class__.__name__ + '.'
msg += frame_info.f_code.co_name + '()'
return NotImplementedError(msg)
class RequiresData:
def __init__(self, data_dir, services):
self.data_dir = data_dir
self.services = services
def has_required_data(self):
raise not_implemented()
def obtain_data(self):
raise not_implemented()
def data_dir_exists(self, name):
return exists(self.data_dir_join(name))
def data_dir_join(self, name):
return join(self.data_dir, name)
def save_json(self, name, data):
with open(self.data_dir_join(name), 'w') as fh:
json.dump(data, fh, indent=4)
return True
def load_json(self, name):
with open(self.data_dir_join(name)) as fh:
return json.load(fh)
class ImageProvider(RequiresData):
def build_image(self):
raise not_implemented()
## Instruction:
Add types to ImageProvider and RequiresData
## Code After:
import inspect
import json
from os.path import exists, join
from pathlib import Path
from typing import Any, Union
from ..services import Services
PathOrStr = Union[str,Path]
def not_implemented():
frame_info = inspect.currentframe().f_back
msg = ''
if 'self' in frame_info.f_locals:
self = frame_info.f_locals['self']
try:
msg += self.__name__ + '#' # for static/class methods
except AttributeError:
msg += self.__class__.__name__ + '.'
msg += frame_info.f_code.co_name + '()'
return NotImplementedError(msg)
class RequiresData:
def __init__(self, data_dir: Path, services: Services) -> None:
self.data_dir = data_dir
self.services = services
def has_required_data(self) -> bool:
raise not_implemented()
def obtain_data(self) -> bool:
raise not_implemented()
def data_dir_exists(self, name: PathOrStr) -> bool:
return exists(self.data_dir_join(name))
def data_dir_join(self, name: PathOrStr) -> str:
return join(self.data_dir, name)
def save_json(self, name: PathOrStr, data: Any) -> bool:
with open(self.data_dir_join(name), 'w') as fh:
json.dump(data, fh, indent=4)
return True
def load_json(self, name: PathOrStr) -> Any:
with open(self.data_dir_join(name)) as fh:
return json.load(fh)
class ImageProvider(RequiresData):
def build_image(self) -> str:
raise not_implemented()
|
// ... existing code ...
import inspect
import json
from os.path import exists, join
from pathlib import Path
from typing import Any, Union
from ..services import Services
PathOrStr = Union[str,Path]
def not_implemented():
// ... modified code ...
class RequiresData:
def __init__(self, data_dir: Path, services: Services) -> None:
self.data_dir = data_dir
self.services = services
def has_required_data(self) -> bool:
raise not_implemented()
def obtain_data(self) -> bool:
raise not_implemented()
def data_dir_exists(self, name: PathOrStr) -> bool:
return exists(self.data_dir_join(name))
def data_dir_join(self, name: PathOrStr) -> str:
return join(self.data_dir, name)
def save_json(self, name: PathOrStr, data: Any) -> bool:
with open(self.data_dir_join(name), 'w') as fh:
json.dump(data, fh, indent=4)
return True
def load_json(self, name: PathOrStr) -> Any:
with open(self.data_dir_join(name)) as fh:
return json.load(fh)
class ImageProvider(RequiresData):
def build_image(self) -> str:
raise not_implemented()
// ... rest of the code ...
|
e120c264f16f89b197ff3416deaefb7f553611db
|
pages/urlconf_registry.py
|
pages/urlconf_registry.py
|
"""Django page CMS urlconf registry."""
from django.utils.translation import ugettext as _
class UrlconfAlreadyRegistered(Exception):
"""
An attempt was made to register a widget for Django page CMS more
than once.
"""
class UrlconfNotFound(Exception):
"""
The requested widget was not found
"""
registry = []
def get_choices():
choices = [('', 'No delegation')]
for reg in registry:
if reg[2]:
label = reg[2]
else:
label = reg[0]
choices.append((reg[0], label))
return choices
def register_urlconf(name, urlconf, label=None):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
raise UrlconfAlreadyRegistered(
_('The urlconf %s has already been registered.') % name)
urlconf_tuple = (name, urlconf, label, urlconf)
registry.append(urlconf_tuple)
def get_urlconf(name):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
return urlconf_tuple[1]
raise UrlconfNotFound(
_('The urlconf %s has not been registered.') % name)
|
"""Django page CMS urlconf registry."""
from django.utils.translation import ugettext as _
class UrlconfAlreadyRegistered(Exception):
"""
An attempt was made to register a urlconf for Django page CMS more
than once.
"""
class UrlconfNotFound(Exception):
"""
The requested urlconf was not found
"""
registry = []
def get_choices():
choices = [('', 'No delegation')]
for reg in registry:
if reg[2]:
label = reg[2]
else:
label = reg[0]
choices.append((reg[0], label))
return choices
def register_urlconf(name, urlconf, label=None):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
raise UrlconfAlreadyRegistered(
_('The urlconf %s has already been registered.') % name)
urlconf_tuple = (name, urlconf, label, urlconf)
registry.append(urlconf_tuple)
def get_urlconf(name):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
return urlconf_tuple[1]
raise UrlconfNotFound(
_('The urlconf %s has not been registered.') % name)
|
Fix typos in urlconf registry
|
Fix typos in urlconf registry
|
Python
|
bsd-3-clause
|
batiste/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms
|
python
|
## Code Before:
"""Django page CMS urlconf registry."""
from django.utils.translation import ugettext as _
class UrlconfAlreadyRegistered(Exception):
"""
An attempt was made to register a widget for Django page CMS more
than once.
"""
class UrlconfNotFound(Exception):
"""
The requested widget was not found
"""
registry = []
def get_choices():
choices = [('', 'No delegation')]
for reg in registry:
if reg[2]:
label = reg[2]
else:
label = reg[0]
choices.append((reg[0], label))
return choices
def register_urlconf(name, urlconf, label=None):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
raise UrlconfAlreadyRegistered(
_('The urlconf %s has already been registered.') % name)
urlconf_tuple = (name, urlconf, label, urlconf)
registry.append(urlconf_tuple)
def get_urlconf(name):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
return urlconf_tuple[1]
raise UrlconfNotFound(
_('The urlconf %s has not been registered.') % name)
## Instruction:
Fix typos in urlconf registry
## Code After:
"""Django page CMS urlconf registry."""
from django.utils.translation import ugettext as _
class UrlconfAlreadyRegistered(Exception):
"""
An attempt was made to register a urlconf for Django page CMS more
than once.
"""
class UrlconfNotFound(Exception):
"""
The requested urlconf was not found
"""
registry = []
def get_choices():
choices = [('', 'No delegation')]
for reg in registry:
if reg[2]:
label = reg[2]
else:
label = reg[0]
choices.append((reg[0], label))
return choices
def register_urlconf(name, urlconf, label=None):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
raise UrlconfAlreadyRegistered(
_('The urlconf %s has already been registered.') % name)
urlconf_tuple = (name, urlconf, label, urlconf)
registry.append(urlconf_tuple)
def get_urlconf(name):
for urlconf_tuple in registry:
if urlconf_tuple[0] == name:
return urlconf_tuple[1]
raise UrlconfNotFound(
_('The urlconf %s has not been registered.') % name)
|
...
class UrlconfAlreadyRegistered(Exception):
"""
An attempt was made to register a urlconf for Django page CMS more
than once.
"""
class UrlconfNotFound(Exception):
"""
The requested urlconf was not found
"""
registry = []
...
|
799ed61e049da558f2fd87db8ef3bf0ad888681c
|
monasca/common/messaging/message_formats/reference/metrics.py
|
monasca/common/messaging/message_formats/reference/metrics.py
|
from oslo_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(transformed_metric)
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric
|
import copy
from oslo_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(copy.deepcopy(transformed_metric))
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric
|
Correct the 'reference' format transform method
|
Correct the 'reference' format transform method
Currently, the 'reference' format transform method will traversal the
metrics list and reconstruct every item of the list to add tenant_id and
region info, but new transformed metrics list will use the reference
of the local dict variable "transformed_metric", that will lead that all
the items of the transformed metrics list be the same value.
Change-Id: Id7f4e18ca3ae0fa93cdafe0d63b7e90c96ce4b28
Closes-bug: #1439055
|
Python
|
apache-2.0
|
stackforge/monasca-api,hpcloud-mon/monasca-events-api,openstack/monasca-api,sapcc/monasca-api,stackforge/monasca-api,hpcloud-mon/monasca-events-api,stackforge/monasca-api,hpcloud-mon/monasca-events-api,oneilcin/monasca-events-api,oneilcin/monasca-events-api,hpcloud-mon/monasca-events-api,sapcc/monasca-api,oneilcin/monasca-events-api,oneilcin/monasca-events-api,sapcc/monasca-api,openstack/monasca-api,stackforge/monasca-api,openstack/monasca-api
|
python
|
## Code Before:
from oslo_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(transformed_metric)
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric
## Instruction:
Correct the 'reference' format transform method
Currently, the 'reference' format transform method will traversal the
metrics list and reconstruct every item of the list to add tenant_id and
region info, but new transformed metrics list will use the reference
of the local dict variable "transformed_metric", that will lead that all
the items of the transformed metrics list be the same value.
Change-Id: Id7f4e18ca3ae0fa93cdafe0d63b7e90c96ce4b28
Closes-bug: #1439055
## Code After:
import copy
from oslo_utils import timeutils
def transform(metrics, tenant_id, region):
transformed_metric = {'metric': {},
'meta': {'tenantId': tenant_id, 'region': region},
'creation_time': timeutils.utcnow_ts()}
if isinstance(metrics, list):
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(copy.deepcopy(transformed_metric))
return transformed_metrics
else:
transformed_metric['metric'] = metrics
return transformed_metric
|
...
import copy
from oslo_utils import timeutils
...
transformed_metrics = []
for metric in metrics:
transformed_metric['metric'] = metric
transformed_metrics.append(copy.deepcopy(transformed_metric))
return transformed_metrics
else:
transformed_metric['metric'] = metrics
...
|
2abf0e6b9009abd7c34b459ad9e3f2c6223bb043
|
polyaxon/db/getters/experiment_groups.py
|
polyaxon/db/getters/experiment_groups.py
|
import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
|
import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group or not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
|
Add condition to check if experiment group exists before checking status
|
Add condition to check if experiment group exists before checking status
|
Python
|
apache-2.0
|
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
|
python
|
## Code Before:
import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
## Instruction:
Add condition to check if experiment group exists before checking status
## Code After:
import logging
from db.models.experiment_groups import ExperimentGroup
_logger = logging.getLogger('polyaxon.db')
def get_valid_experiment_group(experiment_group_id):
try:
return ExperimentGroup.objects.get(id=experiment_group_id)
except ExperimentGroup.DoesNotExist:
_logger.info('ExperimentGroup `%s` was not found.', experiment_group_id)
return None
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group or not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
return experiment_group
|
...
def get_running_experiment_group(experiment_group_id):
experiment_group = get_valid_experiment_group(experiment_group_id=experiment_group_id)
if not experiment_group or not experiment_group.is_running:
_logger.info('ExperimentGroup `%s` is not running.', experiment_group_id)
return None
...
|
e45b3d3a2428d3703260c25b4275359bf6786a37
|
launcher.py
|
launcher.py
|
from pract2d.game import gamemanager
if __name__ == '__main__':
game = gamemanager.GameManager()
game.run()
|
from pract2d.game import gamemanager
from pract2d.core import files
from platform import system
import os
if __name__ == '__main__':
try:
if system() == 'Windows' or not os.environ["PYSDL2_DLL_PATH"]:
os.environ["PYSDL2_DLL_PATH"] = files.get_path()
except KeyError:
pass
game = gamemanager.GameManager()
game.run()
|
Set the default sdl2 library locations.
|
Set the default sdl2 library locations.
|
Python
|
bsd-2-clause
|
mdsitton/pract2d
|
python
|
## Code Before:
from pract2d.game import gamemanager
if __name__ == '__main__':
game = gamemanager.GameManager()
game.run()
## Instruction:
Set the default sdl2 library locations.
## Code After:
from pract2d.game import gamemanager
from pract2d.core import files
from platform import system
import os
if __name__ == '__main__':
try:
if system() == 'Windows' or not os.environ["PYSDL2_DLL_PATH"]:
os.environ["PYSDL2_DLL_PATH"] = files.get_path()
except KeyError:
pass
game = gamemanager.GameManager()
game.run()
|
# ... existing code ...
from pract2d.game import gamemanager
from pract2d.core import files
from platform import system
import os
if __name__ == '__main__':
try:
if system() == 'Windows' or not os.environ["PYSDL2_DLL_PATH"]:
os.environ["PYSDL2_DLL_PATH"] = files.get_path()
except KeyError:
pass
game = gamemanager.GameManager()
game.run()
# ... rest of the code ...
|
10db07f1fc432f6f3e1e530d28cfbfd6ada0a321
|
versebot/webparser.py
|
versebot/webparser.py
|
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Parser:
""" Parser class for BibleGateway parsing methods. """
def __init__(self):
""" Initializes translations attribute and checks if there are any new translations
to add to the database. """
trans = self.find_supported_translations()
if trans is None:
self.translations = None
else:
self.translations = trans.sort(key=len, reverse=True)
def find_supported_translations(self):
""" Retrieves a list of supported translations from BibleGateway's translation
page. """
url = "http://www.biblegateway.com/versions/"
translations = list()
page = urlopen(url)
soup = BeautifulSoup(page.read())
# It seems that BibleGateway has changed the layout of their versions page. This needs
# to be redone!
translations = soup.find("select", {"class":"search-translation-select"})
trans = translations.findAll("option")
for t in trans:
if t.has_attr("value") and not t.has_attr("class"):
cur_trans = t["value"]
translations.append(cur_trans)
# Add local translations to supported translations list
translations.append("NJPS")
return translations
|
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Parser:
""" Parser class for BibleGateway parsing methods. """
def __init__(self):
""" Initializes translations attribute and checks if there are any new translations
to add to the database. """
trans = self.find_supported_translations()
if trans is None:
self.translations = None
else:
self.translations = trans.sort(key=len, reverse=True)
def find_supported_translations(self):
""" Retrieves a list of supported translations from BibleGateway's translation
page. """
url = "https://www.biblegateway.com/versions/"
translations = list()
page = urlopen(url)
soup = BeautifulSoup(page.read())
# It seems that BibleGateway has changed the layout of their versions page. This needs
# to be redone!
translations_select = soup.find("select", {"class":"search-translation-select"})
trans = translations_select.findAll("option")
for t in trans:
if t.has_attr("value") and not t.has_attr("class"):
cur_trans = t["value"]
translations.append(cur_trans)
# Add local translations to supported translations list
translations.append("NJPS")
return translations
|
Rename translations to translations_select, switch to HTTPS
|
Rename translations to translations_select, switch to HTTPS
|
Python
|
mit
|
Matthew-Arnold/slack-versebot,Matthew-Arnold/slack-versebot
|
python
|
## Code Before:
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Parser:
""" Parser class for BibleGateway parsing methods. """
def __init__(self):
""" Initializes translations attribute and checks if there are any new translations
to add to the database. """
trans = self.find_supported_translations()
if trans is None:
self.translations = None
else:
self.translations = trans.sort(key=len, reverse=True)
def find_supported_translations(self):
""" Retrieves a list of supported translations from BibleGateway's translation
page. """
url = "http://www.biblegateway.com/versions/"
translations = list()
page = urlopen(url)
soup = BeautifulSoup(page.read())
# It seems that BibleGateway has changed the layout of their versions page. This needs
# to be redone!
translations = soup.find("select", {"class":"search-translation-select"})
trans = translations.findAll("option")
for t in trans:
if t.has_attr("value") and not t.has_attr("class"):
cur_trans = t["value"]
translations.append(cur_trans)
# Add local translations to supported translations list
translations.append("NJPS")
return translations
## Instruction:
Rename translations to translations_select, switch to HTTPS
## Code After:
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Parser:
""" Parser class for BibleGateway parsing methods. """
def __init__(self):
""" Initializes translations attribute and checks if there are any new translations
to add to the database. """
trans = self.find_supported_translations()
if trans is None:
self.translations = None
else:
self.translations = trans.sort(key=len, reverse=True)
def find_supported_translations(self):
""" Retrieves a list of supported translations from BibleGateway's translation
page. """
url = "https://www.biblegateway.com/versions/"
translations = list()
page = urlopen(url)
soup = BeautifulSoup(page.read())
# It seems that BibleGateway has changed the layout of their versions page. This needs
# to be redone!
translations_select = soup.find("select", {"class":"search-translation-select"})
trans = translations_select.findAll("option")
for t in trans:
if t.has_attr("value") and not t.has_attr("class"):
cur_trans = t["value"]
translations.append(cur_trans)
# Add local translations to supported translations list
translations.append("NJPS")
return translations
|
...
def find_supported_translations(self):
""" Retrieves a list of supported translations from BibleGateway's translation
page. """
url = "https://www.biblegateway.com/versions/"
translations = list()
page = urlopen(url)
...
# It seems that BibleGateway has changed the layout of their versions page. This needs
# to be redone!
translations_select = soup.find("select", {"class":"search-translation-select"})
trans = translations_select.findAll("option")
for t in trans:
if t.has_attr("value") and not t.has_attr("class"):
cur_trans = t["value"]
...
|
4f3ac8b211b32dbb0d3025c178749f9689f853d6
|
src/org/biojava/bio/seq/SimpleSequenceFactory.java
|
src/org/biojava/bio/seq/SimpleSequenceFactory.java
|
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.seq;
import java.io.Serializable;
import org.biojava.bio.*;
import org.biojava.bio.symbol.*;
/**
* A no-frills implementation of SequenceFactory that produces SimpleSequence
* objects.
*
* @author Matthew Pocock
*/
public class SimpleSequenceFactory implements SequenceFactory, Serializable {
public Sequence createSequence(SymbolList resList,
String uri, String name, Annotation annotation) {
return new SimpleSequence(resList, uri, name, annotation);
}
}
|
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.seq;
import java.io.Serializable;
import org.biojava.bio.*;
import org.biojava.bio.symbol.*;
/**
* A no-frills implementation of SequenceFactory that produces SimpleSequence
* objects.
*
* @author Matthew Pocock
* @author Thomas Down
*/
public class SimpleSequenceFactory implements SequenceFactory, Serializable {
private FeatureRealizer realizer = SimpleFeatureRealizer.DEFAULT;
public FeatureRealizer getFeatureRealizer() {
return realizer;
}
/**
* Set the FeatureRealizer used by new sequences created by this
* factory.
*/
public void setFeatureRealizer(FeatureRealizer fr) {
realizer = fr;
}
public Sequence createSequence(SymbolList resList,
String uri, String name, Annotation annotation) {
return new SimpleSequence(resList, uri, name, annotation, realizer);
}
}
|
Add a property to set the FeatureRealizer used by created sequences.
|
Add a property to set the FeatureRealizer used by created sequences.
git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@781 7c6358e6-4a41-0410-a743-a5b2a554c398
|
Java
|
lgpl-2.1
|
sbliven/biojava,sbliven/biojava,sbliven/biojava
|
java
|
## Code Before:
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.seq;
import java.io.Serializable;
import org.biojava.bio.*;
import org.biojava.bio.symbol.*;
/**
* A no-frills implementation of SequenceFactory that produces SimpleSequence
* objects.
*
* @author Matthew Pocock
*/
public class SimpleSequenceFactory implements SequenceFactory, Serializable {
public Sequence createSequence(SymbolList resList,
String uri, String name, Annotation annotation) {
return new SimpleSequence(resList, uri, name, annotation);
}
}
## Instruction:
Add a property to set the FeatureRealizer used by created sequences.
git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@781 7c6358e6-4a41-0410-a743-a5b2a554c398
## Code After:
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.seq;
import java.io.Serializable;
import org.biojava.bio.*;
import org.biojava.bio.symbol.*;
/**
* A no-frills implementation of SequenceFactory that produces SimpleSequence
* objects.
*
* @author Matthew Pocock
* @author Thomas Down
*/
public class SimpleSequenceFactory implements SequenceFactory, Serializable {
private FeatureRealizer realizer = SimpleFeatureRealizer.DEFAULT;
public FeatureRealizer getFeatureRealizer() {
return realizer;
}
/**
* Set the FeatureRealizer used by new sequences created by this
* factory.
*/
public void setFeatureRealizer(FeatureRealizer fr) {
realizer = fr;
}
public Sequence createSequence(SymbolList resList,
String uri, String name, Annotation annotation) {
return new SimpleSequence(resList, uri, name, annotation, realizer);
}
}
|
...
* objects.
*
* @author Matthew Pocock
* @author Thomas Down
*/
public class SimpleSequenceFactory implements SequenceFactory, Serializable {
private FeatureRealizer realizer = SimpleFeatureRealizer.DEFAULT;
public FeatureRealizer getFeatureRealizer() {
return realizer;
}
/**
* Set the FeatureRealizer used by new sequences created by this
* factory.
*/
public void setFeatureRealizer(FeatureRealizer fr) {
realizer = fr;
}
public Sequence createSequence(SymbolList resList,
String uri, String name, Annotation annotation) {
return new SimpleSequence(resList, uri, name, annotation, realizer);
}
}
...
|
b57d5ecf56640c9d0a69b565006e2240662d6b46
|
profile_collection/startup/11-temperature-controller.py
|
profile_collection/startup/11-temperature-controller.py
|
from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO
from ophyd import Component as C
from ophyd.device import DeviceStatus
class CS700TemperatureController(PVPositioner):
setpoint = C(EpicsSignal, 'T-SP')
readback = C(EpicsSignalRO, 'T-I')
done = C(EpicsSignalRO, 'Cmd-Busy')
stop_signal = C(EpicsSignal, 'Cmd-Cmd')
def trigger(self):
# There is nothing to do. Just report that we are done.
# Note: This really should not necessary to do --
# future changes to PVPositioner may obviate this code.
status = DeviceStatus()
status._finished()
return status
cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700',
settle_time=10)
cs700.done_value = 0
cs700.read_attrs = ['setpoint', 'readback']
cs700.readback.name = 'temperautre'
cs700.setpoint.name = 'temperautre_setpoint'
|
from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO
from ophyd import Component as C
from ophyd.device import DeviceStatus
class CS700TemperatureController(PVPositioner):
setpoint = C(EpicsSignal, 'T-SP')
readback = C(EpicsSignalRO, 'T-I')
done = C(EpicsSignalRO, 'Cmd-Busy')
stop_signal = C(EpicsSignal, 'Cmd-Cmd')
def trigger(self):
# There is nothing to do. Just report that we are done.
# Note: This really should not necessary to do --
# future changes to PVPositioner may obviate this code.
status = DeviceStatus()
status._finished()
return status
cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700')
# this functionality never worked, has now been removed, but will shortly be
# coming back
# settle_time=10)
cs700.done_value = 0
cs700.read_attrs = ['setpoint', 'readback']
cs700.readback.name = 'temperautre'
cs700.setpoint.name = 'temperautre_setpoint'
|
Remove settle_time kwarg from c700
|
Remove settle_time kwarg from c700
This kwarg has been removed from ophyd, but will be coming back (and be
functional) soon. Revert these changes when that happens: ophyd 0.2.1)
|
Python
|
bsd-2-clause
|
NSLS-II-XPD/ipython_ophyd,NSLS-II-XPD/ipython_ophyd
|
python
|
## Code Before:
from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO
from ophyd import Component as C
from ophyd.device import DeviceStatus
class CS700TemperatureController(PVPositioner):
setpoint = C(EpicsSignal, 'T-SP')
readback = C(EpicsSignalRO, 'T-I')
done = C(EpicsSignalRO, 'Cmd-Busy')
stop_signal = C(EpicsSignal, 'Cmd-Cmd')
def trigger(self):
# There is nothing to do. Just report that we are done.
# Note: This really should not necessary to do --
# future changes to PVPositioner may obviate this code.
status = DeviceStatus()
status._finished()
return status
cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700',
settle_time=10)
cs700.done_value = 0
cs700.read_attrs = ['setpoint', 'readback']
cs700.readback.name = 'temperautre'
cs700.setpoint.name = 'temperautre_setpoint'
## Instruction:
Remove settle_time kwarg from c700
This kwarg has been removed from ophyd, but will be coming back (and be
functional) soon. Revert these changes when that happens: ophyd 0.2.1)
## Code After:
from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO
from ophyd import Component as C
from ophyd.device import DeviceStatus
class CS700TemperatureController(PVPositioner):
setpoint = C(EpicsSignal, 'T-SP')
readback = C(EpicsSignalRO, 'T-I')
done = C(EpicsSignalRO, 'Cmd-Busy')
stop_signal = C(EpicsSignal, 'Cmd-Cmd')
def trigger(self):
# There is nothing to do. Just report that we are done.
# Note: This really should not necessary to do --
# future changes to PVPositioner may obviate this code.
status = DeviceStatus()
status._finished()
return status
cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700')
# this functionality never worked, has now been removed, but will shortly be
# coming back
# settle_time=10)
cs700.done_value = 0
cs700.read_attrs = ['setpoint', 'readback']
cs700.readback.name = 'temperautre'
cs700.setpoint.name = 'temperautre_setpoint'
|
...
status._finished()
return status
cs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700')
# this functionality never worked, has now been removed, but will shortly be
# coming back
# settle_time=10)
cs700.done_value = 0
cs700.read_attrs = ['setpoint', 'readback']
cs700.readback.name = 'temperautre'
...
|
5cf839df99a03299215db7c2f6d9a78ac724c155
|
src/rinoh/language/__init__.py
|
src/rinoh/language/__init__.py
|
from .cls import Language
from .en import EN
from .fr import FR
from .it import IT
from .nl import NL
__all__ = ['Language', 'EN', 'FR', 'IT', 'NL']
# generate docstrings for the Language instances
for code, language_ref in Language.languages.items():
language = language_ref()
lines = []
for string_collection in language.strings.values():
lines.append("\n.. rubric:: {}\n"
.format(type(string_collection).__name__))
for string in string_collection._strings:
lines.append(":{}: {}".format(string.name,
string_collection[string.name]))
language.__doc__ = '\n'.join(lines)
|
from .cls import Language
from .en import EN
from .fr import FR
from .it import IT
from .nl import NL
__all__ = ['Language', 'EN', 'FR', 'IT', 'NL']
# generate docstrings for the Language instances
for code, language_ref in Language.languages.items():
language = language_ref()
lines = ['Localized strings for {}'.format(language.name)]
for string_collection in language.strings.values():
lines.append("\n.. rubric:: {}\n"
.format(type(string_collection).__name__))
for string in string_collection._strings:
lines.append(":{}: {}".format(string.name,
string_collection[string.name]))
language.__doc__ = '\n'.join(lines)
|
Fix the rendering of language instance docstrings
|
Fix the rendering of language instance docstrings
|
Python
|
agpl-3.0
|
brechtm/rinohtype,brechtm/rinohtype,brechtm/rinohtype
|
python
|
## Code Before:
from .cls import Language
from .en import EN
from .fr import FR
from .it import IT
from .nl import NL
__all__ = ['Language', 'EN', 'FR', 'IT', 'NL']
# generate docstrings for the Language instances
for code, language_ref in Language.languages.items():
language = language_ref()
lines = []
for string_collection in language.strings.values():
lines.append("\n.. rubric:: {}\n"
.format(type(string_collection).__name__))
for string in string_collection._strings:
lines.append(":{}: {}".format(string.name,
string_collection[string.name]))
language.__doc__ = '\n'.join(lines)
## Instruction:
Fix the rendering of language instance docstrings
## Code After:
from .cls import Language
from .en import EN
from .fr import FR
from .it import IT
from .nl import NL
__all__ = ['Language', 'EN', 'FR', 'IT', 'NL']
# generate docstrings for the Language instances
for code, language_ref in Language.languages.items():
language = language_ref()
lines = ['Localized strings for {}'.format(language.name)]
for string_collection in language.strings.values():
lines.append("\n.. rubric:: {}\n"
.format(type(string_collection).__name__))
for string in string_collection._strings:
lines.append(":{}: {}".format(string.name,
string_collection[string.name]))
language.__doc__ = '\n'.join(lines)
|
// ... existing code ...
for code, language_ref in Language.languages.items():
language = language_ref()
lines = ['Localized strings for {}'.format(language.name)]
for string_collection in language.strings.values():
lines.append("\n.. rubric:: {}\n"
.format(type(string_collection).__name__))
for string in string_collection._strings:
lines.append(":{}: {}".format(string.name,
string_collection[string.name]))
language.__doc__ = '\n'.join(lines)
// ... rest of the code ...
|
633248dd521b6868937d3fb838d39264fc170c61
|
greengraph/test/map_integration.py
|
greengraph/test/map_integration.py
|
from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
with open('image.txt','r') as source:
text = source.read()
lat=51
long=30
satellite=True
zoom=10
size=(400,400)
sensor=False
params=dict(
sensor= str(sensor).lower(),
zoom= zoom,
size= "x".join(map(str, size)),
center= ",".join(map(str, (lat, long) )),
style="feature:all|element:labels|visibility:off"
)
base="http://maps.googleapis.com/maps/api/staticmap?"
text = requests.get(base, params=params).content # Fetch our PNG image data
text = 'hello'
image = Mock()
image.content = text
patch_get = Mock(return_value=image)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread') as mock_imread:
london_map = Map(52, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print london_map.count_green()
|
from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
patch_get = Mock()
patch_get.content = ''
image_array = img.imread('image.png')
patch_imread = Mock(return_value=image_array)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread',patch_imread) as mock_imread:
my_map = Map(0, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print my_map.count_green()
|
Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet.
|
Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet.
|
Python
|
apache-2.0
|
paulsbrookes/greengraph
|
python
|
## Code Before:
from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
with open('image.txt','r') as source:
text = source.read()
lat=51
long=30
satellite=True
zoom=10
size=(400,400)
sensor=False
params=dict(
sensor= str(sensor).lower(),
zoom= zoom,
size= "x".join(map(str, size)),
center= ",".join(map(str, (lat, long) )),
style="feature:all|element:labels|visibility:off"
)
base="http://maps.googleapis.com/maps/api/staticmap?"
text = requests.get(base, params=params).content # Fetch our PNG image data
text = 'hello'
image = Mock()
image.content = text
patch_get = Mock(return_value=image)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread') as mock_imread:
london_map = Map(52, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print london_map.count_green()
## Instruction:
Update Map integration test so that Map is fed a PNG from a local image.png file rather than from the internet.
## Code After:
from mock import patch
from mock import Mock
from greengraph import Map
import requests
from matplotlib import image as img
from StringIO import StringIO
patch_get = Mock()
patch_get.content = ''
image_array = img.imread('image.png')
patch_imread = Mock(return_value=image_array)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread',patch_imread) as mock_imread:
my_map = Map(0, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print my_map.count_green()
|
// ... existing code ...
from matplotlib import image as img
from StringIO import StringIO
patch_get = Mock()
patch_get.content = ''
image_array = img.imread('image.png')
patch_imread = Mock(return_value=image_array)
with patch.object(requests,'get',patch_get) as mock_get:
with patch.object(img,'imread',patch_imread) as mock_imread:
my_map = Map(0, 0)
print mock_get.mock_calls
print mock_imread.mock_calls
print my_map.count_green()
// ... rest of the code ...
|
ae5db4c2430039723946b85c1a740b9c347e76ef
|
extensions/amazon-dynamodb/runtime/src/main/java/io/quarkus/dynamodb/runtime/DynamodbConfig.java
|
extensions/amazon-dynamodb/runtime/src/main/java/io/quarkus/dynamodb/runtime/DynamodbConfig.java
|
package io.quarkus.dynamodb.runtime;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public class DynamodbConfig {
/**
* Enable DynamoDB service endpoint discovery.
*/
@ConfigItem
public boolean enableEndpointDiscovery;
/**
* AWS service configurations
*/
@ConfigItem
public AwsConfig aws;
/**
* SDK client configurations
*/
@ConfigItem(name = ConfigItem.PARENT)
public SdkConfig sdk;
/**
* Apache HTTP client transport configuration
*/
@ConfigItem
public ApacheHttpClientConfig syncClient;
/**
* Netty HTTP client transport configuration
*/
@ConfigItem
public NettyHttpClientConfig asyncClient;
}
|
package io.quarkus.dynamodb.runtime;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public class DynamodbConfig {
/**
* Enable DynamoDB service endpoint discovery.
*/
@ConfigItem
public boolean enableEndpointDiscovery;
/**
* SDK client configurations
*/
@ConfigItem(name = ConfigItem.PARENT)
public SdkConfig sdk;
/**
* AWS service configurations
*/
@ConfigItem
public AwsConfig aws;
/**
* Apache HTTP client transport configuration
*/
@ConfigItem
public ApacheHttpClientConfig syncClient;
/**
* Netty HTTP client transport configuration
*/
@ConfigItem
public NettyHttpClientConfig asyncClient;
}
|
Reorder config groups for better documentation
|
Reorder config groups for better documentation
|
Java
|
apache-2.0
|
quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus,quarkusio/quarkus
|
java
|
## Code Before:
package io.quarkus.dynamodb.runtime;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public class DynamodbConfig {
/**
* Enable DynamoDB service endpoint discovery.
*/
@ConfigItem
public boolean enableEndpointDiscovery;
/**
* AWS service configurations
*/
@ConfigItem
public AwsConfig aws;
/**
* SDK client configurations
*/
@ConfigItem(name = ConfigItem.PARENT)
public SdkConfig sdk;
/**
* Apache HTTP client transport configuration
*/
@ConfigItem
public ApacheHttpClientConfig syncClient;
/**
* Netty HTTP client transport configuration
*/
@ConfigItem
public NettyHttpClientConfig asyncClient;
}
## Instruction:
Reorder config groups for better documentation
## Code After:
package io.quarkus.dynamodb.runtime;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public class DynamodbConfig {
/**
* Enable DynamoDB service endpoint discovery.
*/
@ConfigItem
public boolean enableEndpointDiscovery;
/**
* SDK client configurations
*/
@ConfigItem(name = ConfigItem.PARENT)
public SdkConfig sdk;
/**
* AWS service configurations
*/
@ConfigItem
public AwsConfig aws;
/**
* Apache HTTP client transport configuration
*/
@ConfigItem
public ApacheHttpClientConfig syncClient;
/**
* Netty HTTP client transport configuration
*/
@ConfigItem
public NettyHttpClientConfig asyncClient;
}
|
# ... existing code ...
public boolean enableEndpointDiscovery;
/**
* SDK client configurations
*/
@ConfigItem(name = ConfigItem.PARENT)
public SdkConfig sdk;
/**
* AWS service configurations
*/
@ConfigItem
public AwsConfig aws;
/**
* Apache HTTP client transport configuration
# ... rest of the code ...
|
fe79e799f2d3862e4764c69e76ed5a7d0a132002
|
setup.py
|
setup.py
|
from setuptools import setup
import os
__doc__ = """
Command line tool and library wrappers around iwlist and
/etc/network/interfaces.
"""
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
install_requires = [
'setuptools',
'pbkdf2',
]
try:
import argparse
except:
install_requires.append('argparse')
version = '1.0.0'
setup(
name='wifi',
version=version,
author='Rocky Meza, Gavin Wahl',
author_email='[email protected]',
description=__doc__,
long_description=read('README.rst'),
packages=['wifi'],
scripts=['bin/wifi'],
test_suite='tests',
platforms=["Debian"],
license='BSD',
install_requires=install_requires,
classifiers=[
"License :: OSI Approved :: BSD License",
"Topic :: System :: Networking",
"Operating System :: POSIX :: Linux",
"Environment :: Console",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
],
data_files=[
('/etc/bash_completion.d/', ['extras/wifi-completion.bash']),
]
)
|
from setuptools import setup
import os
__doc__ = """
Command line tool and library wrappers around iwlist and
/etc/network/interfaces.
"""
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
install_requires = [
'setuptools',
'pbkdf2',
]
try:
import argparse
except:
install_requires.append('argparse')
version = '1.0.0'
data_files = [
('/etc/bash_completion.d/', ['extras/wifi-completion.bash']),
]
for entry in data_files:
# make sure we actually have write access to the target folder and if not don't
# include it in data_files
if not os.access(entry[0], os.W_OK):
print("Skipping copying files to %s, no write access" % entry[0])
data_files.remove(entry)
setup(
name='wifi',
version=version,
author='Rocky Meza, Gavin Wahl',
author_email='[email protected]',
description=__doc__,
long_description=read('README.rst'),
packages=['wifi'],
scripts=['bin/wifi'],
test_suite='tests',
platforms=["Debian"],
license='BSD',
install_requires=install_requires,
classifiers=[
"License :: OSI Approved :: BSD License",
"Topic :: System :: Networking",
"Operating System :: POSIX :: Linux",
"Environment :: Console",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
],
data_files=data_files
)
|
Check for write access for bashcompletion via os.access
|
Check for write access for bashcompletion via os.access
Alternative version of pull request rockymeza/wifi#41 (which apparently
isn't worked on any more) which checks for write access before
attempting to install the bashcompletion addition during
installation -- if only installed in a library into a virtualenv
the installation will now complete without an issue.
|
Python
|
bsd-2-clause
|
rockymeza/wifi,cangelis/wifi,nicupavel/wifi,foosel/wifi,rockymeza/wifi,cangelis/wifi,foosel/wifi,simudream/wifi,nicupavel/wifi,simudream/wifi
|
python
|
## Code Before:
from setuptools import setup
import os
__doc__ = """
Command line tool and library wrappers around iwlist and
/etc/network/interfaces.
"""
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
install_requires = [
'setuptools',
'pbkdf2',
]
try:
import argparse
except:
install_requires.append('argparse')
version = '1.0.0'
setup(
name='wifi',
version=version,
author='Rocky Meza, Gavin Wahl',
author_email='[email protected]',
description=__doc__,
long_description=read('README.rst'),
packages=['wifi'],
scripts=['bin/wifi'],
test_suite='tests',
platforms=["Debian"],
license='BSD',
install_requires=install_requires,
classifiers=[
"License :: OSI Approved :: BSD License",
"Topic :: System :: Networking",
"Operating System :: POSIX :: Linux",
"Environment :: Console",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
],
data_files=[
('/etc/bash_completion.d/', ['extras/wifi-completion.bash']),
]
)
## Instruction:
Check for write access for bashcompletion via os.access
Alternative version of pull request rockymeza/wifi#41 (which apparently
isn't worked on any more) which checks for write access before
attempting to install the bashcompletion addition during
installation -- if only installed in a library into a virtualenv
the installation will now complete without an issue.
## Code After:
from setuptools import setup
import os
__doc__ = """
Command line tool and library wrappers around iwlist and
/etc/network/interfaces.
"""
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
install_requires = [
'setuptools',
'pbkdf2',
]
try:
import argparse
except:
install_requires.append('argparse')
version = '1.0.0'
data_files = [
('/etc/bash_completion.d/', ['extras/wifi-completion.bash']),
]
for entry in data_files:
# make sure we actually have write access to the target folder and if not don't
# include it in data_files
if not os.access(entry[0], os.W_OK):
print("Skipping copying files to %s, no write access" % entry[0])
data_files.remove(entry)
setup(
name='wifi',
version=version,
author='Rocky Meza, Gavin Wahl',
author_email='[email protected]',
description=__doc__,
long_description=read('README.rst'),
packages=['wifi'],
scripts=['bin/wifi'],
test_suite='tests',
platforms=["Debian"],
license='BSD',
install_requires=install_requires,
classifiers=[
"License :: OSI Approved :: BSD License",
"Topic :: System :: Networking",
"Operating System :: POSIX :: Linux",
"Environment :: Console",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
],
data_files=data_files
)
|
...
version = '1.0.0'
data_files = [
('/etc/bash_completion.d/', ['extras/wifi-completion.bash']),
]
for entry in data_files:
# make sure we actually have write access to the target folder and if not don't
# include it in data_files
if not os.access(entry[0], os.W_OK):
print("Skipping copying files to %s, no write access" % entry[0])
data_files.remove(entry)
setup(
name='wifi',
version=version,
...
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
],
data_files=data_files
)
...
|
802bed896c147fc6bb6dc72f62a80236bc3cd263
|
soccermetrics/rest/resources/personnel.py
|
soccermetrics/rest/resources/personnel.py
|
from soccermetrics.rest.resources import Resource
class Personnel(Resource):
"""
Represents a Personnel REST resource (/personnel/<resource> endpoint).
The Personnel resources let you access biographic and demographic
data on all personnel involved in a football match – players,
managers, and match referees.
Derived from :class:`Resource`.
"""
def __init__(self, resource, base_uri, auth):
"""
Constructor of Personnel class.
:param resource: Name of resource.
:type resource: string
:param base_uri: Base URI of API.
:type base_uri: string
:param auth: Authentication credential.
:type auth: tuple
"""
super(Personnel, self).__init__(base_uri,auth)
self.endpoint += "/personnel/%s" % resource
|
from soccermetrics.rest.resources import Resource
class Personnel(Resource):
"""
Represents a Personnel REST resource (/personnel/<resource> endpoint).
The Personnel resources let you access biographic and demographic
data on the following personnel involved in a football match:
* Players,
* Managers,
* Match referees.
Derived from :class:`Resource`.
"""
def __init__(self, resource, base_uri, auth):
"""
Constructor of Personnel class.
:param resource: Name of resource.
:type resource: string
:param base_uri: Base URI of API.
:type base_uri: string
:param auth: Authentication credential.
:type auth: tuple
"""
super(Personnel, self).__init__(base_uri,auth)
self.endpoint += "/personnel/%s" % resource
|
Remove stray non-ASCII character in docstring
|
Remove stray non-ASCII character in docstring
|
Python
|
mit
|
soccermetrics/soccermetrics-client-py
|
python
|
## Code Before:
from soccermetrics.rest.resources import Resource
class Personnel(Resource):
"""
Represents a Personnel REST resource (/personnel/<resource> endpoint).
The Personnel resources let you access biographic and demographic
data on all personnel involved in a football match – players,
managers, and match referees.
Derived from :class:`Resource`.
"""
def __init__(self, resource, base_uri, auth):
"""
Constructor of Personnel class.
:param resource: Name of resource.
:type resource: string
:param base_uri: Base URI of API.
:type base_uri: string
:param auth: Authentication credential.
:type auth: tuple
"""
super(Personnel, self).__init__(base_uri,auth)
self.endpoint += "/personnel/%s" % resource
## Instruction:
Remove stray non-ASCII character in docstring
## Code After:
from soccermetrics.rest.resources import Resource
class Personnel(Resource):
"""
Represents a Personnel REST resource (/personnel/<resource> endpoint).
The Personnel resources let you access biographic and demographic
data on the following personnel involved in a football match:
* Players,
* Managers,
* Match referees.
Derived from :class:`Resource`.
"""
def __init__(self, resource, base_uri, auth):
"""
Constructor of Personnel class.
:param resource: Name of resource.
:type resource: string
:param base_uri: Base URI of API.
:type base_uri: string
:param auth: Authentication credential.
:type auth: tuple
"""
super(Personnel, self).__init__(base_uri,auth)
self.endpoint += "/personnel/%s" % resource
|
// ... existing code ...
Represents a Personnel REST resource (/personnel/<resource> endpoint).
The Personnel resources let you access biographic and demographic
data on the following personnel involved in a football match:
* Players,
* Managers,
* Match referees.
Derived from :class:`Resource`.
"""
// ... rest of the code ...
|
1657e46cd5c2a81df4cbb73b292b0bf9072d5c51
|
h2o-py/tests/testdir_tree/pyunit_tree_irf.py
|
h2o-py/tests/testdir_tree/pyunit_tree_irf.py
|
import h2o
from h2o.tree import H2OTree
from h2o.estimators import H2OIsolationForestEstimator
from tests import pyunit_utils
def check_tree(tree, tree_number, tree_class = None):
assert tree is not None
assert len(tree) > 0
assert tree._tree_number == tree_number
assert tree._tree_class == tree_class
assert tree.root_node is not None
assert tree.left_children is not None
assert tree.right_children is not None
assert tree.thresholds is not None
assert tree.nas is not None
assert tree.descriptions is not None
assert tree.node_ids is not None
assert tree.model_id is not None
assert tree.levels is not None
assert tree.root_node.na_direction is not None
assert tree.root_node.id is not None
def irf_tree_Test():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate.csv"))
prostate["RACE"] = prostate["RACE"].asfactor()
iso_model = H2OIsolationForestEstimator()
iso_model.train(training_frame = prostate, x = list(set(prostate.col_names) - set(["ID", "CAPSULE"])))
tree = H2OTree(iso_model, 5)
check_tree(tree, 5, None)
print(tree)
if __name__ == "__main__":
pyunit_utils.standalone_test(irf_tree_Test)
else:
irf_tree_Test()
|
import h2o
from h2o.tree import H2OTree
from h2o.estimators import H2OIsolationForestEstimator
from tests import pyunit_utils
def check_tree(tree, tree_number, tree_class = None):
assert tree is not None
assert len(tree) > 0
assert tree._tree_number == tree_number
assert tree._tree_class == tree_class
assert tree.root_node is not None
assert tree.left_children is not None
assert tree.right_children is not None
assert tree.thresholds is not None
assert tree.nas is not None
assert tree.descriptions is not None
assert tree.node_ids is not None
assert tree.model_id is not None
assert tree.levels is not None
assert tree.root_node.na_direction is not None
assert tree.root_node.id is not None
def irf_tree_Test():
cat_frame = h2o.create_frame(cols=10, categorical_fraction=1, seed=42)
# check all columns are categorical
assert set(cat_frame.types.values()) == set(['enum'])
iso_model = H2OIsolationForestEstimator(seed=42)
iso_model.train(training_frame=cat_frame)
tree = H2OTree(iso_model, 5)
check_tree(tree, 5, None)
print(tree)
if __name__ == "__main__":
pyunit_utils.standalone_test(irf_tree_Test)
else:
irf_tree_Test()
|
Fix test: make sure that Isolation Forest actually make a categorical split
|
Fix test: make sure that Isolation Forest actually make a categorical split
|
Python
|
apache-2.0
|
h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,h2oai/h2o-3
|
python
|
## Code Before:
import h2o
from h2o.tree import H2OTree
from h2o.estimators import H2OIsolationForestEstimator
from tests import pyunit_utils
def check_tree(tree, tree_number, tree_class = None):
assert tree is not None
assert len(tree) > 0
assert tree._tree_number == tree_number
assert tree._tree_class == tree_class
assert tree.root_node is not None
assert tree.left_children is not None
assert tree.right_children is not None
assert tree.thresholds is not None
assert tree.nas is not None
assert tree.descriptions is not None
assert tree.node_ids is not None
assert tree.model_id is not None
assert tree.levels is not None
assert tree.root_node.na_direction is not None
assert tree.root_node.id is not None
def irf_tree_Test():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate.csv"))
prostate["RACE"] = prostate["RACE"].asfactor()
iso_model = H2OIsolationForestEstimator()
iso_model.train(training_frame = prostate, x = list(set(prostate.col_names) - set(["ID", "CAPSULE"])))
tree = H2OTree(iso_model, 5)
check_tree(tree, 5, None)
print(tree)
if __name__ == "__main__":
pyunit_utils.standalone_test(irf_tree_Test)
else:
irf_tree_Test()
## Instruction:
Fix test: make sure that Isolation Forest actually make a categorical split
## Code After:
import h2o
from h2o.tree import H2OTree
from h2o.estimators import H2OIsolationForestEstimator
from tests import pyunit_utils
def check_tree(tree, tree_number, tree_class = None):
assert tree is not None
assert len(tree) > 0
assert tree._tree_number == tree_number
assert tree._tree_class == tree_class
assert tree.root_node is not None
assert tree.left_children is not None
assert tree.right_children is not None
assert tree.thresholds is not None
assert tree.nas is not None
assert tree.descriptions is not None
assert tree.node_ids is not None
assert tree.model_id is not None
assert tree.levels is not None
assert tree.root_node.na_direction is not None
assert tree.root_node.id is not None
def irf_tree_Test():
cat_frame = h2o.create_frame(cols=10, categorical_fraction=1, seed=42)
# check all columns are categorical
assert set(cat_frame.types.values()) == set(['enum'])
iso_model = H2OIsolationForestEstimator(seed=42)
iso_model.train(training_frame=cat_frame)
tree = H2OTree(iso_model, 5)
check_tree(tree, 5, None)
print(tree)
if __name__ == "__main__":
pyunit_utils.standalone_test(irf_tree_Test)
else:
irf_tree_Test()
|
# ... existing code ...
def irf_tree_Test():
cat_frame = h2o.create_frame(cols=10, categorical_fraction=1, seed=42)
# check all columns are categorical
assert set(cat_frame.types.values()) == set(['enum'])
iso_model = H2OIsolationForestEstimator(seed=42)
iso_model.train(training_frame=cat_frame)
tree = H2OTree(iso_model, 5)
check_tree(tree, 5, None)
# ... rest of the code ...
|
739a5a85a455105f01013b20762b1b493c4d5027
|
deflect/views.py
|
deflect/views.py
|
from __future__ import unicode_literals
import base32_crockford
import logging
from django.db.models import F
from django.http import Http404
from django.http import HttpResponsePermanentRedirect
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
from .models import ShortURL
from .models import VanityURL
from .utils import add_query_params
logger = logging.getLogger(__name__)
def redirect(request, key):
"""
Given the short URL key, update the statistics and redirect the
user to the destination URL, including available Google Analytics
parameters.
"""
try:
alias = VanityURL.objects.select_related().get(alias=key.upper())
key_id = alias.redirect.id
except VanityURL.DoesNotExist:
try:
key_id = base32_crockford.decode(key)
except ValueError as e:
logger.warning("Error decoding redirect '%s': %s" % (key, e))
raise Http404
redirect = get_object_or_404(ShortURL, pk=key_id)
ShortURL.objects.filter(pk=key_id).update(hits=F('hits') + 1,
last_used=now())
# Inject Google campaign parameters
utm_params = {'utm_source': redirect.key,
'utm_campaign': redirect.campaign,
'utm_content': redirect.content,
'utm_medium': redirect.medium}
url = add_query_params(redirect.long_url, utm_params)
return HttpResponsePermanentRedirect(url)
|
from __future__ import unicode_literals
import base32_crockford
import logging
from django.db.models import F
from django.http import Http404
from django.http import HttpResponsePermanentRedirect
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
from .models import ShortURL
from .models import VanityURL
from .utils import add_query_params
logger = logging.getLogger(__name__)
def redirect(request, key):
"""
Given the short URL key, update the statistics and redirect the
user to the destination URL, including available Google Analytics
parameters.
"""
try:
alias = VanityURL.objects.select_related().get(alias=key.upper())
key_id = alias.redirect.id
except VanityURL.DoesNotExist:
try:
key_id = base32_crockford.decode(key)
except ValueError as e:
logger.warning("Error decoding redirect: %s" % e)
raise Http404
redirect = get_object_or_404(ShortURL, pk=key_id)
ShortURL.objects.filter(pk=key_id).update(hits=F('hits') + 1,
last_used=now())
# Inject Google campaign parameters
utm_params = {'utm_source': redirect.key,
'utm_campaign': redirect.campaign,
'utm_content': redirect.content,
'utm_medium': redirect.medium}
url = add_query_params(redirect.long_url, utm_params)
return HttpResponsePermanentRedirect(url)
|
Simplify invalid decode warning text
|
Simplify invalid decode warning text
The string is already displayed in the error text, so there's no
reason to duplicate it.
|
Python
|
bsd-3-clause
|
jbittel/django-deflect
|
python
|
## Code Before:
from __future__ import unicode_literals
import base32_crockford
import logging
from django.db.models import F
from django.http import Http404
from django.http import HttpResponsePermanentRedirect
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
from .models import ShortURL
from .models import VanityURL
from .utils import add_query_params
logger = logging.getLogger(__name__)
def redirect(request, key):
"""
Given the short URL key, update the statistics and redirect the
user to the destination URL, including available Google Analytics
parameters.
"""
try:
alias = VanityURL.objects.select_related().get(alias=key.upper())
key_id = alias.redirect.id
except VanityURL.DoesNotExist:
try:
key_id = base32_crockford.decode(key)
except ValueError as e:
logger.warning("Error decoding redirect '%s': %s" % (key, e))
raise Http404
redirect = get_object_or_404(ShortURL, pk=key_id)
ShortURL.objects.filter(pk=key_id).update(hits=F('hits') + 1,
last_used=now())
# Inject Google campaign parameters
utm_params = {'utm_source': redirect.key,
'utm_campaign': redirect.campaign,
'utm_content': redirect.content,
'utm_medium': redirect.medium}
url = add_query_params(redirect.long_url, utm_params)
return HttpResponsePermanentRedirect(url)
## Instruction:
Simplify invalid decode warning text
The string is already displayed in the error text, so there's no
reason to duplicate it.
## Code After:
from __future__ import unicode_literals
import base32_crockford
import logging
from django.db.models import F
from django.http import Http404
from django.http import HttpResponsePermanentRedirect
from django.shortcuts import get_object_or_404
from django.utils.timezone import now
from .models import ShortURL
from .models import VanityURL
from .utils import add_query_params
logger = logging.getLogger(__name__)
def redirect(request, key):
"""
Given the short URL key, update the statistics and redirect the
user to the destination URL, including available Google Analytics
parameters.
"""
try:
alias = VanityURL.objects.select_related().get(alias=key.upper())
key_id = alias.redirect.id
except VanityURL.DoesNotExist:
try:
key_id = base32_crockford.decode(key)
except ValueError as e:
logger.warning("Error decoding redirect: %s" % e)
raise Http404
redirect = get_object_or_404(ShortURL, pk=key_id)
ShortURL.objects.filter(pk=key_id).update(hits=F('hits') + 1,
last_used=now())
# Inject Google campaign parameters
utm_params = {'utm_source': redirect.key,
'utm_campaign': redirect.campaign,
'utm_content': redirect.content,
'utm_medium': redirect.medium}
url = add_query_params(redirect.long_url, utm_params)
return HttpResponsePermanentRedirect(url)
|
...
try:
key_id = base32_crockford.decode(key)
except ValueError as e:
logger.warning("Error decoding redirect: %s" % e)
raise Http404
redirect = get_object_or_404(ShortURL, pk=key_id)
...
|
00aa59468c4dbfde282891f1396e29bd3f28fb62
|
gunny/reveille/service.py
|
gunny/reveille/service.py
|
from twisted.application import internet
from twisted.application.service import Service
from twisted.internet import reactor
from autobahn.websocket import connectWS
class ControlService(Service):
pass
class PlayerService(Service):
def __init__(self, factory):
self.factory = factory
self.conn = None
def startService(self):
self.factory.startFactory()
self.conn = connectWS(self.factory)
self.running = 1
def stopService(self):
self.factory.stopFactory()
if self.conn is not None:
self.conn.disconnect()
self.running = 0
|
from twisted.application.service import Service
from twisted.internet import stdio
from autobahn.websocket import connectWS
class CoxswainService(Service):
def __init__(self, factory):
self.factory = factory
self.conn = None
def startService(self):
#self.factory(ReveilleCommandProtocol())
self.conn = connectWS(self.factory)
self.running = True
def stopService(self):
self.factory.stopFactory()
if self.conn is not None:
self.conn.disconnect()
self.running = False
|
Rename classes to reflect intended use.
|
Rename classes to reflect intended use.
|
Python
|
bsd-2-clause
|
davidblewett/gunny,davidblewett/gunny
|
python
|
## Code Before:
from twisted.application import internet
from twisted.application.service import Service
from twisted.internet import reactor
from autobahn.websocket import connectWS
class ControlService(Service):
pass
class PlayerService(Service):
def __init__(self, factory):
self.factory = factory
self.conn = None
def startService(self):
self.factory.startFactory()
self.conn = connectWS(self.factory)
self.running = 1
def stopService(self):
self.factory.stopFactory()
if self.conn is not None:
self.conn.disconnect()
self.running = 0
## Instruction:
Rename classes to reflect intended use.
## Code After:
from twisted.application.service import Service
from twisted.internet import stdio
from autobahn.websocket import connectWS
class CoxswainService(Service):
def __init__(self, factory):
self.factory = factory
self.conn = None
def startService(self):
#self.factory(ReveilleCommandProtocol())
self.conn = connectWS(self.factory)
self.running = True
def stopService(self):
self.factory.stopFactory()
if self.conn is not None:
self.conn.disconnect()
self.running = False
|
# ... existing code ...
from twisted.application.service import Service
from twisted.internet import stdio
from autobahn.websocket import connectWS
class CoxswainService(Service):
def __init__(self, factory):
self.factory = factory
# ... modified code ...
self.conn = None
def startService(self):
#self.factory(ReveilleCommandProtocol())
self.conn = connectWS(self.factory)
self.running = True
def stopService(self):
self.factory.stopFactory()
if self.conn is not None:
self.conn.disconnect()
self.running = False
# ... rest of the code ...
|
6250427143245676a5efd7e5c55054b5b3a285fd
|
src/pushover_complete/__init__.py
|
src/pushover_complete/__init__.py
|
"""A Python 3 package for interacting with *all* aspects of the Pushover API"""
from .error import PushoverCompleteError, BadAPIRequestError
from .pushover_api import PushoverAPI
__all__ = [
'PushoverCompleteError', 'BadAPIRequestError',
'PushoverAPI'
]
__version__ = '0.0.1'
__title__ = 'pushover_complete'
__description__ = ''
__url__ = ''
__author__ = 'Scott Colby'
__email__ = '[email protected]'
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2016 Scott Colby'
|
"""A Python 3 package for interacting with *all* aspects of the Pushover API"""
from .error import PushoverCompleteError, BadAPIRequestError
from .pushover_api import PushoverAPI
__all__ = [
'PushoverCompleteError', 'BadAPIRequestError',
'PushoverAPI'
]
__version__ = '0.0.1'
__title__ = 'pushover_complete'
__description__ = ''
__url__ = 'https://github.com/scolby33/pushover_complete'
__author__ = 'Scott Colby'
__email__ = '[email protected]'
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2016 Scott Colby'
|
Add URL for project to the project metadata
|
Add URL for project to the project metadata
|
Python
|
mit
|
scolby33/pushover_complete
|
python
|
## Code Before:
"""A Python 3 package for interacting with *all* aspects of the Pushover API"""
from .error import PushoverCompleteError, BadAPIRequestError
from .pushover_api import PushoverAPI
__all__ = [
'PushoverCompleteError', 'BadAPIRequestError',
'PushoverAPI'
]
__version__ = '0.0.1'
__title__ = 'pushover_complete'
__description__ = ''
__url__ = ''
__author__ = 'Scott Colby'
__email__ = '[email protected]'
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2016 Scott Colby'
## Instruction:
Add URL for project to the project metadata
## Code After:
"""A Python 3 package for interacting with *all* aspects of the Pushover API"""
from .error import PushoverCompleteError, BadAPIRequestError
from .pushover_api import PushoverAPI
__all__ = [
'PushoverCompleteError', 'BadAPIRequestError',
'PushoverAPI'
]
__version__ = '0.0.1'
__title__ = 'pushover_complete'
__description__ = ''
__url__ = 'https://github.com/scolby33/pushover_complete'
__author__ = 'Scott Colby'
__email__ = '[email protected]'
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2016 Scott Colby'
|
...
__title__ = 'pushover_complete'
__description__ = ''
__url__ = 'https://github.com/scolby33/pushover_complete'
__author__ = 'Scott Colby'
...
|
c30898d785d131a8dc08d93fe4142acda5b34081
|
frappe/core/doctype/docfield/docfield.py
|
frappe/core/doctype/docfield/docfield.py
|
from __future__ import unicode_literals
from frappe.model.document import Document
class DocField(Document):
pass
|
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class DocField(Document):
def get_link_doctype(self):
'''Returns the Link doctype for the docfield (if applicable)
if fieldtype is Link: Returns "options"
if fieldtype is Table MultiSelect: Returns "options" of the Link field in the Child Table
'''
if self.fieldtype == 'Link':
return self.options
if self.fieldtype == 'Table MultiSelect':
table_doctype = self.options
link_doctype = frappe.db.get_value('DocField', {
'fieldtype': 'Link',
'parenttype': 'DocType',
'parent': table_doctype,
'in_list_view': 1
}, 'options')
return link_doctype
|
Add get_link_doctype method in DocField
|
fix: Add get_link_doctype method in DocField
|
Python
|
mit
|
adityahase/frappe,saurabh6790/frappe,almeidapaulopt/frappe,mhbu50/frappe,yashodhank/frappe,almeidapaulopt/frappe,mhbu50/frappe,vjFaLk/frappe,adityahase/frappe,vjFaLk/frappe,vjFaLk/frappe,frappe/frappe,vjFaLk/frappe,saurabh6790/frappe,StrellaGroup/frappe,StrellaGroup/frappe,yashodhank/frappe,frappe/frappe,almeidapaulopt/frappe,frappe/frappe,mhbu50/frappe,StrellaGroup/frappe,almeidapaulopt/frappe,mhbu50/frappe,saurabh6790/frappe,yashodhank/frappe,adityahase/frappe,saurabh6790/frappe,adityahase/frappe,yashodhank/frappe
|
python
|
## Code Before:
from __future__ import unicode_literals
from frappe.model.document import Document
class DocField(Document):
pass
## Instruction:
fix: Add get_link_doctype method in DocField
## Code After:
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class DocField(Document):
def get_link_doctype(self):
'''Returns the Link doctype for the docfield (if applicable)
if fieldtype is Link: Returns "options"
if fieldtype is Table MultiSelect: Returns "options" of the Link field in the Child Table
'''
if self.fieldtype == 'Link':
return self.options
if self.fieldtype == 'Table MultiSelect':
table_doctype = self.options
link_doctype = frappe.db.get_value('DocField', {
'fieldtype': 'Link',
'parenttype': 'DocType',
'parent': table_doctype,
'in_list_view': 1
}, 'options')
return link_doctype
|
# ... existing code ...
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class DocField(Document):
def get_link_doctype(self):
'''Returns the Link doctype for the docfield (if applicable)
if fieldtype is Link: Returns "options"
if fieldtype is Table MultiSelect: Returns "options" of the Link field in the Child Table
'''
if self.fieldtype == 'Link':
return self.options
if self.fieldtype == 'Table MultiSelect':
table_doctype = self.options
link_doctype = frappe.db.get_value('DocField', {
'fieldtype': 'Link',
'parenttype': 'DocType',
'parent': table_doctype,
'in_list_view': 1
}, 'options')
return link_doctype
# ... rest of the code ...
|
11022b79ded961bdd2e9a6bff0c4f4a03097084c
|
scripts/install_new_database.py
|
scripts/install_new_database.py
|
import os
import sys
_upper_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
if _upper_dir not in sys.path:
sys.path.append(_upper_dir)
import chdb
if __name__ == '__main__':
chdb.install_scratch_db()
|
import os
import sys
_upper_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
if _upper_dir not in sys.path:
sys.path.append(_upper_dir)
import chdb
def sanity_check():
sdb = chdb.init_scratch_db()
snippet_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM snippets''')[0]
assert snippet_count > 100
article_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM articles''')[0]
assert article_count > 100
if __name__ == '__main__':
sanity_check()
chdb.install_scratch_db()
|
Add a couple of sanity checks so we don't break the database.
|
Add a couple of sanity checks so we don't break the database.
Part of #139.
|
Python
|
mit
|
guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,eggpi/citationhunt
|
python
|
## Code Before:
import os
import sys
_upper_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
if _upper_dir not in sys.path:
sys.path.append(_upper_dir)
import chdb
if __name__ == '__main__':
chdb.install_scratch_db()
## Instruction:
Add a couple of sanity checks so we don't break the database.
Part of #139.
## Code After:
import os
import sys
_upper_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..'))
if _upper_dir not in sys.path:
sys.path.append(_upper_dir)
import chdb
def sanity_check():
sdb = chdb.init_scratch_db()
snippet_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM snippets''')[0]
assert snippet_count > 100
article_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM articles''')[0]
assert article_count > 100
if __name__ == '__main__':
sanity_check()
chdb.install_scratch_db()
|
...
import chdb
def sanity_check():
sdb = chdb.init_scratch_db()
snippet_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM snippets''')[0]
assert snippet_count > 100
article_count = sdb.execute_with_retry_s(
'''SELECT COUNT(*) FROM articles''')[0]
assert article_count > 100
if __name__ == '__main__':
sanity_check()
chdb.install_scratch_db()
...
|
c8db390195641c33f84ccd1f645a5af73debc2bd
|
xapi/tasks.py
|
xapi/tasks.py
|
from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
if options.get("SEND_CRON_ENABLED"):
TinCanSender.send_2_tincan_by_settings()
|
from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task(name='xapi.send_2_tin_can')
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
TinCanSender.send_2_tincan_by_settings()
|
Add a name to present task in djcelery options
|
Add a name to present task in djcelery options
|
Python
|
agpl-3.0
|
marcore/pok-eco,marcore/pok-eco
|
python
|
## Code Before:
from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
if options.get("SEND_CRON_ENABLED"):
TinCanSender.send_2_tincan_by_settings()
## Instruction:
Add a name to present task in djcelery options
## Code After:
from celery.task import task
from django.conf import settings
from xapi.sender import TinCanSender
@task(name='xapi.send_2_tin_can')
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
TinCanSender.send_2_tincan_by_settings()
|
# ... existing code ...
from xapi.sender import TinCanSender
@task(name='xapi.send_2_tin_can')
def send_2_tin_can():
options = settings.TRACKING_BACKENDS['xapi']['OPTIONS']
TinCanSender.send_2_tincan_by_settings()
# ... rest of the code ...
|
8df65a7aebb4bb6c2b21eacf7272056e02ec21e4
|
app/src/main/java/com/satsumasoftware/timetable/db/TimetableDbHelper.java
|
app/src/main/java/com/satsumasoftware/timetable/db/TimetableDbHelper.java
|
package com.satsumasoftware.timetable.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public final class TimetableDbHelper extends SQLiteOpenHelper {
private static TimetableDbHelper sInstance;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Timetable.db";
public static synchronized TimetableDbHelper getInstance(Context context) {
if (sInstance == null) {
sInstance = new TimetableDbHelper(context.getApplicationContext());
}
return sInstance;
}
private TimetableDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ClassesSchema.SQL_CREATE);
db.execSQL(SubjectsSchema.SQL_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(ClassesSchema.SQL_DELETE);
db.execSQL(SubjectsSchema.SQL_DELETE);
onCreate(db);
}
}
|
package com.satsumasoftware.timetable.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public final class TimetableDbHelper extends SQLiteOpenHelper {
private static TimetableDbHelper sInstance;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Timetable.db";
public static synchronized TimetableDbHelper getInstance(Context context) {
if (sInstance == null) {
sInstance = new TimetableDbHelper(context.getApplicationContext());
}
return sInstance;
}
private TimetableDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ClassDetailsMapSchema.SQL_CREATE);
db.execSQL(ClassDetailsSchema.SQL_CREATE);
db.execSQL(ClassDetailTimesMapSchema.SQL_CREATE);
db.execSQL(ClassesSchema.SQL_CREATE);
db.execSQL(ClassTimesSchema.SQL_CREATE);
db.execSQL(SubjectsSchema.SQL_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(ClassDetailsMapSchema.SQL_DELETE);
db.execSQL(ClassDetailsSchema.SQL_DELETE);
db.execSQL(ClassDetailTimesMapSchema.SQL_DELETE);
db.execSQL(ClassesSchema.SQL_DELETE);
db.execSQL(ClassTimesSchema.SQL_DELETE);
db.execSQL(SubjectsSchema.SQL_DELETE);
onCreate(db);
}
}
|
Add missing creation and deletion SQLite invocations
|
Add missing creation and deletion SQLite invocations
|
Java
|
apache-2.0
|
FarbodSalamat-Zadeh/TimetableApp,FarbodSalamat-Zadeh/TimetableApp
|
java
|
## Code Before:
package com.satsumasoftware.timetable.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public final class TimetableDbHelper extends SQLiteOpenHelper {
private static TimetableDbHelper sInstance;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Timetable.db";
public static synchronized TimetableDbHelper getInstance(Context context) {
if (sInstance == null) {
sInstance = new TimetableDbHelper(context.getApplicationContext());
}
return sInstance;
}
private TimetableDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ClassesSchema.SQL_CREATE);
db.execSQL(SubjectsSchema.SQL_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(ClassesSchema.SQL_DELETE);
db.execSQL(SubjectsSchema.SQL_DELETE);
onCreate(db);
}
}
## Instruction:
Add missing creation and deletion SQLite invocations
## Code After:
package com.satsumasoftware.timetable.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public final class TimetableDbHelper extends SQLiteOpenHelper {
private static TimetableDbHelper sInstance;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Timetable.db";
public static synchronized TimetableDbHelper getInstance(Context context) {
if (sInstance == null) {
sInstance = new TimetableDbHelper(context.getApplicationContext());
}
return sInstance;
}
private TimetableDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ClassDetailsMapSchema.SQL_CREATE);
db.execSQL(ClassDetailsSchema.SQL_CREATE);
db.execSQL(ClassDetailTimesMapSchema.SQL_CREATE);
db.execSQL(ClassesSchema.SQL_CREATE);
db.execSQL(ClassTimesSchema.SQL_CREATE);
db.execSQL(SubjectsSchema.SQL_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(ClassDetailsMapSchema.SQL_DELETE);
db.execSQL(ClassDetailsSchema.SQL_DELETE);
db.execSQL(ClassDetailTimesMapSchema.SQL_DELETE);
db.execSQL(ClassesSchema.SQL_DELETE);
db.execSQL(ClassTimesSchema.SQL_DELETE);
db.execSQL(SubjectsSchema.SQL_DELETE);
onCreate(db);
}
}
|
...
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ClassDetailsMapSchema.SQL_CREATE);
db.execSQL(ClassDetailsSchema.SQL_CREATE);
db.execSQL(ClassDetailTimesMapSchema.SQL_CREATE);
db.execSQL(ClassesSchema.SQL_CREATE);
db.execSQL(ClassTimesSchema.SQL_CREATE);
db.execSQL(SubjectsSchema.SQL_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(ClassDetailsMapSchema.SQL_DELETE);
db.execSQL(ClassDetailsSchema.SQL_DELETE);
db.execSQL(ClassDetailTimesMapSchema.SQL_DELETE);
db.execSQL(ClassesSchema.SQL_DELETE);
db.execSQL(ClassTimesSchema.SQL_DELETE);
db.execSQL(SubjectsSchema.SQL_DELETE);
onCreate(db);
}
...
|
9127e56a26e836c7e2a66359a9f9b67e6c7f8474
|
ovp_users/tests/test_filters.py
|
ovp_users/tests/test_filters.py
|
from django.test import TestCase
from ovp_users.recover_password import RecoveryTokenFilter
from ovp_users.recover_password import RecoverPasswordFilter
def test_filter(c):
obj = c()
obj.filter_queryset('a', 'b', 'c')
obj.get_fields('a')
def TestPasswordRecoveryFilters(TestCase):
def test_filters():
"""Assert filters do not throw error when instantiated"""
# Nothing to assert here, we just instantiate them and
# make sure it throws no error
test_filter(RecoveryTokenFilter)
test_filter(RecoverPasswordFilter)
|
from django.test import TestCase
from ovp_users.recover_password import RecoveryTokenFilter
from ovp_users.recover_password import RecoverPasswordFilter
def test_filter(c):
obj = c()
obj.filter_queryset('a', 'b', 'c')
obj.get_fields('a')
def PasswordRecoveryFiltersTestCase(TestCase):
def test_filters():
"""Assert filters do not throw error when instantiated"""
# Nothing to assert here, we just instantiate them and
# make sure it throws no error
test_filter(RecoveryTokenFilter)
test_filter(RecoverPasswordFilter)
|
Fix PasswordRecovery test case name
|
Fix PasswordRecovery test case name
|
Python
|
agpl-3.0
|
OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users
|
python
|
## Code Before:
from django.test import TestCase
from ovp_users.recover_password import RecoveryTokenFilter
from ovp_users.recover_password import RecoverPasswordFilter
def test_filter(c):
obj = c()
obj.filter_queryset('a', 'b', 'c')
obj.get_fields('a')
def TestPasswordRecoveryFilters(TestCase):
def test_filters():
"""Assert filters do not throw error when instantiated"""
# Nothing to assert here, we just instantiate them and
# make sure it throws no error
test_filter(RecoveryTokenFilter)
test_filter(RecoverPasswordFilter)
## Instruction:
Fix PasswordRecovery test case name
## Code After:
from django.test import TestCase
from ovp_users.recover_password import RecoveryTokenFilter
from ovp_users.recover_password import RecoverPasswordFilter
def test_filter(c):
obj = c()
obj.filter_queryset('a', 'b', 'c')
obj.get_fields('a')
def PasswordRecoveryFiltersTestCase(TestCase):
def test_filters():
"""Assert filters do not throw error when instantiated"""
# Nothing to assert here, we just instantiate them and
# make sure it throws no error
test_filter(RecoveryTokenFilter)
test_filter(RecoverPasswordFilter)
|
...
obj.filter_queryset('a', 'b', 'c')
obj.get_fields('a')
def PasswordRecoveryFiltersTestCase(TestCase):
def test_filters():
"""Assert filters do not throw error when instantiated"""
# Nothing to assert here, we just instantiate them and
...
|
564e611d7cb0b94e71c53e69971a49c312a0f7f8
|
tob-api/tob_api/custom_settings_ongov.py
|
tob-api/tob_api/custom_settings_ongov.py
|
'''
Enclose property names in double quotes in order to JSON serialize the contents in the API
'''
CUSTOMIZATIONS = {
"serializers":
{
"Location":
{
"includeFields":{
"id",
"verifiableOrgId",
"doingBusinessAsId",
"locationTypeId",
"municipality",
"province"
}
}
}
}
|
'''
Enclose property names in double quotes in order to JSON serialize the contents in the API
'''
CUSTOMIZATIONS = {
"serializers":
{
"Location":
{
"includeFields":[
"id",
"verifiableOrgId",
"doingBusinessAsId",
"locationTypeId",
"municipality",
"province"
]
}
}
}
|
Fix ongov customs settings formatting.
|
Fix ongov customs settings formatting.
|
Python
|
apache-2.0
|
swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook
|
python
|
## Code Before:
'''
Enclose property names in double quotes in order to JSON serialize the contents in the API
'''
CUSTOMIZATIONS = {
"serializers":
{
"Location":
{
"includeFields":{
"id",
"verifiableOrgId",
"doingBusinessAsId",
"locationTypeId",
"municipality",
"province"
}
}
}
}
## Instruction:
Fix ongov customs settings formatting.
## Code After:
'''
Enclose property names in double quotes in order to JSON serialize the contents in the API
'''
CUSTOMIZATIONS = {
"serializers":
{
"Location":
{
"includeFields":[
"id",
"verifiableOrgId",
"doingBusinessAsId",
"locationTypeId",
"municipality",
"province"
]
}
}
}
|
// ... existing code ...
{
"Location":
{
"includeFields":[
"id",
"verifiableOrgId",
"doingBusinessAsId",
// ... modified code ...
"locationTypeId",
"municipality",
"province"
]
}
}
}
// ... rest of the code ...
|
52c88fc6a02618829203a12ba69da47bbc89a31d
|
junit-commons/src/main/java/org/junit/gen5/commons/util/CollectionUtils.java
|
junit-commons/src/main/java/org/junit/gen5/commons/util/CollectionUtils.java
|
/*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.commons.util;
import java.util.Collection;
/**
* Collection of utilities for working with {@link Collection Collections}.
*
* @since 5.0
*/
public class CollectionUtils {
/**
* Read the only element of a collection of size 1.
*
* @param collection the collection to read the element from
* @return the only element of the collection
* @throws IllegalArgumentException if the collection is empty or contains
* more than one element
*/
public static <T> T getOnlyElement(Collection<T> collection) {
Preconditions.condition(collection.size() == 1,
() -> "collection must contain exactly one element: " + collection);
return collection.iterator().next();
}
}
|
/*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.commons.util;
import java.util.Collection;
/**
* Collection of utilities for working with {@link Collection Collections}.
*
* @since 5.0
*/
public class CollectionUtils {
private CollectionUtils() {
/* no-op */
}
/**
* Read the only element of a collection of size 1.
*
* @param collection the collection to read the element from
* @return the only element of the collection
* @throws IllegalArgumentException if the collection is empty or contains
* more than one element
*/
public static <T> T getOnlyElement(Collection<T> collection) {
Preconditions.condition(collection.size() == 1,
() -> "collection must contain exactly one element: " + collection);
return collection.iterator().next();
}
}
|
Add private constructor to prevent instantiation
|
Add private constructor to prevent instantiation
------------------------------------------------------------------------
On behalf of the community, the JUnit Lambda Team thanks
msg systems ag (http://www.msg-systems.com) for supporting
the JUnit crowdfunding campaign!
------------------------------------------------------------------------
|
Java
|
epl-1.0
|
junit-team/junit-lambda,marcphilipp/junit5,sbrannen/junit-lambda,marcphilipp/junit-lambda
|
java
|
## Code Before:
/*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.commons.util;
import java.util.Collection;
/**
* Collection of utilities for working with {@link Collection Collections}.
*
* @since 5.0
*/
public class CollectionUtils {
/**
* Read the only element of a collection of size 1.
*
* @param collection the collection to read the element from
* @return the only element of the collection
* @throws IllegalArgumentException if the collection is empty or contains
* more than one element
*/
public static <T> T getOnlyElement(Collection<T> collection) {
Preconditions.condition(collection.size() == 1,
() -> "collection must contain exactly one element: " + collection);
return collection.iterator().next();
}
}
## Instruction:
Add private constructor to prevent instantiation
------------------------------------------------------------------------
On behalf of the community, the JUnit Lambda Team thanks
msg systems ag (http://www.msg-systems.com) for supporting
the JUnit crowdfunding campaign!
------------------------------------------------------------------------
## Code After:
/*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.commons.util;
import java.util.Collection;
/**
* Collection of utilities for working with {@link Collection Collections}.
*
* @since 5.0
*/
public class CollectionUtils {
private CollectionUtils() {
/* no-op */
}
/**
* Read the only element of a collection of size 1.
*
* @param collection the collection to read the element from
* @return the only element of the collection
* @throws IllegalArgumentException if the collection is empty or contains
* more than one element
*/
public static <T> T getOnlyElement(Collection<T> collection) {
Preconditions.condition(collection.size() == 1,
() -> "collection must contain exactly one element: " + collection);
return collection.iterator().next();
}
}
|
...
*/
public class CollectionUtils {
private CollectionUtils() {
/* no-op */
}
/**
* Read the only element of a collection of size 1.
*
...
|
a56b69ef48acb0badf04625650dfdc25d1517a81
|
resdk/tests/functional/resolwe/e2e_resolwe.py
|
resdk/tests/functional/resolwe/e2e_resolwe.py
|
from resdk.tests.functional.base import BaseResdkFunctionalTest
class TestDataUsage(BaseResdkFunctionalTest):
expected_fields = {
'user_id',
'username',
'full_name',
'data_size',
'data_size_normalized',
'data_count',
'data_count_normalized',
'sample_count',
'sample_count_normalized',
}
def test_normal_user(self):
usage_info = self.user_res.data_usage()
self.assertEqual(len(usage_info), 1)
self.assertEqual(set(usage_info[0].keys()), self.expected_fields)
def test_admin_user(self):
usage_info = self.res.data_usage()
self.assertGreaterEqual(len(usage_info), 2)
self.assertEqual(set(usage_info[0].keys()), self.expected_fields)
def test_ordering(self):
usage_info = self.res.data_usage(ordering=['full_name', '-data_size'])
self.assertGreaterEqual(len(usage_info), 2)
first = usage_info[0]
second = usage_info[1]
self.assertEqual(first['full_name'], second['full_name'])
self.assertGreaterEqual(first['data_size'], second['data_size'])
|
from resdk.tests.functional.base import BaseResdkFunctionalTest
class TestDataUsage(BaseResdkFunctionalTest):
expected_fields = {
'user_id',
'username',
'full_name',
'data_size',
'data_size_normalized',
'data_count',
'data_count_normalized',
'collection_count',
'collection_count_normalized',
'sample_count',
'sample_count_normalized',
}
def test_normal_user(self):
usage_info = self.user_res.data_usage()
self.assertEqual(len(usage_info), 1)
self.assertEqual(set(usage_info[0].keys()), self.expected_fields)
def test_admin_user(self):
usage_info = self.res.data_usage()
self.assertGreaterEqual(len(usage_info), 2)
self.assertEqual(set(usage_info[0].keys()), self.expected_fields)
def test_ordering(self):
usage_info = self.res.data_usage(ordering=['full_name', '-data_size'])
self.assertGreaterEqual(len(usage_info), 2)
first = usage_info[0]
second = usage_info[1]
self.assertEqual(first['full_name'], second['full_name'])
self.assertGreaterEqual(first['data_size'], second['data_size'])
|
Support collection statistics in data usage tests
|
Support collection statistics in data usage tests
|
Python
|
apache-2.0
|
genialis/resolwe-bio-py
|
python
|
## Code Before:
from resdk.tests.functional.base import BaseResdkFunctionalTest
class TestDataUsage(BaseResdkFunctionalTest):
expected_fields = {
'user_id',
'username',
'full_name',
'data_size',
'data_size_normalized',
'data_count',
'data_count_normalized',
'sample_count',
'sample_count_normalized',
}
def test_normal_user(self):
usage_info = self.user_res.data_usage()
self.assertEqual(len(usage_info), 1)
self.assertEqual(set(usage_info[0].keys()), self.expected_fields)
def test_admin_user(self):
usage_info = self.res.data_usage()
self.assertGreaterEqual(len(usage_info), 2)
self.assertEqual(set(usage_info[0].keys()), self.expected_fields)
def test_ordering(self):
usage_info = self.res.data_usage(ordering=['full_name', '-data_size'])
self.assertGreaterEqual(len(usage_info), 2)
first = usage_info[0]
second = usage_info[1]
self.assertEqual(first['full_name'], second['full_name'])
self.assertGreaterEqual(first['data_size'], second['data_size'])
## Instruction:
Support collection statistics in data usage tests
## Code After:
from resdk.tests.functional.base import BaseResdkFunctionalTest
class TestDataUsage(BaseResdkFunctionalTest):
expected_fields = {
'user_id',
'username',
'full_name',
'data_size',
'data_size_normalized',
'data_count',
'data_count_normalized',
'collection_count',
'collection_count_normalized',
'sample_count',
'sample_count_normalized',
}
def test_normal_user(self):
usage_info = self.user_res.data_usage()
self.assertEqual(len(usage_info), 1)
self.assertEqual(set(usage_info[0].keys()), self.expected_fields)
def test_admin_user(self):
usage_info = self.res.data_usage()
self.assertGreaterEqual(len(usage_info), 2)
self.assertEqual(set(usage_info[0].keys()), self.expected_fields)
def test_ordering(self):
usage_info = self.res.data_usage(ordering=['full_name', '-data_size'])
self.assertGreaterEqual(len(usage_info), 2)
first = usage_info[0]
second = usage_info[1]
self.assertEqual(first['full_name'], second['full_name'])
self.assertGreaterEqual(first['data_size'], second['data_size'])
|
...
'data_size_normalized',
'data_count',
'data_count_normalized',
'collection_count',
'collection_count_normalized',
'sample_count',
'sample_count_normalized',
}
...
|
4dfe50691b911d05be9a82946df77e234283ffe2
|
codejail/util.py
|
codejail/util.py
|
"""Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
class TempDirectory(object):
def __init__(self):
self.temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(self.temp_dir, 0775)
def clean_up(self):
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(self.temp_dir)
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
tmp = TempDirectory()
try:
yield tmp.temp_dir
finally:
tmp.clean_up()
class ChangeDirectory(object):
def __init__(self, new_dir):
self.old_dir = os.getcwd()
os.chdir(new_dir)
def clean_up(self):
os.chdir(self.old_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
cd = ChangeDirectory(new_dir)
try:
yield new_dir
finally:
cd.clean_up()
|
"""Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(temp_dir, 0775)
try:
yield temp_dir
finally:
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(temp_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
old_dir = os.getcwd()
os.chdir(new_dir)
try:
yield new_dir
finally:
os.chdir(old_dir)
|
Simplify these decorators, since we don't use the classes here anyway.
|
Simplify these decorators, since we don't use the classes here anyway.
|
Python
|
apache-2.0
|
edx/codejail,StepicOrg/codejail
|
python
|
## Code Before:
"""Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
class TempDirectory(object):
def __init__(self):
self.temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(self.temp_dir, 0775)
def clean_up(self):
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(self.temp_dir)
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
tmp = TempDirectory()
try:
yield tmp.temp_dir
finally:
tmp.clean_up()
class ChangeDirectory(object):
def __init__(self, new_dir):
self.old_dir = os.getcwd()
os.chdir(new_dir)
def clean_up(self):
os.chdir(self.old_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
cd = ChangeDirectory(new_dir)
try:
yield new_dir
finally:
cd.clean_up()
## Instruction:
Simplify these decorators, since we don't use the classes here anyway.
## Code After:
"""Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(temp_dir, 0775)
try:
yield temp_dir
finally:
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(temp_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
old_dir = os.getcwd()
os.chdir(new_dir)
try:
yield new_dir
finally:
os.chdir(old_dir)
|
...
import tempfile
@contextlib.contextmanager
def temp_directory():
"""
...
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(temp_dir, 0775)
try:
yield temp_dir
finally:
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(temp_dir)
@contextlib.contextmanager
...
"""
A context manager to change the directory, and then change it back.
"""
old_dir = os.getcwd()
os.chdir(new_dir)
try:
yield new_dir
finally:
os.chdir(old_dir)
...
|
f0d19857914f196db624abcd9de718d1d4b73e84
|
organizer/views.py
|
organizer/views.py
|
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
|
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
return HttpResponse()
|
Tag Detail: create view skeleton.
|
Ch05: Tag Detail: create view skeleton.
|
Python
|
bsd-2-clause
|
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
|
python
|
## Code Before:
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
## Instruction:
Ch05: Tag Detail: create view skeleton.
## Code After:
from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
return HttpResponse()
|
...
context = Context({'tag_list': tag_list})
output = template.render(context)
return HttpResponse(output)
def tag_detail(request):
return HttpResponse()
...
|
92bbf5c179d533c93c19a51a62770cf5392a95a5
|
t/04-nativecall/04-pointers.c
|
t/04-nativecall/04-pointers.c
|
DLLEXPORT void * ReturnSomePointer()
{
char *x = "Got passed back the pointer I returned";
return x;
}
DLLEXPORT int CompareSomePointer(void *ptr)
{
int x = strcmp("Got passed back the pointer I returned", ptr) == 0;
return x;
}
DLLEXPORT void * ReturnNullPointer()
{
return NULL;
}
DLLEXPORT void * TakeTwoPointersToInt(int *ptr1, int *ptr2)
{
return NULL;
}
DLLEXPORT void * TakeCArrayToInt8(int array[]) {
return NULL;
}
|
DLLEXPORT void * ReturnSomePointer()
{
return strdup("Got passed back the pointer I returned");
}
DLLEXPORT int CompareSomePointer(void *ptr)
{
int x = strcmp("Got passed back the pointer I returned", ptr) == 0;
free(ptr);
return x;
}
DLLEXPORT void * ReturnNullPointer()
{
return NULL;
}
DLLEXPORT void * TakeTwoPointersToInt(int *ptr1, int *ptr2)
{
return NULL;
}
DLLEXPORT void * TakeCArrayToInt8(int array[]) {
return NULL;
}
|
Fix C issue in NativeCall tests.
|
Fix C issue in NativeCall tests.
One of the pointer tests returned a pointer to astack allocated string outside
of the function, which is not very safe. Replace it with a strdup()ed string
that's freed on verification.
|
C
|
artistic-2.0
|
ab5tract/rakudo,b2gills/rakudo,niner/rakudo,nbrown/rakudo,sergot/rakudo,cygx/rakudo,samcv/rakudo,rakudo/rakudo,lucasbuchala/rakudo,raydiak/rakudo,b2gills/rakudo,niner/rakudo,niner/rakudo,salortiz/rakudo,rakudo/rakudo,Gnouc/rakudo,softmoth/rakudo,paultcochrane/rakudo,zostay/rakudo,tony-o/rakudo,nunorc/rakudo,cygx/rakudo,ungrim97/rakudo,dankogai/rakudo,salortiz/rakudo,zostay/rakudo,sergot/rakudo,usev6/rakudo,sjn/rakudo,MasterDuke17/rakudo,salortiz/rakudo,MasterDuke17/rakudo,ab5tract/rakudo,cognominal/rakudo,LLFourn/rakudo,ab5tract/rakudo,samcv/rakudo,Gnouc/rakudo,jonathanstowe/rakudo,ungrim97/rakudo,awwaiid/rakudo,tbrowder/rakudo,Leont/rakudo,labster/rakudo,rakudo/rakudo,tony-o/rakudo,salortiz/rakudo,softmoth/rakudo,zhuomingliang/rakudo,labster/rakudo,samcv/rakudo,samcv/rakudo,cygx/rakudo,cognominal/rakudo,sjn/rakudo,jonathanstowe/rakudo,labster/rakudo,jonathanstowe/rakudo,Gnouc/rakudo,ugexe/rakudo,skids/rakudo,laben/rakudo,nbrown/rakudo,awwaiid/rakudo,sjn/rakudo,azawawi/rakudo,LLFourn/rakudo,tony-o/rakudo,nunorc/rakudo,laben/rakudo,Gnouc/rakudo,cygx/rakudo,Leont/rakudo,sergot/rakudo,usev6/rakudo,labster/rakudo,ugexe/rakudo,b2gills/rakudo,paultcochrane/rakudo,MasterDuke17/rakudo,jonathanstowe/rakudo,raydiak/rakudo,skids/rakudo,azawawi/rakudo,MasterDuke17/rakudo,nbrown/rakudo,awwaiid/rakudo,tbrowder/rakudo,laben/rakudo,paultcochrane/rakudo,nunorc/rakudo,paultcochrane/rakudo,ab5tract/rakudo,dankogai/rakudo,zhuomingliang/rakudo,jonathanstowe/rakudo,cognominal/rakudo,lucasbuchala/rakudo,paultcochrane/rakudo,MasterDuke17/rakudo,azawawi/rakudo,dankogai/rakudo,labster/rakudo,rakudo/rakudo,tbrowder/rakudo,lucasbuchala/rakudo,dankogai/rakudo,sjn/rakudo,ugexe/rakudo,nbrown/rakudo,usev6/rakudo,usev6/rakudo,rakudo/rakudo,salortiz/rakudo,ugexe/rakudo,sjn/rakudo,cygx/rakudo,LLFourn/rakudo,rakudo/rakudo,Gnouc/rakudo,skids/rakudo,LLFourn/rakudo,cognominal/rakudo,Leont/rakudo,ungrim97/rakudo,tony-o/rakudo,nbrown/rakudo,awwaiid/rakudo,cognominal/rakudo,samcv/rakudo,niner/rakudo,Leont/rakudo,tbrowder/rakudo,tbrowder/rakudo,softmoth/rakudo,sergot/rakudo,softmoth/rakudo,tony-o/rakudo,salortiz/rakudo,nunorc/rakudo,zhuomingliang/rakudo,laben/rakudo,b2gills/rakudo,lucasbuchala/rakudo,ab5tract/rakudo,awwaiid/rakudo,nbrown/rakudo,skids/rakudo,usev6/rakudo,zostay/rakudo,zhuomingliang/rakudo,b2gills/rakudo,MasterDuke17/rakudo,raydiak/rakudo,skids/rakudo,lucasbuchala/rakudo,Gnouc/rakudo,dankogai/rakudo,LLFourn/rakudo,tbrowder/rakudo,labster/rakudo,azawawi/rakudo,raydiak/rakudo,softmoth/rakudo,ugexe/rakudo,ungrim97/rakudo,tony-o/rakudo,zostay/rakudo,azawawi/rakudo,ungrim97/rakudo
|
c
|
## Code Before:
DLLEXPORT void * ReturnSomePointer()
{
char *x = "Got passed back the pointer I returned";
return x;
}
DLLEXPORT int CompareSomePointer(void *ptr)
{
int x = strcmp("Got passed back the pointer I returned", ptr) == 0;
return x;
}
DLLEXPORT void * ReturnNullPointer()
{
return NULL;
}
DLLEXPORT void * TakeTwoPointersToInt(int *ptr1, int *ptr2)
{
return NULL;
}
DLLEXPORT void * TakeCArrayToInt8(int array[]) {
return NULL;
}
## Instruction:
Fix C issue in NativeCall tests.
One of the pointer tests returned a pointer to astack allocated string outside
of the function, which is not very safe. Replace it with a strdup()ed string
that's freed on verification.
## Code After:
DLLEXPORT void * ReturnSomePointer()
{
return strdup("Got passed back the pointer I returned");
}
DLLEXPORT int CompareSomePointer(void *ptr)
{
int x = strcmp("Got passed back the pointer I returned", ptr) == 0;
free(ptr);
return x;
}
DLLEXPORT void * ReturnNullPointer()
{
return NULL;
}
DLLEXPORT void * TakeTwoPointersToInt(int *ptr1, int *ptr2)
{
return NULL;
}
DLLEXPORT void * TakeCArrayToInt8(int array[]) {
return NULL;
}
|
# ... existing code ...
DLLEXPORT void * ReturnSomePointer()
{
return strdup("Got passed back the pointer I returned");
}
DLLEXPORT int CompareSomePointer(void *ptr)
{
int x = strcmp("Got passed back the pointer I returned", ptr) == 0;
free(ptr);
return x;
}
# ... rest of the code ...
|
f54db5d4e132fe1c227fe5bf1f7079772433429d
|
yunity/models/utils.py
|
yunity/models/utils.py
|
from django.db.models import Model, CharField, Field
class MaxLengthCharField(CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 255
super().__init__(*args, **kwargs)
class BaseModel(Model):
class Meta:
abstract = True
def _get_explicit_field_names(self):
return [field.name for field in self._meta.get_fields()
if isinstance(field, Field) and field.name != 'id']
def to_dict(self):
fields = self._get_explicit_field_names()
return {field: getattr(self, field) for field in fields}
def __repr__(self):
return 'Model({})'.format(repr(self.to_dict()))
|
from django.db.models import Model, CharField, Field
class MaxLengthCharField(CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 255
super().__init__(*args, **kwargs)
class BaseModel(Model):
class Meta:
abstract = True
def _get_explicit_field_names(self):
return [field.name for field in self._meta.get_fields()
if isinstance(field, Field) and field.name != 'id']
def to_dict(self):
fields = self._get_explicit_field_names()
return {field: getattr(self, field) for field in fields}
def __repr__(self):
model = str(self.__class__.__name__)
columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items())
return '{}({})'.format(model, columns)
|
Add columns and values to repr
|
Add columns and values to repr
|
Python
|
agpl-3.0
|
yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
|
python
|
## Code Before:
from django.db.models import Model, CharField, Field
class MaxLengthCharField(CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 255
super().__init__(*args, **kwargs)
class BaseModel(Model):
class Meta:
abstract = True
def _get_explicit_field_names(self):
return [field.name for field in self._meta.get_fields()
if isinstance(field, Field) and field.name != 'id']
def to_dict(self):
fields = self._get_explicit_field_names()
return {field: getattr(self, field) for field in fields}
def __repr__(self):
return 'Model({})'.format(repr(self.to_dict()))
## Instruction:
Add columns and values to repr
## Code After:
from django.db.models import Model, CharField, Field
class MaxLengthCharField(CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 255
super().__init__(*args, **kwargs)
class BaseModel(Model):
class Meta:
abstract = True
def _get_explicit_field_names(self):
return [field.name for field in self._meta.get_fields()
if isinstance(field, Field) and field.name != 'id']
def to_dict(self):
fields = self._get_explicit_field_names()
return {field: getattr(self, field) for field in fields}
def __repr__(self):
model = str(self.__class__.__name__)
columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items())
return '{}({})'.format(model, columns)
|
...
return {field: getattr(self, field) for field in fields}
def __repr__(self):
model = str(self.__class__.__name__)
columns = ', '.join('{}="{}"'.format(field, value) for field, value in self.to_dict().items())
return '{}({})'.format(model, columns)
...
|
f030aedd7a82635aba3ac6baef106a260e1ffaaf
|
src/org/robockets/robotswitcher/Switcher.java
|
src/org/robockets/robotswitcher/Switcher.java
|
package org.robockets.robotswitcher;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/** Used to get and initialize a SmartDashboard field for a robot number
*
*
* @author Jake Backer
* @version
v.1.sleepy.1.0.ocean.1450230474.7
*
*
*
*
*/
public class Switcher {
/** Holds the value of the SmartDashboard field*/
public int currentRobot;
/** Initializes the currentRobot field*/
public Switcher() {
try{
currentRobot = getRobot();
}catch(DoesNotExistException e){
e.printStackTrace();
}
}
/**
* Stores the value of the field in SmartDashboard in currentRobot
* @return The value of currentRobot
* @throws DoesNotExistException Thrown if field on SmartDashboard does not exist
*/
public int getRobot() throws DoesNotExistException{
currentRobot = (int) SmartDashboard.getNumber("RobotNumber");
return currentRobot;
}
/** Initializes the field on SmartDashboard TEMPORARY*/
public void initRobotNumber() {
SmartDashboard.putNumber("RobotNumber", 0); //TEMP
}
}
|
package org.robockets.robotswitcher;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/** Used to get and initialize a SmartDashboard field for a robot number
*
*
* @author Jake Backer
* @version
v.1.sleepy.1.0.ocean.1450230474.7
*
*
*
*
*/
public class Switcher {
/** Holds the value of the SmartDashboard field*/
public int currentRobot;
/** Initializes the currentRobot field*/
public Switcher() {
try{
currentRobot = getRobot();
}catch(DoesNotExistException e){
System.out.println("SmartDashboard field does not exist! Run initRobotNumber()");
}
}
/**
* Stores the value of the field in SmartDashboard in currentRobot
* @return The value of currentRobot
* @throws DoesNotExistException Thrown if field on SmartDashboard does not exist
*/
public int getRobot() throws DoesNotExistException{
currentRobot = (int) SmartDashboard.getNumber("RobotNumber");
return currentRobot;
}
/** Initializes the field on SmartDashboard TEMPORARY*/
public void initRobotNumber() {
SmartDashboard.putNumber("RobotNumber", 0); //TEMP
}
}
|
Change what happens when there is no field on SmartDashboard
|
Change what happens when there is no field on SmartDashboard
|
Java
|
mit
|
Team4761/RobotSwitcher,Team4761/Robot-Switcher
|
java
|
## Code Before:
package org.robockets.robotswitcher;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/** Used to get and initialize a SmartDashboard field for a robot number
*
*
* @author Jake Backer
* @version
v.1.sleepy.1.0.ocean.1450230474.7
*
*
*
*
*/
public class Switcher {
/** Holds the value of the SmartDashboard field*/
public int currentRobot;
/** Initializes the currentRobot field*/
public Switcher() {
try{
currentRobot = getRobot();
}catch(DoesNotExistException e){
e.printStackTrace();
}
}
/**
* Stores the value of the field in SmartDashboard in currentRobot
* @return The value of currentRobot
* @throws DoesNotExistException Thrown if field on SmartDashboard does not exist
*/
public int getRobot() throws DoesNotExistException{
currentRobot = (int) SmartDashboard.getNumber("RobotNumber");
return currentRobot;
}
/** Initializes the field on SmartDashboard TEMPORARY*/
public void initRobotNumber() {
SmartDashboard.putNumber("RobotNumber", 0); //TEMP
}
}
## Instruction:
Change what happens when there is no field on SmartDashboard
## Code After:
package org.robockets.robotswitcher;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/** Used to get and initialize a SmartDashboard field for a robot number
*
*
* @author Jake Backer
* @version
v.1.sleepy.1.0.ocean.1450230474.7
*
*
*
*
*/
public class Switcher {
/** Holds the value of the SmartDashboard field*/
public int currentRobot;
/** Initializes the currentRobot field*/
public Switcher() {
try{
currentRobot = getRobot();
}catch(DoesNotExistException e){
System.out.println("SmartDashboard field does not exist! Run initRobotNumber()");
}
}
/**
* Stores the value of the field in SmartDashboard in currentRobot
* @return The value of currentRobot
* @throws DoesNotExistException Thrown if field on SmartDashboard does not exist
*/
public int getRobot() throws DoesNotExistException{
currentRobot = (int) SmartDashboard.getNumber("RobotNumber");
return currentRobot;
}
/** Initializes the field on SmartDashboard TEMPORARY*/
public void initRobotNumber() {
SmartDashboard.putNumber("RobotNumber", 0); //TEMP
}
}
|
...
try{
currentRobot = getRobot();
}catch(DoesNotExistException e){
System.out.println("SmartDashboard field does not exist! Run initRobotNumber()");
}
}
...
|
3213d4fdf5852aaa3dc2cde4c5cd563abbd011e1
|
ethereumj-core/src/test/java/org/ethereum/solidity/CompilerTest.java
|
ethereumj-core/src/test/java/org/ethereum/solidity/CompilerTest.java
|
package org.ethereum.solidity;
import org.ethereum.solidity.compiler.CompilationResult;
import org.ethereum.solidity.compiler.SolidityCompiler;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
/**
* Created by Anton Nashatyrev on 03.03.2016.
*/
public class CompilerTest {
@Test
public void simpleTest() throws IOException {
String contract =
"contract a {" +
" int i1;" +
" function i() returns (int) {" +
" return i1;" +
" }" +
"}";
SolidityCompiler.Result res = SolidityCompiler.compile(
contract.getBytes(), true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.INTERFACE);
System.out.println(res.output);
System.out.println(res.errors);
CompilationResult result = CompilationResult.parse(res.output);
System.out.println(result.contracts.get("a").bin);
}
public static void main(String[] args) throws Exception {
new CompilerTest().simpleTest();
}
}
|
package org.ethereum.solidity;
import org.ethereum.solidity.compiler.CompilationResult;
import org.ethereum.solidity.compiler.SolidityCompiler;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
/**
* Created by Anton Nashatyrev on 03.03.2016.
*/
public class CompilerTest {
@Test
public void simpleTest() throws IOException {
String contract =
"contract a {" +
" int i1;" +
" function i() returns (int) {" +
" return i1;" +
" }" +
"}";
SolidityCompiler.Result res = SolidityCompiler.compile(
contract.getBytes(), true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.INTERFACE);
System.out.println("Out: '" + res.output + "'");
System.out.println("Err: '" + res.errors + "'");
CompilationResult result = CompilationResult.parse(res.output);
System.out.println(result.contracts.get("a").bin);
}
public static void main(String[] args) throws Exception {
new CompilerTest().simpleTest();
}
}
|
Add bit more out in test
|
Add bit more out in test
|
Java
|
mit
|
chengtalent/ethereumj,loxal/FreeEthereum,loxal/FreeEthereum,loxal/ethereumj,loxal/FreeEthereum,caxqueiroz/ethereumj
|
java
|
## Code Before:
package org.ethereum.solidity;
import org.ethereum.solidity.compiler.CompilationResult;
import org.ethereum.solidity.compiler.SolidityCompiler;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
/**
* Created by Anton Nashatyrev on 03.03.2016.
*/
public class CompilerTest {
@Test
public void simpleTest() throws IOException {
String contract =
"contract a {" +
" int i1;" +
" function i() returns (int) {" +
" return i1;" +
" }" +
"}";
SolidityCompiler.Result res = SolidityCompiler.compile(
contract.getBytes(), true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.INTERFACE);
System.out.println(res.output);
System.out.println(res.errors);
CompilationResult result = CompilationResult.parse(res.output);
System.out.println(result.contracts.get("a").bin);
}
public static void main(String[] args) throws Exception {
new CompilerTest().simpleTest();
}
}
## Instruction:
Add bit more out in test
## Code After:
package org.ethereum.solidity;
import org.ethereum.solidity.compiler.CompilationResult;
import org.ethereum.solidity.compiler.SolidityCompiler;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
/**
* Created by Anton Nashatyrev on 03.03.2016.
*/
public class CompilerTest {
@Test
public void simpleTest() throws IOException {
String contract =
"contract a {" +
" int i1;" +
" function i() returns (int) {" +
" return i1;" +
" }" +
"}";
SolidityCompiler.Result res = SolidityCompiler.compile(
contract.getBytes(), true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.INTERFACE);
System.out.println("Out: '" + res.output + "'");
System.out.println("Err: '" + res.errors + "'");
CompilationResult result = CompilationResult.parse(res.output);
System.out.println(result.contracts.get("a").bin);
}
public static void main(String[] args) throws Exception {
new CompilerTest().simpleTest();
}
}
|
// ... existing code ...
"}";
SolidityCompiler.Result res = SolidityCompiler.compile(
contract.getBytes(), true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.INTERFACE);
System.out.println("Out: '" + res.output + "'");
System.out.println("Err: '" + res.errors + "'");
CompilationResult result = CompilationResult.parse(res.output);
System.out.println(result.contracts.get("a").bin);
}
// ... rest of the code ...
|
f7852806c3198d58162b66e18bfd9998ef33b63c
|
lexos/receivers/stats_receiver.py
|
lexos/receivers/stats_receiver.py
|
from lexos.receivers.base_receiver import BaseReceiver
class StatsReceiver(BaseReceiver):
def __init__(self):
"""So far there is no frontend option for statistics analysis"""
super().__init__()
def options_from_front_end(self):
"""So far there is no frontend option for statistics analysis"""
pass
|
from lexos.receivers.base_receiver import BaseReceiver
class StatsReceiver(BaseReceiver):
def __init__(self):
"""So far there is no frontend option for statistics analysis"""
super().__init__()
def options_from_front_end(self):
"""So far there is no frontend option for statistics analysis"""
raise NotImplementedError
|
Modify receiver to prevent using in future
|
Modify receiver to prevent using in future
|
Python
|
mit
|
WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos
|
python
|
## Code Before:
from lexos.receivers.base_receiver import BaseReceiver
class StatsReceiver(BaseReceiver):
def __init__(self):
"""So far there is no frontend option for statistics analysis"""
super().__init__()
def options_from_front_end(self):
"""So far there is no frontend option for statistics analysis"""
pass
## Instruction:
Modify receiver to prevent using in future
## Code After:
from lexos.receivers.base_receiver import BaseReceiver
class StatsReceiver(BaseReceiver):
def __init__(self):
"""So far there is no frontend option for statistics analysis"""
super().__init__()
def options_from_front_end(self):
"""So far there is no frontend option for statistics analysis"""
raise NotImplementedError
|
// ... existing code ...
def options_from_front_end(self):
"""So far there is no frontend option for statistics analysis"""
raise NotImplementedError
// ... rest of the code ...
|
582460dcfeb85e2132705ba789eb88d1c67ae022
|
counting_sort.py
|
counting_sort.py
|
import random
import time
def counting_sort(array):
k = max(array)
counts = [0]*(k+1)
for x in array:
counts[x] += 1
total = 0
for i in range(0,k+1):
c = counts[i]
counts[i] = total
total = total + c
output = [0]*len(array)
for x in array:
output[counts[x]] = x
counts[x] = counts[x] + 1
return output
if __name__ == "__main__":
assert counting_sort([5,3,2,1]) == [1,2,3,5]
x = []
for i in range(0, 1000):
x.append(random.randint(0, 20))
assert counting_sort(x) == sorted(x)
for i in range(0, 10000000):
x.append(random.randint(0, 4000))
start = time.time()
counting_sort(x)
end = time.time()
print "counting sort took: ", end-start
start = time.time()
sorted(x)
end = time.time()
print "timsort took: ", end-start
|
import random
import time
def counting_sort(array):
k = max(array)
counts = [0]*(k+1)
for x in array:
counts[x] += 1
output = []
for x in xrange(k+1):
output += [x]*counts[x]
return output
if __name__ == "__main__":
assert counting_sort([5,3,2,1]) == [1,2,3,5]
x = []
for i in range(0, 1000):
x.append(random.randint(0, 20))
assert counting_sort(x) == sorted(x)
for i in range(0, 10000000):
x.append(random.randint(0, 4000))
start = time.time()
counting_sort(x)
end = time.time()
print "counting sort took: ", end-start
start = time.time()
sorted(x)
end = time.time()
print "timsort took: ", end-start
|
Use a much simpler (and faster) output building step.
|
Use a much simpler (and faster) output building step.
This implementation is much easeir to read, and is a lot clearer
about what's going on. It turns out that it's about 3 times faster
in python too!
|
Python
|
mit
|
samphippen/linear_sort
|
python
|
## Code Before:
import random
import time
def counting_sort(array):
k = max(array)
counts = [0]*(k+1)
for x in array:
counts[x] += 1
total = 0
for i in range(0,k+1):
c = counts[i]
counts[i] = total
total = total + c
output = [0]*len(array)
for x in array:
output[counts[x]] = x
counts[x] = counts[x] + 1
return output
if __name__ == "__main__":
assert counting_sort([5,3,2,1]) == [1,2,3,5]
x = []
for i in range(0, 1000):
x.append(random.randint(0, 20))
assert counting_sort(x) == sorted(x)
for i in range(0, 10000000):
x.append(random.randint(0, 4000))
start = time.time()
counting_sort(x)
end = time.time()
print "counting sort took: ", end-start
start = time.time()
sorted(x)
end = time.time()
print "timsort took: ", end-start
## Instruction:
Use a much simpler (and faster) output building step.
This implementation is much easeir to read, and is a lot clearer
about what's going on. It turns out that it's about 3 times faster
in python too!
## Code After:
import random
import time
def counting_sort(array):
k = max(array)
counts = [0]*(k+1)
for x in array:
counts[x] += 1
output = []
for x in xrange(k+1):
output += [x]*counts[x]
return output
if __name__ == "__main__":
assert counting_sort([5,3,2,1]) == [1,2,3,5]
x = []
for i in range(0, 1000):
x.append(random.randint(0, 20))
assert counting_sort(x) == sorted(x)
for i in range(0, 10000000):
x.append(random.randint(0, 4000))
start = time.time()
counting_sort(x)
end = time.time()
print "counting sort took: ", end-start
start = time.time()
sorted(x)
end = time.time()
print "timsort took: ", end-start
|
# ... existing code ...
for x in array:
counts[x] += 1
output = []
for x in xrange(k+1):
output += [x]*counts[x]
return output
# ... rest of the code ...
|
8665f94ecb2805dcb861e4d7e75629cd975f4a6c
|
setup.py
|
setup.py
|
import os
import sys
from glob import glob
sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
try:
from setuptools import setup, find_packages
except ImportError:
print "Ansible now needs setuptools in order to build. " \
"Install it using your package manager (usually python-setuptools) or via pip (pip install setuptools)."
sys.exit(1)
setup(name='ansible',
version=__version__,
description='Radically simple IT automation',
author=__author__,
author_email='[email protected]',
url='http://ansible.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6'],
package_dir={ 'ansible': 'lib/ansible' },
packages=find_packages('lib'),
package_data={
'': ['module_utils/*.ps1'],
},
scripts=[
'bin/ansible',
'bin/ansible-playbook',
'bin/ansible-pull',
'bin/ansible-doc',
'bin/ansible-galaxy',
'bin/ansible-vault',
],
data_files=[],
)
|
import os
import sys
from glob import glob
sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
try:
from setuptools import setup, find_packages
except ImportError:
print "Ansible now needs setuptools in order to build. " \
"Install it using your package manager (usually python-setuptools) or via pip (pip install setuptools)."
sys.exit(1)
setup(name='ansible',
version=__version__,
description='Radically simple IT automation',
author=__author__,
author_email='[email protected]',
url='http://ansible.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6'],
package_dir={ 'ansible': 'lib/ansible' },
packages=find_packages('lib'),
package_data={
'': ['module_utils/*.ps1', 'modules/core/windows/*.ps1'],
},
scripts=[
'bin/ansible',
'bin/ansible-playbook',
'bin/ansible-pull',
'bin/ansible-doc',
'bin/ansible-galaxy',
'bin/ansible-vault',
],
data_files=[],
)
|
Make sure Windows modules are installed.
|
Make sure Windows modules are installed.
|
Python
|
mit
|
thaim/ansible,thaim/ansible
|
python
|
## Code Before:
import os
import sys
from glob import glob
sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
try:
from setuptools import setup, find_packages
except ImportError:
print "Ansible now needs setuptools in order to build. " \
"Install it using your package manager (usually python-setuptools) or via pip (pip install setuptools)."
sys.exit(1)
setup(name='ansible',
version=__version__,
description='Radically simple IT automation',
author=__author__,
author_email='[email protected]',
url='http://ansible.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6'],
package_dir={ 'ansible': 'lib/ansible' },
packages=find_packages('lib'),
package_data={
'': ['module_utils/*.ps1'],
},
scripts=[
'bin/ansible',
'bin/ansible-playbook',
'bin/ansible-pull',
'bin/ansible-doc',
'bin/ansible-galaxy',
'bin/ansible-vault',
],
data_files=[],
)
## Instruction:
Make sure Windows modules are installed.
## Code After:
import os
import sys
from glob import glob
sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
try:
from setuptools import setup, find_packages
except ImportError:
print "Ansible now needs setuptools in order to build. " \
"Install it using your package manager (usually python-setuptools) or via pip (pip install setuptools)."
sys.exit(1)
setup(name='ansible',
version=__version__,
description='Radically simple IT automation',
author=__author__,
author_email='[email protected]',
url='http://ansible.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6'],
package_dir={ 'ansible': 'lib/ansible' },
packages=find_packages('lib'),
package_data={
'': ['module_utils/*.ps1', 'modules/core/windows/*.ps1'],
},
scripts=[
'bin/ansible',
'bin/ansible-playbook',
'bin/ansible-pull',
'bin/ansible-doc',
'bin/ansible-galaxy',
'bin/ansible-vault',
],
data_files=[],
)
|
# ... existing code ...
package_dir={ 'ansible': 'lib/ansible' },
packages=find_packages('lib'),
package_data={
'': ['module_utils/*.ps1', 'modules/core/windows/*.ps1'],
},
scripts=[
'bin/ansible',
# ... rest of the code ...
|
013277886a3c9f5d4ab99f11da6a447562fe9e46
|
benchexec/tools/cmaesfuzz.py
|
benchexec/tools/cmaesfuzz.py
|
import re
import benchexec.util as util
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool):
"""
Fuzzing with stochastic optimization guided by CMA-ES
Hynsung Kim, Gidon Ernst
https://github.com/lazygrey/fuzzing_with_cmaes
"""
REQUIRED_PATHS = [
"fuzzer",
"fuzzer.py",
"cma",
"verifiers_bytes",
"verifiers_real",
]
def executable(self):
return util.find_executable("fuzzer")
def version(self, executable):
return self._version_from_tool(executable)
def name(self):
return "CMA-ES Fuzz"
def get_value_from_output(self, lines, identifier):
for line in reversed(lines):
pattern = identifier
if pattern[-1] != ":":
pattern += ":"
match = re.match("^" + pattern + "([^(]*)", line)
if match and match.group(1):
return match.group(1).strip()
return None
|
import re
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Fuzzing with stochastic optimization guided by CMA-ES
Hynsung Kim, Gidon Ernst
https://github.com/lazygrey/fuzzing_with_cmaes
"""
REQUIRED_PATHS = [
"fuzzer",
"fuzzer.py",
"cma",
"verifiers_bytes",
"verifiers_real",
]
def executable(self, tool_locator):
return tool_locator.find_executable("fuzzer")
def version(self, executable):
return self._version_from_tool(executable)
def name(self):
return "CMA-ES Fuzz"
def get_value_from_output(self, output, identifier):
for line in reversed(output):
if line.startswith(identifier):
return line[len(identifier):]
return None
|
Update module to version 2
|
Update module to version 2
|
Python
|
apache-2.0
|
sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,dbeyer/benchexec,sosy-lab/benchexec,dbeyer/benchexec,ultimate-pa/benchexec
|
python
|
## Code Before:
import re
import benchexec.util as util
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool):
"""
Fuzzing with stochastic optimization guided by CMA-ES
Hynsung Kim, Gidon Ernst
https://github.com/lazygrey/fuzzing_with_cmaes
"""
REQUIRED_PATHS = [
"fuzzer",
"fuzzer.py",
"cma",
"verifiers_bytes",
"verifiers_real",
]
def executable(self):
return util.find_executable("fuzzer")
def version(self, executable):
return self._version_from_tool(executable)
def name(self):
return "CMA-ES Fuzz"
def get_value_from_output(self, lines, identifier):
for line in reversed(lines):
pattern = identifier
if pattern[-1] != ":":
pattern += ":"
match = re.match("^" + pattern + "([^(]*)", line)
if match and match.group(1):
return match.group(1).strip()
return None
## Instruction:
Update module to version 2
## Code After:
import re
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Fuzzing with stochastic optimization guided by CMA-ES
Hynsung Kim, Gidon Ernst
https://github.com/lazygrey/fuzzing_with_cmaes
"""
REQUIRED_PATHS = [
"fuzzer",
"fuzzer.py",
"cma",
"verifiers_bytes",
"verifiers_real",
]
def executable(self, tool_locator):
return tool_locator.find_executable("fuzzer")
def version(self, executable):
return self._version_from_tool(executable)
def name(self):
return "CMA-ES Fuzz"
def get_value_from_output(self, output, identifier):
for line in reversed(output):
if line.startswith(identifier):
return line[len(identifier):]
return None
|
# ... existing code ...
import re
import benchexec.tools.template
class Tool(benchexec.tools.template.BaseTool2):
"""
Fuzzing with stochastic optimization guided by CMA-ES
# ... modified code ...
"verifiers_real",
]
def executable(self, tool_locator):
return tool_locator.find_executable("fuzzer")
def version(self, executable):
return self._version_from_tool(executable)
...
def name(self):
return "CMA-ES Fuzz"
def get_value_from_output(self, output, identifier):
for line in reversed(output):
if line.startswith(identifier):
return line[len(identifier):]
return None
# ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.