blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
880fcd0c207f5c5cc5664e89ff0c6d94f5842e7d
583194153161233874ae069adb9e8ffeb8442262
/authentication/admin.py
1c2e0b497ed34ed5189d522420a782a2780214dc
[]
no_license
AlekseiChirkov/meso
75faa7f9f83b9c9a88b9cf180a8bd140244af086
1a1c544d0533736c68b3c21706534f6f8a6d2505
refs/heads/main
2023-02-17T18:59:08.756122
2021-01-12T09:57:08
2021-01-12T09:57:08
325,181,058
0
1
null
2021-01-12T09:57:09
2020-12-29T03:57:28
Python
UTF-8
Python
false
false
230
py
from django.contrib import admin # Register your models here. from .models import User class UserAdmin(admin.ModelAdmin): list_display = ['id', 'email', 'auth_provider', 'created_at'] admin.site.register(User, UserAdmin)
[ "noorsultan.mamataliev@gmail.com" ]
noorsultan.mamataliev@gmail.com
227ede342f7bfe595de25dfa2cc02ac4fb1a043f
d4889901b6337ede68d2dee42d50c76f184ffe98
/generate_figures/fig2/vs.py
7fd5419900eb79905720c168d7913082dae4f6fc
[]
no_license
ModelDBRepository/231105
41b473ed06f46d7b8d7772984ffeb65c7c4d36da
c7c1697acb810bb6d55c6f7b97804b9c671ed9fb
refs/heads/master
2020-05-29T18:28:50.083115
2019-05-31T02:07:48
2019-05-31T02:07:48
189,299,894
0
0
null
null
null
null
UTF-8
Python
false
false
2,030
py
#!/usr/bin/python # This program plots the firing rate nu_I vs. Isyn_E-I_syn_I . import sys import os import math def read_fr(frI, cvI, ffrIx): for line_read in ffrIx: line_list = line_read.split() fr_val = float(line_list[1]) cv_val = float(line_list[7]) frI.append(fr_val) cvI.append(cv_val) def read_synvar(synvarIT, synvarII, fzmpx): for line_read in fzmpx: line_list = line_read.split() VsIT_val = -float(line_list[5]) synvarIT.append(VsIT_val) VsII_val = -float(line_list[6]) synvarII.append(VsII_val) # main #suffix = str(sys.argv[1]); #print 'suffix=',suffix suffix = 'b2b' #suffix = 'b2e' #'b2ra' ffri = open('tc.fri.' + suffix, 'r') fzmp = open('tc.zmp.' + suffix, 'r') ffis = open('vs.fis.' + suffix, 'w') ffcv = open('vs.fcv.' + suffix, 'w') fout = open('vs.out.' + suffix, 'w') Isnic = 0.7328 VsynE = 0.0 tsynE = 2.0 VsynI = -85.0 tsynI = 3.0 KIT = 75.0 gIT = 0.2 * 4 KII = 25.0 gII = 0.55 * 4 gsynIT = gIT / (math.sqrt(KIT) * tsynE) gsynII = gII / (math.sqrt(KII) * tsynI) JIT = gsynIT JII = gsynII print 'gsynIT=', gsynIT, ' JIT=', JIT, 'gsynII=', gsynII, ' JII=', JII frI = [] cvI = [] read_fr(frI, cvI, ffri) synvarIT = [] synvarII = [] read_synvar(synvarIT, synvarII, fzmp) non = len(frI) for ion in range(0, non): Jsitx = JIT * synvarIT[ion] Jsiix = JII * synvarII[ion] ffis.write('{0:g} {1:g} {2:g} {3:g} {4:g} {5:g} {6:d}\n'.format( \ Jsitx + Jsiix, frI[ion], Jsitx, Jsiix, synvarIT[ion], synvarII[ion], ion+1)) ffcv.write('{0:g} {1:g}\n'.format(frI[ion], cvI[ion])) ffis.write(' \n') for ion in range(0, non): Jsitx = JIT * synvarIT[ion] ffis.write('{0:g} {1:g}\n'.format(Jsitx, frI[ion])) ffis.write(' \n') for ion in range(0, non): Jsiix = JII * synvarII[ion] ffis.write('{0:g} {1:g}\n'.format(Jsiix, frI[ion])) ffri.close() fzmp.close() ffis.close() ffcv.close() fout.close()
[ "tom.morse@yale.edu" ]
tom.morse@yale.edu
211a480a8f12fd78e6c18298b4314762a0b8ea65
3327a87cefa2275bd0ba90a500444f3494b14fdf
/captainhcg/py/222-count-complete-tree-nodes.py
c63c98539d7003e40cab6734a601b99ef068043e
[]
no_license
captainhcg/leetcode-in-py-and-go
e1b56f4228e0d60feff8f36eb3d457052a0c8d61
88a822c48ef50187507d0f75ce65ecc39e849839
refs/heads/master
2021-06-09T07:27:20.358074
2017-01-07T00:23:10
2017-01-07T00:23:10
61,697,502
1
0
null
null
null
null
UTF-8
Python
false
false
506
py
class Solution(object): def countNodes(self, root): """ :type root: TreeNode :rtype: int """ left_h = right_h = 0 lnd = rnd = root while lnd: left_h += 1 lnd = lnd.left while rnd: right_h += 1 rnd = rnd.right if left_h == right_h: return 2 ** left_h - 1 else: return 1 + self.countNodes(root.left) + self.countNodes(root.right)
[ "noreply@github.com" ]
captainhcg.noreply@github.com
510a31c918cf293f006bfecde11e6d76c5d2aa37
08a0a5603acb4711fa25acfc3b7034f104d993b0
/jump-game-ii/Solution.8415759.py
d7202d95ee0c24d813579f558af5a02543841586
[ "MIT" ]
permissive
rahul-ramadas/leetcode
401fe2df2f710c824264cc0538f5f2aa8bbe383e
6c84c2333a613729361c5cdb63dc3fc80203b340
refs/heads/master
2020-05-30T07:17:07.311215
2016-11-01T05:27:34
2016-11-01T05:27:34
22,866,344
0
0
null
null
null
null
UTF-8
Python
false
false
488
py
class Solution: def jump(self, A): if len(A) == 1: return 0 steps = 0 farthest = 0 next_farthest = 0 for current in xrange(len(A)): if current > farthest: farthest = next_farthest steps += 1 next_farthest = max(next_farthest, current + A[current]) if next_farthest >= (len(A) - 1): return steps + 1 return -1
[ "tripshock@gmail.com" ]
tripshock@gmail.com
f9eb340e62736e865ce4d10ba52f23207a4e491d
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2927/60608/259827.py
2edeb3c30f2fdf138f74e200b06069554769cd62
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
810
py
import math def isInside(a1, b1, a2, b2, x, y): if a1 <= x <= a2 and b2 <= y <= b1: return True else: return False def func31(): arr = list(map(int, input().split())) a1 = math.sin(math.pi / 4) * arr[1] b1 = math.cos(math.pi / 4) * arr[1] a2 = math.cos(math.pi / 4) * arr[0] + math.sin(math.pi / 4) * (arr[0] - arr[1]) b2 = -math.sin(math.pi / 4) * arr[0] + math.cos(math.pi / 4) * (arr[0] - arr[1]) m = eval(input()) for _ in range(0, m): arr = list(map(int, input().split())) x = math.cos(math.pi / 4) * arr[0] + math.sin(math.pi / 4) * arr[1] y = -math.sin(math.pi / 4) * arr[0] + math.cos(math.pi / 4) * arr[1] if isInside(a1, b1, a2, b2, x, y): print("YES") else: print("NO") func31()
[ "1069583789@qq.com" ]
1069583789@qq.com
eebd75b28665ca91cb500de5634618a87885eacc
5b771c11e8967038025376c6ec31962ca90748dd
/resturant/Resturant/src/blog/migrations/0004_comment.py
f07e3f8d6a9a53ea6011d24313d8a9f81336e5e0
[]
no_license
AsemAntar/Django_Projects
7135eca3b4bcb656fc88e0838483c97d7f1746e1
4141c2c7e91845eec307f6dd6c69199302eabb16
refs/heads/master
2022-12-10T06:32:35.787504
2020-05-26T14:43:01
2020-05-26T14:43:01
216,863,494
0
0
null
2022-12-05T13:31:53
2019-10-22T16:47:28
Python
UTF-8
Python
false
false
965
py
# Generated by Django 3.0.5 on 2020-05-17 09:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('blog', '0003_post_tags'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.TextField()), ('created', models.DateTimeField(default=django.utils.timezone.now)), ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blog.Post')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
[ "asemantar@gmail.com" ]
asemantar@gmail.com
45a6c789ab4c46a1a8e9f75786bd68dbf3e2c43e
7769cb512623c8d3ba96c68556b2cea5547df5fd
/mmdet/models/losses/smooth_l1_loss.py
bc340730b2ec0db938508dfc94e71369484d1918
[ "MIT" ]
permissive
JialeCao001/D2Det
0e49f4c76e539d574e46b02f278242ca912c31ea
a76781ab624a1304f9c15679852a73b4b6770950
refs/heads/master
2022-12-05T01:00:08.498629
2020-09-04T11:33:26
2020-09-04T11:33:26
270,723,372
312
88
MIT
2020-07-08T23:53:23
2020-06-08T15:37:35
Python
UTF-8
Python
false
false
1,288
py
import torch import torch.nn as nn from ..registry import LOSSES from .utils import weighted_loss @weighted_loss def smooth_l1_loss(pred, target, beta=1.0): assert beta > 0 assert pred.size() == target.size() and target.numel() > 0 diff = torch.abs(pred - target) loss = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta) return loss @LOSSES.register_module class SmoothL1Loss(nn.Module): def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0): super(SmoothL1Loss, self).__init__() self.beta = beta self.reduction = reduction self.loss_weight = loss_weight def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None, **kwargs): assert reduction_override in (None, 'none', 'mean', 'sum') reduction = ( reduction_override if reduction_override else self.reduction) loss_bbox = self.loss_weight * smooth_l1_loss( pred, target, weight, beta=self.beta, reduction=reduction, avg_factor=avg_factor, **kwargs) return loss_bbox
[ "connor@tju.edu.cn" ]
connor@tju.edu.cn
130e3ec189c725c6c0fbbcedda199db9b4d2f77a
d364123a0655bff7e9d725382934fe2c15b5bfc4
/Crawler/two/xingneng.py
ae3a6428bc0601f76f83c19217cd42d06832e0f5
[]
no_license
yuan1093040152/SeleniumTest
88d75361c8419354f56856c326f843a0a89d7ca6
d155b98702bc46c174499042b43257696b861b5e
refs/heads/master
2023-08-31T15:00:25.415642
2023-08-30T09:26:42
2023-08-30T09:26:42
227,269,300
0
1
null
null
null
null
UTF-8
Python
false
false
1,741
py
#coding=utf-8 ''' Created on 2018年3月15日 @author: 唐路 ''' fields = ('area','population','iso','country' ,'capital', 'continent','tld','currency_code','currency_name','phone','postal_code_format','postal_code_regex','languages','neighbours') import re,time import lxml.html import lxml.cssselect from re_grab import download from bs4 import BeautifulSoup def re_scraper(html,fields): results = {} for field in fields: results[field] = re.findall('<tr id="places_%s__row">.*?<td class="w2p_fw">(.*?)</td>'%field,html)[0] return results def bs_scraper(html,fields): soup = BeautifulSoup(html,'html.parser') results = {} for field in fields: results[field] = soup.find('table').find('tr',id='places_%s__row'%field).find('td',attrs={'class':"w2p_fw"}).text return results def lxml_scraper(html,fields): tree = lxml.html.fromstring(html) results = {} for field in fields: results[field] = tree.cssselect('table>tr#places_%s__row > td.w2p_fw'%field)[0].text_content() return results num_iteraions = 1000 url = 'http://example.webscraping.com/places/default/view/China-47' html = download(url) for name ,scraper in [('Regular expressions',re_scraper),('BeauifulSoup',bs_scraper),('Lxml',lxml_scraper)]: start = time.time() for i in range(num_iteraions): if scraper == re_scraper: re.purge() result = scraper(html,fields) assert(result['area'] == '9,596,960 square kilometres') end = time.time() print '%s: %.2f seconds'%(name,end-start) # url = 'http://example.webscraping.com/places/default/view/China-47' # html = download(url) # # print html # results = lxml_scraper(html,fields) # print results
[ "1093040152@qq.com" ]
1093040152@qq.com
c8654d745ab7e9b8739b049d093a243c901b2dec
778d942f39abfb74b395d521af1cabfa1487c91c
/Greedy/JobSequencingProblem.py
aec789872cc841135a035f34f279a4553e9cc587
[]
no_license
yashwanthguguloth24/Algorithms
ff80f47ef20be23da245c737640df0799151fdd1
0b9c7540f09f9d5792f5058ef901d588418f4f27
refs/heads/master
2023-07-09T16:51:17.174314
2021-08-08T18:47:43
2021-08-08T18:47:43
279,512,532
1
0
null
null
null
null
UTF-8
Python
false
false
1,494
py
''' Given a set of N jobs where each job i has a deadline and profit associated to it. Each job takes 1 unit of time to complete and only one job can be scheduled at a time. We earn the profit if and only if the job is completed by its deadline. The task is to find the maximum profit and the number of jobs done. Input Format: Jobs will be given in the form (Job id, Deadline, Profit) associated to that Job. Example 1: Input: N = 4 Jobs = (1,4,20)(2,1,10)(3,1,40)(4,1,30) Output: 2 60 Explanation: 2 jobs can be done with maximum profit of 60 (20+40). ''' # code by yashwanth def JobScheduling(Jobs,n): ''' :param Jobs: list of "Job" class defined in driver code, with "profit" and "deadline". :param n: total number of jobs :return: A list of size 2 having list[0] = count of jobs and list[1] = max profit ''' ''' { class Job:. def __init__(self,profit=0,deadline=0): self.profit = profit self.deadline = deadline self.id = 0 } ''' profit = 0 slots = [False]*n Jobs = sorted(Jobs,key = lambda x : x.profit,reverse = True) for i in range(n): for j in range(min(n,Jobs[i].deadline)-1,-1,-1): if slots[j] == False: slots[j] = True profit += Jobs[i].profit break num_jobs = 0 for k in range(n): if slots[k]: num_jobs += 1 res = [num_jobs,profit] return res
[ "noreply@github.com" ]
yashwanthguguloth24.noreply@github.com
09d31f3cfb420681b24d39ce5b6d98b82b443b5b
c3082eb2adc43b311dd3c9ff16fd3ed9df85f266
/python/examples/advanced/slow.py
f2e6b6f91e806518083d6f82e06462b77c31f239
[]
no_license
szabgab/slides
78818c7138331b3ba9e221c81da3678a46efe9b3
63bba06678554db737602f2fbcd6510c36037e8a
refs/heads/main
2023-08-31T07:13:51.536711
2023-08-29T13:17:59
2023-08-29T13:17:59
122,212,527
87
69
null
2023-05-19T06:55:11
2018-02-20T14:57:03
Python
UTF-8
Python
false
false
734
py
import random def f(): n = 0 for i in range(30): n += random.random() return n def g(): return random.random() * 30 def main(n): text = get_str(n) #print(str) text_sorted = sort(text) return text_sorted def sort(s): chars = list(s) for i in reversed(range(len(chars))): a = f() b = g() for j in range(i, len(chars)-1): swap(chars, j) return ''.join(chars) def get_str(n): text = '' for i in range(1, n): text += chr(65 + random.randrange(0, 26)) return text def swap(lst, loc): if lst[loc] > lst[loc + 1]: lst[loc], lst[loc + 1] = lst[loc + 1], lst[loc] if __name__ == '__main__': print(main(1000))
[ "gabor@szabgab.com" ]
gabor@szabgab.com
d4fc9bc42d28a4ae8358c51ca58861c999d614ed
c42672aeac984ab3f57d840710e145f4e918ba01
/nasws/cnn/policy/darts_policy/train.py
f9bbbe1987129dcdc49a1d3205830cfc4856a047
[ "MIT" ]
permissive
kcyu2014/nas-landmarkreg
00212b6015d1fef3e7198bfa596fa69a898167c2
a00c3619bf4042e446e1919087f0b09fe9fa3a65
refs/heads/main
2023-07-21T19:52:19.392719
2021-08-24T09:37:24
2021-08-24T09:37:24
350,368,390
10
0
null
null
null
null
UTF-8
Python
false
false
6,295
py
import os import sys import time import glob import numpy as np import torch # import nasws.cnn.utils import utils import logging import argparse import torch.nn as nn import genotypes import torch.utils import torchvision.datasets as dset import torch.backends.cudnn as cudnn from torch.autograd import Variable from model import NetworkCIFAR as Network parser = argparse.ArgumentParser("cifar") parser.add_argument('--data', type=str, default='../data', help='location of the data corpus') parser.add_argument('--batch_size', type=int, default=96, help='batch size') parser.add_argument('--learning_rate', type=float, default=0.025, help='init learning rate') parser.add_argument('--momentum', type=float, default=0.9, help='momentum') parser.add_argument('--weight_decay', type=float, default=3e-4, help='weight decay') parser.add_argument('--report_freq', type=float, default=50, help='report frequency') parser.add_argument('--gpu', type=int, default=0, help='gpu device id') parser.add_argument('--epochs', type=int, default=600, help='num of training epochs') parser.add_argument('--init_channels', type=int, default=36, help='num of init channels') parser.add_argument('--layers', type=int, default=20, help='total number of layers') parser.add_argument('--model_path', type=str, default='saved_models', help='path to save the model') parser.add_argument('--auxiliary', action='store_true', default=False, help='use auxiliary tower') parser.add_argument('--auxiliary_weight', type=float, default=0.4, help='weight for auxiliary loss') parser.add_argument('--cutout', action='store_true', default=False, help='use cutout') parser.add_argument('--cutout_length', type=int, default=16, help='cutout length') parser.add_argument('--drop_path_prob', type=float, default=0.2, help='drop path probability') parser.add_argument('--save', type=str, default='EXP', help='experiment name') parser.add_argument('--seed', type=int, default=0, help='random seed') parser.add_argument('--arch', type=str, default='DARTS', help='which architecture to use') parser.add_argument('--grad_clip', type=float, default=5, help='gradient clipping') args = parser.parse_args() args.save = 'iclr-resubmission/eval-{}-{}'.format(args.save, time.strftime("%Y%m%d-%H%M%S")) utils.create_exp_dir(args.save, scripts_to_save=glob.glob('*.py')) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') fh = logging.FileHandler(os.path.join(args.save, 'log.txt')) fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) CIFAR_CLASSES = 10 def main(): if not torch.cuda.is_available(): logging.info('no gpu device available') sys.exit(1) np.random.seed(args.seed) torch.cuda.set_device(args.gpu) cudnn.benchmark = True torch.manual_seed(args.seed) cudnn.enabled=True torch.cuda.manual_seed(args.seed) logging.info('gpu device = %d' % args.gpu) logging.info("args = %s", args) genotype = eval("genotypes.%s" % args.arch) model = Network(args.init_channels, CIFAR_CLASSES, args.layers, args.auxiliary, genotype) model = model.cuda() logging.info("param size = %fMB", utils.count_parameters_in_MB(model)) criterion = nn.CrossEntropyLoss() criterion = criterion.cuda() optimizer = torch.optim.SGD( model.parameters(), args.learning_rate, momentum=args.momentum, weight_decay=args.weight_decay ) train_transform, valid_transform = utils._data_transforms_cifar10(args) train_data = dset.CIFAR10(root=args.data, train=True, download=True, transform=train_transform) valid_data = dset.CIFAR10(root=args.data, train=False, download=True, transform=valid_transform) train_queue = torch.utils.data.DataLoader( train_data, batch_size=args.batch_size, shuffle=True, pin_memory=True, num_workers=2) valid_queue = torch.utils.data.DataLoader( valid_data, batch_size=args.batch_size, shuffle=False, pin_memory=True, num_workers=2) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, float(args.epochs)) for epoch in range(args.epochs): scheduler.step() logging.info('epoch %d lr %e', epoch, scheduler.get_lr()[0]) model.drop_path_prob = args.drop_path_prob * epoch / args.epochs train_acc, train_obj = train(train_queue, model, criterion, optimizer) logging.info('train_acc %f', train_acc) valid_acc, valid_obj = infer(valid_queue, model, criterion) logging.info('valid_acc %f', valid_acc) utils.save(model, os.path.join(args.save, 'weights.pt')) def train(train_queue, model, criterion, optimizer): objs = utils.AverageMeter() top1 = utils.AverageMeter() top5 = utils.AverageMeter() model.train() for step, (input, target) in enumerate(train_queue): input = Variable(input).cuda() target = Variable(target).cuda(async=True) optimizer.zero_grad() logits, logits_aux = model(input) loss = criterion(logits, target) if args.auxiliary: loss_aux = criterion(logits_aux, target) loss += args.auxiliary_weight*loss_aux loss.backward() nn.utils.clip_grad_norm(model.parameters(), args.grad_clip) optimizer.step() prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5)) n = input.size(0) objs.update(loss.data[0], n) top1.update(prec1.data[0], n) top5.update(prec5.data[0], n) if step % args.report_freq == 0: logging.info('train %03d %e %f %f', step, objs.avg, top1.avg, top5.avg) return top1.avg, objs.avg def infer(valid_queue, model, criterion): objs = utils.AverageMeter() top1 = utils.AverageMeter() top5 = utils.AverageMeter() model.eval() for step, (input, target) in enumerate(valid_queue): input = Variable(input, volatile=True).cuda() target = Variable(target, volatile=True).cuda(async=True) logits, _ = model(input) loss = criterion(logits, target) prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5)) n = input.size(0) objs.update(loss.data[0], n) top1.update(prec1.data[0], n) top5.update(prec5.data[0], n) if step % args.report_freq == 0: logging.info('valid %03d %e %f %f', step, objs.avg, top1.avg, top5.avg) return top1.avg, objs.avg if __name__ == '__main__': main()
[ "16794548+kcyu2014@users.noreply.github.com" ]
16794548+kcyu2014@users.noreply.github.com
1ce1feb6bf75a790c18144cc6885d7f674924843
2c3da6e0bddf55d64d650040bbf286c47b31811a
/c语言中文网python教程/Python itertools模块:生成迭代器(实例分析).py
24c70c2923eb597f7aa59b8fc68122a78a8ba190
[ "MIT" ]
permissive
Bngzifei/PythonNotes
76bd53db3033a9c51ab4bdd727842cd89607b584
01590e1b6c1bc0f04aa2d355fa2553c04cce27f2
refs/heads/master
2023-02-04T06:49:00.725463
2020-12-15T09:26:40
2020-12-15T09:26:40
155,154,662
1
2
MIT
2020-09-08T01:30:19
2018-10-29T05:02:48
Python
UTF-8
Python
false
false
7,147
py
# Python itertools模块:生成迭代器(实例分析) """ itertools模块主要包含了一些用于生成迭代器的函数.在在 Python 的交互式解释器中先导入 itertools 模块,然后输入 [e for e in dir(itertools) if not e.startswith('_')] 命令, 即可看到该模块所包含的全部属性和函数: >>> [e for e in dir(itertools) if not e.startswith('_')] ['accumulate', 'chain', 'combinations', 'combinations_with_replacement', 'compress', 'count', 'cycle', 'dropwhile', 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee', 'zip_longest'] 从上面的输出结果可以看出,itertools模块中的不少函数都可以用于生成迭代器. 先看itertools模块中三个生成无限迭代器的函数: 1.count(start,[step]):生成 start, start+step, start+2*step,... 的迭代器,其中 step 默认为 1。 比如使用 count(10) 生成的迭代器包含:10, 11 , 12 , 13, 14,... 2.cycle(p):对序列 p 生成无限循环 p0, p1,..., p0, p1,... 的迭代器。比如使用 cycle('ABCD') 生成的迭代器包含:A,B,C,D,A,B,C,D,... 3.repeat(elem [,n]):生成无限个 elem 元素重复的迭代器,如果指定了参数 n,则只生成 n 个 elem 元素。 比如使用 repeat(10, 3) 生成的迭代器包含:10, 10, 10。 """ import itertools as it # count(10,3)生成10,13,16...迭代器 for e in it.count(10, 3): print(e) # 用于跳出无限循环 if e > 20: break print("---------") my_counter = 0 # cycle用途对序列生成无限循环的迭代器 for e in it.cycle(["python","ruby","swift"]): print(e) # 用于跳出无限循环 my_counter += 1 if my_counter > 7: break print("-------") # repeat用于生成n个元素重复的迭代器 for e in it.repeat("python",3): print(e) """ 在 itertools 模块中还有一些常用的迭代器函数,如下所示: accumulate(p[,func]):默认生成根据序列 p 元素累加的迭代器,p0, p0+p1, p0+p1+p2,...序列,如果指定了 func 函数,则用 func 函数来计算下一个元素的值。 chain(p, q, ...):将多个序列里的元素“链”在一起生成新的序列。 compress(data, selectors):根据 selectors 序列的值对 data 序列的元素进行过滤。如果 selector[0] 为真,则保留 data[0];如果 selector[1] 为真,则保留 data[1]......依此类推。 dropwhile(pred, seq):使用 pred 函数对 seq 序列进行过滤,从 seq 中第一个使用 pred 函数计算为 False 的元素开始,保留从该元素到序列结束的全部元素。 takewhile(pred, seq):该函数和上一个函数恰好相反。使用 pred 函数对 seq 序列进行过滤,从 seq 中第一个使用 pred 函数计算为 False 的元素开始,去掉从该元素到序列结束的全部元素。 filterfalse(pred, seq):使用 pred 函数对 seq 序列进行过滤,保留 seq 中使用 pred 计算为 True 的元素。比如 filterfalse(lambda x:x%2, range(10)),得到 0, 2, 4, 6, 8。 islice(seq, [start,] stop [, step]):其功能类似于序列的 slice 方法,实际上就是返回 seq[start:stop:step] 的结果。 starmap(func, seq):使用 func 对 seq 序列的每个元素进行计算,将计算结果作为新的序列元素。当使用 func 计算序列元素时,支持序列解包。比如 seq 序列的元素长度为 3,那么 func 可以是一个接收三个参数的函数,该函数将会根据这三个参数来计算新序列的元素。 zip_longest(p,q,...):将 p、q 等序列中的元素按索引合并成元组,这些元组将作为新序列的元素。 上面这些函数的测试程序如下: """ print("----------") import itertools as it # 默认使用累加的方式计算下一个元素的值 for e in it.accumulate(range(6)): print(e,end=",") print("\n---------------") # 使用x*y的方式来计算迭代器下一个元素的值 for e in it.accumulate(range(1,6),lambda x,y:x*y): print(e,end=", ") print("\n-----------------") # 将两个序列"链接"在一起,生成新的迭代器 for e in it.chain(["a","b"],["kotlin","swift"]): print(e,end=", ") print("\n------------------") # 根据第二个序列来筛选第一个序列的元素. # 由于第二个序列只有中间两个元素为1,因此前一个序列只保留中间两个元素 for e in it.compress(["a","b","kotlin","swift"],[0,1,1,0]): print(e,end=", ") # b, kotlin print("\n-----------------------") # 获取序列中从长度不小于4的元素开始,到结束的所有元素(即保留长度大于4位置开始到结束的所有元素) for e in it.dropwhile(lambda x:len(x)<4,["a","b","kotlin","x","y"]): print(e,end=", ") # 只有: 'Kotlin', 'x', 'y' print("\n----------------") # 去掉序列中从长度不小于4的元素开始,到结束的所有元素 for e in it.takewhile(lambda x:len(x)<4,["a","b","kotlin","x","y"]): print(e,end=", ") # 只有: 'a', 'b' print("\n----------------") # 只保留序列中从长度不小于4的元素 for e in it.filterfalse(lambda x:len(x)<4,["a","b","kotlin","x","y"]): print(e,end=", ") # 只有: 'Kotlin' print("\n----------------------") # 使用pow函数对原序列的元素进行计算,将计算结果作为新序列的元素 for e in it.starmap(pow, [(2,5),(3,2),(10,3)]): print(e,end=", ") print("\n------------------------") # 将"ABCD","xy"的元素按索引合并成元组,这些元组作为新序列的元素 # 长度不够的序列元素使用"-"字符代替 for e in it.zip_longest("ABCD","xy",fillvalue="-"): print(e,end=", ") # # ('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-') """ 在 itertools 模块中还有一些用于生成排列组合的工具函数: product(p, q, ...[repeat= 1)]:用序列 p 、q 、... 中的元素进行排列组合,就相当于使用嵌套循环组合。 permutations(p[, r]):从序列 p 中取出 r 个元素组成全排列,将排列得到的元组作为新迭代器的元素。 combinations(p, r):从序列 p 中取出 r 个元素组成全组合,元素不允许重复,将组合得到的元组作为新迭代器的元素。 combinations with_replacement(p, r),从序列 p 中取出 r 个元素组成全组合,元素允许重复, 将组合得到的元组作为新迭代器的元素。 如下程序示范了上面4个函数的用法: """ import itertools as it print("\n-------") # 使用两个序列进行排列组合 for e in it.product("AB","CD"): print("".join(e),end=",") # AC,AD,BC,BD print("\n------------") # 使用一个序列,重复两次进行全排列 for e in it.product("AB",repeat=2): print("".join(e),end=", ") print("\n-------------------") # 从序列中取2个元素进行排列 for e in it.permutations("ABCD",2): print("".join(e),end=", ") print("\n------------------") # 从序列中取2个元素进行组合,不允许重复 for e in it.combinations("ABCD", 2): print("".join(e),end=", ") print("\n------------------------") """ 上面程序用到了一个字符串的join()方法,该方法用于将元组的所有元素连接成一个字符串. """
[ "bngzifei@gmail.com" ]
bngzifei@gmail.com
52920abfc6f261e127be3ca99e74ed82138ce10e
5761eca23af5ad071a9b15e2052958f2c9de60c0
/generated-stubs/allauth/socialaccount/providers/bitbucket_oauth2/provider.pyi
100feb2b8afd2da0c647bb49cce0b3e58fab5d68
[]
no_license
d-kimuson/drf-iframe-token-example
3ed68aa4463531f0bc416fa66d22ee2aaf72b199
dd4a1ce8e38de9e2bf90455e3d0842a6760ce05b
refs/heads/master
2023-03-16T13:52:45.596818
2021-03-09T22:09:49
2021-03-09T22:09:49
346,156,450
0
0
null
null
null
null
UTF-8
Python
false
false
575
pyi
from allauth.socialaccount.providers.base import ProviderAccount as ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider as OAuth2Provider from typing import Any class BitbucketOAuth2Account(ProviderAccount): def get_profile_url(self): ... def get_avatar_url(self): ... def to_str(self): ... class BitbucketOAuth2Provider(OAuth2Provider): id: str = ... name: str = ... account_class: Any = ... def extract_uid(self, data: Any): ... def extract_common_fields(self, data: Any): ... provider_classes: Any
[ "d-kimuson@gmail.com" ]
d-kimuson@gmail.com
3cd8b6972a27fcb26f2dea995651f24fa971773a
e2d23d749779ed79472a961d2ab529eeffa0b5b0
/gcloud/contrib/function/permissions.py
7c2a108a18154b28e3751cac04a29072152ab26b
[ "MIT", "BSD-3-Clause", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
manlucas/atom
9fa026b3f914e53cd2d34aecdae580bda09adda7
94963fc6fdfd0568473ee68e9d1631f421265359
refs/heads/master
2022-09-30T06:19:53.828308
2020-01-21T14:08:36
2020-01-21T14:08:36
235,356,376
0
0
NOASSERTION
2022-09-16T18:17:08
2020-01-21T14:04:51
Python
UTF-8
Python
false
false
1,234
py
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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. """ from django.utils.translation import ugettext_lazy as _ from auth_backend.resources.base import Action, NeverInitiateResource from auth_backend.backends.bkiam import BKIAMBackend function_center_resource = NeverInitiateResource( rtype='function_center', name=_(u"职能化中心"), scope_type='system', scope_id='bk_sops', scope_name=_(u"标准运维"), actions=[Action(id='view', name=_(u"查看"), is_instance_related=False)], backend=BKIAMBackend())
[ "lucaswang@canway.net" ]
lucaswang@canway.net
3fd1171ad91a14ad977ace1eb611c02b31a71019
ddb185b0cf581d85a1dd733a6d1e5d027ba3e0ca
/phase2/387.py
4ab3425dbedcd713562ef34c92f76e379fea962a
[]
no_license
GavinPHR/code
8a319e1223a307e755211b7e9b34c5abb00b556b
b1d8d49633db362bbab246c0cd4bd28305964b57
refs/heads/master
2020-05-16T04:09:19.026207
2020-04-30T10:00:06
2020-04-30T10:00:06
182,766,600
1
0
null
null
null
null
UTF-8
Python
false
false
382
py
# First Unique Character in a String import collections class Solution: def firstUniqChar(self, s: str) -> int: if not s: return -1 d = collections.Counter(s) i = 0 for c in s: if d[c] == 1: return i else: i += 1 return -1 s = Solution() print(s.firstUniqChar("loveleetcode"))
[ "gavinsweden@gmail.com" ]
gavinsweden@gmail.com
2f10e9f21d71eb1536fb53c92e38822aa53b0480
a8750439f200e4efc11715df797489f30e9828c6
/csAcademy/binary_array.py
40c9693298764e851e76be4a163f8a7a254efb4e
[]
no_license
rajlath/rkl_codes
f657174305dc85c3fa07a6fff1c7c31cfe6e2f89
d4bcee3df2f501349feed7a26ef9828573aff873
refs/heads/master
2023-02-21T10:16:35.800612
2021-01-27T11:43:34
2021-01-27T11:43:34
110,989,354
0
0
null
null
null
null
UTF-8
Python
false
false
1,298
py
''' Find Binary Array Time limit: 1000 ms Memory limit: 256 MB You have a binary array of length NN. For each index i (1 \leq i \leq N)i(1≤i≤N) you know the number of zeroes among the positions on the left side of ii and on the right side of ii, respectively. Find the array! Standard input The first line contains an integer NN, the length of the binary array. The second line contains NN integer values, where the ii-th value represents the number of zeroes among the positions on the left side of the ii-th index of the array. The third line contains NN integer values, where the ii-th value represents the number of zeroes among the positions on the right side of the ii-th index of the array. Standard output The first line will contain NN bits (00 or 11), representing the binary array. Constraints and notes 2 \leq N \leq 10^52≤N≤10 ​5 ​​ It is guaranteed that there is always at least one solution Input Output 5 0 1 1 1 2 1 1 1 0 0 01101 ''' lens = int(input()) arrL = [int(x) for x in input().split()] arrR = [int(x) for x in input().split()] for i in range(1, lens): if arrL[i] != arrL[i-1]: print(0, end="") else: print(1, end="") #arr = [0 if b != a else 1 for a, b in zip(arrL, arrL[1:])] print( 0 if arrR[-1] != arrR[-2] else 1, end="")
[ "raj.lath@gmail.com" ]
raj.lath@gmail.com
a561f92c4f4333b5258bc33ef7c64c6f1d3acb28
4cdd5813d20f40d525b4d418df2788fa72a394bf
/Leetcode/easy/invert-a-binary-tree.py
a00b8eb4764600bf5c8bc9a376fe2119c0737828
[ "MIT" ]
permissive
das-jishu/data-structures-basics-leetcode
9baa78b49cfc1b0f5c48ef961b85b4fa9ffaf0dd
9f877ba8ed1968c21c39ebeae611ba3c448a083a
refs/heads/master
2023-08-21T06:54:57.380306
2021-10-01T02:59:51
2021-10-01T02:59:51
298,940,500
23
21
MIT
2021-10-01T02:59:52
2020-09-27T02:52:50
Python
UTF-8
Python
false
false
916
py
""" # INVERT A BINARY TREE Invert a binary tree. Example: Input: 4 - - 2 7 - - - - 1 3 6 9 Output: 4 - - 7 2 - - - - 9 6 3 1 Trivia: This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off. """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return None if not root.left and not root.right: return root temp = self.invertTree(root.right) root.right = self.invertTree(root.left) root.left = temp return root
[ "das.jishu25@gmail.com" ]
das.jishu25@gmail.com
ae36ea6b3ea5163238fb1b53cb7a789fac529f36
ebd24e400986c57b4bb1b9578ebd8807a6db62e8
/InstaGrade-FormBuilder/xlsxwriter/test/sharedstrings/test_initialisation.py
053c1388226206274fb0df70e2a7a9877a33525b
[]
no_license
nate-parrott/ig
6abed952bf32119a536a524422037ede9b431926
6e0b6ac0fb4b59846680567150ce69a620e7f15d
refs/heads/master
2021-01-12T10:15:15.825004
2016-12-13T21:23:17
2016-12-13T21:23:17
76,399,529
1
0
null
null
null
null
UTF-8
Python
false
false
835
py
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2014, John McNamara, jmcnamara@cpan.org # import unittest from ...compatibility import StringIO from ...sharedstrings import SharedStrings class TestInitialisation(unittest.TestCase): """ Test initialisation of the SharedStrings class and call a method. """ def setUp(self): self.fh = StringIO() self.sharedstrings = SharedStrings() self.sharedstrings._set_filehandle(self.fh) def test_xml_declaration(self): """Test Sharedstrings xml_declaration()""" self.sharedstrings._xml_declaration() exp = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n""" got = self.fh.getvalue() self.assertEqual(got, exp)
[ "nateparro2t@gmail.com" ]
nateparro2t@gmail.com
e0b11893d0de06d4b3be2aaa5725db913e41379e
6ddcb131e5f2806acde46a525ff8d46bfbe0990e
/enaml/backends/qt/noncomponents/toolkit_items.py
a72749e2ac1d15a5b2158138eef276a442329617
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
agrawalprash/enaml
5ce1823188eb51e5b83117ebee6c3655f53e5157
96828b254ac9fdfa2e5b6b31eff93a4933cbc0aa
refs/heads/master
2021-01-15T23:35:21.351626
2012-09-05T03:40:07
2012-09-05T03:40:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
423
py
#------------------------------------------------------------------------------ # Copyright (c) 2012, Enthought, Inc. # All rights reserved. #------------------------------------------------------------------------------ from .qt_dock_manager import QtDockManager from .qt_icon import QtIcon from .qt_image import QtImage TOOLKIT_ITEMS = { 'DockManager': QtDockManager, 'Image': QtImage, 'Icon': QtIcon, }
[ "sccolbert@gmail.com" ]
sccolbert@gmail.com
8be1d1310a0658b39cd9f615911d05de1415385e
0444c96c6c428f75c72696159fb89633ec3ea34f
/backend/driver/migrations/0001_initial.py
c44b338ce03abd20124f390fc8f16f011c02b766
[]
no_license
crowdbotics-apps/juice-and-eatery-21638
03a690239baf56065ee44986dc845f8768f1d999
136357629b22a48ad06731a5a5f14f648052a93f
refs/heads/master
2022-12-27T14:03:23.949577
2020-10-17T21:57:34
2020-10-17T21:57:34
304,975,789
0
0
null
null
null
null
UTF-8
Python
false
false
2,540
py
# Generated by Django 2.2.16 on 2020-10-17 21:55 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("delivery_order", "0001_initial"), ] operations = [ migrations.CreateModel( name="DriverProfile", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("photo", models.URLField()), ("timestamp_created", models.DateTimeField(auto_now_add=True)), ("last_updated", models.DateTimeField(auto_now=True)), ("details", models.TextField(blank=True, null=True)), ( "user", models.OneToOneField( on_delete=django.db.models.deletion.CASCADE, related_name="driverprofile_user", to=settings.AUTH_USER_MODEL, ), ), ], ), migrations.CreateModel( name="DriverOrder", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("timestamp_created", models.DateTimeField(auto_now_add=True)), ( "driver", models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="driverorder_driver", to="driver.DriverProfile", ), ), ( "order", models.OneToOneField( on_delete=django.db.models.deletion.CASCADE, related_name="driverorder_order", to="delivery_order.Order", ), ), ], ), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
73ac9438958d2800fff63c4333e4bceb2498904c
afe04cd22c2a839668dd0f29c314cc4b35bc7345
/mayidaili_tool.py
9aecca25ec13ff9c9429250376ae07b45bfdebb6
[ "Apache-2.0" ]
permissive
343829084/base_function
1bded81816dcc9e18cbd36d1484be782931bec55
296aaf84bbfc084f9d27d84d4b300823a356e484
refs/heads/master
2020-03-23T16:00:48.610252
2018-07-21T03:06:15
2018-07-21T03:06:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,402
py
# coding: utf-8 import hashlib import time import urllib2 # 请替换appkey和secret import requests def useproxy(url,headers,postdata=None,post=False): appkey = "" secret = "c978952ede1661bd5342b34ca0bf561e" paramMap = { "app_key": appkey, "timestamp": time.strftime("%Y-%m-%d %H:%M:%S") # 如果你的程序在国外,请进行时区处理 } # 排序 keys = paramMap.keys() keys.sort() codes = "%s%s%s" % (secret, str().join('%s%s' % (key, paramMap[key]) for key in keys), secret) # 计算签名 sign = hashlib.md5(codes).hexdigest().upper() paramMap["sign"] = sign # 拼装请求头Proxy-Authorization的值 keys = paramMap.keys() authHeader = "MYH-AUTH-MD5 " + str('&').join('%s=%s' % (key, paramMap[key]) for key in keys) proxy='http://s5.proxy.mayidaili.com:8123' # 接下来使用蚂蚁动态代理进行访问 #target='http://members.3322.org/dyndns/getip' headers['Proxy-Authorization'] = authHeader if post: try: r = requests.post(url=url, headers=headers, proxies={'http': proxy},data=postdata) #print('in post') #print(r.text) except Exception as e: return None else: try: r=requests.get(url=url,headers=headers,proxies={'http':proxy}) except Exception as e : return None return r
[ "jinweizsu@gmail.com" ]
jinweizsu@gmail.com
8b11a20af2cab0011ea4d1e067cbf96c6d2c6c41
71e70eb343584d249b6f7d0e366ad5ac91f90723
/common/utils.py
20f12cc78e03a9bc3f6881ff306966a4b146e17e
[]
no_license
ljarufe/giant
bf1d081aec8afbddfc0162f79d38f53da1624255
8f3db1365a8b862b07fae8920a249bf1a532980f
refs/heads/master
2021-01-23T16:30:37.654917
2013-10-21T15:58:12
2013-10-21T15:58:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,299
py
# -*- coding: utf-8 -*- import codecs from django.conf import settings from django.core.mail import EmailMessage, BadHeaderError from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext from django.utils import simplejson # models from proyectos.models import Nivel def direct_response(request, *args, **kwargs): """ Forma resumida de render to response, enviando context_instance al template """ kwargs['context_instance'] = RequestContext(request) return render_to_response(*args, **kwargs) def json_response(data): """ Devuelve una respuesta json con la información de data """ return HttpResponse(simplejson.dumps(data), mimetype = 'application/json') def send_html_mail(subject, html_file, data, from_email, to_emails, files = None): """ Envía un e-mail con contenido html el cual es extraído de un archivo de codificación utf-8 ubicado en /media colocando la data correcta, la cúal debe ser una lista, como parámetro opcional se pueden poner archivos adjuntos en forma de lista """ content = "" try: print "hi" html = codecs.open('%shtml/%s' % (settings.MEDIA_ROOT, html_file), "r", "utf-8") content = html.read() % data html.close() except: print "no se pudo" try: msg = EmailMessage(subject, content, from_email, to_emails) msg.content_subtype = "html" if files == None: pass else: #for afile in files: msg.attach_file(files) msg.send() except BadHeaderError: return HttpResponse('Se encontró una cabecera de e-mail inválida') def get_detalles_construccion(id_proyecto): """ Crea una estructura de datos para almacenar los detalles en la relación de tablas: nivel/ambiente/acabados, la estructura de datos es de la forma:\n\n [{'nivel' : 'Primer piso', 'rowspan': 14, 'ambientes': [{'acabados': [['Parket', 'XXX', '12x23m', 'parket'], ['nombre', 'marca', 'medidas', 'descripcion'], 'ambiente': 'Sala'}]}] """ niveles_objeto = Nivel.objects.filter(construccion__proyecto = id_proyecto).distinct() detalles_construccion = [] for nivel in niveles_objeto: ambientes_objeto = nivel.ambientes.all() detalles_nivel = {'nivel': nivel.nombre, 'ambientes': []} rowspan = 0 for ambiente in ambientes_objeto: acabados_objeto = ambiente.acabados.all() detalles_ambiente = {'ambiente': ambiente.nombre, 'acabados': []} rowspan += len(acabados_objeto) for acabado in acabados_objeto: detalles_acabado = [acabado.nombre, acabado.marca, \ acabado.medidas, acabado.descripcion] detalles_ambiente['acabados'].append(detalles_acabado) detalles_nivel['ambientes'].append(detalles_ambiente) detalles_nivel['rowspan'] = rowspan detalles_construccion.append(detalles_nivel) return detalles_construccion
[ "luisjarufe@gmail.com" ]
luisjarufe@gmail.com
18c382fddeb7fa8c62d83f435d9993cefc3c8fb6
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_looniest.py
7e8f7a11b5de3a81edeb8fc566e9cba6c7fc74ea
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
235
py
from xai.brain.wordbase.nouns._loony import _LOONY #calss header class _LOONIEST(_LOONY, ): def __init__(self,): _LOONY.__init__(self) self.name = "LOONIEST" self.specie = 'nouns' self.basic = "loony" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
7849b3485cdb443da03ffcc1456b6ced0e6ac0a0
01a9e501d60ee5a5d660886a622618bf95eb46d8
/user/forms/__init__.py
52859f22d79b30285d8f8c07c9a2b372ff875791
[]
no_license
tuantran37/UniRanking
1938252a034b3ce3b8ee7f1a797b3d42c2eb9ecb
be8778fa004207bb0fea6e83e8e108347a3693c6
refs/heads/master
2023-08-05T06:31:52.868483
2018-08-27T18:26:04
2018-08-27T18:26:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
171
py
from .sector_form import AddSectorForm, UpdateSectorForm, RemoveSectorForm from .favoutite_university_form import AddFavouriteUniversityForm, RemoveFavouriteUniversityForm
[ "vantrong291@gmail.com" ]
vantrong291@gmail.com
38d4d461845d0243da88843ecba563340d11b19b
75c1ac9405911ff3490d0de854650ade12b95e63
/random_exercises/prework_2-5_consecutive.py
817d7f583ceaa15f75391025c592d7edc2f96701
[]
no_license
PropeReferio/practice-exercises
df6063b859da7f5966fc972ad44e74288054bc16
571856e452ef60d5bac7adebb49f6a6654e96733
refs/heads/master
2020-09-23T13:28:55.020969
2020-04-28T16:51:16
2020-04-28T16:51:16
225,511,686
0
0
null
null
null
null
UTF-8
Python
false
false
596
py
#Write a function to check to see if all numbers in list are consecutive #numbers. For example, [2,3,4,5,6,7] are consecutive numbers, but [1,2,4,5] #are not consecutive numbers. The return should be boolean Type. check = [1,2,4,6] check2 =[2,3,4,5,6,7] def is_consecutive(a_list): """Checks to see if the numbers in a list are consecutive""" total = 2 while total > 1: test = a_list.pop(0) if test == a_list[0] - 1: total = len(a_list) else: return False break return True works = is_consecutive(check) print(works)
[ "lemuel.b.stevens@gmail.com" ]
lemuel.b.stevens@gmail.com
82488481c998675c7f0e1ce4c13fbfc98fb02f5e
90ae1f7729920be498f04faef7efb2195cfc5ab7
/engine/_gevent.py
5cbcd6b17a1f7664ede7170045eae2067053d843
[]
no_license
jrecuero/pyengine
297a65dab16bf2a24d8b9f8a3385db21e5725502
e5de88a0053b2690230c04d7c9183d619ece32cf
refs/heads/master
2022-12-27T01:15:09.302018
2020-10-16T02:53:03
2020-10-16T02:53:03
304,499,208
1
0
null
null
null
null
UTF-8
Python
false
false
2,749
py
import pygame from ._loggar import Log class GEvent: """GEvent implements all codes related with user events used in the application via pygame events. """ NONE = 0 # GEvent type. Used by pygame events. # pygame.USEREVENT = 24 USER = pygame.USEREVENT ENGINE = pygame.USEREVENT + 1 TIMER = pygame.USEREVENT + 2 CALLBACK = pygame.USEREVENT + 3 APP_DEFINED = pygame.USEREVENT + 4 USER_DEFINED = pygame.USEREVENT + 5 # GEvent subtype. Used internaly MOVE_TO = 1 DELETE = 2 CREATE = 3 LOGGER = 4 SUBTYPE_USER_DEFINED = 1000 _gevent_subtypes = { "MOVE_TO": 1, "DELETE": 2, "CREATE": 3, "LOGGER": 4, "USER_DEFINED": 1000, } _gevent_subtypes_user_defined_last = 1000 # Event Source/Destination HANDLER = 1 SCENE = 2 BOARD = 3 OBJECT = 4 OTHER = 5 SRC_DST_USER_DEFINED = 1000 @classmethod def register_subtype_event(cls, name): """register_subtype_event registers a new user defined subtype event. """ if name in cls._gevent_subtypes: return None cls._gevent_subtypes_user_defined_last += 1 cls._gevent_subtypes[name] = cls._gevent_subtypes_user_defined_last return cls._gevent_subtypes[name] @classmethod def get_subtype_event(cls, name): """get_subtype_event returns the subtype for a given user defined subtype event. """ return cls._gevent_subtypes.get(name, None) @staticmethod def check_destination(event, dest): """check_destination checked if the given destination is in the event dest attribute. """ if isinstance(event.destination, list): return dest in event.destination else: return dest == event.destination @staticmethod def post_event(etype, esubtype, source, destination, payload, **kwargs): """post_event creates and post a new event. """ the_event = pygame.event.Event(etype, subtype=esubtype, source=source, destination=destination, payload=payload, **kwargs) pygame.event.post(the_event) Log.Post().Event(etype).Subtype(esubtype).Source(source).Destination(destination).Payload(str(payload)).Kwargs(kwargs).call() @staticmethod def new_event(etype, esubtype, source, destination, payload, **kwargs): """new_event creates a new event. """ the_event = pygame.event.Event(etype, subtype=esubtype, source=source, destination=destination, payload=payload, **kwargs) Log.New().Event(etype).Subtype(esubtype).Source(source).Destination(destination).Payload(str(payload)).Kwargs(kwargs).call() return the_event
[ "jose.recuero@gmail.com" ]
jose.recuero@gmail.com
6dd36fb253ed73f381095bd750e21c9931ab3833
5fdcf15f818eb2d0c7b5dd39443064d5bc42aff9
/lc_valid_parantheses.py
18bb3778b9edc3c6721301f71f978ca4a87a32cb
[]
no_license
vincentt117/coding_challenge
acf3664034a71ffd70c5f1ac0f6a66768e097a6e
5deff070bb9f6b19a1cfc0a6086ac155496fbb78
refs/heads/master
2021-07-02T05:43:08.007851
2020-08-27T02:16:19
2020-08-27T02:16:19
146,027,883
1
0
null
null
null
null
UTF-8
Python
false
false
570
py
# https://leetcode.com/problems/valid-parentheses/description/ def isValid(self, s): """ :type s: str :rtype: bool """ if not s: return True checkStack = [] for i in s: if i == "(": checkStack.append(")") elif i == "[": checkStack.append("]") elif i == "{": checkStack.append("}") else: if not checkStack or checkStack.pop() != i: return False return not checkStack # Faster than 99% of accepted submissions
[ "vincentt117@gmail.com" ]
vincentt117@gmail.com
861a4a235ebe5bbe9d3f3015fffc82b10f920ddd
c1ea75db1da4eaa485d39e9d8de480b6ed0ef40f
/helper/conf/__init__.py
0f8d87b95106d30140f7ae12f00266728f66965c
[ "Apache-2.0" ]
permissive
gasbarroni8/VideoCrawlerEngine
a4f092b0a851dc0487e4dcf4c98b62d6282a6180
994933d91d85bb87ae8dfba1295f7a69f6d50097
refs/heads/master
2023-04-06T07:59:29.269894
2021-02-10T16:09:15
2021-02-10T16:09:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
390
py
from .base import get_conf as __get_conf, ConfMeta, iter_conf from typing import ClassVar import importlib import sys DEBUG = True def get_conf(__name: str, **kwargs) -> ClassVar[ConfMeta]: package = f'{get_conf.__module__}.{__name}' if not sys.modules.get(package, None): importlib.import_module(package) conf_cls = __get_conf(__name) return conf_cls(**kwargs)
[ "zzsaim@163.com" ]
zzsaim@163.com
bf18c68b958da2b5499bf7ff92df74368e1f21ef
db552a9fa9d1a3f45ff3a8fb668ad47998084aa1
/ROS_projects_study/service_use/devel/lib/python2.7/dist-packages/my_service/srv/_AddInts.py
73e64b34dc3500768888b91c9ba4926e7d1f796a
[]
no_license
gdamion/ROS_projects
026529e99898152de0facfa854b01e1b2af55319
a3e9c8d199fd7577ce183689428f159bf29acd41
refs/heads/master
2020-05-01T15:20:46.689036
2019-08-18T09:52:58
2019-08-18T09:52:58
177,544,163
0
0
null
null
null
null
UTF-8
Python
false
false
7,402
py
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from my_service/AddIntsRequest.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class AddIntsRequest(genpy.Message): _md5sum = "05577f62131ad26921bff0de6b2cb722" _type = "my_service/AddIntsRequest" _has_header = False #flag to mark the presence of a Header object _full_text = """int32 first int32 second """ __slots__ = ['first','second'] _slot_types = ['int32','int32'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: first,second :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(AddIntsRequest, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.first is None: self.first = 0 if self.second is None: self.second = 0 else: self.first = 0 self.second = 0 def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self buff.write(_get_struct_2i().pack(_x.first, _x.second)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: end = 0 _x = self start = end end += 8 (_x.first, _x.second,) = _get_struct_2i().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self buff.write(_get_struct_2i().pack(_x.first, _x.second)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ try: end = 0 _x = self start = end end += 8 (_x.first, _x.second,) = _get_struct_2i().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_2i = None def _get_struct_2i(): global _struct_2i if _struct_2i is None: _struct_2i = struct.Struct("<2i") return _struct_2i # This Python file uses the following encoding: utf-8 """autogenerated by genpy from my_service/AddIntsResponse.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class AddIntsResponse(genpy.Message): _md5sum = "0ba699c25c9418c0366f3595c0c8e8ec" _type = "my_service/AddIntsResponse" _has_header = False #flag to mark the presence of a Header object _full_text = """int32 sum """ __slots__ = ['sum'] _slot_types = ['int32'] def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: sum :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(AddIntsResponse, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.sum is None: self.sum = 0 else: self.sum = 0 def _get_types(self): """ internal API method """ return self._slot_types def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: buff.write(_get_struct_i().pack(self.sum)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: end = 0 start = end end += 4 (self.sum,) = _get_struct_i().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill def serialize_numpy(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: buff.write(_get_struct_i().pack(self.sum)) except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self))))) def deserialize_numpy(self, str, numpy): """ unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module """ try: end = 0 start = end end += 4 (self.sum,) = _get_struct_i().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_i = None def _get_struct_i(): global _struct_i if _struct_i is None: _struct_i = struct.Struct("<i") return _struct_i class AddInts(object): _type = 'my_service/AddInts' _md5sum = '85a734c776d49ce7e013b15b395d3f69' _request_class = AddIntsRequest _response_class = AddIntsResponse
[ "you@example.com" ]
you@example.com
221cec3f4089608568eafe559900dd873f9954db
ce7cd2b2f9709dbadf613583d9816c862003b38b
/oof3dtest
8aa978a57bd7edb034f399937ceef705b49f9323
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
usnistgov/OOF3D
32b01a25154443d29d0c44d5892387e8ef6146fa
7614f8ea98a095e78c62c59e8952c0eb494aacfc
refs/heads/master
2023-05-25T13:01:20.604025
2022-02-18T20:24:54
2022-02-18T20:24:54
29,606,158
34
7
null
2015-02-06T19:56:26
2015-01-21T19:04:14
Python
UTF-8
Python
false
false
1,089
#!python # -*- python -*- # This software was produced by NIST, an agency of the U.S. government, # and by statute is not subject to copyright in the United States. # Recipients of this software assume all responsibilities associated # with its operation, modification and maintenance. However, to # facilitate maintenance we ask that before distributing modified # versions of this software, you first contact the authors at # oof_manager@nist.gov. # This is the start up script for the oof3d regression test suite. It # just wraps regression.py. There's no difference between running # this script and running "python regression.py" in the TEST3D # directory except that with this script the user doesn't have to know # how to find regression.py. (Hint: TEST3D is installed as 'ooftests' # in the oof3d directory in site-packages, whereever that might be.) import sys import os from math import * import oof3d sys.path.append(os.path.dirname(oof3d.__file__)) import ooftests from ooftests import regression homedir = os.path.dirname(regression.__file__) regression.run(homedir)
[ "stephen.langer@nist.gov" ]
stephen.langer@nist.gov
792392790e9fed19536acbe1906d318837c248c1
9b64f0f04707a3a18968fd8f8a3ace718cd597bc
/huaweicloud-sdk-mpc/huaweicloudsdkmpc/v1/model/video_extend_settings.py
3ac0cb8875d30324610815939b561555434a26ff
[ "Apache-2.0" ]
permissive
jaminGH/huaweicloud-sdk-python-v3
eeecb3fb0f3396a475995df36d17095038615fba
83ee0e4543c6b74eb0898079c3d8dd1c52c3e16b
refs/heads/master
2023-06-18T11:49:13.958677
2021-07-16T07:57:47
2021-07-16T07:57:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,866
py
# coding: utf-8 import re import six class VideoExtendSettings: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'preset': 'str' } attribute_map = { 'preset': 'preset' } def __init__(self, preset=None): """VideoExtendSettings - a model defined in huaweicloud sdk""" self._preset = None self.discriminator = None if preset is not None: self.preset = preset @property def preset(self): """Gets the preset of this VideoExtendSettings. 扩展编码质量等级,用于覆盖模板中的同名参数。取值如下: - SPEED - HIGHQUALITY :return: The preset of this VideoExtendSettings. :rtype: str """ return self._preset @preset.setter def preset(self, preset): """Sets the preset of this VideoExtendSettings. 扩展编码质量等级,用于覆盖模板中的同名参数。取值如下: - SPEED - HIGHQUALITY :param preset: The preset of this VideoExtendSettings. :type: str """ self._preset = preset def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): import simplejson as json return json.dumps(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, VideoExtendSettings): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
84ea987a1929e5afa62a6584aa35866c79086874
12e78946542250f64792bc6c1d8c8ff1ffecdaf7
/Python/Django/ninja_gold/apps/dojo_ninjas/views.py
10a05c9d6389bbd63f012c7f6704b9a636a3e904
[]
no_license
mkrabacher/CodingDojoAssignments
0fde5adf7223a9eac07a4867499a243e230a300e
4afef4aaf4f129fb56376e57d8be437d1f124521
refs/heads/master
2021-05-14T13:38:03.570533
2018-02-23T00:09:24
2018-02-23T00:09:24
113,722,808
0
0
null
null
null
null
UTF-8
Python
false
false
166
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, HttpResponse def index(request): return HttpResponse('hello')
[ "matt.krabacher@gmail.com" ]
matt.krabacher@gmail.com
8f4884fe12de96cea161db86521397a440b8eef1
732536468e61932e7c0829934262b645effbd6d4
/python_stack/django/django_intro/for_test/form_app/urls.py
d4277500dd0fc48dfbaa91957221c89bff1c4ca0
[]
no_license
jignacioa/Coding-Dojo
7a83919d09fb6ad714379dc58b1ce8e706ccc7b6
0e1f0d4fc528439bf34d866f4c409994741e870b
refs/heads/master
2023-01-21T06:48:15.880635
2021-02-08T01:36:17
2021-02-08T01:36:17
251,421,342
0
0
null
null
null
null
UTF-8
Python
false
false
168
py
from django.urls import path from . import views urlpatterns = [ path('', views.index), path('users', views.create_user), path('success', views.success) ]
[ "jignacio.aglr@gmail.com" ]
jignacio.aglr@gmail.com
d98b243efb145b61bf43a079eb3c779f1d21840e
4b72cfb730e9d967ecc9ece7a5dcdff03242ce7a
/7 კლასი/7_1/ბეგიაშვილი სანდრო/რიცხვის კვადრატები-.py
6216a18d50bc1c6d313d3539b3c0b3b1d88a0031
[]
no_license
sc-199/2018-2019
20945a0aaf7a998e6038e3fd3310c8be2296e54f
578d7aad254dc566cf5f8502f1a82c1eb267cbc2
refs/heads/master
2020-04-26T02:59:26.560166
2019-05-03T13:32:30
2019-05-03T13:32:30
168,499,541
4
0
null
2019-02-14T17:17:25
2019-01-31T09:36:13
Python
UTF-8
Python
false
false
128
py
for i in range(1,10): print(i**2) print( 'kenti ricxvebi:') for i in range(1,10): if i % 2 != 0: print(i**2)
[ "pm72github@yahoo.com" ]
pm72github@yahoo.com
72edaccc4f12c2a7a357dd545d3b19e07e1e876b
ac1bbabc7c1b3149711c416dd8b5f5969a0dbd04
/Python OOP/exams/shop/deliveries/drink.py
e8ab76ba18a1bb5a6342eb4daaa653a29d11c4be
[]
no_license
AssiaHristova/SoftUni-Software-Engineering
9e904221e50cad5b6c7953c81bc8b3b23c1e8d24
d4910098ed5aa19770d30a7d9cdf49f9aeaea165
refs/heads/main
2023-07-04T04:47:00.524677
2021-08-08T23:31:51
2021-08-08T23:31:51
324,847,727
1
0
null
2021-08-08T23:31:52
2020-12-27T20:58:01
Python
UTF-8
Python
false
false
163
py
from shop.deliveries.product import Product class Drink(Product): quantity = 10 def __init__(self, name): super().__init__(name, Drink.quantity)
[ "assiaphristova@gmail.com" ]
assiaphristova@gmail.com
853de356187a49bd486d2e2290adba638ee294a9
8f6cc0e8bd15067f1d9161a4b178383e62377bc7
/__OLD_CODE_STORAGE/openGL_NAME/textbook/5-12.py
f132d16dda9bf39c1a4c61c443e44627b68fb309
[]
no_license
humorbeing/python_github
9c4dfc61a3cefbb266fefff335f6b28d05797e5e
e4b4b49bee7e7e3843c6874717779ce8d619bd02
refs/heads/master
2023-01-22T21:51:20.193131
2020-01-26T21:47:23
2020-01-26T21:47:23
163,707,778
0
0
null
2022-12-27T15:37:48
2019-01-01T01:58:18
Python
UTF-8
Python
false
false
1,751
py
from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * PALETTE = ((255, 255, 255), (0, 255, 255), (255, 0, 255), (0, 0, 255), (192, 192, 192), (128, 128, 128), (0, 128, 128), (128, 0, 128), (0, 0, 128), (255, 255, 0), (0, 255, 0), (128, 128, 0), (0, 128, 0), (255, 0, 0), (128, 0, 0), (0, 0, 0), ) Delta = 0.0 Index = 0 def MyDisplay(): global Delta, Index, PALETTE Red = PALETTE[Index][0] / 255.0 Green = PALETTE[Index][1] / 255.0 Blue = PALETTE[Index][2] / 255.0 glColor3f(Red, Green, Blue) glBegin(GL_LINES) glVertex3f(-1.0 + Delta, 1.0, 0.0) glVertex3f(1.0 - Delta, -1.0, 0.0) glVertex3f(-1.0, -1.0 + Delta, 0.0) glVertex3f(1.0, 1.0 - Delta, 0.0) glEnd() glutSwapBuffers() def MyTimer(Value): global Delta, Index if Delta < 2.0: Delta += 0.01 else: Delta = 0.0 Index += 1 if Index == 15: Index = 0 glutPostRedisplay() glutTimerFunc(10, MyTimer, 1) def main(): glutInit() glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE) glutInitWindowSize(500, 500) glutInitWindowPosition(0, 0) glutCreateWindow(b"OpenGL Timer Animation Sample") # not only string, put 'b' in front of string. glClearColor(0.0, 0.0, 0.0, 1.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0) glutTimerFunc(10, MyTimer, 1) glutDisplayFunc(MyDisplay) glutMainLoop() if __name__ == '__main__': main()
[ "geemguang@gmail.com" ]
geemguang@gmail.com
2fed7108c460e6c23e9fe55b399f1701ac0aeeeb
d9a633b01da49ed38ca7c9c736b271ba671d9c4f
/pygameTest/pygame_test_01.py
83fc17e7c9fa2f2a2183dcbddc176324564775b4
[]
no_license
chmberl/sys
4b90263f86d070f3bb15de4bd788c32f56ee17d0
7b7258796157d1b4417715ababc1d1cc5b7dbc1b
refs/heads/master
2021-01-22T02:58:53.055702
2018-01-08T06:41:47
2018-01-08T06:41:47
22,147,604
0
0
null
2018-01-08T06:41:48
2014-07-23T12:54:34
Python
UTF-8
Python
false
false
658
py
import pygame from pygame.locals import * from sys import exit pygame.init() SCREEN_SIZE = (640, 480) screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32) font = pygame.font.SysFont("arial", 16) font_height = font.get_linesize() event_text = [] while True: event = pygame.event.wait() event_text.append(str(event)) event_text = event_text[-SCREEN_SIZE[1]/font_height:] if event.type == QUIT: exit() screen.fill((255, 255, 255)) y = SCREEN_SIZE[1] - font_height for text in reversed(event_text): screen.blit(font.render(text, True, (0, 0, 0)), (0, y)) y -= font_height pygame.display.update()
[ "chmberl@gmail.com" ]
chmberl@gmail.com
cc2bb833560bf80beae9e1a7cf4d46f75bf7a75b
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/arc053/C/1254642.py
b4ebd66ee9b1032de9f913be200469beb2744bab
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
Python
false
false
1,034
py
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def main(): n = I() a = [] b = [] d = [] for _ in range(n): x,y = LI() if x < y: a.append([x,y]) else: b.append([x,y]) r = 0 c = 0 a = sorted(a) for x,y in a: c += x if r < c: r = c c -= y b = sorted(b, key=lambda x: [-x[1],-x[0]]) for x,y in b: c += x if r < c: r = c c -= y return r print(main())
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
c7add1aab765b5b612d8ba38cb651a1359bd3b53
24c5c46f1d281fc15de7f6b72a5148ae85f89fb4
/script/runTest.py
3256953f3be202d7068f5dbf6030c76716de72c7
[]
no_license
enterpriseih/easyTest
22d87c7ffe40fb10a07f7c5cdd505f63dd45adc0
43b8d294e898f25055c78313cfece2753352c250
refs/heads/master
2023-08-23T22:55:14.798341
2020-02-11T09:13:43
2020-02-11T09:13:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
279
py
# coding:utf-8 import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from script import addPathToPython, initSettings, selectModel addPathToPython() initSettings() selectModel() from SRC.main import Main Main('login.xml').run()
[ "yaolihui0506" ]
yaolihui0506
29d0252de36655292ca9eb8a181601dcd56492fb
545306d8368bbe6a369e462127ba5a9389f3f0e1
/page/migrations/0003_postcategory_link.py
4e121a8e4cbc0adbc6329f148a2ea7fbc3d7d7c3
[ "MIT" ]
permissive
euskate/django-page
d86c45644508af635b828cbde764cdd7fd721d66
f7d12f16a56545ace0e09e03727aa56416b538a2
refs/heads/master
2020-12-07T19:37:45.250776
2020-01-01T15:52:18
2020-01-01T15:52:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
456
py
# Generated by Django 2.0.5 on 2018-11-14 16:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('page', '0002_auto_20181114_0429'), ] operations = [ migrations.AddField( model_name='postcategory', name='link', field=models.CharField(blank=True, max_length=1024, null=True, verbose_name='키테고리 페이지 링크'), ), ]
[ "bluedisk@gmail.com" ]
bluedisk@gmail.com
1b5b6be1567e3fe383b9568a3a0e8ea969def7c4
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/anagram/d8df0609726548d9a6083d84700d3f3e.py
708559896080d2883ad2f51a3acf1faf0d9d44f1
[]
no_license
itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
2016-05-23T05:40:56
2016-05-23T05:40:56
null
UTF-8
Python
false
false
409
py
from collections import Counter def detect_anagrams(word, options): word = word.lower() #ignore case word_char_count = Counter(char for char in word) res = [] for option in options: if option.lower() != word: option_char_count = Counter(c for c in option.lower()) if option_char_count == word_char_count: res.append(option) return res
[ "rrc@berkeley.edu" ]
rrc@berkeley.edu
c1e12dad4fdd03f0ad5fadb0a2918fe560bb2501
c237dfae82e07e606ba9385b336af8173d01b251
/lib/python/Products/ZGadflyDA/db.py
409dcc6774b9ca8d71c9382f168eeff4d9eb2e18
[ "ZPL-2.0" ]
permissive
OS2World/APP-SERVER-Zope
242e0eec294bfb1ac4e6fa715ed423dd2b3ea6ff
dedc799bd7eda913ffc45da43507abe2fa5113be
refs/heads/master
2020-05-09T18:29:47.818789
2014-11-07T01:48:29
2014-11-07T01:48:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,563
py
############################################################################## # # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE # ############################################################################## '''$Id: db.py,v 1.13 2002/08/14 22:25:17 mj Exp $''' __version__='$Revision: 1.13 $'[11:-2] import os from string import strip, split import gadfly import Globals, Shared.DC.ZRDB.THUNK from DateTime import DateTime data_dir=os.path.join(Globals.data_dir,'gadfly') def manage_DataSources(): if not os.path.exists(data_dir): try: os.mkdir(data_dir) os.mkdir(os.path.join(data_dir,'demo')) except: raise 'Gadfly Error', ( """ The Zope Gadfly Database Adapter requires the existence of the directory, <code>%s</code>. An error occurred while trying to create this directory. """ % data_dir) if not os.path.isdir(data_dir): raise 'Gadfly Error', ( """ The Zope Gadfly Database Adapter requires the existence of the directory, <code>%s</code>. This exists, but is not a directory. """ % data_dir) return map( lambda d: (d,''), filter(lambda f, i=os.path.isdir, d=data_dir, j=os.path.join: i(j(d,f)), os.listdir(data_dir)) ) class DB(Shared.DC.ZRDB.THUNK.THUNKED_TM): database_error=gadfly.error opened='' def tables(self,*args,**kw): if self.db is None: self.open() return map( lambda name: { 'TABLE_NAME': name, 'TABLE_TYPE': 'TABLE', }, filter(self.db.database.datadefs.has_key, self.db.table_names()) ) def columns(self, table_name): if self.db is None: self.open() return map(lambda col: { 'Name': col.colid, 'Type': col.datatype, 'Precision': 0, 'Scale': 0, 'Nullable': 'with Null' }, self.db.database.datadefs[table_name].colelts) def open(self): connection=self.connection path=os.path dir=path.join(data_dir,connection) if not path.isdir(dir): raise self.database_error, 'invalid database error, ' + connection if not path.exists(path.join(dir,connection+".gfd")): db=gadfly.gadfly() db.startup(connection,dir) else: db=gadfly.gadfly(connection,dir) self.db=db self.opened=DateTime() def close(self): self.db=None del self.opened def __init__(self,connection): self.connection=connection self.open() def query(self,query_string, max_rows=9999999): if self.db is None: self.open() self._register() c=self.db.cursor() queries=filter(None, map(strip,split(query_string, '\0'))) if not queries: raise 'Query Error', 'empty query' desc=None result=[] for qs in queries: c.execute(qs) d=c.description if d is None: continue if desc is None: desc=d elif d != desc: raise 'Query Error', ( 'Multiple incompatible selects in ' 'multiple sql-statement query' ) if not result: result=c.fetchmany(max_rows) elif len(result) < max_rows: result=result+c.fetchmany(max_rows-len(result)) if desc is None: return (),() items=[] for name, type, width, ds, p, scale, null_ok in desc: if type=='NUMBER': if scale==0: type='i' else: type='n' elif type=='DATE': type='d' else: type='s' items.append({ 'name': name, 'type': type, 'width': width, 'null': null_ok, }) return items, result # Gadfly needs the extra checkpoint call. def _abort(self): self.db.rollback() self.db.checkpoint()
[ "martin@os2world.com" ]
martin@os2world.com
7aa5681a1475a9d4efeaf93110d2d95cf57166aa
528f910908885c3ded4ecc6380b9603c8dcacbd6
/tbapi/top/api/rest/WlbTmsorderQueryRequest.py
bcac48c2b08a01a46b9956084883246e889adc8d
[]
no_license
Monica-ckd/data007
15fe9c4c898a51a58100138b6b064211199d2ed1
0e54ae57eb719b86ec14ce9f77b027882a3398a8
refs/heads/master
2023-03-16T05:26:14.257318
2016-05-25T06:57:05
2016-05-25T06:57:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
363
py
''' Created by auto_sdk on 2013-04-01 16:44:41 ''' from top.api.base import RestApi class WlbTmsorderQueryRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.order_code = None self.page_no = None self.page_size = None def getapiname(self): return 'taobao.wlb.tmsorder.query'
[ "root@u16392468.onlinehome-server.com" ]
root@u16392468.onlinehome-server.com
1330a1d78ccbfcb3b204dddbc5a7a1770d985167
9e3d8cca75de767f948736c7cde601221c4ef8ab
/core/migrations/0006_pontoturistico_enderecos.py
7918f3e394208fee0d5e855cc4eed65f5a8b96d4
[]
no_license
miradouro/pontosturisticos
b6d744c0b33f9ecdc8dca405615c7cc8a3ba202f
4ea382281b8999eceab8add13ab2bd511319d58c
refs/heads/master
2023-03-30T16:11:14.359286
2021-04-07T11:47:18
2021-04-07T11:47:18
354,115,695
0
0
null
null
null
null
UTF-8
Python
false
false
454
py
# Generated by Django 3.1.7 on 2021-04-03 11:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('enderecos', '0001_initial'), ('core', '0005_pontoturistico_avaliacoes'), ] operations = [ migrations.AddField( model_name='pontoturistico', name='enderecos', field=models.ManyToManyField(to='enderecos.Endereco'), ), ]
[ "rafaelmiradouro@gmail.com" ]
rafaelmiradouro@gmail.com
28b89f558948ad6bda3670a0422fe88aae42ce52
c3113792bfe44d160b7cc9d79203d7f6da02aec5
/news/migrations/0023_remove_post_thumbnail.py
e249ea056b565076d9b4e11801fb1189d4dae220
[]
no_license
eyobofficial/sport-news-app
9eb07afeeeae2bf7143405fbc0d1964292e5a11d
2da74b1c458b34a7a8f9a306234f067436eda9da
refs/heads/master
2020-03-18T20:08:18.213627
2018-06-04T19:07:16
2018-06-04T19:07:16
135,197,904
0
0
null
null
null
null
UTF-8
Python
false
false
326
py
# Generated by Django 2.0.5 on 2018-06-02 18:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('news', '0022_auto_20180602_1834'), ] operations = [ migrations.RemoveField( model_name='post', name='thumbnail', ), ]
[ "eyobtariku@gmail.com" ]
eyobtariku@gmail.com
a74223ae54fe94a82e612222bbbeff4f6a24e933
8ef5a09d76a11c56963f18e6a08474a1a8bafe3c
/leet_code/331. Verify Preorder Serialization of a Binary Tree.py
58f4b9c19280f69a0cbf987f798fba83c5888e2b
[]
no_license
roiei/algo
32c4677649c7666db148f6183fbfbf66c8b1969f
ae8bb8bf4ae4026ccaf1dce323b4098547dd35ec
refs/heads/master
2022-04-01T19:21:27.768675
2022-02-19T06:15:29
2022-02-19T06:15:29
169,021,154
0
0
null
null
null
null
UTF-8
Python
false
false
678
py
import time from util_list import * from util_tree import * import copy import collections class Solution: def isValidSerialization(self, preorder: str) -> bool: stk = [] for val in preorder.split(','): stk += val, while len(stk) >= 2 and stk[-2] == '#' and stk[-1] == '#': stk.pop() stk.pop() if not stk: return False stk.pop() stk += '#', return stk == ['#'] stime = time.time() print(True == Solution().isValidSerialization([2,-1,1,2,2])) print('elapse time: {} sec'.format(time.time() - stime))
[ "hyoukjea.son@hyundai.com" ]
hyoukjea.son@hyundai.com
b2450cfef5fe4b41d70cd89869059ea22707ec59
437b1f6c3450a53e6e51eda62c85e3b4e098c8d2
/operadores/Idades.py
ed6f27b28bdc85390c51fcbcd39dc168e5c6fbc8
[]
no_license
pocceschi/aprendendo_git
16d5194b2372970b469ff8db42290f7f152b538b
704e4e40cd0e36b02e09bf411f42f23ab931d5fc
refs/heads/main
2023-04-07T05:25:03.549470
2021-04-01T23:29:04
2021-04-01T23:29:04
353,849,682
0
0
null
null
null
null
UTF-8
Python
false
false
286
py
print("Dados da primeira pessoa: ") nome1 = str(input("Nome: ")) idade1 = int(input("Idade: ")) print("Dados da segunda pessoa: ") nome2 = str(input("Nome: ")) idade2 = int(input("Idade: ")) media = (idade1 + idade2) / 2 print(f"A idade média de {nome1} e {nome2} é de {media:.2f}")
[ "pedrobh94@hotmail.com" ]
pedrobh94@hotmail.com
1d83c4355f9a26123159aa9e8e48d5b0fe6a3a75
37194bcee20e66e84360010d98a45adcced57963
/Algorithem_my/IM_Motherboard/6190/6190.py
fc9d929b23a4e98d9078e6f893607835ebc2a934
[]
no_license
dmdekf/algo
edcd1bbd067102a622ff1d55b2c3f6274126414a
544a531799295f0f9879778a2d092f23a5afc4ce
refs/heads/master
2022-09-13T14:53:31.593307
2020-06-05T07:06:03
2020-06-05T07:06:03
237,857,520
0
0
null
null
null
null
UTF-8
Python
false
false
433
py
import sys sys.stdin = open('input.txt') def p(num): while num: r = num % 10 num = num // 10 if r < num%10: return False return True T = int(input()) for tc in range(1, T+1): N = int(input()) d = list(map(int, input().split())) d = sorted(d) for i in range(N-1,0,-1): x=d[i]*d[i-1] if p(x): print('#{} {}'.format(tc,x)) break
[ "dmdekf@gmail.com" ]
dmdekf@gmail.com
bc7c8910ea133c2a685757bc62f84d72cabcac8b
ffe4c155e228f1d3bcb3ff35265bb727c684ec1a
/UCL/Algorithms/Sorting & Searching/heap_sort.py
9e3cb91645279c9eff8750c1ff7939fbd07e1d04
[]
no_license
yuuee-www/Python-Learning
848407aba39970e7e0058a4adb09dd35818c1d54
2964c9144844aed576ea527acedf1a465e9a8664
refs/heads/master
2023-03-12T00:55:06.034328
2021-02-28T13:43:14
2021-02-28T13:43:14
339,406,816
0
0
null
2021-02-28T11:27:40
2021-02-16T13:26:46
Jupyter Notebook
UTF-8
Python
false
false
231
py
from binary_heap import* def heapSort(alist): bh = BinHeap() bh.buildHeap(alist) lst = [] while not bh.isEmpty(): lst.append(bh.delMin()) return lst alist = [1,2,3,4,5,8,7,6,6] print(heapSort(alist))
[ "50982416+cyndereN@users.noreply.github.com" ]
50982416+cyndereN@users.noreply.github.com
a3bb51288c892782c7b8c94d0503d2598d5cec18
05297c66b8881b734bd3d8cb01b69eb927157f53
/src/ava/job/errors.py
3fa89547c8404e6f5dfdf84142bd377e2814214a
[ "Apache-2.0" ]
permissive
nickchen-mitac/fork
4b75c2204cede08e4c71d85261da2e826330ff9f
64dab56012da47465b4923f30f26925476c87afc
refs/heads/master
2021-01-10T06:27:57.701844
2015-11-03T09:01:31
2015-11-03T09:01:31
45,453,006
0
0
null
null
null
null
UTF-8
Python
false
false
327
py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from ava.core import AvaError class JobCancelledError(AvaError): pass class ScriptSyntaxError(AvaError): def __init__(self, *args, **kwargs): super(ScriptSyntaxError, self).__init__(*args, **kwargs)
[ "sam@eavatar.com" ]
sam@eavatar.com
2dba634705e99a2bad5fca280fc4c0d56088c2d8
78456214246b3fca7636d9f91d15f1c25ae00f77
/flowmeter/config/core/log.py
9e79c6f0bb73290c74854b5ce5ec16488b7f6851
[]
no_license
Zhuuhn/flowmeter
4404bbead2c7e7804364623b612a89ec80a69fb9
9ea4f497fb2a4de64f7b2d8c453066df7ec8a483
refs/heads/master
2022-08-22T01:01:45.687526
2020-05-27T10:02:21
2020-05-27T10:02:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
763
py
# coding=utf-8 from flowmeter.config.db.log_table import AlarmLog, OprLog, SystemLog def add_alarm_log(log): return AlarmLog.objects.create(alarm_type=log['alarm_type'], meter_id=log['meter_id'], opr_time=log['opr_time']) def add_opr_log(log): opr = OprLog.objects.create(**log) return opr def add_system_log(log): log = SystemLog.objects.create(**log) return log def find_one_opr_log(log_info): try: opr = OprLog.objects.get(**log_info) return opr except OprLog.DoesNotExist: return None def find_one_system_log(log_info): try: log = SystemLog.objects.get(**log_info) return log except SystemLog.DoesNotExist: return None
[ "1347704262@qq.com" ]
1347704262@qq.com
8ffc68f6def3a710f9c3285915e486060990e051
b0f2c47881f39ceb5a989b9638483f7439bfb5cf
/Problem77.py
2d72d0b64c35bd5631ecaf1a7efff986981eaefb
[]
no_license
chrisvail/Project_Euler
9ba264c8ec9d158b33ec677811e59d1e0e52fef2
41623c27b3e1344f9d8ebdfac4df297d0666cc07
refs/heads/main
2023-02-13T20:26:42.752780
2021-01-15T16:38:27
2021-01-15T16:38:27
329,964,440
0
0
null
null
null
null
UTF-8
Python
false
false
392
py
from StandardFunctions import genprimes from itertools import count primes = genprimes(1000) for target in count(): ways = [0 for _ in range(target + 1)] ways[0] = 1 for i in primes: for j in range(i, target + 1): ways[j] += ways[j - i] print(ways[-1] - 1) if ways[-1] - 1 > 5000: print(target) break
[ "noreply@github.com" ]
chrisvail.noreply@github.com
cd211fae8a73579ec113ee9bc0d541ad3e3dd4b7
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/kjJWvK9XtdbEJ2EKe_22.py
279d9872a60ea239f541d40214d2a846a569506d
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
1,014
py
""" Python has a beautiful built-in function `sorted` that sorts an iterable, usually an array of numbers, sorting them in ascending order, but using `key=` you can sort the iterable in different ways. Create a function that takes an array of integers as an argument and returns the same array in ascending order. Using `sorted()` would be easy, but for this challenge YOU have to sort the array creating your own algorithm. ### Examples sort_array([2, -5, 1, 4, 7, 8]) ➞ [-5, 1, 2, 4, 7, 8] sort_array([23, 15, 34, 17, -28]) ➞ [-28, 15, 17, 23, 34] sort_array([38, 57, 45, 18, 47, 39]) ➞ [18, 38, 39, 45, 47, 57] ### Notes * The arrays can contain either positive or negative elements. * The arrays will only contain integers. * The arrays won't contain duplicate numbers. * This is a challenge to enhance your ability, using the sorted built-in won't enhance your skills. """ def sort_array(lst): return [lst.pop(lst.index(min(lst))) for x in range(len(lst))]
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
c1d7b781f24649f27e2a1e76543ce918281badf7
1113c8d5689685106fd77363e5561006d8ecef0d
/confbusterplusplus/aligner.py
2ec09dc3fe54ecf09bc33b94b1e27766826602c5
[ "MIT" ]
permissive
dsvatunek/ConfBusterPlusPlus
238f73ab48e6d1d1491cbf4406acf828d76a56f9
2de751f409ffdb791d8b04fd4b3d08645beebaa6
refs/heads/master
2022-11-09T18:28:26.880541
2020-06-24T05:50:35
2020-06-24T05:50:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
448
py
from rdkit.Chem import AllChem class MolAligner: def __init__(self, max_iters): self.max_iters = max_iters def align_global(self, mol): rmsd = [] AllChem.AlignMolConformers(mol, maxIters=self.max_iters, RMSlist=rmsd) return rmsd def align_atoms(self, mol, atoms): rmsd = [] AllChem.AlignMolConformers(mol, maxIters=self.max_iters, atomIds=atoms, RMSlist=rmsd) return rmsd
[ "edang830@gmail.com" ]
edang830@gmail.com
b4e86b17979bb6357a4ba72329709913ee08d6b1
05e2277cf1af409123f43fc0a3226014dd170556
/11286.py
bda540ef1205168f0af5aa383953c4a6c163a4e4
[]
no_license
2021-01-06/baekjoon
4dec386574ce9f51f589a944b71436ce1eb2521e
ca8f02ecbed11fe98adfd1c18ce265b10f1298bc
refs/heads/main
2023-05-06T08:19:53.943479
2021-05-14T03:25:55
2021-05-14T03:25:55
327,730,237
0
0
null
null
null
null
UTF-8
Python
false
false
279
py
import heapq import sys h=[] n=int(sys.stdin.readline()) for _ in range(n): o=int(sys.stdin.readline()) if o==0: if len(h)==0: print(0) else: print(heapq.heappop(h)[1]) else: heapq.heappush(h,(abs(o),o))
[ "noreply@github.com" ]
2021-01-06.noreply@github.com
07b1e3108279514ee49174b1f35c9e3067165c51
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_2/cherry.su/b.py
41f0dc05a41ed75223d02f95d2bd1c67fc0af7a0
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
1,190
py
def flip(S, n): for i in range((n+1)//2): tmp = S[n-1-i] S[n-1-i] = not S[i] S[i] = not tmp def num_upright_bottom(S): c = 0 for p in reversed(S): if p: c += 1 else: break return c def num_down_top(S): c = 0 for p in S: if not p: c += 1 else: break return c def num_upright_top(S): c = 0 for p in S: if p: c += 1 else: break return c def solve(S): N = len(S) k = num_upright_bottom(S) n_flips = 0 k_prev = N while k < N: n_down_top = num_down_top(S) if n_down_top == 0: n_up_top = num_upright_top(S) flip(S, n_up_top) n_flips += 1 """top of stack should have some facing down """ flip(S, N - k) n_flips += 1 k_prev = k k = num_upright_bottom(S) assert k_prev < k, "extra work" return n_flips if '__main__' == __name__: T = int(raw_input()) for _t in range(T): S = [p == '+' for p in raw_input().strip()] print "Case #%d: %d" % (_t+1, solve(S))
[ "[dhuo@tcd.ie]" ]
[dhuo@tcd.ie]
4d1ec5bf8d2d82b6cf5987de69f24df3b6806f4f
1c2ed80f77782ebee5b90480dbfc74a2d145d53f
/python-base/src/learn/function/func_param.py
d44d060af6242c40aa3893ff506a424f0c5fc7fd
[]
no_license
icesx/IPython
970dfe7260906d85706b7117044510b5929e9098
452c63e17c6f05cb0540974f7c01c1e73f9836fe
refs/heads/master
2021-07-05T02:30:29.956369
2021-02-02T07:09:58
2021-02-02T07:09:58
220,771,536
0
0
null
null
null
null
UTF-8
Python
false
false
255
py
#!/usr/bin/python # Filename: func_param.py def printMax(a,b): if a > b: print(a,'is maximum') else: print(b,'is maximum') printMax(3,4) # directly give literal values x = 5 y = 7 printMax(x,y) # give variables as arguments
[ "icesxrun@gmail.com" ]
icesxrun@gmail.com
b4cc2afa134e8d011f1cf4f1848b20a0d3abc505
5c9b70a21636cd64a3d9ccfd224740d4ca049e19
/rest/app.py
fb43feb693bc0233c6893c8bd082e3a9cc4b1e94
[ "MIT" ]
permissive
shaneramey/wq.db
14d8c711796ab29b6d84cca6c2d52db8e3ebb2b6
bc14412e5a7be7964d6d0fcddca931c348120b82
refs/heads/master
2021-01-15T19:13:14.601893
2015-08-11T19:53:44
2015-08-11T19:53:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
256
py
import warnings warnings.warn( "The wq.db.rest.app API has been moved to wq.db.rest. " "The actual Router implementation has moved to wq.db.rest.routers", DeprecationWarning ) from . import ModelRouter as Router, router, autodiscover # NOQA
[ "andrew@wq.io" ]
andrew@wq.io
c36022c620246c3970cc742c543e4e7be05fb805
92b9a9253c63ba56ff4bd58af268c1e304634841
/backend/chat/chat/settings.py
fdd9a88f6827828de5a2564632bedf1457f7533d
[]
no_license
alisamadzadeh46/ChatApplication
264a48a3747235d5f30c254f6fcd7cd145b595ac
77bb86ccc26685a6e4dbf9a84d9d950bd1574549
refs/heads/main
2023-05-10T23:07:00.337906
2021-05-28T16:23:28
2021-05-28T16:23:28
364,041,128
0
0
null
null
null
null
UTF-8
Python
false
false
4,226
py
""" Django settings for chat project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-nj_-*vz+@)fdsv1i8@6ior0r_1tseko#vm)jugfla5y-5r%u_+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] AUTH_USER_MODEL = "account.CustomUser" REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'chat.custom_methods.custom_exception_handler', "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 20, } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 3rd party apps 'rest_framework', 'drf_yasg', # My app 'account.apps.AccountConfig', 'message_control.apps.MessageControlConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'chat.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'chat.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' # STATICFILES_DIRS = [ # BASE_DIR / "static", # ] # STATIC_ROOT = BASE_DIR / 'static' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # ARVAN CLOUD STORAGE DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = 'your access key id' AWS_SECRET_ACCESS_KEY = 'your secret access key' AWS_STORAGE_BUCKET_NAME = 'your bucket name' AWS_SERVICE_NAME = 's3' AWS_S3_ENDPOINT_URL = 'https://s3.ir-thr-at1.arvanstorage.com' AWS_S3_FILE_OVERWRITE = False AWS_LOCAL_STORAGE = f'{BASE_DIR}/aws/' SOCKET_SERVER = config("SOCKET_SERVER")
[ "alisamadzadeh46@gmail.com" ]
alisamadzadeh46@gmail.com
66234f05a7f6f820e92d03a4479a6148be56e6a3
1fe56144905244643dbbab69819720bc16031657
/.history/books/models_20210422134752.py
92cb170912298100d4da3d6feccd653ccf98d187
[]
no_license
RaghdaMadiane/django
2052fcdd532f9678fefb034bd60e44f466bd9759
6ca3f87f0b72880f071d90968f0a63ea5badcca8
refs/heads/master
2023-04-15T17:28:25.939823
2021-04-24T22:33:21
2021-04-24T22:33:21
361,279,372
0
0
null
null
null
null
UTF-8
Python
false
false
1,146
py
from django.db import models from django.contrib.auth.models import User import uuid class Category(models.Model): class Meta: verbose_name_plural="categories" name = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name # class Metric(models.Model): # visits = models.IntegerField(null=True,blank=True) # ratio = models.DecimalField(null=True,blank=True,max_digits=2,decimal_places=1) # def __str__(self): # return f"{self.visits} visits | ratio: {self.ratio}" class Isbn(models.): number=models def __str__(self): return self.name class Book(models.Model): title=models.CharField( max_length=250) author=models.CharField(max_length=100) user=models.ForeignKey(User,on_delete=models.CASCADE,related_name="Books") categories=models.ManyToManyField(Category) # metrics=models.OneToOneField(Metric,on_delete=models.CASCADE,null=True,blank=True) # tag=models.ForeignKey(Tag,null=True,blank=True,on_delete=models.CASCADE) def __str__(self): return self.title
[ "raghdamadiane@gmail.com" ]
raghdamadiane@gmail.com
2cb94f2886fd17bfec48f28e55cc1d7bdcaa1b10
a6e4a6f0a73d24a6ba957277899adbd9b84bd594
/sdk/python/pulumi_azure_native/apimanagement/v20200601preview/get_api_operation_policy.py
8bd64155864e351bfc26b33f84d54382ac902c40
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
MisinformedDNA/pulumi-azure-native
9cbd75306e9c8f92abc25be3f73c113cb93865e9
de974fd984f7e98649951dbe80b4fc0603d03356
refs/heads/master
2023-03-24T22:02:03.842935
2021-03-08T21:16:19
2021-03-08T21:16:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,468
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = [ 'GetApiOperationPolicyResult', 'AwaitableGetApiOperationPolicyResult', 'get_api_operation_policy', ] @pulumi.output_type class GetApiOperationPolicyResult: """ Policy Contract details. """ def __init__(__self__, format=None, id=None, name=None, type=None, value=None): if format and not isinstance(format, str): raise TypeError("Expected argument 'format' to be a str") pulumi.set(__self__, "format", format) if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if name and not isinstance(name, str): raise TypeError("Expected argument 'name' to be a str") pulumi.set(__self__, "name", name) if type and not isinstance(type, str): raise TypeError("Expected argument 'type' to be a str") pulumi.set(__self__, "type", type) if value and not isinstance(value, str): raise TypeError("Expected argument 'value' to be a str") pulumi.set(__self__, "value", value) @property @pulumi.getter def format(self) -> Optional[str]: """ Format of the policyContent. """ return pulumi.get(self, "format") @property @pulumi.getter def id(self) -> str: """ Resource ID. """ return pulumi.get(self, "id") @property @pulumi.getter def name(self) -> str: """ Resource name. """ return pulumi.get(self, "name") @property @pulumi.getter def type(self) -> str: """ Resource type for API Management resource. """ return pulumi.get(self, "type") @property @pulumi.getter def value(self) -> str: """ Contents of the Policy as defined by the format. """ return pulumi.get(self, "value") class AwaitableGetApiOperationPolicyResult(GetApiOperationPolicyResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetApiOperationPolicyResult( format=self.format, id=self.id, name=self.name, type=self.type, value=self.value) def get_api_operation_policy(api_id: Optional[str] = None, format: Optional[str] = None, operation_id: Optional[str] = None, policy_id: Optional[str] = None, resource_group_name: Optional[str] = None, service_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetApiOperationPolicyResult: """ Policy Contract details. :param str api_id: API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number. :param str format: Policy Export Format. :param str operation_id: Operation identifier within an API. Must be unique in the current API Management service instance. :param str policy_id: The identifier of the Policy. :param str resource_group_name: The name of the resource group. :param str service_name: The name of the API Management service. """ __args__ = dict() __args__['apiId'] = api_id __args__['format'] = format __args__['operationId'] = operation_id __args__['policyId'] = policy_id __args__['resourceGroupName'] = resource_group_name __args__['serviceName'] = service_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-native:apimanagement/v20200601preview:getApiOperationPolicy', __args__, opts=opts, typ=GetApiOperationPolicyResult).value return AwaitableGetApiOperationPolicyResult( format=__ret__.format, id=__ret__.id, name=__ret__.name, type=__ret__.type, value=__ret__.value)
[ "noreply@github.com" ]
MisinformedDNA.noreply@github.com
ad4ec0230be02dee98e2add102f733659a731918
e71b6d14fbdbc57c7234ca45a47329d7d02fc6f7
/flask_api/venv/lib/python3.7/site-packages/vsts/git/v4_1/models/git_commit_changes.py
5986784ad2ae58eca95cc064936a557c15a18a50
[]
no_license
u-blavins/secret_sasquatch_society
c36993c738ab29a6a4879bfbeb78a5803f4f2a57
0214eadcdfa9b40254e331a6617c50b422212f4c
refs/heads/master
2020-08-14T00:39:52.948272
2020-01-22T13:54:58
2020-01-22T13:54:58
215,058,646
1
0
null
null
null
null
UTF-8
Python
false
false
1,171
py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- from msrest.serialization import Model class GitCommitChanges(Model): """GitCommitChanges. :param change_counts: :type change_counts: dict :param changes: :type changes: list of :class:`object <git.v4_1.models.object>` """ _attribute_map = { 'change_counts': {'key': 'changeCounts', 'type': '{int}'}, 'changes': {'key': 'changes', 'type': '[object]'} } def __init__(self, change_counts=None, changes=None): super(GitCommitChanges, self).__init__() self.change_counts = change_counts self.changes = changes
[ "usama.blavins1@gmail.com" ]
usama.blavins1@gmail.com
2362371a28d13cb9cafaadbc182329e9fbd924c5
679fc3c015f31859899543c6844c76da44941a28
/main/migrations/0003_auto_20151024_1811.py
d9fd8c07a24c7e40590184cead52757839f2608c
[]
no_license
swheatley/twitter
2323a2c0270b4cd13795e8f0bf342aa428fd5274
ce118d22368d958696710baf44dcd07115e1ce66
refs/heads/master
2021-01-10T03:12:42.113952
2015-11-18T05:18:13
2015-11-18T05:18:13
46,396,954
0
0
null
null
null
null
UTF-8
Python
false
false
1,576
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20151023_1738'), ] operations = [ migrations.DeleteModel( name='Place', ), migrations.RemoveField( model_name='tweet', name='favorites', ), migrations.RemoveField( model_name='tweet', name='lang', ), migrations.AddField( model_name='tweet', name='created_at', field=models.CharField(max_length=200, null=True, blank=True), ), migrations.AddField( model_name='tweet', name='location', field=models.CharField(max_length=100, null=True, blank=True), ), migrations.AddField( model_name='tweet', name='profile_image_url', field=models.CharField(max_length=100, null=True, blank=True), ), migrations.AddField( model_name='tweet', name='screen_name', field=models.CharField(max_length=100, null=True, blank=True), ), migrations.AddField( model_name='tweet', name='source', field=models.CharField(max_length=150, null=True, blank=True), ), migrations.AddField( model_name='tweet', name='time_zone', field=models.IntegerField(null=True, blank=True), ), ]
[ "shaylee1@me.com" ]
shaylee1@me.com
afea4008f8c4c5c9538d98a64af56f9314244cb0
2e8f0de7a1526ef511927783235edc93f7c90036
/communicare/core/migrations/0033_expense.py
bfde8cbaa2f90f3e72d5fa3cfcba4cecd9ac021e
[]
no_license
ConTTudOweb/CommunicareProject
3d663578dfdeb455bc49419b3d103daec69c8fab
211a1124c8c4549c609832ad71069a55c714a430
refs/heads/master
2022-12-21T12:59:35.424560
2021-05-10T22:16:15
2021-05-10T22:16:15
163,891,380
0
1
null
2022-12-08T07:43:22
2019-01-02T21:27:42
HTML
UTF-8
Python
false
false
922
py
# Generated by Django 2.1.8 on 2019-09-23 16:58 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0032_registration_net_value'), ] operations = [ migrations.CreateModel( name='Expense', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.CharField(max_length=255, verbose_name='descrição')), ('amount', models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True, verbose_name='valor')), ('event', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='core.Event', verbose_name='evento')), ], options={ 'verbose_name': 'despesa', }, ), ]
[ "sandrofolk@hotmail.com" ]
sandrofolk@hotmail.com
70221007808c9d0fe7c30493eff55d871b67547e
46279163a543cd8820bdc38133404d79e787c5d2
/torch/distributed/rpc/rref_proxy.py
f087514d92a8deea48d50c6d77e6e353ff2fe889
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0", "BSD-2-Clause" ]
permissive
erwincoumans/pytorch
31738b65e7b998bfdc28d0e8afa7dadeeda81a08
ae9f39eb580c4d92157236d64548b055f71cf14b
refs/heads/master
2023-01-23T10:27:33.628897
2020-12-06T01:22:00
2020-12-06T01:23:40
318,930,000
5
1
NOASSERTION
2020-12-06T01:58:57
2020-12-06T01:58:56
null
UTF-8
Python
false
false
1,197
py
from functools import partial from . import functions import torch def _local_invoke(rref, func_name, args, kwargs): return getattr(rref.local_value(), func_name)(*args, **kwargs) @functions.async_execution def _local_invoke_async_execution(rref, func_name, args, kwargs): return getattr(rref.local_value(), func_name)(*args, **kwargs) def _invoke_rpc(rref, rpc_api, func_name, *args, **kwargs): rref_type = rref._get_type() _invoke_func = _local_invoke # Bypass ScriptModules when checking for async function attribute. bypass_type = issubclass(rref_type, torch.jit.ScriptModule) or issubclass( rref_type, torch._C.ScriptModule ) if not bypass_type: func = getattr(rref_type, func_name) if hasattr(func, "_wrapped_async_rpc_function"): _invoke_func = _local_invoke_async_execution return rpc_api( rref.owner(), _invoke_func, args=(rref, func_name, args, kwargs) ) class RRefProxy: def __init__(self, rref, rpc_api): self.rref = rref self.rpc_api = rpc_api def __getattr__(self, func_name): return partial(_invoke_rpc, self.rref, self.rpc_api, func_name)
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
596324358e29714d198611478dfc5c42b15d24f5
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_136/185.py
9299bc6923e7f47d089372fb9fc20d6aba78a70c
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
434
py
file = open('input', 'r') problems = int(file.readline()) for i in range(1, problems+1): values = file.readline().split() C = float(values[0]) F = float(values[1]) X = float(values[2]) F_t = 2 # total cookie production T_t = 0.0 # total Time while True: if (X-C) / F_t < X / (F_t + F): T_t = T_t + X / F_t print 'Case #' + str(i) + ': ' + str(T_t) break # exit loop else: T_t = T_t + C / F_t F_t = F_t + F
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
2ddbc6fa0cef023e1fcc6a98054552d1885b1d99
e23a4f57ce5474d468258e5e63b9e23fb6011188
/125_algorithms/_exercises/exercises/_algorithms_challenges/pybites/beginner/143_v2/test_merge.py
fea2b47c842e7412cac0de3aad7246451f21676d
[]
no_license
syurskyi/Python_Topics
52851ecce000cb751a3b986408efe32f0b4c0835
be331826b490b73f0a176e6abed86ef68ff2dd2b
refs/heads/master
2023-06-08T19:29:16.214395
2023-05-29T17:09:11
2023-05-29T17:09:11
220,583,118
3
2
null
2023-02-16T03:08:10
2019-11-09T02:58:47
Python
UTF-8
Python
false
false
438
py
# ____ ? _______ ? ? # # # ___ test_regular_name # ... ? 'tim' __ 30 # ... ? 'helen' __ 26 # ... ? 'otto' __ 44 # # # ___ test_case_insensitive_lookup # ... ? 'Tim' __ 30 # ... ? 'BOB' __ 17 # ... ? 'BrEnDa' __ 17 # # # ___ test_name_not_found # ... ? 'timothy' __ ? # ... ? N.. __ ? # ... ? F.. __ ? # ... ?(-1) __ ? # # # ___ test_duplicate_name # ... ? 'thomas' __ 46 # ... ? 'ana' __ 26
[ "sergejyurskyj@yahoo.com" ]
sergejyurskyj@yahoo.com
47958a14553a0915ab6b56f000a447ea7dd84437
35bad5d9982b5d4f107fc39c41f16e99a5eae1f3
/leaflet/views/admin/sitetext.py
8b98796f1183721c1c59d37f075bbd3ea4447018
[]
no_license
umeboshi2/leaflet
17c502ce87076633e3b98c6c85efcb07cda2db6b
63a60d43b93bd07d7d04165ebbe63cb97a44d537
refs/heads/master
2020-04-25T12:19:17.824626
2014-01-31T19:28:15
2014-01-31T19:28:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,338
py
from cStringIO import StringIO from datetime import datetime import transaction from pyramid.httpexceptions import HTTPFound, HTTPNotFound from pyramid.security import authenticated_userid from pyramid.renderers import render from pyramid.response import Response from trumpet.models.sitecontent import SiteText from trumpet.resources import MemoryTmpStore from trumpet.managers.admin.images import ImageManager from trumpet.views.menus import BaseMenu from leaflet.views.base import AdminViewer from leaflet.views.admin.base import make_main_menu from leaflet.managers.wiki import WikiArchiver import colander import deform tmpstore = MemoryTmpStore() class EditSiteTextSchema(colander.Schema): name = colander.SchemaNode( colander.String(), title='Name') content = colander.SchemaNode( colander.String(), title='Content', widget=deform.widget.TextAreaWidget(rows=10, cols=60)) class SiteTextViewer(AdminViewer): def __init__(self, request): super(SiteTextViewer, self).__init__(request) self.layout.main_menu = make_main_menu(request) self.images = ImageManager(self.request.db) self._dispatch_table = dict( list=self.list_site_text, add=self.create_site_text, delete=self.main, confirmdelete=self.main, viewentry=self.view_site_text, editentry=self.edit_site_text, create=self.create_site_text, download_wiki_archive=self.download_wiki_archive,) self.context = self.request.matchdict['context'] self._view = self.context self._set_options_menu() self.dispatch() def _set_options_menu(self): menu = BaseMenu() menu.set_header('Site Text Actions') url = self.url(context='list', id='all') menu.append_new_entry('List Entries', url) url = self.url(context='create', id='new') menu.append_new_entry('Create New Entry', url) url = self.url(context='download_wiki_archive', id='all') menu.append_new_entry('Download Wiki Archive', url) self.layout.options_menus = dict(actions=menu) def main(self): content = '<h1>Here is where we manage site text.</h1>' self.layout.content = content def manage_site_text(self): action = None if 'action' in self.request.GET: action = self.request.GET['action'] return self._manage_site_text_action_map[action]() def view_site_text(self): id = int(self.request.matchdict['id']) self.layout.footer = str(type(id)) entry = self.request.db.query(SiteText).get(id) self.layout.subheader = entry.name self.layout.content = '<pre width="80">%s</pre>' % entry.content def list_site_text(self): template = 'leaflet:templates/list-site-text.mako' entries = self.request.db.query(SiteText).all() env = dict(viewer=self, entries=entries) self.layout.content = self.render(template, env) def _edit_site_text_form(self): schema = EditSiteTextSchema() submit_button = deform.form.Button(name='submit_site_text', title='Update Content') form = deform.Form(schema, buttons=(submit_button,)) self.layout.resources.deform_auto_need(form) return form def _validate_site_text(self, form, create=False): controls = self.request.POST.items() try: data = form.validate(controls) except deform.ValidationFailure, e: self.layout.content = e.render() return {} if create: db = self.request.db query = db.query(SiteText).filter_by(name=data['name']) rows = query.all() if rows: h1 = '<h1>Site Text "%s" already exists.</h1>' h1 = h1 % data['name'] self.layout.content = h1 + form.render(data) return {} else: self.layout.subheader = str(rows) return data def _submit_site_text(self, form, data={}): rendered = form.render(data) if 'submit_site_text' in self.request.params: if not self._validate_site_text(form): return else: self.layout.content = rendered self.layout.subheader = 'Please edit content' def create_site_text(self): form = self._edit_site_text_form() # check submission if 'submit_site_text' in self.request.params: valid = self._validate_site_text(form, create=True) if not valid: return transaction.begin() entry = SiteText(valid['name'], valid['content']) self.request.db.add(entry) transaction.commit() self.layout.content = 'Submitted for approval.' else: self.layout.content = form.render() self.layout.subheader = 'Please edit content' def edit_site_text(self): form = self._edit_site_text_form() rendered = form.render() id = int(self.request.matchdict['id']) entry = self.request.db.query(SiteText).get(id) data = dict(name=entry.name, content=entry.content) if 'submit_site_text' in self.request.params: valid = self._validate_site_text(form) if not valid: return transaction.begin() entry.content = valid['content'] self.request.db.add(entry) transaction.commit() self.layout.content = 'Submitted for approval.' else: self.layout.content = form.render(data) self.layout.subheader = 'Please edit content' def download_wiki_archive(self): archiver = WikiArchiver(self.request.db) archiver.create_new_zipfile() archive = archiver.archive_pages() content_type = 'application/zip' r = Response(content_type=content_type, body=archive) r.content_disposition = 'attachment; filename="tutwiki-archive.zip"' self.response = r
[ "joseph.rawson.works@littledebian.org" ]
joseph.rawson.works@littledebian.org
dcba76ba54dce28cee2bc6891fc957ec5889ac55
1bed2f766620acf085ed2d7fd3e354a3482b8960
/homeassistant/components/hassio/websocket_api.py
eb0d6c5407700eb07de2f6ea5f08199c18eccb70
[ "Apache-2.0" ]
permissive
elupus/home-assistant
5cbb79a2f25a2938a69f3988534486c269b77643
564150169bfc69efdfeda25a99d803441f3a4b10
refs/heads/dev
2023-08-28T16:36:04.304864
2022-09-16T06:35:12
2022-09-16T06:35:12
114,460,522
2
2
Apache-2.0
2023-02-22T06:14:54
2017-12-16T12:50:55
Python
UTF-8
Python
false
false
4,002
py
"""Websocekt API handlers for the hassio integration.""" import logging from numbers import Number import re import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.websocket_api.connection import ActiveConnection from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import Unauthorized import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from . import HassioAPIError from .const import ( ATTR_DATA, ATTR_ENDPOINT, ATTR_METHOD, ATTR_RESULT, ATTR_TIMEOUT, ATTR_WS_EVENT, DOMAIN, EVENT_SUPERVISOR_EVENT, WS_ID, WS_TYPE, WS_TYPE_API, WS_TYPE_EVENT, WS_TYPE_SUBSCRIBE, ) from .handler import HassIO SCHEMA_WEBSOCKET_EVENT = vol.Schema( {vol.Required(ATTR_WS_EVENT): cv.string}, extra=vol.ALLOW_EXTRA, ) # Endpoints needed for ingress can't require admin because addons can set `panel_admin: false` # pylint: disable=implicit-str-concat WS_NO_ADMIN_ENDPOINTS = re.compile( r"^(?:" r"|/ingress/(session|validate_session)" r"|/addons/[^/]+/info" r")$" ) # pylint: enable=implicit-str-concat _LOGGER: logging.Logger = logging.getLogger(__package__) @callback def async_load_websocket_api(hass: HomeAssistant): """Set up the websocket API.""" websocket_api.async_register_command(hass, websocket_supervisor_event) websocket_api.async_register_command(hass, websocket_supervisor_api) websocket_api.async_register_command(hass, websocket_subscribe) @websocket_api.require_admin @websocket_api.websocket_command({vol.Required(WS_TYPE): WS_TYPE_SUBSCRIBE}) @websocket_api.async_response async def websocket_subscribe( hass: HomeAssistant, connection: ActiveConnection, msg: dict ): """Subscribe to supervisor events.""" @callback def forward_messages(data): """Forward events to websocket.""" connection.send_message(websocket_api.event_message(msg[WS_ID], data)) connection.subscriptions[msg[WS_ID]] = async_dispatcher_connect( hass, EVENT_SUPERVISOR_EVENT, forward_messages ) connection.send_message(websocket_api.result_message(msg[WS_ID])) @websocket_api.websocket_command( { vol.Required(WS_TYPE): WS_TYPE_EVENT, vol.Required(ATTR_DATA): SCHEMA_WEBSOCKET_EVENT, } ) @websocket_api.async_response async def websocket_supervisor_event( hass: HomeAssistant, connection: ActiveConnection, msg: dict ): """Publish events from the Supervisor.""" connection.send_result(msg[WS_ID]) async_dispatcher_send(hass, EVENT_SUPERVISOR_EVENT, msg[ATTR_DATA]) @websocket_api.websocket_command( { vol.Required(WS_TYPE): WS_TYPE_API, vol.Required(ATTR_ENDPOINT): cv.string, vol.Required(ATTR_METHOD): cv.string, vol.Optional(ATTR_DATA): dict, vol.Optional(ATTR_TIMEOUT): vol.Any(Number, None), } ) @websocket_api.async_response async def websocket_supervisor_api( hass: HomeAssistant, connection: ActiveConnection, msg: dict ): """Websocket handler to call Supervisor API.""" if not connection.user.is_admin and not WS_NO_ADMIN_ENDPOINTS.match( msg[ATTR_ENDPOINT] ): raise Unauthorized() supervisor: HassIO = hass.data[DOMAIN] try: result = await supervisor.send_command( msg[ATTR_ENDPOINT], method=msg[ATTR_METHOD], timeout=msg.get(ATTR_TIMEOUT, 10), payload=msg.get(ATTR_DATA, {}), ) if result.get(ATTR_RESULT) == "error": raise HassioAPIError(result.get("message")) except HassioAPIError as err: _LOGGER.error("Failed to to call %s - %s", msg[ATTR_ENDPOINT], err) connection.send_error( msg[WS_ID], code=websocket_api.ERR_UNKNOWN_ERROR, message=str(err) ) else: connection.send_result(msg[WS_ID], result.get(ATTR_DATA, {}))
[ "noreply@github.com" ]
elupus.noreply@github.com
58d550ac0a1237bb4221e2f0f80bac28fda11a38
8d9318a33afc2c3b5ca8ac99fce0d8544478c94a
/Books/Casandra DB/opscenter-5.1.0/lib/py-unpure/twisted/cred/portal.py
753b403a49430029b67597bf02961652837e848a
[]
no_license
tushar239/git-large-repo
e30aa7b1894454bf00546312a3fb595f6dad0ed6
9ee51112596e5fc3a7ab2ea97a86ec6adc677162
refs/heads/master
2021-01-12T13:48:43.280111
2016-11-01T22:14:51
2016-11-01T22:14:51
69,609,373
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:d41d59435554fcf0301c2274fa426aa4626a815369ad9324a386bc1b55e624a4 size 5349
[ "tushar239@gmail.com" ]
tushar239@gmail.com
760d089693d1a60a72a09c0a91b878dd7725787c
409cec0b3346bbb88fdaf1df9adbd38de842f6b6
/UploadDataToES/test/testCovertStrToDatatime.py
06098c1dc36750a7f7fe48522406cb6fdaaa567f
[]
no_license
parahaoer/pythoncode
3276815d9cffbff768128ad83db1e344702f7bd8
7cbf7c4e0df7678335e6fbbb48115373c6a8a0df
refs/heads/master
2020-11-26T06:55:07.685666
2020-05-05T02:20:33
2020-05-05T02:20:33
228,995,890
1
1
null
null
null
null
UTF-8
Python
false
false
548
py
''' 需要用大的时间减去小的时间,才能得到以秒为单位的时间差 如果用小的时间减去大的时间,结果为86399 ''' import datetime str_p = "2019-05-14T23:16:11.010Z" str_q = "2019-05-14T23:16:11.011Z" str_r = "2019-05-14T23:16:09.819Z" dateTime_p = datetime.datetime.strptime(str_r,'%Y-%m-%dT%H:%M:%S.%fZ') dateTime_q = datetime.datetime.strptime(str_q,'%Y-%m-%dT%H:%M:%S.%fZ') if dateTime_p.__gt__(dateTime_q): print((dateTime_p - dateTime_q).seconds) else: print((dateTime_q - dateTime_p).seconds)
[ "884101054@qq.com" ]
884101054@qq.com
9d5335f025da0b78549226cfe60197b70b82deec
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_81/295.py
320b05162c6c66e77f1bf427cf3bcdffd862d6cf
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,758
py
# # Google Code Jam 2011 # Roaund 1B: A. RPI # submission by EnTerr # ''' Input 2 3 .10 0.1 10. 4 .11. 0.00 01.1 .10. Output Case #1: 0.5 0.5 0.5 Case #2: 0.645833333333 0.368055555556 0.604166666667 0.395833333333 ''' import sys import psyco psyco.full() inf = open(sys.argv[1]) def input(): return inf.readline().strip() def avg(scores): num = 0. denum = 0. #print scores for v in scores: num += v[0] denum += v[1] return num / denum def rpi(games): global guest global home global P guest = {} home = {} P = {} for x,y,_ in games: guest[x] = [] guest[y] = [] home[x] = [] home[y] = [] for x,y,win in games: f = 14 - 8 * win guest[x].append( (win*f, f, y) ) guest[y].append( (f - win*f, f, x) ) home[x].append( (win, 1, y) ) home[y].append( (1-win, 1, x) ) for t in home: P[t] = avg([ (avg([(x,y) for x,y,z in home[o] if z!=t]), 2) for i,j,o in home[t] ]) #print 'home', home #print 'guest', guest for t in home: home[t] = avg( [(P[o],2) for x,y,o in home[t]]) home[t] += avg( guest[t] )/4 home[t] += P[t] return home for caseNo in range(1, int(input())+1): print >>sys.stderr, caseNo print 'Case #%d:' % caseNo sco = [] for i in range(int(input())): s = input() for j in range(len(s)): if s[j] in '01': sco.append( [i,j, int(s[j])] ) r = rpi(sco) for i in range(len(r)): print r[i]
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
448549db9aca16d831fdea6643397e4b1a98a416
0facb323be8a76bb4c168641309972fa77cbecf2
/Configurations/HWWSemiLepHighMass/nanoAODv5/v6_production/2016/SKIM10/HMVAR10_Full_SBI/FilterMelaReweights.py
43c5460e94e2d470c6b9a5fb095fd1194f74e2d1
[]
no_license
bhoh/SNuAnalytics
ef0a1ba9fa0d682834672a831739dfcfa1e7486b
34d1fc062e212da152faa83be50561600819df0e
refs/heads/master
2023-07-06T03:23:45.343449
2023-06-26T12:18:28
2023-06-26T12:18:28
242,880,298
0
1
null
2020-02-25T01:17:50
2020-02-25T01:17:49
null
UTF-8
Python
false
false
5,858
py
import ROOT from math import sqrt from LatinoAnalysis.Tools.commonTools import * def GetMinMaxCut(filelist,model,mode,nsigma=2): #Root.gROOT.SetBatch(True) Sum=0 Sum2=0 Nentry=0 print "===="+model+mode+"=====" print filelist[0] for f in filelist: if '###' in f: f=f.replace("###","") myfile=ROOT.TFile.Open(f,"read") mytree=myfile.Get("Events") mytree.Draw(model+mode) htemp=ROOT.gPad.GetPrimitive("htemp") #print 'MEAN=',htemp.GetMean() #print 'DEV =',htemp.GetStdDev() #print "Integrals=", htemp.Integral() #print "GetEntries=",htemp.GetEntries() Sum+=htemp.GetMean()*htemp.GetEntries() Sum2+=(htemp.GetStdDev()*htemp.GetStdDev()+htemp.GetMean()*htemp.GetMean())*htemp.GetEntries() Nentry+=htemp.GetEntries() myfile.Close() #print "Total MEAN=",Sum/Nentry #print "Total DEV=",sqrt((Sum2/Nentry)-(Sum/Nentry)*(Sum/Nentry)) #print "GetEntries=",Nentry Mean=Sum/Nentry dev=sqrt((Sum2/Nentry)-(Sum/Nentry)*(Sum/Nentry)) return Mean-nsigma*dev, Mean+nsigma*dev ##--get cuts for multiple modes def GetMinMaxCuts(filelist,model,modes=['','_I','_B','_H','_I_HB'],nsigma=2): ROOT.gROOT.SetBatch(True) mydict={} for mode in modes: mydict[mode]={} mydict[mode]['Sum']=0 mydict[mode]['Sum2']=0 mydict[mode]['Nentry']=0 mydict[mode]['Mean']=0 mydict[mode]['dev']=0 mydict[mode]['min']=0 mydict[mode]['max']=0 mydict['Nveto']=0 mydict['Npass']=0 mydict['cut']='1' #Sum=0 #Sum2=0 #Nentry=0 print filelist[0] for f in filelist: if '###' in f: f=f.replace("###","") myfile=ROOT.TFile.Open(f,"read") mytree=myfile.Get("Events") for mode in modes: #print "===="+model+mode+"=====" mytree.Draw(model+mode) #print "after draw" htemp=ROOT.gPad.GetPrimitive("htemp") #print 'MEAN=',htemp.GetMean() #print 'DEV =',htemp.GetStdDev() #print "Integrals=", htemp.Integral() #print "GetEntries=",htemp.GetEntries() mydict[mode]['Sum']+=htemp.GetMean()*htemp.GetEntries() mydict[mode]['Sum2']+=(htemp.GetStdDev()*htemp.GetStdDev()+htemp.GetMean()*htemp.GetMean())*htemp.GetEntries() mydict[mode]['Nentry']+=htemp.GetEntries() myfile.Close() #print "Total MEAN=",Sum/Nentry #print "Total DEV=",sqrt((Sum2/Nentry)-(Sum/Nentry)*(Sum/Nentry)) #print "GetEntries=",Nentry for mode in modes: mydict[mode]['Mean']=mydict[mode]['Sum']/mydict[mode]['Nentry'] mydict[mode]['dev']=sqrt((mydict[mode]['Sum2']/mydict[mode]['Nentry'])-(mydict[mode]['Sum']/mydict[mode]['Nentry'])*(mydict[mode]['Sum']/mydict[mode]['Nentry'])) mydict[mode]['min']=mydict[mode]['Mean']-nsigma*mydict[mode]['dev'] mydict[mode]['max']=mydict[mode]['Mean']+nsigma*mydict[mode]['dev'] for mode in modes: mydict['cut']+='&&('+model+mode+'<='+str(mydict[mode]['max'])+')&&('+model+mode+'>='+str(mydict[mode]['min'])+')' mydict['cut']="("+mydict['cut']+')' for f in filelist: if '###' in f: f=f.replace("###","") myfile=ROOT.TFile.Open(f,"read") mytree=myfile.Get("Events") cut='0' for mode in modes: #print "===="+model+mode+"=====" #mytree.Draw(model+mode, model+mode+'>'+str(mydict[mode]['max'])+'||'+model+mode+'<'+str(mydict[mode]['min'])) cut+='||('+model+mode+'>'+str(mydict[mode]['max'])+')||('+model+mode+'<'+str(mydict[mode]['min'])+')' #print cut mytree.Draw('abs('+model+mode+')',cut) #print "after draw" htemp=ROOT.gPad.GetPrimitive("htemp") #print "veto's mean=",htemp.GetMean() try: #print "veto's mean=",htemp.GetMean() mydict['Nveto']+=htemp.GetEntries() except AttributeError: #print "veto's mean=0" mydict['Nveto']+=0 cut='1' for mode in modes: cut+='&&('+model+mode+'<='+str(mydict[mode]['max'])+')&&('+model+mode+'>='+str(mydict[mode]['min'])+')' mytree.Draw('1',cut) htemp=ROOT.gPad.GetPrimitive("htemp") try: mydict['Npass']+=htemp.GetEntries() except AttributeError: mydict['Npass']+=0 return mydict #def GetStatement(filelist,model,modes=['','_I','_B','_H','_HB'],nsigma=2): # dict_min_max=GetMinMaxCuts(filelist,model,modes,nsigma) if __name__ == '__main__': SITE=os.uname()[1] xrootdPath = 'root://cms-xrdr.private.lo:2094' treeBaseDir = "/xrootd/store/user/jhchoi/Latino/HWWNano/" CAMPAIGN='Fall2017_102X_nAODv5_Full2017v6' STEP="MCl1loose2017v6__MCCorr2017v6__HMSemilepSKIMv6_10__BWReweight__HMFull_jhchoi10_nom__HMLHEAna" directory=treeBaseDir+CAMPAIGN+'/'+STEP import sys sys.path.insert(0, "MassPoints") from List_MX import * from List_MX_VBF import * model="cprime1.0BRnew0.0" for MX in List_MX: print MX MELA_cuts=GetMinMaxCuts(getSampleFiles(directory,'GluGluHToWWToLNuQQ_M'+str(MX),False,'nanoLatino_'),model) cut=MELA_cuts['cut'] print cut ''' MX=4000 mode='_I' thisdict=GetMinMaxCuts(getSampleFiles(directory,'GluGluHToWWToLNuQQ_M'+str(MX),False,'nanoLatino_'),'MSSModel',['','_I','_B','_I_HB','_H']) vlist=['Mean','Nentry','dev','min','max'] #,'Nveto','Npass'] print mode for v in vlist: print v,thisdict[mode][v] print 'Nveto=',thisdict['Nveto'] print 'Npass=',thisdict['Npass'] print 'cut=',thisdict['cut'] '''
[ "soarnsoar@gmail.com" ]
soarnsoar@gmail.com
0d4b7775ac08f9045cc81bf06fee576d22c7ee4d
3fc4cac282465350d9b2983527140fc735a0d273
/venv/bin/list_instances
e632e65514a792427c742a744945098751afb9b4
[]
no_license
Orderlee/SBA_STUDY
2cfeea54d4a9cbfd0c425e1de56324afcc547b81
4642546e7546f896fc8b06e9daba25d27c29e154
refs/heads/master
2022-12-25T01:08:05.168970
2020-09-27T14:57:23
2020-09-27T14:57:23
299,050,168
0
0
null
null
null
null
UTF-8
Python
false
false
3,140
#!/Users/YoungWoo/PycharmProjects/ClassProject/venv/bin/python import sys from operator import attrgetter from optparse import OptionParser import boto from boto.ec2 import regions HEADERS = { 'ID': {'get': attrgetter('id'), 'length':15}, 'Zone': {'get': attrgetter('placement'), 'length':15}, 'Groups': {'get': attrgetter('groups'), 'length':30}, 'Hostname': {'get': attrgetter('public_dns_name'), 'length':50}, 'PrivateHostname': {'get': attrgetter('private_dns_name'), 'length':50}, 'State': {'get': attrgetter('state'), 'length':15}, 'Image': {'get': attrgetter('image_id'), 'length':15}, 'Type': {'get': attrgetter('instance_type'), 'length':15}, 'IP': {'get': attrgetter('ip_address'), 'length':16}, 'PrivateIP': {'get': attrgetter('private_ip_address'), 'length':16}, 'Key': {'get': attrgetter('key_name'), 'length':25}, 'T:': {'length': 30}, } def get_column(name, instance=None): if name.startswith('T:'): _, tag = name.split(':', 1) return instance.tags.get(tag, '') return HEADERS[name]['get'](instance) def main(): parser = OptionParser() parser.add_option("-r", "--region", help="Region (default us-east-1)", dest="region", default="us-east-1") parser.add_option("-H", "--headers", help="Set headers (use 'T:tagname' for including tags)", default=None, action="store", dest="headers", metavar="ID,Zone,Groups,Hostname,State,T:Name") parser.add_option("-t", "--tab", help="Tab delimited, skip header - useful in shell scripts", action="store_true", default=False) parser.add_option("-f", "--filter", help="Filter option sent to DescribeInstances API call, format is key1=value1,key2=value2,...", default=None) (options, args) = parser.parse_args() # Connect the region for r in regions(): if r.name == options.region: region = r break else: print("Region %s not found." % options.region) sys.exit(1) ec2 = boto.connect_ec2(region=region) # Read headers if options.headers: headers = tuple(options.headers.split(',')) else: headers = ("ID", 'Zone', "Groups", "Hostname") # Create format string format_string = "" for h in headers: if h.startswith('T:'): format_string += "%%-%ds" % HEADERS['T:']['length'] else: format_string += "%%-%ds" % HEADERS[h]['length'] # Parse filters (if any) if options.filter: filters = dict([entry.split('=') for entry in options.filter.split(',')]) else: filters = {} # List and print if not options.tab: print(format_string % headers) print("-" * len(format_string % headers)) for r in ec2.get_all_reservations(filters=filters): groups = [g.name for g in r.groups] for i in r.instances: i.groups = ','.join(groups) if options.tab: print("\t".join(tuple(get_column(h, i) for h in headers))) else: print(format_string % tuple(get_column(h, i) for h in headers)) if __name__ == "__main__": main()
[ "61268230+Orderlee@users.noreply.github.com" ]
61268230+Orderlee@users.noreply.github.com
97c3b121be36f09c69f51581c20a82d254464bc0
751d837b8a4445877bb2f0d1e97ce41cd39ce1bd
/codegolf/szekeress-sequence.py
9da4b302795111ca6d2dc7d80a80fcc565d91a39
[ "MIT" ]
permissive
qeedquan/challenges
d55146f784a3619caa4541ac6f2b670b0a3dd8ba
56823e77cf502bdea68cce0e1221f5add3d64d6a
refs/heads/master
2023-08-11T20:35:09.726571
2023-08-11T13:02:43
2023-08-11T13:02:43
115,886,967
2
1
null
null
null
null
UTF-8
Python
false
false
1,751
py
#!/usr/bin/env python """ Definition a(1)=1 a(2)=2 a(n) is smallest number k>a(n−1) which avoids any 3-term arithmetic progression in a(1),a(2),...,a(n−1),k. In other words, a(n) is the smallest number k>a(n−1) such that there does not exist x,y where 0<x<y<n and a(y)−a(x)=k−a(y). Worked out example For n=5: We have a(1),a(2),a(3),a(4)=1,2,4,5 If a(5)=6, then 2,4,6 form an arithmetic progression. If a(5)=7, then 1,4,7 form an arithmetic progression. If a(5)=8, then 2,5,8 form an arithmetic progression. If a(5)=9, then 1,5,9 form an arithmetic progression. If a(5)=10, no arithmetic progression can be found. Therefore a(5)=10. Task Given n, output a(n). Specs n will be a positive integer. You can use 0-indexed instead of 1-indexed, in which case n can be 0. Please state it in your answer if you are using 0-indexed. Scoring Since we are trying to avoid 3-term arithmetic progression, and 3 is a small number, your code should be as small (i.e. short) as possible, in terms of byte-count. Testcases The testcases are 1-indexed. You can use 0-indexed, but please specify it in your answer if you do so. 1 1 2 2 3 4 4 5 5 10 6 11 7 13 8 14 9 28 10 29 11 31 12 32 13 37 14 38 15 40 16 41 17 82 18 83 19 85 20 86 10000 1679657 References WolframMathWorld OEIS A003278 """ # https://oeis.org/A003278 def szekeres(n): return int(format(n-1, 'b'), 3) + 1 def main(): tab = [[1, 1], [2, 2], [3, 4], [4, 5], [5, 10], [6, 11], [7, 13], [8, 14], [9, 28], [10, 29], [11, 31], [12, 32], [13, 37], [14, 38], [15, 40], [16, 41], [17, 82], [18, 83], [19, 85], [20, 86], [10000, 1679657]] for v in tab: assert(szekeres(v[0]) == v[1]) main()
[ "qeed.quan@gmail.com" ]
qeed.quan@gmail.com
422351a1ca13fdc6b9b94e29d06c8ce38f33fc91
202bfd3bc23b4aa4e7477c9ba3685517dbad592b
/geo/geo_map.py
5b621b60069c22a66140d968fe2dca1a2c72fb1a
[]
no_license
yan7509/python_get_cityDistance
3b493cd9c53ba3543c6febe5d95096b5175ef6f4
ee51faa2f091352e41511749893bd6c4a74d5596
refs/heads/master
2022-03-27T06:59:37.566494
2019-12-24T14:42:15
2019-12-24T14:42:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,916
py
#!/usr/bin/python # -*- coding: utf-8 -*- #__author__: stray_camel import urllib.request #发送请求 from urllib import parse #URL编码 import json,logging,jsonpath,sys,os absPath = os.path.abspath(__file__) #返回代码段所在的位置,肯定是在某个.py文件中 temPath = os.path.dirname(absPath) #往上返回一级目录,得到文件所在的路径 temPath = os.path.dirname(temPath) #在往上返回一级,得到文件夹所在的路径 sys.path.append(temPath) from public import config class Geo_mapInterface(object): def __init__(self, key:"高德地图apikey值" = '3e2235273dd2c0ca2421071fbb96def4'): self.addList = [('湖北省武汉市江岸区', 1, '114.278760,30.592688'), ('湖北省武汉市江汉区', 1, '114.270871,30.601430'), ('湖北省武汉市乔口区', 1, '114.214920,30.582202')] #创建一个列表存放地址数据 # self.dict = dict(set(self.addList))#创建一个字典用于存放地址经纬度数据 self.key = key def get_coordinatesViaaddress(self, address:"地点名" ) -> "返回str类型的经纬度": url='https://restapi.amap.com/v3/geocode/geo?address='+address+'&output=json&key='+self.key #将一些符号进行URL编码 newUrl = parse.quote(url, safe="/:=&?#+!$,;'@()*[]") coor = json.loads(urllib.request.urlopen(newUrl).read())['geocodes'][0]['location'] logging.basicConfig(stream=open(config.src_path + '/log/syserror.log', encoding="utf-8", mode="a"), level = logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') logger = logging.getLogger(__name__) logger.info("查询{}的经纬度:{}!".format(address,coor)) # print() return coor def get_disViaCoordinates(self, addList:"一个列表存放地址数据" ) -> "{'origin':[],'destination':[],'distance':[],'route':[]}": dict_route = {'origin':[],'destination':[],'distance':[],'route':[]} for m in range(len(addList)): for n in range(m,len(addList)): if m!=n: print('get_tetst',m,n) #从addList中得到地址的名称,经纬度 origin = addList[m][2] destination = addList[n][2] url2='https://restapi.amap.com/v3/direction/driving?origin='+origin+'&destination='+destination+'&extensions=all&output=json&key=3e2235273dd2c0ca2421071fbb96def4' #编码 newUrl2 = parse.quote(url2, safe="/:=&?#+!$,;'@()*[]") #发送请求 response2 = urllib.request.urlopen(newUrl2) #接收数据 data2 = response2.read() #解析json文件 jsonData2 = json.loads(data2) #输出该json中所有road的值 # print(jsonData2) road=jsonpath.jsonpath(jsonData2,'$..road') #从json文件中提取距离 distance = jsonData2['route']['paths'][0]['distance'] #字典dict_route中追加数据 dict_route.setdefault("origin",[]).append(addList[m][0]) dict_route.setdefault("destination",[]).append(addList[n][0]) dict_route.setdefault("distance",[]).append(distance) dict_route.setdefault("route",[]).append(road) return dict_route if __name__ == "__main__": test = Geo_mapInterface() print(test.key) print(test.get_disViaCoordinates(test.addList)) # print(test.get_coordinatesViaaddress('湖北省武汉市洪山区')) # dict_route={"出发地":[],"目的地":[],"距离":[],"线路":[]} # k = len(addList) #nameList列表中元素个数 # print(dict_route) # print(dict(([1,2], i )for i in range(2)))
[ "aboyinsky@outlook.com" ]
aboyinsky@outlook.com
8d4383b237d5d13addbf71367b1be45c842b7824
41c824ce983c2a400ca6484b365d6f7ee077c8a3
/tools/dlrobot/robot/adhoc/__init__.py
3c6b21535cd0135398559ace340e20caf1bf521f
[]
no_license
TI-Russia/smart_parser
2c84c12906e308229037c2bc75299a4b227e795e
7428904975b2cf88cb329b8da11017cdebe8fa03
refs/heads/master
2022-12-10T06:40:43.852974
2022-08-05T11:06:18
2022-08-05T11:06:18
129,266,366
16
4
null
2022-12-08T11:18:29
2018-04-12T14:44:23
HTML
UTF-8
Python
false
false
558
py
from .tomsk import tomsk_gov_ru from .gossov_tatarstan_ru import gossov_tatarstan_ru from .tgl_ru import tgl_ru def process_adhoc(project): domain_name = project.web_site_snapshots[0].get_site_url() if domain_name == "tomsk.gov.ru": tomsk_gov_ru(project.web_site_snapshots[0]) return True elif domain_name == "gossov.tatarstan.ru": gossov_tatarstan_ru(project.web_site_snapshots[0]) return True elif domain_name == "tgl.ru": tgl_ru(project.web_site_snapshots[0]) return True return False
[ "sokirko@yandex.ru" ]
sokirko@yandex.ru
58cc6821d162a7e585a143940bbcfeae923b3ce5
8d35b8aa63f3cae4e885e3c081f41235d2a8f61f
/discord/ext/dl/extractor/outsidetv.py
a51556678bbcace6900d5b695026f00117f88f0c
[ "MIT" ]
permissive
alexyy802/Texus
1255f4e54c8d3cc067f0d30daff1cf24932ea0c9
c282a836f43dfd588d89d5c13f432896aebb540f
refs/heads/master
2023-09-05T06:14:36.217601
2021-11-21T03:39:55
2021-11-21T03:39:55
429,390,575
0
0
MIT
2021-11-19T09:22:22
2021-11-18T10:43:11
Python
UTF-8
Python
false
false
1,062
py
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class OutsideTVIE(InfoExtractor): _VALID_URL = r"https?://(?:www\.)?outsidetv\.com/(?:[^/]+/)*?play/[a-zA-Z0-9]{8}/\d+/\d+/(?P<id>[a-zA-Z0-9]{8})" _TESTS = [ { "url": "http://www.outsidetv.com/category/snow/play/ZjQYboH6/1/10/Hdg0jukV/4", "md5": "192d968fedc10b2f70ec31865ffba0da", "info_dict": { "id": "Hdg0jukV", "ext": "mp4", "title": "Home - Jackson Ep 1 | Arbor Snowboards", "description": "md5:41a12e94f3db3ca253b04bb1e8d8f4cd", "upload_date": "20181225", "timestamp": 1545742800, }, }, { "url": "http://www.outsidetv.com/home/play/ZjQYboH6/1/10/Hdg0jukV/4", "only_matching": True, }, ] def _real_extract(self, url): jw_media_id = self._match_id(url) return self.url_result("jwplatform:" + jw_media_id, "JWPlatform", jw_media_id)
[ "noreply@github.com" ]
alexyy802.noreply@github.com
89597cd37a0ca9703e1d6b442608c30d8f3ba662
6c95a0cebf78c27b93d15c17631d208d3d4715b1
/plotApCorr1runMany.py
e4706f6b5032da6193f965dc1c4365fc7b832ef7
[]
no_license
standardgalactic/hipe-code
3a7f9d4a7c4877564de1f6468a9783d1de3e90c5
600bb3fce7cdf2bc1e6120b3cfe4ffc1bb154d55
refs/heads/master
2022-02-11T02:16:35.558135
2014-02-26T10:26:13
2014-02-26T10:26:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,468
py
import sys from herschel.ia.gui.plot.renderer.PComponentEngine import HAlign from herschel.ia.gui.plot.renderer.PComponentEngine import VAlign from herschel.ia.numeric.toolbox.basic import Histogram from herschel.ia.numeric.toolbox.basic import BinCentres ## Plot aperture photometry stuff pc=False pf=False #radiusArcsec=[[22.,30.,45.,50.,60.,100.],\ # [30.,45.,55.,65.,80.,100.],\ # [42.,50.,60.,90.,100.,120.]] ##Max source radii that are valid #radMax=[[5,6,6,6],[3,6,6,6],[3,4,6,6]] radiusArcsec=[[22.],[30.],[42.]] radMax=[[1],[1],[1]] #innerArcsec=[60.,100.,200.,300.] #outerArcsec=[90.,150.,250.,350.] ##Min BR radii that are valid #bgMin=[[0,0,0,0,0,1],[0,0,0,1,1,1],[0,0,0,1,1,2]] innerArcsec=[60.] outerArcsec=[90.] bgMin=[[0],[0],[0]] nRad=len(radiusArcsec[0]) nBg=len(innerArcsec) bgStr=[] for bg in range(nBg): bgStr.append('Background: %i"-%i"'%(int(innerArcsec[bg]),int(outerArcsec[bg]))) #print bgStr dirPath = '/home/astrog82/spxcen/Herschel/Calibration/RelGains/Obs/' dirPlot = '/home/astrog82/spxcen/Herschel/Calibration/RelGains/Plots/' ##Get list of ObsIDs files=[\ '10_Hygeia_obs_All.dat',\ '173_Ino_obs_All.dat',\ '19_Fortuna_obs_All.dat',\ '1_Ceres_obs_All.dat',\ '20_Massalia_obs_All.dat',\ '21_Lutetia_obs_All.dat',\ '253_Mathilde_obs_All.dat',\ '29_Amphitrite_obs_All.dat',\ '2_Pallas_obs_All.dat',\ '372_Palma_obs_All.dat',\ '37_Fides_obs_All.dat',\ '3_Juno_obs_All.dat',\ '40_Harmonia_obs_All.dat',\ '47_Aglaja_obs_All.dat',\ '4_Vesta_obs_All.dat',\ '511_Davida_obs_All.dat',\ '52_Europa_obs_All.dat',\ '54_Alexandra_obs_All.dat',\ '65_Cybele_obs_All.dat',\ '6_Hebe_obs_All.dat',\ '7_Iris_obs_All.dat',\ '88_Thisbe_obs_All.dat',\ '8_Flora_obs_All.dat',\ '93_Minerva_obs_All.dat',\ ] nFiles=len(files) tarNames=[] nObsFiles=Int1d(nFiles) obsIds=[] for f in range(nFiles): fileObsList=dirPath+files[f] bandStr=["PSW","PMW","PLW"] fObs=open(fileObsList,'r') obsidsIn=fObs.readlines() fObs.close() obsids=[] raSrcs=[] decSrcs=[] nobIn=len(obsidsIn) nameFound=False for ob in range(nobIn): line=obsidsIn[ob] if line.find('#') < 0: obsids.append(int(line.split(',')[0],16)) raSrcs.append(float(line.split(',')[1])) decSrcs.append(float(line.split(',')[2])) else: if line.find('Name:') > 0: tarNames.append(line.split(':')[1][1:-1]) nameFound=True if nameFound==False: tarNames.append['UNKNOWN'] obsIds.append(Int1d(obsids)) #raSrcs=Double1d(raSrcs) #decSrcs=Double1d(decSrcs) nob=len(obsids) nObsFiles[f]=nob tarNames[f]='%s (%d)'%(tarNames[f],nObsFiles[f]) #File columns #0:srcRad #1:bgInner #2:bgOuter #3:TimelineFlux #4:TimelineErr #5:MapFlux #6:MapErr #7:MapRgFlux #8:MapRgErr #9:SrcCorr #10:ApCorr #11:SrcFlux #12:SrcErr #13:ApFlux #14:ApErr #15:ApRgFlux #16:ApRgErr ####################################### ## Read in all obsids ####################################### fluxMeanFiles=Double5d(nFiles,nRad,nBg,3,6) fluxRelFiles=Double5d(nFiles,nRad,nBg,3,6) fluxErrFiles=Double5d(nFiles,nRad,nBg,3,6) fluxMeanAll=Double4d(nRad,nBg,3,6) fluxErrAll=Double4d(nRad,nBg,3,6) ##[object, srcRad, bgRad , band , [timeline|map|mapRg|src|ap|apRg] #CorrFact=Double4d(nRad,nBg,3,2) ###[srcRad, bgRad , band , [src|app] maxFlux=0. minFlux=999. for f in range(nFiles): nObs=nObsFiles[f] obsList=obsIds[f] fluxArrOb=Double5d(nObs,nRad,nBg,3,6) fluxErrOb=Double5d(nObs,nRad,nBg,3,6) ##[object, srcRad, bgRad , band , [timeline|map|mapRg|src|ap|apRg] for b in range(3): band=bandStr[b] for ob in range(nObs): myObsid=obsList[ob] #print '%s Band'%band fileDat='%s0x%x_SrcFlux1run_%s.dat'%(dirPath,myObsid,band) fDat=open(fileDat,'r') lines=fDat.readlines() nLine=len(lines) for l in range(nLine): if lines[l].find('#') < 0: line=lines[l].split(',') iRad=radiusArcsec[b].index(float(line[0])) iBg=innerArcsec.index(float(line[1])) fluxArrOb[ob,iRad,iBg,b,0] = float(line[3]) #timeline fluxArrOb[ob,iRad,iBg,b,1] = float(line[5]) #map fluxArrOb[ob,iRad,iBg,b,2] = float(line[7]) #mapRg fluxArrOb[ob,iRad,iBg,b,3] = float(line[11]) #srcFlux fluxArrOb[ob,iRad,iBg,b,4] = float(line[13]) #apFlux fluxArrOb[ob,iRad,iBg,b,5] = float(line[15]) #apRgFlux if min(fluxArrOb[ob,iRad,iBg,b,:]) < minFlux: minFlux=min(fluxArrOb[ob,iRad,iBg,b,:]) if max(fluxArrOb[ob,iRad,iBg,b,:]) > maxFlux: maxFlux=max(fluxArrOb[ob,iRad,iBg,b,:]) fDat.close() print iRad print iBg for r in [iRad]: for bg in [iBg]: for p in range(6): fluxMeanFiles[f,r,bg,b,p]=MEAN(fluxArrOb[:,r,bg,b,p]) print 'File',f,'param',p,'MEAN:',MEAN(fluxArrOb[:,r,bg,b,p]) fluxErrFiles[f,r,bg,b,p]=STDDEV(fluxArrOb[:,r,bg,b,p]) print 'File',f,'param',p,'STDDEV:',STDDEV(fluxArrOb[:,r,bg,b,p]) fluxRelFiles[f,r,bg,b,p]=fluxMeanFiles[f,r,bg,b,p]/fluxMeanFiles[f,r,bg,b,0] for b in range(3): for r in [iRad]: for bg in [iBg]: for p in range(6): fluxMeanAll[r,bg,b,p]=MEAN(fluxMeanFiles[:,r,bg,b,p]) fluxErrAll[r,bg,b,p]=STDDEV(fluxMeanFiles[:,r,bg,b,p]) rFiles=Float1d(range(nFiles)) + 0.5 #pFluxPSW=PlotXY() #lTime=LayerXY(rFiles,fluxMeanFiles[:,0,0,0,0]) #lTime.line=Style.NONE #lTime.name='Timeline' #lTime.symbol=Style.DCROSS #pFluxPSW.addLayer(lTime) # #lMap=LayerXY(rFiles,fluxMeanFiles[:,0,0,0,1]) #lMap.line=Style.NONE #lMap.name='Map' #lMap.symbol=Style.VCROSS #pFluxPSW.addLayer(lMap) # #lAp=LayerXY(rFiles,fluxMeanFiles[:,0,0,0,5]) #lAp.line=Style.NONE #lAp.name='ApCorr' #lAp.symbol=Style.DIAMOND #pFluxPSW.addLayer(lAp) # #pFluxPSW.legend.visible=1 pErrPSW=PlotXY() lTimeRel=LayerXY(rFiles,fluxRelFiles[:,0,0,0,0]) lTimeRel.line=Style.NONE lTimeRel.name='Timeline' lTimeRel.symbol=Style.DCROSS lTimeRel.setErrorY(Double1d(fluxErrFiles[:,0,0,0,0]),Double1d(fluxErrFiles[:,0,0,0,0])) lTimeRel.setColor(java.awt.Color.black) lTimeRel.style.stroke=2. pErrPSW.addLayer(lTimeRel) #lTimeRelUp=LayerXY(rFiles-0.2,fluxRelFiles[:,0,0,0,0]+fluxErrFiles[:,0,0,0,0]) #lTimeRelUp.setColor(java.awt.Color.black) #pErrPSW.addLayer(lTimeRelUp) #lTimeRelDown=LayerXY(rFiles-0.2,fluxRelFiles[:,0,0,0,0]-fluxErrFiles[:,0,0,0,0]) #lTimeRelDown.setColor(java.awt.Color.black) #pErrPSW.addLayer(lTimeRelDown) lMapRel=LayerXY(rFiles-0.2,fluxRelFiles[:,0,0,0,1]) lMapRel.line=Style.NONE lMapRel.name='Map' lMapRel.symbol=Style.VCROSS #lMapRel.setErrorY(Double1d(fluxErrFiles[:,0,0,0,1]),Double1d(fluxErrFiles[:,0,0,0,1])) lMapRel.setColor(java.awt.Color.red) lMapRel.style.stroke=2. pErrPSW.addLayer(lMapRel) lApRel=LayerXY(rFiles+0.2,fluxRelFiles[:,0,0,0,5]) lApRel.line=Style.NONE lApRel.name='Corrected' lApRel.symbol=Style.DIAMOND lApRel.setErrorY(Double1d(fluxErrFiles[:,0,0,0,5]),Double1d(fluxErrFiles[:,0,0,0,5])) lApRel.setColor(java.awt.Color.blue) lApRel.style.stroke=2. pErrPSW.addLayer(lApRel) #lApRelUp=LayerXY(rFiles-0.2,fluxRelFiles[:,0,0,0,5]+fluxErrFiles[:,0,0,0,5]) #lApRelUp.setColor(java.awt.Color.blue) #pErrPSW.addLayer(lApRelUp) #lApRelDown=LayerXY(rFiles-0.2,fluxRelFiles[:,0,0,0,5]-fluxErrFiles[:,0,0,0,5]) #lApRelDown.setColor(java.awt.Color.blue) #pErrPSW.addLayer(lApRelDown) pErrPSW.yaxis.setRange(0,2) pErrPSW.yaxis.setTitleText('Flux relative to timeline flux density') pErrPSW.legend.visible=1 pErrPSW.xaxis.setRange(0,nFiles) pErrPSW.xaxis.tick.setFixedValues(rFiles) pErrPSW.xaxis.tick.label.setFixedStrings(tarNames) pErrPSW.xaxis.tick.label.setOrientation(1) pErrPSW.xaxis.setTitleText('Object (# Obs)')
[ "chris.north@astro.cf.ac.uk" ]
chris.north@astro.cf.ac.uk
98427273cabbe338ee47cfa39fde2c69ec153cca
47bd686ab04d8f6daba2097875dfefdba967d598
/04_30days_codechallenge/23_bst_level_order_traversal.py
37aa0c48d678a98f9e83a481962778e43456ddd1
[]
no_license
EmjayAhn/DailyAlgorithm
9633638c7cb7064baf26126cbabafd658fec3ca8
acda1917fa1a290fe740e1bccb237d83b00d1ea4
refs/heads/master
2023-02-16T17:04:35.245512
2023-02-08T16:29:51
2023-02-08T16:29:51
165,942,743
3
0
null
null
null
null
UTF-8
Python
false
false
1,016
py
# https://www.hackerrank.com/challenges/30-binary-trees/tutorial import sys class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data <= root.data: cur = self.insert(root.left, data) root.left = cur else: cur = self.insert(root.right, data) root.right = cur return root def levelOrder(self, root): #Write your code here queue = [root] while queue: current = queue.pop(0) print(str(current.data) + ' ', end="") if current.left: queue.append(current.left) if current.right: queue.append(current.right) T=int(input()) myTree=Solution() root=None for i in range(T): data=int(input()) root=myTree.insert(root,data) myTree.levelOrder(root)
[ "emjay.data@gmail.com" ]
emjay.data@gmail.com
5e5c6c67ed787564c6fcddba3284c101b5e1b8b2
2b255d07420114c40f6c8aeb0fb25228588282ed
/sitecomber/apps/config/management/commands/init_site_config.py
dcea81441583eabd41af10a706aab0aa348125a0
[]
no_license
ninapavlich/sitecomber
b48b3ee055dac1f419c98f08fffe5e9dc44bd6e3
6f34e5bb96ca4c119f98ee90c88881e8ca3f6f06
refs/heads/master
2022-12-11T20:55:07.215804
2020-03-13T07:58:28
2020-03-13T07:58:28
197,045,165
1
0
null
2022-12-08T01:47:52
2019-07-15T17:42:31
JavaScript
UTF-8
Python
false
false
1,900
py
import logging from django.core.management.base import BaseCommand from django.conf import settings from django.contrib.auth import get_user_model from django.core.validators import URLValidator from django.core.exceptions import ValidationError from sitecomber.apps.config.models import Site, SiteDomain, SiteTestSetting from sitecomber.apps.shared.utils import get_test_choices logger = logging.getLogger('django') class Command(BaseCommand): """ Example Usage: python manage.py init_site_config """ help = 'Initialize Site Config' def handle(self, *args, **options): starting_url = settings.STARTING_URL if not starting_url: starting_url = input("Please enter starting URL: ") validate = URLValidator() try: validate(starting_url) except ValidationError: print("Please enter a fully qualified URL") return user = get_user_model().objects.all().first() if not user: print("Please create an admin user first using the command: python manage.py createsuperuser") return site, site_created = Site.objects.get_or_create( owner=user, title=starting_url ) print("Initializing site settings for %s" % (starting_url)) site_domain, site_domain_created = SiteDomain.objects.get_or_create( site=site, url=starting_url ) test_choices = get_test_choices() for test_choice in test_choices: site_test_setting, site_test_setting_created = SiteTestSetting.objects.get_or_create( site=site, test=test_choice[0] ) print("-- enabled %s" % test_choice[0]) print("Site settings initialized for %s. You may configure it at /admin/config/site/%s/change/" % (site, site.pk))
[ "nina@ninalp.com" ]
nina@ninalp.com
eaff999078aae74c52b25f7fa8882f8922f8eacf
1cc59b6493c7579a81ddec76ea96621b934f510a
/venv/bin/jupyter-serverextension
d1da24e349738bd3a6f0e676f039527d9fb937a1
[]
no_license
miraclemaster11/Corona_Cases
4097c3f317c66ca6c9f31ed3bfd18af678859b6a
804c8165dbd8f631e1b30281fb03ae133976de1c
refs/heads/master
2022-12-10T17:40:03.304722
2020-09-05T05:53:51
2020-09-05T05:53:51
293,014,030
0
0
null
2020-09-05T06:03:48
2020-09-05T06:03:47
null
UTF-8
Python
false
false
263
#!/home/aman/PycharmProjects/Corona_Cases/venv/bin/python # -*- coding: utf-8 -*- import re import sys from notebook.serverextensions import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "KAN007BCT@student.kec.edu.np" ]
KAN007BCT@student.kec.edu.np
0bbbdfcd49815d6b3e6e70f9b0dea685968749ae
c130a094e04eb448201ca2ab8ed4fe56cd1d80bc
/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py
3e0b45cd787b066a6baa3cf8dd7fe960eb9dfa00
[ "Apache-2.0" ]
permissive
janweinschenker/openapi-generator
83fb57f9a5a94e548e9353cbf289f4b4172a724e
2d927a738b1758c2213464e10985ee5124a091c6
refs/heads/master
2022-02-01T17:22:05.604745
2022-01-19T10:43:39
2022-01-19T10:43:39
221,860,152
1
0
Apache-2.0
2019-11-15T06:36:25
2019-11-15T06:36:24
null
UTF-8
Python
false
false
644
py
# coding: utf-8 from __future__ import annotations from datetime import date, datetime # noqa: F401 import re # noqa: F401 from typing import Any, Dict, List, Optional # noqa: F401 from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 class Tag(BaseModel): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. Tag - a model defined in OpenAPI id: The id of this Tag [Optional]. name: The name of this Tag [Optional]. """ id: Optional[int] = None name: Optional[str] = None Tag.update_forward_refs()
[ "noreply@github.com" ]
janweinschenker.noreply@github.com
f4f2545d2a5100feb14734611ceb4e35981e5375
a8a1bc1c2223c4931aa451b7930cc838dae44b80
/eagle_theme_ecomm/models/ks_mega_menu.py
1e9e8c1a6965c6f2f244a275a01a651418d85fc0
[]
no_license
ShaheenHossain/eagle_theme_ecomm
195db37d37896e1c8f9151cfd0b47402d55aa19f
32a290d5386782b74cf670cef13802ac7c8e4318
refs/heads/master
2022-09-18T22:05:03.741941
2020-06-01T21:05:33
2020-06-01T21:05:33
268,632,294
0
3
null
null
null
null
UTF-8
Python
false
false
5,119
py
# # -*- coding: utf-8 -*- from eagle import models, fields, api class Ks_WebsiteMegaMenu(models.Model): _inherit = "website.menu" _description = "This model will add mega menu option to the website menu" ks_is_mega_menu = fields.Boolean("Is Dynamic Mega Menu") ks_display_img = fields.Boolean("Display Category Images") ks_content_id = fields.Char("Content") ks_categories = fields.Many2many("product.public.category", string="Categories to display", relation='website_menu_product_public_categories', domain=[('parent_id', '=', False)]) ks_banner_img = fields.Binary("Banner Image") ks_is_background_image = fields.Boolean("Set Background Image") ks_background_image = fields.Binary("Background Image") ks_item_selection_method = fields.Selection( [('products', 'All Products'), ('brands', 'Brands'), ('Cats', 'Categories')], string='Selection Type', default='products') ks_products_ids = fields.Many2many("product.template", relation="website_menu_product_templates_ids",string="Products",domain=[('website_published','=',True)]) ks_product_brand_ids = fields.Many2many('ks_product_manager.ks_brand', relation='website_menu_ks_product_manager_ks_brands', string='Brands') ks_is_category_tab_layout = fields.Boolean(string='Set Tab Layout For Categories') # Slider Configuration ks_is_slider = fields.Selection( [('image', 'Image'), ('slider', 'Slider')], string='Show Image/Slider') ks_item_slider_selection_method = fields.Selection( [('products', 'All Products'), ('brands', 'Brands'), ('cats', 'Categories')], string='Selection Type', default='products') ks_slider_title = fields.Char("Title") ks_slider_position = fields.Selection( [('left', 'Left'), ('right', 'Right')], string='Position', default='left') ks_slider_Speed = fields.Integer("Slide Speed", default=300) ks_slider_products_ids = fields.Many2many("product.template", string="Products", domain=[('website_published', '=', True)]) ks_slider_product_brand_ids = fields.Many2many('ks_product_manager.ks_brand', relation='website_menu_ks_product_manager_ks_brand', string='Brands') ks_slider_categories = fields.Many2many("product.public.category", relation='website_menu_product_public_category', string="Categories") ks_side_image = fields.Binary("Image") ks_side_image_description = fields.Char("Short Description") ks_side_image_link = fields.Char("Link") # Advance Configuration ks_is_font_color_set = fields.Boolean("Set Font Color") ks_font_color_main_cat = fields.Char(default="#000000", string="Main Heading Color") ks_font_color_sub_cat = fields.Char(default="#000000", string="Sub Heading Color") ks_set_number_of_columns = fields.Selection( [('two', '2'), ('three', '3'), ('four', '4'), ('five', '5'), ('six ', '6')], string='Set Number of Column', default='four') # ToDo Remove this field when create a new database ks_font_color = fields.Char() ks_is_categories_slider = fields.Char() # @api.multi def ks_get_image_url(self): for rec in self: if rec.ks_is_background_image and rec.ks_background_image: return '/web/image/website.menu/' + str(rec.id) + '/ks_background_image/' else: return "" # @api.multi def ks_get_side_image_url(self): for rec in self: if rec.ks_side_image and rec.ks_side_image: return '/web/image/website.menu/' + str(rec.id) + '/ks_side_image/' else: return "" # @api.multi def get_current_website(self): for rec in self: return rec.website.id else: return "" # class ks_website_top_menu(models.Model): # _inherit = 'website' # # @api.model # def copy_menu_hierarchy(self, top_menu): # print("dfshhs") # print("Fdfdsf") # pass # c = super(ks_website_top_menu, self).copy_menu_hierarchy(top_menu) # print("dfshhs") # # def copy_menu(menu, t_menu): # # new_menu = menu.copy({ # # 'parent_id': t_menu.id, # # 'website_id': self.id, # # }) # # for submenu in menu.child_id: # # copy_menu(submenu, new_menu) # # # # for website in self: # # new_top_menu = top_menu.copy({ # # 'name': _('Top Menu for Website %s') % website.id, # # 'website_id': website.id, # # }) # # li = self.env.ref() # # for submenu in top_menu.child_id: # # copy_menu(submenu, new_top_menu) # # @api.multi # def write(self, values): # a = super(ks_website_top_menu, self).write(values) # return a
[ "rapidgrps@princegroup-bd.com" ]
rapidgrps@princegroup-bd.com
c3d5cf62488778f4d8d76cb907368279058fb85c
15788d9ce41189864b228494a66c7409afe3b90c
/ice_addresses/importers/csv.py
8a66fb306f1a349acf791c64a451bf7dd6c266ac
[]
no_license
StefanKjartansson/django-icelandic-addresses
99133e378acce66825ad8a63f1dfd9c3640a4bd3
d602f288c031d60e8404e0b97a96602accc1024d
refs/heads/master
2020-05-30T13:20:55.583308
2014-12-23T14:14:06
2014-12-23T14:14:06
12,543,305
0
1
null
2015-03-28T22:25:38
2013-09-02T15:33:55
Python
UTF-8
Python
false
false
2,545
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ from __future__ import unicode_literals, print_function, absolute_import import codecs import csv import os import sys from ..models import PostCode, Street, Address DATA_ROOT = os.path.join( os.path.abspath(os.path.dirname(__file__)), os.pardir, 'data') PY3 = (sys.version_info[0] > 2) def csv_unireader(f, encoding="utf-8"): if PY3: f = codecs.open(f, encoding=encoding) r = csv.reader(f, delimiter='|', quotechar='"') else: r = csv.reader( codecs.iterencode(codecs.iterdecode(open(f), encoding), 'utf-8'), delimiter=b'|', quotechar=b'"') for row in r: if PY3: yield row else: yield [e.decode("utf-8") for e in row] def import_csv(filename=None): uniques = set() if not filename: filename = os.path.join(DATA_ROOT, 'Stadfangaskra_20131028.dsv') for fields in csv_unireader(filename, encoding='iso-8859-1'): if fields[0] == 'HNITNUM': continue try: postcode = int(fields[7]) except ValueError: postcode = 0 try: house_number = int(fields[10]) except ValueError: house_number = 0 uniques.add(( postcode, fields[8].strip(), fields[9].strip(), house_number, fields[11].strip(), float(fields[-2].replace(',', '.')), float(fields[-1].replace(',', '.')), )) uniques = sorted(uniques) def get_insert_method(model): if model.objects.count() > 0: return model.objects.get_or_create def _wrap(*args, **kwargs): return model.objects.create(*args, **kwargs), True return _wrap codes = {} _m = get_insert_method(PostCode) for c in set((i[0] for i in uniques)): pc, _ = _m(id=c) codes[c] = pc streets = {} _m = get_insert_method(Street) for key in set((i[0:3] for i in uniques)): pc, name1, name2 = key s, _ = _m( postcode=codes[pc], name_nominative=name1, name_genitive=name2) streets[key] = s _m = get_insert_method(Address) for code, name1, name2, house_number, house_chars, lat, lng in uniques: _m(street=streets[(code, name1, name2)], house_number=house_number, house_characters=house_chars, lat=lat, lon=lng) return len(uniques)
[ "esteban.supreme@gmail.com" ]
esteban.supreme@gmail.com
458aec1ce5b13d09ab2c61afc987cbc21b0ee1ef
fcc88521f63a3c22c81a9242ae3b203f2ea888fd
/Python3/0347-Top-K-Frequent-Elements/soln-1.py
58ddccc226cee1a0915ab31e3cfff1c5815c70b1
[ "MIT" ]
permissive
wyaadarsh/LeetCode-Solutions
b5963e3427aa547d485d3a2cb24e6cedc72804fd
3719f5cb059eefd66b83eb8ae990652f4b7fd124
refs/heads/master
2022-12-06T15:50:37.930987
2020-08-30T15:49:27
2020-08-30T15:49:27
291,811,790
0
1
MIT
2020-08-31T19:57:35
2020-08-31T19:57:34
null
UTF-8
Python
false
false
253
py
class Solution: def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ counts = collections.Counter(nums) return heapq.nlargest(k, counts, key=counts.get)
[ "zhang623@wisc.edu" ]
zhang623@wisc.edu
13fe0385f21e9b197be0b5372f8b164fe95f2a6a
a184444cce71e15a7d6789bdf9850e85a6c0e655
/setup.py
63d6745bb4e773a32ee654a8cd808b03b8d569fb
[]
no_license
huiwenzhang/gym-rearrangement
916a3b0a4d3841e3b692be8258bfe0a942b85f36
f9fa5036966fc56ad0b8c96f92ad81adaa77c875
refs/heads/master
2020-05-22T04:49:45.513917
2019-07-25T14:57:58
2019-07-25T14:57:58
186,222,793
5
1
null
null
null
null
UTF-8
Python
false
false
151
py
from setuptools import setup setup(name='gym_rearrangement', version='0.0.1', install_requires=['gym', 'mujoco_py', 'numpy', 'interval'] )
[ "huiwen3304@gmail.com" ]
huiwen3304@gmail.com
3810c8f20221af86b7b4f992411c4e1d29134305
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/rbeuWab36FAiLj65m_22.py
be8d1be7052d2551f6d8fb8766a11133bad6bc76
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
252
py
import re def grouping(w): group = {} for word in w: n = len(re.findall(r'[A-Z]',word)) if not n in group.keys(): group[n] = [word] else: group[n].append(word) group[n].sort(key = lambda x: x.lower()) return group
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
e06f22ec429ba76478781d135e74ba716c72403b
cc72013ede1b3bb02c32a3d0d199be4f7986c173
/ch6/pizzacost2.py
862eddfec218d0d2f770fe5b76b9d079962df5ba
[]
no_license
alextickle/zelle-exercises
b87d2a1476189954565f5cc97ee1448200eb00d4
b784ff9ed9b2cb1c56e31c1c63f3e2b52fa37875
refs/heads/master
2021-01-19T00:33:19.132238
2017-09-14T23:35:35
2017-09-14T23:35:35
87,182,609
1
1
null
null
null
null
UTF-8
Python
false
false
359
py
# pizzacost2.py import math def pizzaarea(d): return math.pi * (d/2.0)**2 def costperinch(area, p): return area/p def main(): price = input("Please enter the price of the pizza, in dollars: ") diameter = input("Please enter the diameter, in inches: ") print "The price per square inch is %0.2f." % (costperinch(pizzaarea(diameter), price)) main()
[ "alexander.tickle@gmail.com" ]
alexander.tickle@gmail.com
bc23a716f2508b19b5cce40ae33c07d4540e1ea0
b76e39e535499704368eddc26237dc0016ef7d06
/TCSPLC/readgeneral_v2.py
121d8ae89a266ee83d5309e0e456fb504addffdc
[]
no_license
BUBAIMITRA2018/castersimulation
0532e53df7d346c2824e577cc91cd0ac2ce4694c
eca5fddff5c0f33f785168f6b1e9f572c1622be0
refs/heads/master
2022-12-10T02:45:04.207196
2020-09-09T05:35:54
2020-09-09T05:35:54
260,110,682
0
0
null
null
null
null
UTF-8
Python
false
false
2,549
py
from snap7.snap7types import areas, S7WLBit, S7WLWord, S7WLReal, S7WLDWord from clientcomm_v1 import * __all__ = ['ReadGeneral'] class ReadGeneral(): def __init__(self, client): self.client = client self.mylock = threading.Lock() def readsymbolvalue(self, address, datatype, dataclass): addressconverted = float(address) self.byte = int(addressconverted) self.bit = round((addressconverted - self.byte)*10) self.daat = str(dataclass) if datatype == 'S7WLBit': self.result = self.client.read_area(areas[self.daat], 0, self.byte, S7WLBit) return get_bool(self.result, 0, self.bit) elif datatype == 'S7WLByte' or datatype == 'S7WLWord': self.result = self.client.read_area(areas[self.daat], 0, self.byte, S7WLWord) return get_int(self.result, 0) elif datatype == S7WLReal: return get_real(self.result, 0) elif datatype == 'S7WLDWord': self.result = self.client.read_area(areas[self.daat], 0, self.byte, S7WLDWord) print(("the result is ", get_int(self.result, 0))) return get_dword(self.result, 0) else: return None def readDBvalue(self, address, datatype): addressconverted = str(address) data1 = addressconverted[addressconverted.find("b") + 1:addressconverted.find(".")] data2 = addressconverted[addressconverted.find("d", 2) + 1:] data3 = data2[data2.find("b") + 1:] data3 = float(data3[1:]) self.byte = int(data3) self.bit = round((data3 - self.byte) * 10) self.dataarea = int(data1) if datatype == 'S7WLBit': self.result = self.client.read_area(areas['DB'], self.dataarea, self.byte, S7WLBit) return get_bool(self.result, 0, self.bit) elif datatype == 'S7WLByte' or datatype == 'S7WLWord': self.result = self.client.read_area(areas['DB'], self.dataarea, self.byte, S7WLWord) return get_int(self.result, 0) elif datatype == 'S7WLReal': self.result = self.client.read_area(areas['DB'], self.dataarea, self.byte, S7WLReal) return get_real(self.result, 0) elif datatype == S7WLDWord: return get_dword(self.result, 0) else: return None def __getstate__(self): state = self.__dict__.copy() # Remove the unpicklable entries. del state['mylock'] return state
[ "subrata.mitra@sms-group.com" ]
subrata.mitra@sms-group.com
216b5bec34fb1562d40bec74a6c32dfa1c426795
dd31235062b1f66fcb7bf9e6d444242e0cdbc447
/SVR/hebbe/run_sbatch.py
16ecc4fbc2672aeb43471ebf9f056f0a37a6447f
[]
no_license
LiYanChalmers/AllstateClaimSeverity
a25b4ebaae767dc674d320b4b5c9de84a41dc539
819304e9dd44c1c12e6251ab84facc180fb484a7
refs/heads/master
2020-03-21T20:34:25.145931
2016-12-12T22:38:24
2016-12-12T22:38:24
139,015,605
0
0
null
null
null
null
UTF-8
Python
false
false
229
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 12 03:00:49 2016 @author: ly """ from subprocess import call n_rounds = 400 for i in range(n_rounds): dst = 'svr'+str(i)+'.sh' call(['sbatch', dst])
[ "li.yan.ly414@gmail.com" ]
li.yan.ly414@gmail.com
ffe970e02a5d956bd21d1ea08782d7edd77f9c66
8e92584fcbc7b5ed393ab778e45ca5aa67c781b8
/generate_nullarbor_table.py
6508e1db126553e0a78246f0adfacbff41facf05
[ "MIT" ]
permissive
cdeitrick/gists
cd4261087deb7eadef19953efaa9be40630ba181
ef0e1ee2b2b9de448e5aceef083b7027e4444317
refs/heads/master
2020-04-01T18:40:29.294645
2019-04-15T20:35:21
2019-04-15T20:35:21
153,507,538
0
0
null
null
null
null
UTF-8
Python
false
false
668
py
from pathlib import Path from typing import Tuple def get_sample_files(folder:Path)->Tuple[Path,Path]: forward = [i for i in folder.iterdir() if 'R1' in i.name][0] reverse = [i for i in folder.iterdir() if 'R2' in i.name][0] return forward, reverse if __name__ == "__main__": folder = Path("/home/cld100/projects/lipuma/samples/") filename = folder / "lipuma_samples.tsv" with filename.open('w') as file1: for sample_folder in folder.iterdir(): if not sample_folder.is_dir(): continue try: f, r = get_sample_files(sample_folder) sample_name = sample_folder.name.split('_')[0] file1.write(f"{sample_name}\t{f}\t{r}\n") except: pass
[ "cld100@pitt.edu" ]
cld100@pitt.edu
3dbf7e36dfa28c5e7bf2dd870a8172ad1b4c905e
711c11d0111a40055ba110e7089a231c2ba42b8e
/toontown/coderedemption/TTCodeRedemptionMgrAI.py
b67fb0f0528c12a748432e77f42d02ffe11814b4
[ "Apache-2.0" ]
permissive
DeadMemez/ProjectAltis-OldAcornAcres
03c8dc912ecccae8456d89790f6b332547b75cc3
e8e0087389933795973e566782affcaec65a2980
refs/heads/master
2021-01-19T13:59:07.234192
2017-08-20T14:41:45
2017-08-20T14:41:45
100,869,782
0
2
null
2017-08-20T15:14:35
2017-08-20T15:14:35
null
UTF-8
Python
false
false
7,236
py
''' Created on Mar 21, 2017 @author: Drew ''' import time from datetime import datetime from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from toontown.catalog import CatalogItem from toontown.catalog.CatalogInvalidItem import CatalogInvalidItem from toontown.catalog.CatalogClothingItem import CatalogClothingItem from toontown.catalog.CatalogItemList import CatalogItemList from toontown.catalog.CatalogPoleItem import CatalogPoleItem from toontown.catalog.CatalogBeanItem import CatalogBeanItem from toontown.catalog.CatalogChatItem import CatalogChatItem from toontown.catalog.CatalogAccessoryItem import CatalogAccessoryItem from toontown.catalog.CatalogRentalItem import CatalogRentalItem from toontown.catalog.CatalogGardenItem import CatalogGardenItem from toontown.catalog.CatalogGardenStarterItem import CatalogGardenStarterItem from toontown.coderedemption import TTCodeRedemptionConsts, TTCodeRedemptionGlobals from toontown.toonbase import ToontownGlobals class TTCodeRedemptionMgrAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory("TTCodeRedemptionMgrAI") def __init__(self, air): DistributedObjectAI.__init__(self, air) self.air = air def announceGenerate(self): DistributedObjectAI.announceGenerate(self) def delete(self): DistributedObjectAI.delete(self) def giveAwardToToonResult(self, todo0, todo1): pass def redeemCode(self, context, code): avId = self.air.getAvatarIdFromSender() if not avId: self.air.writeServerEvent('suspicious', avId=avId, issue='Tried to redeem a code from an invalid avId') return av = self.air.doId2do.get(avId) if not av: self.air.writeServerEvent('suspicious', avId=avId, issue='Invalid avatar tried to redeem a code') return # Default values. They will get modified if needed isValid = True hasExpired = False isEligible = True beenDelivered = False code = str(code.lower().replace(' ', '').replace('-', '').replace('_', '')) # Make every code lower case with no spaces or dashes of any sort avCodes = av.getRedeemedCodes() print avCodes if not avCodes: avCodes = [code] av.setRedeemedCodes(avCodes) else: if not code in avCodes: avCodes.append(code) av.setRedeemedCodes(avCodes) isEligible = True else: isEligible = False expirationDate = TTCodeRedemptionGlobals.codeToExpiration.get(code) if not expirationDate: hasExpired = False else: if datetime.now() > expirationDate: hasExpired = True avId = self.air.getAvatarIdFromSender() print("%s entered %s" %(avId, code)) if not avId: self.air.writeServerEvent('suspicious', avId = avId, issue = 'Tried to redeem a code from an invalid avId') return av = self.air.doId2do.get(avId) if not av: self.air.writeServerEvent('suspicious', avId = avId, issue = 'Invalid avatar tried to redeem a code') return if not isValid: self.air.writeServerEvent('code-redeemed', avId = avId, issue = 'Invalid code: %s' % code) self.sendUpdateToAvatarId(avId, 'redeemCodeResult', [context, ToontownGlobals.CODE_INVALID, 0]) return # Make sure its not expired, which it shouldnt be considering there is none that have expirations :thinking: if hasExpired: self.air.writeServerEvent('code-redeemed', avId = avId, issue = 'Expired code: %s' % code) self.sendUpdateToAvatarId(avId, 'redeemCodeResult', [context, ToontownGlobals.CODE_EXPIRED, 0]) return # Make sure the toon is allowed to use this code if not isEligible: self.air.writeServerEvent('code-redeemed', avId = avId, issue = 'Ineligible for code: %s' % code) self.sendUpdateToAvatarId(avId, 'redeemCodeResult', [context, ToontownGlobals.CODE_INELIGIBLE, 0]) return items = self.getItemsForCode(code) for item in items: if isinstance(item, CatalogInvalidItem): # Incase theres an invalid item type self.air.writeServerEvent('suspicious', avId = avId, issue = 'uh oh! invalid item type for code: %s' % code) self.sendUpdateToAvatarId(avId, 'redeemCodeResult', [context, ToontownGlobals.CODE_INVALID, 0]) break if len(av.mailboxContents) + len(av.onGiftOrder) >= ToontownGlobals.MaxMailboxContents: # Targets mailbox is full beenDelivered = False break item.deliveryDate = int(time.time() / 60) + 1 # Basically instant delivery av.onOrder.append(item) av.b_setDeliverySchedule(av.onOrder) beenDelivered = True if not beenDelivered: # Something went wrong! self.air.writeServerEvent('code-redeemed', avId = avId, issue = 'Could not deliver items for code: %s' % code) self.sendUpdateToAvatarId(avId, 'redeemCodeResult', [context, ToontownGlobals.CODE_INVALID, 0]) return # send self.air.writeServerEvent('code-redeemed', avId = avId, issue = 'Successfuly redeemed code: %s' % code) self.sendUpdateToAvatarId(avId, 'redeemCodeResult', [context, ToontownGlobals.CODE_SUCCESS, 0]) def getItemsForCode(self, code): avId = self.air.getAvatarIdFromSender() if not avId: self.air.writeServerEvent('suspicious', avId = avId, issue = 'AVID is none') return av = self.air.doId2do.get(avId) if not av: self.air.writeServerEvent('suspicious', avId = avId, issue = 'Avatar doesnt exist') return code = str(code.lower().replace(' ', '').replace('-', '').replace('_', '')) # Make every code lower case with no spaces or dashes of any sort if code == "sillymeter": shirt = CatalogClothingItem(1753, 0) return [shirt] if code == "getconnected": shirt = CatalogClothingItem(1752, 0) return [shirt] if code == "toontastic": shirt = CatalogClothingItem(1820, 0) return [shirt] if code == "gardens": gardenStarter = CatalogGardenStarterItem() return [gardenStarter] if code == "sweet": beans = CatalogBeanItem(12000, tagCode = 2) return [beans] return [] def redeemCodeAiToUd(self, avId, context, code): self.sendUpdate('redeemCodeAiToUd', [avId, context, code]) def redeemCodeResultUdToAi(self, avId, context, result, awardMgrResult): self.d_redeemCodeResult(avId, context, result, awardMgrResult) def d_redeemCodeResult(self, avId, context, result, awardMgrResult): self.sendUpdateToAvatarId(avId, 'redeemCodeResult', [context, result, awardMgrResult])
[ "tewtow5@gmail.com" ]
tewtow5@gmail.com
d2fb3d6b96ef10ef390bf7df4126f75fab56c27e
f4afb7a16696803942a999b0687e08997defb114
/build/rotors_simulator_demos/catkin_generated/generate_cached_setup.py
5f65bc27f9863b023889c9944fb330469b9f3650
[]
no_license
EmanueleAucone/ethz_ws
8d4760109be3b1882d875aa28f7ecfe793b1b9e6
883efd2936e8f67e783790d7ac8f3a40e749d1b9
refs/heads/main
2023-01-22T04:03:45.341419
2020-11-25T10:30:49
2020-11-25T10:30:49
308,606,492
0
0
null
null
null
null
UTF-8
Python
false
false
1,358
py
# -*- coding: utf-8 -*- from __future__ import print_function import argparse import os import stat import sys # find the import for catkin's python package - either from source space or from an installed underlay if os.path.exists(os.path.join('/opt/ros/kinetic/share/catkin/cmake', 'catkinConfig.cmake.in')): sys.path.insert(0, os.path.join('/opt/ros/kinetic/share/catkin/cmake', '..', 'python')) try: from catkin.environment_cache import generate_environment_script except ImportError: # search for catkin package in all workspaces and prepend to path for workspace in "/home/emanuele/ethz_ws/devel;/opt/ros/kinetic".split(';'): python_path = os.path.join(workspace, 'lib/python2.7/dist-packages') if os.path.isdir(os.path.join(python_path, 'catkin')): sys.path.insert(0, python_path) break from catkin.environment_cache import generate_environment_script code = generate_environment_script('/home/emanuele/ethz_ws/devel/.private/rotors_simulator_demos/env.sh') output_filename = '/home/emanuele/ethz_ws/build/rotors_simulator_demos/catkin_generated/setup_cached.sh' with open(output_filename, 'w') as f: #print('Generate script for cached setup "%s"' % output_filename) f.write('\n'.join(code)) mode = os.stat(output_filename).st_mode os.chmod(output_filename, mode | stat.S_IXUSR)
[ "emanuele.aucone95@gmail.com" ]
emanuele.aucone95@gmail.com
9d83a56dc0bb592784356093f88c7ba0707cd132
80ae9b5cfb45b6e9cf7873ef7c46e17e117e4019
/data/CodeChef/NW1.py
20f6b9480cad21ebfdc60ecc02a793fd70598c8b
[]
no_license
Ritvik19/CodeBook
ef7764d89b790e902ede5802f36d5ca910d8a50e
2b4ed7938bbf156553d6ba5cba6216449528f0fc
refs/heads/master
2021-07-04T08:25:52.478719
2020-08-08T06:54:14
2020-08-08T06:54:14
138,744,302
3
0
null
null
null
null
UTF-8
Python
false
false
239
py
days = [ "mon", "tues", "wed", "thurs", "fri", "sat", "sun"] t = int(input()) for i in range(t): n, d = input().split() nw = [4, 4, 4, 4, 4, 4, 4] for i in range(int(n)-28): nw[(days.index(d)+i)%7] += 1 print(*nw)
[ "rastogiritvik99@gmail.com" ]
rastogiritvik99@gmail.com
9b579abd1e2cbdcc1cbbbab8a3fc0bd6f4128332
c7979f4f6435fe8d0d07fff7a430da55e3592aed
/ABC037/C.py
6f2c9cd58755ef8a8c60865d3ae965e11ffd2c30
[]
no_license
banboooo044/AtCoder
cee87d40bb98abafde19017f4f4e2f984544b9f8
7541d521cf0da848ecb5eb10ffea7d75a44cbbb6
refs/heads/master
2020-04-14T11:35:24.977457
2019-09-17T03:20:27
2019-09-17T03:20:27
163,818,272
0
0
null
null
null
null
UTF-8
Python
false
false
195
py
N,K = map(int,input().split(" ")) a = list(map(int,input().split(" "))) val = sum(a[:K]) sumv = val for i in range(N-K): val += (sumv - a[i] + a[K+i]) sumv = (sumv - a[i] + a[K+i]) print(val)
[ "touhoucrisis7@gmail.com" ]
touhoucrisis7@gmail.com
9b4650366e2834047484b64cd106dbf11d26d0a2
4d42b57a4ab24b301c4503002ed1038ec12030ba
/satsearch/main.py
be03dccf9316dce990838bb91aa64ce34c60fa9d
[ "MIT" ]
permissive
cgore/sat-search
53435155aee3f0f0dc687387aac68c1c01b48432
230af9b57ad06c1754de6ce97f6ae6893791d8b7
refs/heads/master
2020-03-17T15:38:15.935161
2018-03-19T03:24:52
2018-03-19T03:24:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,208
py
import os import sys import json import logging from .version import __version__ from satsearch import Search, Scenes from satsearch.parser import SatUtilsParser def main(review=False, printsearch=False, printmd=None, printcal=False, load=None, save=None, append=False, download=None, **kwargs): """ Main function for performing a search """ if load is None: if printsearch: txt = 'Search for scenes matching criteria:\n' for kw in kwargs: if kw == 'intersects': geom = json.dumps(json.loads(kwargs[kw])['geometry']) txt += ('{:>20}: {:<40} ...\n'.format(kw, geom[0:70])) else: txt += ('{:>20}: {:<40}\n'.format(kw, kwargs[kw])) print(txt) # get scenes from search search = Search(**kwargs) scenes = Scenes(search.scenes(), metadata={'search': kwargs}) else: search = None scenes = Scenes.load(load) if review: if not os.getenv('IMGCAT', None): raise ValueError('Set IMGCAT envvar to terminal image display program to use review feature') scenes.review_thumbnails() # print summary if printmd is not None: scenes.print_scenes(printmd) # print calendar if printcal: print(scenes.text_calendar()) # save all metadata in JSON file if save is not None: scenes.save(filename=save, append=append) print('%s scenes found' % len(scenes)) # download files given keys if download is not None: for key in download: scenes.download(key=key) return scenes def cli(): parser = SatUtilsParser(description='sat-search (v%s)' % __version__) args = parser.parse_args(sys.argv[1:]) # read the GeoJSON file if 'intersects' in args: if os.path.exists(args['intersects']): with open(args['intersects']) as f: args['intersects'] = json.dumps(json.loads(f.read())) # enable logging logging.basicConfig(stream=sys.stdout, level=args.pop('verbosity') * 10) scenes = main(**args) return len(scenes) if __name__ == "__main__": cli()
[ "matt.a.hanson@gmail.com" ]
matt.a.hanson@gmail.com
e84bacade8b32fd4e66d9b8f06b6668ab4d79cb4
13e91d812e7e0133f45273945ccca5523b1eefe5
/task 3/spacex/migrations/0001_initial.py
fb8a9ca3ac5611143e838d992ff22a71d3619a63
[]
no_license
Harshvartak/Unicode
30d7298253f1feba4c47b89bdb8403e88b1707a1
2903d445fa5435b835f1543b8a67fb417749e1c3
refs/heads/master
2020-07-10T15:29:48.115326
2020-01-20T18:34:42
2020-01-20T18:34:42
204,299,112
0
0
null
null
null
null
UTF-8
Python
false
false
716
py
# Generated by Django 2.2.3 on 2019-08-22 11:45 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='spacex', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('flight_number', models.IntegerField(verbose_name='flight_number')), ('launch_date', models.DateTimeField(verbose_name='launch_date')), ('rocket_name', models.CharField(max_length=150)), ('mission_patch', models.URLField()), ], ), ]
[ "vartak.harsh@gmail.com" ]
vartak.harsh@gmail.com
939cb1a21804f194fc568a0cb554bb20519a3adf
61e98b0302a43ab685be4c255b4ecf2979db55b6
/sdks/python/.tox/lint/lib/python2.7/site-packages/pylint/test/extensions/test_check_mccabe.py
9d995891fd7893e6a664334889981216ab537d0c
[ "BSD-3-Clause", "EPL-2.0", "CDDL-1.0", "Apache-2.0", "WTFPL", "GPL-2.0-only", "BSD-2-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference", "CDDL-1.1", "Classpath-exception-2.0" ]
permissive
dzenyu/kafka
5631c05a6de6e288baeb8955bdddf2ff60ec2a0e
d69a24bce8d108f43376271f89ecc3b81c7b6622
refs/heads/master
2021-07-16T12:31:09.623509
2021-06-28T18:22:16
2021-06-28T18:22:16
198,724,535
0
0
Apache-2.0
2019-07-24T23:51:47
2019-07-24T23:51:46
null
UTF-8
Python
false
false
2,593
py
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/master/COPYING """Tests for the pylint checker in :mod:`pylint.extensions.check_mccabe """ import os.path as osp import unittest from pylint import checkers from pylint.extensions.mccabe import register from pylint.lint import PyLinter from pylint.reporters import BaseReporter class TestReporter(BaseReporter): def handle_message(self, msg): self.messages.append(msg) def on_set_current_module(self, module, filepath): self.messages = [] class TestMcCabeMethodChecker(unittest.TestCase): """Test McCabe Method Checker""" expected_msgs = [ "'f1' is too complex. The McCabe rating is 1", "'f2' is too complex. The McCabe rating is 1", "'f3' is too complex. The McCabe rating is 3", "'f4' is too complex. The McCabe rating is 2", "'f5' is too complex. The McCabe rating is 2", "'f6' is too complex. The McCabe rating is 2", "'f7' is too complex. The McCabe rating is 3", "'f8' is too complex. The McCabe rating is 4", "'f9' is too complex. The McCabe rating is 9", "'method1' is too complex. The McCabe rating is 1", "This 'for' is too complex. The McCabe rating is 4", "'method3' is too complex. The McCabe rating is 2", "'f10' is too complex. The McCabe rating is 11", "'method2' is too complex. The McCabe rating is 18", ] @classmethod def setUpClass(cls): cls._linter = PyLinter() cls._linter.set_reporter(TestReporter()) checkers.initialize(cls._linter) register(cls._linter) cls._linter.disable('all') cls._linter.enable('too-complex') def setUp(self): self.fname_mccabe_example = osp.join( osp.dirname(osp.abspath(__file__)), 'data', 'mccabe.py') def test_too_complex_message(self): self._linter.global_set_option('max-complexity', 0) self._linter.check([self.fname_mccabe_example]) real_msgs = [message.msg for message in self._linter.reporter.messages] self.assertEqual(sorted(self.expected_msgs), sorted(real_msgs)) def test_max_mccabe_rate(self): self._linter.global_set_option('max-complexity', 9) self._linter.check([self.fname_mccabe_example]) real_msgs = [message.msg for message in self._linter.reporter.messages] self.assertEqual(sorted(self.expected_msgs[-2:]), sorted(real_msgs)) if __name__ == '__main__': unittest.main()
[ "alex.barreto@databricks.com" ]
alex.barreto@databricks.com
fc0535302e88c9a984876df5e89680510528d42a
99799383b4e618061fe9261aa70cfe420e02a5aa
/gift/migrations/0001_initial.py
90133582de0ce017c9343a8fc104570f32f46924
[ "MIT" ]
permissive
openkamer/openkamer
f311a97d5c9e182eabd6602f42475e8e049912b0
bb99963c00ad90299deccd44d977c27aee7eb16c
refs/heads/master
2023-07-20T10:45:11.402427
2023-07-18T17:41:56
2023-07-18T17:41:56
57,322,204
62
7
MIT
2023-07-17T18:15:43
2016-04-28T17:43:23
Python
UTF-8
Python
false
false
920
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-12-08 11:09 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('person', '0005_person_twitter_username'), ] operations = [ migrations.CreateModel( name='Gift', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('description', models.CharField(blank=True, default='', max_length=1000)), ('date', models.DateField(blank=True, null=True)), ('value_euro', models.FloatField(blank=True, null=True)), ('person', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='person.Person')), ], ), ]
[ "bart.romgens@gmail.com" ]
bart.romgens@gmail.com