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
cb6815c54d44ca62a8f9b1a06fc07dccecc4ebfa
src/main/scala/intellij/haskell/editor/HaskellFoldingSettings.java
src/main/scala/intellij/haskell/editor/HaskellFoldingSettings.java
package intellij.haskell.editor; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.NotNull; @State(name = "HaskellFoldingSettings", storages = { @Storage("editor.xml"), @Storage(value = "editor.codeinsight.xml", deprecated = true), }, reportStatistic = true) public class HaskellFoldingSettings implements PersistentStateComponent<HaskellFoldingSettings.State> { private final HaskellFoldingSettings.State myState = new State(); public static HaskellFoldingSettings getInstance() { return ServiceManager.getService(HaskellFoldingSettings.class); } public boolean isCollapseImports() { return myState.COLLAPSE_IMPORTS; } public boolean isCollapseFileHeader() { return myState.COLLAPSE_IMPORTS; } public boolean isCollapseTopLevelExpression() { return myState.COLLAPSE_TOP_LEVEL_EXPRESSION; } @Override @NotNull public State getState() { return myState; } @Override public void loadState(@NotNull State state) { XmlSerializerUtil.copyBean(state, myState); } public static final class State { public boolean COLLAPSE_IMPORTS = false; public boolean COLLAPSE_FILE_HEADER = false; public boolean COLLAPSE_TOP_LEVEL_EXPRESSION = false; } }
package intellij.haskell.editor; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.NotNull; @State(name = "HaskellFoldingSettings", storages = { @Storage("editor.xml"), @Storage(value = "editor.codeinsight.xml", deprecated = true), }, reportStatistic = true) public class HaskellFoldingSettings implements PersistentStateComponent<HaskellFoldingSettings.State> { private final HaskellFoldingSettings.State myState = new State(); public static HaskellFoldingSettings getInstance() { return ServiceManager.getService(HaskellFoldingSettings.class); } public boolean isCollapseImports() { return myState.COLLAPSE_IMPORTS; } public boolean isCollapseFileHeader() { return myState.COLLAPSE_FILE_HEADER; } public boolean isCollapseTopLevelExpression() { return myState.COLLAPSE_TOP_LEVEL_EXPRESSION; } @Override @NotNull public State getState() { return myState; } @Override public void loadState(@NotNull State state) { XmlSerializerUtil.copyBean(state, myState); } public static final class State { public boolean COLLAPSE_IMPORTS = false; public boolean COLLAPSE_FILE_HEADER = false; public boolean COLLAPSE_TOP_LEVEL_EXPRESSION = false; } }
Fix collapse file header setting
Fix collapse file header setting
Java
apache-2.0
rikvdkleij/intellij-haskell,rikvdkleij/intellij-haskell
java
## Code Before: package intellij.haskell.editor; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.NotNull; @State(name = "HaskellFoldingSettings", storages = { @Storage("editor.xml"), @Storage(value = "editor.codeinsight.xml", deprecated = true), }, reportStatistic = true) public class HaskellFoldingSettings implements PersistentStateComponent<HaskellFoldingSettings.State> { private final HaskellFoldingSettings.State myState = new State(); public static HaskellFoldingSettings getInstance() { return ServiceManager.getService(HaskellFoldingSettings.class); } public boolean isCollapseImports() { return myState.COLLAPSE_IMPORTS; } public boolean isCollapseFileHeader() { return myState.COLLAPSE_IMPORTS; } public boolean isCollapseTopLevelExpression() { return myState.COLLAPSE_TOP_LEVEL_EXPRESSION; } @Override @NotNull public State getState() { return myState; } @Override public void loadState(@NotNull State state) { XmlSerializerUtil.copyBean(state, myState); } public static final class State { public boolean COLLAPSE_IMPORTS = false; public boolean COLLAPSE_FILE_HEADER = false; public boolean COLLAPSE_TOP_LEVEL_EXPRESSION = false; } } ## Instruction: Fix collapse file header setting ## Code After: package intellij.haskell.editor; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.util.xmlb.XmlSerializerUtil; import org.jetbrains.annotations.NotNull; @State(name = "HaskellFoldingSettings", storages = { @Storage("editor.xml"), @Storage(value = "editor.codeinsight.xml", deprecated = true), }, reportStatistic = true) public class HaskellFoldingSettings implements PersistentStateComponent<HaskellFoldingSettings.State> { private final HaskellFoldingSettings.State myState = new State(); public static HaskellFoldingSettings getInstance() { return ServiceManager.getService(HaskellFoldingSettings.class); } public boolean isCollapseImports() { return myState.COLLAPSE_IMPORTS; } public boolean isCollapseFileHeader() { return myState.COLLAPSE_FILE_HEADER; } public boolean isCollapseTopLevelExpression() { return myState.COLLAPSE_TOP_LEVEL_EXPRESSION; } @Override @NotNull public State getState() { return myState; } @Override public void loadState(@NotNull State state) { XmlSerializerUtil.copyBean(state, myState); } public static final class State { public boolean COLLAPSE_IMPORTS = false; public boolean COLLAPSE_FILE_HEADER = false; public boolean COLLAPSE_TOP_LEVEL_EXPRESSION = false; } }
# ... existing code ... } public boolean isCollapseFileHeader() { return myState.COLLAPSE_FILE_HEADER; } public boolean isCollapseTopLevelExpression() { # ... rest of the code ...
c487dfc63e71abb0e11534c42591c216def5c433
ITDB/ITDB_Main/views.py
ITDB/ITDB_Main/views.py
from django.http import Http404 from django.http import HttpResponse from django.shortcuts import render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): try: theater = Theater.objects.get(pk=theater_id) except Theater.DoesNotExist: raise Http404("Theater does not exist") return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People")
from django.http import Http404 from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): theater = get_object_or_404(Theater, pk=theater_id) return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People")
Update theater view to use get_object_or_404 shortcut
Update theater view to use get_object_or_404 shortcut
Python
apache-2.0
Plaudenslager/ITDB,Plaudenslager/ITDB,Plaudenslager/ITDB
python
## Code Before: from django.http import Http404 from django.http import HttpResponse from django.shortcuts import render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): try: theater = Theater.objects.get(pk=theater_id) except Theater.DoesNotExist: raise Http404("Theater does not exist") return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People") ## Instruction: Update theater view to use get_object_or_404 shortcut ## Code After: from django.http import Http404 from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): theater = get_object_or_404(Theater, pk=theater_id) return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People")
# ... existing code ... from django.http import Http404 from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.template import RequestContext, loader from .models import Theater # ... modified code ... return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): theater = get_object_or_404(Theater, pk=theater_id) return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # ... rest of the code ...
3dc06581d07a204a3044e3a78deb84950a6ebf74
mtp_transaction_uploader/api_client.py
mtp_transaction_uploader/api_client.py
from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient from requests_oauthlib import OAuth2Session import slumber from . import settings REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/') def get_authenticated_connection(): """ Returns: an authenticated slumber connection """ session = OAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, client_id=settings.API_CLIENT_ID, client_secret=settings.API_CLIENT_SECRET ) return slumber.API( base_url=settings.API_URL, session=session )
from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient from requests.auth import HTTPBasicAuth from requests_oauthlib import OAuth2Session import slumber from . import settings REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/') def get_authenticated_connection(): """ Returns: an authenticated slumber connection """ session = OAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, auth=HTTPBasicAuth(settings.API_CLIENT_ID, settings.API_CLIENT_SECRET) ) return slumber.API( base_url=settings.API_URL, session=session )
Use HTTPBasicAuth when connecting to the API
Use HTTPBasicAuth when connecting to the API
Python
mit
ministryofjustice/money-to-prisoners-transaction-uploader
python
## Code Before: from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient from requests_oauthlib import OAuth2Session import slumber from . import settings REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/') def get_authenticated_connection(): """ Returns: an authenticated slumber connection """ session = OAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, client_id=settings.API_CLIENT_ID, client_secret=settings.API_CLIENT_SECRET ) return slumber.API( base_url=settings.API_URL, session=session ) ## Instruction: Use HTTPBasicAuth when connecting to the API ## Code After: from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient from requests.auth import HTTPBasicAuth from requests_oauthlib import OAuth2Session import slumber from . import settings REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/') def get_authenticated_connection(): """ Returns: an authenticated slumber connection """ session = OAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, auth=HTTPBasicAuth(settings.API_CLIENT_ID, settings.API_CLIENT_SECRET) ) return slumber.API( base_url=settings.API_URL, session=session )
// ... existing code ... from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient from requests.auth import HTTPBasicAuth from requests_oauthlib import OAuth2Session import slumber // ... modified code ... token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, auth=HTTPBasicAuth(settings.API_CLIENT_ID, settings.API_CLIENT_SECRET) ) return slumber.API( // ... rest of the code ...
9d972bfa792c08d4f3ce6a6b7cfd9877f801b5e3
setup.py
setup.py
from setuptools import setup setup( name='screenplain', version='0.9.0', description='Convert text file to viewable screenplay.', author='Martin Vilcans', author_email='[email protected]', url='http://www.screenplain.com/', project_urls={ 'Web Page': 'http://www.screenplain.com/', 'Source': 'https://github.com/vilcans/screenplain', }, license='MIT', install_requires=[ ], extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ], classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], )
from setuptools import setup # read the contents of your README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='screenplain', version='0.9.0', description='Convert text file to viewable screenplay.', long_description=long_description, long_description_content_type='text/markdown', author='Martin Vilcans', author_email='[email protected]', url='http://www.screenplain.com/', project_urls={ 'Web Page': 'http://www.screenplain.com/', 'Source': 'https://github.com/vilcans/screenplain', }, license='MIT', install_requires=[ ], extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ], classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], )
Use content or README.md as long_description
Use content or README.md as long_description
Python
mit
vilcans/screenplain,vilcans/screenplain,vilcans/screenplain
python
## Code Before: from setuptools import setup setup( name='screenplain', version='0.9.0', description='Convert text file to viewable screenplay.', author='Martin Vilcans', author_email='[email protected]', url='http://www.screenplain.com/', project_urls={ 'Web Page': 'http://www.screenplain.com/', 'Source': 'https://github.com/vilcans/screenplain', }, license='MIT', install_requires=[ ], extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ], classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], ) ## Instruction: Use content or README.md as long_description ## Code After: from setuptools import setup # read the contents of your README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='screenplain', version='0.9.0', description='Convert text file to viewable screenplay.', long_description=long_description, long_description_content_type='text/markdown', author='Martin Vilcans', author_email='[email protected]', url='http://www.screenplain.com/', project_urls={ 'Web Page': 'http://www.screenplain.com/', 'Source': 'https://github.com/vilcans/screenplain', }, license='MIT', install_requires=[ ], extras_require={ 'PDF': 'reportlab' }, packages=[ 'screenplain', 'screenplain.export', 'screenplain.parsers', ], package_data={ 'screenplain.export': ['default.css'] }, scripts=[ 'bin/screenplain' ], classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], )
... from setuptools import setup # read the contents of your README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='screenplain', version='0.9.0', description='Convert text file to viewable screenplay.', long_description=long_description, long_description_content_type='text/markdown', author='Martin Vilcans', author_email='[email protected]', url='http://www.screenplain.com/', ...
3b02f44e0257811bec3f83905c087fc461a5c368
src/storage/neo4j/src/main/java/org/geogit/storage/neo4j/Neo4JModule.java
src/storage/neo4j/src/main/java/org/geogit/storage/neo4j/Neo4JModule.java
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.storage.neo4j; import org.geogit.storage.GraphDatabase; import com.google.inject.AbstractModule; public class Neo4JModule extends AbstractModule { @Override protected void configure() { bind(GraphDatabase.class).to(Neo4JGraphDatabase.class); } }
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.storage.neo4j; import org.geogit.storage.GraphDatabase; import com.google.inject.AbstractModule; import com.google.inject.Scopes; public class Neo4JModule extends AbstractModule { @Override protected void configure() { bind(GraphDatabase.class).to(Neo4JGraphDatabase.class).in(Scopes.SINGLETON); } }
Use Singleton scope for Neo4JGraphDatabase
Use Singleton scope for Neo4JGraphDatabase Fixes #493
Java
bsd-3-clause
markles/GeoGit,boundlessgeo/GeoGig,boundlessgeo/GeoGig,markles/GeoGit,markles/GeoGit,markles/GeoGit,annacarol/GeoGig,markles/GeoGit,boundlessgeo/GeoGig,annacarol/GeoGig,annacarol/GeoGig
java
## Code Before: /* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.storage.neo4j; import org.geogit.storage.GraphDatabase; import com.google.inject.AbstractModule; public class Neo4JModule extends AbstractModule { @Override protected void configure() { bind(GraphDatabase.class).to(Neo4JGraphDatabase.class); } } ## Instruction: Use Singleton scope for Neo4JGraphDatabase Fixes #493 ## Code After: /* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.storage.neo4j; import org.geogit.storage.GraphDatabase; import com.google.inject.AbstractModule; import com.google.inject.Scopes; public class Neo4JModule extends AbstractModule { @Override protected void configure() { bind(GraphDatabase.class).to(Neo4JGraphDatabase.class).in(Scopes.SINGLETON); } }
// ... existing code ... import org.geogit.storage.GraphDatabase; import com.google.inject.AbstractModule; import com.google.inject.Scopes; public class Neo4JModule extends AbstractModule { @Override protected void configure() { bind(GraphDatabase.class).to(Neo4JGraphDatabase.class).in(Scopes.SINGLETON); } } // ... rest of the code ...
b65de0829d2c9bd47c89862f5991e4915dee04ad
parfait-core/src/main/java/com/custardsource/parfait/timing/ThreadMetricSuite.java
parfait-core/src/main/java/com/custardsource/parfait/timing/ThreadMetricSuite.java
package com.custardsource.parfait.timing; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ThreadMetricSuite { private final List<ThreadMetric> metrics = new ArrayList<ThreadMetric>(StandardThreadMetrics .defaults()); public final void addMetric(ThreadMetric metric) { metrics.add(metric); } public final List<ThreadMetric> metrics() { return Collections.unmodifiableList(metrics); } }
package com.custardsource.parfait.timing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class ThreadMetricSuite { private final List<ThreadMetric> metrics = new ArrayList<ThreadMetric>(StandardThreadMetrics .defaults()); public final void addMetric(ThreadMetric metric) { metrics.add(metric); } public final void addAllMetrics(Collection<ThreadMetric> metrics) { metrics.addAll(metrics); } public final List<ThreadMetric> metrics() { return Collections.unmodifiableList(metrics); } }
Add useful addAll() metric to the suite
Add useful addAll() metric to the suite
Java
apache-2.0
akshayahn/parfait,performancecopilot/parfait,timols/parfait,performancecopilot/parfait
java
## Code Before: package com.custardsource.parfait.timing; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ThreadMetricSuite { private final List<ThreadMetric> metrics = new ArrayList<ThreadMetric>(StandardThreadMetrics .defaults()); public final void addMetric(ThreadMetric metric) { metrics.add(metric); } public final List<ThreadMetric> metrics() { return Collections.unmodifiableList(metrics); } } ## Instruction: Add useful addAll() metric to the suite ## Code After: package com.custardsource.parfait.timing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class ThreadMetricSuite { private final List<ThreadMetric> metrics = new ArrayList<ThreadMetric>(StandardThreadMetrics .defaults()); public final void addMetric(ThreadMetric metric) { metrics.add(metric); } public final void addAllMetrics(Collection<ThreadMetric> metrics) { metrics.addAll(metrics); } public final List<ThreadMetric> metrics() { return Collections.unmodifiableList(metrics); } }
... package com.custardsource.parfait.timing; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; ... public final void addMetric(ThreadMetric metric) { metrics.add(metric); } public final void addAllMetrics(Collection<ThreadMetric> metrics) { metrics.addAll(metrics); } public final List<ThreadMetric> metrics() { return Collections.unmodifiableList(metrics); ...
ed7308df6fc324581482d7508394a34a35cbf65c
xorshift/__init__.py
xorshift/__init__.py
from operator import mul import xorshift.xorgen def _compute_n_elements(shape): if shape is None: shape = (1,) try: nelts = reduce(mul, shape) except TypeError: nelts = int(shape) shape = (shape, ) return nelts, shape class _Generator(object): def uniform(self, low=0.0, high=1.0, size=None): nelts, size = _compute_n_elements(size) rvs = self.rng.uniform(nelts) if (high - low) != 1.0: rvs *= (high - low) if low != 0.0: rvs += low return rvs.reshape(size) def binomial(self, N, p, size=None): nelts, size = _compute_n_elements(size) return self.rng.binomial(N, p, nelts).reshape(size) class Xoroshiro(_Generator): def __init__(self, seed=None): self.rng = xorgen.Xoroshiro(seed) class Xorshift128plus(_Generator): def __init__(self, seed=None): self.rng = xorgen.Xorshift128plus(seed) __all__ = [Xoroshiro, Xorshift128plus]
from operator import mul import xorshift.xorgen def _compute_n_elements(shape): if shape is None: shape = (1,) try: nelts = reduce(mul, shape) except TypeError: nelts = int(shape) shape = (shape, ) return nelts, shape class _Generator(object): def uniform(self, low=0.0, high=1.0, size=None): nelts, size = _compute_n_elements(size) rvs = self.rng.uniform(nelts) if (high - low) != 1.0: rvs *= (high - low) if low != 0.0: rvs += low rvs = rvs.reshape(size) if self.copy: return np.copy(rvs) else: return rvs def binomial(self, N, p, size=None, copy=False): nelts, size = _compute_n_elements(size) rvs = self.rng.binomial(N, p, nelts).reshape(size) if self.copy: return np.copy(rvs) else: return rvs class Xoroshiro(_Generator): def __init__(self, seed=None, copy=True): self.copy = copy self.rng = xorgen.Xoroshiro(seed) class Xorshift128plus(_Generator): def __init__(self, seed=None, copy=True): self.copy = copy self.rng = xorgen.Xorshift128plus(seed) __all__ = [Xoroshiro, Xorshift128plus]
Add optional copy on return
Add optional copy on return
Python
mit
ihaque/xorshift,ihaque/xorshift
python
## Code Before: from operator import mul import xorshift.xorgen def _compute_n_elements(shape): if shape is None: shape = (1,) try: nelts = reduce(mul, shape) except TypeError: nelts = int(shape) shape = (shape, ) return nelts, shape class _Generator(object): def uniform(self, low=0.0, high=1.0, size=None): nelts, size = _compute_n_elements(size) rvs = self.rng.uniform(nelts) if (high - low) != 1.0: rvs *= (high - low) if low != 0.0: rvs += low return rvs.reshape(size) def binomial(self, N, p, size=None): nelts, size = _compute_n_elements(size) return self.rng.binomial(N, p, nelts).reshape(size) class Xoroshiro(_Generator): def __init__(self, seed=None): self.rng = xorgen.Xoroshiro(seed) class Xorshift128plus(_Generator): def __init__(self, seed=None): self.rng = xorgen.Xorshift128plus(seed) __all__ = [Xoroshiro, Xorshift128plus] ## Instruction: Add optional copy on return ## Code After: from operator import mul import xorshift.xorgen def _compute_n_elements(shape): if shape is None: shape = (1,) try: nelts = reduce(mul, shape) except TypeError: nelts = int(shape) shape = (shape, ) return nelts, shape class _Generator(object): def uniform(self, low=0.0, high=1.0, size=None): nelts, size = _compute_n_elements(size) rvs = self.rng.uniform(nelts) if (high - low) != 1.0: rvs *= (high - low) if low != 0.0: rvs += low rvs = rvs.reshape(size) if self.copy: return np.copy(rvs) else: return rvs def binomial(self, N, p, size=None, copy=False): nelts, size = _compute_n_elements(size) rvs = self.rng.binomial(N, p, nelts).reshape(size) if self.copy: return np.copy(rvs) else: return rvs class Xoroshiro(_Generator): def __init__(self, seed=None, copy=True): self.copy = copy self.rng = xorgen.Xoroshiro(seed) class Xorshift128plus(_Generator): def __init__(self, seed=None, copy=True): self.copy = copy self.rng = xorgen.Xorshift128plus(seed) __all__ = [Xoroshiro, Xorshift128plus]
# ... existing code ... if low != 0.0: rvs += low rvs = rvs.reshape(size) if self.copy: return np.copy(rvs) else: return rvs def binomial(self, N, p, size=None, copy=False): nelts, size = _compute_n_elements(size) rvs = self.rng.binomial(N, p, nelts).reshape(size) if self.copy: return np.copy(rvs) else: return rvs class Xoroshiro(_Generator): def __init__(self, seed=None, copy=True): self.copy = copy self.rng = xorgen.Xoroshiro(seed) class Xorshift128plus(_Generator): def __init__(self, seed=None, copy=True): self.copy = copy self.rng = xorgen.Xorshift128plus(seed) # ... rest of the code ...
e647731ecd2f7c3d68744137e298143529962693
setup.py
setup.py
from distutils.core import setup setup(name='Splango', version='0.1', description='Split (A/B) testing library for Django', author='Shimon Rura', author_email='[email protected]', url='http://github.com/shimon/Splango', packages=['splango','splango.templatetags'], )
from distutils.core import setup setup(name='Splango', version='0.1', description='Split (A/B) testing library for Django', author='Shimon Rura', author_email='[email protected]', url='http://github.com/shimon/Splango', packages=['splango','splango.templatetags'], package_data={'splango': ['templates/*.html', 'templates/*/*.html']} )
Make sure templates get included
Make sure templates get included
Python
mit
shimon/Splango
python
## Code Before: from distutils.core import setup setup(name='Splango', version='0.1', description='Split (A/B) testing library for Django', author='Shimon Rura', author_email='[email protected]', url='http://github.com/shimon/Splango', packages=['splango','splango.templatetags'], ) ## Instruction: Make sure templates get included ## Code After: from distutils.core import setup setup(name='Splango', version='0.1', description='Split (A/B) testing library for Django', author='Shimon Rura', author_email='[email protected]', url='http://github.com/shimon/Splango', packages=['splango','splango.templatetags'], package_data={'splango': ['templates/*.html', 'templates/*/*.html']} )
# ... existing code ... author_email='[email protected]', url='http://github.com/shimon/Splango', packages=['splango','splango.templatetags'], package_data={'splango': ['templates/*.html', 'templates/*/*.html']} ) # ... rest of the code ...
6236798a3fce3c4bdbd8ce340e20db16cd67e03a
ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java
ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.config; /** * Hi there, traveller! This configuration class is not meant to be used by end-users of RN. It * contains mainly flags for features that are either under active development and not ready for * public consumption, or for use in experiments. * * These values are safe defaults and should not require manual changes. */ public class ReactFeatureFlags { /** * Whether we should load a specific view manager immediately or when it is accessed by JS */ public static boolean lazilyLoadViewManagers = false; /** * Reduce the number of Java-JS interops while accessing native arrays */ public static boolean useArrayNativeAccessor = false; /** * Reduce the number of Java-JS interops while accessing native maps */ public static boolean useMapNativeAccessor = false; /** * Should this application use TurboModules. If yes, then any module that inherits * {@link com.facebook.react.turbomodule.core.interfaces.TurboModule} will NOT be passed in to * C++ CatalystInstanceImpl */ public static boolean useTurboModules = false; /** * Log tags of when a view deleted on the native side * {@link com.facebook.react.uimanager.NativeViewHierarchyManager dropView} */ public static boolean logDroppedViews = false; }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.config; /** * Hi there, traveller! This configuration class is not meant to be used by end-users of RN. It * contains mainly flags for features that are either under active development and not ready for * public consumption, or for use in experiments. * * These values are safe defaults and should not require manual changes. */ public class ReactFeatureFlags { /** * Whether we should load a specific view manager immediately or when it is accessed by JS */ public static boolean lazilyLoadViewManagers = false; /** * Reduce the number of Java-JS interops while accessing native arrays */ public static boolean useArrayNativeAccessor = false; /** * Reduce the number of Java-JS interops while accessing native maps */ public static boolean useMapNativeAccessor = false; /** * Should this application use TurboModules. If yes, then any module that inherits * {@link com.facebook.react.turbomodule.core.interfaces.TurboModule} will NOT be passed in to * C++ CatalystInstanceImpl */ public static boolean useTurboModules = false; /** * Log tags of when a view deleted on the native side * {@link com.facebook.react.uimanager.NativeViewHierarchyManager dropView} */ public static boolean logDroppedViews = false; /* * This feature flag enables extra logging on ReactWebViews. * Default value is false. */ public static boolean enableExtraWebViewLogs = false; }
Create feature flag to log extra data in ReactWebView
Create feature flag to log extra data in ReactWebView Summary: This diff creates a new react feature flag to enable extra logging on React Web Views Reviewed By: RSNara Differential Revision: D15729871 fbshipit-source-id: 931d4a1b022c6a405228bf896b50ecc7a44478d1
Java
bsd-3-clause
hammerandchisel/react-native,exponentjs/react-native,myntra/react-native,javache/react-native,hoangpham95/react-native,facebook/react-native,myntra/react-native,janicduplessis/react-native,hoangpham95/react-native,exponent/react-native,hammerandchisel/react-native,hoangpham95/react-native,myntra/react-native,exponent/react-native,hoangpham95/react-native,janicduplessis/react-native,hammerandchisel/react-native,myntra/react-native,javache/react-native,janicduplessis/react-native,hoangpham95/react-native,myntra/react-native,javache/react-native,facebook/react-native,exponentjs/react-native,hammerandchisel/react-native,arthuralee/react-native,janicduplessis/react-native,javache/react-native,exponent/react-native,pandiaraj44/react-native,exponentjs/react-native,exponent/react-native,exponentjs/react-native,pandiaraj44/react-native,javache/react-native,janicduplessis/react-native,janicduplessis/react-native,exponentjs/react-native,facebook/react-native,facebook/react-native,javache/react-native,arthuralee/react-native,myntra/react-native,exponent/react-native,arthuralee/react-native,javache/react-native,hammerandchisel/react-native,facebook/react-native,exponentjs/react-native,exponent/react-native,pandiaraj44/react-native,hammerandchisel/react-native,exponent/react-native,facebook/react-native,janicduplessis/react-native,exponent/react-native,pandiaraj44/react-native,hoangpham95/react-native,facebook/react-native,pandiaraj44/react-native,hoangpham95/react-native,janicduplessis/react-native,facebook/react-native,myntra/react-native,hoangpham95/react-native,javache/react-native,exponentjs/react-native,myntra/react-native,facebook/react-native,pandiaraj44/react-native,pandiaraj44/react-native,arthuralee/react-native,myntra/react-native,pandiaraj44/react-native,hammerandchisel/react-native,arthuralee/react-native,hammerandchisel/react-native,javache/react-native,exponentjs/react-native
java
## Code Before: /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.config; /** * Hi there, traveller! This configuration class is not meant to be used by end-users of RN. It * contains mainly flags for features that are either under active development and not ready for * public consumption, or for use in experiments. * * These values are safe defaults and should not require manual changes. */ public class ReactFeatureFlags { /** * Whether we should load a specific view manager immediately or when it is accessed by JS */ public static boolean lazilyLoadViewManagers = false; /** * Reduce the number of Java-JS interops while accessing native arrays */ public static boolean useArrayNativeAccessor = false; /** * Reduce the number of Java-JS interops while accessing native maps */ public static boolean useMapNativeAccessor = false; /** * Should this application use TurboModules. If yes, then any module that inherits * {@link com.facebook.react.turbomodule.core.interfaces.TurboModule} will NOT be passed in to * C++ CatalystInstanceImpl */ public static boolean useTurboModules = false; /** * Log tags of when a view deleted on the native side * {@link com.facebook.react.uimanager.NativeViewHierarchyManager dropView} */ public static boolean logDroppedViews = false; } ## Instruction: Create feature flag to log extra data in ReactWebView Summary: This diff creates a new react feature flag to enable extra logging on React Web Views Reviewed By: RSNara Differential Revision: D15729871 fbshipit-source-id: 931d4a1b022c6a405228bf896b50ecc7a44478d1 ## Code After: /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.config; /** * Hi there, traveller! This configuration class is not meant to be used by end-users of RN. It * contains mainly flags for features that are either under active development and not ready for * public consumption, or for use in experiments. * * These values are safe defaults and should not require manual changes. */ public class ReactFeatureFlags { /** * Whether we should load a specific view manager immediately or when it is accessed by JS */ public static boolean lazilyLoadViewManagers = false; /** * Reduce the number of Java-JS interops while accessing native arrays */ public static boolean useArrayNativeAccessor = false; /** * Reduce the number of Java-JS interops while accessing native maps */ public static boolean useMapNativeAccessor = false; /** * Should this application use TurboModules. If yes, then any module that inherits * {@link com.facebook.react.turbomodule.core.interfaces.TurboModule} will NOT be passed in to * C++ CatalystInstanceImpl */ public static boolean useTurboModules = false; /** * Log tags of when a view deleted on the native side * {@link com.facebook.react.uimanager.NativeViewHierarchyManager dropView} */ public static boolean logDroppedViews = false; /* * This feature flag enables extra logging on ReactWebViews. * Default value is false. */ public static boolean enableExtraWebViewLogs = false; }
... * {@link com.facebook.react.uimanager.NativeViewHierarchyManager dropView} */ public static boolean logDroppedViews = false; /* * This feature flag enables extra logging on ReactWebViews. * Default value is false. */ public static boolean enableExtraWebViewLogs = false; } ...
73f8cfaca98adad518db2f0b827bc9606004d9c2
OpERP/src/main/java/devopsdistilled/operp/client/items/controllers/CreateItemPaneController.java
OpERP/src/main/java/devopsdistilled/operp/client/items/controllers/CreateItemPaneController.java
package devopsdistilled.operp.client.items.controllers; import devopsdistilled.operp.client.abstracts.SubTaskPaneController; import devopsdistilled.operp.client.items.exceptions.ItemNameExistsException; import devopsdistilled.operp.client.items.exceptions.ProductBrandPairExistsException; import devopsdistilled.operp.server.data.entity.items.Item; public interface CreateItemPaneController extends SubTaskPaneController { void validate(Item item) throws ProductBrandPairExistsException, ItemNameExistsException; Item save(Item item); }
package devopsdistilled.operp.client.items.controllers; import devopsdistilled.operp.client.abstracts.SubTaskPaneController; import devopsdistilled.operp.client.items.exceptions.ItemNameExistsException; import devopsdistilled.operp.client.items.exceptions.NullFieldException; import devopsdistilled.operp.client.items.exceptions.ProductBrandPairExistsException; import devopsdistilled.operp.server.data.entity.items.Item; public interface CreateItemPaneController extends SubTaskPaneController { void validate(Item item) throws ProductBrandPairExistsException, ItemNameExistsException, NullFieldException; Item save(Item item); }
Add throws declaration for NullFieldException
Add throws declaration for NullFieldException OPEN - task 45: Creation of Item with null value for Product and Brand possible http://github.com/DevOpsDistilled/OpERP/issues/issue/45
Java
mit
njmube/OpERP,DevOpsDistilled/OpERP
java
## Code Before: package devopsdistilled.operp.client.items.controllers; import devopsdistilled.operp.client.abstracts.SubTaskPaneController; import devopsdistilled.operp.client.items.exceptions.ItemNameExistsException; import devopsdistilled.operp.client.items.exceptions.ProductBrandPairExistsException; import devopsdistilled.operp.server.data.entity.items.Item; public interface CreateItemPaneController extends SubTaskPaneController { void validate(Item item) throws ProductBrandPairExistsException, ItemNameExistsException; Item save(Item item); } ## Instruction: Add throws declaration for NullFieldException OPEN - task 45: Creation of Item with null value for Product and Brand possible http://github.com/DevOpsDistilled/OpERP/issues/issue/45 ## Code After: package devopsdistilled.operp.client.items.controllers; import devopsdistilled.operp.client.abstracts.SubTaskPaneController; import devopsdistilled.operp.client.items.exceptions.ItemNameExistsException; import devopsdistilled.operp.client.items.exceptions.NullFieldException; import devopsdistilled.operp.client.items.exceptions.ProductBrandPairExistsException; import devopsdistilled.operp.server.data.entity.items.Item; public interface CreateItemPaneController extends SubTaskPaneController { void validate(Item item) throws ProductBrandPairExistsException, ItemNameExistsException, NullFieldException; Item save(Item item); }
// ... existing code ... import devopsdistilled.operp.client.abstracts.SubTaskPaneController; import devopsdistilled.operp.client.items.exceptions.ItemNameExistsException; import devopsdistilled.operp.client.items.exceptions.NullFieldException; import devopsdistilled.operp.client.items.exceptions.ProductBrandPairExistsException; import devopsdistilled.operp.server.data.entity.items.Item; // ... modified code ... public interface CreateItemPaneController extends SubTaskPaneController { void validate(Item item) throws ProductBrandPairExistsException, ItemNameExistsException, NullFieldException; Item save(Item item); // ... rest of the code ...
6290b81234f92073262a3fa784ae4e94f16192a8
tests/test_autoconfig.py
tests/test_autoconfig.py
import os import pytest from mock import patch from decouple import AutoConfig def test_autoconfig_env(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'ENV' == config('KEY') def test_autoconfig_ini(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'ini', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'INI' == config('KEY') def test_autoconfig_none(): os.environ['KeyFallback'] = 'On' config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'none') with patch('os.path.exists', return_value=False): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback']
import os import pytest from mock import patch from decouple import AutoConfig def test_autoconfig_env(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'ENV' == config('KEY') def test_autoconfig_ini(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'ini', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'INI' == config('KEY') def test_autoconfig_none(): os.environ['KeyFallback'] = 'On' config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'none') with patch('os.path.exists', return_value=False): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback'] def test_autoconfig_exception(): os.environ['KeyFallback'] = 'On' config = AutoConfig() with patch('os.path.exists', side_effect=Exception('PermissionDenied')): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback']
Test we have access to envvar when we have no file
Test we have access to envvar when we have no file
Python
mit
henriquebastos/python-decouple,flaviohenriqu/python-decouple,mrkschan/python-decouple,henriquebastos/django-decouple,liukaijv/python-decouple
python
## Code Before: import os import pytest from mock import patch from decouple import AutoConfig def test_autoconfig_env(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'ENV' == config('KEY') def test_autoconfig_ini(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'ini', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'INI' == config('KEY') def test_autoconfig_none(): os.environ['KeyFallback'] = 'On' config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'none') with patch('os.path.exists', return_value=False): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback'] ## Instruction: Test we have access to envvar when we have no file ## Code After: import os import pytest from mock import patch from decouple import AutoConfig def test_autoconfig_env(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'env', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'ENV' == config('KEY') def test_autoconfig_ini(): config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'ini', 'project') with patch.object(config, '_caller_path', return_value=path): assert 'INI' == config('KEY') def test_autoconfig_none(): os.environ['KeyFallback'] = 'On' config = AutoConfig() path = os.path.join(os.path.dirname(__file__), 'autoconfig', 'none') with patch('os.path.exists', return_value=False): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback'] def test_autoconfig_exception(): os.environ['KeyFallback'] = 'On' config = AutoConfig() with patch('os.path.exists', side_effect=Exception('PermissionDenied')): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback']
... with patch('os.path.exists', return_value=False): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback'] def test_autoconfig_exception(): os.environ['KeyFallback'] = 'On' config = AutoConfig() with patch('os.path.exists', side_effect=Exception('PermissionDenied')): assert True == config('KeyFallback', cast=bool) del os.environ['KeyFallback'] ...
9495a43e0797d1a089df644663900957cadc3ac0
tests/agents_tests/test_iqn.py
tests/agents_tests/test_iqn.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 from builtins import * # NOQA standard_library.install_aliases() # NOQA import chainer.functions as F import chainer.links as L import basetest_dqn_like as base import chainerrl from chainerrl.agents import iqn class TestIQNOnDiscreteABC(base._TestDQNOnDiscreteABC): def make_q_func(self, env): obs_size = env.observation_space.low.size hidden_size = 64 return iqn.ImplicitQuantileQFunction( psi=chainerrl.links.Sequence( L.Linear(obs_size, hidden_size), F.relu, ), phi=iqn.CosineBasisLinearReLU(64, hidden_size), f=L.Linear(hidden_size, env.action_space.n), ) def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu): return iqn.IQN( q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer, replay_start_size=100, target_update_interval=100)
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library from builtins import * # NOQA standard_library.install_aliases() # NOQA import chainer.functions as F import chainer.links as L from chainer import testing import basetest_dqn_like as base import chainerrl from chainerrl.agents import iqn @testing.parameterize(*testing.product({ 'quantile_thresholds_N': [1, 5], 'quantile_thresholds_N_prime': [1, 7], })) class TestIQNOnDiscreteABC(base._TestDQNOnDiscreteABC): def make_q_func(self, env): obs_size = env.observation_space.low.size hidden_size = 64 return iqn.ImplicitQuantileQFunction( psi=chainerrl.links.Sequence( L.Linear(obs_size, hidden_size), F.relu, ), phi=iqn.CosineBasisLinearReLU(64, hidden_size), f=L.Linear(hidden_size, env.action_space.n), ) def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu): return iqn.IQN( q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer, replay_start_size=100, target_update_interval=100, quantile_thresholds_N=self.quantile_thresholds_N, quantile_thresholds_N_prime=self.quantile_thresholds_N_prime, )
Test multiple values of N and N_prime
Test multiple values of N and N_prime
Python
mit
toslunar/chainerrl,toslunar/chainerrl
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 from builtins import * # NOQA standard_library.install_aliases() # NOQA import chainer.functions as F import chainer.links as L import basetest_dqn_like as base import chainerrl from chainerrl.agents import iqn class TestIQNOnDiscreteABC(base._TestDQNOnDiscreteABC): def make_q_func(self, env): obs_size = env.observation_space.low.size hidden_size = 64 return iqn.ImplicitQuantileQFunction( psi=chainerrl.links.Sequence( L.Linear(obs_size, hidden_size), F.relu, ), phi=iqn.CosineBasisLinearReLU(64, hidden_size), f=L.Linear(hidden_size, env.action_space.n), ) def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu): return iqn.IQN( q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer, replay_start_size=100, target_update_interval=100) ## Instruction: Test multiple values of N and N_prime ## Code After: from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library from builtins import * # NOQA standard_library.install_aliases() # NOQA import chainer.functions as F import chainer.links as L from chainer import testing import basetest_dqn_like as base import chainerrl from chainerrl.agents import iqn @testing.parameterize(*testing.product({ 'quantile_thresholds_N': [1, 5], 'quantile_thresholds_N_prime': [1, 7], })) class TestIQNOnDiscreteABC(base._TestDQNOnDiscreteABC): def make_q_func(self, env): obs_size = env.observation_space.low.size hidden_size = 64 return iqn.ImplicitQuantileQFunction( psi=chainerrl.links.Sequence( L.Linear(obs_size, hidden_size), F.relu, ), phi=iqn.CosineBasisLinearReLU(64, hidden_size), f=L.Linear(hidden_size, env.action_space.n), ) def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu): return iqn.IQN( q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer, replay_start_size=100, target_update_interval=100, quantile_thresholds_N=self.quantile_thresholds_N, quantile_thresholds_N_prime=self.quantile_thresholds_N_prime, )
# ... existing code ... import chainer.functions as F import chainer.links as L from chainer import testing import basetest_dqn_like as base import chainerrl # ... modified code ... from chainerrl.agents import iqn @testing.parameterize(*testing.product({ 'quantile_thresholds_N': [1, 5], 'quantile_thresholds_N_prime': [1, 7], })) class TestIQNOnDiscreteABC(base._TestDQNOnDiscreteABC): def make_q_func(self, env): ... def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu): return iqn.IQN( q_func, opt, rbuf, gpu=gpu, gamma=0.9, explorer=explorer, replay_start_size=100, target_update_interval=100, quantile_thresholds_N=self.quantile_thresholds_N, quantile_thresholds_N_prime=self.quantile_thresholds_N_prime, ) # ... rest of the code ...
becc9ff7e1d260f9a4f47a36a0e6403e71f9f0b0
contentcuration/contentcuration/utils/messages.py
contentcuration/contentcuration/utils/messages.py
import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] locale_path = os.path.join(path, locale) return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale]
import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale]
Remove no longer needed local variable.
Remove no longer needed local variable.
Python
mit
DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation,DXCanas/content-curation
python
## Code Before: import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] locale_path = os.path.join(path, locale) return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale] ## Instruction: Remove no longer needed local variable. ## Code After: import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale]
... def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): ...
a5b57601da6e9b85eca18d61e3784addd1863fa4
i3pystatus/__init__.py
i3pystatus/__init__.py
from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp
from pkgutil import extend_path from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp __path__ = extend_path(__path__, __name__)
Make i3pystatus a namespace package
Make i3pystatus a namespace package
Python
mit
Arvedui/i3pystatus,schroeji/i3pystatus,opatut/i3pystatus,MaicoTimmerman/i3pystatus,eBrnd/i3pystatus,m45t3r/i3pystatus,teto/i3pystatus,drwahl/i3pystatus,Arvedui/i3pystatus,teto/i3pystatus,fmarchenko/i3pystatus,plumps/i3pystatus,paulollivier/i3pystatus,juliushaertl/i3pystatus,ismaelpuerto/i3pystatus,schroeji/i3pystatus,ncoop/i3pystatus,asmikhailov/i3pystatus,enkore/i3pystatus,drwahl/i3pystatus,claria/i3pystatus,ismaelpuerto/i3pystatus,richese/i3pystatus,onkelpit/i3pystatus,plumps/i3pystatus,claria/i3pystatus,yang-ling/i3pystatus,opatut/i3pystatus,MaicoTimmerman/i3pystatus,facetoe/i3pystatus,onkelpit/i3pystatus,eBrnd/i3pystatus,facetoe/i3pystatus,asmikhailov/i3pystatus,richese/i3pystatus,juliushaertl/i3pystatus,yang-ling/i3pystatus,fmarchenko/i3pystatus,m45t3r/i3pystatus,paulollivier/i3pystatus,enkore/i3pystatus,Elder-of-Ozone/i3pystatus,Elder-of-Ozone/i3pystatus,ncoop/i3pystatus
python
## Code Before: from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp ## Instruction: Make i3pystatus a namespace package ## Code After: from pkgutil import extend_path from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp __path__ = extend_path(__path__, __name__)
# ... existing code ... from pkgutil import extend_path from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp __path__ = extend_path(__path__, __name__) # ... rest of the code ...
4ffb58466820cfb2569cf4d4837c8e48caed2c17
seven23/api/permissions.py
seven23/api/permissions.py
from itertools import chain from rest_framework import permissions from django.utils import timezone from seven23 import settings class CanWriteAccount(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. # Instance must have an attribute named `owner`. return obj.account.id in list(chain( request.user.accounts.values_list('id', flat=True), request.user.guests.values_list('account__id', flat=True) )) class IsPaid(permissions.BasePermission): """ Check if user has a paid formula """ def has_permission(self, request, view): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if not settings.SAAS: return True if request.method in permissions.SAFE_METHODS: return True return request.user.profile.valid_until > timezone.now()
from itertools import chain from rest_framework import permissions from datetime import datetime from seven23 import settings class CanWriteAccount(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. # Instance must have an attribute named `owner`. return obj.account.id in list(chain( request.user.accounts.values_list('id', flat=True), request.user.guests.values_list('account__id', flat=True) )) class IsPaid(permissions.BasePermission): """ Check if user has a paid formula """ def has_permission(self, request, view): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if not settings.SAAS: return True if request.method in permissions.SAFE_METHODS: return True return request.user.profile.valid_until > datetime.today()
Fix issue with imezone on IsPaid Permission
Fix issue with imezone on IsPaid Permission
Python
mit
sebastienbarbier/723e,sebastienbarbier/723e_server,sebastienbarbier/723e_server,sebastienbarbier/723e
python
## Code Before: from itertools import chain from rest_framework import permissions from django.utils import timezone from seven23 import settings class CanWriteAccount(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. # Instance must have an attribute named `owner`. return obj.account.id in list(chain( request.user.accounts.values_list('id', flat=True), request.user.guests.values_list('account__id', flat=True) )) class IsPaid(permissions.BasePermission): """ Check if user has a paid formula """ def has_permission(self, request, view): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if not settings.SAAS: return True if request.method in permissions.SAFE_METHODS: return True return request.user.profile.valid_until > timezone.now() ## Instruction: Fix issue with imezone on IsPaid Permission ## Code After: from itertools import chain from rest_framework import permissions from datetime import datetime from seven23 import settings class CanWriteAccount(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. # Instance must have an attribute named `owner`. return obj.account.id in list(chain( request.user.accounts.values_list('id', flat=True), request.user.guests.values_list('account__id', flat=True) )) class IsPaid(permissions.BasePermission): """ Check if user has a paid formula """ def has_permission(self, request, view): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if not settings.SAAS: return True if request.method in permissions.SAFE_METHODS: return True return request.user.profile.valid_until > datetime.today()
... from itertools import chain from rest_framework import permissions from datetime import datetime from seven23 import settings class CanWriteAccount(permissions.BasePermission): ... if request.method in permissions.SAFE_METHODS: return True return request.user.profile.valid_until > datetime.today() ...
476754a381fe38a0bbe6e3c7892c59a6cfa47db1
openedx/features/job_board/models.py
openedx/features/job_board/models.py
from django.db import models from django_countries.fields import CountryField from model_utils.models import TimeStampedModel from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES class Job(TimeStampedModel): """ This model contains all the fields related to a job being posted on the job board. """ title = models.CharField(max_length=255) company = models.CharField(max_length=255) type = models.CharField(max_length=255, choices=JOB_TYPE_CHOICES) compensation = models.CharField(max_length=255, choices=JOB_COMPENSATION_CHOICES) hours = models.CharField(max_length=255, choices=JOB_HOURS_CHOICES) city = models.CharField(max_length=255) country = CountryField() description = models.TextField() function = models.TextField(blank=True, null=True) responsibilities = models.TextField(blank=True, null=True) website_link = models.URLField(max_length=255, blank=True, null=True) contact_email = models.EmailField(max_length=255) logo = models.ImageField(upload_to='job-board/uploaded-logos/', blank=True, null=True) @property def location(self): """Get the full location (city, country) of job.""" return '{city}, {country}'.format(city=self.city, country=self.country.name)
from django.db import models from django_countries.fields import CountryField from model_utils.models import TimeStampedModel from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES class Job(TimeStampedModel): """ This model contains all the fields related to a job being posted on the job board. """ title = models.CharField(max_length=255) company = models.CharField(max_length=255) type = models.CharField(max_length=255, choices=JOB_TYPE_CHOICES) compensation = models.CharField(max_length=255, choices=JOB_COMPENSATION_CHOICES) hours = models.CharField(max_length=255, choices=JOB_HOURS_CHOICES) city = models.CharField(max_length=255) country = CountryField() description = models.TextField() function = models.TextField(blank=True, null=True) responsibilities = models.TextField(blank=True, null=True) website_link = models.URLField(max_length=255, blank=True, null=True) contact_email = models.EmailField(max_length=255) logo = models.ImageField(upload_to='job-board/uploaded-logos/', blank=True, null=True) @property def location(self): """Get the full location (city, country) of job.""" return '{city}, {country}'.format(city=self.city, country=self.country.name.encode('utf-8'))
Add support for countries with accented characters
Add support for countries with accented characters
Python
agpl-3.0
philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform
python
## Code Before: from django.db import models from django_countries.fields import CountryField from model_utils.models import TimeStampedModel from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES class Job(TimeStampedModel): """ This model contains all the fields related to a job being posted on the job board. """ title = models.CharField(max_length=255) company = models.CharField(max_length=255) type = models.CharField(max_length=255, choices=JOB_TYPE_CHOICES) compensation = models.CharField(max_length=255, choices=JOB_COMPENSATION_CHOICES) hours = models.CharField(max_length=255, choices=JOB_HOURS_CHOICES) city = models.CharField(max_length=255) country = CountryField() description = models.TextField() function = models.TextField(blank=True, null=True) responsibilities = models.TextField(blank=True, null=True) website_link = models.URLField(max_length=255, blank=True, null=True) contact_email = models.EmailField(max_length=255) logo = models.ImageField(upload_to='job-board/uploaded-logos/', blank=True, null=True) @property def location(self): """Get the full location (city, country) of job.""" return '{city}, {country}'.format(city=self.city, country=self.country.name) ## Instruction: Add support for countries with accented characters ## Code After: from django.db import models from django_countries.fields import CountryField from model_utils.models import TimeStampedModel from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES class Job(TimeStampedModel): """ This model contains all the fields related to a job being posted on the job board. """ title = models.CharField(max_length=255) company = models.CharField(max_length=255) type = models.CharField(max_length=255, choices=JOB_TYPE_CHOICES) compensation = models.CharField(max_length=255, choices=JOB_COMPENSATION_CHOICES) hours = models.CharField(max_length=255, choices=JOB_HOURS_CHOICES) city = models.CharField(max_length=255) country = CountryField() description = models.TextField() function = models.TextField(blank=True, null=True) responsibilities = models.TextField(blank=True, null=True) website_link = models.URLField(max_length=255, blank=True, null=True) contact_email = models.EmailField(max_length=255) logo = models.ImageField(upload_to='job-board/uploaded-logos/', blank=True, null=True) @property def location(self): """Get the full location (city, country) of job.""" return '{city}, {country}'.format(city=self.city, country=self.country.name.encode('utf-8'))
# ... existing code ... @property def location(self): """Get the full location (city, country) of job.""" return '{city}, {country}'.format(city=self.city, country=self.country.name.encode('utf-8')) # ... rest of the code ...
f3e611c9e373a0147be472cb7913f3604baf2a08
log.c
log.c
static bool flushAfterLog = false; void proxyLogSetFlush(bool enabled) { flushAfterLog = enabled; } void proxyLog(const char* format, ...) { va_list args; va_start(args, format); printTimeString(); printf(" "); vprintf(format, args); printf("\n"); if (flushAfterLog) { fflush(stdout); } va_end(args); }
static bool flushAfterLog = false; void proxyLogSetFlush(bool enabled) { flushAfterLog = enabled; } void proxyLog(const char* format, ...) { va_list args; va_start(args, format); printTimeString(); putchar(' '); vprintf(format, args); putchar('\n'); if (flushAfterLog) { fflush(stdout); } va_end(args); }
Use putchar instead of printf.
Use putchar instead of printf.
C
mit
aaronriekenberg/openbsd_cproxy,aaronriekenberg/openbsd_cproxy
c
## Code Before: static bool flushAfterLog = false; void proxyLogSetFlush(bool enabled) { flushAfterLog = enabled; } void proxyLog(const char* format, ...) { va_list args; va_start(args, format); printTimeString(); printf(" "); vprintf(format, args); printf("\n"); if (flushAfterLog) { fflush(stdout); } va_end(args); } ## Instruction: Use putchar instead of printf. ## Code After: static bool flushAfterLog = false; void proxyLogSetFlush(bool enabled) { flushAfterLog = enabled; } void proxyLog(const char* format, ...) { va_list args; va_start(args, format); printTimeString(); putchar(' '); vprintf(format, args); putchar('\n'); if (flushAfterLog) { fflush(stdout); } va_end(args); }
# ... existing code ... va_start(args, format); printTimeString(); putchar(' '); vprintf(format, args); putchar('\n'); if (flushAfterLog) { # ... rest of the code ...
0d2525de51edd99b821f32b3bfd962f3d673a6e1
Instanssi/admin_store/forms.py
Instanssi/admin_store/forms.py
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoreItemForm, self).__init__(*args, **kwargs) self.fields['event'].required = True self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tuote', 'event', 'name', 'description', 'price', 'max', 'available', 'max_per_order', 'delivery_type', 'imagefile_original', ButtonHolder( Submit('submit', u'Tallenna') ) ) ) class Meta: model = StoreItem exclude = ('imagefile_thumbnail',)
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoreItemForm, self).__init__(*args, **kwargs) self.fields['event'].required = True self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tuote', 'event', 'name', 'description', 'price', 'max', 'available', 'max_per_order', 'imagefile_original', ButtonHolder( Submit('submit', u'Tallenna') ) ) ) class Meta: model = StoreItem exclude = ('imagefile_thumbnail',)
Remove deprecated fields from form
admin_store: Remove deprecated fields from form
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
python
## Code Before: from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoreItemForm, self).__init__(*args, **kwargs) self.fields['event'].required = True self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tuote', 'event', 'name', 'description', 'price', 'max', 'available', 'max_per_order', 'delivery_type', 'imagefile_original', ButtonHolder( Submit('submit', u'Tallenna') ) ) ) class Meta: model = StoreItem exclude = ('imagefile_thumbnail',) ## Instruction: admin_store: Remove deprecated fields from form ## Code After: from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoreItemForm, self).__init__(*args, **kwargs) self.fields['event'].required = True self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Tuote', 'event', 'name', 'description', 'price', 'max', 'available', 'max_per_order', 'imagefile_original', ButtonHolder( Submit('submit', u'Tallenna') ) ) ) class Meta: model = StoreItem exclude = ('imagefile_thumbnail',)
... from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): ... 'max', 'available', 'max_per_order', 'imagefile_original', ButtonHolder( Submit('submit', u'Tallenna') ...
8694b119da494086b650c39a568b95ebe084e41d
src/main/java/pokefenn/totemic/ceremony/CeremonyRain.java
src/main/java/pokefenn/totemic/ceremony/CeremonyRain.java
package pokefenn.totemic.ceremony; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import pokefenn.totemic.api.ceremony.CeremonyEffectContext; import pokefenn.totemic.api.ceremony.CeremonyInstance; public class CeremonyRain extends CeremonyInstance { private final boolean doRain; public CeremonyRain(boolean doRain) { this.doRain = doRain; } @Override public void effect(Level level, BlockPos pos, CeremonyEffectContext context) { if(level.isRaining() != doRain) { level.getLevelData().setRaining(doRain); level.setRainLevel(doRain ? 1.0F : 0.0F); } } }
package pokefenn.totemic.ceremony; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import pokefenn.totemic.api.ceremony.CeremonyEffectContext; import pokefenn.totemic.api.ceremony.CeremonyInstance; public class CeremonyRain extends CeremonyInstance { private final boolean doRain; public CeremonyRain(boolean doRain) { this.doRain = doRain; } @Override public void effect(Level level, BlockPos pos, CeremonyEffectContext context) { if(level instanceof ServerLevel slevel && slevel.isRaining() != doRain) { slevel.setWeatherParameters( doRain ? 0 : 6000, //Clear weather time doRain ? 6000 : 0, //Rain time doRain, //raining false); //thundering } } }
Fix rain ceremony not working correctly
Fix rain ceremony not working correctly
Java
mit
TeamTotemic/Totemic
java
## Code Before: package pokefenn.totemic.ceremony; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import pokefenn.totemic.api.ceremony.CeremonyEffectContext; import pokefenn.totemic.api.ceremony.CeremonyInstance; public class CeremonyRain extends CeremonyInstance { private final boolean doRain; public CeremonyRain(boolean doRain) { this.doRain = doRain; } @Override public void effect(Level level, BlockPos pos, CeremonyEffectContext context) { if(level.isRaining() != doRain) { level.getLevelData().setRaining(doRain); level.setRainLevel(doRain ? 1.0F : 0.0F); } } } ## Instruction: Fix rain ceremony not working correctly ## Code After: package pokefenn.totemic.ceremony; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import pokefenn.totemic.api.ceremony.CeremonyEffectContext; import pokefenn.totemic.api.ceremony.CeremonyInstance; public class CeremonyRain extends CeremonyInstance { private final boolean doRain; public CeremonyRain(boolean doRain) { this.doRain = doRain; } @Override public void effect(Level level, BlockPos pos, CeremonyEffectContext context) { if(level instanceof ServerLevel slevel && slevel.isRaining() != doRain) { slevel.setWeatherParameters( doRain ? 0 : 6000, //Clear weather time doRain ? 6000 : 0, //Rain time doRain, //raining false); //thundering } } }
... package pokefenn.totemic.ceremony; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import pokefenn.totemic.api.ceremony.CeremonyEffectContext; import pokefenn.totemic.api.ceremony.CeremonyInstance; ... @Override public void effect(Level level, BlockPos pos, CeremonyEffectContext context) { if(level instanceof ServerLevel slevel && slevel.isRaining() != doRain) { slevel.setWeatherParameters( doRain ? 0 : 6000, //Clear weather time doRain ? 6000 : 0, //Rain time doRain, //raining false); //thundering } } } ...
9dce07895a773998469aeed8c1cfb8476d4264eb
application.py
application.py
import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) if __name__ == '__main__': manager.run()
import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) manager.add_command("runserver", Server(port=5001)) if __name__ == '__main__': manager.run()
Update to run on port 5001
Update to run on port 5001 For development we will want to run multiple apps, so they should each bind to a different port number.
Python
mit
RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api
python
## Code Before: import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) if __name__ == '__main__': manager.run() ## Instruction: Update to run on port 5001 For development we will want to run multiple apps, so they should each bind to a different port number. ## Code After: import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) manager.add_command("runserver", Server(port=5001)) if __name__ == '__main__': manager.run()
// ... existing code ... import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) manager.add_command("runserver", Server(port=5001)) if __name__ == '__main__': manager.run() // ... rest of the code ...
4a8684ed078fe00933bf1e4a957de3cb587f5fc7
xfire-core/src/main/org/codehaus/xfire/transport/AbstractChannel.java
xfire-core/src/main/org/codehaus/xfire/transport/AbstractChannel.java
package org.codehaus.xfire.transport; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.exchange.InMessage; public abstract class AbstractChannel implements Channel { private ChannelEndpoint receiver; private Transport transport; private String uri; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public void setEndpoint(ChannelEndpoint receiver) { this.receiver = receiver; } public ChannelEndpoint getReceiver() { return receiver; } public void receive(MessageContext context, InMessage message) { message.setChannel(this); getReceiver().onReceive(context, message); } public Transport getTransport() { return transport; } public void setTransport(Transport transport) { this.transport = transport; } }
package org.codehaus.xfire.transport; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.exchange.InMessage; public abstract class AbstractChannel implements Channel { private ChannelEndpoint receiver; private Transport transport; private String uri; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public void setEndpoint(ChannelEndpoint receiver) { this.receiver = receiver; } public ChannelEndpoint getReceiver() { return receiver; } public void receive(MessageContext context, InMessage message) { if (message.getChannel() == null) message.setChannel(this); getReceiver().onReceive(context, message); } public Transport getTransport() { return transport; } public void setTransport(Transport transport) { this.transport = transport; } }
Check to make sure the channel isn't set.
Check to make sure the channel isn't set. git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@611 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba
Java
mit
eduardodaluz/xfire,eduardodaluz/xfire
java
## Code Before: package org.codehaus.xfire.transport; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.exchange.InMessage; public abstract class AbstractChannel implements Channel { private ChannelEndpoint receiver; private Transport transport; private String uri; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public void setEndpoint(ChannelEndpoint receiver) { this.receiver = receiver; } public ChannelEndpoint getReceiver() { return receiver; } public void receive(MessageContext context, InMessage message) { message.setChannel(this); getReceiver().onReceive(context, message); } public Transport getTransport() { return transport; } public void setTransport(Transport transport) { this.transport = transport; } } ## Instruction: Check to make sure the channel isn't set. git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@611 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba ## Code After: package org.codehaus.xfire.transport; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.exchange.InMessage; public abstract class AbstractChannel implements Channel { private ChannelEndpoint receiver; private Transport transport; private String uri; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public void setEndpoint(ChannelEndpoint receiver) { this.receiver = receiver; } public ChannelEndpoint getReceiver() { return receiver; } public void receive(MessageContext context, InMessage message) { if (message.getChannel() == null) message.setChannel(this); getReceiver().onReceive(context, message); } public Transport getTransport() { return transport; } public void setTransport(Transport transport) { this.transport = transport; } }
... public void receive(MessageContext context, InMessage message) { if (message.getChannel() == null) message.setChannel(this); getReceiver().onReceive(context, message); } ...
39b6868042e95a5a412d3d3b9fa5f735e35ddb2c
umodbus/__init__.py
umodbus/__init__.py
from logging import getLogger try: from logging import NullHandler # For Python 2.7 compatibility. except ImportError: from logging import Handler class NullHandler(Handler): def emit(self, record): pass log = getLogger('uModbus') log.addHandler(NullHandler()) from .server import get_server # NOQA
from logging import getLogger, NullHandler log = getLogger('uModbus') log.addHandler(NullHandler()) from .server import get_server # NOQA
Remove another piece of unreachable code.
Remove another piece of unreachable code.
Python
mpl-2.0
AdvancedClimateSystems/python-modbus,AdvancedClimateSystems/uModbus
python
## Code Before: from logging import getLogger try: from logging import NullHandler # For Python 2.7 compatibility. except ImportError: from logging import Handler class NullHandler(Handler): def emit(self, record): pass log = getLogger('uModbus') log.addHandler(NullHandler()) from .server import get_server # NOQA ## Instruction: Remove another piece of unreachable code. ## Code After: from logging import getLogger, NullHandler log = getLogger('uModbus') log.addHandler(NullHandler()) from .server import get_server # NOQA
# ... existing code ... from logging import getLogger, NullHandler log = getLogger('uModbus') log.addHandler(NullHandler()) # ... rest of the code ...
046ab8fc0f60b15ccdafcbb549c7de894ecd064e
putio_cli/commands/base.py
putio_cli/commands/base.py
"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
Remove run method (useless) in Base class
Remove run method (useless) in Base class
Python
mit
jlejeune/putio-cli
python
## Code Before: """The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') ## Instruction: Remove run method (useless) in Base class ## Code After: """The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
# ... existing code ... def __init__(self, options): self.options = options class BaseClient(Base): # ... rest of the code ...
46c33ca68c1124fb06c4ba62306cb00ba61d7e5c
tests/__init__.py
tests/__init__.py
from flexmock import flexmock from flask.ext.storage import MockStorage from flask_uploads import init class TestCase(object): added_objects = [] committed_objects = [] created_objects = [] deleted_objects = [] def setup_method(self, method, resizer=None): init(db_mock, MockStorage, resizer) self.db = db_mock self.Storage = MockStorage self.storage = MockStorage() self.resizer = resizer def teardown_method(self, method): # Empty the stacks. TestCase.added_objects[:] = [] TestCase.committed_objects[:] = [] TestCase.created_objects[:] = [] TestCase.deleted_objects[:] = [] class MockModel(object): def __init__(self, **kw): TestCase.created_objects.append(self) for key, val in kw.iteritems(): setattr(self, key, val) db_mock = flexmock( Column=lambda *a, **kw: ('column', a, kw), Integer=('integer', [], {}), Unicode=lambda *a, **kw: ('unicode', a, kw), Model=MockModel, session=flexmock( add=TestCase.added_objects.append, commit=lambda: TestCase.committed_objects.extend( TestCase.added_objects + TestCase.deleted_objects ), delete=TestCase.deleted_objects.append, ), )
from flexmock import flexmock from flask.ext.storage import MockStorage from flask_uploads import init class TestCase(object): added_objects = [] committed_objects = [] created_objects = [] deleted_objects = [] def setup_method(self, method, resizer=None): init(db_mock, MockStorage, resizer) self.db = db_mock self.Storage = MockStorage self.storage = MockStorage() self.resizer = resizer def teardown_method(self, method): # Empty the stacks. TestCase.added_objects[:] = [] TestCase.committed_objects[:] = [] TestCase.created_objects[:] = [] TestCase.deleted_objects[:] = [] class MockModel(object): def __init__(self, **kw): TestCase.created_objects.append(self) for key, val in kw.iteritems(): setattr(self, key, val) db_mock = flexmock( Column=lambda *a, **kw: ('column', a, kw), Integer=('integer', [], {}), Unicode=lambda *a, **kw: ('unicode', a, kw), Model=MockModel, metadata=flexmock(tables={}), session=flexmock( add=TestCase.added_objects.append, commit=lambda: TestCase.committed_objects.extend( TestCase.added_objects + TestCase.deleted_objects ), delete=TestCase.deleted_objects.append, ), )
Add metadata.tables to mock db.
Add metadata.tables to mock db.
Python
mit
FelixLoether/flask-uploads,FelixLoether/flask-image-upload-thing
python
## Code Before: from flexmock import flexmock from flask.ext.storage import MockStorage from flask_uploads import init class TestCase(object): added_objects = [] committed_objects = [] created_objects = [] deleted_objects = [] def setup_method(self, method, resizer=None): init(db_mock, MockStorage, resizer) self.db = db_mock self.Storage = MockStorage self.storage = MockStorage() self.resizer = resizer def teardown_method(self, method): # Empty the stacks. TestCase.added_objects[:] = [] TestCase.committed_objects[:] = [] TestCase.created_objects[:] = [] TestCase.deleted_objects[:] = [] class MockModel(object): def __init__(self, **kw): TestCase.created_objects.append(self) for key, val in kw.iteritems(): setattr(self, key, val) db_mock = flexmock( Column=lambda *a, **kw: ('column', a, kw), Integer=('integer', [], {}), Unicode=lambda *a, **kw: ('unicode', a, kw), Model=MockModel, session=flexmock( add=TestCase.added_objects.append, commit=lambda: TestCase.committed_objects.extend( TestCase.added_objects + TestCase.deleted_objects ), delete=TestCase.deleted_objects.append, ), ) ## Instruction: Add metadata.tables to mock db. ## Code After: from flexmock import flexmock from flask.ext.storage import MockStorage from flask_uploads import init class TestCase(object): added_objects = [] committed_objects = [] created_objects = [] deleted_objects = [] def setup_method(self, method, resizer=None): init(db_mock, MockStorage, resizer) self.db = db_mock self.Storage = MockStorage self.storage = MockStorage() self.resizer = resizer def teardown_method(self, method): # Empty the stacks. TestCase.added_objects[:] = [] TestCase.committed_objects[:] = [] TestCase.created_objects[:] = [] TestCase.deleted_objects[:] = [] class MockModel(object): def __init__(self, **kw): TestCase.created_objects.append(self) for key, val in kw.iteritems(): setattr(self, key, val) db_mock = flexmock( Column=lambda *a, **kw: ('column', a, kw), Integer=('integer', [], {}), Unicode=lambda *a, **kw: ('unicode', a, kw), Model=MockModel, metadata=flexmock(tables={}), session=flexmock( add=TestCase.added_objects.append, commit=lambda: TestCase.committed_objects.extend( TestCase.added_objects + TestCase.deleted_objects ), delete=TestCase.deleted_objects.append, ), )
// ... existing code ... Integer=('integer', [], {}), Unicode=lambda *a, **kw: ('unicode', a, kw), Model=MockModel, metadata=flexmock(tables={}), session=flexmock( add=TestCase.added_objects.append, commit=lambda: TestCase.committed_objects.extend( // ... rest of the code ...
69924be13f6b4303304c86fa56a802b6d358e7b2
instance/configuration_example.py
instance/configuration_example.py
class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: basestring """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: basestring | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: basestring | None """ SECRET_KEY = 'Absolutely random and very long.' """ A long, random, and secret string used to secure sessions. :type: str """
class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ ADMINS = ['[email protected]'] """ A list of email addresses of all administrators who will be notified on program failures. :type: List[str] """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: str | None """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: str | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: str | None """ SECRET_KEY = '' """ A long, random, and secret string used to secure sessions. :type: str """
Add admin email list to instance configuration.
Add admin email list to instance configuration.
Python
mit
BMeu/Orchard,BMeu/Orchard
python
## Code Before: class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: basestring """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: basestring | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: basestring | None """ SECRET_KEY = 'Absolutely random and very long.' """ A long, random, and secret string used to secure sessions. :type: str """ ## Instruction: Add admin email list to instance configuration. ## Code After: class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ ADMINS = ['[email protected]'] """ A list of email addresses of all administrators who will be notified on program failures. :type: List[str] """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: str | None """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: str | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: str | None """ SECRET_KEY = '' """ A long, random, and secret string used to secure sessions. :type: str """
// ... existing code ... You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ ADMINS = ['[email protected]'] """ A list of email addresses of all administrators who will be notified on program failures. :type: List[str] """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: str | None """ MAIL_PORT = 25 // ... modified code ... A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: str | None """ MAIL_PASSWORD = None ... The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: str | None """ SECRET_KEY = '' """ A long, random, and secret string used to secure sessions. // ... rest of the code ...
4b7e20c5640242a6e06392aaf9cbfe8e4ee8a498
mangopaysdk/types/payinpaymentdetailscard.py
mangopaysdk/types/payinpaymentdetailscard.py
from mangopaysdk.types.payinpaymentdetails import PayInPaymentDetails class PayInPaymentDetailsCard(PayInPaymentDetails): """Class represents Card type for mean of payment in PayIn entity.""" def __init__(self): # CardType enum self.CardType = None
from mangopaysdk.types.payinpaymentdetails import PayInPaymentDetails class PayInPaymentDetailsCard(PayInPaymentDetails): """Class represents Card type for mean of payment in PayIn entity.""" def __init__(self): # CardType enum self.CardType = None self.StatementDescriptor = None
Add StatementDescriptor for card web payins
Add StatementDescriptor for card web payins
Python
mit
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
python
## Code Before: from mangopaysdk.types.payinpaymentdetails import PayInPaymentDetails class PayInPaymentDetailsCard(PayInPaymentDetails): """Class represents Card type for mean of payment in PayIn entity.""" def __init__(self): # CardType enum self.CardType = None ## Instruction: Add StatementDescriptor for card web payins ## Code After: from mangopaysdk.types.payinpaymentdetails import PayInPaymentDetails class PayInPaymentDetailsCard(PayInPaymentDetails): """Class represents Card type for mean of payment in PayIn entity.""" def __init__(self): # CardType enum self.CardType = None self.StatementDescriptor = None
// ... existing code ... def __init__(self): # CardType enum self.CardType = None self.StatementDescriptor = None // ... rest of the code ...
428638304b2da579c8a87191917372153aebbe19
app/src/main/java/org/stepic/droid/ui/activities/FeedbackActivity.kt
app/src/main/java/org/stepic/droid/ui/activities/FeedbackActivity.kt
package org.stepic.droid.ui.activities import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.Fragment import org.stepic.droid.R import org.stepic.droid.base.SingleFragmentActivity import org.stepic.droid.ui.fragments.FeedbackFragment import org.stepic.droid.ui.util.initCenteredToolbar class FeedbackActivity : SingleFragmentActivity() { override fun createFragment(): Fragment = FeedbackFragment.newInstance() override fun getLayoutResId(): Int = R.layout.activity_container_with_bar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.setBackgroundDrawable(null) setUpToolbar() } private fun setUpToolbar() { initCenteredToolbar(R.string.feedback_title, showHomeButton = true, homeIndicator = closeIconDrawableRes) } override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) { android.R.id.home -> { finish() true } else -> super.onOptionsItemSelected(item) } override fun finish() { super.finish() overridePendingTransition(R.anim.no_transition, R.anim.push_down) } }
package org.stepic.droid.ui.activities import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.Fragment import org.stepic.droid.R import org.stepic.droid.base.SingleFragmentActivity import org.stepic.droid.ui.fragments.FeedbackFragment import org.stepic.droid.ui.util.initCenteredToolbar class FeedbackActivity : SingleFragmentActivity() { override fun createFragment(): Fragment = FeedbackFragment.newInstance() override fun getLayoutResId(): Int = R.layout.activity_container_with_bar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setUpToolbar() } private fun setUpToolbar() { initCenteredToolbar(R.string.feedback_title, showHomeButton = true, homeIndicator = closeIconDrawableRes) } override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) { android.R.id.home -> { finish() true } else -> super.onOptionsItemSelected(item) } override fun finish() { super.finish() overridePendingTransition(R.anim.no_transition, R.anim.push_down) } }
Fix background in feedback activity
Fix background in feedback activity
Kotlin
apache-2.0
StepicOrg/stepik-android,StepicOrg/stepic-android,StepicOrg/stepik-android,StepicOrg/stepic-android,StepicOrg/stepik-android,StepicOrg/stepic-android
kotlin
## Code Before: package org.stepic.droid.ui.activities import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.Fragment import org.stepic.droid.R import org.stepic.droid.base.SingleFragmentActivity import org.stepic.droid.ui.fragments.FeedbackFragment import org.stepic.droid.ui.util.initCenteredToolbar class FeedbackActivity : SingleFragmentActivity() { override fun createFragment(): Fragment = FeedbackFragment.newInstance() override fun getLayoutResId(): Int = R.layout.activity_container_with_bar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.setBackgroundDrawable(null) setUpToolbar() } private fun setUpToolbar() { initCenteredToolbar(R.string.feedback_title, showHomeButton = true, homeIndicator = closeIconDrawableRes) } override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) { android.R.id.home -> { finish() true } else -> super.onOptionsItemSelected(item) } override fun finish() { super.finish() overridePendingTransition(R.anim.no_transition, R.anim.push_down) } } ## Instruction: Fix background in feedback activity ## Code After: package org.stepic.droid.ui.activities import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.Fragment import org.stepic.droid.R import org.stepic.droid.base.SingleFragmentActivity import org.stepic.droid.ui.fragments.FeedbackFragment import org.stepic.droid.ui.util.initCenteredToolbar class FeedbackActivity : SingleFragmentActivity() { override fun createFragment(): Fragment = FeedbackFragment.newInstance() override fun getLayoutResId(): Int = R.layout.activity_container_with_bar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setUpToolbar() } private fun setUpToolbar() { initCenteredToolbar(R.string.feedback_title, showHomeButton = true, homeIndicator = closeIconDrawableRes) } override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) { android.R.id.home -> { finish() true } else -> super.onOptionsItemSelected(item) } override fun finish() { super.finish() overridePendingTransition(R.anim.no_transition, R.anim.push_down) } }
# ... existing code ... override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setUpToolbar() } # ... rest of the code ...
1d8f7d4a57b145fa3f8cce12a55b02eb0a754581
crypto/envelope.py
crypto/envelope.py
import hashlib def commit(key, msg): m = hashlib.sha256() m.update(key) m.update(msg) return { "hash": m.hexdigest(), "key": key } def verify(com, key, msg): v = hashlib.sha256() v.update(key) v.update(msg) try: assert v.hexdigest() == com return "Message has been verified" except: raise sealed_msg = 'there' msg = commit('hey', sealed_msg) public_msg = msg.get('hash') print(verify(public_msg, msg.get('key'), sealed_msg))
import hashlib def commit(key, msg): m = hashlib.sha256() m.update(key) m.update(msg) return { "hash": m.hexdigest(), "key": key } def verify(com, key, msg): v = hashlib.sha256() v.update(key) v.update(msg) try: assert v.hexdigest() == com return "Message has been verified" except: raise sealed_msg = 'there' key = hashlib.sha256().hexdigest() msg = commit(key, sealed_msg) public_msg = msg.get('hash') print(verify(public_msg, msg.get('key'), sealed_msg))
Make the key 'more secure'
Make the key 'more secure'
Python
mit
b-ritter/python-notes,b-ritter/python-notes
python
## Code Before: import hashlib def commit(key, msg): m = hashlib.sha256() m.update(key) m.update(msg) return { "hash": m.hexdigest(), "key": key } def verify(com, key, msg): v = hashlib.sha256() v.update(key) v.update(msg) try: assert v.hexdigest() == com return "Message has been verified" except: raise sealed_msg = 'there' msg = commit('hey', sealed_msg) public_msg = msg.get('hash') print(verify(public_msg, msg.get('key'), sealed_msg)) ## Instruction: Make the key 'more secure' ## Code After: import hashlib def commit(key, msg): m = hashlib.sha256() m.update(key) m.update(msg) return { "hash": m.hexdigest(), "key": key } def verify(com, key, msg): v = hashlib.sha256() v.update(key) v.update(msg) try: assert v.hexdigest() == com return "Message has been verified" except: raise sealed_msg = 'there' key = hashlib.sha256().hexdigest() msg = commit(key, sealed_msg) public_msg = msg.get('hash') print(verify(public_msg, msg.get('key'), sealed_msg))
# ... existing code ... sealed_msg = 'there' key = hashlib.sha256().hexdigest() msg = commit(key, sealed_msg) public_msg = msg.get('hash') # ... rest of the code ...
c129e600b91ac0c35e26847ef5b1df75a1dec695
fmn/filters/generic.py
fmn/filters/generic.py
import fedmsg def user_filter(config, message, fasnick=None, *args, **kw): """ Filters the messages by the user that performed the action. Use this filter to filter out messages that are associated with a specified user. """ fasnick = kw.get('fasnick', fasnick) if fasnick: return fasnick in fedmsg.meta.msg2usernames(message)
import fedmsg def user_filter(config, message, fasnick=None, *args, **kw): """ All messages of user Use this filter to filter out messages that are associated with a specified user. """ fasnick = kw.get('fasnick', fasnick) if fasnick: return fasnick in fedmsg.meta.msg2usernames(message)
Update the documentation title for the user_filter
Update the documentation title for the user_filter
Python
lgpl-2.1
jeremycline/fmn,jeremycline/fmn,jeremycline/fmn
python
## Code Before: import fedmsg def user_filter(config, message, fasnick=None, *args, **kw): """ Filters the messages by the user that performed the action. Use this filter to filter out messages that are associated with a specified user. """ fasnick = kw.get('fasnick', fasnick) if fasnick: return fasnick in fedmsg.meta.msg2usernames(message) ## Instruction: Update the documentation title for the user_filter ## Code After: import fedmsg def user_filter(config, message, fasnick=None, *args, **kw): """ All messages of user Use this filter to filter out messages that are associated with a specified user. """ fasnick = kw.get('fasnick', fasnick) if fasnick: return fasnick in fedmsg.meta.msg2usernames(message)
# ... existing code ... def user_filter(config, message, fasnick=None, *args, **kw): """ All messages of user Use this filter to filter out messages that are associated with a specified user. # ... rest of the code ...
e83df69d675eec01bf3253a2c7911cedb0c081af
tests/test_queryable.py
tests/test_queryable.py
from busbus.queryable import Queryable def test_queryable(): q = Queryable(xrange(10)).where(lambda x: x % 5 == 0) assert next(q) == 0 assert next(q) == 5
from busbus.queryable import Queryable from six.moves import range def test_queryable(): q = Queryable(range(10)).where(lambda x: x % 5 == 0) assert next(q) == 0 assert next(q) == 5
Fix basic test case for Queryable class in Python 3
Fix basic test case for Queryable class in Python 3
Python
mit
spaceboats/busbus
python
## Code Before: from busbus.queryable import Queryable def test_queryable(): q = Queryable(xrange(10)).where(lambda x: x % 5 == 0) assert next(q) == 0 assert next(q) == 5 ## Instruction: Fix basic test case for Queryable class in Python 3 ## Code After: from busbus.queryable import Queryable from six.moves import range def test_queryable(): q = Queryable(range(10)).where(lambda x: x % 5 == 0) assert next(q) == 0 assert next(q) == 5
# ... existing code ... from busbus.queryable import Queryable from six.moves import range def test_queryable(): q = Queryable(range(10)).where(lambda x: x % 5 == 0) assert next(q) == 0 assert next(q) == 5 # ... rest of the code ...
29fef644079a03fe0cfeb792dd47af7749382dba
unnaturalcode/http/__main__.py
unnaturalcode/http/__main__.py
from unnaturalcode.http import unnaturalhttp from flask import Flask app = Flask(__name__) app.register_blueprint(unnaturalhttp) app.run(host='0.0.0.0')
try: from unnaturalcode.http import unnaturalhttp except ImportError: import sys, os # Oiugh. sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) from unnaturalcode.http import unnaturalhttp from flask import Flask app = Flask(__name__) app.register_blueprint(unnaturalhttp) app.run(host='0.0.0.0')
Fix to allow invocation by `python unnaturalcode/http`
Fix to allow invocation by `python unnaturalcode/http`
Python
agpl-3.0
orezpraw/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/estimate-charm,naturalness/unnaturalcode,orezpraw/unnaturalcode
python
## Code Before: from unnaturalcode.http import unnaturalhttp from flask import Flask app = Flask(__name__) app.register_blueprint(unnaturalhttp) app.run(host='0.0.0.0') ## Instruction: Fix to allow invocation by `python unnaturalcode/http` ## Code After: try: from unnaturalcode.http import unnaturalhttp except ImportError: import sys, os # Oiugh. sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) from unnaturalcode.http import unnaturalhttp from flask import Flask app = Flask(__name__) app.register_blueprint(unnaturalhttp) app.run(host='0.0.0.0')
... try: from unnaturalcode.http import unnaturalhttp except ImportError: import sys, os # Oiugh. sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) from unnaturalcode.http import unnaturalhttp from flask import Flask app = Flask(__name__) ...
c7172405b835920d553aa3d5ac6d415da2253d0d
oneflow/core/social_pipeline.py
oneflow/core/social_pipeline.py
import logging # from constance import config # from django.shortcuts import redirect from social_auth.backends.facebook import FacebookBackend from social_auth.backends.twitter import TwitterBackend from social_auth.backends import google from models import ( TwitterAccount, # FacebookAccount, FacebookFeed, ) LOGGER = logging.getLogger(__name__) def check_feeds(social_user, user, details, request, response, backend, is_new=False, *args, **kwargs): """ Create Accounts & feeds associated with social networks. """ try: if isinstance(backend, FacebookBackend): pass elif isinstance(backend, google.GoogleOAuth2Backend): pass elif isinstance(backend, TwitterBackend): TwitterAccount.check_social_user(social_user, user, backend) except: LOGGER.exception(u'Could not check feeds for user %s from ' u'backend %s.', user, social_user)
import logging # from constance import config # from django.shortcuts import redirect # from social_auth.backends.facebook import FacebookBackend # from social_auth.backends.twitter import TwitterBackend # from social_auth.backends import google # from models import ( # TwitterAccount, # # FacebookAccount, FacebookFeed, # ) LOGGER = logging.getLogger(__name__)
Remove useless/obsolete social pipeline function (it's done in social_auth post_save()+task to make pipeline independant and faster).
Remove useless/obsolete social pipeline function (it's done in social_auth post_save()+task to make pipeline independant and faster).
Python
agpl-3.0
1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,WillianPaiva/1flow
python
## Code Before: import logging # from constance import config # from django.shortcuts import redirect from social_auth.backends.facebook import FacebookBackend from social_auth.backends.twitter import TwitterBackend from social_auth.backends import google from models import ( TwitterAccount, # FacebookAccount, FacebookFeed, ) LOGGER = logging.getLogger(__name__) def check_feeds(social_user, user, details, request, response, backend, is_new=False, *args, **kwargs): """ Create Accounts & feeds associated with social networks. """ try: if isinstance(backend, FacebookBackend): pass elif isinstance(backend, google.GoogleOAuth2Backend): pass elif isinstance(backend, TwitterBackend): TwitterAccount.check_social_user(social_user, user, backend) except: LOGGER.exception(u'Could not check feeds for user %s from ' u'backend %s.', user, social_user) ## Instruction: Remove useless/obsolete social pipeline function (it's done in social_auth post_save()+task to make pipeline independant and faster). ## Code After: import logging # from constance import config # from django.shortcuts import redirect # from social_auth.backends.facebook import FacebookBackend # from social_auth.backends.twitter import TwitterBackend # from social_auth.backends import google # from models import ( # TwitterAccount, # # FacebookAccount, FacebookFeed, # ) LOGGER = logging.getLogger(__name__)
// ... existing code ... # from django.shortcuts import redirect # from social_auth.backends.facebook import FacebookBackend # from social_auth.backends.twitter import TwitterBackend # from social_auth.backends import google # from models import ( # TwitterAccount, # # FacebookAccount, FacebookFeed, # ) LOGGER = logging.getLogger(__name__) // ... rest of the code ...
b67ee17b401df9dec4f76f1a24cef2a7ce25406b
1-moderate/locks/main.py
1-moderate/locks/main.py
import sys def do_lock_pass(locked): for i in xrange(0, len(locked), 2): locked[i] = True def do_flip_pass(locked): for i in xrange(0, len(locked), 3): locked[i] = not locked[i] def count_unlocked(locked): result = 0 for l in locked: if not l: result += 1 return result def main(): test_cases = open(sys.argv[1], 'r') for test in test_cases: test = test.strip() num_locks = int(test.split(' ')[0]) num_iterations = int(test.split(' ')[1]) locked = [False] * num_locks for i in xrange(num_iterations-1): do_lock_pass(locked) do_flip_pass(locked) locked[-1] = True print count_unlocked(locked) test_cases.close() main()
import sys def do_lock_pass(locked): for i in xrange(1, len(locked), 2): locked[i] = True def do_flip_pass(locked): for i in xrange(2, len(locked), 3): locked[i] = not locked[i] def count_unlocked(locked): result = 0 for l in locked: if not l: result += 1 return result def main(): test_cases = open(sys.argv[1], 'r') for test in test_cases: test = test.strip() num_locks = int(test.split(' ')[0]) num_iterations = int(test.split(' ')[1]) locked = [False] * num_locks for i in xrange(num_iterations-1): do_lock_pass(locked) do_flip_pass(locked) locked[-1] = not locked[-1] print count_unlocked(locked) test_cases.close() main()
Fix solution to the locks problem.
Fix solution to the locks problem.
Python
unlicense
mpillar/codeeval,mpillar/codeeval,mpillar/codeeval,mpillar/codeeval
python
## Code Before: import sys def do_lock_pass(locked): for i in xrange(0, len(locked), 2): locked[i] = True def do_flip_pass(locked): for i in xrange(0, len(locked), 3): locked[i] = not locked[i] def count_unlocked(locked): result = 0 for l in locked: if not l: result += 1 return result def main(): test_cases = open(sys.argv[1], 'r') for test in test_cases: test = test.strip() num_locks = int(test.split(' ')[0]) num_iterations = int(test.split(' ')[1]) locked = [False] * num_locks for i in xrange(num_iterations-1): do_lock_pass(locked) do_flip_pass(locked) locked[-1] = True print count_unlocked(locked) test_cases.close() main() ## Instruction: Fix solution to the locks problem. ## Code After: import sys def do_lock_pass(locked): for i in xrange(1, len(locked), 2): locked[i] = True def do_flip_pass(locked): for i in xrange(2, len(locked), 3): locked[i] = not locked[i] def count_unlocked(locked): result = 0 for l in locked: if not l: result += 1 return result def main(): test_cases = open(sys.argv[1], 'r') for test in test_cases: test = test.strip() num_locks = int(test.split(' ')[0]) num_iterations = int(test.split(' ')[1]) locked = [False] * num_locks for i in xrange(num_iterations-1): do_lock_pass(locked) do_flip_pass(locked) locked[-1] = not locked[-1] print count_unlocked(locked) test_cases.close() main()
# ... existing code ... import sys def do_lock_pass(locked): for i in xrange(1, len(locked), 2): locked[i] = True def do_flip_pass(locked): for i in xrange(2, len(locked), 3): locked[i] = not locked[i] def count_unlocked(locked): # ... modified code ... do_lock_pass(locked) do_flip_pass(locked) locked[-1] = not locked[-1] print count_unlocked(locked) test_cases.close() # ... rest of the code ...
26c3f786064923f0ac099de645289ff75014b354
setup.py
setup.py
import os import sys from setuptools import setup this_dir = os.path.abspath(os.path.dirname(__file__)) VERSIONFILE = os.path.join(this_dir, "textx", "__init__.py") VERSION = None for line in open(VERSIONFILE, "r").readlines(): if line.startswith('__version__'): VERSION = line.split('"')[1] if not VERSION: raise RuntimeError('No version defined in textx.__init__.py') if sys.argv[-1].startswith('publish'): if os.system("pip list | grep wheel"): print("wheel not installed.\nUse `pip install wheel`.\nExiting.") sys.exit() if os.system("pip list | grep twine"): print("twine not installed.\nUse `pip install twine`.\nExiting.") sys.exit() os.system("python setup.py sdist bdist_wheel") if sys.argv[-1] == 'publishtest': os.system("twine upload -r test dist/*") else: os.system("twine upload dist/*") sys.exit() setup(version=VERSION)
import os import sys from setuptools import setup this_dir = os.path.abspath(os.path.dirname(__file__)) VERSIONFILE = os.path.join(this_dir, "textx", "__init__.py") VERSION = None for line in open(VERSIONFILE, "r").readlines(): if line.startswith('__version__'): VERSION = line.split('"')[1] if not VERSION: raise RuntimeError('No version defined in textx.__init__.py') if sys.argv[-1].startswith('publish'): if os.system("pip list | grep wheel"): print("wheel not installed.\nUse `pip install wheel`.\nExiting.") sys.exit() if os.system("pip list | grep twine"): print("twine not installed.\nUse `pip install twine`.\nExiting.") sys.exit() os.system("python setup.py sdist bdist_wheel") if sys.argv[-1] == 'publishtest': os.system("twine upload -r test dist/*") else: os.system("twine upload dist/*") print("You probably want to also tag the version now:") print(" git tag -a {0} -m 'version {0}'".format(VERSION)) print(" git push --tags") sys.exit() setup(version=VERSION)
Revert note to tag the version after publish
Revert note to tag the version after publish
Python
mit
igordejanovic/textX,igordejanovic/textX,igordejanovic/textX
python
## Code Before: import os import sys from setuptools import setup this_dir = os.path.abspath(os.path.dirname(__file__)) VERSIONFILE = os.path.join(this_dir, "textx", "__init__.py") VERSION = None for line in open(VERSIONFILE, "r").readlines(): if line.startswith('__version__'): VERSION = line.split('"')[1] if not VERSION: raise RuntimeError('No version defined in textx.__init__.py') if sys.argv[-1].startswith('publish'): if os.system("pip list | grep wheel"): print("wheel not installed.\nUse `pip install wheel`.\nExiting.") sys.exit() if os.system("pip list | grep twine"): print("twine not installed.\nUse `pip install twine`.\nExiting.") sys.exit() os.system("python setup.py sdist bdist_wheel") if sys.argv[-1] == 'publishtest': os.system("twine upload -r test dist/*") else: os.system("twine upload dist/*") sys.exit() setup(version=VERSION) ## Instruction: Revert note to tag the version after publish ## Code After: import os import sys from setuptools import setup this_dir = os.path.abspath(os.path.dirname(__file__)) VERSIONFILE = os.path.join(this_dir, "textx", "__init__.py") VERSION = None for line in open(VERSIONFILE, "r").readlines(): if line.startswith('__version__'): VERSION = line.split('"')[1] if not VERSION: raise RuntimeError('No version defined in textx.__init__.py') if sys.argv[-1].startswith('publish'): if os.system("pip list | grep wheel"): print("wheel not installed.\nUse `pip install wheel`.\nExiting.") sys.exit() if os.system("pip list | grep twine"): print("twine not installed.\nUse `pip install twine`.\nExiting.") sys.exit() os.system("python setup.py sdist bdist_wheel") if sys.argv[-1] == 'publishtest': os.system("twine upload -r test dist/*") else: os.system("twine upload dist/*") print("You probably want to also tag the version now:") print(" git tag -a {0} -m 'version {0}'".format(VERSION)) print(" git push --tags") sys.exit() setup(version=VERSION)
# ... existing code ... os.system("twine upload -r test dist/*") else: os.system("twine upload dist/*") print("You probably want to also tag the version now:") print(" git tag -a {0} -m 'version {0}'".format(VERSION)) print(" git push --tags") sys.exit() setup(version=VERSION) # ... rest of the code ...
20a0bea197188ffa3e7abaffe030305bc63bd9c4
Libraries/PushNotificationIOS/RCTPushNotificationManager.h
Libraries/PushNotificationIOS/RCTPushNotificationManager.h
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import <UIKit/UIKit.h> #import "../../ReactKit/Base/RCTBridgeModule.h" @interface RCTPushNotificationManager : NSObject <RCTBridgeModule> - (instancetype)initWithInitialNotification:(NSDictionary *)initialNotification NS_DESIGNATED_INITIALIZER; + (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings; + (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification; + (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation; @end
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import <UIKit/UIKit.h> #import "RCTBridgeModule.h" @interface RCTPushNotificationManager : NSObject <RCTBridgeModule> - (instancetype)initWithInitialNotification:(NSDictionary *)initialNotification NS_DESIGNATED_INITIALIZER; + (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings; + (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification; + (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation; @end
Fix build - remove relative import path
Fix build - remove relative import path
C
bsd-3-clause
skevy/react-native,bsansouci/react-native,steben/react-native,udnisap/react-native,garrows/react-native,Lucifer-Kim/react-native,lzbSun/react-native,dabit3/react-native,Andreyco/react-native,darrylblake/react-native,DanielMSchmidt/react-native,christer155/react-native,zhangxq5012/react-native,janicduplessis/react-native,christopherdro/react-native,Livyli/react-native,alinz/react-native,yjyi/react-native,clozr/react-native,Shopify/react-native,cosmith/react-native,Bhullnatik/react-native,alpz5566/react-native,pickhardt/react-native,esauter5/react-native,leeyeh/react-native,chacbumbum/react-native,hammerandchisel/react-native,leopardpan/react-native,mqli/react-native,rodneyss/react-native,miracle2k/react-native,browniefed/react-native,htc2u/react-native,hzgnpu/react-native,peterp/react-native,Applied-Duality/react-native,jaggs6/react-native,boopathi/react-native,yelled3/react-native,chnfeeeeeef/react-native,jeffchienzabinet/react-native,chetstone/react-native,Inner89/react-native,Maxwell2022/react-native,wangjiangwen/react-native,htc2u/react-native,Maxwell2022/react-native,kassens/react-native,garrows/react-native,cosmith/react-native,nktpro/react-native,negativetwelve/react-native,nathanajah/react-native,lzbSun/react-native,yusefnapora/react-native,bright-sparks/react-native,F2EVarMan/react-native,jordanbyron/react-native,bestwpw/react-native,roth1002/react-native,Flickster42490/react-native,popovsh6/react-native,cmhsu/react-native,fw1121/react-native,appersonlabs/react-native,nickhudkins/react-native,satya164/react-native,kotdark/react-native,lee-my/react-native,Ehesp/react-native,devknoll/react-native,luqin/react-native,machard/react-native,tarkus/react-native-appletv,gegaosong/react-native,rebeccahughes/react-native,gabrielbellamy/react-native,chapinkapa/react-native,philonpang/react-native,huangsongyan/react-native,Bhullnatik/react-native,ldehai/react-native,sixtomay/react-native,stonegithubs/react-native,pallyoung/react-native,liufeigit/react-native,lprhodes/react-native,timfpark/react-native,facebook/react-native,jaredly/react-native,dralletje/react-native,lightsofapollo/react-native,ptmt/react-native,threepointone/react-native-1,harrykiselev/react-native,taydakov/react-native,FionaWong/react-native,shinate/react-native,jackeychens/react-native,kfiroo/react-native,naoufal/react-native,MetSystem/react-native,lelandrichardson/react-native,gilesvangruisen/react-native,sudhirj/react-native,corbt/react-native,zuolangguo/react-native,jasonals/react-native,monyxie/react-native,urvashi01/react-native,bowlofstew/react-native,code0100fun/react-native,devknoll/react-native,wangcan2014/react-native,alvarojoao/react-native,wangjiangwen/react-native,bestwpw/react-native,qq644531343/react-native,eduardinni/react-native,alin23/react-native,bright-sparks/react-native,thstarshine/react-native,noif/react-native,thotegowda/react-native,tadeuzagallo/react-native,ndejesus1227/react-native,lightsofapollo/react-native,Bronts/react-native,fish24k/react-native,quyixia/react-native,hydraulic/react-native,mbrock/react-native,sahrens/react-native,quuack/react-native,RGKzhanglei/react-native,wenpkpk/react-native,foghina/react-native,spyrx7/react-native,hoangpham95/react-native,garydonovan/react-native,hesling/react-native,Rowandjj/react-native,cosmith/react-native,judastree/react-native,Poplava/react-native,Iragne/react-native,ludaye123/react-native,imjerrybao/react-native,appersonlabs/react-native,marlonandrade/react-native,averted/react-native,geoffreyfloyd/react-native,lee-my/react-native,TChengZ/react-native,1988fei/react-native,CntChen/react-native,gegaosong/react-native,pletcher/react-native,MetSystem/react-native,dimoge/react-native,leopardpan/react-native,xxccll/react-native,JasonZ321/react-native,codejet/react-native,stonegithubs/react-native,ptmt/react-native-macos,narlian/react-native,NunoEdgarGub1/react-native,orenklein/react-native,threepointone/react-native-1,pjcabrera/react-native,lendup/react-native,DannyvanderJagt/react-native,NishanthShankar/react-native,hwsyy/react-native,brentvatne/react-native,yamill/react-native,salanki/react-native,chrisbutcher/react-native,pvinis/react-native-desktop,ludaye123/react-native,clozr/react-native,alpz5566/react-native,WilliamRen/react-native,lendup/react-native,kushal/react-native,gauribhoite/react-native,jasonnoahchoi/react-native,YComputer/react-native,Maxwell2022/react-native,Furzikov/react-native,mjetek/react-native,liuhong1happy/react-native,glovebx/react-native,rkumar3147/react-native,clozr/react-native,jaggs6/react-native,janicduplessis/react-native,frantic/react-native,neeraj-singh/react-native,timfpark/react-native,krock01/react-native,zhangwei001/react-native,DanielMSchmidt/react-native,ludaye123/react-native,eduvon0220/react-native,zuolangguo/react-native,vincentqiu/react-native,leeyeh/react-native,ptomasroos/react-native,gitim/react-native,gauribhoite/react-native,elliottsj/react-native,eliagrady/react-native,mcrooks88/react-native,insionng/react-native,jmhdez/react-native,dalinaum/react-native,shinate/react-native,ronak301/react-native,Guardiannw/react-native,srounce/react-native,chengky/react-native,wenpkpk/react-native,JulienThibeaut/react-native,htc2u/react-native,Maxwell2022/react-native,lprhodes/react-native,ajwhite/react-native,bistacos/react-native,naoufal/react-native,common2015/react-native,hike2008/react-native,Esdeath/react-native,srounce/react-native,hassanabidpk/react-native,CodeLinkIO/react-native,Andreyco/react-native,jibonpab/react-native,sheep902/react-native,jabinwang/react-native,zvona/react-native,ehd/react-native,F2EVarMan/react-native,rantianhua/react-native,hanxiaofei/react-native,honger05/react-native,chengky/react-native,threepointone/react-native-1,rodneyss/react-native,exponent/react-native,beni55/react-native,aaron-goshine/react-native,bradens/react-native,sdiaz/react-native,sixtomay/react-native,dikaiosune/react-native,chsj1/react-native,yangchengwork/react-native,waynett/react-native,htc2u/react-native,yushiwo/react-native,Inner89/react-native,skevy/react-native,wjb12/react-native,Swaagie/react-native,Bhullnatik/react-native,vincentqiu/react-native,tadeuzagallo/react-native,makadaw/react-native,pengleelove/react-native,simple88/react-native,Shopify/react-native,lokilandon/react-native,ehd/react-native,ChristianHersevoort/react-native,jordanbyron/react-native,Reparadocs/react-native,pj4533/react-native,lprhodes/react-native,zyvas/react-native,krock01/react-native,srounce/react-native,Emilios1995/react-native,jbaumbach/react-native,beni55/react-native,aljs/react-native,dralletje/react-native,liangmingjie/react-native,doochik/react-native,shlomiatar/react-native,rantianhua/react-native,clozr/react-native,rickbeerendonk/react-native,jackeychens/react-native,cdlewis/react-native,charmingzuo/react-native,udnisap/react-native,peterp/react-native,yimouleng/react-native,luqin/react-native,appersonlabs/react-native,gabrielbellamy/react-native,mrngoitall/react-native,brentvatne/react-native,cazacugmihai/react-native,andrewljohnson/react-native,huangsongyan/react-native,sonnylazuardi/react-native,tszajna0/react-native,kamronbatman/react-native,spicyj/react-native,mironiasty/react-native,urvashi01/react-native,Emilios1995/react-native,forcedotcom/react-native,stan229/react-native,vlrchtlt/react-native,hammerandchisel/react-native,nbcnews/react-native,nickhargreaves/react-native,CodeLinkIO/react-native,hayeah/react-native,sudhirj/react-native,nathanajah/react-native,BossKing/react-native,xiangjuntang/react-native,skatpgusskat/react-native,zdsiyan/react-native,timfpark/react-native,shinate/react-native,nevir/react-native,bogdantmm92/react-native,Heart2009/react-native,tgf229/react-native,chetstone/react-native,jacobbubu/react-native,woshili1/react-native,mihaigiurgeanu/react-native,thstarshine/react-native,dut3062796s/react-native,YinshawnRao/react-native,lwansbrough/react-native,rickbeerendonk/react-native,jmhdez/react-native,huip/react-native,xxccll/react-native,Purii/react-native,xxccll/react-native,pallyoung/react-native,milieu/react-native,satya164/react-native,brentvatne/react-native,adrie4mac/react-native,Reparadocs/react-native,johnv315/react-native,PhilippKrone/react-native,gs-akhan/react-native,evilemon/react-native,skatpgusskat/react-native,iOSTestApps/react-native,bestwpw/react-native,quyixia/react-native,JulienThibeaut/react-native,Furzikov/react-native,pjcabrera/react-native,doochik/react-native,sheep902/react-native,machard/react-native,kfiroo/react-native,iodine/react-native,bowlofstew/react-native,code0100fun/react-native,hammerandchisel/react-native,ldehai/react-native,jadbox/react-native,dfala/react-native,rainkong/react-native,lucyywang/react-native,mrspeaker/react-native,Flickster42490/react-native,bestwpw/react-native,liduanw/react-native,xiayz/react-native,foghina/react-native,strwind/react-native,skatpgusskat/react-native,imjerrybao/react-native,makadaw/react-native,zhangxq5012/react-native,quyixia/react-native,nsimmons/react-native,philikon/react-native,hesling/react-native,bright-sparks/react-native,MattFoley/react-native,ouyangwenfeng/react-native,gitim/react-native,jmstout/react-native,hanxiaofei/react-native,hassanabidpk/react-native,almost/react-native,JoeStanton/react-native,billhello/react-native,lanceharper/react-native,Flickster42490/react-native,nathanajah/react-native,futbalguy/react-native,mchinyakov/react-native,tmwoodson/react-native,qingsong-xu/react-native,rwwarren/react-native,HealthyWealthy/react-native,vagrantinoz/react-native,judastree/react-native,MattFoley/react-native,wesley1001/react-native,imDangerous/react-native,negativetwelve/react-native,bradens/react-native,imDangerous/react-native,chentsulin/react-native,rodneyss/react-native,dubert/react-native,yjyi/react-native,gre/react-native,mrngoitall/react-native,josebalius/react-native,lstNull/react-native,sospartan/react-native,pandiaraj44/react-native,Bronts/react-native,gitim/react-native,averted/react-native,tadeuzagallo/react-native,Serfenia/react-native,chirag04/react-native,evilemon/react-native,kesha-antonov/react-native,Bronts/react-native,cxfeng1/react-native,zuolangguo/react-native,cmhsu/react-native,spyrx7/react-native,jacobbubu/react-native,rebeccahughes/react-native,lwansbrough/react-native,shlomiatar/react-native,shrimpy/react-native,yjyi/react-native,yangchengwork/react-native,genome21/react-native,hzgnpu/react-native,iOSTestApps/react-native,krock01/react-native,liuhong1happy/react-native,browniefed/react-native,gilesvangruisen/react-native,wangjiangwen/react-native,mosch/react-native,j27cai/react-native,nevir/react-native,alpz5566/react-native,spyrx7/react-native,orenklein/react-native,leopardpan/react-native,DanielMSchmidt/react-native,zenlambda/react-native,ronak301/react-native,mchinyakov/react-native,strwind/react-native,donyu/react-native,pcottle/react-native,enaqx/react-native,urvashi01/react-native,krock01/react-native,rollokb/react-native,hesling/react-native,shrutic/react-native,chnfeeeeeef/react-native,mchinyakov/react-native,bistacos/react-native,almost/react-native,steben/react-native,supercocoa/react-native,Guardiannw/react-native,ajwhite/react-native,ankitsinghania94/react-native,garydonovan/react-native,devknoll/react-native,YComputer/react-native,hayeah/react-native,bradbumbalough/react-native,michaelchucoder/react-native,jonesgithub/react-native,common2015/react-native,satya164/react-native,harrykiselev/react-native,arbesfeld/react-native,genome21/react-native,yjh0502/react-native,tgriesser/react-native,donyu/react-native,yamill/react-native,Furzikov/react-native,csatf/react-native,gilesvangruisen/react-native,ptmt/react-native-macos,noif/react-native,puf/react-native,lee-my/react-native,richardgill/react-native,a2/react-native,bodefuwa/react-native,ptomasroos/react-native,adamterlson/react-native,happypancake/react-native,pglotov/react-native,Poplava/react-native,Purii/react-native,corbt/react-native,YotrolZ/react-native,irisli/react-native,zhangxq5012/react-native,huangsongyan/react-native,wangcan2014/react-native,foghina/react-native,abdelouahabb/react-native,wlrhnh-David/react-native,jekey/react-native,adamkrell/react-native,CodeLinkIO/react-native,sunblaze/react-native,PlexChat/react-native,puf/react-native,shrutic123/react-native,pitatensai/react-native,KJlmfe/react-native,apprennet/react-native,Furzikov/react-native,yutail/react-native,kotdark/react-native,lendup/react-native,browniefed/react-native,NunoEdgarGub1/react-native,rodneyss/react-native,shrutic/react-native,yamill/react-native,rushidesai/react-native,steveleec/react-native,makadaw/react-native,alinz/react-native,clozr/react-native,enaqx/react-native,popovsh6/react-native,sospartan/react-native,sonnylazuardi/react-native,lloydho/react-native,eduvon0220/react-native,liuzechen/react-native,DerayGa/react-native,jevakallio/react-native,philonpang/react-native,doochik/react-native,dylanchann/react-native,hesling/react-native,jekey/react-native,bouk/react-native,marlonandrade/react-native,cdlewis/react-native,vjeux/react-native,naoufal/react-native,zuolangguo/react-native,Lohit9/react-native,javache/react-native,yangshangde/react-native,yjyi/react-native,ptmt/react-native-macos,xxccll/react-native,shlomiatar/react-native,mway08/react-native,barakcoh/react-native,code0100fun/react-native,patoroco/react-native,hydraulic/react-native,johnv315/react-native,Emilios1995/react-native,YueRuo/react-native,abdelouahabb/react-native,ludaye123/react-native,Applied-Duality/react-native,rantianhua/react-native,miracle2k/react-native,Intellicode/react-native,philikon/react-native,androidgilbert/react-native,iodine/react-native,sjchakrav/react-native,exponent/react-native,Flickster42490/react-native,narlian/react-native,Swaagie/react-native,mjetek/react-native,sdiaz/react-native,kamronbatman/react-native,pj4533/react-native,tsjing/react-native,monyxie/react-native,jmhdez/react-native,facebook/react-native,adrie4mac/react-native,luqin/react-native,jackalchen/react-native,lstNull/react-native,elliottsj/react-native,judastree/react-native,cdlewis/react-native,doochik/react-native,leegilon/react-native,zdsiyan/react-native,DannyvanderJagt/react-native,urvashi01/react-native,formatlos/react-native,enaqx/react-native,exponent/react-native,roy0914/react-native,BossKing/react-native,abdelouahabb/react-native,hassanabidpk/react-native,jaredly/react-native,fw1121/react-native,jadbox/react-native,dralletje/react-native,mihaigiurgeanu/react-native,makadaw/react-native,dut3062796s/react-native,arbesfeld/react-native,ChiMarvine/react-native,trueblue2704/react-native,ProjectSeptemberInc/react-native,satya164/react-native,clooth/react-native,booxood/react-native,zuolangguo/react-native,cez213/react-native,facebook/react-native,Suninus/react-native,guanghuili/react-native,HSFGitHub/react-native,chenbk85/react-native,carcer/react-native,nickhudkins/react-native,Bhullnatik/react-native,cazacugmihai/react-native,chetstone/react-native,aziz-boudi4/react-native,Heart2009/react-native,philikon/react-native,Loke155/react-native,dylanchann/react-native,farazs/react-native,xiayz/react-native,Furzikov/react-native,dralletje/react-native,lstNull/react-native,mrspeaker/react-native,javache/react-native,kujohn/react-native,kassens/react-native,beni55/react-native,philonpang/react-native,eduvon0220/react-native,RGKzhanglei/react-native,nickhargreaves/react-native,bodefuwa/react-native,mukesh-kumar1905/react-native,udnisap/react-native,lee-my/react-native,lmorchard/react-native,farazs/react-native,xiayz/react-native,appersonlabs/react-native,ptmt/react-native-macos,hengcj/react-native,leegilon/react-native,kamronbatman/react-native,kushal/react-native,dimoge/react-native,simple88/react-native,liufeigit/react-native,jeffchienzabinet/react-native,vlrchtlt/react-native,Intellicode/react-native,darkrishabh/react-native,pjcabrera/react-native,Serfenia/react-native,HSFGitHub/react-native,popovsh6/react-native,pcottle/react-native,rxb/react-native,makadaw/react-native,misakuo/react-native,j27cai/react-native,dylanchann/react-native,jhen0409/react-native,wangyzyoga/react-native,Iragne/react-native,MetSystem/react-native,MonirAbuHilal/react-native,tahnok/react-native,affinityis/react-native,HealthyWealthy/react-native,lprhodes/react-native,hike2008/react-native,codejet/react-native,lstNull/react-native,fish24k/react-native,dvcrn/react-native,ramoslin02/react-native,christer155/react-native,thstarshine/react-native,emodeqidao/react-native,Swaagie/react-native,liufeigit/react-native,pjcabrera/react-native,fengshao0907/react-native,gitim/react-native,noif/react-native,common2015/react-native,jasonals/react-native,exponentjs/react-native,xiayz/react-native,jasonals/react-native,levic92/react-native,oren/react-native,huangsongyan/react-native,xinthink/react-native,common2015/react-native,udnisap/react-native,salanki/react-native,Esdeath/react-native,yangshangde/react-native,F2EVarMan/react-native,misakuo/react-native,mukesh-kumar1905/react-native,Inner89/react-native,MattFoley/react-native,gs-akhan/react-native,wjb12/react-native,farazs/react-native,21451061/react-native,jeanblanchard/react-native,Jonekee/react-native,gre/react-native,sonnylazuardi/react-native,ModusCreateOrg/react-native,christer155/react-native,MattFoley/react-native,abdelouahabb/react-native,alinz/react-native,Esdeath/react-native,onesfreedom/react-native,mihaigiurgeanu/react-native,NishanthShankar/react-native,BossKing/react-native,kassens/react-native,udnisap/react-native,heyjim89/react-native,jbaumbach/react-native,wlrhnh-David/react-native,darrylblake/react-native,supercocoa/react-native,common2015/react-native,jasonnoahchoi/react-native,ChristopherSalam/react-native,jeffchienzabinet/react-native,insionng/react-native,johnv315/react-native,codejet/react-native,hassanabidpk/react-native,cpunion/react-native,Srikanth4/react-native,ndejesus1227/react-native,Ehesp/react-native,mironiasty/react-native,apprennet/react-native,jackeychens/react-native,bistacos/react-native,leegilon/react-native,BossKing/react-native,mtford90/react-native,yzarubin/react-native,Livyli/react-native,judastree/react-native,exponent/react-native,christopherdro/react-native,sdiaz/react-native,fish24k/react-native,gitim/react-native,lucyywang/react-native,sospartan/react-native,tszajna0/react-native,kfiroo/react-native,lelandrichardson/react-native,machard/react-native,affinityis/react-native,chenbk85/react-native,rkumar3147/react-native,exponentjs/react-native,garydonovan/react-native,xinthink/react-native,urvashi01/react-native,wenpkpk/react-native,kassens/react-native,hengcj/react-native,wjb12/react-native,ProjectSeptemberInc/react-native,levic92/react-native,gilesvangruisen/react-native,affinityis/react-native,ivanph/react-native,roy0914/react-native,lelandrichardson/react-native,rkumar3147/react-native,chsj1/react-native,liangmingjie/react-native,ankitsinghania94/react-native,folist/react-native,thotegowda/react-native,mchinyakov/react-native,rxb/react-native,wlrhnh-David/react-native,darrylblake/react-native,sitexa/react-native,Poplava/react-native,almost/react-native,nanpian/react-native,dut3062796s/react-native,alin23/react-native,soxunyi/react-native,programming086/react-native,lucyywang/react-native,Intellicode/react-native,dikaiosune/react-native,yutail/react-native,beni55/react-native,facebook/react-native,bright-sparks/react-native,emodeqidao/react-native,lokilandon/react-native,madusankapremaratne/react-native,exponentjs/react-native,aljs/react-native,shadow000902/react-native,fish24k/react-native,kujohn/react-native,taydakov/react-native,mrspeaker/react-native,stan229/react-native,Loke155/react-native,billhello/react-native,mtford90/react-native,imjerrybao/react-native,dikaiosune/react-native,naoufal/react-native,bodefuwa/react-native,roth1002/react-native,javache/react-native,vincentqiu/react-native,tadeuzagallo/react-native,kamronbatman/react-native,DerayGa/react-native,sunblaze/react-native,kamronbatman/react-native,fish24k/react-native,Loke155/react-native,garrows/react-native,steben/react-native,jackalchen/react-native,mrngoitall/react-native,tgriesser/react-native,MonirAbuHilal/react-native,gabrielbellamy/react-native,edward/react-native,darkrishabh/react-native,nickhargreaves/react-native,roth1002/react-native,stan229/react-native,eddiemonge/react-native,pj4533/react-native,udnisap/react-native,Rowandjj/react-native,soulcm/react-native,clooth/react-native,elliottsj/react-native,yangchengwork/react-native,NZAOM/react-native,Maxwell2022/react-native,cosmith/react-native,sarvex/react-native,bouk/react-native,liuzechen/react-native,csatf/react-native,shrimpy/react-native,adamterlson/react-native,gabrielbellamy/react-native,rodneyss/react-native,eduardinni/react-native,ordinarybill/react-native,Applied-Duality/react-native,fengshao0907/react-native,Bhullnatik/react-native,cxfeng1/react-native,cazacugmihai/react-native,lgengsy/react-native,InterfaceInc/react-native,codejet/react-native,glovebx/react-native,cosmith/react-native,nanpian/react-native,supercocoa/react-native,chiefr/react-native,evansolomon/react-native,xiangjuntang/react-native,mihaigiurgeanu/react-native,catalinmiron/react-native,brentvatne/react-native,xiangjuntang/react-native,eliagrady/react-native,nanpian/react-native,shrimpy/react-native,hoangpham95/react-native,pallyoung/react-native,glovebx/react-native,taydakov/react-native,magnus-bergman/react-native,shadow000902/react-native,kesha-antonov/react-native,hydraulic/react-native,spyrx7/react-native,ankitsinghania94/react-native,aaron-goshine/react-native,lucyywang/react-native,lucyywang/react-native,spyrx7/react-native,corbt/react-native,skevy/react-native,formatlos/react-native,adamjmcgrath/react-native,ipmobiletech/react-native,bsansouci/react-native,pcottle/react-native,dimoge/react-native,pjcabrera/react-native,bogdantmm92/react-native,rickbeerendonk/react-native,udnisap/react-native,zenlambda/react-native,sunblaze/react-native,mironiasty/react-native,neeraj-singh/react-native,sarvex/react-native,chapinkapa/react-native,BretJohnson/react-native,ordinarybill/react-native,lmorchard/react-native,Andreyco/react-native,dvcrn/react-native,alpz5566/react-native,yangshangde/react-native,gre/react-native,hike2008/react-native,ptomasroos/react-native,rkumar3147/react-native,exponentjs/rex,mqli/react-native,mjetek/react-native,jhen0409/react-native,yangshangde/react-native,DannyvanderJagt/react-native,kushal/react-native,charlesvinette/react-native,zenlambda/react-native,liuzechen/react-native,wdxgtsh/react-native,Swaagie/react-native,myntra/react-native,jadbox/react-native,exponent/react-native,sjchakrav/react-native,corbt/react-native,rwwarren/react-native,barakcoh/react-native,common2015/react-native,javache/react-native,programming086/react-native,lee-my/react-native,MonirAbuHilal/react-native,popovsh6/react-native,catalinmiron/react-native,jadbox/react-native,sekouperry/react-native,wustxing/react-native,YComputer/react-native,HealthyWealthy/react-native,mtford90/react-native,yjh0502/react-native,mchinyakov/react-native,appersonlabs/react-native,strwind/react-native,Heart2009/react-native,mrngoitall/react-native,abdelouahabb/react-native,jhen0409/react-native,MattFoley/react-native,andrewljohnson/react-native,vincentqiu/react-native,InterfaceInc/react-native,aaron-goshine/react-native,bowlofstew/react-native,Ehesp/react-native,kassens/react-native,iOSTestApps/react-native,rollokb/react-native,quuack/react-native,tsdl2013/react-native,Lohit9/react-native,appersonlabs/react-native,21451061/react-native,programming086/react-native,BossKing/react-native,dylanchann/react-native,jackeychens/react-native,negativetwelve/react-native,tmwoodson/react-native,Swaagie/react-native,InterfaceInc/react-native,pgavazzi/react-unity,yangchengwork/react-native,lgengsy/react-native,MetSystem/react-native,Jericho25/react-native,johnv315/react-native,soxunyi/react-native,darkrishabh/react-native,bradbumbalough/react-native,josebalius/react-native,carcer/react-native,Hkmu/react-native,nsimmons/react-native,qq644531343/react-native,ouyangwenfeng/react-native,Inner89/react-native,rwwarren/react-native,zvona/react-native,formatlos/react-native,jeromjoy/react-native,sekouperry/react-native,nsimmons/react-native,magnus-bergman/react-native,jabinwang/react-native,YComputer/react-native,manhvvhtth/react-native,cazacugmihai/react-native,nathanajah/react-native,bistacos/react-native,nevir/react-native,DannyvanderJagt/react-native,lanceharper/react-native,carcer/react-native,fw1121/react-native,edward/react-native,kotdark/react-native,shrimpy/react-native,dikaiosune/react-native,luqin/react-native,jekey/react-native,lzbSun/react-native,sheep902/react-native,hoastoolshop/react-native,jmhdez/react-native,tadeuzagallo/react-native,narlian/react-native,YComputer/react-native,corbt/react-native,MattFoley/react-native,hzgnpu/react-native,wangjiangwen/react-native,tarkus/react-native-appletv,ProjectSeptemberInc/react-native,androidgilbert/react-native,pickhardt/react-native,liufeigit/react-native,pglotov/react-native,huip/react-native,pandiaraj44/react-native,foghina/react-native,bsansouci/react-native,Reparadocs/react-native,kfiroo/react-native,sitexa/react-native,csatf/react-native,nickhargreaves/react-native,Andreyco/react-native,callstack-io/react-native,prathamesh-sonpatki/react-native,steben/react-native,IveWong/react-native,martinbigio/react-native,jhen0409/react-native,CntChen/react-native,gpbl/react-native,jekey/react-native,genome21/react-native,NZAOM/react-native,pengleelove/react-native,noif/react-native,adamkrell/react-native,glovebx/react-native,doochik/react-native,wdxgtsh/react-native,satya164/react-native,clooth/react-native,BretJohnson/react-native,nevir/react-native,ide/react-native,guanghuili/react-native,ChristopherSalam/react-native,jekey/react-native,CntChen/react-native,Reparadocs/react-native,ChristopherSalam/react-native,ordinarybill/react-native,edward/react-native,bimawa/react-native,eduvon0220/react-native,exponentjs/react-native,aifeld/react-native,michaelchucoder/react-native,naoufal/react-native,mcanthony/react-native,kassens/react-native,gabrielbellamy/react-native,ericvera/react-native,exponentjs/rex,Andreyco/react-native,patoroco/react-native,arbesfeld/react-native,wdxgtsh/react-native,unknownexception/react-native,Zagorakiss/react-native,janicduplessis/react-native,farazs/react-native,liduanw/react-native,Ehesp/react-native,gs-akhan/react-native,qingfeng/react-native,woshili1/react-native,peterp/react-native,cdlewis/react-native,madusankapremaratne/react-native,pcottle/react-native,clooth/react-native,shlomiatar/react-native,adamjmcgrath/react-native,alvarojoao/react-native,MetSystem/react-native,chiefr/react-native,popovsh6/react-native,harrykiselev/react-native,thstarshine/react-native,pallyoung/react-native,wangcan2014/react-native,onesfreedom/react-native,machard/react-native,bouk/react-native,sixtomay/react-native,chnfeeeeeef/react-native,dalinaum/react-native,jabinwang/react-native,onesfreedom/react-native,garrows/react-native,bradens/react-native,Lucifer-Kim/react-native,CodeLinkIO/react-native,shrutic/react-native,Serfenia/react-native,ChiMarvine/react-native,lmorchard/react-native,Rowandjj/react-native,pengleelove/react-native,pj4533/react-native,Srikanth4/react-native,eddiemonge/react-native,chetstone/react-native,MonirAbuHilal/react-native,PhilippKrone/react-native,shlomiatar/react-native,andrewljohnson/react-native,Intellicode/react-native,callstack-io/react-native,roy0914/react-native,ankitsinghania94/react-native,fish24k/react-native,madusankapremaratne/react-native,lprhodes/react-native,chnfeeeeeef/react-native,wangyzyoga/react-native,honger05/react-native,ktoh/react-native,vlrchtlt/react-native,Emilios1995/react-native,forcedotcom/react-native,csatf/react-native,spicyj/react-native,bradbumbalough/react-native,garrows/react-native,adrie4mac/react-native,chetstone/react-native,Tredsite/react-native,magnus-bergman/react-native,tgoldenberg/react-native,wustxing/react-native,rushidesai/react-native,CodeLinkIO/react-native,goodheart/react-native,jonesgithub/react-native,hanxiaofei/react-native,liduanw/react-native,jevakallio/react-native,leegilon/react-native,mcanthony/react-native,adamjmcgrath/react-native,callstack-io/react-native,catalinmiron/react-native,dabit3/react-native,zyvas/react-native,zhangxq5012/react-native,bouk/react-native,jackalchen/react-native,DenisIzmaylov/react-native,chiefr/react-native,wdxgtsh/react-native,kushal/react-native,mtford90/react-native,pgavazzi/react-unity,ldehai/react-native,ortutay/react-native,geoffreyfloyd/react-native,ptmt/react-native,averted/react-native,Jonekee/react-native,MattFoley/react-native,Applied-Duality/react-native,browniefed/react-native,chentsulin/react-native,gitim/react-native,yjyi/react-native,ptomasroos/react-native,eliagrady/react-native,Emilios1995/react-native,dizlexik/react-native,gilesvangruisen/react-native,rebeccahughes/react-native,jevakallio/react-native,PlexChat/react-native,sahat/react-native,wangziqiang/react-native,CntChen/react-native,Guardiannw/react-native,tsdl2013/react-native,huip/react-native,sarvex/react-native,mozillo/react-native,kentaromiura/react-native,slongwang/react-native,lokilandon/react-native,oren/react-native,bistacos/react-native,CodeLinkIO/react-native,cpunion/react-native,jmhdez/react-native,pglotov/react-native,chnfeeeeeef/react-native,pletcher/react-native,liufeigit/react-native,NishanthShankar/react-native,jasonals/react-native,Heart2009/react-native,exponentjs/rex,charlesvinette/react-native,noif/react-native,manhvvhtth/react-native,tgf229/react-native,liduanw/react-native,ModusCreateOrg/react-native,Shopify/react-native,yimouleng/react-native,Andreyco/react-native,programming086/react-native,edward/react-native,madusankapremaratne/react-native,kotdark/react-native,ultralame/react-native,jaggs6/react-native,unknownexception/react-native,DannyvanderJagt/react-native,fengshao0907/react-native,orenklein/react-native,guanghuili/react-native,Heart2009/react-native,lstNull/react-native,lgengsy/react-native,vagrantinoz/react-native,eduvon0220/react-native,sospartan/react-native,ChiMarvine/react-native,averted/react-native,chapinkapa/react-native,skatpgusskat/react-native,tszajna0/react-native,chsj1/react-native,cez213/react-native,Jonekee/react-native,puf/react-native,dizlexik/react-native,jaggs6/react-native,roy0914/react-native,chirag04/react-native,marlonandrade/react-native,kesha-antonov/react-native,jordanbyron/react-native,rodneyss/react-native,ModusCreateOrg/react-native,chacbumbum/react-native,pandiaraj44/react-native,xinthink/react-native,woshili1/react-native,Guardiannw/react-native,kassens/react-native,callstack-io/react-native,quuack/react-native,tarkus/react-native-appletv,hanxiaofei/react-native,ordinarybill/react-native,enaqx/react-native,PlexChat/react-native,booxood/react-native,daveenguyen/react-native,emodeqidao/react-native,adrie4mac/react-native,dvcrn/react-native,spyrx7/react-native,Serfenia/react-native,southasia/react-native,jackalchen/react-native,srounce/react-native,shrutic123/react-native,ajwhite/react-native,jackalchen/react-native,hengcj/react-native,ChristianHersevoort/react-native,jeffchienzabinet/react-native,folist/react-native,DenisIzmaylov/react-native,pglotov/react-native,sahat/react-native,dabit3/react-native,ouyangwenfeng/react-native,thotegowda/react-native,kesha-antonov/react-native,charlesvinette/react-native,aroth/react-native,wangcan2014/react-native,darkrishabh/react-native,HSFGitHub/react-native,jmstout/react-native,christopherdro/react-native,sahat/react-native,xiayz/react-native,josebalius/react-native,jeanblanchard/react-native,wangziqiang/react-native,Tredsite/react-native,sheep902/react-native,glovebx/react-native,nsimmons/react-native,folist/react-native,mrspeaker/react-native,Ehesp/react-native,ChiMarvine/react-native,spicyj/react-native,exponent/react-native,liuzechen/react-native,farazs/react-native,bowlofstew/react-native,wlrhnh-David/react-native,woshili1/react-native,zhangwei001/react-native,imDangerous/react-native,cazacugmihai/react-native,imWildCat/react-native,steveleec/react-native,Emilios1995/react-native,tsjing/react-native,pandiaraj44/react-native,southasia/react-native,Intellicode/react-native,lokilandon/react-native,bogdantmm92/react-native,vjeux/react-native,mchinyakov/react-native,xinthink/react-native,richardgill/react-native,JackLeeMing/react-native,lmorchard/react-native,iOSTestApps/react-native,sdiaz/react-native,yangchengwork/react-native,hoangpham95/react-native,southasia/react-native,sospartan/react-native,xinthink/react-native,arbesfeld/react-native,sahat/react-native,kujohn/react-native,hengcj/react-native,Livyli/react-native,myntra/react-native,ludaye123/react-native,mozillo/react-native,ivanph/react-native,kesha-antonov/react-native,mozillo/react-native,jeanblanchard/react-native,yangchengwork/react-native,charmingzuo/react-native,ehd/react-native,affinityis/react-native,taydakov/react-native,ronak301/react-native,JulienThibeaut/react-native,Loke155/react-native,gs-akhan/react-native,magnus-bergman/react-native,DerayGa/react-native,facebook/react-native,kundanjadhav/react-native,F2EVarMan/react-native,ultralame/react-native,orenklein/react-native,MonirAbuHilal/react-native,johnv315/react-native,zuolangguo/react-native,jekey/react-native,lelandrichardson/react-native,donyu/react-native,carcer/react-native,alantrrs/react-native,levic92/react-native,ordinarybill/react-native,tadeuzagallo/react-native,ptmt/react-native-macos,InterfaceInc/react-native,almost/react-native,zhangxq5012/react-native,aaron-goshine/react-native,ndejesus1227/react-native,huip/react-native,catalinmiron/react-native,imWildCat/react-native,skevy/react-native,rainkong/react-native,dimoge/react-native,wangyzyoga/react-native,JackLeeMing/react-native,pickhardt/react-native,liuhong1happy/react-native,kotdark/react-native,nktpro/react-native,Wingie/react-native,Furzikov/react-native,rickbeerendonk/react-native,liduanw/react-native,wlrhnh-David/react-native,compulim/react-native,lendup/react-native,csatf/react-native,aroth/react-native,chsj1/react-native,nevir/react-native,dalinaum/react-native,ktoh/react-native,callstack-io/react-native,rainkong/react-native,WilliamRen/react-native,sunblaze/react-native,tszajna0/react-native,narlian/react-native,lloydho/react-native,charmingzuo/react-native,jasonnoahchoi/react-native,ouyangwenfeng/react-native,hesling/react-native,patoroco/react-native,sekouperry/react-native,misakuo/react-native,jbaumbach/react-native,yelled3/react-native,qingfeng/react-native,jonesgithub/react-native,puf/react-native,rainkong/react-native,wildKids/react-native,martinbigio/react-native,aziz-boudi4/react-native,udnisap/react-native,zhangwei001/react-native,yiminghe/react-native,geoffreyfloyd/react-native,charlesvinette/react-native,kushal/react-native,yutail/react-native,Shopify/react-native,Jericho25/react-native,bouk/react-native,hoastoolshop/react-native,dut3062796s/react-native,gabrielbellamy/react-native,wangjiangwen/react-native,wangjiangwen/react-native,mbrock/react-native,stan229/react-native,pjcabrera/react-native,kfiroo/react-native,eduvon0220/react-native,kamronbatman/react-native,wjb12/react-native,yjh0502/react-native,jadbox/react-native,daveenguyen/react-native,chengky/react-native,kfiroo/react-native,gilesvangruisen/react-native,wildKids/react-native,JulienThibeaut/react-native,happypancake/react-native,iodine/react-native,shrutic/react-native,negativetwelve/react-native,prathamesh-sonpatki/react-native,Hkmu/react-native,jmhdez/react-native,chirag04/react-native,bogdantmm92/react-native,hoangpham95/react-native,dikaiosune/react-native,lanceharper/react-native,yushiwo/react-native,martinbigio/react-native,code0100fun/react-native,jevakallio/react-native,waynett/react-native,milieu/react-native,YinshawnRao/react-native,xxccll/react-native,almost/react-native,narlian/react-native,ehd/react-native,cdlewis/react-native,formatlos/react-native,code0100fun/react-native,dvcrn/react-native,ljhsai/react-native,YinshawnRao/react-native,gabrielbellamy/react-native,aifeld/react-native,cpunion/react-native,manhvvhtth/react-native,Flickster42490/react-native,strwind/react-native,liuhong1happy/react-native,quyixia/react-native,negativetwelve/react-native,yamill/react-native,BretJohnson/react-native,lucyywang/react-native,xiaoking/react-native,folist/react-native,xiayz/react-native,ChristianHersevoort/react-native,pgavazzi/react-unity,dabit3/react-native,levic92/react-native,jmhdez/react-native,insionng/react-native,jeffchienzabinet/react-native,mozillo/react-native,chapinkapa/react-native,21451061/react-native,cez213/react-native,ndejesus1227/react-native,dralletje/react-native,steveleec/react-native,alantrrs/react-native,roy0914/react-native,tsjing/react-native,futbalguy/react-native,onesfreedom/react-native,YComputer/react-native,iodine/react-native,puf/react-native,supercocoa/react-native,mozillo/react-native,DenisIzmaylov/react-native,levic92/react-native,csatf/react-native,gre/react-native,jeanblanchard/react-native,zenlambda/react-native,eduvon0220/react-native,futbalguy/react-native,mrspeaker/react-native,roy0914/react-native,edward/react-native,popovsh6/react-native,farazs/react-native,lmorchard/react-native,abdelouahabb/react-native,popovsh6/react-native,trueblue2704/react-native,wjb12/react-native,mironiasty/react-native,elliottsj/react-native,ludaye123/react-native,soxunyi/react-native,monyxie/react-native,dut3062796s/react-native,jmhdez/react-native,simple88/react-native,ouyangwenfeng/react-native,sitexa/react-native,billhello/react-native,ProjectSeptemberInc/react-native,lelandrichardson/react-native,dikaiosune/react-native,Shopify/react-native,aifeld/react-native,yusefnapora/react-native,xxccll/react-native,zdsiyan/react-native,charmingzuo/react-native,bradbumbalough/react-native,bright-sparks/react-native,mqli/react-native,tgoldenberg/react-native,slongwang/react-native,peterp/react-native,negativetwelve/react-native,andersryanc/react-native,JoeStanton/react-native,slongwang/react-native,mway08/react-native,rodneyss/react-native,dvcrn/react-native,corbt/react-native,gs-akhan/react-native,barakcoh/react-native,Wingie/react-native,wangjiangwen/react-native,catalinmiron/react-native,javache/react-native,nanpian/react-native,mukesh-kumar1905/react-native,heyjim89/react-native,dabit3/react-native,lprhodes/react-native,jaredly/react-native,adamkrell/react-native,dubert/react-native,CntChen/react-native,cmhsu/react-native,simple88/react-native,judastree/react-native,judastree/react-native,lightsofapollo/react-native,dylanchann/react-native,javache/react-native,Lohit9/react-native,kesha-antonov/react-native,chirag04/react-native,aljs/react-native,forcedotcom/react-native,ChristianHersevoort/react-native,billhello/react-native,Wingie/react-native,pengleelove/react-native,cazacugmihai/react-native,CodeLinkIO/react-native,ivanph/react-native,noif/react-native,booxood/react-native,Guardiannw/react-native,alvarojoao/react-native,ludaye123/react-native,southasia/react-native,chacbumbum/react-native,hengcj/react-native,leegilon/react-native,Intellicode/react-native,Purii/react-native,folist/react-native,dut3062796s/react-native,bouk/react-native,xiayz/react-native,dralletje/react-native,nsimmons/react-native,fw1121/react-native,NunoEdgarGub1/react-native,tszajna0/react-native,a2/react-native,rickbeerendonk/react-native,jeffchienzabinet/react-native,maskkid/react-native,lelandrichardson/react-native,aifeld/react-native,compulim/react-native,ajwhite/react-native,eliagrady/react-native,magnus-bergman/react-native,abdelouahabb/react-native,gauribhoite/react-native,hoangpham95/react-native,vincentqiu/react-native,srounce/react-native,liubko/react-native,lee-my/react-native,rickbeerendonk/react-native,Esdeath/react-native,shadow000902/react-native,mironiasty/react-native,waynett/react-native,frantic/react-native,JulienThibeaut/react-native,lgengsy/react-native,sixtomay/react-native,forcedotcom/react-native,chengky/react-native,rantianhua/react-native,ehd/react-native,Flickster42490/react-native,Heart2009/react-native,soxunyi/react-native,adamterlson/react-native,mcanthony/react-native,Loke155/react-native,gegaosong/react-native,bowlofstew/react-native,philikon/react-native,evilemon/react-native,daveenguyen/react-native,skevy/react-native,mironiasty/react-native,hydraulic/react-native,DanielMSchmidt/react-native,wesley1001/react-native,jordanbyron/react-native,eddiemonge/react-native,dfala/react-native,yjyi/react-native,nktpro/react-native,rainkong/react-native,yushiwo/react-native,ortutay/react-native,eddiemonge/react-native,chirag04/react-native,krock01/react-native,ndejesus1227/react-native,geoffreyfloyd/react-native,hammerandchisel/react-native,csudanthi/react-native,jhen0409/react-native,philonpang/react-native,tszajna0/react-native,imWildCat/react-native,jasonnoahchoi/react-native,tsdl2013/react-native,hayeah/react-native,formatlos/react-native,bowlofstew/react-native,happypancake/react-native,dubert/react-native,sahrens/react-native,sekouperry/react-native,gegaosong/react-native,ChiMarvine/react-native,clozr/react-native,cmhsu/react-native,ChristianHersevoort/react-native,cxfeng1/react-native,puf/react-native,mqli/react-native,olivierlesnicki/react-native,genome21/react-native,spicyj/react-native,thotegowda/react-native,puf/react-native,browniefed/react-native,wenpkpk/react-native,jasonals/react-native,chentsulin/react-native,chapinkapa/react-native,nathanajah/react-native,fish24k/react-native,salanki/react-native,compulim/react-native,DannyvanderJagt/react-native,tgoldenberg/react-native,mariusbutuc/react-native,HealthyWealthy/react-native,maskkid/react-native,heyjim89/react-native,callstack-io/react-native,zyvas/react-native,zvona/react-native,gegaosong/react-native,kesha-antonov/react-native,Hkmu/react-native,spyrx7/react-native,pvinis/react-native-desktop,lokilandon/react-native,krock01/react-native,Jericho25/react-native,bimawa/react-native,adamjmcgrath/react-native,qingsong-xu/react-native,LytayTOUCH/react-native,eduardinni/react-native,pitatensai/react-native,DenisIzmaylov/react-native,sonnylazuardi/react-native,cpunion/react-native,leopardpan/react-native,rwwarren/react-native,glovebx/react-native,gitim/react-native,hydraulic/react-native,huip/react-native,jasonnoahchoi/react-native,jeanblanchard/react-native,pvinis/react-native-desktop,yjyi/react-native,liubko/react-native,FionaWong/react-native,hammerandchisel/react-native,charlesvinette/react-native,hoastoolshop/react-native,F2EVarMan/react-native,foghina/react-native,ChristianHersevoort/react-native,zenlambda/react-native,wesley1001/react-native,gre/react-native,MonirAbuHilal/react-native,xiaoking/react-native,sarvex/react-native,stan229/react-native,jevakallio/react-native,chsj1/react-native,gilesvangruisen/react-native,pandiaraj44/react-native,Maxwell2022/react-native,Bronts/react-native,hoastoolshop/react-native,hanxiaofei/react-native,ptmt/react-native-macos,zhaosichao/react-native,browniefed/react-native,cez213/react-native,yjh0502/react-native,mosch/react-native,aaron-goshine/react-native,codejet/react-native,DerayGa/react-native,Purii/react-native,iodine/react-native,honger05/react-native,foghina/react-native,alantrrs/react-native,sekouperry/react-native,sixtomay/react-native,vincentqiu/react-native,KJlmfe/react-native,billhello/react-native,negativetwelve/react-native,rxb/react-native,mway08/react-native,bestwpw/react-native,sahrens/react-native,hassanabidpk/react-native,1988fei/react-native,taydakov/react-native,genome21/react-native,ericvera/react-native,maskkid/react-native,zhangwei001/react-native,oren/react-native,Heart2009/react-native,htc2u/react-native,facebook/react-native,pitatensai/react-native,ide/react-native,rantianhua/react-native,Applied-Duality/react-native,bsansouci/react-native,Guardiannw/react-native,androidgilbert/react-native,shrutic123/react-native,noif/react-native,shadow000902/react-native,Emilios1995/react-native,csudanthi/react-native,quyixia/react-native,liduanw/react-native,Serfenia/react-native,jeffchienzabinet/react-native,boopathi/react-native,nsimmons/react-native,Bronts/react-native,enaqx/react-native,janicduplessis/react-native,adamterlson/react-native,boopathi/react-native,HealthyWealthy/react-native,thstarshine/react-native,forcedotcom/react-native,wustxing/react-native,charlesvinette/react-native,Applied-Duality/react-native,kamronbatman/react-native,brentvatne/react-native,hesling/react-native,sghiassy/react-native,ajwhite/react-native,mihaigiurgeanu/react-native,carcer/react-native,yelled3/react-native,IveWong/react-native,darrylblake/react-native,strwind/react-native,NZAOM/react-native,timfpark/react-native,darrylblake/react-native,dylanchann/react-native,facebook/react-native,KJlmfe/react-native,miracle2k/react-native,mway08/react-native,trueblue2704/react-native,pcottle/react-native,JulienThibeaut/react-native,mbrock/react-native,IveWong/react-native,judastree/react-native,BossKing/react-native,yimouleng/react-native,tarkus/react-native-appletv,MetSystem/react-native,christer155/react-native,JasonZ321/react-native,soulcm/react-native,monyxie/react-native,mironiasty/react-native,mosch/react-native,ljhsai/react-native,srounce/react-native,ramoslin02/react-native,sahat/react-native,Lucifer-Kim/react-native,leegilon/react-native,sudhirj/react-native,lgengsy/react-native,vagrantinoz/react-native,onesfreedom/react-native,ortutay/react-native,gre/react-native,sheep902/react-native,Purii/react-native,jaggs6/react-native,hike2008/react-native,Heart2009/react-native,wlrhnh-David/react-native,cpunion/react-native,ldehai/react-native,woshili1/react-native,spicyj/react-native,ajwhite/react-native,mrspeaker/react-native,donyu/react-native,madusankapremaratne/react-native,PlexChat/react-native,sheep902/react-native,gauribhoite/react-native,richardgill/react-native,shrutic123/react-native,bimawa/react-native,Jonekee/react-native,JoeStanton/react-native,chrisbutcher/react-native,eduardinni/react-native,hwsyy/react-native,shadow000902/react-native,pgavazzi/react-unity,1988fei/react-native,wdxgtsh/react-native,liubko/react-native,alin23/react-native,Andreyco/react-native,lgengsy/react-native,pairyo/react-native,sekouperry/react-native,jasonnoahchoi/react-native,wdxgtsh/react-native,kushal/react-native,garrows/react-native,prathamesh-sonpatki/react-native,LytayTOUCH/react-native,sheep902/react-native,hanxiaofei/react-native,clozr/react-native,TChengZ/react-native,ktoh/react-native,jmstout/react-native,tmwoodson/react-native,guanghuili/react-native,Swaagie/react-native,tarkus/react-native-appletv,shrutic/react-native,gpbl/react-native,liufeigit/react-native,waynett/react-native,yutail/react-native,rwwarren/react-native,strwind/react-native,soxunyi/react-native,enaqx/react-native,bestwpw/react-native,ramoslin02/react-native,Srikanth4/react-native,zhaosichao/react-native,hassanabidpk/react-native,imDangerous/react-native,lstNull/react-native,alpz5566/react-native,qq644531343/react-native,Rowandjj/react-native,mariusbutuc/react-native,salanki/react-native,FionaWong/react-native,rickbeerendonk/react-native,apprennet/react-native,Loke155/react-native,shrimpy/react-native,yjh0502/react-native,JackLeeMing/react-native,LytayTOUCH/react-native,cdlewis/react-native,facebook/react-native,ericvera/react-native,zvona/react-native,zenlambda/react-native,rxb/react-native,timfpark/react-native,andersryanc/react-native,PlexChat/react-native,donyu/react-native,skatpgusskat/react-native,imDangerous/react-native,lgengsy/react-native,garrows/react-native,christer155/react-native,trueblue2704/react-native,F2EVarMan/react-native,heyjim89/react-native,Hkmu/react-native,andersryanc/react-native,lloydho/react-native,zhaosichao/react-native,kushal/react-native,myntra/react-native,eduvon0220/react-native,alin23/react-native,elliottsj/react-native,chrisbutcher/react-native,simple88/react-native,janicduplessis/react-native,WilliamRen/react-native,qingfeng/react-native,philonpang/react-native,chiefr/react-native,nathanajah/react-native,esauter5/react-native,zdsiyan/react-native,mcanthony/react-native,levic92/react-native,jmstout/react-native,ljhsai/react-native,christer155/react-native,chapinkapa/react-native,southasia/react-native,yutail/react-native,mironiasty/react-native,Wingie/react-native,philikon/react-native,tgoldenberg/react-native,thotegowda/react-native,hoangpham95/react-native,ChristopherSalam/react-native,olivierlesnicki/react-native,johnv315/react-native,JoeStanton/react-native,ipmobiletech/react-native,nbcnews/react-native,simple88/react-native,mozillo/react-native,Ehesp/react-native,alpz5566/react-native,exponentjs/react-native,satya164/react-native,jabinwang/react-native,zhaosichao/react-native,miracle2k/react-native,FionaWong/react-native,liuhong1happy/react-native,ProjectSeptemberInc/react-native,chentsulin/react-native,21451061/react-native,htc2u/react-native,supercocoa/react-native,guanghuili/react-native,lendup/react-native,myntra/react-native,DanielMSchmidt/react-native,eliagrady/react-native,bradbumbalough/react-native,janicduplessis/react-native,forcedotcom/react-native,zvona/react-native,tgoldenberg/react-native,zvona/react-native,tgf229/react-native,kundanjadhav/react-native,yzarubin/react-native,DerayGa/react-native,patoroco/react-native,dubert/react-native,billhello/react-native,quuack/react-native,marlonandrade/react-native,rantianhua/react-native,imjerrybao/react-native,misakuo/react-native,irisli/react-native,ide/react-native,tgriesser/react-native,chrisbutcher/react-native,chenbk85/react-native,bright-sparks/react-native,charlesvinette/react-native,alin23/react-native,hayeah/react-native,ptmt/react-native,folist/react-native,jibonpab/react-native,tahnok/react-native,TChengZ/react-native,mjetek/react-native,Bhullnatik/react-native,rushidesai/react-native,jasonals/react-native,compulim/react-native,WilliamRen/react-native,onesfreedom/react-native,pandiaraj44/react-native,adamjmcgrath/react-native,common2015/react-native,JulienThibeaut/react-native,fengshao0907/react-native,JulienThibeaut/react-native,doochik/react-native,ivanph/react-native,garydonovan/react-native,doochik/react-native,philonpang/react-native,darkrishabh/react-native,common2015/react-native,andrewljohnson/react-native,ptmt/react-native-macos,qingsong-xu/react-native,skatpgusskat/react-native,pairyo/react-native,johnv315/react-native,formatlos/react-native,chirag04/react-native,leopardpan/react-native,RGKzhanglei/react-native,Emilios1995/react-native,liubko/react-native,TChengZ/react-native,onesfreedom/react-native,yutail/react-native,ivanph/react-native,ModusCreateOrg/react-native,makadaw/react-native,tadeuzagallo/react-native,adamjmcgrath/react-native,lightsofapollo/react-native,qq644531343/react-native,martinbigio/react-native,pvinis/react-native-desktop,Suninus/react-native,misakuo/react-native,HSFGitHub/react-native,wlrhnh-David/react-native,zuolangguo/react-native,imDangerous/react-native,orenklein/react-native,affinityis/react-native,Zagorakiss/react-native,dimoge/react-native,Inner89/react-native,shrimpy/react-native,chacbumbum/react-native,mukesh-kumar1905/react-native,kentaromiura/react-native,ankitsinghania94/react-native,salanki/react-native,sospartan/react-native,lmorchard/react-native,waynett/react-native,farazs/react-native,esauter5/react-native,hammerandchisel/react-native,sjchakrav/react-native,luqin/react-native,jhen0409/react-native,tgf229/react-native,madusankapremaratne/react-native,ptmt/react-native,Zagorakiss/react-native,jasonals/react-native,yiminghe/react-native,vagrantinoz/react-native,dvcrn/react-native,jaredly/react-native,JackLeeMing/react-native,mrngoitall/react-native,Srikanth4/react-native,tahnok/react-native,bouk/react-native,jeanblanchard/react-native,Tredsite/react-native,luqin/react-native,rxb/react-native,tarkus/react-native-appletv,charmingzuo/react-native,daveenguyen/react-native,peterp/react-native,Zagorakiss/react-native,chetstone/react-native,hike2008/react-native,ipmobiletech/react-native,charmingzuo/react-native,irisli/react-native,sunblaze/react-native,liuzechen/react-native,tahnok/react-native,huangsongyan/react-native,goodheart/react-native,RGKzhanglei/react-native,mcrooks88/react-native,bradbumbalough/react-native,martinbigio/react-native,wangcan2014/react-native,ramoslin02/react-native,rushidesai/react-native,imjerrybao/react-native,hassanabidpk/react-native,Purii/react-native,jabinwang/react-native,quuack/react-native,sghiassy/react-native,wlrhnh-David/react-native,jaredly/react-native,harrykiselev/react-native,DerayGa/react-native,abdelouahabb/react-native,1988fei/react-native,Serfenia/react-native,browniefed/react-native,yutail/react-native,hengcj/react-native,csudanthi/react-native,mjetek/react-native,jibonpab/react-native,rwwarren/react-native,yelled3/react-native,InterfaceInc/react-native,levic92/react-native,rodneyss/react-native,programming086/react-native,j27cai/react-native,southasia/react-native,shadow000902/react-native,ptomasroos/react-native,spicyj/react-native,thotegowda/react-native,mozillo/react-native,mjetek/react-native,lmorchard/react-native,jackeychens/react-native,oren/react-native,Lohit9/react-native,codejet/react-native,RGKzhanglei/react-native,stonegithubs/react-native,dubert/react-native,evansolomon/react-native,programming086/react-native,zhangwei001/react-native,nickhudkins/react-native,mcanthony/react-native,yimouleng/react-native,mjetek/react-native,YotrolZ/react-native,tgf229/react-native,arbesfeld/react-native,PhilippKrone/react-native,Suninus/react-native,darkrishabh/react-native,patoroco/react-native,Poplava/react-native,adamkrell/react-native,Livyli/react-native,Jonekee/react-native,pandiaraj44/react-native,orenklein/react-native,nbcnews/react-native,corbt/react-native,barakcoh/react-native,Hkmu/react-native,eduardinni/react-native,aziz-boudi4/react-native,lprhodes/react-native,Intellicode/react-native,ipmobiletech/react-native,hengcj/react-native,andrewljohnson/react-native,sekouperry/react-native,hesling/react-native,Tredsite/react-native,tarkus/react-native-appletv,lanceharper/react-native,ktoh/react-native,sudhirj/react-native,tgoldenberg/react-native,xiangjuntang/react-native,pjcabrera/react-native,wdxgtsh/react-native,marlonandrade/react-native,exponentjs/react-native,apprennet/react-native,yimouleng/react-native,imjerrybao/react-native,christopherdro/react-native,hharnisc/react-native,yamill/react-native,alin23/react-native,chapinkapa/react-native,soulcm/react-native,NishanthShankar/react-native,neeraj-singh/react-native,aljs/react-native,leegilon/react-native,lightsofapollo/react-native,insionng/react-native,alin23/react-native,Jonekee/react-native,bsansouci/react-native,mcanthony/react-native,doochik/react-native,jackalchen/react-native,lprhodes/react-native,dut3062796s/react-native,vlrchtlt/react-native,yutail/react-native,eddiemonge/react-native,gauribhoite/react-native,tsjing/react-native,pickhardt/react-native,monyxie/react-native,mbrock/react-native,eliagrady/react-native,yjh0502/react-native,philonpang/react-native,hharnisc/react-native,alinz/react-native,ehd/react-native,DenisIzmaylov/react-native,bsansouci/react-native,kundanjadhav/react-native,steben/react-native,a2/react-native,nickhargreaves/react-native,ordinarybill/react-native,a2/react-native,rebeccahughes/react-native,Swaagie/react-native,clozr/react-native,bistacos/react-native,irisli/react-native,garydonovan/react-native,soulcm/react-native,sheep902/react-native,CntChen/react-native,myntra/react-native,andrewljohnson/react-native,philonpang/react-native,FionaWong/react-native,iodine/react-native,alinz/react-native,strwind/react-native,aljs/react-native,pgavazzi/react-unity,jabinwang/react-native,huip/react-native,Ehesp/react-native,liangmingjie/react-native,cez213/react-native,alantrrs/react-native,huangsongyan/react-native,kujohn/react-native,ktoh/react-native,ldehai/react-native,pairyo/react-native,arthuralee/react-native,geoffreyfloyd/react-native,happypancake/react-native,nsimmons/react-native,soxunyi/react-native,Swaagie/react-native,YinshawnRao/react-native,lloydho/react-native,ChristianHersevoort/react-native,pengleelove/react-native,cpunion/react-native,chengky/react-native,goodheart/react-native,charmingzuo/react-native,dylanchann/react-native,adamterlson/react-native,madusankapremaratne/react-native,ericvera/react-native,gegaosong/react-native,hike2008/react-native,Srikanth4/react-native,hharnisc/react-native,philikon/react-native,shadow000902/react-native,Serfenia/react-native,dfala/react-native,NunoEdgarGub1/react-native,tahnok/react-native,MonirAbuHilal/react-native,bsansouci/react-native,shinate/react-native,jabinwang/react-native,gilesvangruisen/react-native,nickhargreaves/react-native,nickhudkins/react-native,KJlmfe/react-native,christopherdro/react-native,mway08/react-native,wjb12/react-native,lucyywang/react-native,Suninus/react-native,xiaoking/react-native,gre/react-native,cosmith/react-native,popovsh6/react-native,shadow000902/react-native,bodefuwa/react-native,hwsyy/react-native,skevy/react-native,satya164/react-native,taydakov/react-native,averted/react-native,affinityis/react-native,darkrishabh/react-native,zdsiyan/react-native,PlexChat/react-native,orenklein/react-native,qq644531343/react-native,jaggs6/react-native,vincentqiu/react-native,hwsyy/react-native,sarvex/react-native,shrutic123/react-native,alantrrs/react-native,yelled3/react-native,pglotov/react-native,beni55/react-native,fish24k/react-native,shrutic123/react-native,patoroco/react-native,21451061/react-native,martinbigio/react-native,pitatensai/react-native,mqli/react-native,mway08/react-native,lanceharper/react-native,hharnisc/react-native,garydonovan/react-native,yiminghe/react-native,woshili1/react-native,yangshangde/react-native,myntra/react-native,bradbumbalough/react-native,liuzechen/react-native,dalinaum/react-native,xiaoking/react-native,chnfeeeeeef/react-native,dut3062796s/react-native,eduardinni/react-native,wildKids/react-native,ldehai/react-native,affinityis/react-native,hengcj/react-native,androidgilbert/react-native,tgriesser/react-native,alantrrs/react-native,xxccll/react-native,beni55/react-native,mcrooks88/react-native,HealthyWealthy/react-native,yamill/react-native,tahnok/react-native,wangziqiang/react-native,quuack/react-native,arbesfeld/react-native,alin23/react-native,aziz-boudi4/react-native,richardgill/react-native,frantic/react-native,chetstone/react-native,kushal/react-native,sixtomay/react-native,chacbumbum/react-native,janicduplessis/react-native,hammerandchisel/react-native,cosmith/react-native,dralletje/react-native,zdsiyan/react-native,tszajna0/react-native,arthuralee/react-native,tmwoodson/react-native,Rowandjj/react-native,NZAOM/react-native,j27cai/react-native,brentvatne/react-native,jonesgithub/react-native,noif/react-native,fw1121/react-native,bradbumbalough/react-native,liufeigit/react-native,mcanthony/react-native,YinshawnRao/react-native,jbaumbach/react-native,YueRuo/react-native,sahat/react-native,futbalguy/react-native,salanki/react-native,jeromjoy/react-native,Intellicode/react-native,liduanw/react-native,PhilippKrone/react-native,christer155/react-native,jeromjoy/react-native,Guardiannw/react-native,pitatensai/react-native,wangziqiang/react-native,quyixia/react-native,nathanajah/react-native,liangmingjie/react-native,Furzikov/react-native,iodine/react-native,NZAOM/react-native,brentvatne/react-native,Srikanth4/react-native,lgengsy/react-native,chrisbutcher/react-native,adamterlson/react-native,negativetwelve/react-native,aifeld/react-native,yiminghe/react-native,mjetek/react-native,patoroco/react-native,ipmobiletech/react-native,esauter5/react-native,garydonovan/react-native,jadbox/react-native,imDangerous/react-native,Lohit9/react-native,rkumar3147/react-native,aroth/react-native,dfala/react-native,MetSystem/react-native,wustxing/react-native,programming086/react-native,mtford90/react-native,rickbeerendonk/react-native,appersonlabs/react-native,srounce/react-native,machard/react-native,stan229/react-native,androidgilbert/react-native,trueblue2704/react-native,mcanthony/react-native,andrewljohnson/react-native,imWildCat/react-native,liangmingjie/react-native,yzarubin/react-native,bowlofstew/react-native,Shopify/react-native,sitexa/react-native,charlesvinette/react-native,yiminghe/react-native,machard/react-native,honger05/react-native,aaron-goshine/react-native,barakcoh/react-native,YinshawnRao/react-native,luqin/react-native,exponentjs/react-native,lokilandon/react-native,barakcoh/react-native,hoastoolshop/react-native,chetstone/react-native,ProjectSeptemberInc/react-native,rxb/react-native,tsjing/react-native,myntra/react-native,shinate/react-native,wangjiangwen/react-native,facebook/react-native,formatlos/react-native,Livyli/react-native,dubert/react-native,mtford90/react-native,dikaiosune/react-native,jevakallio/react-native,imjerrybao/react-native,PhilippKrone/react-native,machard/react-native,rwwarren/react-native,liuzechen/react-native,ipmobiletech/react-native,apprennet/react-native,ptomasroos/react-native,roth1002/react-native,tadeuzagallo/react-native,nickhudkins/react-native,ouyangwenfeng/react-native,hayeah/react-native,mrngoitall/react-native,yzarubin/react-native,honger05/react-native,wangcan2014/react-native,yiminghe/react-native,jekey/react-native,lwansbrough/react-native,skevy/react-native,yzarubin/react-native,adamkrell/react-native,naoufal/react-native,sudhirj/react-native,orenklein/react-native,NunoEdgarGub1/react-native,spicyj/react-native,nanpian/react-native,threepointone/react-native-1,milieu/react-native,RGKzhanglei/react-native,rollokb/react-native,chengky/react-native,aziz-boudi4/react-native,doochik/react-native,shrutic/react-native,IveWong/react-native,irisli/react-native,gpbl/react-native,edward/react-native,wangyzyoga/react-native,michaelchucoder/react-native,ankitsinghania94/react-native,alpz5566/react-native,rkumar3147/react-native,brentvatne/react-native,ivanph/react-native,oren/react-native,mrngoitall/react-native,code0100fun/react-native,Esdeath/react-native,lwansbrough/react-native,kotdark/react-native,HealthyWealthy/react-native,thstarshine/react-native,tsjing/react-native,IveWong/react-native,jevakallio/react-native,j27cai/react-native,philikon/react-native,sudhirj/react-native,ordinarybill/react-native,androidgilbert/react-native,daveenguyen/react-native,daveenguyen/react-native,vagrantinoz/react-native,sahrens/react-native,jeromjoy/react-native,ndejesus1227/react-native,ajwhite/react-native,Wingie/react-native,tszajna0/react-native,martinbigio/react-native,miracle2k/react-native,csudanthi/react-native,devknoll/react-native,pandiaraj44/react-native,sjchakrav/react-native,eduardinni/react-native,eddiemonge/react-native,wesley1001/react-native,misakuo/react-native,sdiaz/react-native,imjerrybao/react-native,LytayTOUCH/react-native,wangcan2014/react-native,cxfeng1/react-native,neeraj-singh/react-native,tahnok/react-native,lloydho/react-native,Tredsite/react-native,sghiassy/react-native,ajwhite/react-native,pletcher/react-native,zhangxq5012/react-native,wesley1001/react-native,dizlexik/react-native,NunoEdgarGub1/react-native,urvashi01/react-native,pvinis/react-native-desktop,bimawa/react-native,liuhong1happy/react-native,charmingzuo/react-native,wesley1001/react-native,emodeqidao/react-native,andersryanc/react-native,neeraj-singh/react-native,gegaosong/react-native,ortutay/react-native,stonegithubs/react-native,andersryanc/react-native,YueRuo/react-native,liangmingjie/react-native,shrutic/react-native,heyjim89/react-native,kesha-antonov/react-native,sghiassy/react-native,quuack/react-native,lee-my/react-native,billhello/react-native,CntChen/react-native,quyixia/react-native,Jericho25/react-native,pitatensai/react-native,liangmingjie/react-native,prathamesh-sonpatki/react-native,liubko/react-native,Livyli/react-native,clooth/react-native,jackalchen/react-native,NunoEdgarGub1/react-native,glovebx/react-native,genome21/react-native,sdiaz/react-native,leeyeh/react-native,thotegowda/react-native,neeraj-singh/react-native,hwsyy/react-native,MattFoley/react-native,ultralame/react-native,hoastoolshop/react-native,jibonpab/react-native,Maxwell2022/react-native,DannyvanderJagt/react-native,timfpark/react-native,shrutic/react-native,RGKzhanglei/react-native,TChengZ/react-native,yangchengwork/react-native,daveenguyen/react-native,farazs/react-native,mihaigiurgeanu/react-native,thstarshine/react-native,edward/react-native,boopathi/react-native,Applied-Duality/react-native,YueRuo/react-native,arthuralee/react-native,chsj1/react-native,dabit3/react-native,xiaoking/react-native,lloydho/react-native,csatf/react-native,zhaosichao/react-native,dimoge/react-native,catalinmiron/react-native,roth1002/react-native,jonesgithub/react-native,mrspeaker/react-native,prathamesh-sonpatki/react-native,ptomasroos/react-native,trueblue2704/react-native,almost/react-native,hike2008/react-native,Ehesp/react-native,WilliamRen/react-native,DannyvanderJagt/react-native,NishanthShankar/react-native,negativetwelve/react-native,zhangwei001/react-native,htc2u/react-native,ptmt/react-native,exponent/react-native,yushiwo/react-native,jibonpab/react-native,Bronts/react-native,zyvas/react-native,jibonpab/react-native,ankitsinghania94/react-native,ktoh/react-native,chnfeeeeeef/react-native,alantrrs/react-native,jaggs6/react-native,qingsong-xu/react-native,YotrolZ/react-native,andersryanc/react-native,PlexChat/react-native,dfala/react-native,happypancake/react-native,Bhullnatik/react-native,guanghuili/react-native,zenlambda/react-native,evilemon/react-native,mqli/react-native,jackeychens/react-native,wildKids/react-native,catalinmiron/react-native,MonirAbuHilal/react-native,geoffreyfloyd/react-native,sghiassy/react-native,xxccll/react-native,cosmith/react-native,HSFGitHub/react-native,DanielMSchmidt/react-native,mukesh-kumar1905/react-native,makadaw/react-native,yusefnapora/react-native,jackeychens/react-native,christopherdro/react-native,exponent/react-native,adrie4mac/react-native,jevakallio/react-native,sghiassy/react-native,hwsyy/react-native,sghiassy/react-native,arthuralee/react-native,liduanw/react-native,skevy/react-native,krock01/react-native,soxunyi/react-native,christopherdro/react-native,Rowandjj/react-native,ljhsai/react-native,yangshangde/react-native,zyvas/react-native,oren/react-native,lelandrichardson/react-native,pallyoung/react-native,mtford90/react-native,hwsyy/react-native,edward/react-native,elliottsj/react-native,kesha-antonov/react-native,urvashi01/react-native,Tredsite/react-native,woshili1/react-native,wustxing/react-native,kotdark/react-native,wustxing/react-native,judastree/react-native,gs-akhan/react-native,geoffreyfloyd/react-native,miracle2k/react-native,kundanjadhav/react-native,hydraulic/react-native,ndejesus1227/react-native,ivanph/react-native,kentaromiura/react-native,trueblue2704/react-native,evansolomon/react-native,taydakov/react-native,formatlos/react-native,shrutic123/react-native,zvona/react-native,peterp/react-native,HealthyWealthy/react-native,clooth/react-native,gitim/react-native,zdsiyan/react-native,yiminghe/react-native,soxunyi/react-native,narlian/react-native,wildKids/react-native,Guardiannw/react-native,chengky/react-native,shinate/react-native,sudhirj/react-native,supercocoa/react-native,ljhsai/react-native,mbrock/react-native,pairyo/react-native,chengky/react-native,garrows/react-native,bistacos/react-native,adamterlson/react-native,kamronbatman/react-native,manhvvhtth/react-native,Wingie/react-native,nktpro/react-native,sahat/react-native,Lucifer-Kim/react-native,pickhardt/react-native,ide/react-native,mway08/react-native,ptmt/react-native-macos,aljs/react-native,nickhudkins/react-native,evansolomon/react-native,F2EVarMan/react-native,Iragne/react-native,evansolomon/react-native,genome21/react-native,forcedotcom/react-native,hwsyy/react-native,chsj1/react-native,jackeychens/react-native,YueRuo/react-native,PhilippKrone/react-native,mariusbutuc/react-native,Hkmu/react-native,peterp/react-native,lucyywang/react-native,sghiassy/react-native,myntra/react-native,jeanblanchard/react-native,dylanchann/react-native,Lucifer-Kim/react-native,imWildCat/react-native,levic92/react-native,dubert/react-native,codejet/react-native,cpunion/react-native,sospartan/react-native,gs-akhan/react-native,lstNull/react-native,a2/react-native,huangsongyan/react-native,gauribhoite/react-native,sjchakrav/react-native,ModusCreateOrg/react-native,javache/react-native,lzbSun/react-native,sixtomay/react-native,dvcrn/react-native,carcer/react-native,jasonnoahchoi/react-native,pitatensai/react-native,a2/react-native,Reparadocs/react-native,ProjectSeptemberInc/react-native,jbaumbach/react-native,cdlewis/react-native,MetSystem/react-native,jasonnoahchoi/react-native,daveenguyen/react-native,wustxing/react-native,iOSTestApps/react-native,aroth/react-native,billhello/react-native,lloydho/react-native,hanxiaofei/react-native,YComputer/react-native,csudanthi/react-native,jibonpab/react-native,NZAOM/react-native,qingfeng/react-native,rkumar3147/react-native,sonnylazuardi/react-native,j27cai/react-native,marlonandrade/react-native,geoffreyfloyd/react-native,waynett/react-native,YueRuo/react-native,zyvas/react-native,jbaumbach/react-native,ldehai/react-native,yushiwo/react-native,tsjing/react-native,corbt/react-native,alantrrs/react-native,srounce/react-native,chenbk85/react-native,myntra/react-native,rantianhua/react-native,bistacos/react-native,Andreyco/react-native,salanki/react-native,thstarshine/react-native,chnfeeeeeef/react-native,hzgnpu/react-native,Tredsite/react-native,nickhudkins/react-native,Purii/react-native,dalinaum/react-native,marlonandrade/react-native,qingfeng/react-native,BretJohnson/react-native,PlexChat/react-native,Iragne/react-native,fw1121/react-native,browniefed/react-native,CodeLinkIO/react-native,nevir/react-native,JasonZ321/react-native,barakcoh/react-native,salanki/react-native,soulcm/react-native,josebalius/react-native,wjb12/react-native,dralletje/react-native,hzgnpu/react-native,johnv315/react-native,andersryanc/react-native,chenbk85/react-native,eliagrady/react-native,adamterlson/react-native,ramoslin02/react-native,Poplava/react-native,pletcher/react-native,ktoh/react-native,tsdl2013/react-native,YinshawnRao/react-native,lelandrichardson/react-native,ericvera/react-native,olivierlesnicki/react-native,stonegithubs/react-native,shinate/react-native,Zagorakiss/react-native,Furzikov/react-native,yushiwo/react-native,supercocoa/react-native,happypancake/react-native,Shopify/react-native,tgriesser/react-native,sdiaz/react-native,vjeux/react-native,zyvas/react-native,21451061/react-native,wdxgtsh/react-native,qingsong-xu/react-native,rainkong/react-native,mukesh-kumar1905/react-native,hammerandchisel/react-native,quyixia/react-native,kfiroo/react-native,yiminghe/react-native,lokilandon/react-native,miracle2k/react-native,ortutay/react-native,nanpian/react-native,barakcoh/react-native,shrimpy/react-native,sonnylazuardi/react-native,thotegowda/react-native,hanxiaofei/react-native,harrykiselev/react-native,formatlos/react-native,dimoge/react-native,magnus-bergman/react-native,steveleec/react-native,yangshangde/react-native,a2/react-native,zhangwei001/react-native,ultralame/react-native,ronak301/react-native,josebalius/react-native,narlian/react-native,hzgnpu/react-native,JackLeeMing/react-native,yjyi/react-native,wangyzyoga/react-native,andrewljohnson/react-native,jeffchienzabinet/react-native,ultralame/react-native,DanielMSchmidt/react-native,pj4533/react-native,foghina/react-native,naoufal/react-native,simple88/react-native,YotrolZ/react-native,Hkmu/react-native,pletcher/react-native,ktoh/react-native,ChristianHersevoort/react-native,wenpkpk/react-native,imDangerous/react-native,JoeStanton/react-native,j27cai/react-native,jacobbubu/react-native,adamjmcgrath/react-native,spyrx7/react-native,mihaigiurgeanu/react-native,exponentjs/react-native,dimoge/react-native,aljs/react-native,makadaw/react-native,jacobbubu/react-native,a2/react-native,oren/react-native,booxood/react-native,vlrchtlt/react-native,esauter5/react-native,guanghuili/react-native,Poplava/react-native,aljs/react-native,supercocoa/react-native,yusefnapora/react-native,YueRuo/react-native,fw1121/react-native,pitatensai/react-native,programming086/react-native,BretJohnson/react-native,jevakallio/react-native,cmhsu/react-native,arthuralee/react-native,code0100fun/react-native,nickhargreaves/react-native,tmwoodson/react-native,michaelchucoder/react-native,vlrchtlt/react-native,chapinkapa/react-native,DanielMSchmidt/react-native,yangchengwork/react-native,sahat/react-native,mariusbutuc/react-native,misakuo/react-native,devknoll/react-native,clooth/react-native,sitexa/react-native,adamkrell/react-native,roy0914/react-native,leeyeh/react-native,WilliamRen/react-native,F2EVarMan/react-native,eddiemonge/react-native,goodheart/react-native,nathanajah/react-native,wangyzyoga/react-native,lzbSun/react-native,folist/react-native,zenlambda/react-native,jordanbyron/react-native,stan229/react-native,compulim/react-native,rushidesai/react-native,Applied-Duality/react-native,satya164/react-native,Livyli/react-native,DerayGa/react-native,insionng/react-native,chiefr/react-native,olivierlesnicki/react-native,steveleec/react-native,jonesgithub/react-native,yzarubin/react-native,Poplava/react-native,wenpkpk/react-native,arbesfeld/react-native,nanpian/react-native,aaron-goshine/react-native,DerayGa/react-native,javache/react-native,ericvera/react-native,dvcrn/react-native,skatpgusskat/react-native,Bronts/react-native,Flickster42490/react-native,kentaromiura/react-native,southasia/react-native,happypancake/react-native,jbaumbach/react-native,skatpgusskat/react-native,sonnylazuardi/react-native,jadbox/react-native,mcrooks88/react-native,NZAOM/react-native,lmorchard/react-native,naoufal/react-native,jonesgithub/react-native,hoangpham95/react-native,stan229/react-native,xinthink/react-native,unknownexception/react-native,apprennet/react-native,catalinmiron/react-native,androidgilbert/react-native,onesfreedom/react-native,pvinis/react-native-desktop,apprennet/react-native,slongwang/react-native,NunoEdgarGub1/react-native,YinshawnRao/react-native,Tredsite/react-native,yamill/react-native,bouk/react-native,hzgnpu/react-native,garydonovan/react-native,aifeld/react-native,YueRuo/react-native,tahnok/react-native,TChengZ/react-native,vlrchtlt/react-native,pglotov/react-native,nickhudkins/react-native,spicyj/react-native,adrie4mac/react-native,krock01/react-native,imWildCat/react-native,21451061/react-native,forcedotcom/react-native,marlonandrade/react-native,carcer/react-native,woshili1/react-native,genome21/react-native,ivanph/react-native,ptomasroos/react-native,alpz5566/react-native,Purii/react-native,rantianhua/react-native,xiangjuntang/react-native,sahrens/react-native,zdsiyan/react-native,sixtomay/react-native,hesling/react-native,zuolangguo/react-native,nbcnews/react-native,almost/react-native,mchinyakov/react-native,CntChen/react-native,sonnylazuardi/react-native,j27cai/react-native,bradens/react-native,peterp/react-native,mozillo/react-native,sudhirj/react-native,codejet/react-native,ehd/react-native,ide/react-native,jacobbubu/react-native,chirag04/react-native,steben/react-native,kotdark/react-native,Hkmu/react-native,olivierlesnicki/react-native,milieu/react-native,zhangxq5012/react-native,clooth/react-native,pairyo/react-native,Maxwell2022/react-native,jabinwang/react-native,mosch/react-native,hzgnpu/react-native,yzarubin/react-native,mukesh-kumar1905/react-native,Wingie/react-native,alvarojoao/react-native,wangziqiang/react-native,carcer/react-native,kujohn/react-native,mukesh-kumar1905/react-native,nevir/react-native,cazacugmihai/react-native,rickbeerendonk/react-native,hoastoolshop/react-native,liangmingjie/react-native,mqli/react-native,waynett/react-native,folist/react-native,neeraj-singh/react-native,nickhargreaves/react-native,bright-sparks/react-native,mariusbutuc/react-native,narlian/react-native,imWildCat/react-native,yusefnapora/react-native,ordinarybill/react-native,cxfeng1/react-native,nevir/react-native,mosch/react-native,Iragne/react-native,unknownexception/react-native,HSFGitHub/react-native,tsdl2013/react-native,sospartan/react-native,ehd/react-native,ronak301/react-native,jackalchen/react-native,ide/react-native,frantic/react-native,pglotov/react-native,esauter5/react-native,almost/react-native,bogdantmm92/react-native,steben/react-native,hydraulic/react-native,eduardinni/react-native,rwwarren/react-native,LytayTOUCH/react-native,bestwpw/react-native,rollokb/react-native,ouyangwenfeng/react-native,tarkus/react-native-appletv,xiayz/react-native,misakuo/react-native,cazacugmihai/react-native,liufeigit/react-native,strwind/react-native,xinthink/react-native,jeromjoy/react-native,yangshangde/react-native,southasia/react-native,machard/react-native,lwansbrough/react-native,kassens/react-native,jordanbyron/react-native,Loke155/react-native,Flickster42490/react-native,andersryanc/react-native,mrngoitall/react-native,rkumar3147/react-native,wenpkpk/react-native,martinbigio/react-native,dubert/react-native,PhilippKrone/react-native,guanghuili/react-native,happypancake/react-native,chirag04/react-native,JasonZ321/react-native,tsdl2013/react-native,makadaw/react-native,wjb12/react-native,miracle2k/react-native,adamkrell/react-native,dabit3/react-native,darkrishabh/react-native,ipmobiletech/react-native,KJlmfe/react-native,quuack/react-native,jaredly/react-native,zyvas/react-native,kfiroo/react-native,WilliamRen/react-native,nktpro/react-native,yushiwo/react-native,christopherdro/react-native,bowlofstew/react-native,jibonpab/react-native,arbesfeld/react-native,Srikanth4/react-native,ndejesus1227/react-native,Bhullnatik/react-native,ludaye123/react-native,enaqx/react-native,jekey/react-native,chsj1/react-native,patoroco/react-native,appersonlabs/react-native,Loke155/react-native,Jericho25/react-native,InterfaceInc/react-native,gabrielbellamy/react-native,PhilippKrone/react-native,elliottsj/react-native,shrutic123/react-native,taydakov/react-native,aroth/react-native,RGKzhanglei/react-native,wangyzyoga/react-native,wangcan2014/react-native,shrimpy/react-native,yjh0502/react-native,mrspeaker/react-native,mihaigiurgeanu/react-native,cdlewis/react-native,jhen0409/react-native,aaron-goshine/react-native,beni55/react-native,rollokb/react-native,alvarojoao/react-native,ide/react-native,jeanblanchard/react-native,timfpark/react-native,androidgilbert/react-native,jonesgithub/react-native,neeraj-singh/react-native,bsansouci/react-native,BretJohnson/react-native,tsdl2013/react-native,eliagrady/react-native,adamkrell/react-native,pvinis/react-native-desktop,bestwpw/react-native,liuhong1happy/react-native,zhangxq5012/react-native,fw1121/react-native,ipmobiletech/react-native,tgoldenberg/react-native,wenpkpk/react-native,nsimmons/react-native,urvashi01/react-native,rxb/react-native,magnus-bergman/react-native,pglotov/react-native,htc2u/react-native,Bronts/react-native,21451061/react-native,Serfenia/react-native,huangsongyan/react-native,lee-my/react-native,ouyangwenfeng/react-native,callstack-io/react-native,yjh0502/react-native,bodefuwa/react-native,richardgill/react-native,code0100fun/react-native,maskkid/react-native,luqin/react-native,nanpian/react-native,vjeux/react-native,ide/react-native,lloydho/react-native,janicduplessis/react-native,enaqx/react-native,rebeccahughes/react-native,frantic/react-native,waynett/react-native,dizlexik/react-native,mway08/react-native,jaredly/react-native,slongwang/react-native,lstNull/react-native,TChengZ/react-native,hydraulic/react-native,NZAOM/react-native,adamjmcgrath/react-native,bright-sparks/react-native,lokilandon/react-native,Wingie/react-native,mironiasty/react-native,madusankapremaratne/react-native,apprennet/react-native,ChristopherSalam/react-native,bradens/react-native,Rowandjj/react-native,BretJohnson/react-native,imWildCat/react-native,eddiemonge/react-native,gs-akhan/react-native,wangziqiang/react-native,csatf/react-native,jbaumbach/react-native,tsjing/react-native,zhangwei001/react-native,YComputer/react-native,wangyzyoga/react-native,rxb/react-native,jacobbubu/react-native,affinityis/react-native,yzarubin/react-native,gegaosong/react-native,gpbl/react-native,Poplava/react-native,esauter5/react-native,Rowandjj/react-native,threepointone/react-native-1,jaggs6/react-native,kentaromiura/react-native,beni55/react-native,manhvvhtth/react-native,milieu/react-native,vincentqiu/react-native,liuzechen/react-native,emodeqidao/react-native,yamill/react-native,wangziqiang/react-native,hoangpham95/react-native,InterfaceInc/react-native,trueblue2704/react-native,BretJohnson/react-native,wangziqiang/react-native,gauribhoite/react-native,farazs/react-native,gauribhoite/react-native,roy0914/react-native,booxood/react-native,ankitsinghania94/react-native,pjcabrera/react-native,liuhong1happy/react-native,philikon/react-native,Livyli/react-native,wesley1001/react-native,jaredly/react-native,leegilon/react-native,leeyeh/react-native,hharnisc/react-native,steben/react-native,kundanjadhav/react-native,dabit3/react-native,WilliamRen/react-native,zvona/react-native,Suninus/react-native,oren/react-native,callstack-io/react-native,unknownexception/react-native,cpunion/react-native,TChengZ/react-native,dikaiosune/react-native,vjeux/react-native,shinate/react-native,wesley1001/react-native,sdiaz/react-native,gpbl/react-native,iodine/react-native,brentvatne/react-native,dizlexik/react-native,Shopify/react-native,futbalguy/react-native,nbcnews/react-native,elliottsj/react-native,sekouperry/react-native,timfpark/react-native,chentsulin/react-native,jasonals/react-native,mcrooks88/react-native,wustxing/react-native,michaelchucoder/react-native,fengshao0907/react-native,jmstout/react-native,glovebx/react-native,hoastoolshop/react-native,cdlewis/react-native,bimawa/react-native,vlrchtlt/react-native,ProjectSeptemberInc/react-native,esauter5/react-native,puf/react-native,gre/react-native,huip/react-native,ldehai/react-native,InterfaceInc/react-native,Srikanth4/react-native,mqli/react-native,mchinyakov/react-native,simple88/react-native,YotrolZ/react-native,mtford90/react-native,maskkid/react-native,goodheart/react-native,christer155/react-native,yushiwo/react-native,magnus-bergman/react-native,tgoldenberg/react-native,hassanabidpk/react-native,JasonZ321/react-native,xinthink/react-native,javache/react-native,foghina/react-native,jhen0409/react-native,tsdl2013/react-native,jadbox/react-native,hike2008/react-native,boopathi/react-native,huip/react-native,evilemon/react-native,1988fei/react-native
c
## Code Before: /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import <UIKit/UIKit.h> #import "../../ReactKit/Base/RCTBridgeModule.h" @interface RCTPushNotificationManager : NSObject <RCTBridgeModule> - (instancetype)initWithInitialNotification:(NSDictionary *)initialNotification NS_DESIGNATED_INITIALIZER; + (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings; + (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification; + (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation; @end ## Instruction: Fix build - remove relative import path ## Code After: /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import <UIKit/UIKit.h> #import "RCTBridgeModule.h" @interface RCTPushNotificationManager : NSObject <RCTBridgeModule> - (instancetype)initWithInitialNotification:(NSDictionary *)initialNotification NS_DESIGNATED_INITIALIZER; + (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings; + (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification; + (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation; @end
# ... existing code ... #import <UIKit/UIKit.h> #import "RCTBridgeModule.h" @interface RCTPushNotificationManager : NSObject <RCTBridgeModule> # ... rest of the code ...
06ab217f49e00bd52c9f8b632db904e1ebe7256d
pycroft/helpers/date.py
pycroft/helpers/date.py
from datetime import timedelta from datetime import date def diff_month(d1: date, d2: date) -> int: """Calculate the difference in months ignoring the days If d1 > d2, the result is positive. """ return (d1.year - d2.year) * 12 + d1.month - d2.month def last_day_of_month(d): next_month = d.replace(day=28) + timedelta(4) return d.replace(day=(next_month - timedelta(days=next_month.day)).day)
from calendar import monthrange from datetime import date def diff_month(d1: date, d2: date) -> int: """Calculate the difference in months ignoring the days If d1 > d2, the result is positive. """ return (d1.year - d2.year) * 12 + d1.month - d2.month def last_day_of_month(d: date) -> date: _, num_days = monthrange(d.year, d.month) return d.replace(day=num_days)
Use builtin function to find last month
Use builtin function to find last month
Python
apache-2.0
agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft
python
## Code Before: from datetime import timedelta from datetime import date def diff_month(d1: date, d2: date) -> int: """Calculate the difference in months ignoring the days If d1 > d2, the result is positive. """ return (d1.year - d2.year) * 12 + d1.month - d2.month def last_day_of_month(d): next_month = d.replace(day=28) + timedelta(4) return d.replace(day=(next_month - timedelta(days=next_month.day)).day) ## Instruction: Use builtin function to find last month ## Code After: from calendar import monthrange from datetime import date def diff_month(d1: date, d2: date) -> int: """Calculate the difference in months ignoring the days If d1 > d2, the result is positive. """ return (d1.year - d2.year) * 12 + d1.month - d2.month def last_day_of_month(d: date) -> date: _, num_days = monthrange(d.year, d.month) return d.replace(day=num_days)
// ... existing code ... from calendar import monthrange from datetime import date // ... modified code ... return (d1.year - d2.year) * 12 + d1.month - d2.month def last_day_of_month(d: date) -> date: _, num_days = monthrange(d.year, d.month) return d.replace(day=num_days) // ... rest of the code ...
2230832033df7f5d8511dc75f799a9cc738dc46f
games/managers.py
games/managers.py
from django.db.models import Manager class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(user=user)) else: return query.filter(published=True)
from django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True)
Fix missing import and bad query for screenshots
Fix missing import and bad query for screenshots
Python
agpl-3.0
Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website
python
## Code Before: from django.db.models import Manager class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(user=user)) else: return query.filter(published=True) ## Instruction: Fix missing import and bad query for screenshots ## Code After: from django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True)
# ... existing code ... from django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): # ... modified code ... if is_staff: return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True) # ... rest of the code ...
08732041f7ccf35adc848a1f0dc188d8cfe4d578
src/main/java/me/hugmanrique/pokedata/tiles/TilesetHeader.java
src/main/java/me/hugmanrique/pokedata/tiles/TilesetHeader.java
package me.hugmanrique.pokedata.tiles; import lombok.Getter; import me.hugmanrique.pokedata.Data; import me.hugmanrique.pokedata.roms.ROM; /** * http://datacrystal.romhacking.net/wiki/Pok%C3%A9mon_3rd_Generation#Maps * @author Hugmanrique * @since 02/07/2017 */ @Getter public class TilesetHeader extends Data { private boolean compressed; private boolean primary; private long tilesetImgPtr; private long palettesPtr; private long blocksPtr; private long animationPtr; private long behaviorPtr; public TilesetHeader(ROM rom) { compressed = rom.readByte() == 1; primary = rom.readByte() == 0; // Skip two unknown bytes rom.addInternalOffset(2); tilesetImgPtr = rom.getPointer(); palettesPtr = rom.getPointer(); blocksPtr = rom.getPointer(); System.out.println("Read: Tileset imgs -> " + tilesetImgPtr + " Palettes -> " + palettesPtr + " Blocks -> " + blocksPtr); if (rom.getGame().isElements()) { animationPtr = rom.getPointer(); behaviorPtr = rom.getPointer(); } else { behaviorPtr = rom.getPointer(); animationPtr = rom.getPointer(); } } }
package me.hugmanrique.pokedata.tiles; import lombok.Getter; import me.hugmanrique.pokedata.Data; import me.hugmanrique.pokedata.roms.ROM; /** * http://datacrystal.romhacking.net/wiki/Pok%C3%A9mon_3rd_Generation#Maps * @author Hugmanrique * @since 02/07/2017 */ @Getter public class TilesetHeader extends Data { private boolean compressed; private boolean primary; private long tilesetImgPtr; private long palettesPtr; private long blocksPtr; private long animationPtr; private long behaviorPtr; public TilesetHeader(ROM rom) { compressed = rom.readByte() == 1; primary = rom.readByte() == 0; // Skip two unknown bytes rom.addInternalOffset(2); tilesetImgPtr = rom.getPointer(); palettesPtr = rom.getPointer(); blocksPtr = rom.getPointer(); if (rom.getGame().isElements()) { animationPtr = rom.getPointer(); behaviorPtr = rom.getPointer(); } else { behaviorPtr = rom.getPointer(); animationPtr = rom.getPointer(); } } }
Remove tileset load debug message
Remove tileset load debug message
Java
mit
hugmanrique/PokeData
java
## Code Before: package me.hugmanrique.pokedata.tiles; import lombok.Getter; import me.hugmanrique.pokedata.Data; import me.hugmanrique.pokedata.roms.ROM; /** * http://datacrystal.romhacking.net/wiki/Pok%C3%A9mon_3rd_Generation#Maps * @author Hugmanrique * @since 02/07/2017 */ @Getter public class TilesetHeader extends Data { private boolean compressed; private boolean primary; private long tilesetImgPtr; private long palettesPtr; private long blocksPtr; private long animationPtr; private long behaviorPtr; public TilesetHeader(ROM rom) { compressed = rom.readByte() == 1; primary = rom.readByte() == 0; // Skip two unknown bytes rom.addInternalOffset(2); tilesetImgPtr = rom.getPointer(); palettesPtr = rom.getPointer(); blocksPtr = rom.getPointer(); System.out.println("Read: Tileset imgs -> " + tilesetImgPtr + " Palettes -> " + palettesPtr + " Blocks -> " + blocksPtr); if (rom.getGame().isElements()) { animationPtr = rom.getPointer(); behaviorPtr = rom.getPointer(); } else { behaviorPtr = rom.getPointer(); animationPtr = rom.getPointer(); } } } ## Instruction: Remove tileset load debug message ## Code After: package me.hugmanrique.pokedata.tiles; import lombok.Getter; import me.hugmanrique.pokedata.Data; import me.hugmanrique.pokedata.roms.ROM; /** * http://datacrystal.romhacking.net/wiki/Pok%C3%A9mon_3rd_Generation#Maps * @author Hugmanrique * @since 02/07/2017 */ @Getter public class TilesetHeader extends Data { private boolean compressed; private boolean primary; private long tilesetImgPtr; private long palettesPtr; private long blocksPtr; private long animationPtr; private long behaviorPtr; public TilesetHeader(ROM rom) { compressed = rom.readByte() == 1; primary = rom.readByte() == 0; // Skip two unknown bytes rom.addInternalOffset(2); tilesetImgPtr = rom.getPointer(); palettesPtr = rom.getPointer(); blocksPtr = rom.getPointer(); if (rom.getGame().isElements()) { animationPtr = rom.getPointer(); behaviorPtr = rom.getPointer(); } else { behaviorPtr = rom.getPointer(); animationPtr = rom.getPointer(); } } }
... palettesPtr = rom.getPointer(); blocksPtr = rom.getPointer(); if (rom.getGame().isElements()) { animationPtr = rom.getPointer(); behaviorPtr = rom.getPointer(); ...
b8bd5fc044d3dd3b273cba4443c771e60036b6c0
corehq/apps/importer/base.py
corehq/apps/importer/base.py
from corehq.apps.data_interfaces.interfaces import DataInterface from django.utils.translation import ugettext as _ class ImportCases(DataInterface): name = _("Import Cases from Excel") slug = "import_cases" description = _("Import case data from an external Excel file") report_template_path = "importer/import_cases.html" gide_filters = True asynchronous = False
from corehq.apps.data_interfaces.interfaces import DataInterface from django.utils.translation import ugettext_lazy class ImportCases(DataInterface): name = ugettext_lazy("Import Cases from Excel") slug = "import_cases" description = ugettext_lazy("Import case data from an external Excel file") report_template_path = "importer/import_cases.html" gide_filters = True asynchronous = False
Use lazy translation for importer strings
Use lazy translation for importer strings
Python
bsd-3-clause
SEL-Columbia/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,gmimano/commcaretest,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,gmimano/commcaretest,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,gmimano/commcaretest,puttarajubr/commcare-hq
python
## Code Before: from corehq.apps.data_interfaces.interfaces import DataInterface from django.utils.translation import ugettext as _ class ImportCases(DataInterface): name = _("Import Cases from Excel") slug = "import_cases" description = _("Import case data from an external Excel file") report_template_path = "importer/import_cases.html" gide_filters = True asynchronous = False ## Instruction: Use lazy translation for importer strings ## Code After: from corehq.apps.data_interfaces.interfaces import DataInterface from django.utils.translation import ugettext_lazy class ImportCases(DataInterface): name = ugettext_lazy("Import Cases from Excel") slug = "import_cases" description = ugettext_lazy("Import case data from an external Excel file") report_template_path = "importer/import_cases.html" gide_filters = True asynchronous = False
... from corehq.apps.data_interfaces.interfaces import DataInterface from django.utils.translation import ugettext_lazy class ImportCases(DataInterface): name = ugettext_lazy("Import Cases from Excel") slug = "import_cases" description = ugettext_lazy("Import case data from an external Excel file") report_template_path = "importer/import_cases.html" gide_filters = True asynchronous = False ...
49c83e0ef5ec7390a78e95dbc035b7d2808ec13e
feedback/tests.py
feedback/tests.py
from django.test import TestCase, client from .models import Feedback client = client.Client() class FeedbackTest(TestCase): def test_add_feedback(self): before_add = Feedback.objects.count() response = client.post('/feedback/add/', { 'name': 'Пандо Пандев', 'email': '[email protected]', 'information': 'Тука се разхожда една панда по екрана'}) after_add = Feedback.objects.count() self.assertEqual(response.status_code, 302) self.assertEqual(before_add + 1, after_add) def test_user_add_feedback(self): pass
from django.test import TestCase, client from .models import Feedback client = client.Client() class FeedbackTest(TestCase): def test_add_feedback(self): pass # before_add = Feedback.objects.count() # response = client.post('/feedback/add/', { # 'name': 'Пандо Пандев', # 'email': '[email protected]', # 'information': 'Тука се разхожда една панда по екрана'}) # after_add = Feedback.objects.count() # self.assertEqual(response.status_code, 302) # self.assertEqual(before_add + 1, after_add) def test_user_add_feedback(self): pass
Remove test for adding feedback
Remove test for adding feedback
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
python
## Code Before: from django.test import TestCase, client from .models import Feedback client = client.Client() class FeedbackTest(TestCase): def test_add_feedback(self): before_add = Feedback.objects.count() response = client.post('/feedback/add/', { 'name': 'Пандо Пандев', 'email': '[email protected]', 'information': 'Тука се разхожда една панда по екрана'}) after_add = Feedback.objects.count() self.assertEqual(response.status_code, 302) self.assertEqual(before_add + 1, after_add) def test_user_add_feedback(self): pass ## Instruction: Remove test for adding feedback ## Code After: from django.test import TestCase, client from .models import Feedback client = client.Client() class FeedbackTest(TestCase): def test_add_feedback(self): pass # before_add = Feedback.objects.count() # response = client.post('/feedback/add/', { # 'name': 'Пандо Пандев', # 'email': '[email protected]', # 'information': 'Тука се разхожда една панда по екрана'}) # after_add = Feedback.objects.count() # self.assertEqual(response.status_code, 302) # self.assertEqual(before_add + 1, after_add) def test_user_add_feedback(self): pass
... class FeedbackTest(TestCase): def test_add_feedback(self): pass # before_add = Feedback.objects.count() # response = client.post('/feedback/add/', { # 'name': 'Пандо Пандев', # 'email': '[email protected]', # 'information': 'Тука се разхожда една панда по екрана'}) # after_add = Feedback.objects.count() # self.assertEqual(response.status_code, 302) # self.assertEqual(before_add + 1, after_add) def test_user_add_feedback(self): pass ...
b52037176cd1b8a4d99ff195d72680928ba3790f
cms/djangoapps/export_course_metadata/management/commands/export_course_metadata_for_all_courses.py
cms/djangoapps/export_course_metadata/management/commands/export_course_metadata_for_all_courses.py
from django.core.management.base import BaseCommand from xmodule.modulestore.django import modulestore from cms.djangoapps.export_course_metadata.signals import export_course_metadata from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task class Command(BaseCommand): """ Export course metadata for all courses """ help = 'Export course metadata for all courses' def handle(self, *args, **options): """ Execute the command """ export_course_metadata_for_all_courses() def export_course_metadata_for_all_courses(): """ Export course metadata for all courses """ module_store = modulestore() courses = module_store.get_courses() for course in courses: export_course_metadata_task.delay(str(course.id))
from django.core.management.base import BaseCommand from xmodule.modulestore.django import modulestore from cms.djangoapps.export_course_metadata.signals import export_course_metadata from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task class Command(BaseCommand): """ Export course metadata for all courses """ help = 'Export course metadata for all courses' def handle(self, *args, **options): """ Execute the command """ export_course_metadata_for_all_courses() def export_course_metadata_for_all_courses(): """ Export course metadata for all courses """ courses = modulestore().get_course_summaries() for course in courses: export_course_metadata_task.delay(str(course.id))
Change how we get course ids to avoid memory issues
Change how we get course ids to avoid memory issues
Python
agpl-3.0
angelapper/edx-platform,arbrandes/edx-platform,angelapper/edx-platform,eduNEXT/edx-platform,edx/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,angelapper/edx-platform,angelapper/edx-platform,edx/edx-platform,EDUlib/edx-platform,eduNEXT/edx-platform,edx/edx-platform,eduNEXT/edx-platform,arbrandes/edx-platform,edx/edx-platform,EDUlib/edx-platform,eduNEXT/edunext-platform
python
## Code Before: from django.core.management.base import BaseCommand from xmodule.modulestore.django import modulestore from cms.djangoapps.export_course_metadata.signals import export_course_metadata from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task class Command(BaseCommand): """ Export course metadata for all courses """ help = 'Export course metadata for all courses' def handle(self, *args, **options): """ Execute the command """ export_course_metadata_for_all_courses() def export_course_metadata_for_all_courses(): """ Export course metadata for all courses """ module_store = modulestore() courses = module_store.get_courses() for course in courses: export_course_metadata_task.delay(str(course.id)) ## Instruction: Change how we get course ids to avoid memory issues ## Code After: from django.core.management.base import BaseCommand from xmodule.modulestore.django import modulestore from cms.djangoapps.export_course_metadata.signals import export_course_metadata from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task class Command(BaseCommand): """ Export course metadata for all courses """ help = 'Export course metadata for all courses' def handle(self, *args, **options): """ Execute the command """ export_course_metadata_for_all_courses() def export_course_metadata_for_all_courses(): """ Export course metadata for all courses """ courses = modulestore().get_course_summaries() for course in courses: export_course_metadata_task.delay(str(course.id))
// ... existing code ... """ Export course metadata for all courses """ courses = modulestore().get_course_summaries() for course in courses: export_course_metadata_task.delay(str(course.id)) // ... rest of the code ...
d65643e1bb74210a458b370aca5343f5c7059022
wm_metrics/period.py
wm_metrics/period.py
"""Representation of a period of time.""" class Period(object): def __init__(self, start, end): self.start = start self.end = end def __repr__(self): return "%s-%s" % (self.start, self.end)
"""Representation of a period of time.""" class Period(object): def __init__(self, start, end): self.start = start self.end = end def __repr__(self): return "%s-%s" % (self.start, self.end) def __eq__(self, other): return ((other.start == self.start) and (other.end == self.end))
Add __eq__ method to Period object
Add __eq__ method to Period object Ultimately we probably want to reuse Python objects like timestamps.
Python
mit
Commonists/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics,danmichaelo/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics,danmichaelo/wm_metrics
python
## Code Before: """Representation of a period of time.""" class Period(object): def __init__(self, start, end): self.start = start self.end = end def __repr__(self): return "%s-%s" % (self.start, self.end) ## Instruction: Add __eq__ method to Period object Ultimately we probably want to reuse Python objects like timestamps. ## Code After: """Representation of a period of time.""" class Period(object): def __init__(self, start, end): self.start = start self.end = end def __repr__(self): return "%s-%s" % (self.start, self.end) def __eq__(self, other): return ((other.start == self.start) and (other.end == self.end))
// ... existing code ... def __repr__(self): return "%s-%s" % (self.start, self.end) def __eq__(self, other): return ((other.start == self.start) and (other.end == self.end)) // ... rest of the code ...
6140c9cd0315cdd6e7a9bc824f774320f73717f5
app/src/main/java/com/ogsdroid/MyApplication.java
app/src/main/java/com/ogsdroid/MyApplication.java
package com.ogsdroid; import android.app.Application; import android.content.Context; import org.acra.ACRA; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; @ReportsCrashes( mailTo = "[email protected]", mode = ReportingInteractionMode.TOAST, resToastText = R.string.crash_toast_text ) public class MyApplication extends Application { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); // The following line triggers the initialization of ACRA ACRA.init(this); } }
package com.ogsdroid; import android.app.Application; import android.content.Context; import org.acra.ACRA; import org.acra.ReportField; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; @ReportsCrashes( mailTo = "[email protected]", mode = ReportingInteractionMode.TOAST, customReportContent = {ReportField.APP_VERSION_CODE, ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.STACK_TRACE, ReportField.LOGCAT }, resToastText = R.string.crash_toast_text ) public class MyApplication extends Application { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); // The following line triggers the initialization of ACRA ACRA.init(this); } }
Include logcat in crash reports
Include logcat in crash reports
Java
mit
nathanj/ogsdroid,nathanj/ogsdroid
java
## Code Before: package com.ogsdroid; import android.app.Application; import android.content.Context; import org.acra.ACRA; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; @ReportsCrashes( mailTo = "[email protected]", mode = ReportingInteractionMode.TOAST, resToastText = R.string.crash_toast_text ) public class MyApplication extends Application { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); // The following line triggers the initialization of ACRA ACRA.init(this); } } ## Instruction: Include logcat in crash reports ## Code After: package com.ogsdroid; import android.app.Application; import android.content.Context; import org.acra.ACRA; import org.acra.ReportField; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; @ReportsCrashes( mailTo = "[email protected]", mode = ReportingInteractionMode.TOAST, customReportContent = {ReportField.APP_VERSION_CODE, ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.STACK_TRACE, ReportField.LOGCAT }, resToastText = R.string.crash_toast_text ) public class MyApplication extends Application { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); // The following line triggers the initialization of ACRA ACRA.init(this); } }
// ... existing code ... import android.content.Context; import org.acra.ACRA; import org.acra.ReportField; import org.acra.ReportingInteractionMode; import org.acra.annotation.ReportsCrashes; // ... modified code ... @ReportsCrashes( mailTo = "[email protected]", mode = ReportingInteractionMode.TOAST, customReportContent = {ReportField.APP_VERSION_CODE, ReportField.APP_VERSION_NAME, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.STACK_TRACE, ReportField.LOGCAT }, resToastText = R.string.crash_toast_text ) // ... rest of the code ...
c2eccb4ce1259830dd641d19624358af83c09549
webcomix/comic_spider.py
webcomix/comic_spider.py
from urllib.parse import urljoin import scrapy class ComicSpider(scrapy.Spider): name = "My spider" def __init__(self, *args, **kwargs): self.start_urls = kwargs.get('start_urls') or [] self.next_page_selector = kwargs.get('next_page_selector', None) self.comic_image_selector = kwargs.get('comic_image_selector', None) super(ComicSpider, self).__init__(*args, **kwargs) def parse(self, response): comic_image_url = response.xpath( self.comic_image_selector).extract_first() page = response.meta.get('page') or 1 yield { "image_element": urljoin(response.url, comic_image_url), "page": page } next_page_url = response.xpath(self.next_page_selector).extract_first() if next_page_url is not None and not next_page_url.endswith('#'): yield scrapy.Request( response.urljoin(next_page_url), meta={'page': page + 1})
from urllib.parse import urljoin import click import scrapy class ComicSpider(scrapy.Spider): name = "Comic Spider" def __init__(self, *args, **kwargs): self.start_urls = kwargs.get('start_urls') or [] self.next_page_selector = kwargs.get('next_page_selector', None) self.comic_image_selector = kwargs.get('comic_image_selector', None) super(ComicSpider, self).__init__(*args, **kwargs) def parse(self, response): click.echo("Downloading page {}".format(response.url)) comic_image_url = response.xpath( self.comic_image_selector).extract_first() page = response.meta.get('page') or 1 if comic_image_url is not None: yield { "image_element": urljoin(response.url, comic_image_url), "page": page } else: click.echo("Could not find comic image.") next_page_url = response.xpath(self.next_page_selector).extract_first() if next_page_url is not None and not next_page_url.endswith('#'): yield scrapy.Request( response.urljoin(next_page_url), meta={'page': page + 1})
Copy logging from previous version and only yield item to pipeline if a comic image was found
Copy logging from previous version and only yield item to pipeline if a comic image was found
Python
mit
J-CPelletier/webcomix,J-CPelletier/webcomix,J-CPelletier/WebComicToCBZ
python
## Code Before: from urllib.parse import urljoin import scrapy class ComicSpider(scrapy.Spider): name = "My spider" def __init__(self, *args, **kwargs): self.start_urls = kwargs.get('start_urls') or [] self.next_page_selector = kwargs.get('next_page_selector', None) self.comic_image_selector = kwargs.get('comic_image_selector', None) super(ComicSpider, self).__init__(*args, **kwargs) def parse(self, response): comic_image_url = response.xpath( self.comic_image_selector).extract_first() page = response.meta.get('page') or 1 yield { "image_element": urljoin(response.url, comic_image_url), "page": page } next_page_url = response.xpath(self.next_page_selector).extract_first() if next_page_url is not None and not next_page_url.endswith('#'): yield scrapy.Request( response.urljoin(next_page_url), meta={'page': page + 1}) ## Instruction: Copy logging from previous version and only yield item to pipeline if a comic image was found ## Code After: from urllib.parse import urljoin import click import scrapy class ComicSpider(scrapy.Spider): name = "Comic Spider" def __init__(self, *args, **kwargs): self.start_urls = kwargs.get('start_urls') or [] self.next_page_selector = kwargs.get('next_page_selector', None) self.comic_image_selector = kwargs.get('comic_image_selector', None) super(ComicSpider, self).__init__(*args, **kwargs) def parse(self, response): click.echo("Downloading page {}".format(response.url)) comic_image_url = response.xpath( self.comic_image_selector).extract_first() page = response.meta.get('page') or 1 if comic_image_url is not None: yield { "image_element": urljoin(response.url, comic_image_url), "page": page } else: click.echo("Could not find comic image.") next_page_url = response.xpath(self.next_page_selector).extract_first() if next_page_url is not None and not next_page_url.endswith('#'): yield scrapy.Request( response.urljoin(next_page_url), meta={'page': page + 1})
// ... existing code ... from urllib.parse import urljoin import click import scrapy class ComicSpider(scrapy.Spider): name = "Comic Spider" def __init__(self, *args, **kwargs): self.start_urls = kwargs.get('start_urls') or [] // ... modified code ... super(ComicSpider, self).__init__(*args, **kwargs) def parse(self, response): click.echo("Downloading page {}".format(response.url)) comic_image_url = response.xpath( self.comic_image_selector).extract_first() page = response.meta.get('page') or 1 if comic_image_url is not None: yield { "image_element": urljoin(response.url, comic_image_url), "page": page } else: click.echo("Could not find comic image.") next_page_url = response.xpath(self.next_page_selector).extract_first() if next_page_url is not None and not next_page_url.endswith('#'): yield scrapy.Request( // ... rest of the code ...
978e09882f4fb19a8d31a9b91b0258751f745c21
mods/FleetAutoTarget/AutoTarget.py
mods/FleetAutoTarget/AutoTarget.py
import logmodule from eve.client.script.ui.shared.fleet.fleetbroadcast import FleetBroadcastView def PatchFn(fn): def wrapper(self): try: br = sm.GetService('fleet').GetBroadcastHistory()[0] logmodule.general.Log("GetBroadcastListEntry invoked: %s %d %d" % (br.name, br.charID, br.itemID), logmodule.LGNOTICE) if br.name in ("Target", "HealArmor", "HealShield"): sm.GetService('target').TryLockTarget(br.itemID) except: pass return fn(self) return wrapper def RunPatch(): FleetBroadcastView.LoadBroadcastHistory = PatchFn(FleetBroadcastView.LoadBroadcastHistory) logmodule.general.Log("Code Injected", logmodule.LGNOTICE)
import logmodule from eve.client.script.ui.shared.fleet.fleetbroadcast import FleetBroadcastView def PatchFn(fn): def wrapper(self): ret = fn(self) try: br = sm.GetService('fleet').GetBroadcastHistory()[0] logmodule.general.Log("GetBroadcastListEntry invoked: %s %d %d" % (br.name, br.charID, br.itemID), logmodule.LGNOTICE) if br.name in ("Target", "HealArmor", "HealShield"): sm.GetService('target').TryLockTarget(br.itemID) except: pass return ret return wrapper def RunPatch(): FleetBroadcastView.LoadBroadcastHistory = PatchFn(FleetBroadcastView.LoadBroadcastHistory) logmodule.general.Log("Code Injected", logmodule.LGNOTICE)
Adjust the order to reduce latency
Adjust the order to reduce latency
Python
mit
EVEModX/Mods
python
## Code Before: import logmodule from eve.client.script.ui.shared.fleet.fleetbroadcast import FleetBroadcastView def PatchFn(fn): def wrapper(self): try: br = sm.GetService('fleet').GetBroadcastHistory()[0] logmodule.general.Log("GetBroadcastListEntry invoked: %s %d %d" % (br.name, br.charID, br.itemID), logmodule.LGNOTICE) if br.name in ("Target", "HealArmor", "HealShield"): sm.GetService('target').TryLockTarget(br.itemID) except: pass return fn(self) return wrapper def RunPatch(): FleetBroadcastView.LoadBroadcastHistory = PatchFn(FleetBroadcastView.LoadBroadcastHistory) logmodule.general.Log("Code Injected", logmodule.LGNOTICE) ## Instruction: Adjust the order to reduce latency ## Code After: import logmodule from eve.client.script.ui.shared.fleet.fleetbroadcast import FleetBroadcastView def PatchFn(fn): def wrapper(self): ret = fn(self) try: br = sm.GetService('fleet').GetBroadcastHistory()[0] logmodule.general.Log("GetBroadcastListEntry invoked: %s %d %d" % (br.name, br.charID, br.itemID), logmodule.LGNOTICE) if br.name in ("Target", "HealArmor", "HealShield"): sm.GetService('target').TryLockTarget(br.itemID) except: pass return ret return wrapper def RunPatch(): FleetBroadcastView.LoadBroadcastHistory = PatchFn(FleetBroadcastView.LoadBroadcastHistory) logmodule.general.Log("Code Injected", logmodule.LGNOTICE)
... def PatchFn(fn): def wrapper(self): ret = fn(self) try: br = sm.GetService('fleet').GetBroadcastHistory()[0] logmodule.general.Log("GetBroadcastListEntry invoked: %s %d %d" % (br.name, br.charID, br.itemID), logmodule.LGNOTICE) ... sm.GetService('target').TryLockTarget(br.itemID) except: pass return ret return wrapper def RunPatch(): ...
52ffc2b264cbacaee56017cd4a67df4511d60392
celery/managers.py
celery/managers.py
from django.db import models from celery.registry import tasks from datetime import datetime, timedelta __all__ = ["TaskManager", "PeriodicTaskManager"] class TaskManager(models.Manager): def get_task(self, task_id): task, created = self.get_or_create(task_id=task_id) return task def is_done(self, task_id): return self.get_task(task_id).is_done def get_all_expired(self): return self.filter(date_done__lt=datetime.now() - timedelta(days=5)) def delete_expired(self): self.get_all_expired().delete() def mark_as_done(self, task_id): task, created = self.get_or_create(task_id=task_id, defaults={ "is_done": True}) if not created: task.is_done = True task.save() class PeriodicTaskManager(models.Manager): def get_waiting_tasks(self): periodic_tasks = tasks.get_all_periodic() waiting = [] for task_name, task in periodic_tasks.items(): task_meta, created = self.get_or_create(name=task_name) # task_run.every must be a timedelta object. run_at = task_meta.last_run_at + task.run_every if datetime.now() > run_at: waiting.append(task_meta) return waiting
from django.db import models from celery.registry import tasks from datetime import datetime, timedelta __all__ = ["TaskManager", "PeriodicTaskManager"] class TaskManager(models.Manager): def get_task(self, task_id): task, created = self.get_or_create(task_id=task_id) return task def is_done(self, task_id): return self.get_task(task_id).is_done def get_all_expired(self): return self.filter(date_done__lt=datetime.now() - timedelta(days=5), is_done=True) def delete_expired(self): self.get_all_expired().delete() def mark_as_done(self, task_id): task, created = self.get_or_create(task_id=task_id, defaults={ "is_done": True}) if not created: task.is_done = True task.save() class PeriodicTaskManager(models.Manager): def get_waiting_tasks(self): periodic_tasks = tasks.get_all_periodic() waiting = [] for task_name, task in periodic_tasks.items(): task_meta, created = self.get_or_create(name=task_name) # task_run.every must be a timedelta object. run_at = task_meta.last_run_at + task.run_every if datetime.now() > run_at: waiting.append(task_meta) return waiting
Add is_done=True to get_all_expired filter.
Add is_done=True to get_all_expired filter.
Python
bsd-3-clause
WoLpH/celery,cbrepo/celery,cbrepo/celery,ask/celery,frac/celery,WoLpH/celery,mitsuhiko/celery,ask/celery,mitsuhiko/celery,frac/celery
python
## Code Before: from django.db import models from celery.registry import tasks from datetime import datetime, timedelta __all__ = ["TaskManager", "PeriodicTaskManager"] class TaskManager(models.Manager): def get_task(self, task_id): task, created = self.get_or_create(task_id=task_id) return task def is_done(self, task_id): return self.get_task(task_id).is_done def get_all_expired(self): return self.filter(date_done__lt=datetime.now() - timedelta(days=5)) def delete_expired(self): self.get_all_expired().delete() def mark_as_done(self, task_id): task, created = self.get_or_create(task_id=task_id, defaults={ "is_done": True}) if not created: task.is_done = True task.save() class PeriodicTaskManager(models.Manager): def get_waiting_tasks(self): periodic_tasks = tasks.get_all_periodic() waiting = [] for task_name, task in periodic_tasks.items(): task_meta, created = self.get_or_create(name=task_name) # task_run.every must be a timedelta object. run_at = task_meta.last_run_at + task.run_every if datetime.now() > run_at: waiting.append(task_meta) return waiting ## Instruction: Add is_done=True to get_all_expired filter. ## Code After: from django.db import models from celery.registry import tasks from datetime import datetime, timedelta __all__ = ["TaskManager", "PeriodicTaskManager"] class TaskManager(models.Manager): def get_task(self, task_id): task, created = self.get_or_create(task_id=task_id) return task def is_done(self, task_id): return self.get_task(task_id).is_done def get_all_expired(self): return self.filter(date_done__lt=datetime.now() - timedelta(days=5), is_done=True) def delete_expired(self): self.get_all_expired().delete() def mark_as_done(self, task_id): task, created = self.get_or_create(task_id=task_id, defaults={ "is_done": True}) if not created: task.is_done = True task.save() class PeriodicTaskManager(models.Manager): def get_waiting_tasks(self): periodic_tasks = tasks.get_all_periodic() waiting = [] for task_name, task in periodic_tasks.items(): task_meta, created = self.get_or_create(name=task_name) # task_run.every must be a timedelta object. run_at = task_meta.last_run_at + task.run_every if datetime.now() > run_at: waiting.append(task_meta) return waiting
... return self.get_task(task_id).is_done def get_all_expired(self): return self.filter(date_done__lt=datetime.now() - timedelta(days=5), is_done=True) def delete_expired(self): self.get_all_expired().delete() ...
5590899048164dbd892265dfabb5b061845909e7
src/com/activeandroid/widget/ModelAdapter.java
src/com/activeandroid/widget/ModelAdapter.java
package com.activeandroid.widget; import java.util.List; import android.content.Context; import android.widget.ArrayAdapter; import com.activeandroid.Model; public class ModelAdapter<T extends Model> extends ArrayAdapter<T> { public ModelAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } public ModelAdapter(Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId); } public ModelAdapter(Context context, int textViewResourceId, List<T> objects) { super(context, textViewResourceId, objects); } public ModelAdapter(Context context, int resource, int textViewResourceId, List<T> objects) { super(context, resource, textViewResourceId, objects); } /** * Clears the adapter and, if data != null, fills if with new Items. * * @param data A List<T> which members get added to the adapter. */ public void setData(List<T> data) { clear(); if (data != null) { for (T t : data) { add(t); } } } /** * @throws RuntimeException If no record is found. * @return The Id of the record at position. */ @Override public long getItemId(int position) { T t = this.getItem(position); if (t!=null) return t.getId(); else throw new RuntimeException("ItemNotfound"); } }
package com.activeandroid.widget; import java.util.Collection; import java.util.List; import android.content.Context; import android.widget.ArrayAdapter; import com.activeandroid.Model; public class ModelAdapter<T extends Model> extends ArrayAdapter<T> { public ModelAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } public ModelAdapter(Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId); } public ModelAdapter(Context context, int textViewResourceId, List<T> objects) { super(context, textViewResourceId, objects); } public ModelAdapter(Context context, int resource, int textViewResourceId, List<T> objects) { super(context, resource, textViewResourceId, objects); } /** * Clears the adapter and, if data != null, fills if with new Items. * * @param collection A Collection<? extends T> which members get added to the adapter. */ public void setData(Collection<? extends T> collection) { clear(); if (collection != null) { for (T item : collection) { add(item); } } } /** * @return The Id of the record at position. */ @Override public long getItemId(int position) { T item = getItem(position); if (item != null) { return item.getId(); } else { return -1; } } }
Format police. getItemId() fails silently. setData conforms to Android standard.
Format police. getItemId() fails silently. setData conforms to Android standard.
Java
mit
Alanyanbc/sharebook,Alanyanbc/sharebook
java
## Code Before: package com.activeandroid.widget; import java.util.List; import android.content.Context; import android.widget.ArrayAdapter; import com.activeandroid.Model; public class ModelAdapter<T extends Model> extends ArrayAdapter<T> { public ModelAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } public ModelAdapter(Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId); } public ModelAdapter(Context context, int textViewResourceId, List<T> objects) { super(context, textViewResourceId, objects); } public ModelAdapter(Context context, int resource, int textViewResourceId, List<T> objects) { super(context, resource, textViewResourceId, objects); } /** * Clears the adapter and, if data != null, fills if with new Items. * * @param data A List<T> which members get added to the adapter. */ public void setData(List<T> data) { clear(); if (data != null) { for (T t : data) { add(t); } } } /** * @throws RuntimeException If no record is found. * @return The Id of the record at position. */ @Override public long getItemId(int position) { T t = this.getItem(position); if (t!=null) return t.getId(); else throw new RuntimeException("ItemNotfound"); } } ## Instruction: Format police. getItemId() fails silently. setData conforms to Android standard. ## Code After: package com.activeandroid.widget; import java.util.Collection; import java.util.List; import android.content.Context; import android.widget.ArrayAdapter; import com.activeandroid.Model; public class ModelAdapter<T extends Model> extends ArrayAdapter<T> { public ModelAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } public ModelAdapter(Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId); } public ModelAdapter(Context context, int textViewResourceId, List<T> objects) { super(context, textViewResourceId, objects); } public ModelAdapter(Context context, int resource, int textViewResourceId, List<T> objects) { super(context, resource, textViewResourceId, objects); } /** * Clears the adapter and, if data != null, fills if with new Items. * * @param collection A Collection<? extends T> which members get added to the adapter. */ public void setData(Collection<? extends T> collection) { clear(); if (collection != null) { for (T item : collection) { add(item); } } } /** * @return The Id of the record at position. */ @Override public long getItemId(int position) { T item = getItem(position); if (item != null) { return item.getId(); } else { return -1; } } }
// ... existing code ... package com.activeandroid.widget; import java.util.Collection; import java.util.List; import android.content.Context; // ... modified code ... import com.activeandroid.Model; public class ModelAdapter<T extends Model> extends ArrayAdapter<T> { public ModelAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } public ModelAdapter(Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId); } public ModelAdapter(Context context, int textViewResourceId, List<T> objects) { super(context, textViewResourceId, objects); } public ModelAdapter(Context context, int resource, int textViewResourceId, List<T> objects) { super(context, resource, textViewResourceId, objects); } ... /** * Clears the adapter and, if data != null, fills if with new Items. * * @param collection A Collection<? extends T> which members get added to the adapter. */ public void setData(Collection<? extends T> collection) { clear(); if (collection != null) { for (T item : collection) { add(item); } } } /** * @return The Id of the record at position. */ @Override public long getItemId(int position) { T item = getItem(position); if (item != null) { return item.getId(); } else { return -1; } } } // ... rest of the code ...
a7058352df6cd8c0e411df5e1b0948729f8ffe60
dezede/__init__.py
dezede/__init__.py
from __future__ import unicode_literals __version__ = 1, 8, 3 get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède'
from __future__ import unicode_literals __version__ = 2, 0, 0, 'pre' get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède'
Change le numéro de version pour 2.0.0.pre
Change le numéro de version pour 2.0.0.pre
Python
bsd-3-clause
dezede/dezede,dezede/dezede,dezede/dezede,dezede/dezede
python
## Code Before: from __future__ import unicode_literals __version__ = 1, 8, 3 get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède' ## Instruction: Change le numéro de version pour 2.0.0.pre ## Code After: from __future__ import unicode_literals __version__ = 2, 0, 0, 'pre' get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède'
// ... existing code ... from __future__ import unicode_literals __version__ = 2, 0, 0, 'pre' get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède' // ... rest of the code ...
65731a34e152d085f55893c65607b8fa25dcfd63
pathvalidate/_interface.py
pathvalidate/_interface.py
from __future__ import absolute_import, unicode_literals import abc from ._common import validate_null_string from ._six import add_metaclass @add_metaclass(abc.ABCMeta) class NameSanitizer(object): @abc.abstractproperty def reserved_keywords(self): # pragma: no cover pass @abc.abstractmethod def validate(self, value): # pragma: no cover pass @abc.abstractmethod def sanitize(self, value, replacement_text=""): # pragma: no cover pass def _is_reserved_keyword(self, value): return value in self.reserved_keywords @staticmethod def _validate_null_string(text): validate_null_string(text, error_msg="null name")
from __future__ import absolute_import, unicode_literals import abc from ._common import validate_null_string from ._six import add_metaclass from .error import ValidationError @add_metaclass(abc.ABCMeta) class NameSanitizer(object): @abc.abstractproperty def reserved_keywords(self): # pragma: no cover pass @abc.abstractmethod def validate(self, value): # pragma: no cover pass def is_valid(self, value): try: self.validate(value) except (TypeError, ValidationError): return False return True @abc.abstractmethod def sanitize(self, value, replacement_text=""): # pragma: no cover pass def _is_reserved_keyword(self, value): return value in self.reserved_keywords @staticmethod def _validate_null_string(text): validate_null_string(text, error_msg="null name")
Add is_valid method for file sanitizer classes
Add is_valid method for file sanitizer classes
Python
mit
thombashi/pathvalidate
python
## Code Before: from __future__ import absolute_import, unicode_literals import abc from ._common import validate_null_string from ._six import add_metaclass @add_metaclass(abc.ABCMeta) class NameSanitizer(object): @abc.abstractproperty def reserved_keywords(self): # pragma: no cover pass @abc.abstractmethod def validate(self, value): # pragma: no cover pass @abc.abstractmethod def sanitize(self, value, replacement_text=""): # pragma: no cover pass def _is_reserved_keyword(self, value): return value in self.reserved_keywords @staticmethod def _validate_null_string(text): validate_null_string(text, error_msg="null name") ## Instruction: Add is_valid method for file sanitizer classes ## Code After: from __future__ import absolute_import, unicode_literals import abc from ._common import validate_null_string from ._six import add_metaclass from .error import ValidationError @add_metaclass(abc.ABCMeta) class NameSanitizer(object): @abc.abstractproperty def reserved_keywords(self): # pragma: no cover pass @abc.abstractmethod def validate(self, value): # pragma: no cover pass def is_valid(self, value): try: self.validate(value) except (TypeError, ValidationError): return False return True @abc.abstractmethod def sanitize(self, value, replacement_text=""): # pragma: no cover pass def _is_reserved_keyword(self, value): return value in self.reserved_keywords @staticmethod def _validate_null_string(text): validate_null_string(text, error_msg="null name")
# ... existing code ... from ._common import validate_null_string from ._six import add_metaclass from .error import ValidationError @add_metaclass(abc.ABCMeta) # ... modified code ... def validate(self, value): # pragma: no cover pass def is_valid(self, value): try: self.validate(value) except (TypeError, ValidationError): return False return True @abc.abstractmethod def sanitize(self, value, replacement_text=""): # pragma: no cover pass # ... rest of the code ...
51bbc760d0be6f21b1526752f1b4ab5a76c82917
diff_array/diff_array.py
diff_array/diff_array.py
def array_diff(a, b): return a if not b else [x for x in a if x != b[0]]
def array_diff(a, b): return [x for x in a if x not in set(b)]
Change code because failed the random test
Change code because failed the random test
Python
mit
lowks/codewars-katas-python
python
## Code Before: def array_diff(a, b): return a if not b else [x for x in a if x != b[0]] ## Instruction: Change code because failed the random test ## Code After: def array_diff(a, b): return [x for x in a if x not in set(b)]
# ... existing code ... def array_diff(a, b): return [x for x in a if x not in set(b)] # ... rest of the code ...
a40390e142aaf9796ae3fd219e3aabdcda8ee096
src/readstat_malloc.c
src/readstat_malloc.c
void *readstat_malloc(size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { return NULL; } return malloc(len); } void *readstat_calloc(size_t count, size_t size) { if (count > MAX_MALLOC_SIZE || size > MAX_MALLOC_SIZE || count * size > MAX_MALLOC_SIZE) { return NULL; } return calloc(count, size); } void *readstat_realloc(void *ptr, size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { if (ptr) free(ptr); return NULL; } return realloc(ptr, len); }
void *readstat_malloc(size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { return NULL; } return malloc(len); } void *readstat_calloc(size_t count, size_t size) { if (count > MAX_MALLOC_SIZE || size > MAX_MALLOC_SIZE || count * size > MAX_MALLOC_SIZE) { return NULL; } if (count == 0 || size == 0) { return NULL; } return calloc(count, size); } void *readstat_realloc(void *ptr, size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { if (ptr) free(ptr); return NULL; } return realloc(ptr, len); }
Check readstat_calloc for 0-sized input
Check readstat_calloc for 0-sized input
C
mit
WizardMac/ReadStat,WizardMac/ReadStat
c
## Code Before: void *readstat_malloc(size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { return NULL; } return malloc(len); } void *readstat_calloc(size_t count, size_t size) { if (count > MAX_MALLOC_SIZE || size > MAX_MALLOC_SIZE || count * size > MAX_MALLOC_SIZE) { return NULL; } return calloc(count, size); } void *readstat_realloc(void *ptr, size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { if (ptr) free(ptr); return NULL; } return realloc(ptr, len); } ## Instruction: Check readstat_calloc for 0-sized input ## Code After: void *readstat_malloc(size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { return NULL; } return malloc(len); } void *readstat_calloc(size_t count, size_t size) { if (count > MAX_MALLOC_SIZE || size > MAX_MALLOC_SIZE || count * size > MAX_MALLOC_SIZE) { return NULL; } if (count == 0 || size == 0) { return NULL; } return calloc(count, size); } void *readstat_realloc(void *ptr, size_t len) { if (len > MAX_MALLOC_SIZE || len == 0) { if (ptr) free(ptr); return NULL; } return realloc(ptr, len); }
... void *readstat_calloc(size_t count, size_t size) { if (count > MAX_MALLOC_SIZE || size > MAX_MALLOC_SIZE || count * size > MAX_MALLOC_SIZE) { return NULL; } if (count == 0 || size == 0) { return NULL; } return calloc(count, size); ...
39cbe6995ca13a4e24850528c16c33a1bd8f39d5
vtStor/CommandHandlerInterface.h
vtStor/CommandHandlerInterface.h
/* <License> Copyright 2015 Virtium Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </License> */ #ifndef __vtStorCommandHandlerInterface_h__ #define __vtStorCommandHandlerInterface_h__ #pragma once #include <memory> #include "ErrorCodes.h" #include "BufferInterface.h" #include "ProtocolInterface.h" #include "vtStorPlatformDefines.h" namespace vtStor { class VTSTOR_API cDriveInterface; class VTSTOR_API cCommandHandlerInterface { public: cCommandHandlerInterface( std::shared_ptr<Protocol::cProtocolInterface> Protocol ); virtual ~cCommandHandlerInterface(); public: virtual eErrorCode IssueCommand( std::shared_ptr<const cBufferInterface> CommandDescriptor, std::shared_ptr<cBufferInterface> Data ) = 0; protected: std::shared_ptr<Protocol::cProtocolInterface> m_Protocol; }; } #endif
/* <License> Copyright 2015 Virtium Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </License> */ #ifndef __vtStorCommandHandlerInterface_h__ #define __vtStorCommandHandlerInterface_h__ #pragma once #include <memory> #include "ErrorCodes.h" #include "BufferInterface.h" #include "ProtocolInterface.h" #include "vtStorPlatformDefines.h" namespace vtStor { class VTSTOR_API cCommandHandlerInterface { public: cCommandHandlerInterface( std::shared_ptr<Protocol::cProtocolInterface> Protocol ); virtual ~cCommandHandlerInterface(); public: virtual eErrorCode IssueCommand( std::shared_ptr<const cBufferInterface> CommandDescriptor, std::shared_ptr<cBufferInterface> Data ) = 0; protected: std::shared_ptr<Protocol::cProtocolInterface> m_Protocol; }; } #endif
Remove declare: class VTSTOR_API cDriveInterface
Remove declare: class VTSTOR_API cDriveInterface
C
apache-2.0
tranminhtam/vtStor,tranminhtam/vtStor,tranminhtam/vtStor,tranminhtam/vtStor
c
## Code Before: /* <License> Copyright 2015 Virtium Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </License> */ #ifndef __vtStorCommandHandlerInterface_h__ #define __vtStorCommandHandlerInterface_h__ #pragma once #include <memory> #include "ErrorCodes.h" #include "BufferInterface.h" #include "ProtocolInterface.h" #include "vtStorPlatformDefines.h" namespace vtStor { class VTSTOR_API cDriveInterface; class VTSTOR_API cCommandHandlerInterface { public: cCommandHandlerInterface( std::shared_ptr<Protocol::cProtocolInterface> Protocol ); virtual ~cCommandHandlerInterface(); public: virtual eErrorCode IssueCommand( std::shared_ptr<const cBufferInterface> CommandDescriptor, std::shared_ptr<cBufferInterface> Data ) = 0; protected: std::shared_ptr<Protocol::cProtocolInterface> m_Protocol; }; } #endif ## Instruction: Remove declare: class VTSTOR_API cDriveInterface ## Code After: /* <License> Copyright 2015 Virtium Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. </License> */ #ifndef __vtStorCommandHandlerInterface_h__ #define __vtStorCommandHandlerInterface_h__ #pragma once #include <memory> #include "ErrorCodes.h" #include "BufferInterface.h" #include "ProtocolInterface.h" #include "vtStorPlatformDefines.h" namespace vtStor { class VTSTOR_API cCommandHandlerInterface { public: cCommandHandlerInterface( std::shared_ptr<Protocol::cProtocolInterface> Protocol ); virtual ~cCommandHandlerInterface(); public: virtual eErrorCode IssueCommand( std::shared_ptr<const cBufferInterface> CommandDescriptor, std::shared_ptr<cBufferInterface> Data ) = 0; protected: std::shared_ptr<Protocol::cProtocolInterface> m_Protocol; }; } #endif
// ... existing code ... namespace vtStor { class VTSTOR_API cCommandHandlerInterface { public: // ... rest of the code ...
8ce14cfb0044d90f2503a7bd940a7f6401c15db2
wagtail/admin/rich_text/editors/draftail.py
wagtail/admin/rich_text/editors/draftail.py
from django.forms import widgets from wagtail.admin.edit_handlers import RichTextFieldPanel from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter from wagtail.core.rich_text import features class DraftailRichTextArea(widgets.Textarea): # this class's constructor accepts a 'features' kwarg accepts_features = True def get_panel(self): return RichTextFieldPanel def __init__(self, *args, **kwargs): self.options = kwargs.pop('options', None) self.features = kwargs.pop('features', None) if self.features is None: self.features = features.get_default_features() self.converter = ContentstateConverter(self.features) super().__init__(*args, **kwargs) def render(self, name, value, attrs=None): if value is None: translated_value = None else: translated_value = self.converter.from_database_format(value) return super().render(name, translated_value, attrs) def value_from_datadict(self, data, files, name): original_value = super().value_from_datadict(data, files, name) if original_value is None: return None return self.converter.to_database_format(original_value)
import json from django.forms import Media, widgets from wagtail.admin.edit_handlers import RichTextFieldPanel from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter from wagtail.core.rich_text import features class DraftailRichTextArea(widgets.Textarea): # this class's constructor accepts a 'features' kwarg accepts_features = True def get_panel(self): return RichTextFieldPanel def __init__(self, *args, **kwargs): self.options = kwargs.pop('options', None) self.features = kwargs.pop('features', None) if self.features is None: self.features = features.get_default_features() self.converter = ContentstateConverter(self.features) super().__init__(*args, **kwargs) def render(self, name, value, attrs=None): if value is None: translated_value = None else: translated_value = self.converter.from_database_format(value) return super().render(name, translated_value, attrs) def render_js_init(self, id_, name, value): return "window.draftail.initEditor('{name}', {opts})".format( name=name, opts=json.dumps(self.options)) def value_from_datadict(self, data, files, name): original_value = super().value_from_datadict(data, files, name) if original_value is None: return None return self.converter.to_database_format(original_value) @property def media(self): return Media(js=[ 'wagtailadmin/js/draftail.js', ], css={ 'all': ['wagtailadmin/css/panels/dratail.css'] })
Integrate Draftail-related assets with Django widget
Integrate Draftail-related assets with Django widget
Python
bsd-3-clause
mikedingjan/wagtail,kaedroho/wagtail,timorieber/wagtail,mixxorz/wagtail,torchbox/wagtail,gasman/wagtail,gasman/wagtail,wagtail/wagtail,timorieber/wagtail,mixxorz/wagtail,nealtodd/wagtail,nimasmi/wagtail,kaedroho/wagtail,mikedingjan/wagtail,takeflight/wagtail,thenewguy/wagtail,zerolab/wagtail,timorieber/wagtail,thenewguy/wagtail,mixxorz/wagtail,FlipperPA/wagtail,zerolab/wagtail,takeflight/wagtail,nealtodd/wagtail,nimasmi/wagtail,zerolab/wagtail,takeflight/wagtail,zerolab/wagtail,mikedingjan/wagtail,mixxorz/wagtail,kaedroho/wagtail,torchbox/wagtail,thenewguy/wagtail,wagtail/wagtail,torchbox/wagtail,rsalmaso/wagtail,gasman/wagtail,rsalmaso/wagtail,zerolab/wagtail,nimasmi/wagtail,thenewguy/wagtail,wagtail/wagtail,rsalmaso/wagtail,nealtodd/wagtail,thenewguy/wagtail,timorieber/wagtail,rsalmaso/wagtail,torchbox/wagtail,nimasmi/wagtail,rsalmaso/wagtail,jnns/wagtail,kaedroho/wagtail,FlipperPA/wagtail,kaedroho/wagtail,takeflight/wagtail,gasman/wagtail,nealtodd/wagtail,wagtail/wagtail,FlipperPA/wagtail,wagtail/wagtail,jnns/wagtail,jnns/wagtail,FlipperPA/wagtail,mikedingjan/wagtail,jnns/wagtail,mixxorz/wagtail,gasman/wagtail
python
## Code Before: from django.forms import widgets from wagtail.admin.edit_handlers import RichTextFieldPanel from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter from wagtail.core.rich_text import features class DraftailRichTextArea(widgets.Textarea): # this class's constructor accepts a 'features' kwarg accepts_features = True def get_panel(self): return RichTextFieldPanel def __init__(self, *args, **kwargs): self.options = kwargs.pop('options', None) self.features = kwargs.pop('features', None) if self.features is None: self.features = features.get_default_features() self.converter = ContentstateConverter(self.features) super().__init__(*args, **kwargs) def render(self, name, value, attrs=None): if value is None: translated_value = None else: translated_value = self.converter.from_database_format(value) return super().render(name, translated_value, attrs) def value_from_datadict(self, data, files, name): original_value = super().value_from_datadict(data, files, name) if original_value is None: return None return self.converter.to_database_format(original_value) ## Instruction: Integrate Draftail-related assets with Django widget ## Code After: import json from django.forms import Media, widgets from wagtail.admin.edit_handlers import RichTextFieldPanel from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter from wagtail.core.rich_text import features class DraftailRichTextArea(widgets.Textarea): # this class's constructor accepts a 'features' kwarg accepts_features = True def get_panel(self): return RichTextFieldPanel def __init__(self, *args, **kwargs): self.options = kwargs.pop('options', None) self.features = kwargs.pop('features', None) if self.features is None: self.features = features.get_default_features() self.converter = ContentstateConverter(self.features) super().__init__(*args, **kwargs) def render(self, name, value, attrs=None): if value is None: translated_value = None else: translated_value = self.converter.from_database_format(value) return super().render(name, translated_value, attrs) def render_js_init(self, id_, name, value): return "window.draftail.initEditor('{name}', {opts})".format( name=name, opts=json.dumps(self.options)) def value_from_datadict(self, data, files, name): original_value = super().value_from_datadict(data, files, name) if original_value is None: return None return self.converter.to_database_format(original_value) @property def media(self): return Media(js=[ 'wagtailadmin/js/draftail.js', ], css={ 'all': ['wagtailadmin/css/panels/dratail.css'] })
# ... existing code ... import json from django.forms import Media, widgets from wagtail.admin.edit_handlers import RichTextFieldPanel from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter # ... modified code ... translated_value = self.converter.from_database_format(value) return super().render(name, translated_value, attrs) def render_js_init(self, id_, name, value): return "window.draftail.initEditor('{name}', {opts})".format( name=name, opts=json.dumps(self.options)) def value_from_datadict(self, data, files, name): original_value = super().value_from_datadict(data, files, name) if original_value is None: return None return self.converter.to_database_format(original_value) @property def media(self): return Media(js=[ 'wagtailadmin/js/draftail.js', ], css={ 'all': ['wagtailadmin/css/panels/dratail.css'] }) # ... rest of the code ...
f9012b88f60f8e4ac96cb55aea763edc74ad586e
shell/view/BuddyIcon.py
shell/view/BuddyIcon.py
from sugar.canvas.MenuIcon import MenuIcon from view.BuddyMenu import BuddyMenu class BuddyIcon(MenuIcon): def __init__(self, shell, menu_shell, friend): MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy', color=friend.get_color(), size=96) self._shell = shell self._friend = friend def set_popup_distance(self, distance): self._popup_distance = distance def create_menu(self): menu = BuddyMenu(self._shell, self._friend) menu.connect('action', self._popup_action_cb) return menu def _popup_action_cb(self, popup, action): self.popdown() model = self._shell.get_model() if action == BuddyMenu.ACTION_REMOVE_FRIEND: friends = model.get_friends() friends.remove(buddy) buddy = self._friend.get_buddy() if buddy == None: return if action == BuddyMenu.ACTION_INVITE: activity = model.get_current_activity() activity.invite(buddy) elif action == BuddyMenu.ACTION_MAKE_FRIEND: friends = model.get_friends() friends.make_friend(buddy)
from sugar.canvas.MenuIcon import MenuIcon from view.BuddyMenu import BuddyMenu class BuddyIcon(MenuIcon): def __init__(self, shell, menu_shell, friend): MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy', color=friend.get_color(), size=96) self._shell = shell self._friend = friend def set_popup_distance(self, distance): self._popup_distance = distance def create_menu(self): menu = BuddyMenu(self._shell, self._friend) menu.connect('action', self._popup_action_cb) return menu def _popup_action_cb(self, popup, action): self.popdown() buddy = self._friend.get_buddy() if buddy == None: return model = self._shell.get_model() if action == BuddyMenu.ACTION_INVITE: activity = model.get_current_activity() activity.invite(buddy) elif action == BuddyMenu.ACTION_MAKE_FRIEND: friends = model.get_friends() friends.make_friend(buddy) elif action == BuddyMenu.ACTION_REMOVE_FRIEND: friends = model.get_friends() friends.remove(buddy)
Move remove code down to fix undefined var error
Move remove code down to fix undefined var error
Python
lgpl-2.1
samdroid-apps/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,samdroid-apps/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,godiard/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,ceibal-tatu/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,Daksh/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,i5o/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,tchx84/debian-pkg-sugar-toolkit,ceibal-tatu/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,ceibal-tatu/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,puneetgkaur/sugar-toolkit-gtk3,samdroid-apps/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,tchx84/debian-pkg-sugar-toolkit-gtk3,puneetgkaur/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit,puneetgkaur/backup_sugar_sugartoolkit,manuq/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,tchx84/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,gusDuarte/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,ceibal-tatu/sugar-toolkit,sugarlabs/sugar-toolkit-gtk3,sugarlabs/sugar-toolkit-gtk3
python
## Code Before: from sugar.canvas.MenuIcon import MenuIcon from view.BuddyMenu import BuddyMenu class BuddyIcon(MenuIcon): def __init__(self, shell, menu_shell, friend): MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy', color=friend.get_color(), size=96) self._shell = shell self._friend = friend def set_popup_distance(self, distance): self._popup_distance = distance def create_menu(self): menu = BuddyMenu(self._shell, self._friend) menu.connect('action', self._popup_action_cb) return menu def _popup_action_cb(self, popup, action): self.popdown() model = self._shell.get_model() if action == BuddyMenu.ACTION_REMOVE_FRIEND: friends = model.get_friends() friends.remove(buddy) buddy = self._friend.get_buddy() if buddy == None: return if action == BuddyMenu.ACTION_INVITE: activity = model.get_current_activity() activity.invite(buddy) elif action == BuddyMenu.ACTION_MAKE_FRIEND: friends = model.get_friends() friends.make_friend(buddy) ## Instruction: Move remove code down to fix undefined var error ## Code After: from sugar.canvas.MenuIcon import MenuIcon from view.BuddyMenu import BuddyMenu class BuddyIcon(MenuIcon): def __init__(self, shell, menu_shell, friend): MenuIcon.__init__(self, menu_shell, icon_name='stock-buddy', color=friend.get_color(), size=96) self._shell = shell self._friend = friend def set_popup_distance(self, distance): self._popup_distance = distance def create_menu(self): menu = BuddyMenu(self._shell, self._friend) menu.connect('action', self._popup_action_cb) return menu def _popup_action_cb(self, popup, action): self.popdown() buddy = self._friend.get_buddy() if buddy == None: return model = self._shell.get_model() if action == BuddyMenu.ACTION_INVITE: activity = model.get_current_activity() activity.invite(buddy) elif action == BuddyMenu.ACTION_MAKE_FRIEND: friends = model.get_friends() friends.make_friend(buddy) elif action == BuddyMenu.ACTION_REMOVE_FRIEND: friends = model.get_friends() friends.remove(buddy)
// ... existing code ... def _popup_action_cb(self, popup, action): self.popdown() buddy = self._friend.get_buddy() if buddy == None: return model = self._shell.get_model() if action == BuddyMenu.ACTION_INVITE: activity = model.get_current_activity() activity.invite(buddy) // ... modified code ... elif action == BuddyMenu.ACTION_MAKE_FRIEND: friends = model.get_friends() friends.make_friend(buddy) elif action == BuddyMenu.ACTION_REMOVE_FRIEND: friends = model.get_friends() friends.remove(buddy) // ... rest of the code ...
aaae301f62b4e0b3cdd5d1756a03b619a8f18222
tests/test_hamilton.py
tests/test_hamilton.py
"""Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], )
"""Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) @pytest.mark.parametrize("convention", ["a", "1", None]) def test_invalid_convention(get_model, convention): """ Test that giving an invalid 'convention' raises an error. """ model = get_model(t1=0, t2=0.1) with pytest.raises(ValueError): model.hamilton((0, 0, 0), convention=convention)
Add test for invalid 'convention' in hamilton method
Add test for invalid 'convention' in hamilton method
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
python
## Code Before: """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) ## Instruction: Add test for invalid 'convention' in hamilton method ## Code After: """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) @pytest.mark.parametrize("convention", ["a", "1", None]) def test_invalid_convention(get_model, convention): """ Test that giving an invalid 'convention' raises an error. """ model = get_model(t1=0, t2=0.1) with pytest.raises(ValueError): model.hamilton((0, 0, 0), convention=convention)
# ... existing code ... model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) @pytest.mark.parametrize("convention", ["a", "1", None]) def test_invalid_convention(get_model, convention): """ Test that giving an invalid 'convention' raises an error. """ model = get_model(t1=0, t2=0.1) with pytest.raises(ValueError): model.hamilton((0, 0, 0), convention=convention) # ... rest of the code ...
744842877aae29e3308fc383c345596333012663
src/main/java/org/usfirst/frc/team1360/robot/autonomous/AutonomousManager.java
src/main/java/org/usfirst/frc/team1360/robot/autonomous/AutonomousManager.java
package main.java.org.usfirst.frc.team1360.robot.autonomous; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.CommandGroup; import main.java.org.usfirst.frc.team1360.robot.util.CommandData; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class AutonomousManager { private static final String AUTONOMOUSPACKAGE = AutonomousManager.class.getCanonicalName().replace("AutonomousManager", ""); public static Command getAction(String name, CommandData commandData) { Class<?> clazz; String path = AUTONOMOUSPACKAGE + name; if(!name.contains("groups.") && !name.contains("actions.")) path = AUTONOMOUSPACKAGE + "actions." + name; try { clazz = Class.forName(path); Constructor<?> constructor = clazz.getConstructor(CommandData.class); return (Command) constructor.newInstance(commandData); } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return null; } public static CommandGroup getGroup(String name, CommandData commandData) { return (CommandGroup) getAction("groups." + name, commandData); } }
package org.usfirst.frc.team1360.robot.autonomous; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.CommandGroup; import org.usfirst.frc.team1360.robot.util.CommandData; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class AutonomousManager { private static final String AUTONOMOUSPACKAGE = AutonomousManager.class.getCanonicalName().replace("AutonomousManager", ""); public static Command getAction(String name, CommandData commandData) { Class<?> clazz; String path = AUTONOMOUSPACKAGE + name; if(!name.contains("groups.") && !name.contains("actions.")) path = AUTONOMOUSPACKAGE + "actions." + name; try { clazz = Class.forName(path); Constructor<?> constructor = clazz.getConstructor(CommandData.class); return (Command) constructor.newInstance(commandData); } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return null; } public static CommandGroup getGroup(String name, CommandData commandData) { return (CommandGroup) getAction("groups." + name, commandData); } }
Fix ethan's eclipse package issues; Jamie ETHAN - NO MORE ECLIPSE. EVER.
Fix ethan's eclipse package issues; Jamie ETHAN - NO MORE ECLIPSE. EVER.
Java
mit
FRC1360/Stronghold2016
java
## Code Before: package main.java.org.usfirst.frc.team1360.robot.autonomous; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.CommandGroup; import main.java.org.usfirst.frc.team1360.robot.util.CommandData; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class AutonomousManager { private static final String AUTONOMOUSPACKAGE = AutonomousManager.class.getCanonicalName().replace("AutonomousManager", ""); public static Command getAction(String name, CommandData commandData) { Class<?> clazz; String path = AUTONOMOUSPACKAGE + name; if(!name.contains("groups.") && !name.contains("actions.")) path = AUTONOMOUSPACKAGE + "actions." + name; try { clazz = Class.forName(path); Constructor<?> constructor = clazz.getConstructor(CommandData.class); return (Command) constructor.newInstance(commandData); } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return null; } public static CommandGroup getGroup(String name, CommandData commandData) { return (CommandGroup) getAction("groups." + name, commandData); } } ## Instruction: Fix ethan's eclipse package issues; Jamie ETHAN - NO MORE ECLIPSE. EVER. ## Code After: package org.usfirst.frc.team1360.robot.autonomous; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.CommandGroup; import org.usfirst.frc.team1360.robot.util.CommandData; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class AutonomousManager { private static final String AUTONOMOUSPACKAGE = AutonomousManager.class.getCanonicalName().replace("AutonomousManager", ""); public static Command getAction(String name, CommandData commandData) { Class<?> clazz; String path = AUTONOMOUSPACKAGE + name; if(!name.contains("groups.") && !name.contains("actions.")) path = AUTONOMOUSPACKAGE + "actions." + name; try { clazz = Class.forName(path); Constructor<?> constructor = clazz.getConstructor(CommandData.class); return (Command) constructor.newInstance(commandData); } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return null; } public static CommandGroup getGroup(String name, CommandData commandData) { return (CommandGroup) getAction("groups." + name, commandData); } }
# ... existing code ... package org.usfirst.frc.team1360.robot.autonomous; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.CommandGroup; import org.usfirst.frc.team1360.robot.util.CommandData; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; # ... rest of the code ...
a9094588c176059e719361b25433fd17e2113c48
test/com/twu/biblioteca/BibliotecaAppTest.java
test/com/twu/biblioteca/BibliotecaAppTest.java
package com.twu.biblioteca; import com.twu.biblioteca.views.BibliotecaAppView; import com.twu.biblioteca.views.BooksView; import com.twu.biblioteca.views.MenuView; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class BibliotecaAppTest { @Mock private BibliotecaAppView mockBibliotecaAppView; @Mock private BooksView mockBooksView; @Mock private MenuView mockMenuView; @Test public void shouldInvokeMethodsOnBibliotecaAppViewBooksViewAndMenuView() throws Exception { BibliotecaApp bibliotecaApp = new BibliotecaApp(mockBibliotecaAppView, mockBooksView, mockMenuView); bibliotecaApp.start(); Mockito.verify(mockBibliotecaAppView).display("***Welcome to Biblioteca***"); Mockito.verify(mockMenuView).display(); } }
package com.twu.biblioteca; import com.twu.biblioteca.views.BibliotecaAppView; import com.twu.biblioteca.views.BooksView; import com.twu.biblioteca.views.MenuView; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class BibliotecaAppTest { @Mock private BibliotecaAppView mockBibliotecaAppView; @Mock private BooksView mockBooksView; @Mock private MenuView mockMenuView; @Mock private Books mockBooks; @Mock private Menu mockMenu; @Test public void shouldInvokeMethodsOnBibliotecaAppViewBooksViewAndMenuView() throws Exception { BibliotecaApp bibliotecaApp = new BibliotecaApp(mockBibliotecaAppView, mockBooksView, mockMenuView, mockBooks, mockMenu); bibliotecaApp.start(); Mockito.verify(mockBibliotecaAppView).display("***Welcome to Biblioteca***"); Mockito.verify(mockMenuView).display(); } }
Fix - added two missing parameters to the constructor
Fix - added two missing parameters to the constructor
Java
apache-2.0
arunvelsriram/twu-biblioteca-arunvelsriram
java
## Code Before: package com.twu.biblioteca; import com.twu.biblioteca.views.BibliotecaAppView; import com.twu.biblioteca.views.BooksView; import com.twu.biblioteca.views.MenuView; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class BibliotecaAppTest { @Mock private BibliotecaAppView mockBibliotecaAppView; @Mock private BooksView mockBooksView; @Mock private MenuView mockMenuView; @Test public void shouldInvokeMethodsOnBibliotecaAppViewBooksViewAndMenuView() throws Exception { BibliotecaApp bibliotecaApp = new BibliotecaApp(mockBibliotecaAppView, mockBooksView, mockMenuView); bibliotecaApp.start(); Mockito.verify(mockBibliotecaAppView).display("***Welcome to Biblioteca***"); Mockito.verify(mockMenuView).display(); } } ## Instruction: Fix - added two missing parameters to the constructor ## Code After: package com.twu.biblioteca; import com.twu.biblioteca.views.BibliotecaAppView; import com.twu.biblioteca.views.BooksView; import com.twu.biblioteca.views.MenuView; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class BibliotecaAppTest { @Mock private BibliotecaAppView mockBibliotecaAppView; @Mock private BooksView mockBooksView; @Mock private MenuView mockMenuView; @Mock private Books mockBooks; @Mock private Menu mockMenu; @Test public void shouldInvokeMethodsOnBibliotecaAppViewBooksViewAndMenuView() throws Exception { BibliotecaApp bibliotecaApp = new BibliotecaApp(mockBibliotecaAppView, mockBooksView, mockMenuView, mockBooks, mockMenu); bibliotecaApp.start(); Mockito.verify(mockBibliotecaAppView).display("***Welcome to Biblioteca***"); Mockito.verify(mockMenuView).display(); } }
... private BooksView mockBooksView; @Mock private MenuView mockMenuView; @Mock private Books mockBooks; @Mock private Menu mockMenu; @Test public void shouldInvokeMethodsOnBibliotecaAppViewBooksViewAndMenuView() throws Exception { BibliotecaApp bibliotecaApp = new BibliotecaApp(mockBibliotecaAppView, mockBooksView, mockMenuView, mockBooks, mockMenu); bibliotecaApp.start(); Mockito.verify(mockBibliotecaAppView).display("***Welcome to Biblioteca***"); ...
451951b311ef6e2bb76348a116dc0465f735348e
pytest_watch/config.py
pytest_watch/config.py
try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser import pytest CLI_OPTION_PREFIX = '--' class CollectConfig(object): """ A pytest plugin to gets the configuration file. """ def __init__(self): self.path = None def pytest_cmdline_main(self, config): self.path = str(config.inifile) def merge_config(args): collect_config = CollectConfig() pytest.main(['--collect-only'], plugins=[collect_config]) if not collect_config.path: return config = ConfigParser() config.read(collect_config.path) if not config.has_section('pytest-watch'): return for cli_name in args: if not cli_name.startswith(CLI_OPTION_PREFIX): continue config_name = cli_name[len(CLI_OPTION_PREFIX):] # Let CLI options take precedence if args[cli_name]: continue # Find config option if not config.has_option('pytest-watch', config_name): continue # Merge config option using the expected type if isinstance(args[cli_name], bool): args[cli_name] = config.getboolean('pytest-watch', config_name) else: args[cli_name] = config.get('pytest-watch', config_name)
try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser import pytest CLI_OPTION_PREFIX = '--' class CollectConfig(object): """ A pytest plugin to gets the configuration file. """ def __init__(self): self.path = None def pytest_cmdline_main(self, config): if config.inifile: self.path = str(config.inifile) def merge_config(args): collect_config = CollectConfig() pytest.main(['--collect-only'], plugins=[collect_config]) if not collect_config.path: return config = ConfigParser() config.read(collect_config.path) if not config.has_section('pytest-watch'): return for cli_name in args: if not cli_name.startswith(CLI_OPTION_PREFIX): continue config_name = cli_name[len(CLI_OPTION_PREFIX):] # Let CLI options take precedence if args[cli_name]: continue # Find config option if not config.has_option('pytest-watch', config_name): continue # Merge config option using the expected type if isinstance(args[cli_name], bool): args[cli_name] = config.getboolean('pytest-watch', config_name) else: args[cli_name] = config.get('pytest-watch', config_name)
Fix running when pytest.ini is not present.
Fix running when pytest.ini is not present.
Python
mit
joeyespo/pytest-watch
python
## Code Before: try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser import pytest CLI_OPTION_PREFIX = '--' class CollectConfig(object): """ A pytest plugin to gets the configuration file. """ def __init__(self): self.path = None def pytest_cmdline_main(self, config): self.path = str(config.inifile) def merge_config(args): collect_config = CollectConfig() pytest.main(['--collect-only'], plugins=[collect_config]) if not collect_config.path: return config = ConfigParser() config.read(collect_config.path) if not config.has_section('pytest-watch'): return for cli_name in args: if not cli_name.startswith(CLI_OPTION_PREFIX): continue config_name = cli_name[len(CLI_OPTION_PREFIX):] # Let CLI options take precedence if args[cli_name]: continue # Find config option if not config.has_option('pytest-watch', config_name): continue # Merge config option using the expected type if isinstance(args[cli_name], bool): args[cli_name] = config.getboolean('pytest-watch', config_name) else: args[cli_name] = config.get('pytest-watch', config_name) ## Instruction: Fix running when pytest.ini is not present. ## Code After: try: from configparser import ConfigParser except ImportError: from ConfigParser import ConfigParser import pytest CLI_OPTION_PREFIX = '--' class CollectConfig(object): """ A pytest plugin to gets the configuration file. """ def __init__(self): self.path = None def pytest_cmdline_main(self, config): if config.inifile: self.path = str(config.inifile) def merge_config(args): collect_config = CollectConfig() pytest.main(['--collect-only'], plugins=[collect_config]) if not collect_config.path: return config = ConfigParser() config.read(collect_config.path) if not config.has_section('pytest-watch'): return for cli_name in args: if not cli_name.startswith(CLI_OPTION_PREFIX): continue config_name = cli_name[len(CLI_OPTION_PREFIX):] # Let CLI options take precedence if args[cli_name]: continue # Find config option if not config.has_option('pytest-watch', config_name): continue # Merge config option using the expected type if isinstance(args[cli_name], bool): args[cli_name] = config.getboolean('pytest-watch', config_name) else: args[cli_name] = config.get('pytest-watch', config_name)
// ... existing code ... self.path = None def pytest_cmdline_main(self, config): if config.inifile: self.path = str(config.inifile) def merge_config(args): // ... rest of the code ...
df958f04d1f5d764ce47e75fc55e081b3ed3d275
src/world/World.java
src/world/World.java
package edu.stuy.starlorn.world; import edu.stuy.starlorn.entities.Entity; import java.util.ArrayList; /* * Represents a world with entities in it */ public class World { private ArrayList<Entity> _entities; public World() { _entities = new ArrayList<Entity>(); } public void addEntity(Entity e) { _entities.add(e); } public void stepAll() { for (Entity e : _entities) { e.preStep(); e.step(); e.postStep(); } } }
package edu.stuy.starlorn.world; import edu.stuy.starlorn.entities.Entity; import java.util.LinkedList; /* * Represents a world with entities in it */ public class World { private LinkedList<Entity> _entities; public World() { _entities = new LinkedList<Entity>(); } public void addEntity(Entity e) { _entities.add(e); } public void stepAll() { for (Entity e : _entities) { e.preStep(); e.step(); e.postStep(); } } }
Change ArrayList of Entities to LinkedList
Change ArrayList of Entities to LinkedList
Java
mit
Hypersonic/Starlorn
java
## Code Before: package edu.stuy.starlorn.world; import edu.stuy.starlorn.entities.Entity; import java.util.ArrayList; /* * Represents a world with entities in it */ public class World { private ArrayList<Entity> _entities; public World() { _entities = new ArrayList<Entity>(); } public void addEntity(Entity e) { _entities.add(e); } public void stepAll() { for (Entity e : _entities) { e.preStep(); e.step(); e.postStep(); } } } ## Instruction: Change ArrayList of Entities to LinkedList ## Code After: package edu.stuy.starlorn.world; import edu.stuy.starlorn.entities.Entity; import java.util.LinkedList; /* * Represents a world with entities in it */ public class World { private LinkedList<Entity> _entities; public World() { _entities = new LinkedList<Entity>(); } public void addEntity(Entity e) { _entities.add(e); } public void stepAll() { for (Entity e : _entities) { e.preStep(); e.step(); e.postStep(); } } }
# ... existing code ... import edu.stuy.starlorn.entities.Entity; import java.util.LinkedList; /* * Represents a world with entities in it */ public class World { private LinkedList<Entity> _entities; public World() { _entities = new LinkedList<Entity>(); } public void addEntity(Entity e) { # ... rest of the code ...
ff495edc51298c2975ffc5176569fff0deea61e7
karma-common/src/main/java/edu/isi/karma/imp/Import.java
karma-common/src/main/java/edu/isi/karma/imp/Import.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.isi.karma.imp; import java.io.IOException; import org.json.JSONException; import edu.isi.karma.rep.RepFactory; import edu.isi.karma.rep.Worksheet; import edu.isi.karma.rep.Workspace; import edu.isi.karma.webserver.KarmaException; /** * * This abstract class in an interface to all classes with import functionality * * @author mielvandersande */ public abstract class Import { private final RepFactory factory; private Worksheet worksheet; protected Workspace workspace; public Import(String worksheetName, Workspace workspace, String encoding) { this.factory = workspace.getFactory(); this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding); this.workspace = workspace; } public Import(RepFactory factory, Worksheet worksheet) { this.factory = factory; this.worksheet = worksheet; } public RepFactory getFactory() { return factory; } public Worksheet getWorksheet() { return worksheet; } public void createWorksheet(String worksheetName, Workspace workspace, String encoding) { this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding); } /* * Generate worksheet from data */ public abstract Worksheet generateWorksheet() throws JSONException, IOException, KarmaException, ClassNotFoundException; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.isi.karma.imp; import java.io.IOException; import org.json.JSONException; import edu.isi.karma.rep.RepFactory; import edu.isi.karma.rep.Worksheet; import edu.isi.karma.rep.Workspace; import edu.isi.karma.webserver.KarmaException; /** * * This abstract class in an interface to all classes with import functionality * * @author mielvandersande */ public abstract class Import { private final RepFactory factory; private Worksheet worksheet; protected Workspace workspace; public static int MAX_WORKSHEET_NAME_LEN = 100; public Import(String worksheetName, Workspace workspace, String encoding) { this.factory = workspace.getFactory(); if(worksheetName.length() > MAX_WORKSHEET_NAME_LEN) worksheetName = worksheetName.substring(0, MAX_WORKSHEET_NAME_LEN) + "..."; this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding); this.workspace = workspace; } public Import(RepFactory factory, Worksheet worksheet) { this.factory = factory; this.worksheet = worksheet; } public RepFactory getFactory() { return factory; } public Worksheet getWorksheet() { return worksheet; } public void createWorksheet(String worksheetName, Workspace workspace, String encoding) { this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding); } /* * Generate worksheet from data */ public abstract Worksheet generateWorksheet() throws JSONException, IOException, KarmaException, ClassNotFoundException; }
Set a max length for worksheet name
Set a max length for worksheet name
Java
apache-2.0
sylvanmist/Web-Karma,usc-isi-i2/Web-Karma,rpiotti/Web-Karma,usc-isi-i2/Web-Karma,rpiotti/Web-Karma,sylvanmist/Web-Karma,rpiotti/Web-Karma,sylvanmist/Web-Karma,usc-isi-i2/Web-Karma,rpiotti/Web-Karma,usc-isi-i2/Web-Karma,rpiotti/Web-Karma,sylvanmist/Web-Karma,sylvanmist/Web-Karma,usc-isi-i2/Web-Karma
java
## Code Before: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.isi.karma.imp; import java.io.IOException; import org.json.JSONException; import edu.isi.karma.rep.RepFactory; import edu.isi.karma.rep.Worksheet; import edu.isi.karma.rep.Workspace; import edu.isi.karma.webserver.KarmaException; /** * * This abstract class in an interface to all classes with import functionality * * @author mielvandersande */ public abstract class Import { private final RepFactory factory; private Worksheet worksheet; protected Workspace workspace; public Import(String worksheetName, Workspace workspace, String encoding) { this.factory = workspace.getFactory(); this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding); this.workspace = workspace; } public Import(RepFactory factory, Worksheet worksheet) { this.factory = factory; this.worksheet = worksheet; } public RepFactory getFactory() { return factory; } public Worksheet getWorksheet() { return worksheet; } public void createWorksheet(String worksheetName, Workspace workspace, String encoding) { this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding); } /* * Generate worksheet from data */ public abstract Worksheet generateWorksheet() throws JSONException, IOException, KarmaException, ClassNotFoundException; } ## Instruction: Set a max length for worksheet name ## Code After: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.isi.karma.imp; import java.io.IOException; import org.json.JSONException; import edu.isi.karma.rep.RepFactory; import edu.isi.karma.rep.Worksheet; import edu.isi.karma.rep.Workspace; import edu.isi.karma.webserver.KarmaException; /** * * This abstract class in an interface to all classes with import functionality * * @author mielvandersande */ public abstract class Import { private final RepFactory factory; private Worksheet worksheet; protected Workspace workspace; public static int MAX_WORKSHEET_NAME_LEN = 100; public Import(String worksheetName, Workspace workspace, String encoding) { this.factory = workspace.getFactory(); if(worksheetName.length() > MAX_WORKSHEET_NAME_LEN) worksheetName = worksheetName.substring(0, MAX_WORKSHEET_NAME_LEN) + "..."; this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding); this.workspace = workspace; } public Import(RepFactory factory, Worksheet worksheet) { this.factory = factory; this.worksheet = worksheet; } public RepFactory getFactory() { return factory; } public Worksheet getWorksheet() { return worksheet; } public void createWorksheet(String worksheetName, Workspace workspace, String encoding) { this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding); } /* * Generate worksheet from data */ public abstract Worksheet generateWorksheet() throws JSONException, IOException, KarmaException, ClassNotFoundException; }
... private Worksheet worksheet; protected Workspace workspace; public static int MAX_WORKSHEET_NAME_LEN = 100; public Import(String worksheetName, Workspace workspace, String encoding) { this.factory = workspace.getFactory(); if(worksheetName.length() > MAX_WORKSHEET_NAME_LEN) worksheetName = worksheetName.substring(0, MAX_WORKSHEET_NAME_LEN) + "..."; this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding); this.workspace = workspace; } ...
7e3aa7d73b75c51946156a18126cac7ba8446070
DaggerAndroidHelperLibrary/src/main/java/com/anprosit/android/dagger/factory/MediaPlayerFactory.java
DaggerAndroidHelperLibrary/src/main/java/com/anprosit/android/dagger/factory/MediaPlayerFactory.java
package com.anprosit.android.dagger.factory; import android.content.Context; import android.media.MediaPlayer; /** * Created by Hirofumi Nakagawa on 13/09/06. */ public class MediaPlayerFactory { public MediaPlayer create(Context context, int resId) { return MediaPlayer.create(context, resId); } public MediaPlayer create() { return new MediaPlayer(); } }
package com.anprosit.android.dagger.factory; import android.content.Context; import android.media.MediaPlayer; import android.net.Uri; /** * @author hnakagawa */ public class MediaPlayerFactory { public MediaPlayer create(Context context, int resId) { return MediaPlayer.create(context, resId); } public MediaPlayer create(Context context, Uri uri) { return MediaPlayer.create(context, uri); } public MediaPlayer create() { return new MediaPlayer(); } }
Add factory method for media player
Add factory method for media player
Java
apache-2.0
hnakagawa/dagger-android-helper-library,KeithYokoma/dagger-android-helper-library
java
## Code Before: package com.anprosit.android.dagger.factory; import android.content.Context; import android.media.MediaPlayer; /** * Created by Hirofumi Nakagawa on 13/09/06. */ public class MediaPlayerFactory { public MediaPlayer create(Context context, int resId) { return MediaPlayer.create(context, resId); } public MediaPlayer create() { return new MediaPlayer(); } } ## Instruction: Add factory method for media player ## Code After: package com.anprosit.android.dagger.factory; import android.content.Context; import android.media.MediaPlayer; import android.net.Uri; /** * @author hnakagawa */ public class MediaPlayerFactory { public MediaPlayer create(Context context, int resId) { return MediaPlayer.create(context, resId); } public MediaPlayer create(Context context, Uri uri) { return MediaPlayer.create(context, uri); } public MediaPlayer create() { return new MediaPlayer(); } }
... import android.content.Context; import android.media.MediaPlayer; import android.net.Uri; /** * @author hnakagawa */ public class MediaPlayerFactory { public MediaPlayer create(Context context, int resId) { ... return MediaPlayer.create(context, resId); } public MediaPlayer create(Context context, Uri uri) { return MediaPlayer.create(context, uri); } public MediaPlayer create() { return new MediaPlayer(); } ...
35514dcb70ed5ede39299802e82fa352188f3546
examples/nested_inline_tasksets.py
examples/nested_inline_tasksets.py
from locust import HttpUser, TaskSet, task, between class WebsiteUser(HttpUser): """ Example of the ability of inline nested TaskSet classes """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) class TopLevelTaskSet(TaskSet): @task class IndexTaskSet(TaskSet): @task(10) def index(self): self.client.get("/") @task(1) def stop(self): self.interrupt() @task def stats(self): self.client.get("/stats/requests") tasks = [TopLevelTaskSet]
from locust import HttpUser, TaskSet, task, between class WebsiteUser(HttpUser): """ Example of the ability of inline nested TaskSet classes """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) @task class TopLevelTaskSet(TaskSet): @task class IndexTaskSet(TaskSet): @task(10) def index(self): self.client.get("/") @task(1) def stop(self): self.interrupt() @task def stats(self): self.client.get("/stats/requests")
Use @task decorator in taskset example
Use @task decorator in taskset example
Python
mit
mbeacom/locust,locustio/locust,mbeacom/locust,locustio/locust,mbeacom/locust,mbeacom/locust,locustio/locust,locustio/locust
python
## Code Before: from locust import HttpUser, TaskSet, task, between class WebsiteUser(HttpUser): """ Example of the ability of inline nested TaskSet classes """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) class TopLevelTaskSet(TaskSet): @task class IndexTaskSet(TaskSet): @task(10) def index(self): self.client.get("/") @task(1) def stop(self): self.interrupt() @task def stats(self): self.client.get("/stats/requests") tasks = [TopLevelTaskSet] ## Instruction: Use @task decorator in taskset example ## Code After: from locust import HttpUser, TaskSet, task, between class WebsiteUser(HttpUser): """ Example of the ability of inline nested TaskSet classes """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) @task class TopLevelTaskSet(TaskSet): @task class IndexTaskSet(TaskSet): @task(10) def index(self): self.client.get("/") @task(1) def stop(self): self.interrupt() @task def stats(self): self.client.get("/stats/requests")
# ... existing code ... """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) @task class TopLevelTaskSet(TaskSet): @task class IndexTaskSet(TaskSet): # ... modified code ... @task def stats(self): self.client.get("/stats/requests") # ... rest of the code ...
213b889a580f58f5dea13fa63c999ca7dac04450
src/extras/__init__.py
src/extras/__init__.py
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis
Add Stemmed Kucera Francis to extras package
Add Stemmed Kucera Francis to extras package
Python
mit
Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify
python
## Code Before: __author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis ## Instruction: Add Stemmed Kucera Francis to extras package ## Code After: __author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis
... from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis ...
a244623642cdf26bd6615cdc7ff2540c9361d10d
tmapi/models/typed.py
tmapi/models/typed.py
from django.db import models from construct import Construct class Typed (Construct, models.Model): """Indicates that a Topic Maps construct is typed. `Association`s, `Role`s, `Occurrence`s, and `Name`s are typed.""" type = models.ForeignKey('Topic', related_name='typed_%(class)ss') class Meta: abstract = True app_label = 'tmapi' def get_type (self): """Returns the type of this construct. :rtype: the `Topic` that represents the type """ return self.type def set_type (self, construct_type): """Sets the type of this construct. Any previous type is overridden. :param construct_type: the `Topic` that should define the nature of this construct """ self.type = construct_type self.save()
from django.db import models from tmapi.exceptions import ModelConstraintException from construct import Construct class Typed (Construct, models.Model): """Indicates that a Topic Maps construct is typed. `Association`s, `Role`s, `Occurrence`s, and `Name`s are typed.""" type = models.ForeignKey('Topic', related_name='typed_%(class)ss') class Meta: abstract = True app_label = 'tmapi' def get_type (self): """Returns the type of this construct. :rtype: the `Topic` that represents the type """ return self.type def set_type (self, construct_type): """Sets the type of this construct. Any previous type is overridden. :param construct_type: the `Topic` that should define the nature of this construct """ if construct_type is None: raise ModelConstraintException self.type = construct_type self.save()
Raise an exception when setting a construct's type to None.
Raise an exception when setting a construct's type to None.
Python
apache-2.0
ajenhl/django-tmapi
python
## Code Before: from django.db import models from construct import Construct class Typed (Construct, models.Model): """Indicates that a Topic Maps construct is typed. `Association`s, `Role`s, `Occurrence`s, and `Name`s are typed.""" type = models.ForeignKey('Topic', related_name='typed_%(class)ss') class Meta: abstract = True app_label = 'tmapi' def get_type (self): """Returns the type of this construct. :rtype: the `Topic` that represents the type """ return self.type def set_type (self, construct_type): """Sets the type of this construct. Any previous type is overridden. :param construct_type: the `Topic` that should define the nature of this construct """ self.type = construct_type self.save() ## Instruction: Raise an exception when setting a construct's type to None. ## Code After: from django.db import models from tmapi.exceptions import ModelConstraintException from construct import Construct class Typed (Construct, models.Model): """Indicates that a Topic Maps construct is typed. `Association`s, `Role`s, `Occurrence`s, and `Name`s are typed.""" type = models.ForeignKey('Topic', related_name='typed_%(class)ss') class Meta: abstract = True app_label = 'tmapi' def get_type (self): """Returns the type of this construct. :rtype: the `Topic` that represents the type """ return self.type def set_type (self, construct_type): """Sets the type of this construct. Any previous type is overridden. :param construct_type: the `Topic` that should define the nature of this construct """ if construct_type is None: raise ModelConstraintException self.type = construct_type self.save()
# ... existing code ... from django.db import models from tmapi.exceptions import ModelConstraintException from construct import Construct # ... modified code ... nature of this construct """ if construct_type is None: raise ModelConstraintException self.type = construct_type self.save() # ... rest of the code ...
27ff5f4ee1322a988e5ddce02741da3158a23c9d
src/main/java/com/hubspot/jinjava/util/LengthLimitingStringBuilder.java
src/main/java/com/hubspot/jinjava/util/LengthLimitingStringBuilder.java
package com.hubspot.jinjava.util; import com.hubspot.jinjava.interpret.OutputTooBigException; import java.io.Serializable; import java.util.stream.IntStream; public class LengthLimitingStringBuilder implements Serializable, CharSequence { private static final long serialVersionUID = -1891922886257965755L; private final StringBuilder builder; private long length = 0; private final long maxLength; public LengthLimitingStringBuilder(long maxLength) { builder = new StringBuilder(); this.maxLength = maxLength; } @Override public int length() { return builder.length(); } @Override public char charAt(int index) { return builder.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return builder.subSequence(start, end); } @Override public String toString() { return builder.toString(); } @Override public IntStream chars() { return builder.chars(); } @Override public IntStream codePoints() { return builder.codePoints(); } public void append(Object obj) { append(String.valueOf(obj)); } public void append(String str) { length += str.length(); if (maxLength > 0 && length > maxLength) { throw new OutputTooBigException(maxLength, length); } builder.append(str); } }
package com.hubspot.jinjava.util; import com.hubspot.jinjava.interpret.OutputTooBigException; import java.io.Serializable; import java.util.stream.IntStream; public class LengthLimitingStringBuilder implements Serializable, CharSequence { private static final long serialVersionUID = -1891922886257965755L; private final StringBuilder builder; private long length = 0; private final long maxLength; public LengthLimitingStringBuilder(long maxLength) { builder = new StringBuilder(); this.maxLength = maxLength; } @Override public int length() { return builder.length(); } @Override public char charAt(int index) { return builder.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return builder.subSequence(start, end); } @Override public String toString() { return builder.toString(); } @Override public IntStream chars() { return builder.chars(); } @Override public IntStream codePoints() { return builder.codePoints(); } public void append(Object obj) { append(String.valueOf(obj)); } public void append(String str) { if (str == null) { return; } length += str.length(); if (maxLength > 0 && length > maxLength) { throw new OutputTooBigException(maxLength, length); } builder.append(str); } }
Check for null value before appending
Check for null value before appending
Java
apache-2.0
HubSpot/jinjava,HubSpot/jinjava
java
## Code Before: package com.hubspot.jinjava.util; import com.hubspot.jinjava.interpret.OutputTooBigException; import java.io.Serializable; import java.util.stream.IntStream; public class LengthLimitingStringBuilder implements Serializable, CharSequence { private static final long serialVersionUID = -1891922886257965755L; private final StringBuilder builder; private long length = 0; private final long maxLength; public LengthLimitingStringBuilder(long maxLength) { builder = new StringBuilder(); this.maxLength = maxLength; } @Override public int length() { return builder.length(); } @Override public char charAt(int index) { return builder.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return builder.subSequence(start, end); } @Override public String toString() { return builder.toString(); } @Override public IntStream chars() { return builder.chars(); } @Override public IntStream codePoints() { return builder.codePoints(); } public void append(Object obj) { append(String.valueOf(obj)); } public void append(String str) { length += str.length(); if (maxLength > 0 && length > maxLength) { throw new OutputTooBigException(maxLength, length); } builder.append(str); } } ## Instruction: Check for null value before appending ## Code After: package com.hubspot.jinjava.util; import com.hubspot.jinjava.interpret.OutputTooBigException; import java.io.Serializable; import java.util.stream.IntStream; public class LengthLimitingStringBuilder implements Serializable, CharSequence { private static final long serialVersionUID = -1891922886257965755L; private final StringBuilder builder; private long length = 0; private final long maxLength; public LengthLimitingStringBuilder(long maxLength) { builder = new StringBuilder(); this.maxLength = maxLength; } @Override public int length() { return builder.length(); } @Override public char charAt(int index) { return builder.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return builder.subSequence(start, end); } @Override public String toString() { return builder.toString(); } @Override public IntStream chars() { return builder.chars(); } @Override public IntStream codePoints() { return builder.codePoints(); } public void append(Object obj) { append(String.valueOf(obj)); } public void append(String str) { if (str == null) { return; } length += str.length(); if (maxLength > 0 && length > maxLength) { throw new OutputTooBigException(maxLength, length); } builder.append(str); } }
// ... existing code ... } public void append(String str) { if (str == null) { return; } length += str.length(); if (maxLength > 0 && length > maxLength) { throw new OutputTooBigException(maxLength, length); // ... rest of the code ...
38b20649403f2cbffc4581211f1b61868e3b358f
include/features.h
include/features.h
/* Almost ansi */ #if __STDC__ != 1 #define const #define volatile #endif #else /* K&R */ #define __P(x) () #define __const #define const #define volatile #endif /* No C++ */ #define __BEGIN_DECLS #define __END_DECLS /* GNUish things */ #define __CONSTVALUE #define __CONSTVALUE2 #define _POSIX_THREAD_SAFE_FUNCTIONS #include <sys/cdefs.h> #endif
/* Major and minor version number of the uCLibc library package. Use these macros to test for features in specific releases. */ #define __UCLIBC__ 0 #define __UCLIBC_MAJOR__ 9 #define __UCLIBC_MINOR__ 1 #ifdef __STDC__ #define __P(x) x #define __const const /* Almost ansi */ #if __STDC__ != 1 #define const #define volatile #endif #else /* K&R */ #define __P(x) () #define __const #define const #define volatile #endif /* No C++ */ #define __BEGIN_DECLS #define __END_DECLS /* GNUish things */ #define __CONSTVALUE #define __CONSTVALUE2 #define _POSIX_THREAD_SAFE_FUNCTIONS #include <sys/cdefs.h> #endif
Add in a version number so apps can tell uclib is being used. -Erik
Add in a version number so apps can tell uclib is being used. -Erik
C
lgpl-2.1
wbx-github/uclibc-ng,atgreen/uClibc-moxie,ysat0/uClibc,skristiansson/uClibc-or1k,skristiansson/uClibc-or1k,wbx-github/uclibc-ng,klee/klee-uclibc,atgreen/uClibc-moxie,hjl-tools/uClibc,kraj/uClibc,ffainelli/uClibc,groundwater/uClibc,m-labs/uclibc-lm32,groundwater/uClibc,majek/uclibc-vx32,groundwater/uClibc,foss-xtensa/uClibc,ysat0/uClibc,klee/klee-uclibc,ffainelli/uClibc,m-labs/uclibc-lm32,OpenInkpot-archive/iplinux-uclibc,hjl-tools/uClibc,kraj/uClibc,ChickenRunjyd/klee-uclibc,skristiansson/uClibc-or1k,mephi42/uClibc,groundwater/uClibc,foss-xtensa/uClibc,groundwater/uClibc,hjl-tools/uClibc,ddcc/klee-uclibc-0.9.33.2,brgl/uclibc-ng,waweber/uclibc-clang,kraj/uClibc,klee/klee-uclibc,hwoarang/uClibc,hwoarang/uClibc,ddcc/klee-uclibc-0.9.33.2,klee/klee-uclibc,OpenInkpot-archive/iplinux-uclibc,waweber/uclibc-clang,m-labs/uclibc-lm32,czankel/xtensa-uclibc,kraj/uclibc-ng,brgl/uclibc-ng,majek/uclibc-vx32,mephi42/uClibc,hjl-tools/uClibc,kraj/uclibc-ng,m-labs/uclibc-lm32,ChickenRunjyd/klee-uclibc,kraj/uclibc-ng,atgreen/uClibc-moxie,czankel/xtensa-uclibc,ndmsystems/uClibc,gittup/uClibc,gittup/uClibc,ffainelli/uClibc,ddcc/klee-uclibc-0.9.33.2,czankel/xtensa-uclibc,hjl-tools/uClibc,ffainelli/uClibc,wbx-github/uclibc-ng,foss-for-synopsys-dwc-arc-processors/uClibc,brgl/uclibc-ng,wbx-github/uclibc-ng,OpenInkpot-archive/iplinux-uclibc,skristiansson/uClibc-or1k,foss-for-synopsys-dwc-arc-processors/uClibc,ndmsystems/uClibc,OpenInkpot-archive/iplinux-uclibc,ysat0/uClibc,czankel/xtensa-uclibc,gittup/uClibc,ChickenRunjyd/klee-uclibc,foss-for-synopsys-dwc-arc-processors/uClibc,gittup/uClibc,foss-for-synopsys-dwc-arc-processors/uClibc,atgreen/uClibc-moxie,ddcc/klee-uclibc-0.9.33.2,foss-xtensa/uClibc,ndmsystems/uClibc,hwoarang/uClibc,ndmsystems/uClibc,kraj/uclibc-ng,brgl/uclibc-ng,ysat0/uClibc,mephi42/uClibc,majek/uclibc-vx32,foss-xtensa/uClibc,majek/uclibc-vx32,mephi42/uClibc,hwoarang/uClibc,ChickenRunjyd/klee-uclibc,kraj/uClibc,waweber/uclibc-clang,ffainelli/uClibc,waweber/uclibc-clang
c
## Code Before: /* Almost ansi */ #if __STDC__ != 1 #define const #define volatile #endif #else /* K&R */ #define __P(x) () #define __const #define const #define volatile #endif /* No C++ */ #define __BEGIN_DECLS #define __END_DECLS /* GNUish things */ #define __CONSTVALUE #define __CONSTVALUE2 #define _POSIX_THREAD_SAFE_FUNCTIONS #include <sys/cdefs.h> #endif ## Instruction: Add in a version number so apps can tell uclib is being used. -Erik ## Code After: /* Major and minor version number of the uCLibc library package. Use these macros to test for features in specific releases. */ #define __UCLIBC__ 0 #define __UCLIBC_MAJOR__ 9 #define __UCLIBC_MINOR__ 1 #ifdef __STDC__ #define __P(x) x #define __const const /* Almost ansi */ #if __STDC__ != 1 #define const #define volatile #endif #else /* K&R */ #define __P(x) () #define __const #define const #define volatile #endif /* No C++ */ #define __BEGIN_DECLS #define __END_DECLS /* GNUish things */ #define __CONSTVALUE #define __CONSTVALUE2 #define _POSIX_THREAD_SAFE_FUNCTIONS #include <sys/cdefs.h> #endif
... /* Major and minor version number of the uCLibc library package. Use these macros to test for features in specific releases. */ #define __UCLIBC__ 0 #define __UCLIBC_MAJOR__ 9 #define __UCLIBC_MINOR__ 1 #ifdef __STDC__ #define __P(x) x #define __const const /* Almost ansi */ #if __STDC__ != 1 ...
81b9a8179ef4db9857b4d133769c92c7b1972ee6
pysuru/tests/test_base.py
pysuru/tests/test_base.py
from pysuru.base import BaseAPI, ObjectMixin def test_baseapi_headers_should_return_authorization_header(): api = BaseAPI(None, 'TOKEN') assert {'Authorization': 'bearer TOKEN'} == api.headers def test_build_url_should_return_full_api_endpoint(): api = BaseAPI('http://example.com/', None) assert 'http://example.com/apis' == api.build_url('/apis') api = BaseAPI('http://example.com', None) assert 'http://example.com/apis' == api.build_url('/apis') def test_baseobject_create_should_ignore_unknown_fields(): data = {'field1': 'value1', 'unknown': 'ignored'} created = _DummyObject.create(**data) assert created.attrs['field1'] == 'value1' assert 'unknown' not in created.attrs class _DummyObject(ObjectMixin): _fields = ('field1', 'field2') def __init__(self, **kwargs): self.attrs = kwargs
from pysuru.base import BaseAPI, ObjectMixin def test_baseapi_headers_should_return_authorization_header(): api = BaseAPI(None, 'TOKEN') assert {'Authorization': 'bearer TOKEN'} == api.headers def test_baseapi_conn_should_return_same_object(): api = BaseAPI(None, None) obj1 = api.conn obj2 = api.conn assert obj1 is obj2 def test_build_url_should_return_full_api_endpoint(): api = BaseAPI('http://example.com/', None) assert 'http://example.com/apis' == api.build_url('/apis') api = BaseAPI('http://example.com', None) assert 'http://example.com/apis' == api.build_url('/apis') def test_baseobject_create_should_ignore_unknown_fields(): data = {'field1': 'value1', 'unknown': 'ignored'} created = _DummyObject.create(**data) assert created.attrs['field1'] == 'value1' assert 'unknown' not in created.attrs class _DummyObject(ObjectMixin): _fields = ('field1', 'field2') def __init__(self, **kwargs): self.attrs = kwargs
Add test to ensure only one conn object is created
Add test to ensure only one conn object is created
Python
mit
rcmachado/pysuru
python
## Code Before: from pysuru.base import BaseAPI, ObjectMixin def test_baseapi_headers_should_return_authorization_header(): api = BaseAPI(None, 'TOKEN') assert {'Authorization': 'bearer TOKEN'} == api.headers def test_build_url_should_return_full_api_endpoint(): api = BaseAPI('http://example.com/', None) assert 'http://example.com/apis' == api.build_url('/apis') api = BaseAPI('http://example.com', None) assert 'http://example.com/apis' == api.build_url('/apis') def test_baseobject_create_should_ignore_unknown_fields(): data = {'field1': 'value1', 'unknown': 'ignored'} created = _DummyObject.create(**data) assert created.attrs['field1'] == 'value1' assert 'unknown' not in created.attrs class _DummyObject(ObjectMixin): _fields = ('field1', 'field2') def __init__(self, **kwargs): self.attrs = kwargs ## Instruction: Add test to ensure only one conn object is created ## Code After: from pysuru.base import BaseAPI, ObjectMixin def test_baseapi_headers_should_return_authorization_header(): api = BaseAPI(None, 'TOKEN') assert {'Authorization': 'bearer TOKEN'} == api.headers def test_baseapi_conn_should_return_same_object(): api = BaseAPI(None, None) obj1 = api.conn obj2 = api.conn assert obj1 is obj2 def test_build_url_should_return_full_api_endpoint(): api = BaseAPI('http://example.com/', None) assert 'http://example.com/apis' == api.build_url('/apis') api = BaseAPI('http://example.com', None) assert 'http://example.com/apis' == api.build_url('/apis') def test_baseobject_create_should_ignore_unknown_fields(): data = {'field1': 'value1', 'unknown': 'ignored'} created = _DummyObject.create(**data) assert created.attrs['field1'] == 'value1' assert 'unknown' not in created.attrs class _DummyObject(ObjectMixin): _fields = ('field1', 'field2') def __init__(self, **kwargs): self.attrs = kwargs
// ... existing code ... def test_baseapi_headers_should_return_authorization_header(): api = BaseAPI(None, 'TOKEN') assert {'Authorization': 'bearer TOKEN'} == api.headers def test_baseapi_conn_should_return_same_object(): api = BaseAPI(None, None) obj1 = api.conn obj2 = api.conn assert obj1 is obj2 def test_build_url_should_return_full_api_endpoint(): // ... rest of the code ...
90c816bd40a4971dda8bd96d865efb1dee131566
files/install_workflow.py
files/install_workflow.py
import argparse from bioblend import galaxy import json def main(): """ This script uses bioblend to import .ga workflow files into a running instance of Galaxy """ parser = argparse.ArgumentParser() parser.add_argument("-w", "--workflow_path", help='Path to workflow file') parser.add_argument("-g", "--galaxy", dest="galaxy_url", help="Target Galaxy instance URL/IP address (required " "if not defined in the tools list file)",) parser.add_argument("-a", "--apikey", dest="api_key", help="Galaxy admin user API key (required if not " "defined in the tools list file)",) args = parser.parse_args() gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key) import_uuid = json.load(open(args.workflow_path, 'r')).get('uuid') existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()] if import_uuid not in existing_uuids: gi.workflows.import_workflow_from_local_path(args.workflow_path) if __name__ == '__main__': main()
import argparse from bioblend import galaxy import json def main(): """ This script uses bioblend to import .ga workflow files into a running instance of Galaxy """ parser = argparse.ArgumentParser() parser.add_argument("-w", "--workflow_path", help='Path to workflow file') parser.add_argument("-g", "--galaxy", dest="galaxy_url", help="Target Galaxy instance URL/IP address (required " "if not defined in the tools list file)",) parser.add_argument("-a", "--apikey", dest="api_key", help="Galaxy admin user API key (required if not " "defined in the tools list file)",) args = parser.parse_args() gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key) with open(args.workflow_path, 'r') as wf_file: import_uuid = json.load(wf_file).get('uuid') existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()] if import_uuid not in existing_uuids: gi.workflows.import_workflow_from_local_path(args.workflow_path) if __name__ == '__main__': main()
Make sure the opened workflow file gets closed after it's been loaded
Make sure the opened workflow file gets closed after it's been loaded
Python
mit
galaxyproject/ansible-galaxy-tools,galaxyproject/ansible-tools,nuwang/ansible-galaxy-tools,anmoljh/ansible-galaxy-tools
python
## Code Before: import argparse from bioblend import galaxy import json def main(): """ This script uses bioblend to import .ga workflow files into a running instance of Galaxy """ parser = argparse.ArgumentParser() parser.add_argument("-w", "--workflow_path", help='Path to workflow file') parser.add_argument("-g", "--galaxy", dest="galaxy_url", help="Target Galaxy instance URL/IP address (required " "if not defined in the tools list file)",) parser.add_argument("-a", "--apikey", dest="api_key", help="Galaxy admin user API key (required if not " "defined in the tools list file)",) args = parser.parse_args() gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key) import_uuid = json.load(open(args.workflow_path, 'r')).get('uuid') existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()] if import_uuid not in existing_uuids: gi.workflows.import_workflow_from_local_path(args.workflow_path) if __name__ == '__main__': main() ## Instruction: Make sure the opened workflow file gets closed after it's been loaded ## Code After: import argparse from bioblend import galaxy import json def main(): """ This script uses bioblend to import .ga workflow files into a running instance of Galaxy """ parser = argparse.ArgumentParser() parser.add_argument("-w", "--workflow_path", help='Path to workflow file') parser.add_argument("-g", "--galaxy", dest="galaxy_url", help="Target Galaxy instance URL/IP address (required " "if not defined in the tools list file)",) parser.add_argument("-a", "--apikey", dest="api_key", help="Galaxy admin user API key (required if not " "defined in the tools list file)",) args = parser.parse_args() gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key) with open(args.workflow_path, 'r') as wf_file: import_uuid = json.load(wf_file).get('uuid') existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()] if import_uuid not in existing_uuids: gi.workflows.import_workflow_from_local_path(args.workflow_path) if __name__ == '__main__': main()
// ... existing code ... gi = galaxy.GalaxyInstance(url=args.galaxy_url, key=args.api_key) with open(args.workflow_path, 'r') as wf_file: import_uuid = json.load(wf_file).get('uuid') existing_uuids = [d.get('latest_workflow_uuid') for d in gi.workflows.get_workflows()] if import_uuid not in existing_uuids: gi.workflows.import_workflow_from_local_path(args.workflow_path) // ... rest of the code ...
3ddd22e1ade2716f96439e7d1e3b044217c44b2a
src/adts/adts_list.h
src/adts/adts_list.h
/** ************************************************************************** * \details * ************************************************************************** */ #define ADTS_LIST_BYTES (32) #define ADTS_LIST_ELEM_BYTES (32) /** ************************************************************************** * \details * ************************************************************************** */ typedef struct { char reserved[ ADTS_LIST_BYTES ]; } adts_list_t; typedef struct { char reserved[ ADTS_LIST_ELEM_BYTES ]; } adts_list_elem_t; void utest_adts_list( void ); #endif /* _H_ADTS_LIST */
/** ************************************************************************** * \details * ************************************************************************** */ #define ADTS_LIST_BYTES (32) #define ADTS_LIST_ELEM_BYTES (32) /** ************************************************************************** * \details * ************************************************************************** */ typedef struct { const char reserved[ ADTS_LIST_BYTES ]; } adts_list_t; typedef struct { const char reserved[ ADTS_LIST_ELEM_BYTES ]; } adts_list_elem_t; void utest_adts_list( void ); #endif /* _H_ADTS_LIST */
Make list.h non-modifiabe in ADT
Make list.h non-modifiabe in ADT
C
mit
78613/sample,78613/sample
c
## Code Before: /** ************************************************************************** * \details * ************************************************************************** */ #define ADTS_LIST_BYTES (32) #define ADTS_LIST_ELEM_BYTES (32) /** ************************************************************************** * \details * ************************************************************************** */ typedef struct { char reserved[ ADTS_LIST_BYTES ]; } adts_list_t; typedef struct { char reserved[ ADTS_LIST_ELEM_BYTES ]; } adts_list_elem_t; void utest_adts_list( void ); #endif /* _H_ADTS_LIST */ ## Instruction: Make list.h non-modifiabe in ADT ## Code After: /** ************************************************************************** * \details * ************************************************************************** */ #define ADTS_LIST_BYTES (32) #define ADTS_LIST_ELEM_BYTES (32) /** ************************************************************************** * \details * ************************************************************************** */ typedef struct { const char reserved[ ADTS_LIST_BYTES ]; } adts_list_t; typedef struct { const char reserved[ ADTS_LIST_ELEM_BYTES ]; } adts_list_elem_t; void utest_adts_list( void ); #endif /* _H_ADTS_LIST */
... ************************************************************************** */ typedef struct { const char reserved[ ADTS_LIST_BYTES ]; } adts_list_t; typedef struct { const char reserved[ ADTS_LIST_ELEM_BYTES ]; } adts_list_elem_t; ...
d01a13f498e01efe613bace4c140d6901752475b
multilingual_model/admin.py
multilingual_model/admin.py
from django.contrib import admin from .forms import TranslationFormSet from . import settings class TranslationInline(admin.StackedInline): def __init__(self, *args, **kwargs): super(TranslationInline, self).__init__(*args, **kwargs) if settings.AUTO_HIDE_LANGUAGE: self.exclude = ('language_code', ) self.can_delete = False extra = 1 formset = TranslationFormSet max_num = len(settings.LANGUAGES)
from django.contrib import admin from .forms import TranslationFormSet from . import settings class TranslationStackedInline(admin.StackedInline): def __init__(self, *args, **kwargs): super(TranslationStackedInline, self).__init__(*args, **kwargs) if settings.AUTO_HIDE_LANGUAGE: self.exclude = ('language_code', ) self.can_delete = False extra = 1 formset = TranslationFormSet max_num = MAX_LANGUAGES class TranslationTabularInline(admin.TabularInline): def __init__(self, *args, **kwargs): super(TranslationTabularInline, self).__init__(*args, **kwargs) if settings.AUTO_HIDE_LANGUAGE: self.exclude = ('language_code', ) self.can_delete = False extra = 1 formset = TranslationFormSet max_num = len(settings.LANGUAGES)
Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline.
Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline.
Python
agpl-3.0
dokterbob/django-multilingual-model
python
## Code Before: from django.contrib import admin from .forms import TranslationFormSet from . import settings class TranslationInline(admin.StackedInline): def __init__(self, *args, **kwargs): super(TranslationInline, self).__init__(*args, **kwargs) if settings.AUTO_HIDE_LANGUAGE: self.exclude = ('language_code', ) self.can_delete = False extra = 1 formset = TranslationFormSet max_num = len(settings.LANGUAGES) ## Instruction: Rename TranslationInline to TranslationStackedInline, add TranslationTabularInline. ## Code After: from django.contrib import admin from .forms import TranslationFormSet from . import settings class TranslationStackedInline(admin.StackedInline): def __init__(self, *args, **kwargs): super(TranslationStackedInline, self).__init__(*args, **kwargs) if settings.AUTO_HIDE_LANGUAGE: self.exclude = ('language_code', ) self.can_delete = False extra = 1 formset = TranslationFormSet max_num = MAX_LANGUAGES class TranslationTabularInline(admin.TabularInline): def __init__(self, *args, **kwargs): super(TranslationTabularInline, self).__init__(*args, **kwargs) if settings.AUTO_HIDE_LANGUAGE: self.exclude = ('language_code', ) self.can_delete = False extra = 1 formset = TranslationFormSet max_num = len(settings.LANGUAGES)
... from . import settings class TranslationStackedInline(admin.StackedInline): def __init__(self, *args, **kwargs): super(TranslationStackedInline, self).__init__(*args, **kwargs) if settings.AUTO_HIDE_LANGUAGE: self.exclude = ('language_code', ) self.can_delete = False extra = 1 formset = TranslationFormSet max_num = MAX_LANGUAGES class TranslationTabularInline(admin.TabularInline): def __init__(self, *args, **kwargs): super(TranslationTabularInline, self).__init__(*args, **kwargs) if settings.AUTO_HIDE_LANGUAGE: self.exclude = ('language_code', ) ...
7566ba4a701d8da431b6987a7a921b297152615e
setup.py
setup.py
from setuptools import setup setup(name="manhattan", version='0.2', description='Robust Server-Side Analytics', long_description='', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware', 'Topic :: Internet :: WWW/HTTP :: Site Management', ], keywords='', url='http://github.com/cartlogic/manhattan', author='Scott Torborg', author_email='[email protected]', install_requires=[ 'sqlalchemy>=0.7', 'webob', 'redis>=2.7.2', 'pytz', 'pyzmq', 'simplejson', ], license='MIT', packages=['manhattan'], entry_points=dict( console_scripts=[ 'manhattan-server=manhattan.server:main', 'manhattan-client=manhattan.client:main', 'manhattan-log-server=manhattan.log.remote:server', ] ), test_suite='nose.collector', tests_require=['nose'], zip_safe=False)
from setuptools import setup, find_packages setup(name="manhattan", version='0.2', description='Robust Server-Side Analytics', long_description='', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware', 'Topic :: Internet :: WWW/HTTP :: Site Management', ], keywords='', url='http://github.com/cartlogic/manhattan', author='Scott Torborg', author_email='[email protected]', install_requires=[ 'sqlalchemy>=0.7', 'webob', 'redis>=2.7.2', 'pytz', 'pyzmq', 'simplejson', ], license='MIT', packages=find_packages(), entry_points=dict( console_scripts=[ 'manhattan-server=manhattan.server:main', 'manhattan-client=manhattan.client:main', 'manhattan-log-server=manhattan.log.remote:server', ] ), test_suite='nose.collector', tests_require=['nose'], zip_safe=False)
Use find_packages() instead of manually specifying package name, so that subpackages get included
Use find_packages() instead of manually specifying package name, so that subpackages get included
Python
mit
storborg/manhattan
python
## Code Before: from setuptools import setup setup(name="manhattan", version='0.2', description='Robust Server-Side Analytics', long_description='', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware', 'Topic :: Internet :: WWW/HTTP :: Site Management', ], keywords='', url='http://github.com/cartlogic/manhattan', author='Scott Torborg', author_email='[email protected]', install_requires=[ 'sqlalchemy>=0.7', 'webob', 'redis>=2.7.2', 'pytz', 'pyzmq', 'simplejson', ], license='MIT', packages=['manhattan'], entry_points=dict( console_scripts=[ 'manhattan-server=manhattan.server:main', 'manhattan-client=manhattan.client:main', 'manhattan-log-server=manhattan.log.remote:server', ] ), test_suite='nose.collector', tests_require=['nose'], zip_safe=False) ## Instruction: Use find_packages() instead of manually specifying package name, so that subpackages get included ## Code After: from setuptools import setup, find_packages setup(name="manhattan", version='0.2', description='Robust Server-Side Analytics', long_description='', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware', 'Topic :: Internet :: WWW/HTTP :: Site Management', ], keywords='', url='http://github.com/cartlogic/manhattan', author='Scott Torborg', author_email='[email protected]', install_requires=[ 'sqlalchemy>=0.7', 'webob', 'redis>=2.7.2', 'pytz', 'pyzmq', 'simplejson', ], license='MIT', packages=find_packages(), entry_points=dict( console_scripts=[ 'manhattan-server=manhattan.server:main', 'manhattan-client=manhattan.client:main', 'manhattan-log-server=manhattan.log.remote:server', ] ), test_suite='nose.collector', tests_require=['nose'], zip_safe=False)
// ... existing code ... from setuptools import setup, find_packages setup(name="manhattan", // ... modified code ... 'simplejson', ], license='MIT', packages=find_packages(), entry_points=dict( console_scripts=[ 'manhattan-server=manhattan.server:main', // ... rest of the code ...
0c8484323be566e3bd362bcd99efc24d26c74afd
java/src/main/java/me/gowdru/notes/sort/Sorter.java
java/src/main/java/me/gowdru/notes/sort/Sorter.java
package me.gowdru.notes.sort; import java.util.Comparator; /** * Defines contract for Sorter algorithm implementations */ public interface Sorter<T> { /** * sorts {@code items}i in an array by comparing them using {@code comparator} * @param items items to be sorted * @param comparator comparison assistant */ public void sort(T[] items, Comparator<T> comparator); }
package me.gowdru.notes.sort; import java.util.Comparator; /** * Defines contract for Sorter algorithm implementations */ public interface Sorter<T> { /** * sorts {@code items}i in an array by comparing them using {@code comparator} * @param items items to be sorted * @param comparator comparison assistant */ public void sort(T[] items, Comparator<T> comparator); /** * swaps a pair of elements in array * @param array - array of items * @param pos1 position of an item to be swapped to/with * @param pos2 position of another item to be swapped to/with */ public default void swap(T[] array, int pos1, int pos2){ T tmp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = tmp; } }
Add swap method to base class
Add swap method to base class
Java
apache-2.0
thammegowda/algos,thammegowda/algos,thammegowda/notes,thammegowda/notes,thammegowda/notes,thammegowda/algos
java
## Code Before: package me.gowdru.notes.sort; import java.util.Comparator; /** * Defines contract for Sorter algorithm implementations */ public interface Sorter<T> { /** * sorts {@code items}i in an array by comparing them using {@code comparator} * @param items items to be sorted * @param comparator comparison assistant */ public void sort(T[] items, Comparator<T> comparator); } ## Instruction: Add swap method to base class ## Code After: package me.gowdru.notes.sort; import java.util.Comparator; /** * Defines contract for Sorter algorithm implementations */ public interface Sorter<T> { /** * sorts {@code items}i in an array by comparing them using {@code comparator} * @param items items to be sorted * @param comparator comparison assistant */ public void sort(T[] items, Comparator<T> comparator); /** * swaps a pair of elements in array * @param array - array of items * @param pos1 position of an item to be swapped to/with * @param pos2 position of another item to be swapped to/with */ public default void swap(T[] array, int pos1, int pos2){ T tmp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = tmp; } }
... */ public void sort(T[] items, Comparator<T> comparator); /** * swaps a pair of elements in array * @param array - array of items * @param pos1 position of an item to be swapped to/with * @param pos2 position of another item to be swapped to/with */ public default void swap(T[] array, int pos1, int pos2){ T tmp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = tmp; } } ...
401f98ad74792e9a5d9354dec8c24dc9637d1f5e
tests/gsim/pezeshk_2011_test.py
tests/gsim/pezeshk_2011_test.py
from openquake.hazardlib.gsim.pezeshk_2011 import Pezeshk2011 from tests.gsim.utils import BaseGSIMTestCase class Pezeshk2011TestCase(BaseGSIMTestCase): GSIM_CLASS = Pezeshk2011 # Test data were obtained from a tool given by the authors # The data of the values of the mean PGA and SA are in g's. def test_mean(self): self.check('PEZE11/PZ11_MEAN.csv', max_discrep_percentage=0.5) def test_std_total(self): self.check('PEZE11/PZ11_STD_TOTAL.csv', max_discrep_percentage=0.5)
from openquake.hazardlib.gsim.pezeshk_2011 import PezeshkEtAl2011 from tests.gsim.utils import BaseGSIMTestCase class Pezeshk2011EtAlTestCase(BaseGSIMTestCase): GSIM_CLASS = PezeshkEtAl2011 # Test data were obtained from a tool given by the authors # The data of the values of the mean PGA and SA are in g's. def test_mean(self): self.check('PEZE11/PZ11_MEAN.csv', max_discrep_percentage=0.5) def test_std_total(self): self.check('PEZE11/PZ11_STD_TOTAL.csv', max_discrep_percentage=0.5)
Add implementation of gmpe Pezeshk et al 2011 for ENA
Add implementation of gmpe Pezeshk et al 2011 for ENA
Python
agpl-3.0
vup1120/oq-hazardlib,gem/oq-engine,g-weatherill/oq-hazardlib,gem/oq-hazardlib,gem/oq-hazardlib,g-weatherill/oq-hazardlib,gem/oq-engine,gem/oq-engine,rcgee/oq-hazardlib,mmpagani/oq-hazardlib,g-weatherill/oq-hazardlib,gem/oq-hazardlib,ROB-Seismology/oq-hazardlib,silviacanessa/oq-hazardlib,vup1120/oq-hazardlib,ROB-Seismology/oq-hazardlib,silviacanessa/oq-hazardlib,larsbutler/oq-hazardlib,ROB-Seismology/oq-hazardlib,silviacanessa/oq-hazardlib,larsbutler/oq-hazardlib,silviacanessa/oq-hazardlib,gem/oq-engine,larsbutler/oq-hazardlib,g-weatherill/oq-hazardlib,rcgee/oq-hazardlib,vup1120/oq-hazardlib,ROB-Seismology/oq-hazardlib,gem/oq-engine,mmpagani/oq-hazardlib,mmpagani/oq-hazardlib
python
## Code Before: from openquake.hazardlib.gsim.pezeshk_2011 import Pezeshk2011 from tests.gsim.utils import BaseGSIMTestCase class Pezeshk2011TestCase(BaseGSIMTestCase): GSIM_CLASS = Pezeshk2011 # Test data were obtained from a tool given by the authors # The data of the values of the mean PGA and SA are in g's. def test_mean(self): self.check('PEZE11/PZ11_MEAN.csv', max_discrep_percentage=0.5) def test_std_total(self): self.check('PEZE11/PZ11_STD_TOTAL.csv', max_discrep_percentage=0.5) ## Instruction: Add implementation of gmpe Pezeshk et al 2011 for ENA ## Code After: from openquake.hazardlib.gsim.pezeshk_2011 import PezeshkEtAl2011 from tests.gsim.utils import BaseGSIMTestCase class Pezeshk2011EtAlTestCase(BaseGSIMTestCase): GSIM_CLASS = PezeshkEtAl2011 # Test data were obtained from a tool given by the authors # The data of the values of the mean PGA and SA are in g's. def test_mean(self): self.check('PEZE11/PZ11_MEAN.csv', max_discrep_percentage=0.5) def test_std_total(self): self.check('PEZE11/PZ11_STD_TOTAL.csv', max_discrep_percentage=0.5)
// ... existing code ... from openquake.hazardlib.gsim.pezeshk_2011 import PezeshkEtAl2011 from tests.gsim.utils import BaseGSIMTestCase class Pezeshk2011EtAlTestCase(BaseGSIMTestCase): GSIM_CLASS = PezeshkEtAl2011 # Test data were obtained from a tool given by the authors # The data of the values of the mean PGA and SA are in g's. // ... rest of the code ...
f85425a2c74cf15555bbed233287ddbd7ab8b24e
flexget/ui/plugins/log/log.py
flexget/ui/plugins/log/log.py
from __future__ import unicode_literals, division, absolute_import from flexget.ui import register_plugin, Blueprint, register_menu log = Blueprint('log', __name__) register_plugin(log) log.register_angular_route( '', url=log.url_prefix, template_url='index.html', controller='LogViewCtrl' ) log.register_css('log', 'css/log.css', order=99) log.register_js('log', 'js/log.js') log.register_js('angular-oboe', 'js/libs/angular-oboe.js') log.register_js('oboe-browser', 'js/libs/oboe-browser.js') register_menu(log.url_prefix, 'Log', icon='fa fa-file-text-o')
from __future__ import unicode_literals, division, absolute_import from flexget.ui import register_plugin, Blueprint, register_menu log = Blueprint('log', __name__) register_plugin(log) log.register_angular_route( '', url=log.url_prefix, template_url='index.html', controller='LogViewCtrl' ) log.register_css('log', 'css/log.css', order=99) log.register_js('log', 'js/log.js') log.register_js('angular-oboe', 'libs/oboe/js/angular-oboe.js') log.register_js('oboe-browser', 'libs/oboe/js/oboe-browser.js') register_menu(log.url_prefix, 'Log', icon='fa fa-file-text-o')
Rename libs to keep with standard
Rename libs to keep with standard
Python
mit
LynxyssCZ/Flexget,qvazzler/Flexget,tobinjt/Flexget,malkavi/Flexget,ZefQ/Flexget,qk4l/Flexget,Flexget/Flexget,tsnoam/Flexget,ianstalk/Flexget,grrr2/Flexget,jacobmetrick/Flexget,qvazzler/Flexget,crawln45/Flexget,poulpito/Flexget,JorisDeRieck/Flexget,gazpachoking/Flexget,tobinjt/Flexget,oxc/Flexget,dsemi/Flexget,jawilson/Flexget,malkavi/Flexget,tsnoam/Flexget,jacobmetrick/Flexget,OmgOhnoes/Flexget,tarzasai/Flexget,jacobmetrick/Flexget,dsemi/Flexget,Danfocus/Flexget,antivirtel/Flexget,Danfocus/Flexget,drwyrm/Flexget,tobinjt/Flexget,JorisDeRieck/Flexget,drwyrm/Flexget,JorisDeRieck/Flexget,antivirtel/Flexget,lildadou/Flexget,tarzasai/Flexget,offbyone/Flexget,grrr2/Flexget,qvazzler/Flexget,Pretagonist/Flexget,crawln45/Flexget,Pretagonist/Flexget,grrr2/Flexget,tsnoam/Flexget,ZefQ/Flexget,dsemi/Flexget,poulpito/Flexget,crawln45/Flexget,gazpachoking/Flexget,sean797/Flexget,Pretagonist/Flexget,lildadou/Flexget,LynxyssCZ/Flexget,JorisDeRieck/Flexget,Flexget/Flexget,OmgOhnoes/Flexget,Flexget/Flexget,Flexget/Flexget,sean797/Flexget,LynxyssCZ/Flexget,jawilson/Flexget,tarzasai/Flexget,malkavi/Flexget,jawilson/Flexget,Danfocus/Flexget,antivirtel/Flexget,ianstalk/Flexget,OmgOhnoes/Flexget,jawilson/Flexget,oxc/Flexget,crawln45/Flexget,cvium/Flexget,qk4l/Flexget,sean797/Flexget,Danfocus/Flexget,lildadou/Flexget,LynxyssCZ/Flexget,ianstalk/Flexget,poulpito/Flexget,offbyone/Flexget,ZefQ/Flexget,tobinjt/Flexget,qk4l/Flexget,cvium/Flexget,cvium/Flexget,drwyrm/Flexget,offbyone/Flexget,malkavi/Flexget,oxc/Flexget
python
## Code Before: from __future__ import unicode_literals, division, absolute_import from flexget.ui import register_plugin, Blueprint, register_menu log = Blueprint('log', __name__) register_plugin(log) log.register_angular_route( '', url=log.url_prefix, template_url='index.html', controller='LogViewCtrl' ) log.register_css('log', 'css/log.css', order=99) log.register_js('log', 'js/log.js') log.register_js('angular-oboe', 'js/libs/angular-oboe.js') log.register_js('oboe-browser', 'js/libs/oboe-browser.js') register_menu(log.url_prefix, 'Log', icon='fa fa-file-text-o') ## Instruction: Rename libs to keep with standard ## Code After: from __future__ import unicode_literals, division, absolute_import from flexget.ui import register_plugin, Blueprint, register_menu log = Blueprint('log', __name__) register_plugin(log) log.register_angular_route( '', url=log.url_prefix, template_url='index.html', controller='LogViewCtrl' ) log.register_css('log', 'css/log.css', order=99) log.register_js('log', 'js/log.js') log.register_js('angular-oboe', 'libs/oboe/js/angular-oboe.js') log.register_js('oboe-browser', 'libs/oboe/js/oboe-browser.js') register_menu(log.url_prefix, 'Log', icon='fa fa-file-text-o')
# ... existing code ... log.register_css('log', 'css/log.css', order=99) log.register_js('log', 'js/log.js') log.register_js('angular-oboe', 'libs/oboe/js/angular-oboe.js') log.register_js('oboe-browser', 'libs/oboe/js/oboe-browser.js') register_menu(log.url_prefix, 'Log', icon='fa fa-file-text-o') # ... rest of the code ...
05c057b44460eea6f6fe4a3dd891038d65e6d781
naxos/naxos/settings/secretKeyGen.py
naxos/naxos/settings/secretKeyGen.py
try: SECRET_KEY except NameError: from os.path import join from .base import BASE_DIR SECRET_FILE = join(BASE_DIR, 'secret.txt') try: SECRET_KEY = open(SECRET_FILE).read().strip() except IOError: try: import random SECRET_KEY = ''.join([random.SystemRandom().choice( 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]) secret = open(SECRET_FILE, 'w') secret.write(SECRET_KEY) secret.close() except IOError: Exception('Please create a {:s} file with random characters \ to generate your secret key!'.format(SECRET_FILE))
try: SECRET_KEY except NameError: from os.path import join from .base import BASE_DIR SECRET_FILE = join(BASE_DIR, 'secret.txt') try: with open(SECRET_FILE) as f: SECRET_KEY = f.read().strip() except IOError: try: import random SECRET_KEY = ''.join([random.SystemRandom().choice( 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]) secret = open(SECRET_FILE, 'w') secret.write(SECRET_KEY) secret.close() except IOError: Exception('Please create a {:s} file with random characters \ to generate your secret key!'.format(SECRET_FILE))
Fix not closed file warning
fix: Fix not closed file warning
Python
apache-2.0
maur1th/naxos,maur1th/naxos,maur1th/naxos,maur1th/naxos
python
## Code Before: try: SECRET_KEY except NameError: from os.path import join from .base import BASE_DIR SECRET_FILE = join(BASE_DIR, 'secret.txt') try: SECRET_KEY = open(SECRET_FILE).read().strip() except IOError: try: import random SECRET_KEY = ''.join([random.SystemRandom().choice( 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]) secret = open(SECRET_FILE, 'w') secret.write(SECRET_KEY) secret.close() except IOError: Exception('Please create a {:s} file with random characters \ to generate your secret key!'.format(SECRET_FILE)) ## Instruction: fix: Fix not closed file warning ## Code After: try: SECRET_KEY except NameError: from os.path import join from .base import BASE_DIR SECRET_FILE = join(BASE_DIR, 'secret.txt') try: with open(SECRET_FILE) as f: SECRET_KEY = f.read().strip() except IOError: try: import random SECRET_KEY = ''.join([random.SystemRandom().choice( 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]) secret = open(SECRET_FILE, 'w') secret.write(SECRET_KEY) secret.close() except IOError: Exception('Please create a {:s} file with random characters \ to generate your secret key!'.format(SECRET_FILE))
... from .base import BASE_DIR SECRET_FILE = join(BASE_DIR, 'secret.txt') try: with open(SECRET_FILE) as f: SECRET_KEY = f.read().strip() except IOError: try: import random ...
668a5240c29047d86fe9451f3078bb163bea0db9
skan/__init__.py
skan/__init__.py
from .csr import skeleton_to_csgraph, branch_statistics, summarise __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise']
from .csr import skeleton_to_csgraph, branch_statistics, summarise __version__ = '0.1-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise']
Add version info to package init
Add version info to package init
Python
bsd-3-clause
jni/skan
python
## Code Before: from .csr import skeleton_to_csgraph, branch_statistics, summarise __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise'] ## Instruction: Add version info to package init ## Code After: from .csr import skeleton_to_csgraph, branch_statistics, summarise __version__ = '0.1-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', 'summarise']
// ... existing code ... from .csr import skeleton_to_csgraph, branch_statistics, summarise __version__ = '0.1-dev' __all__ = ['skeleton_to_csgraph', 'branch_statistics', // ... rest of the code ...
e2fbf646b193284fc5d01684193b9c5aeb415efe
generate_html.py
generate_html.py
from jinja2 import Environment, FileSystemLoader import datetime import json env = Environment(loader=FileSystemLoader('templates'), autoescape=True) names_template = env.get_template('names.html') area_template = env.get_template('areas.html') with open("output/templates.js") as templatesjs: templates = templatesjs.read() with open("processed/area_matches.json") as area_matches_file: area_matches = json.load(area_matches_file) with open('output/areas.html', 'w+') as name_output: name_output.write(area_template.render( templates=templates, area_matches=area_matches, date=datetime.date.today().isoformat(), )) with open("processed/interesting_names.json") as interesting_names_file: interesting_names = json.load(interesting_names_file) with open('output/names.html', 'w+') as name_output: name_output.write(names_template.render( templates=templates, interesting_names=interesting_names, interesting_names_json=json.dumps(interesting_names), date=datetime.date.today().isoformat(), ))
from jinja2 import Environment, FileSystemLoader import datetime import json env = Environment(loader=FileSystemLoader('templates'), autoescape=True) names_template = env.get_template('names.html') area_template = env.get_template('areas.html') with open("output/templates.js") as templatesjs: templates = templatesjs.read() with open("processed/area_matches.json") as area_matches_file: area_matches = json.load(area_matches_file) with open('output/areas.html', 'w+') as name_output: name_output.write(area_template.render( templates=templates, area_matches=area_matches, date=datetime.date.today().isoformat(), )) with open("processed/interesting_names.json") as interesting_names_file: interesting_names = json.load(interesting_names_file) with open('output/names.html', 'w+') as name_output, open("key_field_names.txt") as key_field_names_file: key_fields = list(set([key_field_name.strip() for key_field_name in key_field_names_file])) name_output.write(names_template.render( templates=templates, interesting_names=interesting_names, interesting_names_json=json.dumps(interesting_names), date=datetime.date.today().isoformat(), key_fields_json=json.dumps(key_fields), ))
Fix due to merge conflicts
Fix due to merge conflicts
Python
agpl-3.0
TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine
python
## Code Before: from jinja2 import Environment, FileSystemLoader import datetime import json env = Environment(loader=FileSystemLoader('templates'), autoescape=True) names_template = env.get_template('names.html') area_template = env.get_template('areas.html') with open("output/templates.js") as templatesjs: templates = templatesjs.read() with open("processed/area_matches.json") as area_matches_file: area_matches = json.load(area_matches_file) with open('output/areas.html', 'w+') as name_output: name_output.write(area_template.render( templates=templates, area_matches=area_matches, date=datetime.date.today().isoformat(), )) with open("processed/interesting_names.json") as interesting_names_file: interesting_names = json.load(interesting_names_file) with open('output/names.html', 'w+') as name_output: name_output.write(names_template.render( templates=templates, interesting_names=interesting_names, interesting_names_json=json.dumps(interesting_names), date=datetime.date.today().isoformat(), )) ## Instruction: Fix due to merge conflicts ## Code After: from jinja2 import Environment, FileSystemLoader import datetime import json env = Environment(loader=FileSystemLoader('templates'), autoescape=True) names_template = env.get_template('names.html') area_template = env.get_template('areas.html') with open("output/templates.js") as templatesjs: templates = templatesjs.read() with open("processed/area_matches.json") as area_matches_file: area_matches = json.load(area_matches_file) with open('output/areas.html', 'w+') as name_output: name_output.write(area_template.render( templates=templates, area_matches=area_matches, date=datetime.date.today().isoformat(), )) with open("processed/interesting_names.json") as interesting_names_file: interesting_names = json.load(interesting_names_file) with open('output/names.html', 'w+') as name_output, open("key_field_names.txt") as key_field_names_file: key_fields = list(set([key_field_name.strip() for key_field_name in key_field_names_file])) name_output.write(names_template.render( templates=templates, interesting_names=interesting_names, interesting_names_json=json.dumps(interesting_names), date=datetime.date.today().isoformat(), key_fields_json=json.dumps(key_fields), ))
// ... existing code ... with open("processed/interesting_names.json") as interesting_names_file: interesting_names = json.load(interesting_names_file) with open('output/names.html', 'w+') as name_output, open("key_field_names.txt") as key_field_names_file: key_fields = list(set([key_field_name.strip() for key_field_name in key_field_names_file])) name_output.write(names_template.render( templates=templates, interesting_names=interesting_names, interesting_names_json=json.dumps(interesting_names), date=datetime.date.today().isoformat(), key_fields_json=json.dumps(key_fields), )) // ... rest of the code ...
c4f0f13892f1a1af73a94e6cbea95d30e676203c
xorgauth/accounts/views.py
xorgauth/accounts/views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import TemplateView from oidc_provider.models import UserConsent, Client @login_required def list_consents(request): # if a revoke request was done, process it revoke = request.POST.get('revoke', None) if revoke is not None: consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke) if consent: revoked_client = consent[0].client consent[0].delete() messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name)) else: client = Client.objects.filter(client_id=revoke) if client: messages.error(request, "You have no consent for client \"{}\".".format(client[0].name)) else: messages.error(request, "Unknown client.") # render the result consents = UserConsent.objects.filter(user=request.user) return render(request, 'list_consents.html', { 'consents': consents }) class ProfileView(TemplateView, LoginRequiredMixin): template_name = 'profile.html'
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import TemplateView from oidc_provider.models import UserConsent, Client @login_required def list_consents(request): # if a revoke request was done, process it revoke = request.POST.get('revoke', None) if revoke is not None: consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke) if consent: revoked_client = consent[0].client consent[0].delete() messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name)) else: client = Client.objects.filter(client_id=revoke) if client: messages.error(request, "You have no consent for client \"{}\".".format(client[0].name)) else: messages.error(request, "Unknown client.") # render the result consents = UserConsent.objects.filter(user=request.user) return render(request, 'list_consents.html', { 'consents': consents }) class ProfileView(LoginRequiredMixin, TemplateView): template_name = 'profile.html'
Fix access restriction to /accounts/profile/
Fix access restriction to /accounts/profile/ LoginRequiredMixin needs to come first for it to be applied. Otherwise, /accounts/profile/ is accessible even when the user is not authenticated.
Python
agpl-3.0
Polytechnique-org/xorgauth,Polytechnique-org/xorgauth
python
## Code Before: from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import TemplateView from oidc_provider.models import UserConsent, Client @login_required def list_consents(request): # if a revoke request was done, process it revoke = request.POST.get('revoke', None) if revoke is not None: consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke) if consent: revoked_client = consent[0].client consent[0].delete() messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name)) else: client = Client.objects.filter(client_id=revoke) if client: messages.error(request, "You have no consent for client \"{}\".".format(client[0].name)) else: messages.error(request, "Unknown client.") # render the result consents = UserConsent.objects.filter(user=request.user) return render(request, 'list_consents.html', { 'consents': consents }) class ProfileView(TemplateView, LoginRequiredMixin): template_name = 'profile.html' ## Instruction: Fix access restriction to /accounts/profile/ LoginRequiredMixin needs to come first for it to be applied. Otherwise, /accounts/profile/ is accessible even when the user is not authenticated. ## Code After: from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import TemplateView from oidc_provider.models import UserConsent, Client @login_required def list_consents(request): # if a revoke request was done, process it revoke = request.POST.get('revoke', None) if revoke is not None: consent = UserConsent.objects.filter(user=request.user, client__client_id=revoke) if consent: revoked_client = consent[0].client consent[0].delete() messages.success(request, "Successfully revoked consent for client \"{}\"".format(revoked_client.name)) else: client = Client.objects.filter(client_id=revoke) if client: messages.error(request, "You have no consent for client \"{}\".".format(client[0].name)) else: messages.error(request, "Unknown client.") # render the result consents = UserConsent.objects.filter(user=request.user) return render(request, 'list_consents.html', { 'consents': consents }) class ProfileView(LoginRequiredMixin, TemplateView): template_name = 'profile.html'
# ... existing code ... }) class ProfileView(LoginRequiredMixin, TemplateView): template_name = 'profile.html' # ... rest of the code ...
56a94b6ca5cadceb503edc7b968f813e66fafe92
src/web/__init__.py
src/web/__init__.py
from random import choice from faker.providers import BaseProvider from .mimetypes import mime_types class WebProvider(BaseProvider): """ A Provider for web-related test data. >>> from faker import Faker >>> from faker_web import WebProvider >>> fake = Faker() >>> fake.add_provider(WebProvider) """ all_content = mime_types popular_content = { 'application/javascript': ['js'], 'application/json': ['json'], 'application/pdf': ['pdf'], 'image/jpeg': ['jpeg', 'jpg', 'jpe'], 'image/gif': ['gif'], 'image/png': ['png'], 'image/svg+xml': ['svg', 'svgz'], 'text/css': ['css'], 'text/html': ['html', 'htm'], 'text/plain': ['txt', 'text', 'conf', 'def', 'list', 'log', 'in'], } def mime_type(self): """ Returns a mime-type from the list of types understood by the Apache http server. >>> fake.mime_type() application/mxf :return: content-type/mime-type :rtype: str """ return choice(list(self.all_content.keys())) def mime_type_popular(self): """ Returns a popular mime-type. >>> fake.mime_type_popular() text/html :return: content-type/mime-type :rtype: str """ return choice(list(self.popular_content.keys()))
from faker.providers import BaseProvider from .mimetypes import mime_types class WebProvider(BaseProvider): """ A Provider for web-related test data. >>> from faker import Faker >>> from faker_web import WebProvider >>> fake = Faker() >>> fake.add_provider(WebProvider) """ all_mime_types = mime_types popular_mime_types = { 'application/javascript': ['js'], 'application/json': ['json'], 'application/pdf': ['pdf'], 'image/jpeg': ['jpeg', 'jpg', 'jpe'], 'image/gif': ['gif'], 'image/png': ['png'], 'image/svg+xml': ['svg', 'svgz'], 'text/css': ['css'], 'text/html': ['html', 'htm'], 'text/plain': ['txt', 'text', 'conf', 'def', 'list', 'log', 'in'], } def mime_type(self): """ Returns a mime-type from the list of types understood by the Apache http server. >>> fake.mime_type() application/mxf :return: content-type/mime-type :rtype: str """ return self.random_element(self.all_mime_types.keys()) def mime_type_popular(self): """ Returns a popular mime-type. >>> fake.mime_type_popular() text/html :return: content-type/mime-type :rtype: str """ return self.random_element(self.popular_mime_types.keys())
Use random_element instead of random.choice
Use random_element instead of random.choice
Python
apache-2.0
thiagofigueiro/faker_web
python
## Code Before: from random import choice from faker.providers import BaseProvider from .mimetypes import mime_types class WebProvider(BaseProvider): """ A Provider for web-related test data. >>> from faker import Faker >>> from faker_web import WebProvider >>> fake = Faker() >>> fake.add_provider(WebProvider) """ all_content = mime_types popular_content = { 'application/javascript': ['js'], 'application/json': ['json'], 'application/pdf': ['pdf'], 'image/jpeg': ['jpeg', 'jpg', 'jpe'], 'image/gif': ['gif'], 'image/png': ['png'], 'image/svg+xml': ['svg', 'svgz'], 'text/css': ['css'], 'text/html': ['html', 'htm'], 'text/plain': ['txt', 'text', 'conf', 'def', 'list', 'log', 'in'], } def mime_type(self): """ Returns a mime-type from the list of types understood by the Apache http server. >>> fake.mime_type() application/mxf :return: content-type/mime-type :rtype: str """ return choice(list(self.all_content.keys())) def mime_type_popular(self): """ Returns a popular mime-type. >>> fake.mime_type_popular() text/html :return: content-type/mime-type :rtype: str """ return choice(list(self.popular_content.keys())) ## Instruction: Use random_element instead of random.choice ## Code After: from faker.providers import BaseProvider from .mimetypes import mime_types class WebProvider(BaseProvider): """ A Provider for web-related test data. >>> from faker import Faker >>> from faker_web import WebProvider >>> fake = Faker() >>> fake.add_provider(WebProvider) """ all_mime_types = mime_types popular_mime_types = { 'application/javascript': ['js'], 'application/json': ['json'], 'application/pdf': ['pdf'], 'image/jpeg': ['jpeg', 'jpg', 'jpe'], 'image/gif': ['gif'], 'image/png': ['png'], 'image/svg+xml': ['svg', 'svgz'], 'text/css': ['css'], 'text/html': ['html', 'htm'], 'text/plain': ['txt', 'text', 'conf', 'def', 'list', 'log', 'in'], } def mime_type(self): """ Returns a mime-type from the list of types understood by the Apache http server. >>> fake.mime_type() application/mxf :return: content-type/mime-type :rtype: str """ return self.random_element(self.all_mime_types.keys()) def mime_type_popular(self): """ Returns a popular mime-type. >>> fake.mime_type_popular() text/html :return: content-type/mime-type :rtype: str """ return self.random_element(self.popular_mime_types.keys())
# ... existing code ... from faker.providers import BaseProvider from .mimetypes import mime_types # ... modified code ... >>> fake = Faker() >>> fake.add_provider(WebProvider) """ all_mime_types = mime_types popular_mime_types = { 'application/javascript': ['js'], 'application/json': ['json'], 'application/pdf': ['pdf'], ... :return: content-type/mime-type :rtype: str """ return self.random_element(self.all_mime_types.keys()) def mime_type_popular(self): """ ... :return: content-type/mime-type :rtype: str """ return self.random_element(self.popular_mime_types.keys()) # ... rest of the code ...
90d563b4a2362de25bc08b2d9de318e957abae60
subprojects/resources-gcs/build.gradle.kts
subprojects/resources-gcs/build.gradle.kts
plugins { id("gradlebuild.distribution.api-java") } description = "Implementation for interacting with GCS repositories" dependencies { implementation(project(":base-services")) implementation(project(":logging")) implementation(project(":resources")) implementation(project(":resources-http")) implementation(project(":core")) implementation(libs.slf4jApi) implementation(libs.guava) implementation(libs.commonsLang) implementation(libs.jacksonCore) implementation(libs.jacksonDatabind) implementation(libs.gcs) testImplementation(libs.groovy) testImplementation(testFixtures(project(":core"))) testImplementation(testFixtures(project(":dependency-management"))) testImplementation(testFixtures(project(":ivy"))) testImplementation(testFixtures(project(":maven"))) integTestImplementation(project(":core-api")) integTestImplementation(project(":model-core")) integTestImplementation(libs.commonsIo) integTestImplementation(libs.jetty) integTestImplementation(libs.joda) integTestDistributionRuntimeOnly(project(":distributions-basics")) }
plugins { id("gradlebuild.distribution.api-java") } description = "Implementation for interacting with Google Cloud Storage (GCS) repositories" dependencies { implementation(project(":base-services")) implementation(project(":logging")) implementation(project(":resources")) implementation(project(":resources-http")) implementation(project(":core")) implementation(libs.slf4jApi) implementation(libs.guava) implementation(libs.commonsLang) implementation(libs.jacksonCore) implementation(libs.jacksonDatabind) implementation(libs.gcs) testImplementation(libs.groovy) testImplementation(testFixtures(project(":core"))) testImplementation(testFixtures(project(":dependency-management"))) testImplementation(testFixtures(project(":ivy"))) testImplementation(testFixtures(project(":maven"))) integTestImplementation(project(":core-api")) integTestImplementation(project(":model-core")) integTestImplementation(libs.commonsIo) integTestImplementation(libs.jetty) integTestImplementation(libs.joda) integTestDistributionRuntimeOnly(project(":distributions-basics")) }
Expand what GCS means in project description
Expand what GCS means in project description
Kotlin
apache-2.0
gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle
kotlin
## Code Before: plugins { id("gradlebuild.distribution.api-java") } description = "Implementation for interacting with GCS repositories" dependencies { implementation(project(":base-services")) implementation(project(":logging")) implementation(project(":resources")) implementation(project(":resources-http")) implementation(project(":core")) implementation(libs.slf4jApi) implementation(libs.guava) implementation(libs.commonsLang) implementation(libs.jacksonCore) implementation(libs.jacksonDatabind) implementation(libs.gcs) testImplementation(libs.groovy) testImplementation(testFixtures(project(":core"))) testImplementation(testFixtures(project(":dependency-management"))) testImplementation(testFixtures(project(":ivy"))) testImplementation(testFixtures(project(":maven"))) integTestImplementation(project(":core-api")) integTestImplementation(project(":model-core")) integTestImplementation(libs.commonsIo) integTestImplementation(libs.jetty) integTestImplementation(libs.joda) integTestDistributionRuntimeOnly(project(":distributions-basics")) } ## Instruction: Expand what GCS means in project description ## Code After: plugins { id("gradlebuild.distribution.api-java") } description = "Implementation for interacting with Google Cloud Storage (GCS) repositories" dependencies { implementation(project(":base-services")) implementation(project(":logging")) implementation(project(":resources")) implementation(project(":resources-http")) implementation(project(":core")) implementation(libs.slf4jApi) implementation(libs.guava) implementation(libs.commonsLang) implementation(libs.jacksonCore) implementation(libs.jacksonDatabind) implementation(libs.gcs) testImplementation(libs.groovy) testImplementation(testFixtures(project(":core"))) testImplementation(testFixtures(project(":dependency-management"))) testImplementation(testFixtures(project(":ivy"))) testImplementation(testFixtures(project(":maven"))) integTestImplementation(project(":core-api")) integTestImplementation(project(":model-core")) integTestImplementation(libs.commonsIo) integTestImplementation(libs.jetty) integTestImplementation(libs.joda) integTestDistributionRuntimeOnly(project(":distributions-basics")) }
// ... existing code ... id("gradlebuild.distribution.api-java") } description = "Implementation for interacting with Google Cloud Storage (GCS) repositories" dependencies { implementation(project(":base-services")) // ... rest of the code ...
9cea98e320bfc37a6df373245f916b15c68a7f01
src/consensus/consensus.h
src/consensus/consensus.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CONSENSUS_CONSENSUS_H #define BITCOIN_CONSENSUS_CONSENSUS_H /** The maximum allowed size for a serialized block, in bytes (network rule) */ static const unsigned int MAX_BLOCK_SIZE = 1000000; /** The maximum allowed number of signature check operations in a block (network rule) */ static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */ static const int COINBASE_MATURITY = 100; /** Flags for nSequence and nLockTime locks */ enum { /* Interpret sequence numbers as relative lock-time constraints. */ LOCKTIME_VERIFY_SEQUENCE = (1 << 0), /* Use GetMedianTimePast() instead of nTime for end point timestamp. */ LOCKTIME_MEDIAN_TIME_PAST = (1 << 1), }; #endif // BITCOIN_CONSENSUS_CONSENSUS_H
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2016 The Bitcoin Ocho developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CONSENSUS_CONSENSUS_H #define BITCOIN_CONSENSUS_CONSENSUS_H /** The maximum allowed size for a serialized block, in bytes (network rule) */ /** Bitcoin Ocho, we multiply by 8 for Ocho */ static const unsigned int MAX_BLOCK_SIZE = 1000000*8; /** The maximum allowed number of signature check operations in a block (network rule) */ static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */ static const int COINBASE_MATURITY = 100; /** Flags for nSequence and nLockTime locks */ enum { /* Interpret sequence numbers as relative lock-time constraints. */ LOCKTIME_VERIFY_SEQUENCE = (1 << 0), /* Use GetMedianTimePast() instead of nTime for end point timestamp. */ LOCKTIME_MEDIAN_TIME_PAST = (1 << 1), }; #endif // BITCOIN_CONSENSUS_CONSENSUS_H
Add more Ochoness to Bitcoin.
Add more Ochoness to Bitcoin.
C
mit
goku1997/bitcoin,goku1997/bitcoin,goku1997/bitcoin,goku1997/bitcoin,goku1997/bitcoin,goku1997/bitcoin
c
## Code Before: // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CONSENSUS_CONSENSUS_H #define BITCOIN_CONSENSUS_CONSENSUS_H /** The maximum allowed size for a serialized block, in bytes (network rule) */ static const unsigned int MAX_BLOCK_SIZE = 1000000; /** The maximum allowed number of signature check operations in a block (network rule) */ static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */ static const int COINBASE_MATURITY = 100; /** Flags for nSequence and nLockTime locks */ enum { /* Interpret sequence numbers as relative lock-time constraints. */ LOCKTIME_VERIFY_SEQUENCE = (1 << 0), /* Use GetMedianTimePast() instead of nTime for end point timestamp. */ LOCKTIME_MEDIAN_TIME_PAST = (1 << 1), }; #endif // BITCOIN_CONSENSUS_CONSENSUS_H ## Instruction: Add more Ochoness to Bitcoin. ## Code After: // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2016 The Bitcoin Ocho developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CONSENSUS_CONSENSUS_H #define BITCOIN_CONSENSUS_CONSENSUS_H /** The maximum allowed size for a serialized block, in bytes (network rule) */ /** Bitcoin Ocho, we multiply by 8 for Ocho */ static const unsigned int MAX_BLOCK_SIZE = 1000000*8; /** The maximum allowed number of signature check operations in a block (network rule) */ static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */ static const int COINBASE_MATURITY = 100; /** Flags for nSequence and nLockTime locks */ enum { /* Interpret sequence numbers as relative lock-time constraints. */ LOCKTIME_VERIFY_SEQUENCE = (1 << 0), /* Use GetMedianTimePast() instead of nTime for end point timestamp. */ LOCKTIME_MEDIAN_TIME_PAST = (1 << 1), }; #endif // BITCOIN_CONSENSUS_CONSENSUS_H
// ... existing code ... // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2016 The Bitcoin Ocho developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // ... modified code ... #define BITCOIN_CONSENSUS_CONSENSUS_H /** The maximum allowed size for a serialized block, in bytes (network rule) */ /** Bitcoin Ocho, we multiply by 8 for Ocho */ static const unsigned int MAX_BLOCK_SIZE = 1000000*8; /** The maximum allowed number of signature check operations in a block (network rule) */ static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */ // ... rest of the code ...
937a5e32c77ca57917d60a891616fbcf19ab19f9
respite/utils.py
respite/utils.py
from django import forms def generate_form(model): """ Generate a form from a model. Arguments: model -- A Django model. """ _model = model class Form(forms.ModelForm): class Meta: model = _model return Form def parse_http_accept_header(header): """ Return a list of content types listed in the HTTP Accept header ordered by quality. Arguments: header -- A string describing the contents of the HTTP Accept header. """ components = header.split(',') l = [] for component in components: if ';' in component: subcomponents = component.split(';') l.append( ( subcomponents[0], # eg. 'text/html' subcomponents[1][2:] # eg. 'q=0.9' ) ) else: l.append((component, '1')) l.sort( key = lambda i: i[1], reverse = True ) content_types = [] for i in l: content_types.append(i[0]) return content_types
from django import forms def generate_form(model): """ Generate a form from a model. Arguments: model -- A Django model. """ _model = model class Form(forms.ModelForm): class Meta: model = _model return Form def parse_http_accept_header(header): """ Return a list of content types listed in the HTTP Accept header ordered by quality. Arguments: header -- A string describing the contents of the HTTP Accept header. """ components = [item.strip() for item in header.split(',')] l = [] for component in components: if ';' in component: subcomponents = [item.strip() for item in component.split(';')] l.append( ( subcomponents[0], # eg. 'text/html' subcomponents[1][2:] # eg. 'q=0.9' ) ) else: l.append((component, '1')) l.sort( key = lambda i: i[1], reverse = True ) content_types = [] for i in l: content_types.append(i[0]) return content_types
Fix a bug that caused HTTP Accept headers with whitespace to be parsed incorrectly
Fix a bug that caused HTTP Accept headers with whitespace to be parsed incorrectly
Python
mit
jgorset/django-respite,jgorset/django-respite,jgorset/django-respite
python
## Code Before: from django import forms def generate_form(model): """ Generate a form from a model. Arguments: model -- A Django model. """ _model = model class Form(forms.ModelForm): class Meta: model = _model return Form def parse_http_accept_header(header): """ Return a list of content types listed in the HTTP Accept header ordered by quality. Arguments: header -- A string describing the contents of the HTTP Accept header. """ components = header.split(',') l = [] for component in components: if ';' in component: subcomponents = component.split(';') l.append( ( subcomponents[0], # eg. 'text/html' subcomponents[1][2:] # eg. 'q=0.9' ) ) else: l.append((component, '1')) l.sort( key = lambda i: i[1], reverse = True ) content_types = [] for i in l: content_types.append(i[0]) return content_types ## Instruction: Fix a bug that caused HTTP Accept headers with whitespace to be parsed incorrectly ## Code After: from django import forms def generate_form(model): """ Generate a form from a model. Arguments: model -- A Django model. """ _model = model class Form(forms.ModelForm): class Meta: model = _model return Form def parse_http_accept_header(header): """ Return a list of content types listed in the HTTP Accept header ordered by quality. Arguments: header -- A string describing the contents of the HTTP Accept header. """ components = [item.strip() for item in header.split(',')] l = [] for component in components: if ';' in component: subcomponents = [item.strip() for item in component.split(';')] l.append( ( subcomponents[0], # eg. 'text/html' subcomponents[1][2:] # eg. 'q=0.9' ) ) else: l.append((component, '1')) l.sort( key = lambda i: i[1], reverse = True ) content_types = [] for i in l: content_types.append(i[0]) return content_types
... Arguments: header -- A string describing the contents of the HTTP Accept header. """ components = [item.strip() for item in header.split(',')] l = [] for component in components: if ';' in component: subcomponents = [item.strip() for item in component.split(';')] l.append( ( subcomponents[0], # eg. 'text/html' ...
bbfe056602075a46b231dc28ddcada7f525ce927
conftest.py
conftest.py
import pytest import django_webtest from django.core.urlresolvers import reverse from ideasbox.tests.factories import UserFactory @pytest.fixture() def user(): return UserFactory(short_name="Hello", password='password') @pytest.fixture() def staffuser(): return UserFactory(short_name="Hello", password='password', is_staff=True) @pytest.fixture() def app(request): wtm = django_webtest.WebTestMixin() wtm._patch_settings() request.addfinalizer(wtm._unpatch_settings) return django_webtest.DjangoTestApp() @pytest.fixture() def loggedapp(app, user): """Return an app with an already logged in user.""" form = app.get(reverse('login')).forms['login'] form['username'] = user.serial form['password'] = 'password' form.submit().follow() setattr(app, 'user', user) # for later use, if needed return app @pytest.fixture() def staffapp(app, staffuser): """Return an app with an already logged in staff user.""" form = app.get(reverse('login')).forms['login'] form['username'] = staffuser.serial form['password'] = 'password' form.submit().follow() setattr(app, 'user', user) # for later use, if needed return app
import pytest import django_webtest from django.core.urlresolvers import reverse from ideasbox.tests.factories import UserFactory @pytest.fixture() def user(): return UserFactory(short_name="Hello", password='password') @pytest.fixture() def staffuser(): return UserFactory(short_name="Hello", password='password', is_staff=True) @pytest.yield_fixture() def app(request): wtm = django_webtest.WebTestMixin() wtm._patch_settings() yield django_webtest.DjangoTestApp() wtm._unpatch_settings() @pytest.fixture() def loggedapp(app, user): """Return an app with an already logged in user.""" form = app.get(reverse('login')).forms['login'] form['username'] = user.serial form['password'] = 'password' form.submit().follow() setattr(app, 'user', user) # for later use, if needed return app @pytest.fixture() def staffapp(app, staffuser): """Return an app with an already logged in staff user.""" form = app.get(reverse('login')).forms['login'] form['username'] = staffuser.serial form['password'] = 'password' form.submit().follow() setattr(app, 'user', user) # for later use, if needed return app
Use yield_fixture for app fixture
Use yield_fixture for app fixture
Python
agpl-3.0
ideascube/ideascube,Lcaracol/ideasbox.lan,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan
python
## Code Before: import pytest import django_webtest from django.core.urlresolvers import reverse from ideasbox.tests.factories import UserFactory @pytest.fixture() def user(): return UserFactory(short_name="Hello", password='password') @pytest.fixture() def staffuser(): return UserFactory(short_name="Hello", password='password', is_staff=True) @pytest.fixture() def app(request): wtm = django_webtest.WebTestMixin() wtm._patch_settings() request.addfinalizer(wtm._unpatch_settings) return django_webtest.DjangoTestApp() @pytest.fixture() def loggedapp(app, user): """Return an app with an already logged in user.""" form = app.get(reverse('login')).forms['login'] form['username'] = user.serial form['password'] = 'password' form.submit().follow() setattr(app, 'user', user) # for later use, if needed return app @pytest.fixture() def staffapp(app, staffuser): """Return an app with an already logged in staff user.""" form = app.get(reverse('login')).forms['login'] form['username'] = staffuser.serial form['password'] = 'password' form.submit().follow() setattr(app, 'user', user) # for later use, if needed return app ## Instruction: Use yield_fixture for app fixture ## Code After: import pytest import django_webtest from django.core.urlresolvers import reverse from ideasbox.tests.factories import UserFactory @pytest.fixture() def user(): return UserFactory(short_name="Hello", password='password') @pytest.fixture() def staffuser(): return UserFactory(short_name="Hello", password='password', is_staff=True) @pytest.yield_fixture() def app(request): wtm = django_webtest.WebTestMixin() wtm._patch_settings() yield django_webtest.DjangoTestApp() wtm._unpatch_settings() @pytest.fixture() def loggedapp(app, user): """Return an app with an already logged in user.""" form = app.get(reverse('login')).forms['login'] form['username'] = user.serial form['password'] = 'password' form.submit().follow() setattr(app, 'user', user) # for later use, if needed return app @pytest.fixture() def staffapp(app, staffuser): """Return an app with an already logged in staff user.""" form = app.get(reverse('login')).forms['login'] form['username'] = staffuser.serial form['password'] = 'password' form.submit().follow() setattr(app, 'user', user) # for later use, if needed return app
... return UserFactory(short_name="Hello", password='password', is_staff=True) @pytest.yield_fixture() def app(request): wtm = django_webtest.WebTestMixin() wtm._patch_settings() yield django_webtest.DjangoTestApp() wtm._unpatch_settings() @pytest.fixture() ...
9273b9e9cac50c949c8ac4befa7290cbff84d2b7
src/main/java/com/pg/creg/expr/character/Negation.java
src/main/java/com/pg/creg/expr/character/Negation.java
/* * Copyright 2014 gandola. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pg.creg.expr.character; import com.pg.creg.exception.CregException; /** * Applies negation operator over the given CharacterExpression. [^a-z] * @author Pedro Gandola <[email protected]> */ public class Negation implements CharacterExpression { private final CharacterExpression expr; public Negation(CharacterExpression expr) { this.expr = expr; } public void eval(StringBuilder builder) throws CregException { builder.append("^"); expr.eval(builder); } }
/* * Copyright 2014 gandola. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pg.creg.expr.character; import com.pg.creg.exception.CregException; import static com.pg.creg.util.OperatorPosition.*; import static com.pg.creg.util.StringUtils.*; /** * Applies negation operator over the given CharacterExpression. [^a-z] * @author Pedro Gandola <[email protected]> */ public class Negation implements CharacterExpression { private final CharacterExpression expr; public Negation(CharacterExpression expr) { this.expr = expr; } public void eval(StringBuilder builder) throws CregException { appendExpr(expr, "^", builder, BEGIN); } }
Use appendExpr on simple expressions
Use appendExpr on simple expressions
Java
apache-2.0
gandola/creg
java
## Code Before: /* * Copyright 2014 gandola. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pg.creg.expr.character; import com.pg.creg.exception.CregException; /** * Applies negation operator over the given CharacterExpression. [^a-z] * @author Pedro Gandola <[email protected]> */ public class Negation implements CharacterExpression { private final CharacterExpression expr; public Negation(CharacterExpression expr) { this.expr = expr; } public void eval(StringBuilder builder) throws CregException { builder.append("^"); expr.eval(builder); } } ## Instruction: Use appendExpr on simple expressions ## Code After: /* * Copyright 2014 gandola. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pg.creg.expr.character; import com.pg.creg.exception.CregException; import static com.pg.creg.util.OperatorPosition.*; import static com.pg.creg.util.StringUtils.*; /** * Applies negation operator over the given CharacterExpression. [^a-z] * @author Pedro Gandola <[email protected]> */ public class Negation implements CharacterExpression { private final CharacterExpression expr; public Negation(CharacterExpression expr) { this.expr = expr; } public void eval(StringBuilder builder) throws CregException { appendExpr(expr, "^", builder, BEGIN); } }
... package com.pg.creg.expr.character; import com.pg.creg.exception.CregException; import static com.pg.creg.util.OperatorPosition.*; import static com.pg.creg.util.StringUtils.*; /** * Applies negation operator over the given CharacterExpression. [^a-z] ... } public void eval(StringBuilder builder) throws CregException { appendExpr(expr, "^", builder, BEGIN); } } ...
8608283592338960c80113ff4d68f42936ddb969
linter.py
linter.py
"""This module exports the Perl plugin class.""" import shlex from SublimeLinter.lint import Linter, util class Perl(Linter): """Provides an interface to perl -c.""" syntax = ('modernperl', 'perl') executable = 'perl' base_cmd = ('perl -c') regex = r'(?P<message>.+?) at .+? line (?P<line>\d+)(, near "(?P<near>.+?)")?' error_stream = util.STREAM_STDERR def cmd(self): """ Return the command line to execute. Overridden so we can add include paths based on the 'include_dirs' settings. """ full_cmd = self.base_cmd settings = self.get_view_settings() include_dirs = settings.get('include_dirs', []) if include_dirs: full_cmd += ' ' . join([' -I ' + shlex.quote(include) for include in include_dirs]) return full_cmd
"""This module exports the Perl plugin class.""" import shlex from SublimeLinter.lint import Linter, util class Perl(Linter): """Provides an interface to perl -c.""" syntax = ('modernperl', 'perl') executable = 'perl' regex = r'(?P<message>.+?) at .+? line (?P<line>\d+)(, near "(?P<near>.+?)")?' error_stream = util.STREAM_STDERR def cmd(self): """ Return the command line to execute. Overridden so we can add include paths based on the 'include_dirs' settings. """ command = [self.executable_path, '-c'] include_dirs = self.get_view_settings().get('include_dirs', []) for e in include_dirs: command.append('-I') command.append(shlex.quote(e)) return command
Clean up include dir code
Clean up include dir code
Python
mit
oschwald/SublimeLinter-perl
python
## Code Before: """This module exports the Perl plugin class.""" import shlex from SublimeLinter.lint import Linter, util class Perl(Linter): """Provides an interface to perl -c.""" syntax = ('modernperl', 'perl') executable = 'perl' base_cmd = ('perl -c') regex = r'(?P<message>.+?) at .+? line (?P<line>\d+)(, near "(?P<near>.+?)")?' error_stream = util.STREAM_STDERR def cmd(self): """ Return the command line to execute. Overridden so we can add include paths based on the 'include_dirs' settings. """ full_cmd = self.base_cmd settings = self.get_view_settings() include_dirs = settings.get('include_dirs', []) if include_dirs: full_cmd += ' ' . join([' -I ' + shlex.quote(include) for include in include_dirs]) return full_cmd ## Instruction: Clean up include dir code ## Code After: """This module exports the Perl plugin class.""" import shlex from SublimeLinter.lint import Linter, util class Perl(Linter): """Provides an interface to perl -c.""" syntax = ('modernperl', 'perl') executable = 'perl' regex = r'(?P<message>.+?) at .+? line (?P<line>\d+)(, near "(?P<near>.+?)")?' error_stream = util.STREAM_STDERR def cmd(self): """ Return the command line to execute. Overridden so we can add include paths based on the 'include_dirs' settings. """ command = [self.executable_path, '-c'] include_dirs = self.get_view_settings().get('include_dirs', []) for e in include_dirs: command.append('-I') command.append(shlex.quote(e)) return command
# ... existing code ... syntax = ('modernperl', 'perl') executable = 'perl' regex = r'(?P<message>.+?) at .+? line (?P<line>\d+)(, near "(?P<near>.+?)")?' error_stream = util.STREAM_STDERR # ... modified code ... """ command = [self.executable_path, '-c'] include_dirs = self.get_view_settings().get('include_dirs', []) for e in include_dirs: command.append('-I') command.append(shlex.quote(e)) return command # ... rest of the code ...
29c1d901eb2e50c485aa617585be536c3fe468ad
src/test/java/endtoend/ApiEndToEndTest.java
src/test/java/endtoend/ApiEndToEndTest.java
package endtoend; import static org.junit.Assert.assertEquals; import me.moodcat.api.models.RoomModel; import me.moodcat.api.models.SongModel; import org.junit.Test; public class ApiEndToEndTest extends EndToEndTest { @Test public void canRetrieveRooms() { RoomModel room = this.performGETRequest(RoomModel.class, "rooms/1"); assertEquals(1, room.getId().intValue()); assertEquals(1, room.getNowPlaying().getSong().getId().intValue()); } @Test public void canRetrieveSongs() { SongModel song = this.performGETRequest(SongModel.class, "songs/1"); assertEquals(1, song.getId().intValue()); assertEquals(202330997, song.getSoundCloudId().intValue()); } }
package endtoend; import static org.junit.Assert.assertEquals; import java.util.List; import javax.ws.rs.core.GenericType; import me.moodcat.api.models.RoomModel; import me.moodcat.api.models.SongModel; import org.junit.Test; public class ApiEndToEndTest extends EndToEndTest { @Test public void canRetrieveRoom() { RoomModel room = this.performGETRequest(RoomModel.class, "rooms/1"); assertEquals(1, room.getId().intValue()); assertEquals(1, room.getNowPlaying().getSong().getId().intValue()); } @Test public void canRetrieveSongs() { SongModel song = this.performGETRequest(SongModel.class, "songs/1"); assertEquals(1, song.getId().intValue()); assertEquals(202330997, song.getSoundCloudId().intValue()); } @Test public void canRetrieveRooms() { List<RoomModel> rooms = this.performGETRequestWithGenericType(new GenericType<List<RoomModel>>(){}, "rooms"); assertEquals(1, rooms.get(0).getId().intValue()); } }
Test that might be failing. Let's see.
Test that might be failing. Let's see.
Java
mit
MoodCat/MoodCat.me-Core,MoodCat/MoodCat.me-Core
java
## Code Before: package endtoend; import static org.junit.Assert.assertEquals; import me.moodcat.api.models.RoomModel; import me.moodcat.api.models.SongModel; import org.junit.Test; public class ApiEndToEndTest extends EndToEndTest { @Test public void canRetrieveRooms() { RoomModel room = this.performGETRequest(RoomModel.class, "rooms/1"); assertEquals(1, room.getId().intValue()); assertEquals(1, room.getNowPlaying().getSong().getId().intValue()); } @Test public void canRetrieveSongs() { SongModel song = this.performGETRequest(SongModel.class, "songs/1"); assertEquals(1, song.getId().intValue()); assertEquals(202330997, song.getSoundCloudId().intValue()); } } ## Instruction: Test that might be failing. Let's see. ## Code After: package endtoend; import static org.junit.Assert.assertEquals; import java.util.List; import javax.ws.rs.core.GenericType; import me.moodcat.api.models.RoomModel; import me.moodcat.api.models.SongModel; import org.junit.Test; public class ApiEndToEndTest extends EndToEndTest { @Test public void canRetrieveRoom() { RoomModel room = this.performGETRequest(RoomModel.class, "rooms/1"); assertEquals(1, room.getId().intValue()); assertEquals(1, room.getNowPlaying().getSong().getId().intValue()); } @Test public void canRetrieveSongs() { SongModel song = this.performGETRequest(SongModel.class, "songs/1"); assertEquals(1, song.getId().intValue()); assertEquals(202330997, song.getSoundCloudId().intValue()); } @Test public void canRetrieveRooms() { List<RoomModel> rooms = this.performGETRequestWithGenericType(new GenericType<List<RoomModel>>(){}, "rooms"); assertEquals(1, rooms.get(0).getId().intValue()); } }
// ... existing code ... package endtoend; import static org.junit.Assert.assertEquals; import java.util.List; import javax.ws.rs.core.GenericType; import me.moodcat.api.models.RoomModel; import me.moodcat.api.models.SongModel; // ... modified code ... public class ApiEndToEndTest extends EndToEndTest { @Test public void canRetrieveRoom() { RoomModel room = this.performGETRequest(RoomModel.class, "rooms/1"); assertEquals(1, room.getId().intValue()); ... assertEquals(1, song.getId().intValue()); assertEquals(202330997, song.getSoundCloudId().intValue()); } @Test public void canRetrieveRooms() { List<RoomModel> rooms = this.performGETRequestWithGenericType(new GenericType<List<RoomModel>>(){}, "rooms"); assertEquals(1, rooms.get(0).getId().intValue()); } } // ... rest of the code ...
c4adc045c286e5c3c9040f15f9f27210b724ef64
src/main/java/io/burt/jmespath/ast/FlattenListNode.java
src/main/java/io/burt/jmespath/ast/FlattenListNode.java
package io.burt.jmespath.ast; public class FlattenListNode extends JmesPathNode { public FlattenListNode() { super(); } public FlattenListNode(JmesPathNode source) { super(source); } @Override protected boolean internalEquals(Object o) { return true; } @Override protected int internalHashCode() { return 19; } }
package io.burt.jmespath.ast; public class FlattenListNode extends JmesPathNode { public FlattenListNode(JmesPathNode source) { super(source); } @Override protected boolean internalEquals(Object o) { return true; } @Override protected int internalHashCode() { return 19; } }
Remove the no-args constructor from FlattenNode
Remove the no-args constructor from FlattenNode It is not used.
Java
bsd-3-clause
burtcorp/jmespath-java
java
## Code Before: package io.burt.jmespath.ast; public class FlattenListNode extends JmesPathNode { public FlattenListNode() { super(); } public FlattenListNode(JmesPathNode source) { super(source); } @Override protected boolean internalEquals(Object o) { return true; } @Override protected int internalHashCode() { return 19; } } ## Instruction: Remove the no-args constructor from FlattenNode It is not used. ## Code After: package io.burt.jmespath.ast; public class FlattenListNode extends JmesPathNode { public FlattenListNode(JmesPathNode source) { super(source); } @Override protected boolean internalEquals(Object o) { return true; } @Override protected int internalHashCode() { return 19; } }
// ... existing code ... package io.burt.jmespath.ast; public class FlattenListNode extends JmesPathNode { public FlattenListNode(JmesPathNode source) { super(source); } // ... rest of the code ...
dad970e9db2d3985a4995982d91a995898c8781b
virtool/handlers/updates.py
virtool/handlers/updates.py
import virtool.app import virtool.updates from virtool.handlers.utils import json_response async def get(req): db = req.app["db"] settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() await virtool.updates.get_releases(repo, server_version) return json_response({"message": "YAY"})
import virtool.app import virtool.updates from virtool.handlers.utils import json_response async def get(req): # db = req.app["db"] settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() releases = await virtool.updates.get_releases(repo, server_version) return json_response({ "releases": releases })
Make retrieval of releases from GitHub functional
Make retrieval of releases from GitHub functional
Python
mit
igboyes/virtool,virtool/virtool,virtool/virtool,igboyes/virtool
python
## Code Before: import virtool.app import virtool.updates from virtool.handlers.utils import json_response async def get(req): db = req.app["db"] settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() await virtool.updates.get_releases(repo, server_version) return json_response({"message": "YAY"}) ## Instruction: Make retrieval of releases from GitHub functional ## Code After: import virtool.app import virtool.updates from virtool.handlers.utils import json_response async def get(req): # db = req.app["db"] settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() releases = await virtool.updates.get_releases(repo, server_version) return json_response({ "releases": releases })
# ... existing code ... async def get(req): # db = req.app["db"] settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() releases = await virtool.updates.get_releases(repo, server_version) return json_response({ "releases": releases }) # ... rest of the code ...
cb6e44ad90cbf12f0569ec2a5777f74425d5d1be
findbugs/test/TwoStreams.java
findbugs/test/TwoStreams.java
import java.io.*; public class TwoStreams { public void twoStreamsWrong() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (r != null) { r.close(); } if (w != null) { try { w.close(); } catch (IOException e) { } } } } public void twoStreamsRight() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } if (r != null) { r.close(); } } } }
import java.io.*; public class TwoStreams { int x; public void twoStreamsWrong() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (r != null) { r.close(); } if (w != null) { try { w.close(); } catch (IOException e) { } } } } public void nullDereferenceCheck(TwoStreams o) throws IOException { BufferedReader r = new BufferedReader( new InputStreamReader( new FileInputStream("hello"))); int i = o.x; r.close(); } public void twoStreamsRight() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } if (r != null) { r.close(); } } } }
Check for potential null pointer exception
Check for potential null pointer exception git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@2103 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
Java
lgpl-2.1
johnscancella/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,sewe/spotbugs,sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs
java
## Code Before: import java.io.*; public class TwoStreams { public void twoStreamsWrong() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (r != null) { r.close(); } if (w != null) { try { w.close(); } catch (IOException e) { } } } } public void twoStreamsRight() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } if (r != null) { r.close(); } } } } ## Instruction: Check for potential null pointer exception git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@2103 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3 ## Code After: import java.io.*; public class TwoStreams { int x; public void twoStreamsWrong() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (r != null) { r.close(); } if (w != null) { try { w.close(); } catch (IOException e) { } } } } public void nullDereferenceCheck(TwoStreams o) throws IOException { BufferedReader r = new BufferedReader( new InputStreamReader( new FileInputStream("hello"))); int i = o.x; r.close(); } public void twoStreamsRight() throws IOException { BufferedReader r = null; Writer w = null; try { r = new BufferedReader(new InputStreamReader(new FileInputStream("hello"))); String l = r.readLine(); w = new OutputStreamWriter(new FileOutputStream("blah")); w.write(l); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } if (r != null) { r.close(); } } } }
// ... existing code ... import java.io.*; public class TwoStreams { int x; public void twoStreamsWrong() throws IOException { BufferedReader r = null; Writer w = null; // ... modified code ... } } public void nullDereferenceCheck(TwoStreams o) throws IOException { BufferedReader r = new BufferedReader( new InputStreamReader( new FileInputStream("hello"))); int i = o.x; r.close(); } public void twoStreamsRight() throws IOException { BufferedReader r = null; Writer w = null; // ... rest of the code ...
2ee34d2d74a8fb41dfe49cd3933d0d7abb25fee4
rsvp/admin.py
rsvp/admin.py
from django.contrib import admin from rsvp.models import Guest, Location, Table, Event, Hotel, Party, Song class AdminModel(admin.ModelAdmin): list_display = ['name'] class GuestAdmin(admin.ModelAdmin): list_display = ['last_name', 'first_name'] list_filter = ['last_name', 'first_name'] search_fields = ['last_name', 'first_name', ] save_on_top = True class LocationAdmin(AdminModel): pass class TableAdmin(AdminModel): pass class EventAdmin(AdminModel): pass class HotelAdmin(AdminModel): pass class PartyAdmin(admin.ModelAdmin): filter_horizontal = ('guests',) list_display = ['name', 'responded'] class SongAdmin(admin.ModelAdmin): list_display = ['title', 'artist', 'votes'] admin.site.register(Guest, GuestAdmin) admin.site.register(Location, LocationAdmin) admin.site.register(Table, TableAdmin) admin.site.register(Event, EventAdmin) admin.site.register(Hotel, HotelAdmin) admin.site.register(Party, PartyAdmin) admin.site.register(Song, SongAdmin)
from django.contrib import admin from rsvp.models import Guest, Location, Table, Event, Hotel, Party, Song class AdminModel(admin.ModelAdmin): list_display = ['name'] class GuestAdmin(admin.ModelAdmin): list_display = ['last_name', 'first_name', 'attending', ] list_filter = ['last_name', 'first_name'] search_fields = ['last_name', 'first_name', ] save_on_top = True class LocationAdmin(AdminModel): pass class TableAdmin(AdminModel): pass class EventAdmin(AdminModel): pass class HotelAdmin(AdminModel): pass class PartyAdmin(admin.ModelAdmin): filter_horizontal = ('guests',) list_display = ['name', 'responded'] class SongAdmin(admin.ModelAdmin): list_display = ['title', 'artist', 'votes'] admin.site.register(Guest, GuestAdmin) admin.site.register(Location, LocationAdmin) admin.site.register(Table, TableAdmin) admin.site.register(Event, EventAdmin) admin.site.register(Hotel, HotelAdmin) admin.site.register(Party, PartyAdmin) admin.site.register(Song, SongAdmin)
Add attending as column to Guest
Add attending as column to Guest
Python
mit
gboone/wedding.harmsboone.org,gboone/wedding.harmsboone.org
python
## Code Before: from django.contrib import admin from rsvp.models import Guest, Location, Table, Event, Hotel, Party, Song class AdminModel(admin.ModelAdmin): list_display = ['name'] class GuestAdmin(admin.ModelAdmin): list_display = ['last_name', 'first_name'] list_filter = ['last_name', 'first_name'] search_fields = ['last_name', 'first_name', ] save_on_top = True class LocationAdmin(AdminModel): pass class TableAdmin(AdminModel): pass class EventAdmin(AdminModel): pass class HotelAdmin(AdminModel): pass class PartyAdmin(admin.ModelAdmin): filter_horizontal = ('guests',) list_display = ['name', 'responded'] class SongAdmin(admin.ModelAdmin): list_display = ['title', 'artist', 'votes'] admin.site.register(Guest, GuestAdmin) admin.site.register(Location, LocationAdmin) admin.site.register(Table, TableAdmin) admin.site.register(Event, EventAdmin) admin.site.register(Hotel, HotelAdmin) admin.site.register(Party, PartyAdmin) admin.site.register(Song, SongAdmin) ## Instruction: Add attending as column to Guest ## Code After: from django.contrib import admin from rsvp.models import Guest, Location, Table, Event, Hotel, Party, Song class AdminModel(admin.ModelAdmin): list_display = ['name'] class GuestAdmin(admin.ModelAdmin): list_display = ['last_name', 'first_name', 'attending', ] list_filter = ['last_name', 'first_name'] search_fields = ['last_name', 'first_name', ] save_on_top = True class LocationAdmin(AdminModel): pass class TableAdmin(AdminModel): pass class EventAdmin(AdminModel): pass class HotelAdmin(AdminModel): pass class PartyAdmin(admin.ModelAdmin): filter_horizontal = ('guests',) list_display = ['name', 'responded'] class SongAdmin(admin.ModelAdmin): list_display = ['title', 'artist', 'votes'] admin.site.register(Guest, GuestAdmin) admin.site.register(Location, LocationAdmin) admin.site.register(Table, TableAdmin) admin.site.register(Event, EventAdmin) admin.site.register(Hotel, HotelAdmin) admin.site.register(Party, PartyAdmin) admin.site.register(Song, SongAdmin)
// ... existing code ... list_display = ['name'] class GuestAdmin(admin.ModelAdmin): list_display = ['last_name', 'first_name', 'attending', ] list_filter = ['last_name', 'first_name'] search_fields = ['last_name', 'first_name', ] save_on_top = True // ... rest of the code ...
a0f030cd03d28d97924a3277722d7a51cf3a3e92
cms/test_utils/project/extensionapp/models.py
cms/test_utils/project/extensionapp/models.py
from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favorite_users = models.ManyToManyField(User, blank=True, null=True) def copy_relations(self, other, language): for favorite_user in other.favorite_users.all(): favorite_user.pk = None favorite_user.mypageextension = self favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
Update extension app to include a M2M
Update extension app to include a M2M
Python
bsd-3-clause
kk9599/django-cms,jrclaramunt/django-cms,farhaadila/django-cms,FinalAngel/django-cms,leture/django-cms,yakky/django-cms,wuzhihui1123/django-cms,czpython/django-cms,jproffitt/django-cms,astagi/django-cms,DylannCordel/django-cms,evildmp/django-cms,jrclaramunt/django-cms,SachaMPS/django-cms,netzkolchose/django-cms,donce/django-cms,bittner/django-cms,jeffreylu9/django-cms,cyberintruder/django-cms,takeshineshiro/django-cms,Vegasvikk/django-cms,nostalgiaz/django-cms,kk9599/django-cms,rryan/django-cms,rscnt/django-cms,SmithsonianEnterprises/django-cms,jsma/django-cms,sephii/django-cms,selecsosi/django-cms,jsma/django-cms,SmithsonianEnterprises/django-cms,donce/django-cms,sznekol/django-cms,robmagee/django-cms,rsalmaso/django-cms,Livefyre/django-cms,divio/django-cms,owers19856/django-cms,isotoma/django-cms,intip/django-cms,qnub/django-cms,divio/django-cms,farhaadila/django-cms,iddqd1/django-cms,josjevv/django-cms,stefanfoulis/django-cms,farhaadila/django-cms,SofiaReis/django-cms,wuzhihui1123/django-cms,owers19856/django-cms,MagicSolutions/django-cms,jproffitt/django-cms,FinalAngel/django-cms,benzkji/django-cms,360youlun/django-cms,bittner/django-cms,netzkolchose/django-cms,jeffreylu9/django-cms,vstoykov/django-cms,stefanw/django-cms,jeffreylu9/django-cms,chkir/django-cms,nimbis/django-cms,vxsx/django-cms,selecsosi/django-cms,chkir/django-cms,qnub/django-cms,Jaccorot/django-cms,evildmp/django-cms,bittner/django-cms,wuzhihui1123/django-cms,iddqd1/django-cms,datakortet/django-cms,Vegasvikk/django-cms,benzkji/django-cms,wyg3958/django-cms,andyzsf/django-cms,MagicSolutions/django-cms,vstoykov/django-cms,intip/django-cms,intip/django-cms,memnonila/django-cms,takeshineshiro/django-cms,philippze/django-cms,vxsx/django-cms,jproffitt/django-cms,Livefyre/django-cms,SachaMPS/django-cms,stefanfoulis/django-cms,rryan/django-cms,AlexProfi/django-cms,petecummings/django-cms,vxsx/django-cms,rscnt/django-cms,dhorelik/django-cms,rsalmaso/django-cms,Vegasvikk/django-cms,liuyisiyisi/django-cms,youprofit/django-cms,wyg3958/django-cms,FinalAngel/django-cms,sznekol/django-cms,360youlun/django-cms,jrief/django-cms,andyzsf/django-cms,stefanw/django-cms,nostalgiaz/django-cms,selecsosi/django-cms,jsma/django-cms,donce/django-cms,360youlun/django-cms,rryan/django-cms,benzkji/django-cms,petecummings/django-cms,memnonila/django-cms,DylannCordel/django-cms,intgr/django-cms,Jaccorot/django-cms,rscnt/django-cms,frnhr/django-cms,astagi/django-cms,rsalmaso/django-cms,irudayarajisawa/django-cms,andyzsf/django-cms,chmberl/django-cms,saintbird/django-cms,evildmp/django-cms,frnhr/django-cms,MagicSolutions/django-cms,evildmp/django-cms,mkoistinen/django-cms,liuyisiyisi/django-cms,datakortet/django-cms,jeffreylu9/django-cms,intip/django-cms,vad/django-cms,isotoma/django-cms,divio/django-cms,mkoistinen/django-cms,intgr/django-cms,stefanw/django-cms,AlexProfi/django-cms,rryan/django-cms,stefanfoulis/django-cms,chmberl/django-cms,dhorelik/django-cms,nimbis/django-cms,mkoistinen/django-cms,Livefyre/django-cms,jrclaramunt/django-cms,saintbird/django-cms,yakky/django-cms,datakortet/django-cms,irudayarajisawa/django-cms,vstoykov/django-cms,jsma/django-cms,irudayarajisawa/django-cms,astagi/django-cms,FinalAngel/django-cms,wyg3958/django-cms,sephii/django-cms,kk9599/django-cms,saintbird/django-cms,divio/django-cms,chmberl/django-cms,josjevv/django-cms,intgr/django-cms,jrief/django-cms,wuzhihui1123/django-cms,webu/django-cms,frnhr/django-cms,sznekol/django-cms,SofiaReis/django-cms,philippze/django-cms,czpython/django-cms,frnhr/django-cms,vxsx/django-cms,cyberintruder/django-cms,cyberintruder/django-cms,rsalmaso/django-cms,timgraham/django-cms,yakky/django-cms,isotoma/django-cms,benzkji/django-cms,Livefyre/django-cms,nimbis/django-cms,AlexProfi/django-cms,robmagee/django-cms,jrief/django-cms,ScholzVolkmer/django-cms,robmagee/django-cms,webu/django-cms,netzkolchose/django-cms,intgr/django-cms,keimlink/django-cms,memnonila/django-cms,timgraham/django-cms,yakky/django-cms,datakortet/django-cms,mkoistinen/django-cms,philippze/django-cms,youprofit/django-cms,SmithsonianEnterprises/django-cms,SofiaReis/django-cms,chkir/django-cms,vad/django-cms,ScholzVolkmer/django-cms,takeshineshiro/django-cms,DylannCordel/django-cms,jrief/django-cms,liuyisiyisi/django-cms,stefanfoulis/django-cms,czpython/django-cms,owers19856/django-cms,petecummings/django-cms,keimlink/django-cms,nimbis/django-cms,ScholzVolkmer/django-cms,selecsosi/django-cms,leture/django-cms,jproffitt/django-cms,iddqd1/django-cms,keimlink/django-cms,qnub/django-cms,timgraham/django-cms,andyzsf/django-cms,SachaMPS/django-cms,czpython/django-cms,vad/django-cms,dhorelik/django-cms,vad/django-cms,youprofit/django-cms,netzkolchose/django-cms,Jaccorot/django-cms,sephii/django-cms,bittner/django-cms,isotoma/django-cms,josjevv/django-cms,nostalgiaz/django-cms,webu/django-cms,stefanw/django-cms,nostalgiaz/django-cms,sephii/django-cms,leture/django-cms
python
## Code Before: from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension) ## Instruction: Update extension app to include a M2M ## Code After: from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favorite_users = models.ManyToManyField(User, blank=True, null=True) def copy_relations(self, other, language): for favorite_user in other.favorite_users.all(): favorite_user.pk = None favorite_user.mypageextension = self favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
... from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favorite_users = models.ManyToManyField(User, blank=True, null=True) def copy_relations(self, other, language): for favorite_user in other.favorite_users.all(): favorite_user.pk = None favorite_user.mypageextension = self favorite_user.save() extension_pool.register(MyPageExtension) ... class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension) ...
255a93e2e075a8db914e4736cb79fbdb58b41a24
file_transfer/baltrad_to_s3.py
file_transfer/baltrad_to_s3.py
import sys from creds import URL, LOGIN, PASSWORD import datamover as dm def main(): """Run data transfer from Baltrad to S3""" # ------------------ # DATA TRANSFER # ------------------ # Setup the connection of the Baltrad and S3 btos = dm.BaltradToS3(URL, LOGIN, PASSWORD, "lw-enram") # Execute the transfer btos.transfer(name_match="_vp_", overwrite=False, limit=None) btos.report(reset_file=False, transfertype="Baltrad to S3") # ------------------ # UPDATE COVERAGE # ------------------ # Connect to S3 client s3client = dm.S3EnramHandler("lw-enram") # Rerun file list overview to extract the current coverage coverage_count = s3client.count_enram_coverage(level='day') with open("coverage.csv", 'w') as outfile: dm.coverage_to_csv(outfile, coverage_count) s3client.upload_file("coverage.csv", "coverage.csv") # ---------------------------- # UPDATE ZIP FILE AVAILABILITY # ---------------------------- # Rerun ZIP handling of S3 for the transferred files, given by report s3client.create_zip_version(btos.transferred) if __name__ == "__main__": sys.exit(main())
import sys from creds import URL, LOGIN, PASSWORD import datamover as dm def main(): """Run data transfer from Baltrad to S3""" # ------------------ # DATA TRANSFER # ------------------ # Setup the connection of the Baltrad and S3 btos = dm.BaltradToS3(URL, LOGIN, PASSWORD, "lw-enram") # Execute the transfer btos.transfer(name_match="_vp_", overwrite=False, limit=None) btos.report(reset_file=False, transfertype="Baltrad to S3") # --------------------------------------------- # UPDATE COVERAGE AND MOST RECENT FILE DATETIME # --------------------------------------------- # Connect to S3 client s3client = dm.S3EnramHandler("lw-enram") # Rerun file list overview to extract the current coverage coverage_count, most_recent = s3client.count_enram_coverage(level='day') # Save the coverage information on S3 with open("coverage.csv", 'w') as outfile: dm.coverage_to_csv(outfile, coverage_count) s3client.upload_file("coverage.csv", "coverage.csv") # Save the last provided radar file information on S3 with open("radars.csv", 'w') as outfile: dm.most_recent_to_csv(outfile, most_recent) s3client.upload_file("radars.csv", "radars.csv") # ---------------------------- # UPDATE ZIP FILE AVAILABILITY # ---------------------------- # Rerun ZIP handling of S3 for the transferred files, given by report s3client.create_zip_version(btos.transferred) if __name__ == "__main__": sys.exit(main())
Extend data pipeline from baltrad
Extend data pipeline from baltrad
Python
mit
enram/data-repository,enram/data-repository,enram/data-repository,enram/data-repository,enram/infrastructure,enram/infrastructure
python
## Code Before: import sys from creds import URL, LOGIN, PASSWORD import datamover as dm def main(): """Run data transfer from Baltrad to S3""" # ------------------ # DATA TRANSFER # ------------------ # Setup the connection of the Baltrad and S3 btos = dm.BaltradToS3(URL, LOGIN, PASSWORD, "lw-enram") # Execute the transfer btos.transfer(name_match="_vp_", overwrite=False, limit=None) btos.report(reset_file=False, transfertype="Baltrad to S3") # ------------------ # UPDATE COVERAGE # ------------------ # Connect to S3 client s3client = dm.S3EnramHandler("lw-enram") # Rerun file list overview to extract the current coverage coverage_count = s3client.count_enram_coverage(level='day') with open("coverage.csv", 'w') as outfile: dm.coverage_to_csv(outfile, coverage_count) s3client.upload_file("coverage.csv", "coverage.csv") # ---------------------------- # UPDATE ZIP FILE AVAILABILITY # ---------------------------- # Rerun ZIP handling of S3 for the transferred files, given by report s3client.create_zip_version(btos.transferred) if __name__ == "__main__": sys.exit(main()) ## Instruction: Extend data pipeline from baltrad ## Code After: import sys from creds import URL, LOGIN, PASSWORD import datamover as dm def main(): """Run data transfer from Baltrad to S3""" # ------------------ # DATA TRANSFER # ------------------ # Setup the connection of the Baltrad and S3 btos = dm.BaltradToS3(URL, LOGIN, PASSWORD, "lw-enram") # Execute the transfer btos.transfer(name_match="_vp_", overwrite=False, limit=None) btos.report(reset_file=False, transfertype="Baltrad to S3") # --------------------------------------------- # UPDATE COVERAGE AND MOST RECENT FILE DATETIME # --------------------------------------------- # Connect to S3 client s3client = dm.S3EnramHandler("lw-enram") # Rerun file list overview to extract the current coverage coverage_count, most_recent = s3client.count_enram_coverage(level='day') # Save the coverage information on S3 with open("coverage.csv", 'w') as outfile: dm.coverage_to_csv(outfile, coverage_count) s3client.upload_file("coverage.csv", "coverage.csv") # Save the last provided radar file information on S3 with open("radars.csv", 'w') as outfile: dm.most_recent_to_csv(outfile, most_recent) s3client.upload_file("radars.csv", "radars.csv") # ---------------------------- # UPDATE ZIP FILE AVAILABILITY # ---------------------------- # Rerun ZIP handling of S3 for the transferred files, given by report s3client.create_zip_version(btos.transferred) if __name__ == "__main__": sys.exit(main())
// ... existing code ... btos.transfer(name_match="_vp_", overwrite=False, limit=None) btos.report(reset_file=False, transfertype="Baltrad to S3") # --------------------------------------------- # UPDATE COVERAGE AND MOST RECENT FILE DATETIME # --------------------------------------------- # Connect to S3 client s3client = dm.S3EnramHandler("lw-enram") # Rerun file list overview to extract the current coverage coverage_count, most_recent = s3client.count_enram_coverage(level='day') # Save the coverage information on S3 with open("coverage.csv", 'w') as outfile: dm.coverage_to_csv(outfile, coverage_count) s3client.upload_file("coverage.csv", "coverage.csv") # Save the last provided radar file information on S3 with open("radars.csv", 'w') as outfile: dm.most_recent_to_csv(outfile, most_recent) s3client.upload_file("radars.csv", "radars.csv") # ---------------------------- # UPDATE ZIP FILE AVAILABILITY // ... rest of the code ...
52f58b3594ce7c8f687b45d71c7528fbb905f35e
src/data_test/java/info/u_team/u_team_test/data/provider/TestBlockTagsProvider.java
src/data_test/java/info/u_team/u_team_test/data/provider/TestBlockTagsProvider.java
package info.u_team.u_team_test.data.provider; import info.u_team.u_team_core.data.*; public class TestBlockTagsProvider extends CommonBlockTagsProvider { public TestBlockTagsProvider(GenerationData data) { super(data); } @Override protected void registerTags() { } }
package info.u_team.u_team_test.data.provider; import static info.u_team.u_team_test.init.TestTags.Blocks.*; import info.u_team.u_team_core.data.*; import net.minecraft.block.Blocks; import net.minecraft.tags.*; public class TestBlockTagsProvider extends CommonBlockTagsProvider { public TestBlockTagsProvider(GenerationData data) { super(data); } @Override protected void registerTags() { getBuilder(TEST_TAG_1).add(Blocks.ACACIA_BUTTON, Blocks.ACACIA_DOOR); getBuilder(TEST_TAG_2).addTag(TEST_TAG_1).add(Blocks.ACACIA_LOG); getBuilder(TEST_TAG_1).add(Blocks.BIRCH_LEAVES); getBuilder(TEST_TAG_1).addTag(BlockTags.BEDS); } }
Add some stuff to the block tags provider
Add some stuff to the block tags provider
Java
apache-2.0
MC-U-Team/U-Team-Core,MC-U-Team/U-Team-Core
java
## Code Before: package info.u_team.u_team_test.data.provider; import info.u_team.u_team_core.data.*; public class TestBlockTagsProvider extends CommonBlockTagsProvider { public TestBlockTagsProvider(GenerationData data) { super(data); } @Override protected void registerTags() { } } ## Instruction: Add some stuff to the block tags provider ## Code After: package info.u_team.u_team_test.data.provider; import static info.u_team.u_team_test.init.TestTags.Blocks.*; import info.u_team.u_team_core.data.*; import net.minecraft.block.Blocks; import net.minecraft.tags.*; public class TestBlockTagsProvider extends CommonBlockTagsProvider { public TestBlockTagsProvider(GenerationData data) { super(data); } @Override protected void registerTags() { getBuilder(TEST_TAG_1).add(Blocks.ACACIA_BUTTON, Blocks.ACACIA_DOOR); getBuilder(TEST_TAG_2).addTag(TEST_TAG_1).add(Blocks.ACACIA_LOG); getBuilder(TEST_TAG_1).add(Blocks.BIRCH_LEAVES); getBuilder(TEST_TAG_1).addTag(BlockTags.BEDS); } }
# ... existing code ... package info.u_team.u_team_test.data.provider; import static info.u_team.u_team_test.init.TestTags.Blocks.*; import info.u_team.u_team_core.data.*; import net.minecraft.block.Blocks; import net.minecraft.tags.*; public class TestBlockTagsProvider extends CommonBlockTagsProvider { # ... modified code ... @Override protected void registerTags() { getBuilder(TEST_TAG_1).add(Blocks.ACACIA_BUTTON, Blocks.ACACIA_DOOR); getBuilder(TEST_TAG_2).addTag(TEST_TAG_1).add(Blocks.ACACIA_LOG); getBuilder(TEST_TAG_1).add(Blocks.BIRCH_LEAVES); getBuilder(TEST_TAG_1).addTag(BlockTags.BEDS); } } # ... rest of the code ...
0ef96b3c2dbf65fd92dd700e15689180af74d438
firmware/WidgetTerminal.h
firmware/WidgetTerminal.h
/** * @file WidgetTerminal.h * @author Volodymyr Shymanskyy * @license This project is released under the MIT License (MIT) * @copyright Copyright (c) 2015 Volodymyr Shymanskyy * @date Jan 2015 * @brief */ #ifndef WidgetTerminal_h #define WidgetTerminal_h #include <Print.h> #include <Blynk/BlynkApi.h> class WidgetTerminal : public Print { public: WidgetTerminal(int vPin) : mPin(vPin), mOutQty(0) {} virtual size_t write(uint8_t byte) { mOutBuf[mOutQty++] = byte; if (mOutQty >= sizeof(mOutBuf)) { flush(); } return 1; } void flush() { if (mOutQty) { Blynk.virtualWrite(mPin, mOutBuf, mOutQty); mOutQty = 0; } } using Print::write; private: uint8_t mPin; uint8_t mOutBuf[32]; uint8_t mOutQty; }; #endif
/** * @file WidgetTerminal.h * @author Volodymyr Shymanskyy * @license This project is released under the MIT License (MIT) * @copyright Copyright (c) 2015 Volodymyr Shymanskyy * @date Jan 2015 * @brief */ #ifndef WidgetTerminal_h #define WidgetTerminal_h #include <Print.h> #if !defined(SPARK) // On Spark this is auto-included #include <Blynk/BlynkApi.h> #endif class WidgetTerminal : public Print { public: WidgetTerminal(int vPin) : mPin(vPin), mOutQty(0) {} virtual size_t write(uint8_t byte) { mOutBuf[mOutQty++] = byte; if (mOutQty >= sizeof(mOutBuf)) { flush(); } return 1; } void flush() { if (mOutQty) { Blynk.virtualWrite(mPin, mOutBuf, mOutQty); mOutQty = 0; } } using Print::write; private: uint8_t mPin; uint8_t mOutBuf[32]; uint8_t mOutQty; }; #endif
Fix terminal widget on Spark Core
Fix terminal widget on Spark Core
C
mit
yaneexy/blynk-library-spark,vshymanskyy/blynk-library-spark,domo-connect/blynk-library-spark,vshymanskyy/blynk-library-spark,chieftuscan/blynk-library-spark,chieftuscan/blynk-library-spark,yaneexy/blynk-library-spark,domo-connect/blynk-library-spark
c
## Code Before: /** * @file WidgetTerminal.h * @author Volodymyr Shymanskyy * @license This project is released under the MIT License (MIT) * @copyright Copyright (c) 2015 Volodymyr Shymanskyy * @date Jan 2015 * @brief */ #ifndef WidgetTerminal_h #define WidgetTerminal_h #include <Print.h> #include <Blynk/BlynkApi.h> class WidgetTerminal : public Print { public: WidgetTerminal(int vPin) : mPin(vPin), mOutQty(0) {} virtual size_t write(uint8_t byte) { mOutBuf[mOutQty++] = byte; if (mOutQty >= sizeof(mOutBuf)) { flush(); } return 1; } void flush() { if (mOutQty) { Blynk.virtualWrite(mPin, mOutBuf, mOutQty); mOutQty = 0; } } using Print::write; private: uint8_t mPin; uint8_t mOutBuf[32]; uint8_t mOutQty; }; #endif ## Instruction: Fix terminal widget on Spark Core ## Code After: /** * @file WidgetTerminal.h * @author Volodymyr Shymanskyy * @license This project is released under the MIT License (MIT) * @copyright Copyright (c) 2015 Volodymyr Shymanskyy * @date Jan 2015 * @brief */ #ifndef WidgetTerminal_h #define WidgetTerminal_h #include <Print.h> #if !defined(SPARK) // On Spark this is auto-included #include <Blynk/BlynkApi.h> #endif class WidgetTerminal : public Print { public: WidgetTerminal(int vPin) : mPin(vPin), mOutQty(0) {} virtual size_t write(uint8_t byte) { mOutBuf[mOutQty++] = byte; if (mOutQty >= sizeof(mOutBuf)) { flush(); } return 1; } void flush() { if (mOutQty) { Blynk.virtualWrite(mPin, mOutBuf, mOutQty); mOutQty = 0; } } using Print::write; private: uint8_t mPin; uint8_t mOutBuf[32]; uint8_t mOutQty; }; #endif
... #define WidgetTerminal_h #include <Print.h> #if !defined(SPARK) // On Spark this is auto-included #include <Blynk/BlynkApi.h> #endif class WidgetTerminal : public Print ...
5da7189f195d0daf9595c61f05156c85031ba0c5
tests/testapp/tests/test_scheduling.py
tests/testapp/tests/test_scheduling.py
from django.test import TestCase from testapp.tests import factories class SchedulingTestCase(TestCase): def test_scheduling(self): for i in range(20): factories.AssignmentFactory.create() factories.WaitListFactory.create() admin = factories.UserFactory.create(is_staff=True, is_superuser=True) self.client.login(username=admin.username, password='test') self.client.get('/zivinetz/admin/scheduling/')
from django.test import TestCase from zivinetz.models import Assignment from testapp.tests import factories class SchedulingTestCase(TestCase): def test_scheduling(self): for i in range(20): factories.AssignmentFactory.create() factories.WaitListFactory.create() admin = factories.UserFactory.create(is_staff=True, is_superuser=True) self.client.login(username=admin.username, password='test') self.assertEqual( self.client.get('/zivinetz/admin/scheduling/').status_code, 200) Assignment.objects.all().delete() self.assertEqual( self.client.get('/zivinetz/admin/scheduling/').status_code, 200)
Test that scheduling does not crash
Test that scheduling does not crash
Python
mit
matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz
python
## Code Before: from django.test import TestCase from testapp.tests import factories class SchedulingTestCase(TestCase): def test_scheduling(self): for i in range(20): factories.AssignmentFactory.create() factories.WaitListFactory.create() admin = factories.UserFactory.create(is_staff=True, is_superuser=True) self.client.login(username=admin.username, password='test') self.client.get('/zivinetz/admin/scheduling/') ## Instruction: Test that scheduling does not crash ## Code After: from django.test import TestCase from zivinetz.models import Assignment from testapp.tests import factories class SchedulingTestCase(TestCase): def test_scheduling(self): for i in range(20): factories.AssignmentFactory.create() factories.WaitListFactory.create() admin = factories.UserFactory.create(is_staff=True, is_superuser=True) self.client.login(username=admin.username, password='test') self.assertEqual( self.client.get('/zivinetz/admin/scheduling/').status_code, 200) Assignment.objects.all().delete() self.assertEqual( self.client.get('/zivinetz/admin/scheduling/').status_code, 200)
# ... existing code ... from django.test import TestCase from zivinetz.models import Assignment from testapp.tests import factories # ... modified code ... admin = factories.UserFactory.create(is_staff=True, is_superuser=True) self.client.login(username=admin.username, password='test') self.assertEqual( self.client.get('/zivinetz/admin/scheduling/').status_code, 200) Assignment.objects.all().delete() self.assertEqual( self.client.get('/zivinetz/admin/scheduling/').status_code, 200) # ... rest of the code ...
7c1dd8a6a547cb6183f66d73b27868a75451eb54
dsh.py
dsh.py
__author__ = 'Michael Montero <[email protected]>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] # ----- Private Classes ------------------------------------------------------- class UnitTestNullDSH(object): ''' Supports unit test cases that do not perform transactional data store operations but attempt to close or rollback transactions. ''' def close(self): pass def rollback(self, ignore_exceptions=True): pass # ----- Instructions ---------------------------------------------------------- class __DSH(object): def __init__(self): self.__provider = None self.__unit_test_null_dsh = UnitTestNullDSH() def __call__(self): if self.__provider is None: if tinyAPI.env_unit_test() is True: return self.__unit_test_null_dsh else: raise RuntimeError('data store handle has not been selected') return self.__provider def select_db(self, connection, db, persistent=True): self.__provider = \ DataStoreProvider() \ .get_data_store_handle( connection, db, tinyAPI.env_cli() is not True and persistent ) return self dsh = __DSH()
__author__ = 'Michael Montero <[email protected]>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] # ----- Private Classes ------------------------------------------------------- class NoOpDSH(object): ''' The use of this object in __DSH is ambiguous. It's unclear why a call to a commit or rollback command would be executed without a connection ever being established. ''' def close(self): pass def commit(self, ignore_exceptions=True): pass def rollback(self, ignore_exceptions=True): pass # ----- Instructions ---------------------------------------------------------- class __DSH(object): def __init__(self): self.__provider = None def __call__(self): return self.__provider if self.__provider is not None else NoOpDSH() def select_db(self, connection, db, persistent=True): self.__provider = \ DataStoreProvider() \ .get_data_store_handle( connection, db, tinyAPI.env_cli() is not True and persistent ) return self dsh = __DSH()
Revert "Revert "Testing NoOpDSH() when database commands are executed without a connection being opened.""
Revert "Revert "Testing NoOpDSH() when database commands are executed without a connection being opened."" This reverts commit 9c428fbfb69c93ef3da935d0d2ab098fbeb1c317.
Python
mit
mcmontero/tinyAPI,mcmontero/tinyAPI
python
## Code Before: __author__ = 'Michael Montero <[email protected]>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] # ----- Private Classes ------------------------------------------------------- class UnitTestNullDSH(object): ''' Supports unit test cases that do not perform transactional data store operations but attempt to close or rollback transactions. ''' def close(self): pass def rollback(self, ignore_exceptions=True): pass # ----- Instructions ---------------------------------------------------------- class __DSH(object): def __init__(self): self.__provider = None self.__unit_test_null_dsh = UnitTestNullDSH() def __call__(self): if self.__provider is None: if tinyAPI.env_unit_test() is True: return self.__unit_test_null_dsh else: raise RuntimeError('data store handle has not been selected') return self.__provider def select_db(self, connection, db, persistent=True): self.__provider = \ DataStoreProvider() \ .get_data_store_handle( connection, db, tinyAPI.env_cli() is not True and persistent ) return self dsh = __DSH() ## Instruction: Revert "Revert "Testing NoOpDSH() when database commands are executed without a connection being opened."" This reverts commit 9c428fbfb69c93ef3da935d0d2ab098fbeb1c317. ## Code After: __author__ = 'Michael Montero <[email protected]>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] # ----- Private Classes ------------------------------------------------------- class NoOpDSH(object): ''' The use of this object in __DSH is ambiguous. It's unclear why a call to a commit or rollback command would be executed without a connection ever being established. ''' def close(self): pass def commit(self, ignore_exceptions=True): pass def rollback(self, ignore_exceptions=True): pass # ----- Instructions ---------------------------------------------------------- class __DSH(object): def __init__(self): self.__provider = None def __call__(self): return self.__provider if self.__provider is not None else NoOpDSH() def select_db(self, connection, db, persistent=True): self.__provider = \ DataStoreProvider() \ .get_data_store_handle( connection, db, tinyAPI.env_cli() is not True and persistent ) return self dsh = __DSH()
// ... existing code ... # ----- Private Classes ------------------------------------------------------- class NoOpDSH(object): ''' The use of this object in __DSH is ambiguous. It's unclear why a call to a commit or rollback command would be executed without a connection ever being established. ''' def close(self): pass def commit(self, ignore_exceptions=True): pass // ... modified code ... def __init__(self): self.__provider = None def __call__(self): return self.__provider if self.__provider is not None else NoOpDSH() def select_db(self, connection, db, persistent=True): // ... rest of the code ...
6823b063444dc6853ed524d2aad913fc0ba6c965
towel/templatetags/towel_batch_tags.py
towel/templatetags/towel_batch_tags.py
from django import template register = template.Library() @register.simple_tag def batch_checkbox(form, id): """ Checkbox which allows selecting objects for batch processing:: {% for object in object_list %} {% batch_checkbox batch_form object.id %} {{ object }} etc... {% endfor %} """ cb = u'<input type="checkbox" name="batch_%s" value="%s" class="batch" %s/>' if id in form.ids: return cb % (id, id, 'checked="checked" ') return cb % (id, id, '')
from django import template register = template.Library() @register.simple_tag def batch_checkbox(form, id): """ Checkbox which allows selecting objects for batch processing:: {% for object in object_list %} {% batch_checkbox batch_form object.id %} {{ object }} etc... {% endfor %} """ cb = u'<input type="checkbox" name="batch_%s" value="%s" class="batch" %s/>' if id in getattr(form, 'ids', []): return cb % (id, id, 'checked="checked" ') return cb % (id, id, '')
Make batch_checkbox a bit more resilient against problems with context variables
Make batch_checkbox a bit more resilient against problems with context variables
Python
bsd-3-clause
matthiask/towel,matthiask/towel,matthiask/towel,matthiask/towel
python
## Code Before: from django import template register = template.Library() @register.simple_tag def batch_checkbox(form, id): """ Checkbox which allows selecting objects for batch processing:: {% for object in object_list %} {% batch_checkbox batch_form object.id %} {{ object }} etc... {% endfor %} """ cb = u'<input type="checkbox" name="batch_%s" value="%s" class="batch" %s/>' if id in form.ids: return cb % (id, id, 'checked="checked" ') return cb % (id, id, '') ## Instruction: Make batch_checkbox a bit more resilient against problems with context variables ## Code After: from django import template register = template.Library() @register.simple_tag def batch_checkbox(form, id): """ Checkbox which allows selecting objects for batch processing:: {% for object in object_list %} {% batch_checkbox batch_form object.id %} {{ object }} etc... {% endfor %} """ cb = u'<input type="checkbox" name="batch_%s" value="%s" class="batch" %s/>' if id in getattr(form, 'ids', []): return cb % (id, id, 'checked="checked" ') return cb % (id, id, '')
# ... existing code ... cb = u'<input type="checkbox" name="batch_%s" value="%s" class="batch" %s/>' if id in getattr(form, 'ids', []): return cb % (id, id, 'checked="checked" ') return cb % (id, id, '') # ... rest of the code ...
143c0188566ac07ac3fdb9e6dfca8863cc169bbb
ts3observer/observer.py
ts3observer/observer.py
''' Created on Nov 9, 2014 @author: fechnert ''' import yaml import logging import features class Configuration(dict): ''' Read and provide the yaml config ''' def __init__(self, path): ''' Initialize the file ''' with open(path, 'r') as f: self.update(yaml.load(f)) class Supervisor(object): ''' Guide the different features to do their work ''' def __init__(self): ''' Initialize the Config ''' self.config = Configuration('config.yml') def execute(self): for feature in self._import_features().values(): try: feature.run() except NotImplementedError: logging.warn('Can\'t run Feature \'{}\''.format(feature.__class__.__name__)) def _get_enabled_features(self): ''' Get all features which are enabled in config ''' features = [] for feature in self.config['features']: if self.config['features'][feature]['enable']: features.append(feature) return features def _import_features(self): ''' Import only the needed features ''' feature_objects = {} for feature in self._get_enabled_features(): feature_objects.update({ feature: getattr(features, feature)(self.config['features'][feature]) }) return feature_objects
''' Created on Nov 9, 2014 @author: fechnert ''' import yaml import logging import features class Configuration(dict): ''' Read and provide the yaml config ''' def __init__(self, path): ''' Initialize the file ''' with open(path, 'r') as f: self.update(yaml.load(f)) class Supervisor(object): ''' Guide the different features to do their work ''' def __init__(self): ''' Initialize the Config ''' self.config = Configuration('config.yml') def execute(self): for feature in self._import_features().values(): try: feature.run() except NotImplementedError: logging.warn('Can\'t run Feature \'{}\''.format(feature.__class__.__name__)) def _get_enabled_features(self): ''' Get all features which are enabled in config ''' features = [] for feature in self.config['features']: if self.config['features'][feature]['enable']: features.append(feature) return features def _import_features(self): ''' Import only the needed features ''' feature_objects = {} for feature in self._get_enabled_features(): feature_objects.update({ feature: getattr(features, feature)(self.config['features'][feature]) }) return feature_objects class Client(object): ''' Represents the client ''' def __init__(self, **kwargs): ''' Fill the object dynamically with client attributes got from telnet ''' for key, value in kwargs.items(): setattr(self, key, value) class Channel(object): ''' Represents the Channel ''' def __init__(self, **kwargs): ''' Fill the object dynamically with channel attributes got from telnet ''' for key, value in kwargs.items(): setattr(self, key, value)
Add client and channel models
Add client and channel models
Python
mit
HWDexperte/ts3observer
python
## Code Before: ''' Created on Nov 9, 2014 @author: fechnert ''' import yaml import logging import features class Configuration(dict): ''' Read and provide the yaml config ''' def __init__(self, path): ''' Initialize the file ''' with open(path, 'r') as f: self.update(yaml.load(f)) class Supervisor(object): ''' Guide the different features to do their work ''' def __init__(self): ''' Initialize the Config ''' self.config = Configuration('config.yml') def execute(self): for feature in self._import_features().values(): try: feature.run() except NotImplementedError: logging.warn('Can\'t run Feature \'{}\''.format(feature.__class__.__name__)) def _get_enabled_features(self): ''' Get all features which are enabled in config ''' features = [] for feature in self.config['features']: if self.config['features'][feature]['enable']: features.append(feature) return features def _import_features(self): ''' Import only the needed features ''' feature_objects = {} for feature in self._get_enabled_features(): feature_objects.update({ feature: getattr(features, feature)(self.config['features'][feature]) }) return feature_objects ## Instruction: Add client and channel models ## Code After: ''' Created on Nov 9, 2014 @author: fechnert ''' import yaml import logging import features class Configuration(dict): ''' Read and provide the yaml config ''' def __init__(self, path): ''' Initialize the file ''' with open(path, 'r') as f: self.update(yaml.load(f)) class Supervisor(object): ''' Guide the different features to do their work ''' def __init__(self): ''' Initialize the Config ''' self.config = Configuration('config.yml') def execute(self): for feature in self._import_features().values(): try: feature.run() except NotImplementedError: logging.warn('Can\'t run Feature \'{}\''.format(feature.__class__.__name__)) def _get_enabled_features(self): ''' Get all features which are enabled in config ''' features = [] for feature in self.config['features']: if self.config['features'][feature]['enable']: features.append(feature) return features def _import_features(self): ''' Import only the needed features ''' feature_objects = {} for feature in self._get_enabled_features(): feature_objects.update({ feature: getattr(features, feature)(self.config['features'][feature]) }) return feature_objects class Client(object): ''' Represents the client ''' def __init__(self, **kwargs): ''' Fill the object dynamically with client attributes got from telnet ''' for key, value in kwargs.items(): setattr(self, key, value) class Channel(object): ''' Represents the Channel ''' def __init__(self, **kwargs): ''' Fill the object dynamically with channel attributes got from telnet ''' for key, value in kwargs.items(): setattr(self, key, value)
# ... existing code ... feature: getattr(features, feature)(self.config['features'][feature]) }) return feature_objects class Client(object): ''' Represents the client ''' def __init__(self, **kwargs): ''' Fill the object dynamically with client attributes got from telnet ''' for key, value in kwargs.items(): setattr(self, key, value) class Channel(object): ''' Represents the Channel ''' def __init__(self, **kwargs): ''' Fill the object dynamically with channel attributes got from telnet ''' for key, value in kwargs.items(): setattr(self, key, value) # ... rest of the code ...
4b41555727178109cba3c44ee1d82214a79c2ee2
examples/notifications-style/src/main/java/com/deltadna/android/sdk/notifications/example/StyledNotificationFactory.java
examples/notifications-style/src/main/java/com/deltadna/android/sdk/notifications/example/StyledNotificationFactory.java
/* * Copyright (c) 2017 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deltadna.android.sdk.notifications.example; import android.content.Context; import androidx.core.app.NotificationCompat; import com.deltadna.android.sdk.notifications.NotificationFactory; import com.deltadna.android.sdk.notifications.PushMessage; /** * Example of a {@link NotificationFactory} which changes the look of the * notification after a push message is received. */ public class StyledNotificationFactory extends NotificationFactory { public StyledNotificationFactory(Context context) { super(context); } @Override public NotificationCompat.Builder configure( NotificationCompat.Builder builder, PushMessage message){ return super.configure(builder, message); } }
/* * Copyright (c) 2017 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deltadna.android.sdk.notifications.example; import android.content.Context; import androidx.core.app.NotificationCompat; import com.deltadna.android.sdk.notifications.NotificationFactory; import com.deltadna.android.sdk.notifications.PushMessage; /** * Example of a {@link NotificationFactory} which changes the look of the * notification after a push message is received. */ public class StyledNotificationFactory extends NotificationFactory { public StyledNotificationFactory(Context context) { super(context); } @Override public NotificationCompat.Builder configure( Context context, PushMessage message){ return super.configure(context, message); } }
Update the example notifications app
DDSDK: Update the example notifications app
Java
apache-2.0
deltaDNA/android-sdk,deltaDNA/android-sdk,deltaDNA/android-sdk
java
## Code Before: /* * Copyright (c) 2017 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deltadna.android.sdk.notifications.example; import android.content.Context; import androidx.core.app.NotificationCompat; import com.deltadna.android.sdk.notifications.NotificationFactory; import com.deltadna.android.sdk.notifications.PushMessage; /** * Example of a {@link NotificationFactory} which changes the look of the * notification after a push message is received. */ public class StyledNotificationFactory extends NotificationFactory { public StyledNotificationFactory(Context context) { super(context); } @Override public NotificationCompat.Builder configure( NotificationCompat.Builder builder, PushMessage message){ return super.configure(builder, message); } } ## Instruction: DDSDK: Update the example notifications app ## Code After: /* * Copyright (c) 2017 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deltadna.android.sdk.notifications.example; import android.content.Context; import androidx.core.app.NotificationCompat; import com.deltadna.android.sdk.notifications.NotificationFactory; import com.deltadna.android.sdk.notifications.PushMessage; /** * Example of a {@link NotificationFactory} which changes the look of the * notification after a push message is received. */ public class StyledNotificationFactory extends NotificationFactory { public StyledNotificationFactory(Context context) { super(context); } @Override public NotificationCompat.Builder configure( Context context, PushMessage message){ return super.configure(context, message); } }
... @Override public NotificationCompat.Builder configure( Context context, PushMessage message){ return super.configure(context, message); } } ...
630ba21f3b08dcd2685297b057cbee4b6abee6f7
us_ignite/sections/models.py
us_ignite/sections/models.py
from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField(upload_to="sponsor") order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name
from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField( upload_to="sponsor", help_text='This image is not post processed. ' 'Please make sure it has the right design specs.') order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name
Add help text describing the image field functionality.
Add help text describing the image field functionality.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
python
## Code Before: from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField(upload_to="sponsor") order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name ## Instruction: Add help text describing the image field functionality. ## Code After: from django.db import models class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField( upload_to="sponsor", help_text='This image is not post processed. ' 'Please make sure it has the right design specs.') order = models.IntegerField(default=0) class Meta: ordering = ('order', ) def __unicode__(self): return self.name
... class Sponsor(models.Model): name = models.CharField(max_length=255) website = models.URLField(max_length=500) image = models.ImageField( upload_to="sponsor", help_text='This image is not post processed. ' 'Please make sure it has the right design specs.') order = models.IntegerField(default=0) class Meta: ...