function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def __init__(
self, plotly_name="tickvals", parent_name="sunburst.marker.colorbar", **kwargs | plotly/python-api | [
13052,
2308,
13052,
1319,
1385013188
] |
def __init__(self, breakingCapacity=0.0, ProtectionEquipments=None, RecloseSequences=None, *args, **kw_args):
"""Initialises a new 'ProtectedSwitch' instance.
@param breakingCapacity: The maximum fault current a breaking device can break safely under prescribed conditions of use.
@param ProtectionEquipments: Protection equipments that operate this ProtectedSwitch.
@param RecloseSequences: A breaker may have zero or more automatic reclosures after a trip occurs.
"""
#: The maximum fault current a breaking device can break safely under prescribed conditions of use.
self.breakingCapacity = breakingCapacity
self._ProtectionEquipments = []
self.ProtectionEquipments = [] if ProtectionEquipments is None else ProtectionEquipments
self._RecloseSequences = []
self.RecloseSequences = [] if RecloseSequences is None else RecloseSequences
super(ProtectedSwitch, self).__init__(*args, **kw_args) | rwl/PyCIM | [
68,
33,
68,
7,
1238978196
] |
def getProtectionEquipments(self):
"""Protection equipments that operate this ProtectedSwitch.
"""
return self._ProtectionEquipments | rwl/PyCIM | [
68,
33,
68,
7,
1238978196
] |
def addProtectionEquipments(self, *ProtectionEquipments):
for obj in ProtectionEquipments:
if self not in obj._ProtectedSwitches:
obj._ProtectedSwitches.append(self)
self._ProtectionEquipments.append(obj) | rwl/PyCIM | [
68,
33,
68,
7,
1238978196
] |
def getRecloseSequences(self):
"""A breaker may have zero or more automatic reclosures after a trip occurs.
"""
return self._RecloseSequences | rwl/PyCIM | [
68,
33,
68,
7,
1238978196
] |
def addRecloseSequences(self, *RecloseSequences):
for obj in RecloseSequences:
obj.ProtectedSwitch = self | rwl/PyCIM | [
68,
33,
68,
7,
1238978196
] |
def test_equal(self):
self.assertEqual(KeySignature(name='C major'),
KeySignature(name='C major'))
self.assertNotEqual(KeySignature(name='C major'),
KeySignature(name='G major')) | odahoda/noisicaa | [
10,
2,
10,
2,
1448313403
] |
def returnToQueriersLocationWithReply( querier, reply ):
"""
@summary : Changes location back to the querier + returns the
reply of the query to the querier. | khosrow/metpx | [
1,
1,
1,
1,
1446661693
] |
def getQuerierLocation( form ):
"""
@param form : Form with whom this programm was called. | khosrow/metpx | [
1,
1,
1,
1,
1446661693
] |
def handlePlotRequest( form, language ):
"""
@param form: form wich contains
the parameters to use
for the query. | khosrow/metpx | [
1,
1,
1,
1,
1446661693
] |
def getPlotterType( form ):
"""
@param form : Form with whom this programm was called. | khosrow/metpx | [
1,
1,
1,
1,
1446661693
] |
def getForm():
"""
@summary: Returns the form with whom this page was called. | khosrow/metpx | [
1,
1,
1,
1,
1446661693
] |
def getLanguage( form ):
"""
@summary : Returns the language in which
the page should be generated. | khosrow/metpx | [
1,
1,
1,
1,
1446661693
] |
def setGlobalLanguageParameters( language ):
"""
@summary : Sets up all the needed global language
variables so that they can be used
everywhere in this program. | khosrow/metpx | [
1,
1,
1,
1,
1446661693
] |
def main():
"""
@summary: Based on the plotter specified in the received form,
executes query using a broker that's specific to
the said plotter.
""" | khosrow/metpx | [
1,
1,
1,
1,
1446661693
] |
def before(self, form):
query = ActivityType.query()
types = query.filter_by(active=True)
modes = ActivityMode.query()
query = ActivityAction.query()
query = query.filter_by(parent_id=None)
actions = query.filter_by(active=True)
activity_appstruct = {
'footer': self.request.config.get("activity_footer", ""),
'types': [type_.appstruct() for type_ in types],
'modes': [mode.appstruct() for mode in modes],
'actions': self._recursive_action_appstruct(actions)
}
self._add_pdf_img_to_appstruct('activity', activity_appstruct)
form.set_appstruct(activity_appstruct) | CroissanceCommune/autonomie | [
21,
14,
21,
284,
1381245170
] |
def __init__(self, *args, **kw):
BaseCommand.__init__(self, *args, **kw)
ESData.__init__(self) | StamusNetworks/scirius | [
525,
142,
525,
111,
1399230932
] |
def __init__(self, long_strings: bool = False, **kwargs: Any) -> None:
"""Initialize Strcmp95 instance.
Parameters
----------
long_strings : bool
Set to True to increase the probability of a match when the number
of matched characters is large. This option allows for a little
more tolerance when the strings are large. It is not an appropriate
test when comparing fixed length fields such as phone and social
security numbers.
**kwargs
Arbitrary keyword arguments
.. versionadded:: 0.4.0
"""
super(Strcmp95, self).__init__(**kwargs)
self._long_strings = long_strings | chrislit/abydos | [
154,
26,
154,
63,
1398235847
] |
def _in_range(char: str) -> bool:
"""Return True if char is in the range (0, 91).
Parameters
----------
char : str
The character to check
Returns
-------
bool
True if char is in the range (0, 91)
.. versionadded:: 0.1.0
"""
return 91 > ord(char) > 0 | chrislit/abydos | [
154,
26,
154,
63,
1398235847
] |
def T1197_telem_test_instance():
return T1197Telem(STATUS, MACHINE, USAGE_STR) | guardicore/monkey | [
6098,
725,
6098,
196,
1440919371
] |
def binned_statistic(x, values, statistic='mean',
bins=10, range=None):
"""
Compute a binned statistic for a set of data. | beiko-lab/gengis | [
28,
14,
28,
18,
1363614616
] |
def binned_statistic_2d(x, y, values, statistic='mean',
bins=10, range=None):
"""
Compute a bidimensional binned statistic for a set of data. | beiko-lab/gengis | [
28,
14,
28,
18,
1363614616
] |
def binned_statistic_dd(sample, values, statistic='mean',
bins=10, range=None):
"""
Compute a multidimensional binned statistic for a set of data. | beiko-lab/gengis | [
28,
14,
28,
18,
1363614616
] |
def action_import(self, cr, uid, ids, context=None):
wizard = self.browse(cr, uid, ids[0])
invoice_id = util.active_id(context, "account.invoice")
if not invoice_id:
raise osv.except_osv(_("Error!"), _("No invoice found"))
report_obj = self.pool.get("ir.actions.report.xml")
data=base64.decodestring(wizard.document)
data = report_aeroo.fixPdf(data)
if not data:
raise osv.except_osv(_("Error!"), _("PDF is corrupted and unable to fix!"))
if not report_obj.write_attachment(cr, uid, "account.invoice", invoice_id, report_name="account.report_invoice", datas=base64.encodestring(data), context=context, origin="account.invoice.attachment.wizard"):
raise osv.except_osv(_("Error!"), _("Unable to import document (check if invoice is validated)"))
return { "type" : "ir.actions.act_window_close" } | funkring/fdoo | [
1,
5,
1,
8,
1400249085
] |
def css_class(self):
return self._meta.module_name | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def update_or_create(self, filter_attrs, attrs):
"""Given unique look-up attributes, and extra data attributes, either
updates the entry referred to if it exists, or creates it if it doesn't. | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def __unicode__(self):
return self.name | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def __unicode__(self):
return "%s (%s for %s)" % (self.value, self.kind, self.content_object) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def __unicode__(self):
return "%s: %s" % (self.source, self.content_object) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def is_politician(self, when=None):
# FIXME - Don't like the look of this, rather a big subquery.
return self.filter(position__in=Position.objects.all().current_politician_positions(when)) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def get_query_set(self):
return PersonQuerySet(self.model) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def loose_match_name(self, name):
"""Search for a loose match on a name. May not be too reliable"""
# import here to avoid creating an import loop
from haystack.query import SearchQuerySet
# Try matching all the bits
results = SearchQuerySet().filter_and(content=name).models(self.model)
# if that fails try matching all the bits in any order
if not len(results):
results = SearchQuerySet().models(Person)
for bit in re.split(r'\s+', name):
results = results.filter_and(content=bit)
# If we have exactly one result return that
if len(results) == 1:
return results[0].object
else:
return None | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def get_next_featured(self, current_slug, want_previous=False):
""" Returns the next featured person, in slug order: using slug order because it's unique and easy to
exclude the current person. | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def clean(self):
# strip other_names and flatten multiple newlines
self.other_names = re.sub(r"\n+", "\n", self.other_names).strip() | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def name(self):
if self.other_names:
return self.other_names.split("\n")[0]
else:
return self.legal_name | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def additional_names(self):
if self.other_names:
return self.other_names.split("\n")[1:]
else:
return [] | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def aspirant_positions(self):
return self.position_set.all().current_aspirant_positions() | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def politician_positions(self):
return self.position_set.all().current_politician_positions() | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def parties(self):
"""Return list of parties that this person is currently a member of"""
party_memberships = self.position_set.all().currently_active().filter(title__slug='member').filter(organisation__kind__slug='party')
return Organisation.objects.filter(position__in=party_memberships) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def constituencies(self):
"""Return list of constituencies that this person is currently an politician for"""
return Place.objects.filter(position__in=self.politician_positions()) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def get_absolute_url(self):
return ('person', [self.slug]) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def generate_tasks(self):
"""Generate tasks for missing contact details etc"""
task_slugs = [] | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def scorecard_overall(self):
total_count = super(Person, self).active_scorecards().count()
total_score = super(Person, self).active_scorecards().aggregate(models.Sum('score'))['score__sum']
for constituency in self.constituencies():
constituency_count = constituency.active_scorecards().count()
if constituency_count:
total_count += constituency_count
total_score += constituency.active_scorecards().aggregate(models.Sum('score'))['score__sum']
return total_score / total_count | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def has_scorecards(self):
# We're only showing scorecards for current MPs
if self.is_politician():
return super(Person, self).has_scorecards() or any([x.has_scorecards() for x in self.constituencies()]) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def __unicode__(self):
return self.name | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def parties(self):
return self.filter(kind__slug='party') | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def get_query_set(self):
return OrganisationQuerySet(self.model) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def __unicode__(self):
return "%s (%s)" % (self.name, self.kind) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def get_absolute_url(self):
return ('organisation', [self.slug]) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def __unicode__(self):
return self.name | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def constituencies(self):
return self.filter(kind__slug='constituency') | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def get_query_set(self):
return PlaceQuerySet(self.model) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def position_with_organisation_set(self):
return self.position_set.filter(organisation__isnull=False) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def is_constituency(self):
return self.kind.slug == 'constituency' | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def current_politician_position(self):
"""Return the current politician position, or None"""
qs = self.position_set.all().current_politician_positions()
try:
return qs[0]
except IndexError:
return None | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def get_absolute_url(self):
return ('place', [self.slug]) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def __unicode__(self):
return self.name | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def get_absolute_url(self):
return ('position', [self.slug]) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def organisations(self):
"""
Return a qs of organisations, with the most frequently related first.
Each organisation is also annotated with 'position_count' which might be
useful.
This is intended as an alternative to assigning a org to each
position_title. Instead we can deduce it from the postions.
"""
orgs = (
Organisation
.objects
.filter(position__title=self)
.annotate(position_count=models.Count('position'))
.order_by('-position_count')
)
return orgs | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def currently_active(self, when=None):
"""Filter on start and end dates to limit to currently active postitions"""
if when == None:
when = datetime.date.today()
now_approx = repr(ApproximateDate(year=when.year, month=when.month, day=when.day))
qs = (
self
.filter(start_date__lte=now_approx)
.filter(Q(sorting_end_date_high__gte=now_approx) | Q(end_date=''))
)
return qs | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def aspirant_positions(self):
"""
Filter down to only positions which are aspirant ones. This uses the
convention that the slugs always start with 'aspirant-'.
"""
return self.filter( title__slug__startswith='aspirant-' ) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def politician_positions(self):
"""Filter down to only positions which are one of the two kinds of
politician (those with constituencies, and nominated ones).
"""
return self.filter(title__slug__in=settings.POLITICIAN_TITLE_SLUGS) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def political(self):
"""Filter down to only the political category"""
return self.filter(category='political') | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def other(self):
"""Filter down to only the other category"""
return self.filter(category='other') | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def order_by_place(self):
"""Sort by the place name"""
return self.order_by('place__name') | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def get_query_set(self):
return PositionQuerySet(self.model) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def clean(self):
if not (self.organisation or self.title or self.place):
raise exceptions.ValidationError('Must have at least one of organisation, title or place.')
if self.title and self.title.requires_place and not self.place:
raise exceptions.ValidationError("The job title '%s' requires a place to be set" % self.title.name) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def display_dates(self):
"""Nice HTML for the display of dates"""
# no dates
if not (self.start_date or self.end_date):
return ''
# start but no end
if self.start_date and not self.end_date:
return "Started %s" % self.start_date
# both dates
if self.start_date and self.end_date:
if self.end_date.future:
return "Started %s" % self.start_date
else:
return "%s → %s" % (self.start_date, self.end_date) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def display_start_date(self):
"""Return text that represents the start date"""
if self.start_date:
return str(self.start_date)
return '?' | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def display_end_date(self):
"""Return text that represents the end date"""
if self.end_date:
return str(self.end_date)
return '?' | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def has_known_dates(self):
"""Is there at least one known (not future) date?"""
return (self.start_date and not self.start_date.future) or \
(self.end_date and not self.end_date.future) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def _set_sorting_dates(self):
"""Set the sorting dates from the actual dates (does not call save())"""
# value can be yyyy-mm-dd, future or None
start = repr(self.start_date) if self.start_date else ''
end = repr(self.end_date) if self.end_date else '' | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def is_nominated_politician(self):
return self.title.slug == 'nominated-member-parliament' | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def __unicode__(self):
title = self.title or '???'
if self.organisation:
organisation = self.organisation.name
else:
organisation = '???'
return "%s (%s at %s)" % ( self.person.name, title, organisation) | Hutspace/odekro | [
1,
5,
1,
7,
1337882548
] |
def __str__(self):
return 'Abstract Class' | rosenvladimirov/addons | [
3,
6,
3,
2,
1484327648
] |
def __str__(self):
return 'Abstract Method' | rosenvladimirov/addons | [
3,
6,
3,
2,
1484327648
] |
def __str__(self):
return 'Unknown Class' | rosenvladimirov/addons | [
3,
6,
3,
2,
1484327648
] |
def __init__(self, value):
self.curr = value | rosenvladimirov/addons | [
3,
6,
3,
2,
1484327648
] |
def __repr__(self):
return 'Unsupported currency %s' % self.curr | rosenvladimirov/addons | [
3,
6,
3,
2,
1484327648
] |
def test_preview_fragment(self):
"""
Test for calling get_preview_html. Ensures data-usage-id is correctly set and
asides are correctly included.
"""
course = CourseFactory.create(default_store=ModuleStoreEnum.Type.split)
html = ItemFactory.create(
parent_location=course.location,
category="html",
data={'data': "<html>foobar</html>"}
)
config = StudioConfig.current()
config.enabled = True
config.save()
request = RequestFactory().get('/dummy-url')
request.user = UserFactory()
request.session = {}
# Call get_preview_fragment directly.
context = {
'reorderable_items': set(),
'read_only': True
}
html = get_preview_fragment(request, html, context).content
# Verify student view html is returned, and the usage ID is as expected.
html_pattern = re.escape(
str(course.id.make_usage_key('html', 'replaceme'))
).replace('replaceme', r'html_[0-9]*')
self.assertRegex(
html,
f'data-usage-id="{html_pattern}"'
)
self.assertRegex(html, '<html>foobar</html>')
self.assertRegex(html, r"data-block-type=[\"\']test_aside[\"\']")
self.assertRegex(html, "Aside rendered")
# Now ensure the acid_aside is not in the result
self.assertNotRegex(html, r"data-block-type=[\"\']acid_aside[\"\']")
# Ensure about pages don't have asides
about = modulestore().get_item(course.id.make_usage_key('about', 'overview'))
html = get_preview_fragment(request, about, context).content
self.assertNotRegex(html, r"data-block-type=[\"\']test_aside[\"\']")
self.assertNotRegex(html, "Aside rendered") | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_preview_no_asides(self):
"""
Test for calling get_preview_html. Ensures data-usage-id is correctly set and
asides are correctly excluded because they are not enabled.
"""
course = CourseFactory.create(default_store=ModuleStoreEnum.Type.split)
html = ItemFactory.create(
parent_location=course.location,
category="html",
data={'data': "<html>foobar</html>"}
)
config = StudioConfig.current()
config.enabled = False
config.save()
request = RequestFactory().get('/dummy-url')
request.user = UserFactory()
request.session = {}
# Call get_preview_fragment directly.
context = {
'reorderable_items': set(),
'read_only': True
}
html = get_preview_fragment(request, html, context).content
self.assertNotRegex(html, r"data-block-type=[\"\']test_aside[\"\']")
self.assertNotRegex(html, "Aside rendered") | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_preview_conditional_module_children_context(self, mock_is_condition_satisfied):
"""
Tests that when empty context is pass to children of ConditionalBlock it will not raise KeyError.
"""
mock_is_condition_satisfied.return_value = True
client = Client()
client.login(username=self.user.username, password=self.user_password)
with self.store.default_store(ModuleStoreEnum.Type.split):
course = CourseFactory.create()
conditional_block = ItemFactory.create(
parent_location=course.location,
category="conditional"
)
# child conditional_block
ItemFactory.create(
parent_location=conditional_block.location,
category="conditional"
)
url = reverse_usage_url(
'preview_handler',
conditional_block.location,
kwargs={'handler': 'xmodule_handler/conditional_get'}
)
response = client.post(url)
self.assertEqual(response.status_code, 200) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_block_branch_not_changed_by_preview_handler(self, default_store):
"""
Tests preview_handler should not update blocks being previewed
"""
client = Client()
client.login(username=self.user.username, password=self.user_password)
with self.store.default_store(default_store):
course = CourseFactory.create()
block = ItemFactory.create(
parent_location=course.location,
category="problem"
)
url = reverse_usage_url(
'preview_handler',
block.location,
kwargs={'handler': 'xmodule_handler/problem_check'}
)
response = client.post(url)
self.assertEqual(response.status_code, 200)
self.assertFalse(modulestore().has_changes(modulestore().get_item(block.location))) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def student_view(self, context):
"""
Renders the output that a student will see.
"""
fragment = Fragment()
fragment.add_content(self.runtime.service(self, 'mako').render_template('edxmako.html', context))
return fragment | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def setUp(self):
"""
Set up the user and request that will be used.
"""
super().setUp()
self.user = UserFactory()
self.course = CourseFactory.create()
self.request = mock.Mock()
self.field_data = mock.Mock() | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_expected_services_exist(self, expected_service):
"""
Tests that the 'user' and 'i18n' services are provided by the Studio runtime.
"""
descriptor = ItemFactory(category="pure", parent=self.course)
runtime = _preview_module_system(
self.request,
descriptor,
self.field_data,
)
service = runtime.service(descriptor, expected_service)
self.assertIsNotNone(service) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def setUp(self):
"""
Set up the user and other fields that will be used to instantiate the runtime.
"""
super().setUp()
self.course = CourseFactory.create()
self.user = UserFactory()
self.request = RequestFactory().get('/dummy-url')
self.request.user = self.user
self.request.session = {}
self.descriptor = ItemFactory(category="video", parent=self.course)
self.field_data = mock.Mock()
self.runtime = _preview_module_system(
self.request,
self.descriptor,
self.field_data,
) | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def test_render_template(self):
descriptor = ItemFactory(category="pure", parent=self.course)
html = get_preview_fragment(self.request, descriptor, {'element_id': 142}).content
assert '<div id="142" ns="main">Testing the MakoService</div>' in html | edx/edx-platform | [
6290,
3437,
6290,
280,
1369945238
] |
def create_custom_fields_as_needed():
CustomField.objects.get_or_create(
name='record_id',
defaults={
"label": 'Citrix DNS Record ID',
"type": 'STR',
}
)
CustomField.objects.get_or_create(
name='record_value',
defaults={
"label": 'Citrix DNS Record Value',
"type": 'STR',
}
)
CustomField.objects.get_or_create(
name='ttl',
defaults={
"label": 'Citrix DNS Record TTL',
"type": 'INT',
}
)
CustomField.objects.get_or_create(
name='recordType',
defaults={
"label": 'Citrix DNS Record Type',
"type": 'STR',
}
) | CloudBoltSoftware/cloudbolt-forge | [
34,
32,
34,
16,
1437063482
] |
def get_citrix_api_token():
# Citrix api uses tokens to authorise requests. The tokens expires after a short while and has to be regenerated.
ci = ConnectionInfo.objects.get(name=API_CLIENT_CI)
url = get_citrix_url()
response = requests.get(
"{url}/api/oauth/token?client_id={client_id}&client_secret={client_secret}&grant_type=client_credentials".format(
url=url, client_id=ci.username, client_secret=ci.password))
token = response.json().get('access_token')
return token | CloudBoltSoftware/cloudbolt-forge | [
34,
32,
34,
16,
1437063482
] |
def generate_options_for_editRecordType(**kwargs):
return [(True, "Yes"), (False, "No")] | CloudBoltSoftware/cloudbolt-forge | [
34,
32,
34,
16,
1437063482
] |
def generate_options_for_editTTL(**kwargs):
return [(True, "Yes"), (False, "No")] | CloudBoltSoftware/cloudbolt-forge | [
34,
32,
34,
16,
1437063482
] |
def sample_append_rows():
# Create a client
client = bigquery_storage_v1beta2.BigQueryWriteClient()
# Initialize request argument(s)
request = bigquery_storage_v1beta2.AppendRowsRequest(
write_stream="write_stream_value",
)
# This method expects an iterator which contains
# 'bigquery_storage_v1beta2.AppendRowsRequest' objects
# Here we create a generator that yields a single `request` for
# demonstrative purposes.
requests = [request]
def request_generator():
for request in requests:
yield request
# Make the request
stream = client.append_rows(requests=request_generator())
# Handle the response
for response in stream:
print(response) | googleapis/python-bigquery-storage | [
73,
35,
73,
15,
1575936548
] |
def keras_model_builder_with_zeros():
# Create a simple linear regression model, single output.
# We initialize all weights to zero.
model = tf.keras.Sequential([
tf.keras.layers.Dense(
1,
kernel_initializer='zeros',
bias_initializer='zeros',
input_shape=(1,))
])
return model | google-research/federated | [
505,
161,
505,
11,
1600124947
] |
def create_dataset():
# Create data satisfying y = 2*x + 1
x = [[1.0], [2.0], [3.0]]
y = [[3.0], [5.0], [7.0]]
return tf.data.Dataset.from_tensor_slices((x, y)).batch(1) | google-research/federated | [
505,
161,
505,
11,
1600124947
] |
def get_input_spec():
return create_dataset().element_spec | google-research/federated | [
505,
161,
505,
11,
1600124947
] |
def tff_model_builder():
return tff.learning.from_keras_model(
keras_model=keras_model_builder_with_zeros(),
input_spec=get_input_spec(),
loss=tf.keras.losses.MeanSquaredError(),
metrics=metrics_builder()) | google-research/federated | [
505,
161,
505,
11,
1600124947
] |
def test_create_federated_eval_fns(self, use_test_cd):
"""Test for create_federated_eval_fns."""
(part_train_eval_fn, part_val_fn, unpart_fn,
test_fn) = trainer_utils.create_federated_eval_fns(
tff_model_builder=tff_model_builder,
metrics_builder=metrics_builder,
part_train_eval_cd=create_federated_cd(),
part_val_cd=create_federated_cd(),
unpart_cd=create_federated_cd(),
test_cd=create_federated_cd() if use_test_cd else None,
stat_fns=eval_metric_distribution.ALL_STAT_FNS,
rounds_per_eval=1,
part_clients_per_eval=2,
unpart_clients_per_eval=2,
test_clients_for_eval=3,
resample_eval_clients=False,
eval_clients_random_seed=1)
keras_model = keras_model_builder_with_zeros()
model_weights = tff.learning.ModelWeights.from_model(keras_model)
server_state = tff.learning.framework.ServerState(model_weights, [], [], [])
expected_keys = [
f'mean_squared_error/{s}' for s in eval_metric_distribution.ALL_STAT_FNS
]
# Federated validation fn requires a positional arg round_num.
if use_test_cd:
self.assertIsNotNone(test_fn)
eval_fns_to_test = (part_train_eval_fn, part_val_fn, unpart_fn, test_fn)
else:
self.assertIsNone(test_fn)
eval_fns_to_test = (part_train_eval_fn, part_val_fn, unpart_fn)
for eval_fn in eval_fns_to_test:
metrics_dict = eval_fn(server_state, 0)
self.assertEqual(list(metrics_dict.keys()), expected_keys) | google-research/federated | [
505,
161,
505,
11,
1600124947
] |
def test_create_federated_eval_fns_skips_rounds(self, rounds_per_eval,
round_num):
"""Test that create_federated_eval_fns skips the appropriate rounds."""
part_train_eval_fn, part_val_fn, unpart_fn, _ = trainer_utils.create_federated_eval_fns(
tff_model_builder=tff_model_builder,
metrics_builder=metrics_builder,
part_train_eval_cd=create_federated_cd(),
part_val_cd=create_federated_cd(),
unpart_cd=create_federated_cd(),
test_cd=create_federated_cd(),
stat_fns=eval_metric_distribution.ALL_STAT_FNS,
rounds_per_eval=rounds_per_eval,
part_clients_per_eval=2,
unpart_clients_per_eval=2,
test_clients_for_eval=3,
resample_eval_clients=False,
eval_clients_random_seed=1)
keras_model = keras_model_builder_with_zeros()
model_weights = tff.learning.ModelWeights.from_model(keras_model)
server_state = tff.learning.framework.ServerState(model_weights, [], [], [])
# Federated validation fn requires a positional arg round_num.
for eval_fn in (part_train_eval_fn, part_val_fn, unpart_fn):
metrics_dict = eval_fn(server_state, round_num)
self.assertEmpty(metrics_dict.keys()) | google-research/federated | [
505,
161,
505,
11,
1600124947
] |
def test_create_centralized_eval_fns(self, use_test_cd):
"""Test for create_centralized_eval_fns."""
(part_train_eval_fn, part_val_fn, unpart_fn,
test_fn) = trainer_utils.create_centralized_eval_fns(
tff_model_builder=tff_model_builder,
metrics_builder=metrics_builder,
part_train_eval_cd=create_federated_cd(),
part_val_cd=create_federated_cd(),
unpart_cd=create_federated_cd(),
test_cd=create_federated_cd() if use_test_cd else None,
stat_fns=eval_metric_distribution.ALL_STAT_FNS,
part_clients_per_eval=2,
unpart_clients_per_eval=2,
test_clients_for_eval=3,
resample_eval_clients=False,
eval_clients_random_seed=1)
keras_model = keras_model_builder_with_zeros()
expected_keys = [
f'mean_squared_error/{s}' for s in eval_metric_distribution.ALL_STAT_FNS
]
if use_test_cd:
self.assertIsNotNone(test_fn)
eval_fns_to_test = (part_train_eval_fn, part_val_fn, unpart_fn, test_fn)
else:
self.assertIsNone(test_fn)
eval_fns_to_test = (part_train_eval_fn, part_val_fn, unpart_fn)
for eval_fn in eval_fns_to_test:
metrics_dict = eval_fn(keras_model)
self.assertEqual(list(metrics_dict.keys()), expected_keys) | google-research/federated | [
505,
161,
505,
11,
1600124947
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.