function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def stop(self):
self.running = False | Kefkius/electrum-frc | [
3,
5,
3,
1,
1423949169
] |
def register_callback(self, event, callback):
with self.lock:
if not self.callbacks.get(event):
self.callbacks[event] = []
self.callbacks[event].append(callback) | Kefkius/electrum-frc | [
3,
5,
3,
1,
1423949169
] |
def get_tokens():
"""
Returns a tuple of tokens in the format {{site/property}} that will be used
to build the dictionary passed into execute
"""
return (HDFS_SITE_KEY, NN_HTTP_ADDRESS_KEY, NN_HTTPS_ADDRESS_KEY, NN_HTTP_POLICY_KEY, EXECUTABLE_SEARCH_PATHS,
NN_CHECKPOINT_TX_KEY, NN_CHECKPOINT_PERIOD_KEY, KERBEROS_KEYTAB, KERBEROS_PRINCIPAL, SECURITY_ENABLED_KEY, SMOKEUSER_KEY) | arenadata/ambari | [
3,
7,
3,
3,
1478181309
] |
def execute(configurations={}, parameters={}, host_name=None):
"""
Returns a tuple containing the result code and a pre-formatted result label
Keyword arguments:
configurations (dictionary): a mapping of configuration key to value
parameters (dictionary): a mapping of script parameter key to value
host_name (string): the name of this host where the alert is running
"""
if configurations is None:
return (('UNKNOWN', ['There were no configurations supplied to the script.'])) | arenadata/ambari | [
3,
7,
3,
3,
1478181309
] |
def get_time(delta):
h = int(delta/3600)
m = int((delta % 3600)/60)
return {'h':h, 'm':m} | arenadata/ambari | [
3,
7,
3,
3,
1478181309
] |
def numeric_as_float(data):
for v in data.columns:
if data[v].dtype is np.dtype('int64'):
data[v] = data[v].astype(np.float64) | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def setUp(self):
self.dirpath = tm.get_data_path()
self.file01 = os.path.join(self.dirpath, "DEMO_G.XPT")
self.file02 = os.path.join(self.dirpath, "SSHSV1_A.XPT")
self.file03 = os.path.join(self.dirpath, "DRXFCD_G.XPT") | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def test1_index(self):
# Tests with DEMO_G.XPT using index (all numeric file)
# Compare to this
data_csv = pd.read_csv(self.file01.replace(".XPT", ".csv"))
data_csv = data_csv.set_index("SEQN")
numeric_as_float(data_csv)
# Read full file
data = XportReader(self.file01, index="SEQN").read()
tm.assert_frame_equal(data, data_csv, check_index_type=False)
# Test incremental read with `read` method.
reader = XportReader(self.file01, index="SEQN")
data = reader.read(10)
tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False)
# Test incremental read with `get_chunk` method.
reader = XportReader(self.file01, index="SEQN", chunksize=10)
data = reader.get_chunk()
tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False) | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def test2(self):
# Test with SSHSV1_A.XPT
# Compare to this
data_csv = pd.read_csv(self.file02.replace(".XPT", ".csv"))
numeric_as_float(data_csv)
data = XportReader(self.file02).read()
tm.assert_frame_equal(data, data_csv) | Vvucinic/Wander | [
1,
1,
1,
11,
1449375044
] |
def f():
return 42 | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def m(n):
return 24 | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def test_simple(self):
# simple set/get
cache.set("key", "value")
self.assertEqual(cache.get("key"), "value") | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def test_non_existent(self):
# get with non-existent keys
self.assertEqual(cache.get("does_not_exist"), None)
self.assertEqual(cache.get("does_not_exist", "bang!"), "bang!") | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def test_delete(self):
# delete
cache.set("key1", "spam")
cache.set("key2", "eggs")
self.assertEqual(cache.get("key1"), "spam")
cache.delete("key1")
self.assertEqual(cache.get("key1"), None)
self.assertEqual(cache.get("key2"), "eggs") | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def test_in(self):
cache.set("hello2", "goodbye2")
self.assertEqual("hello2" in cache, True)
self.assertEqual("goodbye2" in cache, False) | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def test_expiration(self):
cache.set('expire1', 'very quickly', 1)
cache.set('expire2', 'very quickly', 1)
cache.set('expire3', 'very quickly', 1)
time.sleep(2)
self.assertEqual(cache.get("expire1"), None) | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def test_unicode(self):
stuff = {
u'ascii': u'ascii_value',
u'unicode_ascii': u'Iñtërnâtiônàlizætiøn1',
u'Iñtërnâtiônàlizætiøn': u'Iñtërnâtiônàlizætiøn2',
u'ascii': {u'x' : 1 }
}
for (key, value) in stuff.items():
cache.set(key, value)
self.assertEqual(cache.get(key), value) | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def setUp(self):
self.dirname = tempfile.mktemp()
os.mkdir(self.dirname)
self.cache = FileCache(self.dirname, {}) | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def tearDown(self):
shutil.rmtree(self.dirname) | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def test_hashing(self):
"""Test that keys are hashed into subdirectories correctly"""
self.cache.set("foo", "bar")
keyhash = md5.new("foo").hexdigest()
keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
self.assert_(os.path.exists(keypath)) | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def test_subdirectory_removal(self):
"""
Make sure that the created subdirectories are correctly removed when empty.
"""
self.cache.set("foo", "bar")
keyhash = md5.new("foo").hexdigest()
keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
self.assert_(os.path.exists(keypath))
self.cache.delete("foo")
self.assert_(not os.path.exists(keypath))
self.assert_(not os.path.exists(os.path.dirname(keypath)))
self.assert_(not os.path.exists(os.path.dirname(os.path.dirname(keypath)))) | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def test_patch_vary_headers(self):
headers = (
# Initial vary, new headers, resulting vary.
(None, ('Accept-Encoding',), 'Accept-Encoding'),
('Accept-Encoding', ('accept-encoding',), 'Accept-Encoding'),
('Accept-Encoding', ('ACCEPT-ENCODING',), 'Accept-Encoding'),
('Cookie', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
('Cookie, Accept-Encoding', ('Accept-Encoding',), 'Cookie, Accept-Encoding'),
('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
(None, ('Accept-Encoding', 'COOKIE'), 'Accept-Encoding, COOKIE'),
('Cookie, Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
('Cookie , Accept-Encoding', ('Accept-Encoding', 'cookie'), 'Cookie, Accept-Encoding'),
)
for initial_vary, newheaders, resulting_vary in headers:
response = HttpResponse()
if initial_vary is not None:
response['Vary'] = initial_vary
patch_vary_headers(response, newheaders)
self.assertEqual(response['Vary'], resulting_vary) | paulsmith/geodjango | [
20,
7,
20,
1,
1215189246
] |
def get_object(self):
cnpj = self.kwargs.get(self.lookup_field, '00000000000000')
return get_object_or_404(Company, cnpj=format_cnpj(cnpj)) | datasciencebr/serenata-de-amor | [
4451,
683,
4451,
74,
1467060911
] |
def get(self, request, **kwargs):
"""
Create checkout page.
Gets shopping information from cart and sends it to the payment app
in form of a dict. It then renders the checkout template which can then
be used to pay.
Args:
request: The incoming get request object
**kwargs: Any keyword arguments passed to the function
Returns:
A template rendered with the payment details context
"""
cart = Cart(request.session)
amount = cart.total
amount_in_cents = int(amount) * 100
title = "Total payment expected"
description = "Troupon shopping"
payment_details = {
"title": title,
"key": self.stripe_publishable_api_key,
"amount": amount_in_cents,
"description": description,
"currency": "usd",
}
request.session['payment_details'] = payment_details
context = {
"amount": amount,
"title": title,
"description": description,
"payment_details": payment_details,
}
return render(request, self.template_name, context) | andela/troupon | [
14,
13,
14,
5,
1439373417
] |
def post(self, request, **kwargs):
"""
Add item to cart.
Args:
request: The incoming post request object
**kwargs: Any keyword arguments passed to the function
Returns:
A redirect to the deals homepage
"""
dealid = request.POST.get('dealid')
deal = Deal.objects.get(id=dealid)
cart = Cart(request.session)
cart.add(deal, price=deal.price)
return redirect('/') | andela/troupon | [
14,
13,
14,
5,
1439373417
] |
def get(self, request):
cart = Cart(request.session)
context = {'cart': cart}
return TemplateResponse(request, 'cart/shipping.html', context) | andela/troupon | [
14,
13,
14,
5,
1439373417
] |
def get(self, request, **kwargs):
"""
Show cart items.
Args:
request: The incoming get request object
**kwargs: Any keyword arguments passed to the function
Returns:
A template rendered with all the cart items.
"""
cart = Cart(request.session)
context = {'cart': cart}
return TemplateResponse(request, 'cart/cart.html', context) | andela/troupon | [
14,
13,
14,
5,
1439373417
] |
def get(self, request, **kwargs):
"""
Get cart from session and remove everything from it.
Args:
request: The incoming get request object
**kwargs: Any keyword arguments passed to the function
Returns:
A redirect to the deals homepage
"""
cart = Cart(request.session)
cart.clear()
return redirect('/') | andela/troupon | [
14,
13,
14,
5,
1439373417
] |
def get(self, request, *args, **kwargs):
job = get_object_or_404(Job, pk=self.kwargs.get('pk'))
feature_types = FeatureType.objects.all()
aoi_count = job.total_count()
aoi_complete = job.complete_count()
aoi_work = job.in_work_count()
cookie_url_trailer = get_cookie_trailer(request)
description = 'Job #'+str(job.id)+': '+str(job.name)+'\n'+str(job.project.name)+'\n'
if aoi_count == 0:
output = '<?xml version="1.0" encoding="UTF-8"?>\n'
output += '<kml xmlns="http://www.opengis.net/kml/2.2">\n'
output += ' <Document>\n'
output += ' <name>Empty Job</name>\n'
output += ' <description>'+description+'</description>\n'
output += ' </Document>\n'
output += '</kml>\n'
return HttpResponse(output, mimetype="application/vnd.google-earth.kml+xml", status=200)
aoi_comp_pct = (100 * float(aoi_complete)/float(aoi_count))
aoi_work_pct = int(100 * float(aoi_work)/float(aoi_count))
aoi_tot_pct = int(100 * float(aoi_work+aoi_complete)/float(aoi_count))
doc_name = 'GeoQ C:'+str(aoi_complete)+', W:'+str(aoi_work)+', Tot:'+str(aoi_count)+' ['+str(aoi_tot_pct)+'%]'
description = description + 'Complete Cells: ' + str(aoi_complete) + ' ['+str(aoi_comp_pct)+'%], In Work: ' + str(aoi_work) + ' ['+str(aoi_work_pct)+'%], Total: ' + str(aoi_count)
output = '<?xml version="1.0" encoding="UTF-8"?>\n'
output += '<kml xmlns="http://www.opengis.net/kml/2.2">\n'
output += ' <Document>\n'
output += ' <name>'+doc_name+'</name>\n'
output += ' <description>'+description+'</description>\n'
output += ' <Style id="geoq_inwork">\n'
output += ' <LineStyle>\n'
output += ' <width>4</width>\n'
output += ' <color>7f0186cf</color>\n'
output += ' </LineStyle>\n'
output += ' <PolyStyle>\n'
output += ' <fill>0</fill>\n'
output += ' <outline>1</outline>\n'
output += ' </PolyStyle>\n'
output += ' </Style>\n'
output += ' <Style id="geoq_complete">\n'
output += ' <LineStyle>\n'
output += ' <width>3</width>\n'
output += ' <color>7f0101cf</color>\n'
output += ' </LineStyle>\n'
output += ' <PolyStyle>\n'
output += ' <fill>0</fill>\n'
output += ' <outline>1</outline>\n'
output += ' </PolyStyle>\n'
output += ' </Style>\n'
output += ' <Style id="geoq_unassigned">\n'
output += ' <LineStyle>\n'
output += ' <width>2</width>\n'
output += ' <color>7f00ff00</color>\n'
output += ' </LineStyle>\n'
output += ' <PolyStyle>\n'
output += ' <fill>0</fill>\n'
output += ' <outline>1</outline>\n'
output += ' </PolyStyle>\n'
output += ' </Style>\n'
for feature in feature_types:
output += ' <Style id="geoq_'+str(feature.id)+'">\n'
out_color = '7f0066ff'
if feature.style == None:
output += ' </Style>\n'
continue
if 'color' in feature.style:
color = feature.style['color']
#convert to a kml-recognized color
if color[0:1] == '#' and len(color) == 4:
color = normalize_hex(color)
try:
c = name_to_hex(color)
out_color = '7f' + c[5:7] + c[3:5] + c[1:3]
except Exception:
out_color = '7f0066ff'
output += ' <PolyStyle>\n'
output += ' <color>'+out_color+'</color>\n'
output += ' <colorMode>normal</colorMode>\n'
output += ' <fill>1</fill>\n'
output += ' <outline>1</outline>\n'
output += ' </PolyStyle>\n'
if 'weight' in feature.style:
output += ' <LineStyle>\n'
output += ' <width>'+str(feature.style['weight'])+'</width>\n'
if 'color' in feature.style:
output += ' <color>'+out_color+'</color>\n'
output += ' </LineStyle>\n'
if 'iconUrl' in feature.style:
icon_url = str(feature.style['iconUrl'])
if not icon_url.startswith("http"):
icon_url = request.build_absolute_uri(icon_url)
else:
icon_url += cookie_url_trailer
output += ' <IconStyle>\n'
output += ' <Icon>\n'
output += ' <href>' + xml_escape(icon_url) + '</href>\n'
output += ' </Icon>\n'
output += ' </IconStyle>\n'
output += ' </Style>\n'
# locations = job.feature_set.all().order_by('template')
locations = job.feature_set.all()\
.extra(tables=['maps_featuretype'])\
.extra(where=['maps_featuretype.id=maps_feature.template_id'])\
.order_by('maps_featuretype.name')
last_template = ""
skip_the_first = True
template_has_started = False
for loc in locations:
template_name = str(loc.template.name)
if template_name != last_template:
if skip_the_first:
skip_the_first = False
else:
output += ' </Folder>\n'
output += ' <Folder><name>'+template_name+'</name>\n'
last_template = template_name
template_has_started = True
analyst_name = str(loc.analyst.username)
dtg = str(loc.created_at)
job_id = str(loc.job.id)
#TODO: Add links to Jobs and Projects
datetime_obj = datetime.strptime(dtg, "%Y-%m-%d %H:%M:%S.%f+00:00")
datetime_obj_utc = datetime_obj.replace(tzinfo=timezone('UTC'))
date_time = datetime_obj_utc.strftime('%Y-%m-%dT%H:%M:%SZ')
date_time_desc = datetime_obj_utc.strftime('%Y-%m-%d %H:%M:%S')
desc = 'Posted by '+analyst_name+' at '+date_time_desc+' Zulu (UTC) in Job #'+job_id
#TODO: Add more details
#TODO: Add links to linked objects
#Simplify polygons to reduce points in complex shapes
if loc.the_geom.num_coords > 0: #skip empty locations
simplegeom = loc.the_geom.simplify(0.0002)
if simplegeom.num_coords > 0:
kml = str(loc.the_geom.simplify(0.0002).kml)
else:
kml = str(loc.the_geom.kml)
if '<Polygon><outerBoundaryIs><LinearRing><coordinates>' in kml:
add_text = '<altitudeMode>clampToGround</altitudeMode>'
kml = kml.replace('<coordinates>', add_text+'<coordinates>')
kml = kml.replace('</outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing>', '')
output += ' <Placemark><name>'+template_name+'</name>\n'
output += ' <TimeStamp><when>'+date_time+'</when></TimeStamp>\n'
output += ' <description>'+desc+'</description>\n'
output += ' <styleUrl>#geoq_'+str(loc.template.id)+'</styleUrl>\n'
output += ' '+str(kml)+'\n'
output += ' </Placemark>\n'
if template_has_started:
output += ' </Folder>\n'
output += ' <Folder><name>Work Cells</name>\n'
aois = job.aois.order_by('status')
for aoi in aois:
style = 'complete'
if aoi.status == 'In work':
style = 'inwork'
if aoi.status == 'Unassigned':
style = 'unassigned'
aoi_name = "#"+str(aoi.id)+", "+str(aoi.status)+" - Priority:"+str(aoi.priority)
kml = str(aoi.polygon.simplify(0.0002).kml)
if '<Polygon><outerBoundaryIs><LinearRing><coordinates>' in kml:
add_text = '<tessellate>1</tessellate><altitudeMode>clampToGround</altitudeMode>'
kml = kml.replace('<coordinates>', add_text+'<coordinates>')
output += ' <Placemark>\n'
output += ' <name>'+aoi_name+'</name>\n'
output += ' <styleUrl>#geoq_'+style+'</styleUrl>\n'
output += ' '+kml+'\n'
output += ' </Placemark>\n'
output += ' </Folder>\n'
output += ' </Document>\n'
output += '</kml>'
return HttpResponse(output, content_type="application/vnd.google-earth.kml+xml", status=200) | ngageoint/geoq | [
612,
133,
612,
115,
1396643643
] |
def coupler_ring(
gap: float = 0.2,
radius: float = 5.0,
length_x: float = 4.0,
coupler90: ComponentFactory = coupler90function,
bend: Optional[ComponentFactory] = None,
coupler_straight: ComponentFactory = coupler_straight_function,
cross_section: CrossSectionFactory = strip,
bend_cross_section: Optional[CrossSectionFactory] = None,
**kwargs | gdsfactory/gdsfactory | [
177,
72,
177,
80,
1585200379
] |
def time2s(time):
""" given 's.s' or 'h:m:s.s' returns s.s """
if time:
sec = reduce(lambda x, i: x*60 + i,
list(map(float, time.split(':'))))
else:
sec = 0.0
return sec | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def __str__(self):
return self.name | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def natural_key(self):
return self.name | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def client_name(self):
return self.client | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_absolute_url(self):
return ('episode_list', [self.client.slug,self.slug,]) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def __next__(self):
"""
gets the next clip in the room.
"""
rfs = Raw_File.objects.filter(location=self.location,
start__gt=self.start,
).order_by('start','id')
# id__gt=self.id).order_by('start','id')
if rfs:
rf=rfs[0]
else:
rf=None
return rf | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def base_url(self):
""" Returns the url for the file, minus the MEDIA_URL and extension """
return "%s/%s/dv/%s/%s" % (self.show.client.slug,
self.show.slug,
self.location.slug,
self.filename) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_adjusted_start(self):
return self.start + datetime.timedelta(
hours = 0 if self.location.hours_offset is None
else self.location.hours_offset ) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_adjusted_end(self):
return self.end + datetime.timedelta(
hours = 0 if self.location.hours_offset is None
else self.location.hours_offset ) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_end_seconds(self):
return time2s( self.end ) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_minutes(self):
# return durration in minutes (float)
return self.get_seconds()/60.0 | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_absolute_url(self):
return ('raw_file', [self.id,]) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def __str__(self):
return self.click.isoformat() | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def __str__(self):
return self.name | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def generate_edit_key():
""" Generate a random key """
return str(random.randint(10000000,99999999)) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_absolute_url(self):
return ('episode', [self.id]) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def cuts_time(self):
# get total time in seoonds of video based on selected cuts.
# or None if there are no clips.
cuts = Cut_List.objects.filter(episode=self, apply=True)
if not cuts:
ret = None
else:
s=0
for cut in cuts:
s+=int(cut.duration()) # durration is in seconds :p
ret = s
return ret | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def add_email(self, email):
if self.emails is None: emails=[]
else: emails = self.emails.split(',')
if email not in emails:
if self.emails:
emails.append(email)
self.emails = ','.join(emails)
else:
self.emails = email
self.save() | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def titlecase(self):
return titlecase(self.name) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def location_slug(self):
location_slug=self.location.slug
print(location_slug)
return location_slug | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def composed_description(self):
# build a wad of text to use as public facing description
show = self.show
client = show.client
footer = "Produced by NDV: https://youtube.com/channel/UCQ7dFBzZGlBvtU2hCecsBBg?sub_confirmation=1"
# (show tags seperate the talk from the event text)
descriptions = [self.authors,
self.public_url,
self.conf_url,
self.description,
show.tags,
show.description, client.description,
footer,
client.tags,
"{} at {}".format(
self.start.strftime("%c"),
self.location.name),
]
# remove blanks
descriptions = [d for d in descriptions if d]
# combine wiht CRs between each item
description = "\n\n".join(descriptions)
# remove extra blank lines
description = re.sub( r'\n{2,}', r'\n\n', description)
# description = "<br/>\n".join(description.split('\n'))
return description | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_absolute_url(self):
return urls.reverse('episode', [self.episode.id]) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_start_seconds(self):
return time2s( self.start ) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_end_seconds(self):
return time2s( self.end ) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def duration(self):
# calc size of clip in secconds
# may be size of raw, but take into account trimming start/end
def to_sec(time, default=0):
# convert h:m:s to s
if time:
sec = reduce(lambda x, i: x*60 + i,
list(map(float, time.split(':'))))
else:
sec=default
return sec
start = to_sec( self.start )
end = to_sec( self.end, to_sec(self.raw_file.duration))
dur = end-start
return dur | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def base_url(self):
""" Returns the url for the file, minus the MEDIA_URL and extension """
return self.raw_file.base_url() | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def __str__(self):
return self.slug | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_absolute_url(self):
# https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode
url = "{}?{}={}".format(
urls.reverse( 'admin:main_episode_changelist'),
"image_file__id__exact",
self.id)
return url | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def duration(self):
if self.start and self.end:
dur = self.end - self.start
dur = datetime.timedelta(dur.days,dur.seconds)
return dur
else:
return None | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def get_absolute_url(self):
return ('episode', [self.episode.id]) | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def set_end(sender, instance, **kwargs):
if instance.start:
if instance.duration:
seconds = reduce(lambda x, i: x*60 + i,
list(map(float, instance.duration.split(':'))))
instance.end = instance.start + \
datetime.timedelta(seconds=seconds)
elif instance.end:
# calc duration based on End
d = instance.end - instance.start
seconds = d.total_seconds()
hms = seconds//3600, (seconds%3600)//60, seconds%60
instance.duration = "%02d:%02d:%02d" % hms
else:
instance.end = None
else:
instance.end = None | CarlFK/veyepar | [
45,
22,
45,
11,
1240753874
] |
def _kepler_equation(E, M, ecc):
return E_to_M(E, ecc) - M | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def _kepler_equation_prime(E, M, ecc):
return 1 - ecc * np.cos(E) | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def _kepler_equation_hyper(F, M, ecc):
return F_to_M(F, ecc) - M | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def _kepler_equation_prime_hyper(F, M, ecc):
return ecc * np.cosh(F) - 1 | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def jit_newton_wrapper(x0, args=(), tol=1.48e-08, maxiter=50):
p0 = float(x0)
for _ in range(maxiter):
fval = func(p0, *args)
fder = fprime(p0, *args)
newton_step = fval / fder
p = p0 - newton_step
if abs(p - p0) < tol:
return p
p0 = p
return np.nan | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def D_to_nu(D):
r"""True anomaly from parabolic anomaly.
Parameters
----------
D : float
Eccentric anomaly.
Returns
-------
nu : float
True anomaly.
Notes
-----
From [1]_:
.. math::
\nu = 2 \arctan{D}
"""
return 2.0 * np.arctan(D) | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def nu_to_D(nu):
r"""Parabolic anomaly from true anomaly.
Parameters
----------
nu : float
True anomaly in radians.
Returns
-------
D : float
Parabolic anomaly.
Warnings
--------
The parabolic anomaly will be continuous in (-∞, ∞)
only if the true anomaly is in (-π, π].
No validation or wrapping is performed.
Notes
-----
The treatment of the parabolic case is heterogeneous in the literature,
and that includes the use of an equivalent quantity to the eccentric anomaly:
[1]_ calls it "parabolic eccentric anomaly" D,
[2]_ also uses the letter D but calls it just "parabolic anomaly",
[3]_ uses the letter B citing indirectly [4]_
(which however calls it "parabolic time argument"),
and [5]_ does not bother to define it.
We use this definition:
.. math::
B = \tan{\frac{\nu}{2}}
References
----------
.. [1] Farnocchia, Davide, Davide Bracali Cioci, and Andrea Milani.
"Robust resolution of Kepler’s equation in all eccentricity regimes."
.. [2] Bate, Muller, White.
.. [3] Vallado, David. "Fundamentals of Astrodynamics and Applications",
2013.
.. [4] IAU VIth General Assembly, 1938.
.. [5] Battin, Richard H. "An introduction to the Mathematics and Methods
of Astrodynamics, Revised Edition", 1999.
"""
# TODO: Rename to B
return np.tan(nu / 2.0) | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def nu_to_E(nu, ecc):
r"""Eccentric anomaly from true anomaly.
.. versionadded:: 0.4.0
Parameters
----------
nu : float
True anomaly in radians.
ecc : float
Eccentricity.
Returns
-------
E : float
Eccentric anomaly, between -π and π radians.
Warnings
--------
The eccentric anomaly will be between -π and π radians,
no matter the value of the true anomaly.
Notes
-----
The implementation uses the half-angle formula from [3]_:
.. math::
E = 2 \arctan \left ( \sqrt{\frac{1 - e}{1 + e}} \tan{\frac{\nu}{2}} \right)
\in (-\pi, \pi]
"""
E = 2 * np.arctan(np.sqrt((1 - ecc) / (1 + ecc)) * np.tan(nu / 2))
return E | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def nu_to_F(nu, ecc):
r"""Hyperbolic anomaly from true anomaly.
Parameters
----------
nu : float
True anomaly in radians.
ecc : float
Eccentricity (>1).
Returns
-------
F : float
Hyperbolic anomaly.
Warnings
--------
The hyperbolic anomaly will be continuous in (-∞, ∞)
only if the true anomaly is in (-π, π],
which should happen anyway
because the true anomaly is limited for hyperbolic orbits.
No validation or wrapping is performed.
Notes
-----
The implementation uses the half-angle formula from [3]_:
.. math::
F = 2 \operatorname{arctanh} \left( \sqrt{\frac{e-1}{e+1}} \tan{\frac{\nu}{2}} \right)
"""
F = 2 * np.arctanh(np.sqrt((ecc - 1) / (ecc + 1)) * np.tan(nu / 2))
return F | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def E_to_nu(E, ecc):
r"""True anomaly from eccentric anomaly.
.. versionadded:: 0.4.0
Parameters
----------
E : float
Eccentric anomaly in radians.
ecc : float
Eccentricity.
Returns
-------
nu : float
True anomaly, between -π and π radians.
Warnings
--------
The true anomaly will be between -π and π radians,
no matter the value of the eccentric anomaly.
Notes
-----
The implementation uses the half-angle formula from [3]_:
.. math::
\nu = 2 \arctan \left( \sqrt{\frac{1 + e}{1 - e}} \tan{\frac{E}{2}} \right)
\in (-\pi, \pi]
"""
nu = 2 * np.arctan(np.sqrt((1 + ecc) / (1 - ecc)) * np.tan(E / 2))
return nu | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def F_to_nu(F, ecc):
r"""True anomaly from hyperbolic anomaly.
Parameters
----------
F : float
Hyperbolic anomaly.
ecc : float
Eccentricity (>1).
Returns
-------
nu : float
True anomaly.
Notes
-----
The implementation uses the half-angle formula from [3]_:
.. math::
\nu = 2 \arctan \left( \sqrt{\frac{e + 1}{e - 1}} \tanh{\frac{F}{2}} \right)
\in (-\pi, \pi]
"""
nu = 2 * np.arctan(np.sqrt((ecc + 1) / (ecc - 1)) * np.tanh(F / 2))
return nu | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def M_to_E(M, ecc):
"""Eccentric anomaly from mean anomaly.
.. versionadded:: 0.4.0
Parameters
----------
M : float
Mean anomaly in radians.
ecc : float
Eccentricity.
Returns
-------
E : float
Eccentric anomaly.
Notes
-----
This uses a Newton iteration on the Kepler equation.
"""
if -np.pi < M < 0 or np.pi < M:
E0 = M - ecc
else:
E0 = M + ecc
E = _newton_elliptic(E0, args=(M, ecc))
return E | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def M_to_F(M, ecc):
"""Hyperbolic anomaly from mean anomaly.
Parameters
----------
M : float
Mean anomaly in radians.
ecc : float
Eccentricity (>1).
Returns
-------
F : float
Hyperbolic anomaly.
Notes
-----
This uses a Newton iteration on the hyperbolic Kepler equation.
"""
F0 = np.arcsinh(M / ecc)
F = _newton_hyperbolic(F0, args=(M, ecc), maxiter=100)
return F | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def M_to_D(M):
"""Parabolic anomaly from mean anomaly.
Parameters
----------
M : float
Mean anomaly in radians.
Returns
-------
D : float
Parabolic anomaly.
Notes
-----
This uses the analytical solution of Barker's equation from [5]_.
"""
B = 3.0 * M / 2.0
A = (B + (1.0 + B**2) ** 0.5) ** (2.0 / 3.0)
D = 2 * A * B / (1 + A + A**2)
return D | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def E_to_M(E, ecc):
r"""Mean anomaly from eccentric anomaly.
.. versionadded:: 0.4.0
Parameters
----------
E : float
Eccentric anomaly in radians.
ecc : float
Eccentricity.
Returns
-------
M : float
Mean anomaly.
Warnings
--------
The mean anomaly will be outside of (-π, π]
if the eccentric anomaly is.
No validation or wrapping is performed.
Notes
-----
The implementation uses the plain original Kepler equation:
.. math::
M = E - e \sin{E}
"""
M = E - ecc * np.sin(E)
return M | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def F_to_M(F, ecc):
r"""Mean anomaly from eccentric anomaly.
Parameters
----------
F : float
Hyperbolic anomaly.
ecc : float
Eccentricity (>1).
Returns
-------
M : float
Mean anomaly.
Notes
-----
As noted in [5]_, by manipulating
the parametric equations of the hyperbola
we can derive a quantity that is equivalent
to the eccentric anomaly in the elliptic case:
.. math::
M = e \sinh{F} - F
"""
M = ecc * np.sinh(F) - F
return M | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def D_to_M(D):
r"""Mean anomaly from parabolic anomaly.
Parameters
----------
D : float
Parabolic anomaly.
Returns
-------
M : float
Mean anomaly.
Notes
-----
We use this definition:
.. math::
M = B + \frac{B^3}{3}
Notice that M < ν until ν ~ 100 degrees,
then it reaches π when ν ~ 120 degrees,
and grows without bounds after that.
Therefore, it can hardly be called an "anomaly"
since it is by no means an angle.
"""
M = D + D**3 / 3
return M | poliastro/poliastro | [
713,
256,
713,
128,
1372947285
] |
def __init__(self):
self.api = DoubanAPI(flush=False)
self._applied = {}
self._users = {} | acrazing/dbapi | [
25,
9,
25,
1,
1493312648
] |
def handle_user(self, user_alias):
self.join_user_groups(user_alias)
users = self.api.people.list_contacts()['results']
for user in users:
if self._users.get(user['alias'], None) is None:
self.handle_user(user['alias'])
self._users[user['alias']] = True
time.sleep(30)
else:
print('skip user: %s' % (user['alias'])) | acrazing/dbapi | [
25,
9,
25,
1,
1493312648
] |
def music(name):
print 'I am listening to music {0}'.format(name)
time.sleep(1) | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def movie(name):
print 'I am watching movie {0}'.format(name)
time.sleep(5) | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def single_thread():
for i in range(10):
music(i)
for i in range(2):
movie(i) | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def multi_thread():
# 线程列表
threads = []
for i in range(10):
# 创建一个线程,target参数为任务处理函数,args为任务处理函数所需的参数元组
threads.append(threading.Thread(target = music,args = (i,)))
for i in range(2):
threads.append(threading.Thread(target = movie,args = (i,))) | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def use_pool():
# 设置线程池大小为20,如果不设置,默认值是CPU核心数
pool = Pool(20)
pool.map(movie,range(2))
pool.map(music,range(10))
pool.close()
pool.join() | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def download_using_single_thread(urls):
resps = []
for url in urls:
resp = requests.get(url)
resps.append(resp)
return resps | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def download_using_multi_thread(urls):
threads = []
for url in urls:
threads.append(threading.Thread(target = requests.get,args = (url,)))
for t in threads:
t.setDaemon(True)
t.start()
for t in threads:
t.join() | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def download_using_pool(urls):
pool = Pool(20)
# 第一个参数为函数名,第二个参数一个可迭代对象,为函数所需的参数列表
resps = pool.map(requests.get,urls)
pool.close()
pool.join()
return resps | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def main():
# 测试单线程
# single_thread()
# 输出:
'''
I am listening to music 0
I am listening to music 1
I am listening to music 2
I am listening to music 3
I am listening to music 4
I am listening to music 5
I am listening to music 6
I am listening to music 7
I am listening to music 8
I am listening to music 9
I am watching movie 0
I am watching movie 1
[finished function:single_thread in 20.14s]
''' | dnxbjyj/python-basic | [
1,
4,
1,
11,
1501510345
] |
def to_bool(val):
"""Take a string representation of true or false and convert it to a boolean
value. Returns a boolean value or None, if no corresponding boolean value
exists.
"""
bool_states = {'true': True, 'false': False, '0': False, '1': True}
if not val:
return None
if isinstance(val, bool):
return val
val = str(val)
val = val.strip().lower()
return bool_states.get(val) | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
def write_dict(val):
return ",".join('='.join([str(k),str(v)]) for k,v in val.items()) | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
def read_list(val):
if isinstance(val, list):
return val
if not val:
return []
return val.split(',') | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
def copy_list(val):
return val[:] | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
def write_area(val):
if isinstance(val, basestring):
return val
return val.name | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
def write_merchandise(val):
lst = []
for dicts in val:
if dicts.get('keywords'):
del dicts['keywords']
lst.append(write_dict(dicts))
return '<>'.join(lst) | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
def write_json(val):
return json.dumps(val) | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
def read_int_dict(val):
d = {}
if val:
for a in val.split(','):
key, val = a.split('=')
d[key] = int(val)
return d | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
def read_damage(val):
dmg = []
if val:
for d in val.split('|'):
dmg.append(Damage(d))
return dmg | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
def read_channels(val):
d = {}
for pair in val.split(','):
k,v = pair.split('=')
d[k] = to_bool(v)
return d | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
def write_location(val):
if val:
return '%s,%s' % (val.area.name, val.id)
return None | shinymud/ShinyMUD | [
40,
10,
40,
38,
1272249483
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.