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
d74f9bc9792a616e6c0933d06f78cde2201693ba
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/agc008/B/3719594.py
b69ea63898a0d7baadd01fe4aaeb65de1040ec21
[]
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
457
py
N, K = map(int, input().split()) A = [int(a) for a in input().split()] Plus, Whole = [0], [0] for i in range(N): Plus.append(Plus[-1] + max(A[i], 0)) Whole.append(Whole[-1] + A[i]) Score = max(max(0, Whole[K] - Whole[0]) + Plus[N] - Plus[K], Plus[N-K] - Plus[0] + max(0, Whole[N] - Whole[N-K])) for i in range(1, N-K): temp = Plus[i] + max(0, Whole[i+K] - Whole[i]) + Plus[N] - Plus[i+K] Score = max(Score, temp) print(Score)
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
e3b1ca32371f220e5494e925dba257fd3aaf7afc
f11600b9a256bf6a2b584d127faddc27a0f0b474
/normal/826.py
291cb5bbbf8d6b2a6f742b0274197291c8258dd9
[]
no_license
longhao54/leetcode
9c1f0ce4ca505ec33640dd9b334bae906acd2db5
d156c6a13c89727f80ed6244cae40574395ecf34
refs/heads/master
2022-10-24T07:40:47.242861
2022-10-20T08:50:52
2022-10-20T08:50:52
196,952,603
0
0
null
null
null
null
UTF-8
Python
false
false
1,245
py
# 弱智方法 class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: w, p = {}, {} for d,pri in zip (difficulty, profit): w[d] = 1 if d in p: p[d] = max(pri, p[d]) else: p[d] = pri difficulty.sort() m = p[difficulty[0]] d1 = difficulty[0] while d1-1 >= 1: p[d1-1] = 0 d1 -= 1 m1 = max(worker) for v in difficulty[1:]: t = v while t-1 not in p: p[t-1] = m t -= 1 m = max(p[v], m) p[v] = m for i in range(difficulty[-1]+1, m1+1): p[i] = m ans = 0 for i in worker: ans += p[i] return ans #官方方法 class Solution(object): def maxProfitAssignment(self, difficulty, profit, worker): jobs = zip(difficulty, profit) jobs.sort() ans = i = best = 0 for skill in sorted(worker): while i < len(jobs) and skill >= jobs[i][0]: best = max(best, jobs[i][1]) i += 1 ans += best return ans
[ "jinlha@jiedaibao.com" ]
jinlha@jiedaibao.com
2909cf54ad06e7340aeb3128d7794c1718acc4d6
76a6890c01006fff69a920719df0065e6109a5e9
/full_django_blog/myblog/views.py
bba2acc11ab84388f7f433b809dac48a52bc09c4
[]
no_license
prathmesh2048/full-django-blog
0c94ce08c1a17b74c21420d4e658f1b5b5fe12d6
b25c9af1d25b1677cf82b929d133f1067109b26b
refs/heads/master
2022-11-21T21:50:39.990007
2020-07-23T15:59:39
2020-07-23T15:59:39
281,994,887
1
0
null
null
null
null
UTF-8
Python
false
false
2,964
py
from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.http import Http404 from django.shortcuts import render, redirect from django.urls import reverse_lazy, reverse from .models import Post from django.utils.decorators import method_decorator from django.views.generic import ListView, DetailView, TemplateView, CreateView, UpdateView, DeleteView from .forms import UserProfileForm, UserUpdateForm from .models import Profile from django.contrib.auth.decorators import login_required class PostListView(ListView): model = Post template_name = 'myblog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] # @method_decorator(login_required, name='dispatch') class PostDetailView(LoginRequiredMixin, DetailView): model = Post # context is automatically called 'object' class PostCreateView(LoginRequiredMixin, CreateView): # context rendered is 'form' model = Post fields = ['title', 'content'] # success_url = reverse_lazy('detail') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) # This view does'nt requires a template class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView, ): # context rendered is 'form' , this order is toooo important model = Post fields = ['title', 'content'] # success_url = reverse_lazy('detail') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) success_url = '/' def test_func(self): obj = self.get_object() if obj.author == self.request.user: return True else: raise Http404("You are not allowed to edit this Post") class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def test_func(self): obj = self.get_object() if obj.author == self.request.user: return True else: raise Http404("You are not allowed to delete this Post") @login_required def profile(request): template = 'account/profile.html' details = Profile.objects.get(user=request.user) if request.method == "POST": p_form = UserProfileForm(request.POST, request.FILES, instance=request.user.profile) u_form = UserUpdateForm(request.POST, instance=request.user) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'your profile has been updated !') return redirect('/profile') else: p_form = UserProfileForm(instance=request.user.profile) u_form = UserUpdateForm(instance=request.user) context = {'details': details, 'u_form': u_form, 'p_form': p_form} return render(request, template, context)
[ "prathmeshnandurkar123@gmail.com" ]
prathmeshnandurkar123@gmail.com
32af5f9daa05db8a9394c42989ce82fece01f08d
180a3795a115c0da71078f81efbde45ab2025ca0
/machine_learning_book/CH02/plot.py
614ec79097c9a7d30eb96456cd9a02dddfa28638
[]
no_license
lizhe960118/Machine-Learning
a7593e6788433408bcf072e5e25672debd931ee4
2d6fe2373839964645d632895ed2a7dcb9de48b0
refs/heads/master
2020-03-31T15:53:57.408037
2019-08-18T12:29:11
2019-08-18T12:29:11
152,355,543
0
0
null
null
null
null
UTF-8
Python
false
false
666
py
# import matplotlib import matplotlib.pyplot as plt import KNN from numpy import * datingDataMat, datingLabels = KNN.file2matrix('datingTestSet2.txt') # print(datingDataMat[0:100]) # print(datingLabels[0:20]) fig = plt.figure() ax = fig.add_subplot(111) ''' 这些是编码为单个整数的子图网格参数。 例如,“111”表示“1×1 grid,first subplot”,“234”表示“2×3 grid,4th subplot”。 add_subplot(111)的替代形式是add_subplot(1, 1, 1) ''' ax.scatter(datingDataMat[:, 1], datingDataMat[:, 2], 15.0 * array(datingLabels), 15.0 * array(datingLabels)) # 使用标签来决定所画图像的颜色和大小 plt.show()
[ "2957308424@qq.com" ]
2957308424@qq.com
902bc632e7a592419bfbdd250fd9fe501cfafc04
bbf1ae079309eca11270422d3f0d259d1515d430
/numerical-tours/python/todo/solutions/multidim_2_volumetric.py
dc13ecfee2d90c85abdd280d18d22bef9a5a7d1f
[ "BSD-2-Clause" ]
permissive
ZichaoDi/Di_MATLABTool
5e6a67b613c4bcf4d904ddc47c2744b4bcea4885
c071291c63685c236f507b2cb893c0316ab6415c
refs/heads/master
2021-08-11T07:28:34.286526
2021-08-04T18:26:46
2021-08-04T18:26:46
149,222,333
9
5
null
null
null
null
UTF-8
Python
false
false
5,481
py
def exo1(): """ Implement the forward wavelet transform by iteratively applying these transform steps to the low pass residual. nitialize the transform """ MW = M for j in 1: log2(n): p = n/ 2^(j-1) sel = 1: p % average/ difference along X MW(sel, sel, sel) = cat3(1, (MW(1: 2: p, sel, sel) + MW(2: 2: p, sel, sel))/ sqrt(2), (MW(1: 2: p, sel, sel)-MW(2: 2: p, sel, sel))/ sqrt(2)) % average/ difference along Y MW(sel, sel, sel) = cat3(2, (MW(sel, 1: 2: p, sel) + MW(sel, 2: 2: p, sel))/ sqrt(2), (MW(sel, 1: 2: p, sel)-MW(sel, 2: 2: p, sel))/ sqrt(2)) % average/ difference along Z MW(sel, sel, sel) = cat3(3, (MW(sel, sel, 1: 2: p) + MW(sel, sel, 2: 2: p))/ sqrt(2), (MW(sel, sel, 1: 2: p)-MW(sel, sel, 2: 2: p))/ sqrt(2)) def exo2(): """ Implement the backward transform to compute an approximation |M1| from the coefficients |MWT|. """ M1 = MWT for j in log2(n): -1: 1: p = n/ 2^(j) sel = 1: p sel1 = 1: 2*p selw = p + 1: 2*p % average/ difference along X A = M1(sel, sel1, sel1) D = M1(selw, sel1, sel1) M1(1: 2: 2*p, sel1, sel1) = (A + D)/ sqrt(2) M1(2: 2: 2*p, sel1, sel1) = (A-D)/ sqrt(2) % average/ difference along Y A = M1(sel1, sel, sel1) D = M1(sel1, selw, sel1) M1(sel1, 1: 2: 2*p, sel1) = (A + D)/ sqrt(2) M1(sel1, 2: 2: 2*p, sel1) = (A-D)/ sqrt(2) % average/ difference along Z A = M1(sel1, sel1, sel) D = M1(sel1, sel1, selw) M1(sel1, sel1, 1: 2: 2*p) = (A + D)/ sqrt(2) M1(sel1, sel1, 2: 2: 2*p) = (A-D)/ sqrt(2) def exo3(): """ Select the optimal blurring width |s| to reach the smallest possible SNR. Keep the optimal denoising |Mblur| """ ntests = 20 slist = linspace(.01, 1.5, ntests) err = [] for i in 1: ntests: h = exp(-(X.^2 + Y.^2 + Z.^2)/ (2*slist(i)^2)) h = h/ sum(h(: )) Mh = real(ifftn(fftn(Mnoisy) .* fftn(fftshift(h)))) err(i) = snr(M, Mh) if i >1 && err(i) >max(err(1: i-1)) Mblur = Mh plot(slist, err, '.-') axis('tight') set_label('s', 'SNR') def exo4(): """ Perforn Wavelet denoising by thresholding the wavelet coefficients of Mnoisy. Test both hard thresholding and soft thresholding to determine the optimal threshold and the corresponding SNR. Record the optimal result |Mwav|. """ MW = perform_haar_transf(Mnoisy, 1, + 1) Tlist = linspace(1, 4, 20)*sigma err_hard = []; err_soft = [] for i in 1: length(Tlist): MWT = perform_thresholding(MW, Tlist(i), 'hard') M1 = perform_haar_transf(MWT, 1, -1) err_hard(i) = snr(M, M1) MWT = perform_thresholding(MW, Tlist(i), 'soft') M1 = perform_haar_transf(MWT, 1, -1) err_soft(i) = snr(M, M1) if i >1 & err_soft(i) >max(err_soft(1: i-1)) Mwav = M1 plot(Tlist/ sigma, [err_hard; err_soft]', '.-') axis('tight') set_label('T/ sigma', 'SNR') legend('hard', 'soft') def exo5(): """ Implement cycle spinning hard thresholding with |T=3*sigma|. """ T = 3*sigma w = 4 [dX, dY, dZ] = ndgrid(0: w-1, 0: w-1, 0: w-1) Mspin = zeros(n, n, n) for i in 1: w^3: MnoisyC = circshift(Mnoisy, [dX(i) dY(i) dZ(i)]) % denoise MW = perform_haar_transf(MnoisyC, 1, + 1) MWT = perform_thresholding(MW, T, 'hard') M1 = perform_haar_transf(MWT, 1, -1) % back M1 = circshift(M1, -[dX(i) dY(i) dZ(i)]) Mspin = Mspin*(i-1)/ i + M1/ i def exo6(): """ Implement the full 3D forward wavelet transform by applying these steps for decaying scales |j| toward 0. """ Jmin = 0 options.h = h MW = perform_wavortho_transf(M, Jmin, + 1, options) def exo7(): """ Implement the full 3D backward wavelet transform by applying these steps for increasing scales |j|. """ M1 = perform_wavortho_transf(MWT, Jmin, -1, options) def exo8(): """ Implement denoising by soft and hard thresholding Daubechies wavelet coefficients. """ MW = perform_wavortho_transf(Mnoisy, 1, + 1, options) Tlist = linspace(1, 4, 10)*sigma err_hard = []; err_soft = [] for i in 1: length(Tlist): MWT = perform_thresholding(MW, Tlist(i), 'hard') M1 = perform_wavortho_transf(MWT, 1, -1, options) err_hard(i) = snr(M, M1) MWT = perform_thresholding(MW, Tlist(i), 'soft') M1 = perform_haar_transf(MWT, 1, -1, options) err_soft(i) = snr(M, M1) if i >1 & err_soft(i) >max(err_soft(1: i-1)) Mwav = M1 plot(Tlist/ sigma, [err_hard; err_soft]', '.-') axis('tight') set_label('T/ sigma', 'SNR') legend('hard', 'soft') def exo9(): """ Implement cycle spinning hard thresholding with Daubechies wavelets with |T=3*sigma|. """ T = 3*sigma w = 4 [dX, dY, dZ] = ndgrid(0: w-1, 0: w-1, 0: w-1) Mspin = zeros(n, n, n) for i in 1: w^3: MnoisyC = circshift(Mnoisy, [dX(i) dY(i) dZ(i)]) % denoise MW = perform_wavortho_transf(MnoisyC, 1, + 1, options) MWT = perform_thresholding(MW, T, 'hard') M1 = perform_wavortho_transf(MWT, 1, -1, options) % back M1 = circshift(M1, -[dX(i) dY(i) dZ(i)]) Mspin = Mspin*(i-1)/ i + M1/ i
[ "wendydi@compute001.mcs.anl.gov" ]
wendydi@compute001.mcs.anl.gov
cb4bacfba02f35a4b06e50b9536f97f7af866298
7bd9be7f25be80791f9220b62025f06170273293
/front-plugins/zstatuses/py_cerebro/__init__.py
aa488f1dd5c398d45e43845090805cd67b2b34de
[]
no_license
cerebrohq/cerebro-plugins
ab46b4844adcb12c51d14e21f2c0d8b758b0bb57
e2e0f97b548ef22957e13d614200027ba89215e0
refs/heads/master
2021-11-12T16:25:48.228521
2021-10-22T11:25:58
2021-10-22T11:25:58
143,178,631
5
3
null
null
null
null
UTF-8
Python
false
false
663
py
# -*- coding: utf-8 -*- """ py_cerebro package contains modules that provide program interface for file storage (Cargador) and database. The package includes the following modules: * :py:mod:`py_cerebro.database` -- access to the database to execute :ref:`SQL-queries <sapi-sql>`. * :py:mod:`py_cerebro.dbtypes` -- describes the data tuples of the bit flags used when working with the database. * :py:mod:`py_cerebro.cargador` -- Access to the Cargador file storage. * :py:mod:`py_cerebro.cclib` -- Contains auxiliary functions for handling hashes and bit flags. """ __all__ = ["database", "cargador", "dbtypes", "cclib"] from zstatuses.py_cerebro import *
[ "41910371+cerebroSupport@users.noreply.github.com" ]
41910371+cerebroSupport@users.noreply.github.com
a519345197a1a925a18bcdcaa5c384edde2d15d1
c8335705ff06641622668c9b0a3020df9213bc77
/core/migrations/0013_productpage.py
aae0848edcfab0b1936b19b0cfb191c9132025ec
[]
no_license
Richardh36/ANS
0adedcc760a6acbf539c8cbedde8edc28186218a
2c46d36cf349f3ab8556bf713d2a0125c415029a
refs/heads/master
2016-09-11T02:42:21.952145
2015-05-03T14:03:10
2015-05-03T14:03:10
34,852,005
0
0
null
null
null
null
UTF-8
Python
false
false
680
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0013_update_golive_expire_help_text'), ('core', '0012_contactpage_intro'), ] operations = [ migrations.CreateModel( name='ProductPage', fields=[ ('page_ptr', models.OneToOneField(serialize=False, auto_created=True, parent_link=True, to='wagtailcore.Page', primary_key=True)), ], options={ 'abstract': False, }, bases=('wagtailcore.page',), ), ]
[ "karlhobley10@gmail.com" ]
karlhobley10@gmail.com
f28bd4048ae55c0248d5c639b87f134d62a85807
37e87b3d5e1ee9009f0ea0671bc0c6edf0e233b7
/088_3.py
4cfa9bc9edcedf2f4efdb6f13e6e3b3d9d40b18f
[]
no_license
Jane11111/Leetcode2021
d9f4987792938597bf89ff72ba6bbcb4a3f9d081
a95b871578aae0103066962c33b8c0f4ec22d0f2
refs/heads/master
2023-07-14T21:29:41.196752
2021-08-23T03:28:02
2021-08-23T03:28:02
344,804,297
2
0
null
null
null
null
UTF-8
Python
false
false
736
py
# -*- coding: utf-8 -*- # @Time : 2021-05-13 13:12 # @Author : zxl # @FileName: 088_3.py class Solution: def merge(self, nums1 , m: int, nums2 , n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ if n==0: return p = m+n-1 i = m-1 j = n-1 while p>=0: if i>=0: n1 = nums1[i] else: n1 = float('-inf') if j>=0: n2 = nums2[j] else: n2 = float('-inf') if n1>=n2: nums1[p] = n1 i-=1 else: nums1[p] = n2 j-=1 p-=1
[ "791057615@qq.com" ]
791057615@qq.com
40bef4374a23d5005e5255ead7feb9767a4d762d
d33352f90d3d046e2e2fa55a123b4b2828260fc3
/LeetcodePython/Sqrt(x)69.py
9a627c1f67d9355bb70af15dd91c73dbdcb574e3
[]
no_license
DianaLuca/Algorithms
272c27d7d5fa4b7aa03e7500af01a4d67f15d0bf
b3a2013d1c3c7a5a16727dbc2ecbc934a01a3979
refs/heads/master
2021-09-11T12:37:00.334011
2018-04-07T00:17:57
2018-04-07T00:17:57
68,707,603
1
0
null
null
null
null
UTF-8
Python
false
false
442
py
# Implement int sqrt(int x). # Compute and return the square root of x. class Solution(object): def mySqrt(self, x): """ :type x: float :rtype: float """ l, r = 0, x while l + 1e-6 <= r: print(l, r) m = l + (r - l)/2 if m**2 <= x: l = m else: r = m return l s = Solution() r = s.mySqrt(81) print(r)
[ "lucadiana88@gmail.com" ]
lucadiana88@gmail.com
dc039f93edf88b962ac46de478b4828a0973415a
15a676a82a1344726172e5f422cf0ae56505be69
/src/web/controller/spiderController.py
e555bdcf6a620c0e3da10c75e74f0176912cfc97
[ "MIT" ]
permissive
343695222/QQZoneMood
35c12291ddf58c2571646723b7b8167da3912195
1c406d26bb63681e26d986bce57ab402808bf48a
refs/heads/master
2020-08-20T19:45:35.602392
2019-10-14T06:26:29
2019-10-14T06:26:29
216,059,716
1
0
MIT
2019-10-18T15:57:34
2019-10-18T15:57:33
null
UTF-8
Python
false
false
8,208
py
from flask import Blueprint, session import json from src.util.constant import * from flask import request from src.spider.main import web_interface import threading from time import sleep from src.web.controller.dataController import do_clear_data_by_user from src.web.web_util.web_constant import INVALID_LOGIN, SUCCESS_STATE, FAILED_STATE, FINISH_FRIEND, WAITING_USER_STATE, \ ALREADY_IN, CHECK_COOKIE, LOGGING_STATE, NOT_MATCH_STATE from src.web.web_util.web_util import check_password, md5_password, init_redis_key, get_redis_conn, judge_pool spider = Blueprint('spider', __name__) @spider.route('/query_spider_info/<QQ>/<password>') def query_spider_info(QQ, password): pool_flag = session.get(POOL_FLAG) conn = get_redis_conn(pool_flag) info = conn.lpop(WEB_SPIDER_INFO + QQ) if not check_password(conn, QQ, password): if info is not None and info.find("登陆失败") != -1: return json.dumps(dict(finish=FAILED_STATE, info=info)) else: return json.dumps(dict(finish=INVALID_LOGIN, info=0)) finish = 0 mood_num = -1 friend_num = 0 if info is not None: if info.find(".jpg") != -1: finish = LOGGING_STATE elif info.find(LOGIN_NOT_MATCH) != -1: conn.lrem(WAITING_USER_LIST, QQ) conn.hdel(USER_MAP_KEY, QQ) finish = NOT_MATCH_STATE elif info.find(FRIEND_INFO_PRE) != -1: finish = FINISH_FRIEND friend_num = int(info.split(':')[1]) elif info.find(MOOD_NUM_PRE) != -1: finish = SUCCESS_STATE mood_num = int(info.split(':')[1]) elif info.find("失败") != -1: conn.lrem(WAITING_USER_LIST, QQ) conn.hdel(USER_MAP_KEY, QQ) finish = FAILED_STATE mood_num = FAILED_STATE result = dict(info=info, finish=finish, mood_num=mood_num, friend_num=friend_num) return json.dumps(result, ensure_ascii=False) else: info = '' result = dict(info=info, finish=finish, mood_num=mood_num, friend_num=friend_num) return json.dumps(result, ensure_ascii=False) @spider.route('/query_spider_num/<QQ>/<mood_num>/<password>') def query_spider_num(QQ, mood_num, password): pool_flag = session.get(POOL_FLAG) conn = get_redis_conn(pool_flag) if not check_password(conn, QQ, password): return json.dumps(dict(finish=INVALID_LOGIN)) info = conn.get(MOOD_COUNT_KEY + str(QQ)) # 强制停止,保证在由于网络等原因导致爬取的说说数量有缺失时也能正常停止程序 finish_key = conn.get(MOOD_FINISH_KEY + str(QQ)) finish = 0 if mood_num == "null": mood_num = 0 if finish_key == "1" or int(info) >= int(mood_num): finish = SUCCESS_STATE return json.dumps(dict(num=info, finish=finish, finish_key=finish_key)) @spider.route('/start_spider', methods=['GET', 'POST']) def start_spider(): if request.method == 'POST': nick_name = request.form['nick_name'] qq = request.form['qq'] stop_time = str(request.form['stop_time']) mood_num = int(request.form['mood_num']) no_delete = False if request.form['no_delete'] == 'false' else True password = request.form['password'] password = md5_password(password) print("begin spider:", qq) pool_flag = session.get(POOL_FLAG) conn = get_redis_conn(pool_flag) if conn is None: try: session[POOL_FLAG] = judge_pool() pool_flag = session.get(POOL_FLAG) conn = get_redis_conn(pool_flag) except BaseException: result = dict(result="连接数据库失败,请稍后再尝试") return json.dumps(result, ensure_ascii=False) init_redis_key(conn, qq) waiting_list = check_waiting_list(conn) # 如果排队用户大于阈值,就返回 waiting_num = len(waiting_list) login_success = conn.get(USER_LOGIN_STATE + qq) if qq in waiting_list and login_success == "1": friend_num = conn.get(FRIEND_NUM_KEY + qq) mood_num = conn.get(MOOD_NUM_KEY + qq) result = dict(result=ALREADY_IN, waiting_num=waiting_num, friend_num=friend_num, mood_num=mood_num) return json.dumps(result, ensure_ascii=False) elif qq in waiting_list and login_success == "0": conn.lrem(WAITING_USER_LIST, qq) if waiting_num >= SPIDER_USER_NUM_LIMIT: result = dict(result=WAITING_USER_STATE, waiting_num=waiting_num) return json.dumps(result, ensure_ascii=False) else: # 放进数组,开始爬虫 conn.rpush(WAITING_USER_LIST, qq) try: t = threading.Thread(target=web_interface, args=(qq, nick_name, stop_time, mood_num, "xxx", no_delete, password, pool_flag)) t.start() result = dict(result=SUCCESS_STATE) return json.dumps(result, ensure_ascii=False) except BaseException as e: result = dict(result=e) return json.dumps(result, ensure_ascii=False) else: return "老哥你干嘛?" @spider.route('/stop_spider/<QQ>/<password>') def stop_spider(QQ, password): pool_flag = session.get(POOL_FLAG) conn = get_redis_conn(pool_flag) if not check_password(conn, QQ, password): return json.dumps(dict(finish=INVALID_LOGIN)) # 更新标记位,停止爬虫 conn.set(STOP_SPIDER_KEY + QQ, STOP_SPIDER_FLAG) stop = 0 # 等待数据保存 while True: finish_info = conn.get(STOP_SPIDER_KEY + QQ) if finish_info == FINISH_ALL_INFO: stop = 1 break else: sleep(0.1) num = conn.get(MOOD_COUNT_KEY + str(QQ)) friend_num = conn.get(FRIEND_INFO_COUNT_KEY + str(QQ)) return json.dumps(dict(num=num, finish=stop, friend_num=friend_num)) # 强制停止spider @spider.route('/stop_spider_force/<QQ>/<password>') def stop_spider_force(QQ, password): pool_flag = session.get(POOL_FLAG) conn = get_redis_conn(pool_flag) if not check_password(conn, QQ, password): return json.dumps(dict(finish=INVALID_LOGIN)) # 删除与该用户有关的数据 finish = do_clear_data_by_user(QQ, conn) # 重新设置标记位 conn.set(STOP_SPIDER_KEY + QQ, STOP_SPIDER_FLAG) conn.set(FORCE_STOP_SPIDER_FLAG + QQ, FORCE_STOP_SPIDER_FLAG) return json.dumps(dict(finish=finish)) @spider.route('/query_friend_info_num/<QQ>/<friend_num>/<password>') def query_friend_info_num(QQ, friend_num, password): pool_flag = session.get(POOL_FLAG) conn = get_redis_conn(pool_flag) if not check_password(conn, QQ, password): return json.dumps(dict(finish=INVALID_LOGIN)) info = conn.get(FRIEND_INFO_COUNT_KEY + str(QQ)) finish = 0 if friend_num == "null": friend_num = 0 if int(info) >= int(friend_num): finish = 1 return json.dumps(dict(num=info, finish=finish)) @spider.route('/query_clean_data/<QQ>/<password>') def query_clean_data(QQ, password): pool_flag = session.get(POOL_FLAG) conn = get_redis_conn(pool_flag) if not check_password(conn, QQ, password): return json.dumps(dict(finish=INVALID_LOGIN), ensure_ascii=False) while True: key = conn.get(CLEAN_DATA_KEY + QQ) if key == '1': break else: sleep(0.1) return json.dumps(dict(finish=key), ensure_ascii=False) def check_waiting_list(conn): waiting_list = conn.lrange(WAITING_USER_LIST, 0, -1) return waiting_list @spider.route('/query_finish_user_num') def query_finish_user_num(): pool_flag = session.get(POOL_FLAG) conn = get_redis_conn(pool_flag) if conn is None: host = judge_pool() conn = get_redis_conn(host) finish_user_num = conn.get(FINISH_USER_NUM_KEY) if finish_user_num is None: finish_user_num = 0 waiting_list = check_waiting_list(conn) waiting_num = len(waiting_list) return json.dumps(dict(finish_user_num=finish_user_num, waiting_user_num=waiting_num))
[ "maicius@outlook.com" ]
maicius@outlook.com
0cac1a24f83e80e5ba1a814ae54c5fd731b17ba7
eb38517d24bb32cd8a33206d4588c3e80f51132d
/grayscale.py
5a20f7197e61735bd1df50f7d333c75f69b6fa50
[]
no_license
Fernando23296/l_proy
2c6e209892112ceafa00c3584883880c856b6983
b7fdf99b9bd833ca1c957d106b2429cbd378abd3
refs/heads/master
2020-04-01T18:01:41.333302
2018-12-04T23:45:53
2018-12-04T23:45:53
153,466,681
2
0
null
null
null
null
UTF-8
Python
false
false
197
py
import cv2 image = cv2.imread('ex6.png') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow('Original image', image) cv2.imshow('Gray image', gray) cv2.waitKey(0) cv2.destroyAllWindows()
[ "fernando23296@gmail.com" ]
fernando23296@gmail.com
4bc12c51c6a8d4ba96daf796d0e2e6a2bb932602
787344a140b1f1ca05277b44dbf72fda3fa25cda
/bin/send_reports.py
504319ea16ef9ba6c2a8c41f9fcdcd965bba3976
[ "MIT" ]
permissive
poldrack/r-autograder
6785b40dbd3011dfe5fb47c134c66a8d18985d21
58ab96bed7456aef2cec9e01ff6eff23daec0425
refs/heads/master
2020-12-29T22:57:53.816305
2020-03-05T22:33:24
2020-03-05T22:33:24
238,765,808
3
0
null
2020-02-06T19:25:53
2020-02-06T19:20:10
Python
UTF-8
Python
false
false
976
py
#!/usr/bin/env python """ send reports to students automatically set up postfix gmail relay ala: https://www.justinsilver.com/technology/osx/send-emails-mac-os-x-postfix-gmail-relay/ http://postfix.1071664.n5.nabble.com/MacOS-High-Sierra-10-13-and-Postfix-relaying-td93421.html date | mail -s "Test Email" poldrack@gmail.com """ import os,glob import numpy import json with open('config.json','r') as f: config = json.load(f) infiles=glob.glob('reports/*.txt') sunetDict={} for i in infiles: sunetID=os.path.basename(i).split('_')[0] if sunetID.find('unknown') > -1: print('skipping', sunetID) continue sunetDict[sunetID]=i with open('send_report.sh','w') as f: for sunetID in sunetDict: cmd='mail -s "Results from Week %d PSet automated tests for %s" %s@stanford.edu < %s'%( config['week'], sunetID,sunetID,sunetDict[sunetID]) f.write(cmd+'\n') f.write('sleep %d\n'%(1+numpy.random.randint(18)))
[ "poldrack@gmail.com" ]
poldrack@gmail.com
1b64159778f2c89847c2b168143a6810ad3f4711
5178f5aa20a857f8744fb959e8b246079c800c65
/01_basic/text/src/03/if_ex3.py
fca268651ddcee0a837d8890fbf57c1392c708e2
[]
no_license
murayama333/python2020
4c3f35a0d78426c96f0fbaed335f9a63227205da
8afe367b8b42fcf9489fff1da1866e88f3af3b33
refs/heads/master
2021-05-19T04:03:46.295906
2021-03-09T22:23:58
2021-03-09T22:23:58
251,520,131
0
3
null
2020-10-26T01:20:09
2020-03-31T06:35:18
Python
UTF-8
Python
false
false
153
py
user_id = input("USER ID: ") password = input("PASSWORD: ") if user_id == "Alice" and password == "pass": print("Success") else: print("Error")
[ "murayama333@gmail.com" ]
murayama333@gmail.com
2bd783713fc5e7f9ca1abcb919e06d59ee812dd5
05d3b4d5e0a2b531429434f4500a0f60ec63785d
/Method_Using range in a function.py
f264dfbe02f502becf77e7fae829ed8d8c234943
[]
no_license
golfnut1400/Python201
8fcce72bfee78aafef230b5fdb1bc47bad51b829
311a6d7d55b5e2f76623809102c58ef70464a722
refs/heads/master
2021-09-03T06:33:49.792487
2018-01-06T13:38:58
2018-01-06T13:38:58
110,043,016
0
0
null
null
null
null
UTF-8
Python
false
false
242
py
import random def request_range(start, end): x = random.randrange(start,end) # creates a random number from the 2 arguments print(x) request_range(1,1000) # calls the request_range function and passes the 2 arguments
[ "srcorpuz@hotmail.com" ]
srcorpuz@hotmail.com
e4bc1036fc2022301460be8634e270c0ff35dfdc
8ca045c0b94729222e8f3ffe184c0d4f564418c4
/Image/composite_bands.py
5969cc2f6e8204679acd4bee99030483ca72b467
[ "MIT" ]
permissive
levi-manley/earthengine-py-notebooks
bc77632ca22ca85c0092c18f1eb8321abfbe874a
f5a888ddb6834f164e7399b20c683fb9cf604465
refs/heads/master
2021-01-02T12:17:27.974005
2020-02-09T02:59:20
2020-02-09T02:59:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,656
py
''' <table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/composite_bands.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Image/composite_bands.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td> <td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Image/composite_bands.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Image/composite_bands.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td> </table> ''' # %% ''' ## Install Earth Engine API Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`. The magic command `%%capture` can be used to hide output from a specific cell. Uncomment these lines if you are running this notebook for the first time. ''' # %% # %%capture # !pip install earthengine-api # !pip install geehydro # %% ''' Import libraries ''' # %% import ee import folium import geehydro # %% ''' Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()` if you are running this notebook for the first time or if you are getting an authentication error. ''' # %% # ee.Authenticate() ee.Initialize() # %% ''' ## Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`. ''' # %% Map = folium.Map(location=[40, -100], zoom_start=4) Map.setOptions('HYBRID') # %% ''' ## Add Earth Engine Python script ''' # %% # There are many fine places to look here is one. Comment # this out if you want to twiddle knobs while panning around. Map.setCenter(-61.61625, -11.64273, 14) # Grab a sample L7 image and pull out the RGB and pan bands # in the range (0, 1). (The range of the pan band values was # chosen to roughly match the other bands.) image1 = ee.Image('LANDSAT/LE7/LE72300681999227EDC00') rgb = image1.select('B3', 'B2', 'B1').unitScale(0, 255) gray = image1.select('B8').unitScale(0, 155) # Convert to HSV, swap in the pan band, and convert back to RGB. huesat = rgb.rgbToHsv().select('hue', 'saturation') upres = ee.Image.cat(huesat, gray).hsvToRgb() # Display before and after layers using the same vis parameters. visparams = {'min': [.15, .15, .25], 'max': [1, .9, .9], 'gamma': 1.6} Map.addLayer(rgb, visparams, 'Orignal') Map.addLayer(upres, visparams, 'Pansharpened') # %% ''' ## Display Earth Engine data layers ''' # %% Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True) Map
[ "giswqs@gmail.com" ]
giswqs@gmail.com
369fd4ab3b738c3c268ae4549cc141ea8c623db8
e5f5468ba082b1c057ac4167831aab95aa7c0d27
/backend/home/migrations/0002_load_initial_data.py
c6bfce958c6507b9aeb1cb4243b11fe43b59d7ea
[]
no_license
crowdbotics-apps/mobile-28-oct-dev-14129
bd98341f59a15200661a3896b1288b229247b906
02abe8260760b9eef10871767982e8407642b9b9
refs/heads/master
2023-01-09T13:41:10.439050
2020-10-28T11:31:33
2020-10-28T11:31:33
307,911,560
0
0
null
null
null
null
UTF-8
Python
false
false
1,310
py
from django.db import migrations def create_customtext(apps, schema_editor): CustomText = apps.get_model("home", "CustomText") customtext_title = "mobile 28 oct" CustomText.objects.create(title=customtext_title) def create_homepage(apps, schema_editor): HomePage = apps.get_model("home", "HomePage") homepage_body = """ <h1 class="display-4 text-center">mobile 28 oct</h1> <p class="lead"> This is the sample application created and deployed from the Crowdbotics app. You can view list of packages selected for this application below. </p>""" HomePage.objects.create(body=homepage_body) def create_site(apps, schema_editor): Site = apps.get_model("sites", "Site") custom_domain = "mobile-28-oct-dev-14129.botics.co" site_params = { "name": "mobile 28 oct", } if custom_domain: site_params["domain"] = custom_domain Site.objects.update_or_create(defaults=site_params, id=1) class Migration(migrations.Migration): dependencies = [ ("home", "0001_initial"), ("sites", "0002_alter_domain_unique"), ] operations = [ migrations.RunPython(create_customtext), migrations.RunPython(create_homepage), migrations.RunPython(create_site), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
87294359d3c089c38ac1634f9454dd7fffc84699
943dca755b940493a8452223cfe5daa2fb4908eb
/abc114/c.py
b6b7ae6b28b7b8b6d6eff7f89534a53858c8d4db
[]
no_license
ymsk-sky/atcoder
5e34556582763b7095a5f3a7bae18cbe5b2696b2
36d7841b70b521bee853cdd6d670f8e283d83e8d
refs/heads/master
2023-08-20T01:34:16.323870
2023-08-13T04:49:12
2023-08-13T04:49:12
254,348,518
0
0
null
null
null
null
UTF-8
Python
false
false
178
py
n=int(input()) c=0 def a(i): if int(i)>n: return 0 r=1 if all(i.count(c)>0for c in '753') else 0 for c in '753': r+=a(i+c) return r print(a('0'))
[ "ymsk.sky.95@gmail.com" ]
ymsk.sky.95@gmail.com
105f6318e16efd787729c4524688009e64c39a6b
57023b55d9e136b8e2527e2c666b053f73bb6bc9
/get_url.py
9e8146918c444ca7b18e1f93400b9904f267d58e
[]
no_license
zengzhiyi/zhuanzhuan_pyspider
f98867742d9f7c760d7274528f85e91439964a48
4f27f410a75acec467de4fa73b759cb8a4d6351a
refs/heads/master
2021-01-13T10:55:28.659431
2016-10-29T11:34:56
2016-10-29T11:34:56
72,281,052
0
0
null
null
null
null
UTF-8
Python
false
false
1,389
py
from pyspider.libs.base_handler import * import pymysql class Handler(BaseHandler): crawl_config = { } # # def __init__(self): # self.db = pymysql.Connect('localhost', 'localhost', '123456', data=) start_url = 'http://www.zhuanzhuan.com/' grab_url = 'http://zhuanzhuan.58.com/detail/744782895816835076z.shtml' @every(minutes=24*60) def on_start(self): self.crawl(self.start_url, callback=self.channel_page) @config(age=10*24*60*60) def channel_page(self, response): for each in response.doc('a[href^="http://cd.58.com/"').items(): self.crawl(each.attr.href, callback=self.grab_index) @config(age=10*24*60*60) def grab_index(self, response): for each in response.doc('a[href^="http://zhuanzhuan.58.com/detail/"').items(): self.crawl(each.attr.href, callback=self.detail_page) @config(age=10*24*60*60) def detail_page(self, response): title = response.doc('h1').text() place = response.doc('div.palce_li > span > i').text() price = response.doc('div.price_li > span > i').text() quality = response.doc('div.info_massege.left > div.biaoqian_li').text() # self.add_question(title, content) return { 'title': title, 'place': place, 'price': price, 'quality': quality, }
[ "zengzhiyi@gearblade.com" ]
zengzhiyi@gearblade.com
40b7f46aecadddd429b5ea68491717f4c62a0d36
a4ecd7798cfa04676e892898774d1e5824b095fb
/distributed/utils.py
8e2136a99c71da5584d431ba41d5733e85db4cb9
[]
no_license
kevineriklee/distributed
c48ccb6086861c1adb2a5d7091d792a923387a27
b0b7c27e4ee6d7b5eebe6569fcf29b32418be440
refs/heads/master
2020-12-24T21:27:06.374245
2016-02-03T12:43:06
2016-02-03T12:43:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,049
py
from __future__ import print_function, division, absolute_import from collections import Iterable from contextlib import contextmanager import logging import os import re import socket import sys import tempfile import traceback from dask import istask from toolz import memoize from tornado import gen logger = logging.getLogger(__name__) def funcname(func): """Get the name of a function.""" while hasattr(func, 'func'): func = func.func try: return func.__name__ except: return str(func) def get_ip(): return [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1] @contextmanager def ignoring(*exceptions): try: yield except exceptions: pass @gen.coroutine def ignore_exceptions(coroutines, *exceptions): """ Process list of coroutines, ignoring certain exceptions >>> coroutines = [cor(...) for ...] # doctest: +SKIP >>> x = yield ignore_exceptions(coroutines, TypeError) # doctest: +SKIP """ wait_iterator = gen.WaitIterator(*coroutines) results = [] while not wait_iterator.done(): with ignoring(*exceptions): result = yield wait_iterator.next() results.append(result) raise gen.Return(results) @gen.coroutine def All(*args): """ Wait on many tasks at the same time Err once any of the tasks err. See https://github.com/tornadoweb/tornado/issues/1546 """ if len(args) == 1 and isinstance(args[0], Iterable): args = args[0] tasks = gen.WaitIterator(*args) results = [None for _ in args] while not tasks.done(): result = yield tasks.next() results[tasks.current_index] = result raise gen.Return(results) def sync(loop, func, *args, **kwargs): """ Run coroutine in loop running in separate thread """ if not loop._running: try: return loop.run_sync(lambda: func(*args, **kwargs)) except RuntimeError: # loop already running pass from threading import Event e = Event() result = [None] error = [False] @gen.coroutine def f(): try: result[0] = yield gen.maybe_future(func(*args, **kwargs)) except Exception as exc: logger.exception(exc) result[0] = exc error[0] = True finally: e.set() a = loop.add_callback(f) e.wait() if error[0]: raise result[0] else: return result[0] @contextmanager def tmp_text(filename, text): fn = os.path.join(tempfile.gettempdir(), filename) with open(fn, 'w') as f: f.write(text) try: yield fn finally: if os.path.exists(fn): os.remove(fn) def clear_queue(q): while not q.empty(): q.get_nowait() def is_kernel(): """ Determine if we're running within an IPython kernel >>> is_kernel() False """ # http://stackoverflow.com/questions/34091701/determine-if-were-in-an-ipython-notebook-session if 'IPython' not in sys.modules: # IPython hasn't been imported return False from IPython import get_ipython # check for `kernel` attribute on the IPython instance return getattr(get_ipython(), 'kernel', None) is not None def _deps(dsk, arg): """ Get dependencies from keys or tasks Helper function for get_dependencies. >>> inc = lambda x: x + 1 >>> add = lambda x, y: x + y >>> dsk = {'x': 1, 'y': 2} >>> _deps(dsk, 'x') ['x'] >>> _deps(dsk, (add, 'x', 1)) ['x'] >>> _deps(dsk, ['x', 'y']) ['x', 'y'] >>> _deps(dsk, {'name': 'x'}) ['x'] >>> _deps(dsk, (add, 'x', (inc, 'y'))) # doctest: +SKIP ['x', 'y'] """ if istask(arg): result = [] for a in arg[1:]: result.extend(_deps(dsk, a)) return result if isinstance(arg, list): return sum([_deps(dsk, a) for a in arg], []) if isinstance(arg, dict): return sum([_deps(dsk, v) for v in arg.values()], []) try: if arg not in dsk: return [] except TypeError: # not hashable return [] return [arg] def key_split(s): """ >>> key_split('x-1') 'x' >>> key_split('x-1-2-3') 'x' >>> key_split(('x-2', 1)) 'x' >>> key_split(None) 'Other' """ if isinstance(s, tuple): return key_split(s[0]) try: return s.split('-', 1)[0] except: return 'Other' @contextmanager def log_errors(): try: yield except gen.Return: raise except Exception as e: logger.exception(e) raise @memoize def ensure_ip(hostname): """ Ensure that address is an IP address >>> ensure_ip('localhost') '127.0.0.1' >>> ensure_ip('123.123.123.123') # pass through IP addresses '123.123.123.123' """ if re.match('\d+\.\d+\.\d+\.\d+', hostname): # is IP return hostname else: return socket.gethostbyname(hostname) def get_traceback(): exc_type, exc_value, exc_traceback = sys.exc_info() tb = traceback.format_tb(exc_traceback) tb = [line[:10000] for line in tb] return tb def truncate_exception(e, n=10000): """ Truncate exception to be about a certain length """ if len(str(e)) > n: try: return type(e)("Long error message", str(e)[:n]) except: return Exception("Long error message", type(e), str(e)[:n]) else: return e import logging logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s', level=logging.INFO) # http://stackoverflow.com/questions/21234772/python-tornado-disable-logging-to-stderr stream = logging.StreamHandler(sys.stderr) stream.setLevel(logging.CRITICAL) logging.getLogger('tornado').addHandler(stream) logging.getLogger('tornado').propagate = False
[ "mrocklin@gmail.com" ]
mrocklin@gmail.com
7fd3ef46896d70511ef8915b44227ec5c7aea8e2
167c6226bc77c5daaedab007dfdad4377f588ef4
/python/ql/test/query-tests/Expressions/general/compare.py
141b5e6a0286eb0877da38d45efaf28b0cf9277e
[ "MIT", "LicenseRef-scancode-python-cwi", "LicenseRef-scancode-other-copyleft", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Python-2.0" ]
permissive
github/codeql
1eebb449a34f774db9e881b52cb8f7a1b1a53612
d109637e2d7ab3b819812eb960c05cb31d9d2168
refs/heads/main
2023-08-20T11:32:39.162059
2023-08-18T14:33:32
2023-08-18T14:33:32
143,040,428
5,987
1,363
MIT
2023-09-14T19:36:50
2018-07-31T16:35:51
CodeQL
UTF-8
Python
false
false
327
py
#OK a = b = 1 a == b a.x == b.x #Same variables a == a a.x == a.x #Compare constants 1 == 1 1 == 2 #Maybe missing self class X(object): def __init__(self, x): self.x = x def missing_self(self, x): if x == x: print ("Yes") #Compare constants in assert -- ok assert(1 == 1)
[ "mark@hotpy.org" ]
mark@hotpy.org
ca8a8ac861ee58b34eefc98e9160ef198072392a
145439ad19a9c3c9d40f805ccf9ff5794ca28d62
/senseplot_es.1.py
541013ab8d2377881041a491815ab1ede5137190
[]
no_license
emawind84/sensehat-discotest
f5b122f004eee4e74ba63322aecb723d7a191583
87a7aff71969ef9beab0120eaddc132e0d16b561
refs/heads/master
2020-05-21T04:27:43.090658
2017-10-10T14:30:52
2017-10-10T14:30:52
46,617,896
0
0
null
null
null
null
UTF-8
Python
false
false
2,411
py
#!/usr/bin/env python import csv import sys import logging import argparse import matplotlib import requests import json import dateutil.parser matplotlib.use("Agg") import matplotlib.dates as md import matplotlib.pyplot as plt logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s') _logger = logging.getLogger(__name__) _logger.setLevel(logging.DEBUG) x = [] y = [] plotdata = 'temp_h' PLOT_SAVE_PATH = '/home/pi/sensehat-datalog/plot' CSV_MAP = {'temp_h': 0, 'temp_p': 1, 'humidity': 2, 'pressure': 3, 'pitch': 4, 'roll': 5, 'yaw': 6, 'mag_x': 7, 'mag_y': 8, 'mag_z': 9, 'acc_x': 10, 'acc_y': 11, 'acc_z': 12, 'gyro_x': 13, 'gyro_y': 14, 'gyro_z': 15, 'timestamp': 16} def main(): s = requests.session() query = { "query": { "range": { "timestamp": { "gte": "now-4d/d", "lte": "now/d" } } }, "size": 2000, "sort": [{ "timestamp": { "order": "asc" } }] } result = s.get('http://localhost:9200/sense/stats/_search', data=json.dumps(query)) jresult = result.json() datalist = jresult['hits']['hits'] _t = len(datalist) // 40 _i = -1 for rowdata in datalist: _i += 1 if _i % _t != 0: continue rowdata = rowdata['_source'] _logger.debug(rowdata) x.append(dateutil.parser.parse(rowdata['timestamp'])) y.append(rowdata[plotdata]) plt.plot(x, y) plt.gca().xaxis.set_major_formatter(md.DateFormatter("%Y-%m-%d %H:%M")) plt.gca().get_yaxis().get_major_formatter().set_useOffset(False) plt.axhline(0, color='black', lw=2) plt.xlabel("timestamp") plt.ylabel(plotdata) plt.gcf().autofmt_xdate() #plt.savefig(PLOT_SAVE_PATH + "/senselog.png") plt.savefig(PLOT_SAVE_PATH + "/senselog.png", bbox_inches = "tight") plt.clf() if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] in CSV_MAP: plotdata = sys.argv[1] ''' parser = argparse.ArgumentParser() parser.add_argument('--debug', '-d', action='store_true', dest='debug', help='More logging on console') _args = parser.parse_args() if _args.debug: _logger.setLevel(logging.DEBUG) ''' main()
[ "emawind84@gmail.com" ]
emawind84@gmail.com
640b1981de612c8310929ae47e05cb72c6ab8ffd
243d0543f8d38f91954616c014456122292a1a3c
/CS1/0340_lists/challenge1.py
34564036d9d41147eeed4c7ecb4f996fdaf78e98
[ "MIT" ]
permissive
roni-kemp/python_programming_curricula
758be921953d82d97c816d4768fbcf400649e969
eda4432dab97178b4a5712b160f5b1da74c068cb
refs/heads/master
2023-03-23T13:46:42.186939
2020-07-15T17:03:34
2020-07-15T17:03:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
850
py
#For 35 points, answer the following questions. '''1. Write a function that takes a single number named x and returns a list of all the numbers from x to 0 in descending order. For example, if 5 is passed to the function, then the function should return a list that equals [5,4,3,2,1,0].''' '''2. The following program contains a function that searches for the smallest value in a list and returns the index of that value. The program also includes an example call to the function to test it out. Unscramble the code to make it work. Include proper indentation.''' index = 0 print('working correctly.') smallest = 2**30 #Start very large smallest=numbers[i] index = i def getSmallest(numbers): if result == 3: return index my_list = [-45,2,78,-100,331,-4] if numbers[i] < smallest: result = getSmallest(my_list) for i in range(len(numbers)):
[ "neal.holts@gmail.com" ]
neal.holts@gmail.com
65d7ff9326e1b49582142df46e4ec8e58c0ea585
32fdc94d1b8d98085db5d1e8caae4161d3e70667
/3rd_party/python3.7/lib/python3.7/site-packages/aliyunsdkcore/acs_exception/exceptions.py
c5a3152d161d237e31cef9651573890127244bbf
[ "Python-2.0" ]
permissive
czfdlut/ticket_proxy
fa0f1924a86babfa7ce96cf97e929f7bf78643b7
0d7c19448741bc9030484a97c1b8f118098213ad
refs/heads/master
2022-12-23T05:25:58.207123
2019-11-20T03:58:31
2019-11-20T03:58:31
174,579,562
1
3
null
2022-12-18T01:18:07
2019-03-08T17:22:48
Python
UTF-8
Python
false
false
2,808
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # coding=utf-8 """ SDK exception module. """ from aliyunsdkcore.acs_exception import error_type class ClientException(Exception): """client exception""" def __init__(self, code, msg): """ :param code: error code :param message: error message :return: """ Exception.__init__(self) self.__error_type = error_type.ERROR_TYPE_CLIENT self.message = msg self.error_code = code def __str__(self): return "%s %s" % ( self.error_code, self.message, ) def set_error_code(self, code): self.error_code = code def set_error_msg(self, msg): self.message = msg def get_error_type(self): return self.__error_type def get_error_code(self): return self.error_code def get_error_msg(self): return self.message class ServerException(Exception): """ server exception """ def __init__(self, code, msg, http_status=None, request_id=None): Exception.__init__(self) self.error_code = code self.message = msg self.__error_type = error_type.ERROR_TYPE_SERVER self.http_status = http_status self.request_id = request_id def __str__(self): return "HTTP Status: %s Error:%s %s RequestID: %s" % ( str(self.http_status), self.error_code, self.message, self.request_id ) def set_error_code(self, code): self.error_code = code def set_error_msg(self, msg): self.message = msg def get_error_type(self): return self.__error_type def get_error_code(self): return self.error_code def get_error_msg(self): return self.message def get_http_status(self): return self.http_status def get_request_id(self): return self.request_id
[ "czfdlut@163.com" ]
czfdlut@163.com
462c1c5536931ffd74fe6adb0021f49f47a22917
c4c4a825e361d15aa60603e52195bbeea2b31ad8
/src/generator.py
ae550a23acdbb4d5b1895b970705ac88b8b828f5
[]
no_license
brianyu28/accompaniment
cabb55cd26f6e0525dc60df7a493430860b702e8
a2dd062631d7316bda38823ca23ea6fba33aafb4
refs/heads/master
2021-08-24T08:02:45.675990
2017-12-08T19:28:06
2017-12-08T19:28:06
109,048,094
0
1
null
null
null
null
UTF-8
Python
false
false
2,787
py
import os import uuid from contextlib import redirect_stdout from midi2audio import FluidSynth from midiutil import MIDIFile from pydub import AudioSegment def generate(filename, sequence, configuration, mls, volumes): """ Generates merged audio file. """ print("Generating accompaniment audio...") # Maintain dictionary of which notes of configuration to play. notes = {0: None} prev = None for i, note_number in enumerate(mls): # Don't play notes we've already played, or that aren't meant to be. if note_number in notes or \ str(note_number) not in configuration["accompaniment"]: continue # Add note to dictionary. time = sequence["notes"][i - 1][0] velocity = volumes[configuration["piece"][note_number - 1]["vel"]] pitches = configuration["accompaniment"][str(note_number)] notes[note_number] = { "time": time, "velocity": velocity, "pitches": pitches } # Set duration of the prior note. if prev is not None: notes[prev]["duration"] = time - notes[prev]["time"] prev = note_number # Set duration of the final note. notes[prev]["duration"] = sequence["duration"] - notes[prev]["time"] # Configure MIDI file. midifile = MIDIFile(1, adjust_origin=True) track, channel = 0, 0 midifile.addTempo(0, 0, 60) # Add notes to MIDI file. for i in range(1, prev + 1): if i not in notes: continue for pitch in notes[i]["pitches"]: midifile.addNote(track, channel, pitch, notes[i]["time"], notes[i]["duration"], notes[i]["velocity"]) # Create temporary MIDI file. identifier = str(uuid.uuid4()) with open("{}.mid".format(identifier), "wb") as outfile: midifile.writeFile(outfile) # Convert temporary MIDI file to teporary WAV file. FluidSynth().midi_to_audio("{}.mid".format(identifier), "{}.wav".format(identifier)) # Combine accompaniment audio with soloist audio. merge(filename, "{}.wav".format(identifier), "output.wav") # Clean up temporary files. os.remove("{}.mid".format(identifier)) os.remove("{}.wav".format(identifier)) def merge(file1, file2, outfile): """ Overlays two .wav files and converts to a single .wav output. """ print("Merging recording with accompaniment...") # Take .wav file inputs and adjust volume. audio1 = AudioSegment.from_file(file1) audio1 = audio1 - 10 audio2 = AudioSegment.from_file(file2) audio2 = audio2 + 10 # Overlay audio and export to file. overlayed = audio1.overlay(audio2) overlayed.export(outfile, format="wav")
[ "brianyu28@gmail.com" ]
brianyu28@gmail.com
d81fb844ab079e8c36d9a292a808fafb58ad814e
bde2d795de28f9bbfc414752cc49d8ec3e0f00fd
/syntext/test/test_dynamical_load_classes.py
3f642821f1fa935e8ad25d61bfc44709cb6d2ac1
[]
no_license
lem89757/syntext
b934cd9339fb938db1c0bb9228852cec3d6e5a03
9d3e2e9bb68b325122072d8378217623d3804641
refs/heads/master
2022-12-01T20:06:25.328315
2020-08-18T04:38:06
2020-08-18T04:38:06
294,897,996
1
0
null
2020-09-12T07:57:33
2020-09-12T07:57:32
null
UTF-8
Python
false
false
370
py
from syntext.utils.utils import dynamic_load from syntext.text.generator import TextGenerator module_name = "syntext.text.generator" modules = dynamic_load(module_name, TextGenerator) for module in modules: print(module) # RUN: python -m syntext.test.test_dynamical_load_classes def test_fake_print(*arg): print(*arg) test_fake_print("%s is string" % "xxx")
[ "piginzoo@gmail.com" ]
piginzoo@gmail.com
36cf57e1c202ca5edbc650d557e7ec4d3e91c89f
c426a94f2e48a464a19076e4bea5d9553f11a979
/src/collective/cover/tests/test_refresh_behavior.py
9a99f022cfdeafc14722093a42b8a39cb6dacf3a
[]
no_license
Mubra/collective.cover
36932c5ed3df295a9079db5e2786765370b68fcd
410254dc73093181637e7982c25d18f63936fcb1
refs/heads/master
2020-07-31T18:49:26.617963
2019-10-01T15:18:52
2019-10-01T15:18:52
210,716,653
1
0
null
2019-10-01T15:18:54
2019-09-24T23:43:28
Python
UTF-8
Python
false
false
2,325
py
# -*- coding: utf-8 -*- from collective.cover.behaviors.interfaces import IRefresh from collective.cover.interfaces import ICoverLayer from collective.cover.testing import INTEGRATION_TESTING from plone import api from plone.behavior.interfaces import IBehavior from plone.dexterity.interfaces import IDexterityFTI from plone.dexterity.schema import SchemaInvalidatedEvent from zope.component import queryUtility from zope.event import notify from zope.interface import alsoProvides import unittest class RefreshBehaviorTestCase(unittest.TestCase): layer = INTEGRATION_TESTING def _enable_refresh_behavior(self): fti = queryUtility(IDexterityFTI, name='collective.cover.content') behaviors = list(fti.behaviors) behaviors.append(IRefresh.__identifier__) fti.behaviors = tuple(behaviors) # invalidate schema cache notify(SchemaInvalidatedEvent('collective.cover.content')) def _disable_refresh_behavior(self): fti = queryUtility(IDexterityFTI, name='collective.cover.content') behaviors = list(fti.behaviors) behaviors.remove(IRefresh.__identifier__) fti.behaviors = tuple(behaviors) # invalidate schema cache notify(SchemaInvalidatedEvent('collective.cover.content')) def setUp(self): self.portal = self.layer['portal'] self.request = self.layer['request'] alsoProvides(self.request, ICoverLayer) with api.env.adopt_roles(['Manager']): self.cover = api.content.create( self.portal, 'collective.cover.content', 'c1') def test_refresh_registration(self): registration = queryUtility(IBehavior, name=IRefresh.__identifier__) self.assertIsNotNone(registration) def test_refresh_behavior(self): view = api.content.get_view(u'view', self.cover, self.request) self.assertNotIn('<meta http-equiv="refresh" content="300" />', view()) self._enable_refresh_behavior() self.cover.enable_refresh = True self.assertIn('<meta http-equiv="refresh" content="300" />', view()) self.cover.ttl = 5 self.assertIn('<meta http-equiv="refresh" content="5" />', view()) self._disable_refresh_behavior() self.assertNotIn('<meta http-equiv="refresh" content="5" />', view())
[ "hector.velarde@gmail.com" ]
hector.velarde@gmail.com
66b3e2d6486ac2860cf3d9dc0e2ce7f27b2b2f61
5da5473ff3026165a47f98744bac82903cf008e0
/packages/google-cloud-rapidmigrationassessment/samples/generated_samples/rapidmigrationassessment_v1_generated_rapid_migration_assessment_create_collector_async.py
e8096a9b9f9911d1e03ce9c62faa838ef80f8c2b
[ "Apache-2.0" ]
permissive
googleapis/google-cloud-python
ed61a5f03a476ab6053870f4da7bc5534e25558b
93c4e63408c65129422f65217325f4e7d41f7edf
refs/heads/main
2023-09-04T09:09:07.852632
2023-08-31T22:49:26
2023-08-31T22:49:26
16,316,451
2,792
917
Apache-2.0
2023-09-14T21:45:18
2014-01-28T15:51:47
Python
UTF-8
Python
false
false
2,128
py
# -*- coding: utf-8 -*- # Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for CreateCollector # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-rapidmigrationassessment # [START rapidmigrationassessment_v1_generated_RapidMigrationAssessment_CreateCollector_async] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: # - It may require correct/in-range values for request initialization. # - It may require specifying regional endpoints when creating the service # client as shown in: # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import rapidmigrationassessment_v1 async def sample_create_collector(): # Create a client client = rapidmigrationassessment_v1.RapidMigrationAssessmentAsyncClient() # Initialize request argument(s) request = rapidmigrationassessment_v1.CreateCollectorRequest( parent="parent_value", collector_id="collector_id_value", ) # Make the request operation = client.create_collector(request=request) print("Waiting for operation to complete...") response = (await operation).result() # Handle the response print(response) # [END rapidmigrationassessment_v1_generated_RapidMigrationAssessment_CreateCollector_async]
[ "noreply@github.com" ]
googleapis.noreply@github.com
7ae1c12e9f2be77ce9f0ab92c3f38e121f1a177c
0b79d66196e9bef7cf81c0c17b6baac025b0d7f1
/apps/institute/exchange/models/trans.py
4df3228dfa5fefa15caa4a09069fda9dca77b0a5
[]
no_license
tsevindik/sis-back
bf0244a803ba9432980844ff35498780ac664564
4ba942fe38cc150c70898db4daf211213b84a61a
refs/heads/master
2021-03-24T09:35:49.199712
2017-01-25T08:19:37
2017-01-25T08:19:37
73,540,756
0
0
null
null
null
null
UTF-8
Python
false
false
446
py
from django.utils.translation import ugettext_lazy as _ from django.db import models from utils.models import trans as trans_models from . import main class ExchangeProgramTrans(trans_models.Translation): neutral = models.ForeignKey( main.ExchangeProgram ) name = models.CharField( max_length=150, verbose_name=_("İsim") ) description = models.TextField( verbose_name=_("Açıklama") )
[ "abdullahsecer@std.sehir.edu.tr" ]
abdullahsecer@std.sehir.edu.tr
e4ad7da2163fa94929de33817be367d5a2304aa4
9c9c6b8deca524c9401dd24d19510d3843bebe4b
/lib/rosserial-0.7.7/rosserial_python/nodes/message_info_service.py
255dc0b61ed3c8c8ee470478ca83f71d4bb5d3c3
[ "MIT" ]
permissive
tku-iarc/wrs2020
3f6473c2f3077400527b5e3008ae8a6e88eb00d6
a19d1106206e65f9565fa68ad91887e722d30eff
refs/heads/master
2022-12-12T20:33:10.958300
2021-02-01T10:21:09
2021-02-01T10:21:09
238,463,359
3
8
MIT
2022-12-09T02:09:35
2020-02-05T14:00:16
C++
UTF-8
Python
false
false
3,811
py
#!/usr/bin/env python ##################################################################### # Software License Agreement (BSD License) # # Copyright (c) 2013, Clearpath Robotics # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ The node provided by this file exposes a helper service used by the C++ rosserial_server. The service allows the C++ driver to look up message definitions and hash strings which would not have been known to it at compile time, allowing it to fully advertise topics originating from microcontrollers. This allows rosserial_server to be distributed in binary form. """ import rospy from rosserial_msgs.srv import RequestMessageInfo from rosserial_msgs.srv import RequestServiceInfo from rosserial_python import load_message from rosserial_python import load_service class MessageInfoService(object): """ """ def __init__(self): rospy.init_node("message_info_service") rospy.loginfo("rosserial message_info_service node") self.service = rospy.Service("message_info", RequestMessageInfo, self._message_info_cb) self.serviceInfoService = rospy.Service("service_info", RequestServiceInfo, self._service_info_cb) self.message_cache = {} self.service_cache = {} def _message_info_cb(self, req): package_message = tuple(req.type.split("/")) if not self.message_cache.has_key(package_message): rospy.loginfo("Loading module to return info on %s/%s." % package_message) msg = load_message(*package_message) self.message_cache[package_message] = (msg._md5sum, msg._full_text) else: rospy.loginfo("Returning info from cache on %s/%s." % package_message) return self.message_cache[package_message] def _service_info_cb(self, req): rospy.logdebug("req.service is %s" % req.service) package_service = tuple(req.service.split("/")) if not self.service_cache.has_key(package_service): rospy.loginfo("Loading module to return info on service %s/%s." % package_service) srv,mreq,mres = load_service(*package_service) self.service_cache[package_service] = (srv._md5sum,mreq._md5sum,mres._md5sum) else: rospy.loginfo("Returning info from cache on %s/%s." % package_service) return self.service_cache[package_service] def spin(self): rospy.spin() if __name__=="__main__": MessageInfoService().spin()
[ "dual-arm@dualarm.com" ]
dual-arm@dualarm.com
e5ea6a00ec40529047d2c1c4091f48835b8d9bcf
ba3cd834eb2810dd672e026f5f809b8b32918052
/app/models.py
c55325761c7e8e42ece2616e51e8e8765ad45bc3
[]
no_license
JellyWX/stripe-donations
6f9fb789fdfb09417b33964edf1c8c7083d7e248
1c4b38dace0c952dfb7a7eb425f83069312fed6a
refs/heads/master
2020-03-21T01:06:57.410200
2018-07-23T17:29:56
2018-07-23T17:29:56
137,925,116
0
0
null
null
null
null
UTF-8
Python
false
false
240
py
from app import db class SimpleUser(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String) email = db.Column(db.String, index=True, unique=True) user_id = db.Column(db.Integer, unique=True)
[ "judewrs@gmail.com" ]
judewrs@gmail.com
d7826c4912bd789949d878121f50e3572b86da3f
d05c946e345baa67e7894ee33ca21e24b8d26028
/general/detect-fraudulent-transactions/producer.py
158ba419a43b331f7a476d98ab26bb4e9fd7350e
[ "MIT" ]
permissive
x4nth055/pythoncode-tutorials
327255550812f84149841d56f2d13eaa84efd42e
d6ba5d672f7060ba88384db5910efab1768c7230
refs/heads/master
2023-09-01T02:36:58.442748
2023-08-19T14:04:34
2023-08-19T14:04:34
199,449,624
1,858
2,055
MIT
2023-08-25T20:41:56
2019-07-29T12:35:40
Jupyter Notebook
UTF-8
Python
false
false
641
py
import os import json from time import sleep from kafka import KafkaProducer # import initialization parameters from settings import * from transactions import create_random_transaction if __name__ == "__main__": producer = KafkaProducer(bootstrap_servers = KAFKA_BROKER_URL #Encode all values as JSON ,value_serializer = lambda value: json.dumps(value).encode() ,) while True: transaction: dict = create_random_transaction() producer.send(TRANSACTIONS_TOPIC, value= transaction) print(transaction) #DEBUG sleep(SLEEP_TIME)
[ "fullclip@protonmail.com" ]
fullclip@protonmail.com
fe18a1b59c75b08af2133e32331902343921e6ae
5cd7a8e67a911d1a5562488349db38979ff1c047
/CSV/exercise 25.1/exercise 25.1.py
066d70d3f7456650d769f9e18d8de7595b1fc119
[]
no_license
IshaanBAgrawal/Day-25
3f154186b040de35b19908fb790807954f5805dc
070ab3178c5aa3dde25391e69065e08a69665ee1
refs/heads/master
2023-07-01T18:45:27.997485
2021-08-10T10:04:41
2021-08-10T10:04:41
394,603,857
0
0
null
null
null
null
UTF-8
Python
false
false
605
py
import pandas squirrel_data = pandas.read_csv("Central_Park_Squirrel_census.csv") print(type(squirrel_data)) squirrel_fur_color = squirrel_data["Primary Fur Color"] black = 0 gray = 0 cinnamon = 0 for color in squirrel_fur_color: if color == "Black": black += 1 elif color == "Gray": gray += 1 elif color == "Cinnamon": cinnamon += 1 else: pass squirrel_color = { "colors": ["Black", "Gray", "Cinnamon"], "squirrel_no": [black, gray, cinnamon] } squirrel_color_no = pandas.DataFrame(squirrel_color) squirrel_color_no.to_csv("Squirrel_color.csv")
[ "agrawalishaan115@gmail.com" ]
agrawalishaan115@gmail.com
65cdcdf0253ddb4b8e88d7d4ee6ec35326b939af
8e1844578805b43b7b5ef81b6a4efb85e5481af2
/sysfacts/api.py
0ea674167d2cec14bf352976739e2419bbfcdd07
[ "MIT" ]
permissive
pmav99/sysfacts
d73720c42d00b5d8327e483cef0221bacd13035e
09a5658a8f4e789db71844759dd4ae61369f4f4a
refs/heads/master
2020-04-17T14:08:13.182321
2019-01-25T20:20:36
2019-01-25T23:31:03
166,644,847
2
0
null
null
null
null
UTF-8
Python
false
false
1,442
py
# from __future__ import annotations import platform import cpuinfo # type: ignore import distro # type: ignore import pendulum # type: ignore import psutil # type: ignore # TODO @##@#$! mypy def _to_dict(named_tuple) -> dict: return dict(named_tuple._asdict()) def get_timestamp() -> str: return str(pendulum.now()) def get_os_release() -> dict: return distro.os_release_info() def get_lsb_release() -> dict: return distro.lsb_release_info() def get_distro_release() -> dict: return distro.distro_release_info() def get_uname() -> dict: return _to_dict(platform.uname()) def get_cpuinfo() -> dict: return cpuinfo.get_cpu_info() def get_memory_info() -> dict: return _to_dict(psutil.virtual_memory()) def get_swap_info() -> dict: return _to_dict(psutil.swap_memory()) def get_cpu_usage() -> dict: return _to_dict(psutil.cpu_times_percent()) def collect_facts() -> dict: """ Return a dictionary with data collected from various source. """ data: dict = { "timestamp": get_timestamp(), "os_release": get_os_release(), "lsb_release": get_lsb_release(), "distro_release": get_distro_release(), "uname": get_uname(), "cpu_info": get_cpuinfo(), "memory_info": get_memory_info(), "swap_info": get_swap_info(), "cpu_usage": get_cpu_usage(), } return data __all__ = ["collect_facts"]
[ "pmav99@gmail.com" ]
pmav99@gmail.com
07931e2f7377890e3555fc52ea41e287579a4de0
c62fc7366ba080c22d54249561ce572dee085f07
/tests/test_widget_selectdate.py
bc18260ede55a64d3e9fa4d93660e608ef939aa2
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
wendelas/django-material
9b69e7040e7279b88e45f82ad6aea33a46a82d02
e29d1568bd450a8066b637d0018a9bf07d2f7948
refs/heads/master
2021-01-13T15:45:24.107306
2015-12-31T02:19:17
2015-12-31T02:19:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,767
py
import json from django import forms from django.test.utils import override_settings from django_webtest import WebTest from . import build_test_urls try: from django.forms.widgets import SelectDateWidget except ImportError: # django 1.8 from django.forms.extras import SelectDateWidget class SelectForm(forms.Form): test_field = forms.DateField( widget=SelectDateWidget) data_field = forms.BooleanField(required=False, widget=forms.HiddenInput, initial=True, help_text='To produce non empty POST for empty test_field') @override_settings(ROOT_URLCONF=__name__) class Test(WebTest): default_form = SelectForm def test_default_usecase(self): page = self.app.get(self.test_default_usecase.url) self.assertIn('id="id_test_field_container"', page.body.decode('utf-8')) self.assertIn('id="id_test_field_year"', page.body.decode('utf-8')) self.assertIn('id="id_test_field_month"', page.body.decode('utf-8')) self.assertIn('id="id_test_field_day"', page.body.decode('utf-8')) # self.assertIn('data-test="Test Attr"', page.body.decode('utf-8')) form = page.form self.assertIn('test_field_year', form.fields) self.assertIn('test_field_month', form.fields) self.assertIn('test_field_day', form.fields) form['test_field_year'] = '2015' form['test_field_month'] = '1' form['test_field_day'] = '13' response = json.loads(form.submit().body.decode('utf-8')) self.assertIn('cleaned_data', response) self.assertIn('test_field', response['cleaned_data']) self.assertEquals('2015-01-13', response['cleaned_data']['test_field']) urlpatterns = build_test_urls(Test)
[ "kmmbvnr@gmail.com" ]
kmmbvnr@gmail.com
7407c2e2b17c0229bc90b732819e8d9409972b16
8b6cd902deb20812fba07f1bd51a4460d22adc03
/.history/back-end/djreact/articles/api/urls_20191212170930.py
3e7b419002f664981ec5529074a7a5d3fed5aac1
[]
no_license
vishaldenzil/Django-react-
f3a49d141e0b6882685b7eaa4dc43c84857f335a
35b6d41f6dacb3bddcf7858aa4dc0d2fe039ff98
refs/heads/master
2022-11-08T09:27:02.938053
2020-05-29T04:53:52
2020-05-29T04:53:52
267,768,028
0
1
null
2022-10-15T14:08:30
2020-05-29T04:52:20
Python
UTF-8
Python
false
false
250
py
from django.urls import path from .views import ArticleDetailView,ArticleListView,ArticleCreateView urlpatterns = [ path('',ArticleListView.as_view()),\ path('<pk>',ArticleCreateView.as_view()) path('<pk>',ArticleDetailView.as_view()), ]
[ "vishal.denzil@ezedox.com" ]
vishal.denzil@ezedox.com
9d21e326eec729c6206b1528818da7493cf0a122
01fbe5abd060ecedda70c7ae5db928e2bc3371e2
/scripts/git-sync
12ace2c00429c60c12eba6750aa8f66539612904
[]
no_license
arecker/bastard
a3911c7c0abc53c4f254bb1c492fa0fccfad0283
2e3ab598022dba127503e4f55b43cb0e755c3cd2
refs/heads/master
2022-03-14T23:19:13.883117
2019-12-02T22:02:51
2019-12-02T22:02:51
198,136,763
0
0
null
null
null
null
UTF-8
Python
false
false
2,831
#!/usr/bin/env python import argparse import datetime import logging import os import sys def get_logger(verbose=False): if verbose: level = logging.DEBUG else: level = logging.INFO logger = logging.getLogger('git-sync') logger.setLevel(level) handler = logging.StreamHandler(sys.stdout) handler.setLevel(level) formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) return logger def get_args(): parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='store_true', help='print debug logs') parser.add_argument('-d', '--dir', '--directory', help='path to git repo') return parser.parse_args() class ShellCommandFailed(Exception): pass def shell(cmd, suppress=False): code = os.system(cmd) if not suppress and code != 0: raise ShellCommandFailed return code def main(): args = get_args() logger = get_logger(verbose=args.verbose) logger.debug('starting git-sync') logger.debug('validating git is installed') try: shell('which git') except ShellCommandFailed: logger.error('git is not installed!') sys.exit(1) path = os.path.abspath(args.dir) logger.debug('moving to %s', path) os.chdir(path) logger.info('checking for changes') if shell('git diff --exit-code', suppress=True) == 0: logger.info('no changes') logger.info('rebasing') try: shell('git fetch --all --prune >/dev/null') shell('git rebase origin/master >/dev/null') except ShellCommandFailed: logger.error('failed to rebase!') sys.exit(1) sys.exit(0) logger.info('adding modifications') try: shell('git add -A > /dev/null') except ShellCommandFailed: logger.error('failed to add modifications!') sys.exit(1) logger.info('writing commit') message = 'git-sync: {}'.format(datetime.datetime.now()) logger.debug('generated commit message: %s', message) try: shell('git commit -m "{}" > /dev/null'.format(message)) except ShellCommandFailed: logger.error('failed write commit modifications!') sys.exit(1) try: logger.info('pushing commit') shell('git push > /dev/null') except ShellCommandFailed: logger.info('failed to push, trying rebase') try: shell('git fetch --all --prune > /dev/null') shell('git rebase origin/master > /dev/null') shell('git push > /dev/null') except ShellCommandFailed: logger.error('failed to rebase + push!') sys.exit(1) logger.info('finished!') if __name__ == '__main__': main()
[ "alex@reckerfamily.com" ]
alex@reckerfamily.com
abddd850b8a545171a5c6c097c1615a2f5a038b0
62e58c051128baef9452e7e0eb0b5a83367add26
/x12/6040/107006040.py
a26c23e1f479d456f90f6ff07e4618f40f826786
[]
no_license
dougvanhorn/bots-grammars
2eb6c0a6b5231c14a6faf194b932aa614809076c
09db18d9d9bd9d92cefbf00f1c0de1c590fe3d0d
refs/heads/master
2021-05-16T12:55:58.022904
2019-05-17T15:22:23
2019-05-17T15:22:23
105,274,633
0
0
null
2017-09-29T13:21:21
2017-09-29T13:21:21
null
UTF-8
Python
false
false
2,065
py
from bots.botsconfig import * from records006040 import recorddefs syntax = { 'version': '00604', 'functionalgroup': 'MC', } structure = [ {ID: 'ST', MIN: 1, MAX: 1, LEVEL: [ {ID: 'BGN', MIN: 1, MAX: 1}, {ID: 'G62', MIN: 0, MAX: 10}, {ID: 'AT5', MIN: 0, MAX: 99}, {ID: 'PR', MIN: 0, MAX: 99}, {ID: 'ID4', MIN: 0, MAX: 1}, {ID: 'IV1', MIN: 0, MAX: 1}, {ID: 'MI1', MIN: 0, MAX: 1}, {ID: 'CUR', MIN: 0, MAX: 1}, {ID: 'MCT', MIN: 0, MAX: 999}, {ID: 'MS2', MIN: 0, MAX: 1, LEVEL: [ {ID: 'AT9', MIN: 0, MAX: 1}, ]}, {ID: 'N1', MIN: 1, MAX: 10, LEVEL: [ {ID: 'N2', MIN: 0, MAX: 1}, {ID: 'N3', MIN: 0, MAX: 2}, {ID: 'N4', MIN: 0, MAX: 1}, {ID: 'PER', MIN: 0, MAX: 5}, ]}, {ID: 'LX', MIN: 1, MAX: 99999, LEVEL: [ {ID: 'GY', MIN: 1, MAX: 999}, {ID: 'CUR', MIN: 0, MAX: 1}, {ID: 'PR', MIN: 0, MAX: 99}, {ID: 'ID4', MIN: 0, MAX: 1}, {ID: 'AT5', MIN: 0, MAX: 99}, {ID: 'MS2', MIN: 0, MAX: 1, LEVEL: [ {ID: 'AT9', MIN: 0, MAX: 1}, ]}, {ID: 'N1', MIN: 0, MAX: 1, LEVEL: [ {ID: 'N2', MIN: 0, MAX: 1}, {ID: 'N3', MIN: 0, MAX: 2}, {ID: 'N4', MIN: 0, MAX: 1}, {ID: 'G62', MIN: 0, MAX: 10}, ]}, {ID: 'CA1', MIN: 1, MAX: 99999, LEVEL: [ {ID: 'GY', MIN: 1, MAX: 999}, {ID: 'PR', MIN: 0, MAX: 99}, {ID: 'ID4', MIN: 0, MAX: 1}, {ID: 'IV1', MIN: 0, MAX: 1}, {ID: 'SV', MIN: 0, MAX: 1}, {ID: 'AT5', MIN: 0, MAX: 99}, {ID: 'MCT', MIN: 0, MAX: 999}, {ID: 'MS2', MIN: 0, MAX: 1, LEVEL: [ {ID: 'AT9', MIN: 0, MAX: 1}, ]}, {ID: 'N1', MIN: 0, MAX: 1, LEVEL: [ {ID: 'N2', MIN: 0, MAX: 1}, {ID: 'N3', MIN: 0, MAX: 2}, {ID: 'N4', MIN: 0, MAX: 1}, {ID: 'G62', MIN: 0, MAX: 10}, ]}, ]}, ]}, {ID: 'SE', MIN: 1, MAX: 1}, ]} ]
[ "doug.vanhorn@tagglogistics.com" ]
doug.vanhorn@tagglogistics.com
e2b7411a8ee36f2d8980496e3c37c414729356fb
74091dce735f281188d38d2f00d1a68e1d38ff7a
/network_programs/bridge_demo/bridge.py
9763824c4e75dcdb9d39fd950ea0f3be209e0614
[]
no_license
nbiadrytski-zz/python-training
96741aa0ef37bda32d049fde5938191025fe2924
559a64aae2db51e11812cea5ff602f25953e8070
refs/heads/master
2023-05-07T04:08:23.898161
2019-12-10T12:12:59
2019-12-10T12:12:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
137
py
import serial sr = serial.Serial('/dev/tty.usbserial-14200', 115200) sr.write(b'hello\n') sr.s print(sr.readline().decode('utf-8'))
[ "Mikalai_Biadrytski@epam.com" ]
Mikalai_Biadrytski@epam.com
0a07372dde34fc99c3a5e21470fc0c5ab2b738c3
43c96941aae099dd0d01120fd22abaccd6e55b21
/tests/test_instantiate.py
e3bd9a88fdd63583d743b475da8789f3560c831d
[ "BSD-3-Clause" ]
permissive
agoose77/widget-ts-cookiecutter
6ddba56c724d9dba6f0d667f23cdab84ed5f9faf
bd6825f02bfd5dc34965024d68dc3f69700863c4
refs/heads/master
2023-03-15T23:41:39.624795
2020-03-25T12:13:51
2020-03-25T12:13:51
258,137,524
0
0
BSD-3-Clause
2020-04-23T08:14:11
2020-04-23T08:14:10
null
UTF-8
Python
false
false
1,267
py
import os import sys import pytest HERE = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(HERE) pytest_plugins = "pytester" use_shell = os.name == 'nt' @pytest.fixture(scope='session') def example_instance(tmpdir_factory): from cookiecutter.main import cookiecutter import pip tmpdir = tmpdir_factory.mktemp('example_instance') with tmpdir.as_cwd(): cookiecutter(PROJECT_ROOT, no_input=True, config_file=os.path.join(HERE, 'testconfig.yaml')) instance_path = tmpdir.join('jupyter-widget-testwidgets') with instance_path.as_cwd(): print(str(instance_path)) try: pip.main(['install', '-v', '-e', '.[test]']) yield instance_path finally: try: pip.main(['uninstall', 'ipywidgettestwidgets', '-y']) except Exception: pass def test_python_tests(example_instance, testdir): with example_instance.as_cwd(): testdir.runpytest() def test_js_tests(example_instance): from subprocess import check_call cmd = ['npm', 'test'] with example_instance.as_cwd(): check_call(cmd, stdout=sys.stdout, stderr=sys.stderr, shell=use_shell)
[ "vidartf@gmail.com" ]
vidartf@gmail.com
8ab219fea28eb0c510914d55eb4b35a9627a217a
6234f8d6f22d73ae2759d1388e8de5e5761c16e6
/meshio/dolfin_io.py
686ee4d45bd9ae0e4a2720c40b9124d1501913b2
[ "MIT" ]
permissive
renanozelo/meshio
44f457cae3a86976629ee8606795b79a7fde649d
073b99b0315c326bee17527498494aa7941bbe9e
refs/heads/master
2021-01-13T14:54:31.092974
2016-12-06T19:36:06
2016-12-06T19:36:06
76,459,995
1
0
null
2016-12-14T13:01:04
2016-12-14T13:01:04
null
UTF-8
Python
false
false
4,338
py
# -*- coding: utf-8 -*- # ''' I/O for DOLFIN's XML format, cf. <https://people.sc.fsu.edu/~jburkardt/data/dolfin_xml/dolfin_xml.html>. .. moduleauthor:: Nico Schlömer <nico.schloemer@gmail.com> ''' import numpy import warnings def read(filename): from lxml import etree as ET tree = ET.parse(filename) root = tree.getroot() mesh = root.getchildren()[0] assert mesh.tag == 'mesh' dolfin_to_meshio_type = { 'triangle': ('triangle', 3), 'tetrahedron': ('tetra', 4), } cell_type, npc = dolfin_to_meshio_type[mesh.attrib['celltype']] is_2d = mesh.attrib['dim'] == '2' if not is_2d: assert mesh.attrib['dim'] == '3' points = None cells = { cell_type: None } for child in mesh.getchildren(): if child.tag == 'vertices': num_verts = int(child.attrib['size']) points = numpy.empty((num_verts, 3)) for vert in child.getchildren(): assert vert.tag == 'vertex' idx = int(vert.attrib['index']) points[idx, 0] = vert.attrib['x'] points[idx, 1] = vert.attrib['y'] if is_2d: points[idx, 2] = 0.0 else: points[idx, 2] = vert.attrib['z'] elif child.tag == 'cells': num_cells = int(child.attrib['size']) cells[cell_type] = numpy.empty((num_cells, npc), dtype=int) for cell in child.getchildren(): assert(dolfin_to_meshio_type[cell.tag][0] == cell_type) idx = int(cell.attrib['index']) for k in range(npc): cells[cell_type][idx, k] = cell.attrib['v%s' % k] else: raise RuntimeError('Unknown entry \'%s\'.' % child.tag) point_data = {} cell_data = {} field_data = {} return points, cells, point_data, cell_data, field_data def write( filename, points, cells, point_data=None, cell_data=None, field_data=None ): from lxml import etree as ET if point_data is None: point_data = {} if cell_data is None: cell_data = {} if field_data is None: field_data = {} dolfin = ET.Element( 'dolfin', nsmap={'dolfin': 'http://fenicsproject.org/'} ) meshio_to_dolfin_type = { 'triangle': 'triangle', 'tetra': 'tetrahedron', } if 'tetra' in cells: stripped_cells = {'tetra': cells['tetra']} cell_type = 'tetra' elif 'triangle' in cells: stripped_cells = {'triangle': cells['triangle']} cell_type = 'triangle' else: raise RuntimeError( 'Dolfin XML can only deal with triangle or tetra. ' 'The input data contains only ' + ', '.join(cells.keys()) + '.' ) if len(cells) > 1: discarded_cells = cells.keys() discarded_cells.remove(cell_type) warnings.warn( 'DOLFIN XML can only handle one cell type at a time. ' 'Using ' + cell_type + ', discarding ' + ', '.join(discarded_cells) + '.' ) if all(points[:, 2] == 0): dim = '2' else: dim = '3' mesh = ET.SubElement( dolfin, 'mesh', celltype=meshio_to_dolfin_type[cell_type], dim=dim ) vertices = ET.SubElement(mesh, 'vertices', size=str(len(points))) for k, point in enumerate(points): ET.SubElement( vertices, 'vertex', index=str(k), x=str(point[0]), y=str(point[1]), z=str(point[2]) ) num_cells = 0 for cls in stripped_cells.values(): num_cells += len(cls) xcells = ET.SubElement(mesh, 'cells', size=str(num_cells)) idx = 0 for cell_type, cls in stripped_cells.iteritems(): for cell in cls: cell_entry = ET.SubElement( xcells, meshio_to_dolfin_type[cell_type], index=str(idx) ) for k, c in enumerate(cell): cell_entry.attrib['v%d' % k] = str(c) idx += 1 tree = ET.ElementTree(dolfin) tree.write(filename, pretty_print=True) return
[ "nico.schloemer@gmail.com" ]
nico.schloemer@gmail.com
7fc2467f0250ee8322bbda3d68f914db118efa47
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02725/s138858472.py
cea9d71bc4a6904057ab3ad27c3bc17dd530ad24
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
442
py
# 改善1:sys入力 # 改善2:ifで分岐させるより、あとから個別対応した方が分岐を毎回やらないですむ? import sys input=sys.stdin.readline def main(): k,n = map(int, input().split()) s = list(map(int, input().split())) l = [] for i in range(1,n): a = s[i] - s[i-1] l.append(a) l.append(k - (s[-1] - s[0])) print(k - max(l)) if __name__ == '__main__': main()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
5bc3f4f8bb4647a25f30f51ce63937096d4246a1
784936ad8234b5c3c20311ce499551ee02a08879
/lab9/file/parse_file.py
cc36e2a591a78376ec7e3cffe6d4e0078c023d42
[]
no_license
jonlin97/CPE101
100ba6e5030364d4045f37e317aa05fd6a06cb08
985d64497a9861f59ab7473322b9089bfa57fd10
refs/heads/master
2021-06-16T01:31:31.025153
2017-02-28T19:29:11
2017-02-28T19:29:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,077
py
from sys import argv def main(): if len(argv) == 1 or len(argv) > 3: print 'Usage: [-s] file_name' exit() elif len(argv) == 3 and '-s' not in argv: print 'Usage: [-s] file_name' exit() else: if len(argv) == 2: file_name = argv[1] else: argv.pop(argv.index('-s')) file_name = argv[1] argv.append('-s') try: inFile = open(file_name, 'r') except IOError as e: print e exit() total = 0 ints = floats = other = 0 for line in inFile: the_line = line.split() for elem in the_line: try: temp = int(elem) ints += 1 total += temp except: try: temp = float(elem) floats += 1 total += temp except: other += 1 inFile.close() print 'Ints: %d' % ints print 'Floats: %d' % floats print 'Other: %d' % other if len(argv) == 3: print 'Sum: %.2f' % total if __name__ == '__main__': main()
[ "eitan.simler@gmail.com" ]
eitan.simler@gmail.com
cc187ad5d061659b1d141e6ae8c0c903749475b1
45de7d905486934629730945619f49281ad19359
/xlsxwriter/test/comparison/test_textbox11.py
ca80f1243f3d1dbb199c896488058878d7a21f2d
[ "BSD-2-Clause" ]
permissive
jmcnamara/XlsxWriter
599e1d225d698120ef931a776a9d93a6f60186ed
ab13807a1be68652ffc512ae6f5791d113b94ee1
refs/heads/main
2023-09-04T04:21:04.559742
2023-08-31T19:30:52
2023-08-31T19:30:52
7,433,211
3,251
712
BSD-2-Clause
2023-08-28T18:52:14
2013-01-04T01:07:06
Python
UTF-8
Python
false
false
857
py
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2023, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("textbox11.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_textbox("E9", "This is some text", {"fill": {"color": "red"}}) workbook.close() self.assertExcelEqual()
[ "jmcnamara@cpan.org" ]
jmcnamara@cpan.org
9411320ce5f493de2d42d37e564a2e9624a820f8
97884252481ff208519194ecd63dc3a79c250220
/pyobs/events/newspectrum.py
bb03c0263c82eddeafae717430787cfbb9842aa4
[ "MIT" ]
permissive
pyobs/pyobs-core
a1f30137d7f991bad4e115de38f543e59a6e30d2
2d7a06e5485b61b6ca7e51d99b08651ea6021086
refs/heads/master
2023-09-01T20:49:07.610730
2023-08-29T09:20:05
2023-08-29T09:20:05
174,351,157
9
3
NOASSERTION
2023-09-14T20:39:48
2019-03-07T13:41:27
Python
UTF-8
Python
false
false
1,003
py
from __future__ import annotations from typing import Dict, Any from typing_extensions import TypedDict from pyobs.events.event import Event DataType = TypedDict("DataType", {"filename": str}) class NewSpectrumEvent(Event): """Event to be sent on a new image.""" __module__ = "pyobs.events" def __init__(self, filename: str, **kwargs: Any): """Initializes new NewSpectrumEvent. Args: filename: Name of new image file. """ Event.__init__(self) self.data: DataType = {"filename": filename} @classmethod def from_dict(cls, d: Dict[str, Any]) -> Event: # get filename if "filename" not in d or not isinstance(d["filename"], str): raise ValueError("Invalid type for filename.") filename: str = d["filename"] # return object return NewSpectrumEvent(filename) @property def filename(self) -> str: return self.data["filename"] __all__ = ["NewSpectrumEvent"]
[ "thusser@uni-goettingen.de" ]
thusser@uni-goettingen.de
854ae9710abde0ac2c9a66fa74291936c78a3839
503e97b5c0bb77e923fe135ff14a8b5ca5e6ba07
/mxshop/mxshop/settings.py
14c8a2c9bfd1e2ae8fcb833563b71aac4cf284a3
[]
no_license
pshyms/dianshang-1
72345de3ce769efeb2b17c975b586590524dcdbe
788b7950f52cb7979a8b73e5d9193243f2e69cad
refs/heads/master
2021-05-21T10:11:38.248170
2020-04-03T06:25:13
2020-04-03T06:25:13
252,649,823
0
0
null
null
null
null
UTF-8
Python
false
false
3,483
py
""" Django settings for mxshop project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import sys # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, BASE_DIR) sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'u(txeme@dat=dxizn0@rrm7k85(#ce+9m3up7u!v6!djs#6i3y' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] AUTH_USER_MODEL = "users.UserProfile" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'goods', 'trade', 'user_operation', 'DjangoUeditor', ] 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 = 'mxshop.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'mxshop.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'vue_shop', 'USER': 'root', 'PASSWORD': '123456', 'HOST': '127.0.0.1', "OPTIONS": {"init_command": "SET default_storage_engine=INNODB;"} } } # Password validation # https://docs.djangoproject.com/en/2.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/2.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/2.2/howto/static-files/ STATIC_URL = '/static/'
[ "1816635208@qq.com" ]
1816635208@qq.com
f3dd845a32db99083ff44cd824500f31f1ae9c52
4d4d05bb396e19e32e1ecbba1e2bd20c52d5d22e
/backend/mobile_testing_12_d_14208/wsgi.py
2897d07e06cc71965e9451a659567a8368ba3255
[]
no_license
crowdbotics-apps/mobile-testing-12-d-14208
c78e93a4b214901383bf803d12dbf70573536b87
9dacf9161fbd7912f57a07e47c017b1ac4b52f5b
refs/heads/master
2023-01-02T20:56:47.081621
2020-10-29T15:34:50
2020-10-29T15:34:50
308,371,847
0
0
null
null
null
null
UTF-8
Python
false
false
427
py
""" WSGI config for mobile_testing_12_d_14208 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mobile_testing_12_d_14208.settings') application = get_wsgi_application()
[ "team@crowdbotics.com" ]
team@crowdbotics.com
af19b5a06d215882024497e34544be63114c99d3
4d64248b2d7fed5fc61afb93717f6da9d77bb78e
/test/integration/test_main.py
d29c6c5b74ebd22411d73ba02378a9073d052370
[ "Apache-2.0" ]
permissive
aniltimilsina/ansible-runner
eab0e40b2e2f1f9db202d9bc532abe92b5439f6e
dd6dbdf137e91adaabff3a1bb602615e174c0f73
refs/heads/master
2020-03-31T01:37:39.924968
2018-09-28T14:22:50
2018-09-28T14:22:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,312
py
from __future__ import print_function from ansible_runner.__main__ import main import os import multiprocessing import shutil import yaml import tempfile import time from contextlib import contextmanager from pytest import raises from ansible_runner.exceptions import AnsibleRunnerException HERE = os.path.abspath(os.path.dirname(__file__)) def ensure_directory(directory): if not os.path.exists(directory): os.makedirs(directory) def ensure_removed(file_path): if os.path.exists(file_path): os.unlink(file_path) @contextmanager def temp_directory(files=None): temp_dir = tempfile.mkdtemp() try: yield temp_dir shutil.rmtree(temp_dir) except BaseException: print(temp_dir) if files is not None: for file in files: if os.path.exists(file): with open(file) as f: print(f.read()) raise def test_temp_directory(): context = dict() def will_fail(): with temp_directory() as temp_dir: context['saved_temp_dir'] = temp_dir assert False def will_pass(): with temp_directory() as temp_dir: context['saved_temp_dir'] = temp_dir assert True with raises(AssertionError): will_fail() assert os.path.exists(context['saved_temp_dir']) shutil.rmtree(context['saved_temp_dir']) will_pass() assert not os.path.exists(context['saved_temp_dir']) def test_help(): with raises(SystemExit) as exc: main([]) assert exc.value.code == 2, 'Should raise SystemExit with return code 2' def test_module_run(): main(['-m', 'ping', '--hosts', 'localhost', 'run', 'ping']) def test_module_run_clean(): with temp_directory() as temp_dir: main(['-m', 'ping', '--hosts', 'localhost', 'run', temp_dir]) def test_role_run(): with temp_directory() as temp_dir: main(['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', 'run', temp_dir]) def test_role_logfile(): with temp_directory() as temp_dir: main(['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', '--logfile', 'new_logfile', 'run', temp_dir]) def test_role_bad_project_dir(): with open("bad_project_dir", 'w') as f: f.write('not a directory') try: with raises(OSError): main(['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', '--logfile', 'new_logfile', 'run', 'bad_project_dir']) finally: os.unlink('bad_project_dir') def test_role_run_clean(): with temp_directory() as temp_dir: main(['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', 'run', temp_dir]) def test_role_run_cmd_line(): with temp_directory() as temp_dir: main(['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', '--cmdline', 'msg=hi', 'run', temp_dir]) def test_role_run_artifacts_dir(): with temp_directory() as temp_dir: main(['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', '--artifact-dir', 'otherartifacts', 'run', temp_dir]) def test_role_run_env_vars(): with temp_directory() as temp_dir: ensure_directory(os.path.join(temp_dir, 'env')) with open(os.path.join(temp_dir, 'env/envvars'), 'w') as f: f.write(yaml.dump(dict(msg='hi'))) main(['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', 'run', temp_dir]) def test_role_run_args(): with temp_directory() as temp_dir: main(['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', '--role-vars', 'msg=hi', 'run', temp_dir]) def test_role_run_inventory(): with temp_directory() as temp_dir: ensure_directory(os.path.join(temp_dir, 'inventory')) shutil.copy(os.path.join(HERE, 'inventories/localhost'), os.path.join(temp_dir, 'inventory/localhost')) main(['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', '--inventory', 'localhost', 'run', temp_dir]) def test_role_run_inventory_missing(): with temp_directory() as temp_dir: ensure_directory(os.path.join(temp_dir, 'inventory')) shutil.copy(os.path.join(HERE, 'inventories/localhost'), os.path.join(temp_dir, 'inventory/localhost')) with raises(AnsibleRunnerException): main(['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', '--inventory', 'does_not_exist', 'run', temp_dir]) def test_role_start(): with temp_directory() as temp_dir: p = multiprocessing.Process(target=main, args=[['-r', 'benthomasson.hello_role', '--hosts', 'localhost', '--roles-path', 'test/integration/roles', 'start', temp_dir]]) p.start() p.join() def test_playbook_start(): with temp_directory() as temp_dir: project_dir = os.path.join(temp_dir, 'project') ensure_directory(project_dir) shutil.copy(os.path.join(HERE, 'playbooks/hello.yml'), project_dir) ensure_directory(os.path.join(temp_dir, 'inventory')) shutil.copy(os.path.join(HERE, 'inventories/localhost'), os.path.join(temp_dir, 'inventory/localhost')) p = multiprocessing.Process(target=main, args=[['-p', 'hello.yml', '--inventory', os.path.join(HERE, 'inventories/localhost'), '--hosts', 'localhost', 'start', temp_dir]]) p.start() time.sleep(5) assert os.path.exists(os.path.join(temp_dir, 'pid')) rc = main(['is-alive', temp_dir]) assert rc == 0 rc = main(['stop', temp_dir]) assert rc == 0 time.sleep(1) rc = main(['is-alive', temp_dir]) assert rc == 1 ensure_removed(os.path.join(temp_dir, 'pid')) rc = main(['stop', temp_dir]) assert rc == 1
[ "bthomass@redhat.com" ]
bthomass@redhat.com
61bce7c35d257868765417a85473fa98fae8ce2f
75a35cefa5adf2f42503eb0cc8c60f7f96ff9650
/economico/migrations/0003_auto_20210624_1236.py
49bc13dc659775704cd8f50eb92f82ef53321af2
[]
no_license
PatacaSis/agroweb
5c70f35001d0e88fb5f1642161d4eee6b4abda59
e2181fa0bb6ca7752bdbaab62fe60ede9f2630b2
refs/heads/main
2023-06-20T23:37:50.294745
2021-07-19T23:26:55
2021-07-19T23:26:55
381,737,279
0
0
null
null
null
null
UTF-8
Python
false
false
1,984
py
# Generated by Django 2.2 on 2021-06-24 15:36 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('economico', '0002_auto_20210624_1117'), ] operations = [ migrations.CreateModel( name='Subrubro', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=100, verbose_name='Rubro')), ], options={ 'verbose_name': 'Subrubro', 'verbose_name_plural': 'Sububros', 'ordering': ['nombre'], }, ), migrations.AlterModelOptions( name='rubro', options={'ordering': ['nombre'], 'verbose_name': 'Rubro', 'verbose_name_plural': 'Rubros'}, ), migrations.CreateModel( name='Gasto', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fecha', models.DateField()), ('comprobante', models.CharField(max_length=10)), ('concepto', models.CharField(max_length=150)), ('cantidad', models.IntegerField()), ('unidades', models.CharField(max_length=10)), ('importe', models.IntegerField()), ('iva', models.IntegerField()), ('rubro', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rubros', to='economico.Rubro')), ('subrubro', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='subrubros', to='economico.Subrubro')), ], options={ 'verbose_name': 'Gasto', 'verbose_name_plural': 'Gastos', 'ordering': ['fecha'], }, ), ]
[ "patacasis@gmail.com" ]
patacasis@gmail.com
0fa8189b6205033ea38a4baca5d931a95dd69480
6203b9132af8f78c6cb12242bd223fa17d14f31e
/leetcode/hot100/739.py
4a83290d96acb97e8294d1fcc0c49ad525e00df8
[]
no_license
joshuap233/algorithms
82c608d7493b0d21989b287a2e246ef739e60443
dc68b883362f3ddcfb433d3d83d1bbf925bbcf02
refs/heads/master
2023-08-23T12:44:42.675137
2021-09-28T02:37:01
2021-09-28T02:37:01
230,285,450
1
0
null
null
null
null
UTF-8
Python
false
false
689
py
# https://leetcode-cn.com/problems/daily-temperatures/ # 739. 每日温度 from typing import List from collections import deque class Solution: """ 从左向右遍历 维护一个单调栈,如果当前元素 <= 栈顶元素, 当前元素入栈 否则栈顶元素出栈,直到当前元素为最小元素 """ def dailyTemperatures(self, temperatures: List[int]) -> List[int]: stack = deque() res = [0] * len(temperatures) for i, t in enumerate(temperatures): while stack and temperatures[stack[-1]] < t: e = stack.pop() res[e] = i - e stack.append(i) return res
[ "shushugo233@gmail.com" ]
shushugo233@gmail.com
d219b210b9aea9a439ac50e2a4a42aed1ea38432
37dd9a4970ef0c69868809cd1f09bb9bf137187a
/tests/cupy_tests/core_tests/test_ndarray_scatter.py
26b568f3b49a1944ebbef7aa07ef03a659b8a08c
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
minus9d/chainer
3d7549135a85926a528e7167e37947735dd096d7
f34c20e45dc86dfa6bbc62e080be3fd97aa3f466
refs/heads/master
2021-01-11T22:17:47.567101
2017-01-13T03:49:34
2017-01-13T03:49:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,537
py
import unittest import numpy import cupy from cupy import testing @testing.parameterize( # array only {'shape': (2, 3, 4), 'slices': numpy.array(-1), 'value': 1}, {'shape': (2, 3, 4), 'slices': numpy.array([1, 0]), 'value': 1}, {'shape': (2, 3, 4), 'slices': (slice(None), [1, 2]), 'value': 1}, {'shape': (3, 4, 5), 'slices': (slice(None), [[1, 2], [0, -1]],), 'value': 1}, {'shape': (3, 4, 5), 'slices': (slice(None), slice(None), [[1, 2], [0, 3]]), 'value': 1}, # slice and array {'shape': (3, 4, 5), 'slices': (slice(None), slice(1, 2), [[1, 3], [0, 2]]), 'value': 1}, # None and array {'shape': (3, 4, 5), 'slices': (None, [1, -1]), 'value': 1}, {'shape': (3, 4, 5), 'slices': (None, [1, -1], None), 'value': 1}, {'shape': (3, 4, 5), 'slices': (None, None, None, [1, -1]), 'value': 1}, # None, slice and array {'shape': (3, 4, 5), 'slices': (slice(0, 1), None, [1, -1]), 'value': 1}, {'shape': (3, 4, 5), 'slices': (slice(0, 1), slice(1, 2), [1, -1]), 'value': 1}, {'shape': (3, 4, 5), 'slices': (slice(0, 1), None, slice(1, 2), [1, -1]), 'value': 1}, # broadcasting {'shape': (3, 4, 5), 'slices': (slice(None), [[1, 2], [0, -1]],), 'value': numpy.arange(3 * 2 * 2 * 5).reshape(3, 2, 2, 5)}, ) @testing.gpu class TestScatterAddNoDuplicate(unittest.TestCase): @testing.for_dtypes([numpy.float32, numpy.int32]) @testing.numpy_cupy_array_equal() def test_scatter_add(self, xp, dtype): a = xp.zeros(self.shape, dtype) if xp is cupy: a.scatter_add(self.slices, self.value) else: a[self.slices] = a[self.slices] + self.value return a @testing.parameterize( {'shape': (2, 3), 'slices': ([1, 1], slice(None)), 'value': 1, 'expected': numpy.array([[0, 0, 0], [2, 2, 2]])}, {'shape': (2, 3), 'slices': ([1, 0, 1], slice(None)), 'value': 1, 'expected': numpy.array([[1, 1, 1], [2, 2, 2]])}, {'shape': (2, 3), 'slices': (slice(1, 2), [1, 0, 1]), 'value': 1, 'expected': numpy.array([[0, 0, 0], [1, 2, 0]])}, ) @testing.gpu class TestScatterAddDuplicateVectorValue(unittest.TestCase): @testing.for_dtypes([numpy.float32, numpy.int32]) def test_scatter_add(self, dtype): a = cupy.zeros(self.shape, dtype) a.scatter_add(self.slices, self.value) numpy.testing.assert_almost_equal(a.get(), self.expected) @testing.gpu class TestScatterAdd(unittest.TestCase): @testing.for_dtypes([numpy.float32, numpy.int32]) def test_scatter_add_cupy_arguments(self, dtype): shape = (2, 3) a = cupy.zeros(shape, dtype) slices = (cupy.array([1, 1]), slice(None)) a.scatter_add(slices, cupy.array(1.)) testing.assert_array_equal( a, cupy.array([[0., 0., 0.], [2., 2., 2.]], dtype)) @testing.for_dtypes( [numpy.float32, numpy.int32, numpy.uint32, numpy.uint64, numpy.ulonglong], name='src_dtype') @testing.for_dtypes( [numpy.float32, numpy.int32, numpy.uint32, numpy.uint64, numpy.ulonglong], name='dst_dtype') def test_scatter_add_differnt_dtypes(self, src_dtype, dst_dtype): shape = (2, 3) a = cupy.zeros(shape, dtype=src_dtype) value = cupy.array(1, dtype=dst_dtype) slices = ([1, 1], slice(None)) a.scatter_add(slices, value) numpy.testing.assert_almost_equal( a.get(), numpy.array([[0, 0, 0], [2, 2, 2]], dtype=src_dtype))
[ "yuyuniitani@gmail.com" ]
yuyuniitani@gmail.com
79f035817224a222421136ec0202b67a832a3d4d
4e30d990963870478ed248567e432795f519e1cc
/tests/models/validators/v3_1_patch_1/jsd_bea2910401185295a9715d65cb1c07c9.py
4c20015d51ab24952aff9a591ff4fba674cede0d
[ "MIT" ]
permissive
CiscoISE/ciscoisesdk
84074a57bf1042a735e3fc6eb7876555150d2b51
f468c54998ec1ad85435ea28988922f0573bfee8
refs/heads/main
2023-09-04T23:56:32.232035
2023-08-25T17:31:49
2023-08-25T17:31:49
365,359,531
48
9
MIT
2023-08-25T17:31:51
2021-05-07T21:43:52
Python
UTF-8
Python
false
false
8,098
py
# -*- coding: utf-8 -*- """Identity Services Engine updateNetworkAccessConditionByName data model. Copyright (c) 2021 Cisco and/or its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import, division, print_function, unicode_literals import json from builtins import * import fastjsonschema from ciscoisesdk.exceptions import MalformedRequest class JSONSchemaValidatorBea2910401185295A9715D65Cb1C07C9(object): """updateNetworkAccessConditionByName request schema definition.""" def __init__(self): super(JSONSchemaValidatorBea2910401185295A9715D65Cb1C07C9, self).__init__() self._validator = fastjsonschema.compile(json.loads( '''{ "$schema": "http://json-schema.org/draft-04/schema#", "properties": { "response": { "properties": { "attributeName": { "type": "string" }, "attributeValue": { "type": "string" }, "children": { "items": { "properties": { "conditionType": { "enum": [ "ConditionAndBlock", "ConditionAttributes", "ConditionOrBlock", "ConditionReference", "LibraryConditionAndBlock", "LibraryConditionAttributes", "LibraryConditionOrBlock", "TimeAndDateCondition" ], "type": "string" }, "isNegate": { "type": "boolean" }, "link": { "properties": { "href": { "type": "string" }, "rel": { "enum": [ "next", "previous", "self", "status" ], "type": "string" }, "type": { "type": "string" } }, "type": "object" } }, "type": "object" }, "type": "array" }, "conditionType": { "enum": [ "ConditionAndBlock", "ConditionAttributes", "ConditionOrBlock", "ConditionReference", "LibraryConditionAndBlock", "LibraryConditionAttributes", "LibraryConditionOrBlock", "TimeAndDateCondition" ], "type": "string" }, "datesRange": { "properties": { "endDate": { "type": "string" }, "startDate": { "type": "string" } }, "type": "object" }, "datesRangeException": { "properties": { "endDate": { "type": "string" }, "startDate": { "type": "string" } }, "type": "object" }, "description": { "type": "string" }, "dictionaryName": { "type": "string" }, "dictionaryValue": { "type": "string" }, "hoursRange": { "properties": { "endTime": { "type": "string" }, "startTime": { "type": "string" } }, "type": "object" }, "hoursRangeException": { "properties": { "endTime": { "type": "string" }, "startTime": { "type": "string" } }, "type": "object" }, "id": { "type": "string" }, "isNegate": { "type": "boolean" }, "link": { "properties": { "href": { "type": "string" }, "rel": { "enum": [ "next", "previous", "self", "status" ], "type": "string" }, "type": { "type": "string" } }, "type": "object" }, "name": { "type": "string" }, "operator": { "enum": [ "contains", "endsWith", "equals", "greaterOrEquals", "greaterThan", "in", "ipEquals", "ipGreaterThan", "ipLessThan", "ipNotEquals", "lessOrEquals", "lessThan", "matches", "notContains", "notEndsWith", "notEquals", "notIn", "notStartsWith", "startsWith" ], "type": "string" }, "weekDays": { "items": { "enum": [ "Friday", "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday" ], "type": "string" }, "type": "array" }, "weekDaysException": { "items": { "enum": [ "Friday", "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday" ], "type": "string" }, "type": "array" } }, "type": "object" }, "version": { "type": "string" } }, "required": [ "response", "version" ], "type": "object" }'''.replace("\n" + ' ' * 16, '') )) def validate(self, request): try: self._validator(request) except fastjsonschema.exceptions.JsonSchemaException as e: raise MalformedRequest( '{} is invalid. Reason: {}'.format(request, e.message) )
[ "bvargas@altus.cr" ]
bvargas@altus.cr
45a1448d0fb517a8f6109c50acd0d444b35696a9
09301c71638abf45230192e62503f79a52e0bd80
/besco_erp/besco_account/general_account_asset/wizard/wizard_asset_compute.py
2159e39e0228453a5ac13d57989d9b0e66b11412
[]
no_license
westlyou/NEDCOFFEE
24ef8c46f74a129059622f126401366497ba72a6
4079ab7312428c0eb12015e543605eac0bd3976f
refs/heads/master
2020-05-27T06:01:15.188827
2017-11-14T15:35:22
2017-11-14T15:35:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,916
py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from osv import osv, fields from tools.translate import _ DATETIME_FORMAT = "%Y-%m-%d" DATE_FORMAT = "%Y-%m-%d" import time from datetime import datetime class asset_depreciation_confirmation_wizard(osv.osv_memory): _inherit = "asset.depreciation.confirmation.wizard" _columns = { 'date': fields.date('Date',required=True), 'period_id': fields.many2one('account.period', 'Period', required=True, domain=[('state','=','draft')], help="Choose the period for which you want to automatically post the depreciation lines of running assets") } def default_get(self, cr, uid, fields, context=None): res = {} period_obj = self.pool.get('account.period') depreciation_obj = self.pool.get('account.asset.depreciation.line') if 'active_ids' in context and context['active_ids']: depreciation_ids = depreciation_obj.browse(cr,uid,context['active_ids'][0]) if depreciation_ids: res.update({'date':depreciation_ids.depreciation_date}) return res def onchange_date(self,cr,uid,ids,date,period_id): value ={} warning ={} period_id_after = False period_ids = self.pool.get('account.period').search(cr,uid,[('date_start','<=',date),('date_stop','>=',date),('state','=','draft')]) if period_ids: period_id_after = self.pool.get('account.period').browse(cr,uid,period_ids[0]) if period_id_after: value.update({'period_id':period_id_after.id}) else: value.update({'date':False}) warning = { 'title': _('Period Warning!'), 'message' : _('You must open Period') } return {'value': value, 'warning': warning} def asset_compute(self, cr, uid, ids, context): ass_obj = self.pool.get('account.asset.asset') period_obj = self.pool.get('account.period') asset_ids = ass_obj.search(cr, uid, [('state','=','open')], context=context) data = self.browse(cr, uid, ids, context=context) period_id = data[0].period_id.id period = period_obj.browse(cr, uid, period_id, context=context) date = data and data[0].date if period: if (date >= period.date_start and date <= period.date_stop)==False: raise osv.except_osv(_('Error !'), _('You must choose date between start_date and end_date in period')) # sql =''' # select '%s' between '%s' and '%s' condition # ''' %(date,period.date_start,period.date_stop) # cr.execute(sql) # res = cr.dictfetchone() # if res['condition'] == False: # raise osv.except_osv(_('Error !'), _('You must choose date between start_date and end_date in period')) # date_now = time.strftime(DATE_FORMAT) # date_now = datetime.strptime(date_now, DATE_FORMAT) # month_now = int(date_now.strftime('%m')) # year_now = int(date_now.strftime('%Y')) # # date_compare = datetime.strptime(date, DATE_FORMAT) # month_compare = int(date_compare.strftime('%m')) # year_compare = int(date_compare.strftime('%Y')) # # if (month_now >= month_compare and year_now >= year_compare)==False: # raise osv.except_osv(_('Error !'), _('Period must smaller Current Date')) # sql =''' # select '%s' >= '%s' and '%s' >= '%s' condition # ''' %(month_now,month_compare,year_now,year_compare) # cr.execute(sql) # res = cr.dictfetchone() # if res['condition'] == False: # context.update({'date':date}) if 'asset_type' in context and context['asset_type'] == 'create_move': active_ids = context.get('active_ids') depreciation_obj = self.pool.get('account.asset.depreciation.line') depreciation_ids = depreciation_obj.search(cr, uid, [('id', 'in', active_ids), ('depreciation_date', '<=', period.date_stop), ('depreciation_date', '>=', period.date_start), ('move_check', '=', False)], context=context) created_move_ids = self.pool.get('account.asset.depreciation.line').create_move(cr,uid,depreciation_ids,context) else: created_move_ids = ass_obj._compute_entries(cr, uid, asset_ids, period_id, context=context) return { 'name': _('Created Asset Moves'), 'view_type': 'form', 'view_mode': 'tree,form', 'res_model': 'account.move', 'view_id': False, 'domain': "[('id','in',["+','.join(map(str,created_move_ids))+"])]", 'type': 'ir.actions.act_window', } asset_depreciation_confirmation_wizard() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
[ "son.huynh@nedcoffee.vn" ]
son.huynh@nedcoffee.vn
e8fe137014c1db7c346768859e5a1022752e8930
231ced7456347d52fdcd126cfc6427bef47843d3
/spj/timc.py
1b9cec7e3976f743b8bc8040989f2d874b006b54
[]
no_license
overminder/SPJ-D.Lester-book-Reading
d6590590d39d0e41ba23b77aecd448ed9888203b
8a80f4100cdb32c73acf0c14ffdee5f72a8b7288
refs/heads/master
2016-09-05T23:37:40.028269
2012-12-04T14:25:32
2012-12-04T14:25:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,401
py
from spj.errors import InterpError from spj.language import W_Root, W_EAp, W_EInt, W_EVar, W_ELet, ppr from spj.timrun import (State, Take, Enter, Return, PushInt, PushLabel, PushArg, PushCode, PushVInt, Move, Cond, Closure) from spj.primitive import module def compile(prog): cc = ProgramCompiler() cc.compile_program(prog) ppr(cc) initcode = [PushLabel('main'), Enter()] initstack = [Closure('<init>', [], None)] return State(initcode, None, initstack, cc.globalenv, cc.codefrags) class ProgramCompiler(W_Root): def __init__(self): self.codefrags = module.codefrags[:] self.globalenv = module.scs.copy() def ppr(self, p): p.writeln('<ProgCompiler>') with p.block(2): p.writeln('Supercombinators:') p.write_dict(self.globalenv.items()) p.newline(2) p.writeln('Anonymous codes:') for i, code in enumerate(self.codefrags): p.write('%d:' % i) p.writeln(code) p.writeln('') def compile_program(self, prog): for sc in prog: cc = Compiler(self, sc.name, framesize=sc.arity) cc.compile_sc(sc) self.globalenv[sc.name] = cc.code def add_code(self, code): i = len(self.codefrags) self.codefrags.append(code) return i class Compiler(object): def __init__(self, progcc, name='?', initcode=None, framesize=0): self.progcc = progcc self.name = name if initcode is None: self.code = [] else: self.code = initcode self.framesize = framesize def emit(self, instr): self.code.append(instr) def emit_move(self, addr_mode): if isinstance(addr_mode, Arg): self.emit(Move(addr_mode.ival)) elif isinstance(addr_mode, IndirectArg): self.emit(Move(addr_mode.ival)) else: assert 0 def emit_push(self, addr_mode): if isinstance(addr_mode, Arg): self.emit(PushArg(addr_mode.ival)) elif isinstance(addr_mode, IndirectArg): co = [PushArg(addr_mode.ival), Enter()] self.emit(PushCode(self.progcc.add_code(co))) elif isinstance(addr_mode, Label): self.emit(PushLabel(addr_mode.name)) else: assert 0 def compile_sc(self, sc): local_env = mk_func_env(sc.args) self.compile_r(sc.body, local_env) self.code = [Take(self.framesize, sc.arity)] + self.code # Compile apply e to args (sort of like unwind) def compile_r(self, expr, env): # First try to compile as arith if self.compile_b(expr, env, [Return()]): return if isinstance(expr, W_EAp): self.compile_a(expr.a, env) self.compile_r(expr.f, env) elif isinstance(expr, W_EInt) or isinstance(expr, W_EVar): self.compile_a(expr, env) self.emit(Enter()) elif isinstance(expr, W_ELet): new_env = env.copy() if expr.isrec: rec_env = new_env.copy() for i, (name, e) in enumerate(expr.defns): frameslot = self.framesize self.framesize += 1 new_env[name] = Arg(frameslot) rec_env[name] = IndirectArg(frameslot) for i, (name, e) in enumerate(expr.defns): self.compile_a(e, rec_env) self.emit_move(new_env[name]) else: for i, (name, e) in enumerate(expr.defns): self.compile_a(e, env) frameslot = self.framesize self.framesize += 1 new_env[name] = Arg(frameslot) self.emit_move(new_env[name]) self.compile_r(expr.expr, new_env) else: raise InterpError('compile_r(%s): not implemented' % expr.to_s()) # Compile atomic expression (addressing mode?) def compile_a(self, expr, env): if isinstance(expr, W_EInt): self.emit(PushInt(expr.ival)) elif isinstance(expr, W_EVar): if expr.name in env: self.emit_push(env[expr.name]) else: self.emit_push(Label(expr.name)) elif isinstance(expr, W_EAp): # Create a shared closure cc = Compiler(self.progcc, expr.to_s()) cc.compile_r(expr, env) fragindex = self.progcc.add_code(cc.code) self.emit(PushCode(fragindex)) else: raise InterpError('compile_a(%s): not implemented' % expr.to_s()) # eval <expr> inline, push the result then jump to <cont> # Return True if <expr> is successfully compiled inlined, False otherwise def compile_b(self, expr, env, cont, use_fallback=False): if isinstance(expr, W_EAp): revargs = [] # [argn, ..., arg1] iterexpr = expr while isinstance(iterexpr, W_EAp): revargs.append(iterexpr.a) iterexpr = iterexpr.f func = iterexpr if (isinstance(func, W_EVar) and func.name in module.ops and len(revargs) == module.ops[func.name].get_arity()): cont = [module.ops[func.name]] + cont # We can just inline the arith for i in xrange(len(revargs) - 1, -1, -1): arg = revargs[i] cc = Compiler(self.progcc, '<cont for %s>' % func.name) cc.compile_b(arg, env, cont, use_fallback=True) cont = cc.code for instr in cont: self.emit(instr) return True elif (isinstance(func, W_EVar) and func.name == 'if' and len(revargs) == 3): condexpr = revargs[2] trueexpr = revargs[1] falseexpr = revargs[0] cc1 = Compiler(self.progcc, '<cont for true>') cc1.compile_r(trueexpr, env) truecode = cc1.code truefrag = self.progcc.add_code(truecode) cc2 = Compiler(self.progcc, '<cont for false>') cc2.compile_r(falseexpr, env) falsecode = cc2.code falsefrag = self.progcc.add_code(falsecode) newcont = [Cond(truefrag, falsefrag)] + cont self.compile_b(condexpr, env, newcont) return True elif isinstance(expr, W_EInt): self.emit(PushVInt(expr.ival)) for instr in cont: self.emit(instr) return True # Otherwise if use_fallback: i = self.progcc.add_code(cont) self.emit(PushCode(i)) self.compile_r(expr, env) return False class AddressMode(object): pass class Arg(AddressMode): def __init__(self, ival): self.ival = ival class IndirectArg(AddressMode): def __init__(self, ival): self.ival = ival class Label(AddressMode): def __init__(self, name): self.name = name def mk_func_env(args): d = {} for i, name in enumerate(args): d[name] = Arg(i) return d
[ "p90eri@gmail.com" ]
p90eri@gmail.com
a26a366b10cc223f2342920a7884674cb453093c
be50b4dd0b5b8c3813b8c3158332b1154fe8fe62
/Strings/Python/ConvertToPalindrome.py
46439cae661b90bd3d651d5ecdbabb178e6a9e66
[]
no_license
Zimmermann25/InterviewBit
a8d89e090068d9644e28085625963c8ce75d3dff
6d2138e740bd5ba8eab992d9bf090977e077bfc5
refs/heads/main
2023-03-24T18:12:48.244950
2021-03-24T14:36:48
2021-03-24T14:36:48
350,835,917
0
0
null
null
null
null
UTF-8
Python
false
false
1,093
py
class Solution: # @param A : string # @return an integer def solve(self, A): '''while(i<j){ if(count>1) return 0; if(A[i]==A[j]) i++,j--; else if(A[i]!=A[j] && A[i+1]==A[j]) i++,count++; else if(A[i]!=A[j] && A[i]==A[j-1]) j--,count++; else return 0; } if(i==j && count>1) return 0; return 1;''' if len(A) < 1:return 0 # jak wchodzi parzysta dlugosc, usuwam 1 znak, bedzie nieparzysta left = 0 right = len(A)-1 used = 0 while left < right: if A[left] == A[right]: right -=1 left +=1 elif A[left+1] == A[right]: used +=1 left +=1 elif A[left] == A[right-1]: right -=1 used +=1 else: # jeśli trzeba by bylo minimum 2 zmienić return 0 if used > 1: return 0 return 1
[ "noreply@github.com" ]
Zimmermann25.noreply@github.com
6b06a0acefe3c3545167fd5f57a55c8c71e71347
fa60536fbc7c0d8a2a8f08f0a5b6351c77d08054
/3]. Competitive Programming/03]. HackerRank/1]. Practice/08]. Problem Solving/Algorithms/02]. Implementation/Python/_63) Sequence Equation.py
b4f4bb8ecf6be9a2c2c62234e16e5f5721b99482
[ "MIT" ]
permissive
poojitha2002/The-Complete-FAANG-Preparation
15cad1f9fb0371d15acc0fb541a79593e0605c4c
7910c846252d3f1a66f92af3b7d9fb9ad1f86999
refs/heads/master
2023-07-17T20:24:19.161348
2021-08-28T11:39:48
2021-08-28T11:39:48
400,784,346
5
2
MIT
2021-08-28T12:14:35
2021-08-28T12:14:34
null
UTF-8
Python
false
false
191
py
# Contributed by Paraj Shah # https://github.com/parajshah n = int(input().strip()) p = list(map(int,input().strip().split(' '))) for i in range(n): print(p.index(p.index(i+1)+1)+1)
[ "parajshah2000@gmail.com" ]
parajshah2000@gmail.com
89ce91e9cdd45bcea7cda1f6618b0a8911d4b680
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_97/1400.py
447598b617c56ae623656f731538c43f7a43f01b
[]
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
466
py
import sys _ = sys.stdin.readline() for case, line in enumerate(sys.stdin.readlines()): case += 1 a, b = map(int, line.split()) if a/10 == 0 and b/10 == 0: print 'Case #%d: 0' % case else: r = {} for i in xrange(a, b+1): n = m = str(i) for _ in n: m = m[-1] + m[:-1] if a <= i < int(m) <= b: r[n+m] = 1 print 'Case #%d: %d' % (case, len(r))
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
f836bad57be012645982c1938cbfcf9f3c52db1d
5844d61fc4e9fe70a6936e9d0d6bb4bc4f84465c
/phy/traces/filter.py
ef951d1253112612182224882c05961906dd82a7
[]
no_license
danieljdenman/phy
4f57c910020e3839432cf56e5ed817bf7b997e8e
9ba3a00d12b6b72856f1420ed977586d8a8f7d31
refs/heads/master
2021-01-22T15:35:47.522407
2015-06-25T15:40:41
2015-06-25T15:40:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,532
py
# -*- coding: utf-8 -*- """Waveform filtering routines.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import numpy as np from scipy import signal from ..utils._types import _as_array #------------------------------------------------------------------------------ # Waveform filtering routines #------------------------------------------------------------------------------ def bandpass_filter(rate=None, low=None, high=None, order=None): """Butterworth bandpass filter.""" assert low < high assert order >= 1 return signal.butter(order, (low / (rate / 2.), high / (rate / 2.)), 'pass') def apply_filter(x, filter=None): """Apply a filter to an array.""" x = _as_array(x) if x.shape[0] == 0: return x b, a = filter return signal.filtfilt(b, a, x, axis=0) class Filter(object): """Bandpass filter.""" def __init__(self, rate=None, low=None, high=None, order=None): self._filter = bandpass_filter(rate=rate, low=low, high=high, order=order, ) def __call__(self, data): return apply_filter(data, filter=self._filter) #------------------------------------------------------------------------------ # Whitening #------------------------------------------------------------------------------ class Whitening(object): """Compute a whitening matrix and apply it to data. Contributed by Pierre Yger. """ def fit(self, x, fudge=1e-18): """Compute the whitening matrix. Parameters ---------- x : array An `(n_samples, n_channels)` array. """ assert x.ndim == 2 ns, nc = x.shape x_cov = np.cov(x, rowvar=0) assert x_cov.shape == (nc, nc) d, v = np.linalg.eigh(x_cov) d = np.diag(1. / np.sqrt(d + fudge)) # This is equivalent, but seems much slower... # w = np.einsum('il,lk,jk->ij', v, d, v) w = np.dot(np.dot(v, d), v.T) self._matrix = w return w def transform(self, x): """Whiten some data. Parameters ---------- x : array An `(n_samples, n_channels)` array. """ return np.dot(x, self._matrix)
[ "cyrille.rossant@gmail.com" ]
cyrille.rossant@gmail.com
6a2bab06289e994ca0c8efdf9279028438e85c5d
9f48355699f7e12915241024b01985a76620c203
/CustomStack/mystack.py
0ab1c2f9594ce238ff9729bd2f2fdc0884d8d517
[]
no_license
zingp/leetcode-py
537bebaeb2ac223f5e10014f755ab961582ed0d3
53975bd952a1ceb34189682fda16bbee403fd84b
refs/heads/master
2021-08-10T12:34:07.061017
2021-06-15T01:00:23
2021-06-15T01:00:23
155,186,882
0
0
null
null
null
null
UTF-8
Python
false
false
474
py
class stack(object): def __init__(self): self.stack = [] def push(self, ele): self.stack.append(ele) def pop(self): if len(self.stack) > 0: return self.stack.pop() else: return None def get_top(self): if len(self.stack) > 0: return self.stack[-1] else: return None if __name__ == "__main__": s = stack() s.push(1) s.push(2) print(s.stack)
[ "605156398@qq.com" ]
605156398@qq.com
7b912e2285b65f0e82ad4d4d5cf759fb35624272
51f887286aa3bd2c3dbe4c616ad306ce08976441
/pybind/slxos/v17r_2_00/routing_system/router/isis/router_isis_cmds_holder/address_family/ipv4/af_ipv4_unicast/af_ipv4_attributes/af_common_attributes/redistribute/isis/level_1/__init__.py
1a220564369c61b327bc9301d3e66a11c96fa4d0
[ "Apache-2.0" ]
permissive
b2220333/pybind
a8c06460fd66a97a78c243bf144488eb88d7732a
44c467e71b2b425be63867aba6e6fa28b2cfe7fb
refs/heads/master
2020-03-18T09:09:29.574226
2018-04-03T20:09:50
2018-04-03T20:09:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,914
py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ import into class level_1(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-common-def - based on the path /routing-system/router/isis/router-isis-cmds-holder/address-family/ipv4/af-ipv4-unicast/af-ipv4-attributes/af-common-attributes/redistribute/isis/level-1. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__into',) _yang_name = 'level-1' _rest_name = 'level-1' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__into = YANGDynClass(base=into.into, is_container='container', presence=False, yang_name="into", rest_name="into", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='urn:brocade.com:mgmt:brocade-isis', defining_module='brocade-isis', yang_type='container', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'routing-system', u'router', u'isis', u'router-isis-cmds-holder', u'address-family', u'ipv4', u'af-ipv4-unicast', u'af-ipv4-attributes', u'af-common-attributes', u'redistribute', u'isis', u'level-1'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'router', u'isis', u'address-family', u'ipv4', u'unicast', u'redistribute', u'isis', u'level-1'] def _get_into(self): """ Getter method for into, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv4/af_ipv4_unicast/af_ipv4_attributes/af_common_attributes/redistribute/isis/level_1/into (container) """ return self.__into def _set_into(self, v, load=False): """ Setter method for into, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv4/af_ipv4_unicast/af_ipv4_attributes/af_common_attributes/redistribute/isis/level_1/into (container) If this variable is read-only (config: false) in the source YANG file, then _set_into is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_into() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=into.into, is_container='container', presence=False, yang_name="into", rest_name="into", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='urn:brocade.com:mgmt:brocade-isis', defining_module='brocade-isis', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """into must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=into.into, is_container='container', presence=False, yang_name="into", rest_name="into", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='urn:brocade.com:mgmt:brocade-isis', defining_module='brocade-isis', yang_type='container', is_config=True)""", }) self.__into = t if hasattr(self, '_set'): self._set() def _unset_into(self): self.__into = YANGDynClass(base=into.into, is_container='container', presence=False, yang_name="into", rest_name="into", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='urn:brocade.com:mgmt:brocade-isis', defining_module='brocade-isis', yang_type='container', is_config=True) into = __builtin__.property(_get_into, _set_into) _pyangbind_elements = {'into': into, }
[ "badaniya@brocade.com" ]
badaniya@brocade.com
68ba6bf1e51fff464bbcb634b294cd93a537c5f4
9e3d6b9f3bbc1d139d3b5a69bbf025c081289ea1
/manage.py
fbcefc8d2c7375dad31a142433bc03dfdf09fd04
[]
no_license
abugasavio/msalama
aca5ef2257ff4e192b895c1bb4831d1d43ab7e65
2acc5807e8a7f87f387c34a6ae7612d454685292
refs/heads/master
2021-05-29T11:44:18.268131
2015-09-01T11:28:52
2015-09-01T11:28:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
252
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "msalama.production") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "savioabuga@gmail.com" ]
savioabuga@gmail.com
12aae2888e93f9adc894ae28e23152cd367211f1
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/pa3/benchmarks/sieve-868.py
0df90c2432f34c2721944ae516c8dedfeab8a95b
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
2,589
py
# A resizable list of integers class Vector(object): items: [int] = None size: int = 0 def __init__(self:"Vector"): self.items = [0] # Returns current capacity def capacity(self:"Vector") -> int: return len(self.items) # Increases capacity of vector by one element def increase_capacity(self:"Vector") -> int: self.items = self.items + [0] return self.capacity() # Appends one item to end of vector def append(self:"Vector", item: int) -> object: if self.size == self.capacity(): self.increase_capacity() self.items[self.size] = item self.size = self.size + 1 # Appends many items to end of vector def append_all(self:"Vector", new_items: [int]) -> object: item:int = 0 for item in new_items: self.append(item) # Removes an item from the middle of vector def remove_at(self:"Vector", idx: int) -> object: if idx < 0: return while idx < self.size - 1: self.items[idx] = self.items[idx + 1] idx = idx + 1 self.size = self.size - 1 # Retrieves an item at a given index def get(self:"Vector", idx: int) -> int: return self.items[idx] # Retrieves the current size of the vector def length(self:"Vector") -> int: return self.size # A faster (but more memory-consuming) implementation of vector class DoublingVector(Vector): doubling_limit:int = 1000 # Overriding to do fewer resizes def increase_capacity(self:"DoublingVector") -> int: if (self.capacity() <= self.doubling_limit // 2): self.items = self.items + self.items else: # If doubling limit has been reached, fall back to # standard capacity increases self.items = self.items + [0] return self.capacity() # Makes a vector in the range [i, j) def vrange(i:int, j:int) -> Vector: v:Vector = None v = DoublingVector() while i < j: v.append(i) i = i + 1 return v # Sieve of Eratosthenes (not really) def sieve(v:Vector) -> object: i:int = 0 j:int = 0 k:int = 0 while i < v.length(): k = v.get(i) j = i + 1 while j < v.length(): if v.get(j) % k == 0: v.remove_at(j) else: j = j + 1 i = i + 1 # Input parameter n:int = 50 # Data v:Vector = None i:int = 0 # Crunch v = vrange(2, n) sieve(v) # Print while i < v.length(): print(v.get(i)) i = $ID + 1
[ "647530+Virtlink@users.noreply.github.com" ]
647530+Virtlink@users.noreply.github.com
aa5e04f5a6941d9b5a4fe1cd4674a98c766f223a
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/kzZD8Xp3EC7bipfxe_5.py
1d9f1e7d1c26d008ef7a788ee6e967091963b8a4
[]
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
686
py
""" Create a function that outputs the result of a math expression in words. ### Examples worded_math("One plus one") ➞ "Two" worded_math("zero Plus one") ➞ "One" worded_math("one minus one") ➞ "Zero" ### Notes * Expect only the operations `plus` and `minus`. * Expect to only get numbers and answers from `0` to `2`. * The first letter of the answer must be capitalised. """ def worded_math(equ): d={"ZERO":0,"ONE":1,"TWO":2} eq=equ.upper().split() if eq[1]=="PLUS": return (list(d.keys())[list(d.values()).index(d[eq[0]]+d[eq[2]])]).capitalize() return (list(d.keys())[list(d.values()).index(d[eq[0]]-d[eq[2]])]).capitalize()
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
9bc92d13acd0e88decb4e96d6907a77962b3f05e
182d36353a6e33dc1f27f2dc7c0ae95577941dca
/liaoxuefeng/debug.py
6be77d8e784f6bd8495c5b83bddcd9efcf4e57e1
[]
no_license
tp-yan/PythonScript
d0da587162b1f621ed6852be758705690a6c9dce
497c933217019046aca0d4258b174a13965348a7
refs/heads/master
2020-09-02T02:49:20.305732
2019-12-01T06:54:19
2019-12-01T06:54:19
219,115,755
0
0
null
null
null
null
UTF-8
Python
false
false
2,774
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 22 14:22:06 2019 @author: tangpeng 调试 """ """ 1. 断言 凡是用print()来辅助查看的地方,都可以用断言(assert)来替代,如果断言失败,assert语句本身就会抛出AssertionError。 启动Python解释器时可以用-O参数(英文大写字母O)来关闭assert: python -O err.py """ def foo(s): n = int(s) assert n != 0, "n is zero" # assert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错。 def main(): foo('0') #main() # AssertionError: n is zero """ 2. logging 把print()替换为logging,和assert比,logging不会抛出错误,而且可以输出到文件: logging.basicConfig(level=logging.INFO) 指定记录信息的级别,有debug,info,warning,error等几个级别, 当我们指定level=INFO时,logging.debug就不起作用了。同理,指定level=WARNING后,debug和info就不起作用了。 logging的另一个好处是通过简单的配置,一条语句可以同时输出到不同的地方,比如console和文件。 """ import logging logging.basicConfig(level=logging.INFO) # 控制logging输出等级,默认不输出 s = "0" n = int(s) logging.info("n = %d" % n) # logging.info()就可以输出一段文本 print(10/n) """ # 在控制台会有logging输出,在IPython下没有 python debug.py INFO:root:n = 0 Traceback (most recent call last): File "debug.py", line 34, in <module> print(10/n) ZeroDivisionError: division by zero """ """ 3. pdb Python的调试器 pdb ,让程序以单步方式运行,可以随时查看运行状态: python -m pdb err.py # 以参数-m pdb启动 pdb > d:\project\pythonproject\script\err.py(9)<module>() -> ''' (Pdb) l # 输入命令l来查看代码: 4 Created on Tue Oct 22 15:26:08 2019 5 6 @author: tangpeng 7 8 err.py:用于调试测试的模块 9 -> ''' 10 11 s = '0' 12 n = int(s) 13 print(10 / n) [EOF] (Pdb) n # 输入命令n可以单步执行代码 > d:\project\pythonproject\script\err.py(11)<module>() -> s = '0' (Pdb) n > d:\project\pythonproject\script\err.py(12)<module>() -> n = int(s) (Pdb) n > d:\project\pythonproject\script\err.py(13)<module>() -> print(10 / n) (Pdb) p s # 任何时候都可以输入命令p 变量名来查看变量: '0' (Pdb) p n 0 (Pdb) n ZeroDivisionError: division by zero > d:\project\pythonproject\script\err.py(13)<module>() -> print(10 / n) (Pdb) q # 输入命令q结束调试,退出程序 """ """ `pdb.set_trace()`:这个方法也是用pdb,但是不需要单步执行,我们只需要`import pdb`, 然后,在可能出错的地方放一个`pdb.set_trace()`,就可以设置一个断点: """
[ "tp1084165470@gmail.com" ]
tp1084165470@gmail.com
5f772c255a2d963e4174ee771b2d84e4f7d34570
0f9f8e8478017da7c8d408058f78853d69ac0171
/python3/l0283_move_zeros.py
45ac985e2ff57c7e657675ed0adcd7c6d9b39d2c
[]
no_license
sprax/1337
dc38f1776959ec7965c33f060f4d43d939f19302
33b6b68a8136109d2aaa26bb8bf9e873f995d5ab
refs/heads/master
2022-09-06T18:43:54.850467
2020-06-04T17:19:51
2020-06-04T17:19:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
350
py
from typing import List class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ i, j = 0, 0 while j < len(nums): if nums[j] != 0: nums[i], nums[j] = nums[j], nums[i] i += 1 j += 1
[ "zhoulv82@gmail.com" ]
zhoulv82@gmail.com
8c47efca30c846eaf43046cb0784d1cc21e03a32
9ecdf9b65c0d0ab96945ccdcb7c59e08ea3ad49e
/arelle/plugin/profileFormula.py
2485a86198492bc9cb376af75f32f6fec1689b7d
[ "Apache-2.0" ]
permissive
joskoanicic/carelle
348bd5b4e0619161035d2906e6c99ed1ab362c1a
311f97bd944d49016885cc90d8be41a4bb85300a
refs/heads/master
2020-04-15T10:04:51.445961
2015-11-10T16:50:09
2015-11-10T16:50:09
68,085,924
1
0
null
null
null
null
UTF-8
Python
false
false
5,608
py
''' Profile Formula Validation is an example of a plug-in to GUI menu that will profile formula execution. (c) Copyright 2012 Mark V Systems Limited, All rights reserved. ''' import os from tkinter import simpledialog, messagebox def profileFormulaMenuEntender(cntlr, menu): # Extend menu with an item for the profile formula plugin menu.add_command(label="Profile formula validation", underline=0, command=lambda: profileFormulaMenuCommand(cntlr) ) def profileFormulaMenuCommand(cntlr): # save DTS menu item has been invoked if cntlr.modelManager is None or cntlr.modelManager.modelXbrl is None: cntlr.addToLog("No taxonomy loaded.") return # get file name into which to save log file while in foreground thread profileReportFile = cntlr.uiFileDialog("save", title=_("arelle - Save Formula Profile Report"), initialdir=cntlr.config.setdefault("formulaProfileReportDir","."), filetypes=[(_("Profile report file .log"), "*.log")], defaultextension=".log") if not profileReportFile: return False errMsg = "" maxRunTime = 0 while (1): timeout = simpledialog.askstring(_("arelle - Set formula run time limit"), _("{0}You may enter the maximum number of minutes to run formulas.\n" "(Leave empty for no run time limitation.)".format(errMsg)), parent=cntlr.parent) if timeout: try: maxRunTime = float(timeout) break except ValueError as err: errMsg = str(err) + "\n\n" excludeCompileTime = messagebox.askyesno(_("arelle - Exclude formula compile statistics"), _("Should formula compiling be excluded from the statistics?\n" "(Yes will make a separate compiling \"pass\" so that statistics include execution only.)".format(errMsg)), parent=cntlr.parent) cntlr.config["formulaProfileReportDir"] = os.path.dirname(profileReportFile) cntlr.saveConfig() # perform validation and profiling on background thread import threading thread = threading.Thread(target=lambda c=cntlr, f=profileReportFile, t=maxRunTime, e=excludeCompileTime: backgroundProfileFormula(c,f,t,e)) thread.daemon = True thread.start() def backgroundProfileFormula(cntlr, profileReportFile, maxRunTime, excludeCompileTime): from arelle import Locale, XPathParser, ValidateXbrlDimensions, ValidateFormula # build grammar before profiling (if this is the first pass, so it doesn't count in profile statistics) XPathParser.initializeParser(cntlr.modelManager) # load dimension defaults ValidateXbrlDimensions.loadDimensionDefaults(cntlr.modelManager) import cProfile, pstats, sys, time # a minimal validation class for formula validator parameters that are needed class Validate: def __init__(self, modelXbrl, maxRunTime): self.modelXbrl = modelXbrl self.parameters = None self.validateSBRNL = False self.maxFormulaRunTime = maxRunTime def close(self): self.__dict__.clear() val = Validate(cntlr.modelManager.modelXbrl, maxRunTime) formulaOptions = val.modelXbrl.modelManager.formulaOptions if excludeCompileTime: startedAt = time.time() cntlr.addToLog(_("pre-compiling formulas before profiling")) val.validateFormulaCompileOnly = True ValidateFormula.validate(val) del val.validateFormulaCompileOnly cntlr.addToLog(Locale.format_string(cntlr.modelManager.locale, _("formula pre-compiling completed in %.2f secs"), time.time() - startedAt)) cntlr.addToLog(_("executing formulas for profiling")) else: cntlr.addToLog(_("compiling and executing formulas for profiling")) startedAt = time.time() statsFile = profileReportFile + ".bin" cProfile.runctx("ValidateFormula.validate(val)", globals(), locals(), statsFile) cntlr.addToLog(Locale.format_string(cntlr.modelManager.locale, _("formula profiling completed in %.2f secs"), time.time() - startedAt)) # dereference val val.close() # specify a file for log priorStdOut = sys.stdout sys.stdout = open(profileReportFile, "w") statObj = pstats.Stats(statsFile) statObj.strip_dirs() statObj.sort_stats("time") statObj.print_stats() statObj.print_callees() statObj.print_callers() sys.stdout.flush() sys.stdout.close() del statObj sys.stdout = priorStdOut os.remove(statsFile) __pluginInfo__ = { 'name': 'Profile Formula Validation', 'version': '1.0', 'description': "This plug-in adds a profiled formula validation. " "Includes XPath compilation in the profile if it is the first validation of instance; " "to exclude XPath compile statistics, validate first the normal way (e.g., toolbar button) " "and then validate again using this profile formula validation plug-in. ", 'license': 'Apache-2', 'author': 'Mark V Systems Limited', 'copyright': '(c) Copyright 2012 Mark V Systems Limited, All rights reserved.', # classes of mount points (required) 'CntlrWinMain.Menu.Validation': profileFormulaMenuEntender, }
[ "fischer@markv.com" ]
fischer@markv.com
1f9525b6078ff952fcc29b26d4a6bb1223a4dac0
23392f060c85b5fee645d319f2fd5560653dfd5c
/01_jumptopy/chap03/124.py
1ee85ae3e8516ba4fe143ffe5436b7c0839cc65d
[]
no_license
heyhello89/openbigdata
65192f381de83e4d153c072ff09fa7574f003037
b35ff237c32013c3e5380eee782085a64edb9d80
refs/heads/master
2021-10-22T04:29:00.852546
2019-03-08T02:14:34
2019-03-08T02:14:34
125,938,319
0
0
null
null
null
null
UHC
Python
false
false
486
py
# coding: cp949 prompt=""" 1. 추가 2. 삭제 3. 목록 4. 종료 숫자를 입력하세요: """ number=0 while number!=4: number=int(input(prompt)) if number==1: print("'1. 추가' 메뉴를 선택하셨습니다.") elif number==2: print("'2. 삭제' 메뉴를 선택하셨습니다.") elif number==3: print("'3. 목록' 메뉴를 선택하셨습니다.") elif number==4: print("'4. 종료' 메뉴를 선택하셨습니다.")
[ "heyhello89@hanmail.net" ]
heyhello89@hanmail.net
e6a331871f9ab5acab6cd7dd8eaab2051ab270f2
43e0cfda9c2ac5be1123f50723a79da1dd56195f
/python/paddle/distributed/auto_parallel/tuner/trial.py
3937ca9865181f066597d4afb48ac9832f1036bd
[ "Apache-2.0" ]
permissive
jiangjiajun/Paddle
837f5a36e868a3c21006f5f7bb824055edae671f
9b35f03572867bbca056da93698f36035106c1f3
refs/heads/develop
2022-08-23T11:12:04.503753
2022-08-11T14:40:07
2022-08-11T14:40:07
426,936,577
0
0
Apache-2.0
2022-02-17T03:43:19
2021-11-11T09:09:28
Python
UTF-8
Python
false
false
4,766
py
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Notice that the following codes are modified from KerasTuner to implement our own tuner. # Please refer to https://github.com/keras-team/keras-tuner/blob/master/keras_tuner/engine/trial.py. import hashlib import random import time from enum import Enum from .storable import Storable from .recorder import MetricsRecorder from .tunable_space import TunableSpace class TrialStatus: RUNNING = "RUNNING" COMPLETED = "COMPLETED" STOPPED = "STOPPED" INVALID = "INVALID" class Trial(Storable): def __init__(self, tunable_space, trial_id=None, status=TrialStatus.RUNNING): self._id = _generate_trial_id() if trial_id is None else trial_id self._space = tunable_space self._recorder = MetricsRecorder() self._score = None self._best_step = None self._status = status @property def id(self): return self._id @property def space(self): return self._space @property def recorder(self): return self._recorder @property def score(self): return self._score @score.setter def score(self, score): self._score = score @property def best_step(self): return self._best_step @best_step.setter def best_step(self, best_step): self._best_step = best_step @property def status(self): return self._status @status.setter def status(self, status): self._status = status def summary(self): print("Tunable space:") if self.space.values: for tv, value in self.space.values.items(): print(tv + ":", value) if self.score is not None: print("Score: {}".format(self.score)) def get_state(self): return { "id": self.id, "space": self.space.get_state(), "recorder": self.recorder.get_state(), "score": self.score, "best_step": self.best_step, "status": self.status, } def set_state(self, state): self._id = state["id"] self._space = TunableSpace.from_state(state["space"]) self._recorder = MetricsRecorder.from_state(state["recorder"]) self._score = state["score"] self._best_step = state["best_step"] self._status = state["status"] @classmethod def from_state(cls, state): trial = cls(tunable_space=None) trial.set_state(state) return trial class OptimizationTunerTrial(Trial): def __init__(self, config, name, changed_configs, trial_id=None, status=TrialStatus.RUNNING): super(OptimizationTunerTrial, self).__init__(config, trial_id, status) self._name = name self._changed_configs = changed_configs @property def name(self): return self._name def summary(self): spacing = 2 max_k = 38 max_v = 38 length = max_k + max_v + spacing h1_format = " " + "|{{:^{}s}}|\n".format(length) h2_format = " " + "|{{:>{}s}}{}{{:^{}s}}|\n".format( max_k, " " * spacing, max_v) border = " +" + "".join(["="] * length) + "+" line = " +" + "".join(["-"] * length) + "+" draws = border + "\n" draws += h1_format.format("") draws += h1_format.format("Tuned Configuartions Overview") draws += h1_format.format("") for name in self._changed_configs: draws += border + "\n" draws += h1_format.format("{} auto=True <-> {}".format(name, name)) draws += line + "\n" my_configs = getattr(self.space, name) keys = my_configs.keys() for key in keys: draws += h2_format.format(key, str(my_configs.get(key, None))) result_res = draws + border return result_res def _generate_trial_id(): s = str(time.time()) + str(random.randint(1, int(1e7))) return hashlib.sha256(s.encode("utf-8")).hexdigest()[:32]
[ "noreply@github.com" ]
jiangjiajun.noreply@github.com
ff56e6a71796c367dacdf9136d62cb7bbd047cc4
ca9152cf5adf7c38867aad2fb8ca4d2747149c84
/src/pytorch_metric_learning/losses/triplet_margin_loss.py
9e7843bcc5bc24db1cc148eaf81d0060454c7e81
[ "MIT" ]
permissive
Bobo-y/pytorch-metric-learning
91d14dec18b988f5acc153c8205e85e069cbc548
dff4ae570db89dcb59a102f13f665502f9c1c7c6
refs/heads/master
2023-04-15T21:01:16.115250
2021-04-03T02:44:16
2021-04-03T02:44:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,110
py
import torch from ..reducers import AvgNonZeroReducer from ..utils import loss_and_miner_utils as lmu from .base_metric_loss_function import BaseMetricLossFunction class TripletMarginLoss(BaseMetricLossFunction): """ Args: margin: The desired difference between the anchor-positive distance and the anchor-negative distance. swap: Use the positive-negative distance instead of anchor-negative distance, if it violates the margin more. smooth_loss: Use the log-exp version of the triplet loss """ def __init__( self, margin=0.05, swap=False, smooth_loss=False, triplets_per_anchor="all", **kwargs ): super().__init__(**kwargs) self.margin = margin self.swap = swap self.smooth_loss = smooth_loss self.triplets_per_anchor = triplets_per_anchor self.add_to_recordable_attributes(list_of_names=["margin"], is_stat=False) def compute_loss(self, embeddings, labels, indices_tuple): indices_tuple = lmu.convert_to_triplets( indices_tuple, labels, t_per_anchor=self.triplets_per_anchor ) anchor_idx, positive_idx, negative_idx = indices_tuple if len(anchor_idx) == 0: return self.zero_losses() mat = self.distance(embeddings) ap_dists = mat[anchor_idx, positive_idx] an_dists = mat[anchor_idx, negative_idx] if self.swap: pn_dists = mat[positive_idx, negative_idx] an_dists = self.distance.smallest_dist(an_dists, pn_dists) current_margins = self.distance.margin(an_dists, ap_dists) if self.smooth_loss: loss = torch.log(1 + torch.exp(-current_margins)) else: loss = torch.nn.functional.relu(-current_margins + self.margin) return { "loss": { "losses": loss, "indices": indices_tuple, "reduction_type": "triplet", } } def get_default_reducer(self): return AvgNonZeroReducer()
[ "tkm45@cornell.edu" ]
tkm45@cornell.edu
06f580e8601734f21702378de0b414ab38485f97
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02271/s017858399.py
b1332bc0fcd0f6a8c679f83cab6e08e303625121
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
956
py
from itertools import repeat from itertools import combinations def rec(s, i, total, m): if total == m: return 1 if len(s) == i or total > m: return 0 return rec(s, i + 1, total, m) + rec(s, i + 1, total + s[i], m) def makeCache(s): cache = {} for i in range(len(s)): comb = list(combinations(s, i)) for c in comb: cache[sum(c)] = 1 return cache def loop(s, m): for i in range(len(s)): comb = list(combinations(s, i)) for c in comb: if sum(c) == m: return 1 return 0 if __name__ == "__main__": n = int(input()) a = [int (x) for x in input().split()] q = int(input()) m = [int (x) for x in input().split()] s = makeCache(a) for i in m: #print("yes") if rec(a, 0, 0, i) > 0 else print("no") #print("yes") if loop(a, i) > 0 else print("no") print("yes") if i in s else print("no")
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
b45991fc4b005bf57fcb4a36ebb41de146a131fa
65c0eb470e48a018c65631a995c5cf4d0f142cf8
/test_camera.py
c5b5d5e588650b9737463a5e098433f186ef427f
[]
no_license
WolfgangFahl/ESE205-CVChess
eab7491d130fa534ed966fe3af39cbb7a6f33341
3b88090be3015caa90e42f59db4c88be8a67c355
refs/heads/master
2020-08-14T05:45:59.729411
2019-11-12T08:44:28
2019-11-12T08:44:28
215,108,730
0
1
null
2019-10-14T17:46:17
2019-10-14T17:46:16
null
UTF-8
Python
false
false
163
py
from Camera import Camera # test the camera def test_Camera(): camera=Camera() assert camera assert camera.cam # call the camera test test_Camera()
[ "wf@bitplan.com" ]
wf@bitplan.com
6eb1c2b72186303722500f9625bae4ec1dd3f465
61673ab9a42f7151de7337608c442fa6247f13bb
/tkinter/label/label-os.listdir/main.py
befd86ad6bda534d9a7e53df6543a2a2e83995a9
[ "MIT" ]
permissive
furas/python-examples
22d101670ecd667a29376d7c7d7d86f8ec71f6cf
95cb53b664f312e0830f010c0c96be94d4a4db90
refs/heads/master
2022-08-23T23:55:08.313936
2022-08-01T14:48:33
2022-08-01T14:48:33
45,575,296
176
91
MIT
2021-02-17T23:33:37
2015-11-04T23:54:32
Python
UTF-8
Python
false
false
459
py
#!/usr/bin/env python3 # date: 2019.10.15 # https://stackoverflow.com/questions/58364159/printing-text-from-a-function-into-a-tkinter-label import os import tkinter as tk def get_filenames(): filenames = sorted(os.listdir('.')) text = "\n".join(filenames) label['text'] = text # change text in label root = tk.Tk() label = tk.Label(root) # empty label label.pack() tk.Button(root, text="OK", command=get_filenames).pack() root.mainloop()
[ "furas@tlen.pl" ]
furas@tlen.pl
27700db0c9ee4bb37b0c7f811e97c74938133910
278d7f4467a112416d1adfbcd3218033ff0fd9b3
/mmdet/models/detectors/fcos.py
9f34b76946c8e068fb0a13416e4c7f7d582acc4c
[]
no_license
Young-1217/detection
e3d67938b454e955b5b7a82d5ae222e62f9545fb
6760288dac92e00ddc3e813ed0e1363c1fa1ce2d
refs/heads/main
2023-06-01T21:41:37.998947
2021-06-21T10:03:01
2021-06-21T10:03:01
371,868,683
0
0
null
null
null
null
UTF-8
Python
false
false
562
py
from ..builder import DETECTORS from .single_stage import SingleStageDetector @DETECTORS.register_module() class FCOS(SingleStageDetector): """Implementation of `FCOS <https://arxiv.org/abs/1904.01355>`_""" def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None): super(FCOS, self).__init__(backbone, neck, bbox_head, train_cfg, test_cfg, pretrained)
[ "noreply@github.com" ]
Young-1217.noreply@github.com
7df13a7dca896b802ae30f52268f015494835398
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_353/ch135_2020_04_01_12_34_36_501450.py
17730c3e4d8367f61aa6c05c9fd0102f30264240
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
225
py
def equaliza_imagem(k,cores): i=0 ls=[] n=len(cores) while i<=(n-1): if(cores[i]*k)>=255: ls.append(255) else: ls.append(cores[i]*k) i+=1 return ls
[ "you@example.com" ]
you@example.com
b86e6518cc484c69443fbd6a6ac37c886b02c94b
1977dfcd971bb80fd5926f00a86d37c21cf80520
/y/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/core/exceptions.py
98eab373e0afc66b67b7c92ec5685cdea0b2abd9
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
camidagreat/music_game_poc
fd39cd1bbcddaee6ccac2601b95ec81d0358dbf8
be3c69c026a254078e1dbcee936b368766092a5e
refs/heads/master
2023-01-08T22:12:05.372029
2020-04-22T19:40:31
2020-04-22T19:40:31
204,744,171
0
1
null
2022-12-10T07:53:06
2019-08-27T16:27:00
Python
UTF-8
Python
false
false
4,408
py
# -*- coding: utf-8 -*- # # Copyright 2014 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base exceptions for the Cloud SDK.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import os import sys from googlecloudsdk.core.util import platforms import six class _Error(Exception): """A base exception for all Cloud SDK errors. This exception should not be used directly. """ pass class InternalError(_Error): """A base class for all non-recoverable internal errors.""" pass class Error(_Error): """A base exception for all user recoverable errors. Any exception that extends this class will not be printed with a stack trace when running from CLI mode. Instead it will be shows with a message of how the user can correct this problem. All exceptions of this type must have a message for the user. """ def __init__(self, *args, **kwargs): """Initialize a core.Error. Args: *args: positional args for exceptions. **kwargs: keyword args for exceptions, and additional arguments: - exit_code: int, The desired exit code for the CLI. """ super(Error, self).__init__(*args) self.exit_code = kwargs.get('exit_code', 1) class MultiError(Error): """Collection of Error instances as single exception.""" def __init__(self, errors): super(MultiError, self).__init__(', '.join(six.text_type(e) for e in errors)) class RequiresAdminRightsError(Error): """An exception for when you don't have permission to modify the SDK. This tells the user how to run their command with administrator rights so that they can perform the operation. """ def __init__(self, sdk_root): message = ( 'You cannot perform this action because you do not have permission ' 'to modify the Google Cloud SDK installation directory [{root}].\n\n' .format(root=sdk_root)) if (platforms.OperatingSystem.Current() == platforms.OperatingSystem.WINDOWS): message += ( 'Click the Google Cloud SDK Shell icon and re-run the command in ' 'that window, or re-run the command with elevated privileges by ' 'right-clicking cmd.exe and selecting "Run as Administrator".') else: # Specify the full path because sudo often uses secure_path and won't # respect the user's $PATH settings. gcloud_path = os.path.join(sdk_root, 'bin', 'gcloud') message += ( 'Re-run the command with sudo: sudo {0} ...'.format(gcloud_path)) super(RequiresAdminRightsError, self).__init__(message) class NetworkIssueError(Error): """An error to wrap a general network issue.""" def __init__(self, message): super(NetworkIssueError, self).__init__( '{message}\n' 'This may be due to network connectivity issues. Please check your ' 'network settings, and the status of the service you are trying to ' 'reach.'.format(message=message)) class ExceptionContext(object): """An exception context that can be re-raised outside of try-except. Usage: exception_context = None ... try: ... except ... e: # This MUST be called in the except: clause. exception_context = exceptions.ExceptionContext(e) ... if exception_context: exception_context.Reraise() """ def __init__(self, e): self._exception = e self._traceback = sys.exc_info()[2] if not self._traceback: raise ValueError('Must set ExceptionContext within an except clause.') def Reraise(self): six.reraise(type(self._exception), self._exception, self._traceback) def reraise(exc_value, tb=None): # pylint: disable=invalid-name """Adds tb or the most recent traceback to exc_value and reraises.""" tb = tb or sys.exc_info()[2] six.reraise(type(exc_value), exc_value, tb)
[ "l.bidigare.curtis@gmail.com" ]
l.bidigare.curtis@gmail.com
08434b4f3f8fccef164b31dfdc8d67c11c1d3bfc
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/bob/9b8c6e044ac64769ba086a15c36a3d73.py
d48491b573d2706315333b916b8c906f5b06dde1
[]
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
271
py
# # Skeleton file for the Python "Bob" exercise. # def hey(what): if what.isupper(): return 'Whoa, chill out!' if what.endswith('?'): return 'Sure.' if not what.strip(): return 'Fine. Be that way!' else: return 'Whatever.'
[ "rrc@berkeley.edu" ]
rrc@berkeley.edu
f7491a276be527fc1210623a64651d181bcea56d
187a6558f3c7cb6234164677a2bda2e73c26eaaf
/jdcloud_sdk/services/antipro/apis/DescribeCpsIpResourcesRequest.py
27085dc7fbcfc694427a428f43b1e9cbd3a61bc4
[ "Apache-2.0" ]
permissive
jdcloud-api/jdcloud-sdk-python
4d2db584acc2620b7a866af82d21658cdd7cc227
3d1c50ed9117304d3b77a21babe899f939ae91cd
refs/heads/master
2023-09-04T02:51:08.335168
2023-08-30T12:00:25
2023-08-30T12:00:25
126,276,169
18
36
Apache-2.0
2023-09-07T06:54:49
2018-03-22T03:47:02
Python
UTF-8
Python
false
false
1,797
py
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # NOTE: This class is auto generated by the jdcloud code generator program. from jdcloud_sdk.core.jdcloudrequest import JDCloudRequest class DescribeCpsIpResourcesRequest(JDCloudRequest): """ 查询 DDoS 防护包可防护的云物理服务器公网 IP(包括云物理服务器弹性公网 IP 及云物理服务器基础网络实例的公网 IP) """ def __init__(self, parameters, header=None, version="v1"): super(DescribeCpsIpResourcesRequest, self).__init__( '/regions/{regionId}/cpsIpResources', 'GET', header, version) self.parameters = parameters class DescribeCpsIpResourcesParameters(object): def __init__(self, regionId, ): """ :param regionId: 地域编码, 防护包目前支持: 华北-北京, 华东-宿迁, 华东-上海 """ self.regionId = regionId self.pageNumber = None self.pageSize = None def setPageNumber(self, pageNumber): """ :param pageNumber: (Optional) 页码 """ self.pageNumber = pageNumber def setPageSize(self, pageSize): """ :param pageSize: (Optional) 分页大小 """ self.pageSize = pageSize
[ "oulinbao@jd.com" ]
oulinbao@jd.com
f36c42bb664c1f1846d355327925384abfd55024
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_74/1232.py
a374f2c0f81a9d1cd08433442c5246cff3db1822
[]
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
659
py
#!/usr/bin/python import sys import string def alg(case,f): row = f.readline().split() moves = int(row[0]) pO = pB = 1 tO = tB = 0 for i in range(moves): who = row[i*2+1] btn = int(row[i*2+2]) if (who == 'O'): tO += abs(btn-pO) # go if (tB>=tO): tO=tB # wait before press tO+=1 # and press pO=btn else: # who == 'B' tB += abs(btn-pB) # go if (tO>=tB): tB=tO # wait before press tB+=1 # and press pB=btn print 'Case #%d: %d'%(case+1,max(tO,tB)) def main(argv): with open(argv[1],'r') as f: cases = int(f.readline()) for i in range(cases): alg(i,f) f.closed if __name__ == "__main__": main(sys.argv)
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
b242453fdad7f3bf393fc5997532df9cb737c959
e1f5cf7055e54f24f4bea5b1232f337fcbcae63c
/loop/solution/loop_label_encoder.py
9263b77c47d9d3e6a37ba4fe190b9ce3e983fbd3
[ "MIT" ]
permissive
revirevy/book-python
fcd64d44840b68e528422de785383f9d4a81fb98
9da7bfd43117f33530e708e889c26152dc8c7a25
refs/heads/master
2020-04-01T05:13:50.394724
2018-10-13T14:58:19
2018-10-13T14:58:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,563
py
from random import shuffle DATABASE = [ ('Sepal length', 'Sepal width', 'Petal length', 'Petal width', 'Species'), (5.1, 3.5, 1.4, 0.2, 'setosa'), (4.9, 3.0, 1.4, 0.2, 'setosa'), (4.7, 3.2, 1.3, 0.2, 'setosa'), (4.6, 3.1, 1.5, 0.2, 'setosa'), (5.0, 3.6, 1.4, 0.3, 'setosa'), (5.4, 3.9, 1.7, 0.4, 'setosa'), (4.6, 3.4, 1.4, 0.3, 'setosa'), (7.0, 3.2, 4.7, 1.4, 'versicolor'), (6.4, 3.2, 4.5, 1.5, 'versicolor'), (6.9, 3.1, 4.9, 1.5, 'versicolor'), (5.5, 2.3, 4.0, 1.3, 'versicolor'), (6.5, 2.8, 4.6, 1.5, 'versicolor'), (5.7, 2.8, 4.5, 1.3, 'versicolor'), (5.7, 2.8, 4.1, 1.3, 'versicolor'), (6.3, 3.3, 6.0, 2.5, 'virginica'), (5.8, 2.7, 5.1, 1.9, 'virginica'), (7.1, 3.0, 5.9, 2.1, 'virginica'), (6.3, 2.9, 5.6, 1.8, 'virginica'), (6.5, 3.0, 5.8, 2.2, 'virginica'), (7.6, 3.0, 6.6, 2.1, 'virginica'), (4.9, 2.5, 4.5, 1.7, 'virginica'), ] species = dict() labels = list() header = DATABASE[0] data = DATABASE[1:] shuffle(data) for record in data: name = record[-1] if name not in species.keys(): species[name] = len(species) labels.append(species[name]) species = {value: key for key, value in species.items()} print(species) # {0: 'versicolor', 1: 'virginica', 2: 'setosa'} print(labels) # [0, 1, 2, 1, 1, 0, ...] ## Alternative solution 1 species = set(x[-1] for x in data) indexes = range(0, len(species)) d = zip(species, indexes) d = dict(d) ## In numerical analysis you can find this result = dict(enumerate(set(x[-1] for x in data)))
[ "matt@astrotech.io" ]
matt@astrotech.io
74a0f6c997b3b3ace16354b5deb86dd6faa55781
62e58c051128baef9452e7e0eb0b5a83367add26
/x12/5010/354005010.py
08b7b2d5821d99edd27618c3cec12800d84b3b4e
[]
no_license
dougvanhorn/bots-grammars
2eb6c0a6b5231c14a6faf194b932aa614809076c
09db18d9d9bd9d92cefbf00f1c0de1c590fe3d0d
refs/heads/master
2021-05-16T12:55:58.022904
2019-05-17T15:22:23
2019-05-17T15:22:23
105,274,633
0
0
null
2017-09-29T13:21:21
2017-09-29T13:21:21
null
UTF-8
Python
false
false
453
py
from bots.botsconfig import * from records005010 import recorddefs syntax = { 'version' : '00403', #version of ISA to send 'functionalgroup' : 'AY', } structure = [ {ID: 'ST', MIN: 1, MAX: 1, LEVEL: [ {ID: 'M10', MIN: 1, MAX: 1}, {ID: 'P4', MIN: 1, MAX: 20, LEVEL: [ {ID: 'X01', MIN: 1, MAX: 1}, {ID: 'X02', MIN: 0, MAX: 9999}, ]}, {ID: 'SE', MIN: 1, MAX: 1}, ]} ]
[ "jason.capriotti@gmail.com" ]
jason.capriotti@gmail.com
8d83846060bb604cdedc59bea541a59c93abc2d5
1086ef8bcd54d4417175a4a77e5d63b53a47c8cf
/Mine/marathon2019/marathon.py
0a130b63e70d6e960c9cd1e632b5c35ddce5e692
[]
no_license
wisdomtohe/CompetitiveProgramming
b883da6380f56af0c2625318deed3529cb0838f6
a20bfea8a2fd539382a100d843fb91126ab5ad34
refs/heads/master
2022-12-18T17:33:48.399350
2020-09-25T02:24:41
2020-09-25T02:24:41
298,446,025
0
0
null
null
null
null
UTF-8
Python
false
false
268
py
def findValleys(n, s): compteur = 0 marqueur = 0 if s[i] == "U": marqueur = 1 else: marqueur = -1 start = (s[i] == "U" and s[i+1] == "D") for i in s: if start : compteur += 1 if !start:
[ "elmanciowisdom@gmail.com" ]
elmanciowisdom@gmail.com
3733f46ba880d140ef4e0a90c9a769cf7108649a
a2c7bc7f0cf5c18ba84e9a605cfc722fbf169901
/python_1_to_1000/269_Alien_Dictionary.py
01a1de2634d2366896df31c02bfe358cf26a20f1
[]
no_license
jakehoare/leetcode
3bf9edd499034ce32be462d4c197af9a8ed53b5d
05e0beff0047f0ad399d0b46d625bb8d3459814e
refs/heads/master
2022-02-07T04:03:20.659422
2022-01-26T22:03:00
2022-01-26T22:03:00
71,602,471
58
38
null
null
null
null
UTF-8
Python
false
false
2,771
py
_author_ = 'jake' _project_ = 'leetcode' # https://leetcode.com/problems/alien-dictionary/ # There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. # You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this # new language. Derive the order of letters in this language. # For each character, count the number of chars that appear before it and create a set of chars that appear after it. # The first difference in chars at the same position for consecutive words in the dictionary gives an ordered pair # of chars. Find a topologial ordering of the resulting directed graph by repeatedly removing chars that have no # earlier chars remaining. # Time - O(n), total number of chars in all words # Space - O(m**2), nb chars in alphabet - order can be set of all chars for each char from collections import defaultdict class Solution(object): def alienOrder(self, words): """ :type words: List[str] :rtype: str """ after = defaultdict(int) # key is char, value is nb times char depends on a previous char order = defaultdict(set) # key is char, value is set of chars appearing after char seen = set(words[0]) # all chars found so far for i in range(1, len(words)): diff_to_prev = False for j, c in enumerate(words[i]): seen.add(c) # add every char of every word to seen # new difference from previous word at this position if j < len(words[i-1]) and not diff_to_prev and c != words[i-1][j]: if c not in order[words[i-1][j]]: # have not seen this ordering before order[words[i-1][j]].add(c) after[c] += 1 diff_to_prev = True if not diff_to_prev and len(words[i-1]) > len(words[i]): # no differences and longer word first return "" for c in seen: # all chars depend on at least zero previous chars if c not in after: after[c] = 0 frontier = set() # frontier have no dependencies for a in after: if after[a] == 0: frontier.add(a) letters = [] while frontier: b = frontier.pop() # add char from frontier to result del after[b] letters.append(b) for a in order[b]: # decrement dependency count of those appearing after b after[a] -= 1 if after[a] == 0: frontier.add(a) if after: return "" return "".join(letters)
[ "jake_hoare@hotmail.com" ]
jake_hoare@hotmail.com
c89c37e3bf9189730efe0f6a17ec092b259312f8
bdccb54daf0d0b0a19fabfe9ea9b90fcfc1bdfbf
/Tutorials/10 Days of Statistics/Day 1/interquartile_range.py
c3b235ee9c1a4978d65e8c075307fef710c91737
[ "MIT" ]
permissive
xuedong/hacker-rank
aba1ad8587bc88efda1e90d7ecfef8dbd74ccd68
1ee76899d555850a257a7d3000d8c2be78339dc9
refs/heads/master
2022-08-08T07:43:26.633759
2022-07-16T11:02:27
2022-07-16T11:02:27
120,025,883
1
0
null
null
null
null
UTF-8
Python
false
false
754
py
#!/bin/python3 import sys n = int(input().strip()) values = [int(arr_i) for arr_i in input().strip().split(' ')] freqs = [int(arr_i) for arr_i in input().strip().split(' ')] arr = [] for i in range(n): current = [values[i]] * freqs[i] arr.extend(current) sorted_arr = sorted(arr) def my_median(arr): length = len(arr) if length % 2 == 0: median = (arr[length//2-1] + arr[length//2])/2 else: median = arr[(length-1)//2] return median def my_quartiles(arr): length = len(arr) L = arr[0:length//2] U = arr[(length+1)//2:] q1 = my_median(L) q3 = my_median(U) return q1, q3 def interquartile(arr): q1, q3 = my_quartiles(arr) return q3 - q1 print(float(interquartile(sorted_arr)))
[ "shang.xuedong@yahoo.fr" ]
shang.xuedong@yahoo.fr
b616ace58044491cc943fd3f4f586b46d8608671
8155e744f698f7ed4ae32bbbfad3f72c65e810d9
/admin_honeypot/migrations/0002_auto_20160208_0854.py
44af8099881b4e75447578fd2f441b5d07de62c4
[ "MIT" ]
permissive
dmpayton/django-admin-honeypot
3ccdbd3f65d9a1238356d4e7ee50a8e1d58fe125
a840496d183df89965eeb33c9a5dd9ea3919dfff
refs/heads/develop
2023-07-29T00:06:18.292499
2022-01-01T22:31:28
2022-01-01T22:31:28
2,382,101
925
199
MIT
2022-08-09T07:08:28
2011-09-13T23:29:15
Python
UTF-8
Python
false
false
503
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-08 08:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('admin_honeypot', '0001_initial'), ] operations = [ migrations.AlterField( model_name='loginattempt', name='ip_address', field=models.GenericIPAddressField(blank=True, null=True, verbose_name='ip address'), ), ]
[ "derek.payton@gmail.com" ]
derek.payton@gmail.com
22851edde555a723915cdb62226e165703f4edfb
55c250525bd7198ac905b1f2f86d16a44f73e03a
/Python/Games/Game of Thrones/flask/bin/flask/lib/python2.7/site-packages/pip/cmdoptions.py
5b9f06dc119b57172b170108b5967275f923fa78
[]
no_license
NateWeiler/Resources
213d18ba86f7cc9d845741b8571b9e2c2c6be916
bd4a8a82a3e83a381c97d19e5df42cbababfc66c
refs/heads/master
2023-09-03T17:50:31.937137
2023-08-28T23:50:57
2023-08-28T23:50:57
267,368,545
2
1
null
2022-09-08T15:20:18
2020-05-27T16:18:17
null
UTF-8
Python
false
false
130
py
version https://git-lfs.github.com/spec/v1 oid sha256:a5fdb88accc0dfdae1709e438c5038a03ff3e6f4c8d0d1bdf2a51a847b37a8f3 size 15878
[ "nateweiler84@gmail.com" ]
nateweiler84@gmail.com
54442e9c8e985ef92e301aa2c7baa274c910bc31
050ccac41c3b3b217204eb5871ca987f897b8d56
/tradeorsale/tests/unit/core.py
a231ecb06478a6a93f65777b268bfbf34a8239b0
[]
no_license
marconi/tradeorsale
6aefc7760f389aabd7e08fe40953914f5ea60abc
6750260734f77cbf60c19ddddc83ebd27a5fb3a9
refs/heads/master
2021-01-23T20:21:24.210074
2013-01-12T09:05:09
2013-01-12T09:05:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,821
py
# -*- coding: utf-8 -*- import unittest import importlib from paste.deploy.loadwsgi import appconfig from sqlalchemy import engine_from_config from StringIO import StringIO from PIL import Image from pyramid import testing from tradeorsale import settings from tradeorsale.libs.models import initialize_db, Base, DBSession from tradeorsale.apps.item.models import Item, ItemStatus pyramid_settings = appconfig('config:test.ini', relative_to='.') class BaseTestCase(unittest.TestCase): """ A parent TestCase with the following enabled support: - database - settings - threadlocals - static file serving """ def __init__(self, *args, **kwargs): super(BaseTestCase, self).__init__(*args, **kwargs) self.model_scanner() # cache the engine so it doesn't get recreated on every setup self.engine = engine_from_config(pyramid_settings, 'sqlalchemy.') def model_scanner(self): """ Scans all apps for models and imports them so they can be found by sqlalchemy's metadata. """ for app in settings.INSTALLED_APPS: importlib.import_module(app) def setUp(self): initialize_db(self.engine) Base.metadata.create_all() # create all tables request = testing.DummyRequest() self.config = testing.setUp(request=request, settings=pyramid_settings) self.config.add_static_view('static', 'tradeorsale:static') self.config.testing_securitypolicy(userid='marc', permissive=True) def tearDown(self): testing.tearDown() # manually delete images path created by item because tearDown # disruptively drops table and no time to execute delete images event. self._remove_existing_items() DBSession.remove() Base.metadata.drop_all(self.engine) # drop all tables def _create_item_status(self): """ Helper method to create item statuses. """ self.draft_status = ItemStatus('DRAFTS') self.ongoing_status = ItemStatus('ONGOING') self.archived_status = ItemStatus('ARCHIVED') DBSession.add(self.draft_status) DBSession.add(self.ongoing_status) DBSession.add(self.archived_status) DBSession.commit() def _remove_existing_items(self): """ Helper method to remove existing items. """ for item in DBSession.query(Item).all(): DBSession.delete(item) DBSession.commit() class MockFileImage(object): def __init__(self, file, filename='image.jpg'): self.file = StringIO() # create empty image and save it to file attribute Image.new("RGB", (5, 5), (255, 255, 255)).save(self.file, 'JPEG') self.file.seek(0) self.filename = filename
[ "caketoad@gmail.com" ]
caketoad@gmail.com
46ea56be6c49a072fddf5364b9d3558b946ccc02
acd582814b04fb8065d795582f7c5d77db604bea
/nightreads/user_manager/models.py
02e7dc0a2feb0ca3cc9dd49578f3ecfa6b24f968
[ "MIT" ]
permissive
lgp171188/nightreads
30a37a106f05b0bb8c15c95a7e45931e7068f2d3
b1bf663d4e752b1c137e846e9928fc55004f7951
refs/heads/master
2021-01-21T16:15:39.137766
2016-05-26T03:40:13
2016-05-26T03:47:16
59,670,135
0
0
null
2016-05-25T14:28:42
2016-05-25T14:28:42
null
UTF-8
Python
false
false
386
py
from django.db import models from django.contrib.auth.models import User from nightreads.utils import TimeStampMixin from nightreads.posts.models import Tag class Subscription(TimeStampMixin): is_subscribed = models.BooleanField(default=False) user = models.OneToOneField(User) tags = models.ManyToManyField(Tag) def __str__(self): return self.user.username
[ "hi@avi.im" ]
hi@avi.im
73d69759d852d2c0af909923caf42a47c061ee40
8952afe242c836b516c6236cf0987676cfb7abf7
/TaobaoSdk/Request/SimbaNonsearchAllplacesGetRequest.py
0d0d5542730ad88aef570803179f657da9678931
[]
no_license
xieguanfu/TaobaoOpenPythonSDK
2fc20df983811990a2d981379c9da6c1117f9f21
88cdab41ba19a2326aa4085c92455697bd37d8d7
refs/heads/master
2021-01-18T14:38:51.465614
2014-08-21T05:44:42
2014-08-21T05:44:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,784
py
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim: set ts=4 sts=4 sw=4 et: ## @brief 获取单独出价投放位置列表 # @author wuliang@maimiaotech.com # @version: 0.0.0 import os import sys import time def __getCurrentPath(): return os.path.normpath(os.path.join(os.path.realpath(__file__), os.path.pardir)) __modulePath = os.path.join(__getCurrentPath(), os.path.pardir) __modulePath = os.path.normpath(__modulePath) if __modulePath not in sys.path: sys.path.insert(0, __modulePath) ## @brief <SPAN style="font-size:16px; font-family:'宋体','Times New Roman',Georgia,Serif;">获取单独出价投放位置列表</SPAN> # <UL> # </UL> class SimbaNonsearchAllplacesGetRequest(object): def __init__(self): super(self.__class__, self).__init__() ## @brief <SPAN style="font-size:16px; font-family:'宋体','Times New Roman',Georgia,Serif;">获取API名称</SPAN> # <UL> # <LI> # <SPAN style="color:DarkRed; font-size:18px; font-family:'Times New Roman',Georgia,Serif;">Type</SPAN>: <SPAN style="color:DarkMagenta; font-size:16px; font-family:'Times New Roman','宋体',Georgia,Serif;">str</SPAN> # </LI> # </UL> self.method = "taobao.simba.nonsearch.allplaces.get" ## @brief <SPAN style="font-size:16px; font-family:'宋体','Times New Roman',Georgia,Serif;">时间戳,如果不设置,发送请求时将使用当时的时间</SPAN> # <UL> # <LI> # <SPAN style="color:DarkRed; font-size:18px; font-family:'Times New Roman',Georgia,Serif;">Type</SPAN>: <SPAN style="color:DarkMagenta; font-size:16px; font-family:'Times New Roman','宋体',Georgia,Serif;">int</SPAN> # </LI> # </UL> self.timestamp = int(time.time())
[ "liyangmin@maimiaotech.com" ]
liyangmin@maimiaotech.com
81a47a577a07d2ef20d2a0d108284521ccb59b0b
60654caf2633613021470d0285817343f76223e5
/utils/body_to_row.py
8d642084644245e05c5263bd4a23600e7fa7f042
[]
no_license
whoiskx/com_code
79460ccee973d1dfe770af3780c273e4a0f466c9
388b5a055393ee7768cc8525c0484f19c3f97193
refs/heads/master
2020-04-09T23:14:28.228729
2018-12-06T07:10:25
2018-12-06T07:10:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,529
py
def body_to_row(body=''): if '?' in body: body = body.split('?')[-1] # print(body) body_split = body.split('&') result = "" for r in body_split: result += r + '\n' print(result) return result def headers_to_dict(headers=''): if headers == '': return '' items = headers.split("\n") # print(items) d = {} for item in items: k, v = item.split(": ", 1) d[k] = v.strip() print(d) return d def main(): # body_to_row(body) headers_to_dict(headers=headers) if __name__ == '__main__': # body = 'r=0.7690273252447204&__biz=MjM5MTI2MTI0MA%3D%3D&appmsg_type=9&mid=2655142500&sn=77fbb51f69117d7b573e17928f1a26ce&idx=1&scene=0&title=16%25E5%25A4%25A7%25E9%2587%258D%25E7%2582%25B9%25E9%25A1%25B9%25E7%259B%25AE%25E6%259B%259D%25E5%2585%2589%25EF%25BC%2581%25E4%25BD%259B%25E5%25B1%25B1%25E4%25B8%2589%25E6%2597%25A7%25E6%2594%25B9%25E9%2580%25A0%25E5%25AE%25A3%25E4%25BC%25A0%25E5%25A4%25A7%25E7%2589%2587%25E5%2587%25BA%25E7%2582%2589&ct=1530443859&abtest_cookie=BAABAAoACwAMABIACgA%2Bix4A44seAEKPHgBllR4AepUeAICVHgDwlR4AOJYeAJ2WHgC1lh4AAAA%3D&devicetype=android-26&version=26060739&is_need_ticket=0&is_need_ad=1&comment_id=349831597094109186&is_need_reward=0&both_ad=0&reward_uin_count=0&send_time=&msg_daily_idx=1&is_original=0&is_only_read=1&req_id=030920599jFyODX9v0PULyo0&pass_ticket=lmz4dXv%25252FWib0B0%25252B0lpXZZ8VPthtTPqPnjpwYcH6p5usaQBW%25252FdJNeVlTua%25252FCMp8Ki&is_temp_url=0&item_show_type=undefined&tmp_version=1' headers = '''Host: jin.baidu.com Connection: keep-alive Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Referer: https://jin.baidu.com/v/static/mip2/gongjijin-mip2/mip-login.html?wyn=5213da38-73b8-48ab-adb0-dfd7b9380aff Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9 Cookie: BAIDUID=B2C24DC33FBE42CE4C613FF24AD6DDBE:FG=1; BIDUPSID=B2C24DC33FBE42CE4C613FF24AD6DDBE; PSTM=1528341053; pgv_pvi=4125007872; BDRCVFR[IzI_eUGSZP3]=mbxnW11j9Dfmh7GuZR8mvqV; delPer=0; PSINO=6; pgv_si=s6237508608; ZD_ENTRY=google; BDUSS=kJiaThuZDhvZkhFRTdQckZJeU52cGNoNzVDRzhYYjZDWnl2Y3RBNk5zMEVIZ3BjQVFBQUFBJCQAAAAAAAAAAAEAAACn~KxI0MfG2rDLX7K7t8W82QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASR4lsEkeJbf; H_PS_PSSID=1441_25810_21102_18559_20882_27508''' main()
[ "574613576@qq.com" ]
574613576@qq.com
9f01b0a8f9ec6d29aba97973f582194564ec31b4
1924da60fa3298e386acc6dac9bd390784a9b5bb
/test57.py
5c6a319152b336f3c4ea818e87668b062f0e03ec
[]
no_license
yukitomo/NLP100DrillExercises
c8a177b56f798cef225ace540e965809a1fc1fbc
ea2ceb366de1fa1f27d084e3b9328cc6f34ac1dd
refs/heads/master
2020-06-01T02:55:11.423238
2015-06-10T15:39:03
2015-06-10T15:39:03
37,205,750
1
0
null
null
null
null
UTF-8
Python
false
false
884
py
#!/usr/bin/python #-*-coding:utf-8-*- #2014-12-14 Yuki Tomo #(57) (56)を修正し,非自立語は出力に含めないようにせよ #cat test51_japanese.txt|python test57.py import sys from test52 import Morph from test53 import Chunk,cabtxt2chunk_inputter from collections import defaultdict def show_dependency_indynoun_verb(text): for i in range(len(text)): for j in range(len(text[i])): dst = text[i][j].dst if not dst == -1 : #係り元文節 text[i][j] #係り先文節 text[i][dst] if text[i][j].noun_in() and text[i][dst].verb_in(): #それぞれ名詞、動詞を含むか #非自立語は除去 print "%s\t%s"%(text[i][j].phrase_independent(), text[i][dst].phrase_independent()) else: pass def main(): text_chunk = cabtxt2chunk_inputter(sys.stdin) show_dependency_indynoun_verb(text_chunk) if __name__ == '__main__': main()
[ "over.the.tr0ouble@gmail.com" ]
over.the.tr0ouble@gmail.com
7f1d0a8ce4c9888b733f77c5f659c376afbf1b78
9f2445e9a00cc34eebcf3d3f60124d0388dcb613
/2019-04-02-Traub1991/plot_steadystate_constants.py
b77e2617830947d93bdfdab0f5048daf51f56e97
[]
no_license
analkumar2/Thesis-work
7ee916d71f04a60afbd117325df588908518b7d2
75905427c2a78a101b4eed2c27a955867c04465c
refs/heads/master
2022-01-02T02:33:35.864896
2021-12-18T03:34:04
2021-12-18T03:34:04
201,130,673
0
1
null
null
null
null
UTF-8
Python
false
false
5,573
py
#Author - Anal Kumar #disclaimer - The code uses eval() function. Use at your own discretion. import moose import rdesigneur as rd import numpy as np import matplotlib.pyplot as plt import Channelprotos as Cp #Channelprotos and rdesigneurProtos should be in the same directory as the pwd try: moose.delete('/model') moose.delete('/library') except: pass Cp_list = dir(Cp) #getting a list of all variables and functions in the Channelprotos and rdesigneurProtos for func in Cp_list: #Channelprotos if callable( eval('Cp.%s' %(func)) ): #checking if its a function or another variable moose.Neutral('/library') #setting up library try: eval('Cp.%s(\'%s\')' %(func, func)) # setting up the channel Chan = moose.element('/library/' + func) except: continue if Chan.className == 'HHChannel': #use this if the channel setup is HHChanel #Xgate if Chan.Xpower >=1 and Chan.instant != 1: Chanxgate = moose.element(Chan.path + '/gateX') min = Chanxgate.min max = Chanxgate.max minf = Chanxgate.tableA/Chanxgate.tableB tau = 1/Chanxgate.tableB plt.figure(0) plt.plot(np.linspace(min, max, len(minf)), minf, color = 'red', label = 'mInfinity') plt.xlabel('Membrane potential (V)') plt.ylabel('mInfinity') plt.title(func + ' mInfinity for its x gate') plt.legend() plt.savefig('./gateparams/Cp_' + func + '_xgate_mInf.png') plt.figure(1) plt.plot(np.linspace(min, max, len(tau)), tau, color = 'blue', label = 'Tau') plt.xlabel('Membrane potential (V)') plt.ylabel('Time constant (s)') plt.title(func + ' time constant for its x gate') plt.legend() plt.savefig('./gateparams/Cp_' + func + '_xgate_tau.png') plt.close('all') # Ygate if Chan.Ypower >=1 and Chan.instant != 2: Chanygate = moose.element(Chan.path + '/gateY') min = Chanygate.min max = Chanygate.max minf = Chanygate.tableA/Chanygate.tableB tau = 1/Chanygate.tableB plt.figure(0) plt.plot(np.linspace(min, max, len(minf)), minf, color = 'red', label = 'mInfinity') plt.xlabel('Membrane potential (V)') plt.ylabel('mInfinity') plt.title(func + ' mInfinity for its y gate') plt.legend() plt.savefig('./gateparams/Cp_' + func + '_ygate_mInf.png') plt.figure(1) plt.plot(np.linspace(min, max, len(tau)), tau, color = 'blue', label = 'Tau') plt.xlabel('Membrane potential (V)') plt.ylabel('Time constant (s)') plt.title(func + ' time constant for its y gate') plt.legend() plt.savefig('./gateparams/Cp_' + func + '_ygate_tau.png') plt.close('all') # Zgate if Chan.Zpower >=1 and Chan.instant != 4 and Chan.useConcentration == 0: Chanzgate = moose.element(Chan.path + '/gateZ') min = Chanzgate.min max = Chanzgate.max minf = Chanzgate.tableA/Chanzgate.tableB tau = 1/Chanzgate.tableB plt.figure(0) plt.plot(np.linspace(min, max, len(minf)), minf, color = 'red', label = 'mInfinity') plt.xlabel('Membrane potential (V)') plt.ylabel('mInfinity') plt.title(func + ' mInfinity for its z gate') plt.legend() plt.savefig('./gateparams/Cp_' + func + '_zgate_mInf.png') plt.figure(1) plt.plot(np.linspace(min, max, len(tau)), tau, color = 'blue', label = 'Tau') plt.xlabel('Membrane potential (V)') plt.ylabel('Time constant (s)') plt.title(func + ' time constant for its z gate') plt.legend() plt.savefig('./gateparams/Cp_' + func + '_zgate_tau.png') plt.close('all') elif Chan.Zpower >=1 and Chan.instant != 4 and Chan.useConcentration == 1: Chanzgate = moose.element(Chan.path + '/gateZ') min = Chanzgate.min max = Chanzgate.max minf = Chanzgate.tableA/Chanzgate.tableB tau = 1/Chanzgate.tableB plt.figure(0) plt.plot(np.linspace(min, max, len(minf)), minf, color = 'red', label = 'mInfinity') plt.xlabel('Calcium concentration (mol/m^3)') plt.ylabel('mInfinity') plt.title(func + ' mInfinity for its z gate') plt.legend() plt.savefig('./gateparams/Cp_' + func + '_zgate_mInf.png') plt.figure(1) plt.plot(np.linspace(min, max, len(tau)), tau, color = 'blue', label = 'Tau') plt.xlabel('Calcium concentration (mol/m^3)') plt.ylabel('Time constant (s)') plt.title(func + ' time constant for its z gate') plt.legend() plt.savefig('./gateparams/Cp_' + func + '_zgate_tau.png') plt.close('all') print 'Cp_' + str(func) moose.delete('/library')
[ "analkumar2@gmail.com" ]
analkumar2@gmail.com
408bc8142e8201c4f69273c94a5d7cc8a3391f73
f52c121da03c427a7b1a4f70d6c6d379869f338e
/CGAT/WrapperBl2Seq.py
2b72705164e87201f6a0724c9bde4859f7425fce
[ "BSD-2-Clause" ]
permissive
orianna14/cgat
7975e5cb8d907f2c83236a6e926d7f4230eb6788
7494d17f0a9e3f2333483426aef2c163f3fee0b1
refs/heads/master
2021-01-22T11:11:24.509030
2015-01-09T11:16:25
2015-01-09T11:16:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,850
py
########################################################################## # # MRC FGU Computational Genomics Group # # $Id$ # # Copyright (C) 2009 Andreas Heger # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ########################################################################## ''' WrapperBl2Seq.py - ====================================================== :Author: Andreas Heger :Release: $Id$ :Date: |today| :Tags: Python Code ---- ''' import os import sys import string import re import tempfile import subprocess import optparse """Wrapper for adaptive codon bias program """ from CGAT import Experiment as Experiment from CGAT import FastaIterator as FastaIterator class Bl2SeqError(Exception): pass class Bl2Seq: mOptions = "" mExecutable = "bl2seq" mStderr = sys.stderr def __init__(self, options=""): self.mOptions = options def CreateTemporaryFiles(self): """create temporary files.""" self.mTempDirectory = tempfile.mkdtemp() self.mFilenameTempInput = self.mTempDirectory + "/input" self.mFilenameTempOutput = self.mTempDirectory + "/output" def DeleteTemporaryFiles(self): """clean up.""" os.remove(self.mFilenameTempInput) os.remove(self.mFilenameTempOutput) os.rmdir(self.mTempDirectory) def SetStderr(self, file=None): """set file for dumping stderr.""" self.mStderr = file def WriteOutput(self, lines, filename_output=None): """write output to file. If file is not given, lines are written to stdout. """ if filename_output: outfile = open(filename_output, "w") else: outfile = sys.stdout outfile.write(string.join(lines, "")) if filename_output: outfile.close() def ParseResult(self, trace_file=None, information_file=None): result = AdaptiveCAIResult() result.Read(trace_file, information_file) return result def RunOnFile(self, infile, outfile, errfile): self.CreateTemporaryFiles() statement = string.join((self.mExecutable, self.mFilenameTempInput, self.mFilenameTempOutput), " ") i = FastaIterator.FastaIterator(infile) outfile.write("GENE\tBl2Seq\n") while 1: f = i.next() if f is None: break file = open(self.mFilenameTempInput, "w") file.write(">%s\n%s" % (f.title, f.sequence)) file.close() s = subprocess.Popen(statement, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.mTempDirectory, close_fds=True) (out, err) = s.communicate() if s.returncode != 0: raise Bl2SeqError, "Error in calculating Bl2Seq\n%s" % err d = open(self.mFilenameTempOutput).readlines()[2][:-1] enc = d.split(" ")[2] outfile.write((string.join((f.title, enc), "\t")) + "\n") errfile.write(err) self.DeleteTemporaryFiles() if __name__ == "__main__": parser = E.OptionParser( version="%prog version: $Id: WrapperBl2Seq.py 2781 2009-09-10 11:33:14Z andreas $") parser.add_option("-f", "--input-file", dest="input_filename", type="string", help="input filename. If '-', stdin is used [default=%default].", metavar="FILE") parser.add_option("-o", "--output-file", dest="output_filename", type="string", help="output filename for codon usage. If '-', output is stdout [default=%default].", metavar="FILE") parser.add_option("-e", "--error-file", dest="error_filename", type="string", help="output filename for error messages. If '-', output is stderr [default=%default].", metavar="FILE") parser.set_defaults( input_filename="-", output_filename="-", error_filename="/dev/null", ) (options, args) = Experiment.Start(parser) wrapper = Bl2Seq() if options.input_filename == "-": file_stdin = sys.stdin else: file_stdin = open(options.input_filename, "r") if options.output_filename: if options.output_filename == "-": file_stdout = sys.stdout else: file_stdout = open(options.output_filename, "w") if options.error_filename: if options.error_filename == "-": file_stderr = sys.stderr else: file_stderr = open(options.error_filename, "w") wrapper.RunOnFile(file_stdin, file_stdout, file_stderr) if file_stdin and file_stdin != sys.stdin: file_stdin.close() if file_stdout and file_stdout != sys.stdout: file_stdout.close() if file_stderr and file_stderr != sys.stderr: file_stderr.close() Experiment.Stop()
[ "andreas.heger@gmail.com" ]
andreas.heger@gmail.com
9585a4e4a65ef46efe897765a84b7e09465160f0
81acce1d49924d89e6ebf5a472ad5b1b80cc202c
/Draw2D.py
7f1ca89964823ded207e1bb4b4b9b8c0241f238d
[]
no_license
truggles/Z_to_TauTau_13TeV
36a85b024052fcfef3c9efd8aebc63dc85744f7b
123fe0d25f8e926d8959f54cd4f64122394b60d5
refs/heads/master
2021-03-13T01:50:43.031581
2017-10-12T18:56:25
2017-10-12T18:56:25
37,312,811
0
0
null
2016-09-29T08:29:13
2015-06-12T09:08:22
Python
UTF-8
Python
false
false
7,908
py
#!/usr/bin/env python import ROOT import re from array import array import math ROOT.gROOT.SetBatch(True) def add_lumi(): lowX=0.58 lowY=0.835 lumi = ROOT.TPaveText(lowX, lowY+0.06, lowX+0.30, lowY+0.16, "NDC") lumi.SetBorderSize( 0 ) lumi.SetFillStyle( 0 ) lumi.SetTextAlign( 12 ) lumi.SetTextColor( 1 ) lumi.SetTextSize(0.06) lumi.SetTextFont ( 42 ) lumi.AddText("2016, 35.9 fb^{-1} (13 TeV)") return lumi def add_CMS(): lowX=0.21 lowY=0.70 lumi = ROOT.TPaveText(lowX, lowY+0.06, lowX+0.15, lowY+0.16, "NDC") lumi.SetTextFont(61) lumi.SetTextSize(0.08) lumi.SetBorderSize( 0 ) lumi.SetFillStyle( 0 ) lumi.SetTextAlign( 12 ) lumi.SetTextColor( 1 ) lumi.AddText("CMS") return lumi def add_Preliminary(): lowX=0.21 lowY=0.63 lumi = ROOT.TPaveText(lowX, lowY+0.06, lowX+0.15, lowY+0.16, "NDC") lumi.SetTextFont(52) lumi.SetTextSize(0.06) lumi.SetBorderSize( 0 ) lumi.SetFillStyle( 0 ) lumi.SetTextAlign( 12 ) lumi.SetTextColor( 1 ) lumi.AddText("Preliminary") return lumi def make_legend(): output = ROOT.TLegend(0.65, 0.4, 0.92, 0.82, "", "brNDC") output.SetLineWidth(0) output.SetLineStyle(0) output.SetFillStyle(0) output.SetBorderSize(0) output.SetTextFont(62) return output import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--mthd', action='store', dest='mthd', help="Which method? FF or Standard?") args = parser.parse_args() print args.mthd ROOT.gStyle.SetFrameLineWidth(3) ROOT.gStyle.SetLineWidth(3) ROOT.gStyle.SetOptStat(0) c=ROOT.TCanvas("canvas","",0,0,1200,600) c.cd() file=ROOT.TFile("httShapes/htt/htt_tt.inputs-sm-13TeV_svFitMass2D-5040-Tight.root","r") adapt=ROOT.gROOT.GetColor(12) new_idx=ROOT.gROOT.GetListOfColors().GetSize() + 1 trans=ROOT.TColor(new_idx, adapt.GetRed(), adapt.GetGreen(),adapt.GetBlue(), "",0.5) categories= ["tt_boosted","tt_VBF",] categories= ["tt_0jet",] ncat=len(categories) for cat in categories: print cat Data=file.Get(cat).Get("data_obs") print Data.Integral() QCD=file.Get(cat).Get("QCD") W=file.Get(cat).Get("W") TT=file.Get(cat).Get("TTT") VV=file.Get(cat).Get("VV") #if not "2bjet" in cat : if W != None : VV.Add(W) ZL=file.Get(cat).Get("ZL") ZJ=file.Get(cat).Get("ZJ") if ZJ != None : ZL.Add(ZJ) ZTT=file.Get(cat).Get("ZTT") SMHiggs=file.Get(cat).Get("ggH125") SMHiggs.Add(file.Get(cat).Get("qqH125")) Data.GetXaxis().SetTitle("") Data.GetXaxis().SetTitleSize(0) Data.GetXaxis().SetNdivisions(505) Data.GetYaxis().SetLabelFont(42) Data.GetYaxis().SetLabelOffset(0.01) Data.GetYaxis().SetLabelSize(0.06) Data.GetYaxis().SetTitleSize(0.075) Data.GetYaxis().SetTitleOffset(1.04) Data.SetTitle("") Data.GetYaxis().SetTitle("Events/bin") QCD.SetFillColor(ROOT.TColor.GetColor("#ffccff")) VV.SetFillColor(ROOT.TColor.GetColor("#de5a6a")) TT.SetFillColor(ROOT.TColor.GetColor("#9999cc")) if not "2bjet" in cat : ZL.SetFillColor(ROOT.TColor.GetColor("#4496c8")) ZTT.SetFillColor(ROOT.TColor.GetColor("#ffcc66")) SMHiggs.SetLineColor(ROOT.kBlue) Data.SetMarkerStyle(20) Data.SetMarkerSize(1) QCD.SetLineColor(1) VV.SetLineColor(1) TT.SetLineColor(1) ZTT.SetLineColor(1) if not "2bjet" in cat : ZL.SetLineColor(1) Data.SetLineColor(1) Data.SetLineWidth(2) SMHiggs.SetLineWidth(2) stack=ROOT.THStack("stack","stack") stack.Add(QCD) stack.Add(VV) stack.Add(TT) if not "2bjet" in cat : stack.Add(ZL) stack.Add(ZTT) errorBand = QCD.Clone() errorBand.Add(VV) errorBand.Add(TT) if not "2bjet" in cat : errorBand.Add(ZL) errorBand.Add(ZTT) errorBand.SetMarkerSize(0) errorBand.SetFillColor(new_idx) errorBand.SetFillStyle(3001) errorBand.SetLineWidth(1) pad1 = ROOT.TPad("pad1","pad1",0,0.35,1,1) pad1.Draw() pad1.cd() pad1.SetFillColor(0) pad1.SetBorderMode(0) pad1.SetBorderSize(10) pad1.SetTickx(1) pad1.SetTicky(1) pad1.SetLeftMargin(0.18) pad1.SetRightMargin(0.05) pad1.SetTopMargin(0.122) pad1.SetBottomMargin(0.026) pad1.SetFrameFillStyle(0) pad1.SetFrameLineStyle(0) pad1.SetFrameLineWidth(3) pad1.SetFrameBorderMode(0) pad1.SetFrameBorderSize(10) Data.GetXaxis().SetLabelSize(0) Data.SetMaximum(Data.GetMaximum()*1.5) Data.Draw("e") stack.Draw("hist same") # Scale SMH x 10 higgsSF = 10. SMHiggs.Scale( higgsSF ) SMHiggs.Draw("histsame") errorBand.Draw("e2same") # Blind for bin in range(1, Data.GetNbinsX()+1): smh = SMHiggs.GetBinContent( bin ) / higgsSF bkg = stack.GetStack().Last().GetBinContent( bin ) if smh > 0. or bkg > 0. : sig = smh / math.sqrt( smh + bkg ) else : sig = 0. if sig > 0.1 : Data.SetBinContent( bin, 0. ) Data.SetBinError( bin, 0. ) Data.Draw("esamex0") legende=make_legend() legende.AddEntry(Data,"Observed","elp") legende.AddEntry(ZTT,"Z#rightarrow#tau_{h}#tau_{h}","f") if not "2bjet" in cat : legende.AddEntry(ZL,"DY others","f") legende.AddEntry(TT,"t#bar{t}+jets","f") legende.AddEntry(VV,"Electroweak","f") legende.AddEntry(QCD,"QCD multijet","f") legende.AddEntry(SMHiggs,"SM h(125) x %s" % higgsSF,"f") legende.AddEntry(errorBand,"Uncertainty","f") legende.Draw() l1=add_lumi() l1.Draw("same") l2=add_CMS() l2.Draw("same") l3=add_Preliminary() l3.Draw("same") pad1.RedrawAxis() categ = ROOT.TPaveText(0.21, 0.5+0.013, 0.43, 0.70+0.155, "NDC") categ.SetBorderSize( 0 ) categ.SetFillStyle( 0 ) categ.SetTextAlign( 12 ) categ.SetTextSize ( 0.06 ) categ.SetTextColor( 1 ) categ.SetTextFont ( 41 ) categ.AddText(cat) categ.Draw("same") c.cd() pad2 = ROOT.TPad("pad2","pad2",0,0,1,0.35); pad2.SetTopMargin(0.05); pad2.SetBottomMargin(0.35); pad2.SetLeftMargin(0.18); pad2.SetRightMargin(0.05); pad2.SetTickx(1) pad2.SetTicky(1) pad2.SetFrameLineWidth(3) pad2.SetGridx() pad2.SetGridy() pad2.Draw() pad2.cd() h1=Data.Clone() #h1.SetMaximum(1.5)#FIXME(1.5) #h1.SetMinimum(0.5)#FIXME(0.5) h1.SetMaximum(1.75)#FIXME(1.5) h1.SetMinimum(0.25)#FIXME(0.5) h1.SetMarkerStyle(20) h3=errorBand.Clone() hwoE=errorBand.Clone() for iii in range (1,hwoE.GetSize()-2): hwoE.SetBinError(iii,0) h3.Sumw2() h1.Sumw2() h1.SetStats(0) h1.Divide(hwoE) h3.Divide(hwoE) h1.GetXaxis().SetTitle("m_{#tau#tau} (GeV)") #h1.GetXaxis().SetTitle("m_{vis} (GeV)") #h1.GetXaxis().SetTitle("N_{charged}") h1.GetXaxis().SetLabelSize(0.08) h1.GetYaxis().SetLabelSize(0.08) h1.GetYaxis().SetTitle("Obs./Exp.") h1.GetXaxis().SetNdivisions(505) h1.GetYaxis().SetNdivisions(5) h1.GetXaxis().SetTitleSize(0.15) h1.GetYaxis().SetTitleSize(0.15) h1.GetYaxis().SetTitleOffset(0.56) h1.GetXaxis().SetTitleOffset(1.04) h1.GetXaxis().SetLabelSize(0.11) h1.GetYaxis().SetLabelSize(0.11) h1.GetXaxis().SetTitleFont(42) h1.GetYaxis().SetTitleFont(42) h1.Draw("ep") h3.Draw("e2same") c.cd() pad1.Draw() ROOT.gPad.RedrawAxis() c.Modified() #c.SaveAs("mVis"+cat+args.mthd+".pdf") #c.SaveAs("mVis"+cat+args.mthd+".png") date='Nov02' c.SaveAs("/afs/cern.ch/user/t/truggles/www/2D/"+date+"/mSV"+cat+args.mthd+".pdf") c.SaveAs("/afs/cern.ch/user/t/truggles/www/2D/"+date+"/mSV"+cat+args.mthd+".png") pad1.SetLogy() del legende Data.SetMaximum(Data.GetMaximum()*3) Data.SetMinimum(0.01) pad1.Update() c.SaveAs("/afs/cern.ch/user/t/truggles/www/2D/"+date+"/mSV"+cat+args.mthd+"log.pdf") c.SaveAs("/afs/cern.ch/user/t/truggles/www/2D/"+date+"/mSV"+cat+args.mthd+"log.png")
[ "truggles@wisc.edu" ]
truggles@wisc.edu
90d2a950603b34fd3f89912efe29b45abdb4d45a
2bb90b620f86d0d49f19f01593e1a4cc3c2e7ba8
/pardus/tags/2007.3/programming/languages/perl/XML-XQL/actions.py
e6165f4328993702d0ec62af5da1fff8f5818066
[]
no_license
aligulle1/kuller
bda0d59ce8400aa3c7ba9c7e19589f27313492f7
7f98de19be27d7a517fe19a37c814748f7e18ba6
refs/heads/master
2021-01-20T02:22:09.451356
2013-07-23T17:57:58
2013-07-23T17:57:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
456
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2006 TUBITAK/UEKAE # Licensed under the GNU General Public License, version 2. # See the file http://www.gnu.org/copyleft/gpl.txt. from pisi.actionsapi import perlmodules from pisi.actionsapi import pisitools def setup(): perlmodules.configure("/usr") def build(): perlmodules.make() def install(): perlmodules.install() pisitools.dodoc("Changes","README")
[ "yusuf.aydemir@istanbul.com" ]
yusuf.aydemir@istanbul.com
27a5fbcd017b34cabd64cefb4a53a4f4208369b8
a55ad28bbb4fa7edb534f6c1834e7aa00b7dbc2a
/ververica_api_sdk/models/job.py
b3cc3e3509886202781ef2aff5ddaa66edbccc8a
[]
no_license
justlikemikezz/ververica-api-sdk
df29dca99af00944aef5cf06b715e697752fada8
0eee284b4433f74b35fd2f41d149e619624aaed3
refs/heads/master
2020-12-22T16:01:43.588537
2020-01-29T00:39:34
2020-01-29T00:39:34
236,848,741
0
0
null
null
null
null
UTF-8
Python
false
false
5,421
py
# coding: utf-8 """ Application Manager API Application Manager APIs to control Apache Flink jobs # noqa: E501 OpenAPI spec version: 2.0.1 Contact: platform@ververica.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class Job(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_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. """ swagger_types = { 'api_version': 'str', 'kind': 'str', 'metadata': 'JobMetadata', 'spec': 'JobSpec', 'status': 'JobStatus' } attribute_map = { 'api_version': 'apiVersion', 'kind': 'kind', 'metadata': 'metadata', 'spec': 'spec', 'status': 'status' } def __init__(self, api_version=None, kind=None, metadata=None, spec=None, status=None): # noqa: E501 """Job - a model defined in Swagger""" # noqa: E501 self._api_version = None self._kind = None self._metadata = None self._spec = None self._status = None self.discriminator = None if api_version is not None: self.api_version = api_version if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata if spec is not None: self.spec = spec if status is not None: self.status = status @property def api_version(self): """Gets the api_version of this Job. # noqa: E501 :return: The api_version of this Job. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this Job. :param api_version: The api_version of this Job. # noqa: E501 :type: str """ self._api_version = api_version @property def kind(self): """Gets the kind of this Job. # noqa: E501 :return: The kind of this Job. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this Job. :param kind: The kind of this Job. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this Job. # noqa: E501 :return: The metadata of this Job. # noqa: E501 :rtype: JobMetadata """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this Job. :param metadata: The metadata of this Job. # noqa: E501 :type: JobMetadata """ self._metadata = metadata @property def spec(self): """Gets the spec of this Job. # noqa: E501 :return: The spec of this Job. # noqa: E501 :rtype: JobSpec """ return self._spec @spec.setter def spec(self, spec): """Sets the spec of this Job. :param spec: The spec of this Job. # noqa: E501 :type: JobSpec """ self._spec = spec @property def status(self): """Gets the status of this Job. # noqa: E501 :return: The status of this Job. # noqa: E501 :rtype: JobStatus """ return self._status @status.setter def status(self, status): """Sets the status of this Job. :param status: The status of this Job. # noqa: E501 :type: JobStatus """ self._status = status def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_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: result[attr] = value if issubclass(Job, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(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, Job): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "michael.handria@bird.co" ]
michael.handria@bird.co
207a7011a5837bad96395aed19342501aa663f78
a3cc7286d4a319cb76f3a44a593c4a18e5ddc104
/lib/surface/tasks/queues/resume.py
230674c0f92827e5d0fc9bf32cb2124351e7564d
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
jordanistan/Google-Cloud-SDK
f2c6bb7abc2f33b9dfaec5de792aa1be91154099
42b9d7914c36a30d1e4b84ae2925df7edeca9962
refs/heads/master
2023-09-01T01:24:53.495537
2023-08-22T01:12:23
2023-08-22T01:12:23
127,072,491
0
1
NOASSERTION
2023-08-22T01:12:24
2018-03-28T02:31:19
Python
UTF-8
Python
false
false
1,406
py
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """`gcloud tasks queues resume` command.""" from googlecloudsdk.api_lib.tasks import queues from googlecloudsdk.calliope import base from googlecloudsdk.command_lib.tasks import constants from googlecloudsdk.command_lib.tasks import flags from googlecloudsdk.command_lib.tasks import parsers from googlecloudsdk.core import log class Resume(base.Command): """Request to resume a paused or disabled queue.""" @staticmethod def Args(parser): flags.AddQueueResourceArg(parser, 'to resume') flags.AddLocationFlag(parser) def Run(self, args): queues_client = queues.Queues() queue_ref = parsers.ParseQueue(args.queue, args.location) log.warn(constants.QUEUE_MANAGEMENT_WARNING) queues_client.Resume(queue_ref) log.status.Print('Resumed queue [{}].'.format(queue_ref.Name()))
[ "jordan.robison@gmail.com" ]
jordan.robison@gmail.com
0d12a1eb786b8fb073816be57a8967bb4bb8891a
875188967ac96bdabc2780983ef2db32c8c727ef
/ebirdtaiwan/home/migrations/0006_auto_20200824_1303.py
e9cdb42fcf9d8df64348e88652a2c892ff30a1d9
[ "MIT" ]
permissive
even311379/EbirdTaiwan2020
b57ef8db79ef0d6b452016b6aa48bee2afe227b2
2c1aa4d7346b5ade909d45f7c245fa4988394124
refs/heads/master
2022-12-28T01:04:48.431595
2020-10-16T15:03:52
2020-10-16T15:03:52
289,954,202
0
0
null
null
null
null
UTF-8
Python
false
false
356
py
# Generated by Django 3.1 on 2020-08-24 13:03 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0005_auto_20200824_1301'), ] operations = [ migrations.RenameField( model_name='homepage', old_name='Title', new_name='Why', ), ]
[ "even311379@hotmail.com" ]
even311379@hotmail.com
e93167fdb787888ff891a9b26a2a79b76ce27430
f202ac96ff532c5dfba9914cc5b0c843c9ad34e1
/parlai/agents/programr/processors/post/denormalize.py
d05d38b9c718e33a2958870d12afecede2d0e06c
[ "MIT" ]
permissive
roholazandie/ParlAI
3caf2c913bbe6a4c2e7e7eee5674d7786eca5427
32352cab81ecb666aefd596232c5ed9f33cbaeb9
refs/heads/master
2021-12-02T01:30:09.548622
2021-10-19T17:38:23
2021-10-19T17:38:23
187,677,302
0
0
MIT
2021-06-24T21:44:34
2019-05-20T16:31:52
Python
UTF-8
Python
false
false
497
py
from parlai.agents.programr.utils.logging.ylogger import YLogger from parlai.agents.programr.processors.processing import PostProcessor DEBUG = False class DenormalizePostProcessor(PostProcessor): def __init__(self): super().__init__() def process(self, word_string): # denormalized = brain.denormals.denormalise_string(word_string) # if DEBUG: YLogger.debug(brain, "Denormalising input from [%s] to [%s]", word_string, denormalized) return word_string
[ "hilbert.cantor@gmail.com" ]
hilbert.cantor@gmail.com
b48dd591d3492478f1c4606a1de80669a3716b41
9b1cf71a9b744b66276701ef76ed3a4190b1bd84
/kcliutils/utils/texts/core_texts/readme.py
4dbab9971fb669563ee1b0136eeee6b4f6a45ee1
[ "MIT" ]
permissive
kkristof200/py_cli_utils
f9678ae5de322e558f3c29f9fede546f73d95db2
8c18ea37e84be5e7df1f5fcf7cdc10ae70ecf7c6
refs/heads/main
2023-07-18T10:02:02.783816
2021-09-06T20:35:43
2021-09-06T20:35:43
331,058,727
0
0
null
null
null
null
UTF-8
Python
false
false
252
py
readme = ''' # [PACKAGE_NAME] [SHIELDS] ## Description [DESCRIPTION] ## Install ~~~~bash pip install [PACKAGE_NAME] # or pip3 install [PACKAGE_NAME] ~~~~ ## Usage ~~~~python import [PACKAGE_NAME] ~~~~ ## Dependencies [DEPENDENCIES] '''.strip()
[ "kovacskristof200@gmail.com" ]
kovacskristof200@gmail.com
fd564c59e983ccc78fb0dc633639dc628bc55e09
a34507bee8dc5502c663a71f3e98257f8ff0334d
/easy/326-3的幂.py
466aedce67d6f53f2b802168fd8b4e5de6ccb34c
[]
no_license
michelleweii/Leetcode
85b7876a3e283f3982dd86de01ccc5470e63388f
0c09b5a018e7334bd49dd251834fc8e547084cc1
refs/heads/master
2022-05-17T07:28:23.684720
2022-04-28T12:40:48
2022-04-28T12:40:48
149,776,312
3
2
null
null
null
null
UTF-8
Python
false
false
971
py
# 利用pow(a, b)函数即可。需要开a的r次方则pow(a, 1/r)。 # 用取余! python除法/都保留小数点后的数字的 # 不知道为什么leetcode上报错 # class Solution(object): # def isPowerOfThree(self, n): # """ # :type n: int # :rtype: bool # """ # if n==0: # return False # else: # rs = pow(n,1/3) # if 3**int(rs) == n: # return True # return False class Solution: def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ while n > 1 : l = list(map(int, str(n))) # 妙! if sum(l) % 3 == 0: n = n // 3 else: return False if n <= 0: return False return True def main(): n= 27 myResult = Solution() print(myResult.isPowerOfThree(n)) if __name__ == '__main__': main()
[ "641052383@qq.com" ]
641052383@qq.com
11a68425333067afa7dc3f201861931da7d6047d
ae12996324ff89489ded4c10163f7ff9919d080b
/LeetCodePython/CanPlaceFlowers.py
0358e0ea494a51eb3138962f4b54b4310d1f6b00
[]
no_license
DeanHe/Practice
31f1f2522f3e7a35dc57f6c1ae74487ad044e2df
3230cda09ad345f71bb1537cb66124ec051de3a5
refs/heads/master
2023-07-05T20:31:33.033409
2023-07-01T18:02:32
2023-07-01T18:02:32
149,399,927
1
1
null
null
null
null
UTF-8
Python
false
false
1,130
py
""" You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule. Example 1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: true Example 2: Input: flowerbed = [1,0,0,0,1], n = 2 Output: false Constraints: 1 <= flowerbed.length <= 2 * 10^4 flowerbed[i] is 0 or 1. There are no two adjacent flowers in flowerbed. 0 <= n <= flowerbed.length """ from typing import List class CanPlaceFlowers: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: cnt = 0 for i in range(len(flowerbed)): pre, nxt = i - 1, i + 1 if (pre < 0 or flowerbed[pre] == 0) and (nxt >= len(flowerbed) or flowerbed[nxt] == 0): if flowerbed[i] == 0: flowerbed[i] = 1 cnt += 1 if cnt >= n: return True return False
[ "tengda.he@gmail.com" ]
tengda.he@gmail.com