blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2
values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220
values | src_encoding stringclasses 30
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 2 10.3M | extension stringclasses 257
values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
195b54472a950b19d6d0200f9b752439765b50c7 | c6a6f78f27f476df9821d6db6feee076ab1837a2 | /user/put.py | 247b5a9223193a9e94d1c2f53192c20c57d193ac | [] | no_license | tarasinf/accure | 1c925de019dc089125fd2f6ff69f6b40f241e7ba | 1374b8568eaea0c4d8d31b11f48e002319718c98 | refs/heads/master | 2021-01-20T06:55:08.794939 | 2017-03-06T07:21:39 | 2017-03-06T07:21:39 | 83,879,163 | 3 | 0 | null | 2017-03-06T07:21:40 | 2017-03-04T08:31:22 | Python | UTF-8 | Python | false | false | 2,476 | py | import json
import time
import logging
import os
import decimalencoder
import boto3
dynamodb = boto3.resource('dynamodb')
def put(event, context):
data = json.loads(event['body'])
# if 'text' not in data or 'checked' not in data:
# logging.error("Validation Failed")
# raise Exception("Couldn't update the user item.")
# return
timestamp = int(time.time() * 1000)
table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
# update the user in the database
expressionAttributeNames = {}
expressionAttributeValues = {':updatedAt': timestamp}
updateExpression = 'SET updatedAt = :updatedAt'
if 'friends' in data:
expressionAttributeNames['#user_friends'] = 'friends'
expressionAttributeValues[':friends'] = data['friends']
updateExpression += ', #user_friends = :friends'
if 'FCMToken' in data:
expressionAttributeNames['#user_FCMToken'] = 'FCMToken'
expressionAttributeValues[':FCMToken'] = data['FCMToken']
updateExpression += ', #user_FCMToken = :FCMToken'
if 'firstName' in data:
expressionAttributeNames['#user_firstName'] = 'firstName'
expressionAttributeValues[':firstName'] = data['firstName']
updateExpression += ', #user_firstName = :firstName'
if 'lastName' in data:
expressionAttributeNames['#user_lastName'] = 'lastName'
expressionAttributeValues[':lastName'] = data['lastName']
updateExpression += ', #user_lastName = :lastName'
if 'avatar' in data:
expressionAttributeNames['#user_avatar'] = 'avatar'
expressionAttributeValues[':avatar'] = data['avatar']
updateExpression += ', #user_avatar = :avatar'
if 'ownLocations' in data:
expressionAttributeNames['#user_ownLocations'] = 'ownLocations'
expressionAttributeValues[':ownLocations'] = data['ownLocations']
updateExpression += ', #user_ownLocations = :ownLocations'
result = table.update_item(
Key={
'id': event['pathParameters']['id']
},
ExpressionAttributeNames=expressionAttributeNames,
ExpressionAttributeValues=expressionAttributeValues,
UpdateExpression=updateExpression,
ReturnValues='ALL_NEW',
)
# create a response
response = {
"statusCode": 200,
"body": json.dumps(result['Attributes'],
cls=decimalencoder.DecimalEncoder)
}
return response
| [
"tarasinf2013@gmail.com"
] | tarasinf2013@gmail.com |
179a2ae9fb649252b7b18de35de828f4c023da6b | 2e747ec5306b75ab7fca1b0300c3a0185d353a3a | /Article/urls.py | 793df92546b97ff34a3d416cdb50d9532d416cc5 | [] | no_license | Liaoyingjie/Blog | eef7a035301f08f409bb455c83c485213fe3dfc4 | b2ab182c20d25709a9b85d940429736d0713a19f | refs/heads/master | 2022-11-01T18:05:55.436519 | 2020-06-06T10:51:04 | 2020-06-06T10:51:04 | 269,859,607 | 0 | 1 | null | 2022-09-29T16:57:02 | 2020-06-06T03:51:35 | Python | UTF-8 | Python | false | false | 204 | py | from django.urls import path
from . import views
urlpatterns = [
path('<int:article_id>', views.article_detail, name='article_detail_url'),
path('', views.article_list, name='article_list_url')
] | [
"lyjiwy@163.com"
] | lyjiwy@163.com |
be9014533c6f0b97962e8c6e295b02007fc03b1f | cad58c0bb847e5077c5e4b32d2bd6b00e24c7e2d | /checkout/admin.py | 24e63f312a8d304ebc669d986ca7c8a378922970 | [] | no_license | NeiloErnesto89/FullStack_Django_MS4_MaChine | cc8a57180ac750c6d5333232d2fc13843aa501d7 | e489d1cc2d6129a2c42270b5aeacfe62c36ea40c | refs/heads/master | 2022-12-07T10:55:39.157851 | 2020-10-09T21:10:55 | 2020-10-09T21:10:55 | 252,693,669 | 2 | 1 | null | 2022-11-22T06:32:52 | 2020-04-03T09:54:58 | JavaScript | UTF-8 | Python | false | false | 268 | py | from django.contrib import admin
from .models import Order, OrderLineItem
class OrderLineAdminInline(admin.TabularInline):
model = OrderLineItem
class OrderAdmin(admin.ModelAdmin):
inlines = (OrderLineAdminInline, )
admin.site.register(Order, OrderAdmin) | [
"neil.smyth1989@hotmail.com"
] | neil.smyth1989@hotmail.com |
26b7a606afbb7eb2f327d97444d30625b6855761 | ba5a7a0077fb2ace5f5dd87bef8224b0aaa40d7e | /OpenCv.py | ba8692bd926228454a846bdc0fe562b090aa02c2 | [] | no_license | ahmetiltersahin/KARRP | 7827f901abd2754fa9738c859501b2a2fdd0899a | c41a28a1e9102fb6ebfe55fcf5d6cd18af9a8635 | refs/heads/master | 2023-08-06T09:24:19.494812 | 2021-09-30T00:29:00 | 2021-09-30T00:29:00 | 411,860,549 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,945 | py | import cv2
import mediapipe as mp
import time
cap = cv2.VideoCapture("Videos/1.mp4")
pTime = 0
mpFaceDetection = mp.solutions.face_detection
mpDraw = mp.solutions.drawing_utils
faceDetection = mpFaceDetection.FaceDetection(0.75)
while True:
success, img = cap.read()
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
results = faceDetection.process(imgRGB)
print(results)
if results.detections:
for id, detection in enumerate(results.detections):
# mpDraw.draw_detection(img, detection)
# print(id, detection)
# print(detection.score)
# print(detection.location_data.relative_bounding_box)
bboxC = detection.location_data.relative_bounding_box
ih, iw, ic = img.shape
bbox = int(bboxC.xmin * iw), int(bboxC.ymin * ih), \
int(bboxC.width * iw), int(bboxC.height * ih)
cv2.rectangle(img, bbox, (255, 0, 255), 2)
cv2.putText(img, f'{int(detection.score[0] * 100)}%',
(bbox[0], bbox[1] - 20), cv2.FONT_HERSHEY_PLAIN,
2, (255, 0, 255), 2)
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(img, f'FPS: {int(fps)}', (20, 70), cv2.FONT_HERSHEY_PLAIN,
3, (0, 255, 0), 2)
cv2.imshow("Image", img)
cv2.waitKey(1)
FaceDetectionModule.py
import cv2
import mediapipe as mp
import time
class FaceDetector():
def __init__(self, minDetectionCon=0.5):
self.minDetectionCon = minDetectionCon
self.mpFaceDetection = mp.solutions.face_detection
self.mpDraw = mp.solutions.drawing_utils
self.faceDetection = self.mpFaceDetection.FaceDetection(self.minDetectionCon)
def findFaces(self, img, draw=True):
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
self.results = self.faceDetection.process(imgRGB)
# print(self.results)
bboxs = []
if self.results.detections:
for id, detection in enumerate(self.results.detections):
bboxC = detection.location_data.relative_bounding_box
ih, iw, ic = img.shape
bbox = int(bboxC.xmin * iw), int(bboxC.ymin * ih), \
int(bboxC.width * iw), int(bboxC.height * ih)
bboxs.append([id, bbox, detection.score])
if draw:
img = self.fancyDraw(img,bbox)
cv2.putText(img, f'{int(detection.score[0] * 100)}%',
(bbox[0], bbox[1] - 20), cv2.FONT_HERSHEY_PLAIN,
2, (255, 0, 255), 2)
return img, bboxs
def fancyDraw(self, img, bbox, l=30, t=5, rt= 1):
x, y, w, h = bbox
x1, y1 = x + w, y + h
cv2.rectangle(img, bbox, (255, 0, 255), rt)
# Top Left x,y
cv2.line(img, (x, y), (x + l, y), (255, 0, 255), t)
cv2.line(img, (x, y), (x, y+l), (255, 0, 255), t)
# Top Right x1,y
cv2.line(img, (x1, y), (x1 - l, y), (255, 0, 255), t)
cv2.line(img, (x1, y), (x1, y+l), (255, 0, 255), t)
# Bottom Left x,y1
cv2.line(img, (x, y1), (x + l, y1), (255, 0, 255), t)
cv2.line(img, (x, y1), (x, y1 - l), (255, 0, 255), t)
# Bottom Right x1,y1
cv2.line(img, (x1, y1), (x1 - l, y1), (255, 0, 255), t)
cv2.line(img, (x1, y1), (x1, y1 - l), (255, 0, 255), t)
return img
def main():
cap = cv2.VideoCapture("Videos/6.mp4")
pTime = 0
detector = FaceDetector()
while True:
success, img = cap.read()
img, bboxs = detector.findFaces(img)
print(bboxs)
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(img, f'FPS: {int(fps)}', (20, 70), cv2.FONT_HERSHEY_PLAIN, 3, (0, 255, 0), 2)
cv2.imshow("Image", img)
cv2.waitKey(1)
if __name__ == "__main__":
main()
| [
"56512950+ahmetiltersahin@users.noreply.github.com"
] | 56512950+ahmetiltersahin@users.noreply.github.com |
55b8d158657135087ec4fc1413c6d251ce3cc8db | 1f60db1816597c11b3dc0a33275fe731a2da0dee | /user/serializers.py | 8bba6d4291683df553f4f5a502716d16395682aa | [
"MIT"
] | permissive | Sunbird-Ed/evolve-api | cb36b383dc010168948baeba19a5742e4933547f | 371b39422839762e32401340456c13858cb8e1e9 | refs/heads/master | 2022-12-04T00:25:54.379252 | 2019-12-16T10:18:02 | 2019-12-16T10:18:02 | 172,674,340 | 1 | 0 | MIT | 2022-11-22T03:27:51 | 2019-02-26T08:56:14 | Python | UTF-8 | Python | false | false | 1,379 | py | from rest_framework import routers, serializers
from django.contrib.auth.models import User
from rest_framework.serializers import ModelSerializer
from .models import UserDetails,Roles
from apps.configuration.models import State
from django.contrib.auth.models import User
class UserDetailSerializer(ModelSerializer):
user=serializers.SerializerMethodField()
role=serializers.SerializerMethodField()
state=serializers.SerializerMethodField()
class Meta:
model = UserDetails
fields = ['role','user','state']
def get_user(self,req):
user = User.objects.filter(id=req.user.id)
serializer=UserSerializer(user,many=True)
return serializer.data
def get_state(self,req):
role = State.objects.filter(id=req.state.id)
serializer=StateSerializer(role,many=True)
return serializer.data
def get_role(self,req):
user = Roles.objects.filter(id=req.role.id)
serializer=RoleSerializer(user,many=True)
return serializer.data
class UserSerializer(ModelSerializer):
class Meta:
model=User
fields=['id','username','is_active','groups']
class StateSerializer(ModelSerializer):
class Meta:
model=State
fields='__all__'
class RoleSerializer(ModelSerializer):
class Meta:
model=Roles
fields='__all__'
| [
"tanvir@mantralabsglobal.com"
] | tanvir@mantralabsglobal.com |
5f7532ac384b9126d4e775efe47b6ea061d960b9 | 55c102589c6cda20cde60842323a86b182183b15 | /backend/apps/mdjcelery/adminx.py | 9891032fa4882f04b16b3415261bb91b6daf3c5f | [] | no_license | amtech/opengalaxy-workflow | e1290ce30f49af331e4c2d908b58babb38565580 | 5b6745e83120a644fbdbf18237ee68cdf4239cf2 | refs/heads/master | 2023-05-13T00:18:32.470262 | 2020-04-21T10:33:32 | 2020-04-21T10:33:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 571 | py | # -*- coding: utf-8 -*-
from djcelery.models import TaskState, WorkerState, PeriodicTask, IntervalSchedule, CrontabSchedule
from xadmin.sites import site
from .models import *
class TaskAdmin(object):
list_display = ['name', 'cname','create_time']
site.register(Task, TaskAdmin)
site.register(IntervalSchedule) # 存储循环任务设置的时间
site.register(CrontabSchedule) # 存储定时任务设置的时间
site.register(PeriodicTask) # 存储任务
site.register(TaskState) # 存储任务执行状态
site.register(WorkerState) # 存储执行任务的worker | [
"sunming@huohua.cn"
] | sunming@huohua.cn |
19f84d78ea975a69dd34b0cb4694ae95e40e2bbb | b2b401bd6f15a152cfeeef32de66c0c456dc4189 | /airdialogue/evaluator/metrics/rouge.py | 51d7676309295769bbbca192b49ef975b4d9e0bd | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | HMJiangGatech/airdialogue | dbc30f9068a17b862d7371be288d53592eba0500 | fca56769fefec2f1ecccb309cf666e368166473f | refs/heads/master | 2022-11-18T10:36:35.596037 | 2020-07-15T16:40:03 | 2020-07-15T16:40:03 | 270,094,426 | 0 | 0 | Apache-2.0 | 2020-06-06T20:20:45 | 2020-06-06T20:20:45 | null | UTF-8 | Python | false | false | 10,855 | py | # Copyright 2019 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
#
# https://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.
"""ROUGE metric implementation.
Copy from tf_seq2seq/seq2seq/metrics/rouge.py.
This is a modified and slightly extended verison of
https://github.com/miso-belica/sumy/blob/dev/sumy/evaluation/rouge.py.
"""
import itertools
import numpy as np
def _get_ngrams(n, text):
"""Calcualtes n-grams.
Args:
n: which n-grams to calculate
text: An array of tokens
Returns:
A set of n-grams
"""
ngram_set = set()
text_length = len(text)
max_index_ngram_start = text_length - n
for i in range(max_index_ngram_start + 1):
ngram_set.add(tuple(text[i:i + n]))
return ngram_set
def _split_into_words(sentences):
"""Splits multiple sentences into words and flattens the result."""
return list(itertools.chain(*[_.split(" ") for _ in sentences]))
def _get_word_ngrams(n, sentences):
"""Calculates word n-grams for multiple sentences."""
assert len(sentences) > 0
assert n > 0
words = _split_into_words(sentences)
return _get_ngrams(n, words)
def _len_lcs(x, y):
"""
Returns the length of the Longest Common Subsequence between sequences x
and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns
integer: Length of LCS between x and y
"""
table = _lcs(x, y)
n, m = len(x), len(y)
return table[n, m]
def _lcs(x, y):
"""
Computes the length of the longest common subsequence (lcs) between two
strings. The implementation below uses a DP programming algorithm and runs
in O(nm) time where n = len(x) and m = len(y).
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: collection of words
y: collection of words
Returns:
Table of dictionary of coord and len lcs
"""
n, m = len(x), len(y)
table = dict()
for i in range(n + 1):
for j in range(m + 1):
if i == 0 or j == 0:
table[i, j] = 0
elif x[i - 1] == y[j - 1]:
table[i, j] = table[i - 1, j - 1] + 1
else:
table[i, j] = max(table[i - 1, j], table[i, j - 1])
return table
def _recon_lcs(x, y):
"""
Returns the Longest Subsequence between x and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns:
sequence: LCS of x and y
"""
i, j = len(x), len(y)
table = _lcs(x, y)
def _recon(i, j):
"""private recon calculation"""
if i == 0 or j == 0:
return []
elif x[i - 1] == y[j - 1]:
return _recon(i - 1, j - 1) + [(x[i - 1], i)]
elif table[i - 1, j] > table[i, j - 1]:
return _recon(i - 1, j)
else:
return _recon(i, j - 1)
recon_tuple = tuple([x[0] for x in _recon(i, j)])
return recon_tuple
def rouge_n(evaluated_sentences, reference_sentences, n=2):
"""
Computes ROUGE-N of two text collections of sentences.
Sourece: http://research.microsoft.com/en-us/um/people/cyl/download/
papers/rouge-working-note-v1.3.1.pdf
Args:
evaluated_sentences: The sentences that have been picked by the summarizer
reference_sentences: The sentences from the referene set
n: Size of ngram. Defaults to 2.
Returns:
A tuple (f1, precision, recall) for ROUGE-N
Raises:
ValueError: raises exception if a param has len <= 0
"""
if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
evaluated_ngrams = _get_word_ngrams(n, evaluated_sentences)
reference_ngrams = _get_word_ngrams(n, reference_sentences)
reference_count = len(reference_ngrams)
evaluated_count = len(evaluated_ngrams)
# Gets the overlapping ngrams between evaluated and reference
overlapping_ngrams = evaluated_ngrams.intersection(reference_ngrams)
overlapping_count = len(overlapping_ngrams)
# Handle edge case. This isn't mathematically correct, but it's good enough
if evaluated_count == 0:
precision = 0.0
else:
precision = overlapping_count / evaluated_count
if reference_count == 0:
recall = 0.0
else:
recall = overlapping_count / reference_count
f1_score = 2.0 * ((precision * recall) / (precision + recall + 1e-8))
# return overlapping_count / reference_count
return f1_score, precision, recall
def _f_p_r_lcs(llcs, m, n):
"""
Computes the LCS-based F-measure score
Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Args:
llcs: Length of LCS
m: number of words in reference summary
n: number of words in candidate summary
Returns:
Float. LCS-based F-measure score
"""
r_lcs = llcs / m
p_lcs = llcs / n
beta = p_lcs / (r_lcs + 1e-12)
num = (1 + (beta**2)) * r_lcs * p_lcs
denom = r_lcs + ((beta**2) * p_lcs)
f_lcs = num / (denom + 1e-12)
return f_lcs, p_lcs, r_lcs
def rouge_l_sentence_level(evaluated_sentences, reference_sentences):
"""
Computes ROUGE-L (sentence level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = LCS(X,Y)/m
P_lcs = LCS(X,Y)/n
F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs)
where:
X = reference summary
Y = Candidate summary
m = length of reference summary
n = length of candidate summary
Args:
evaluated_sentences: The sentences that have been picked by the summarizer
reference_sentences: The sentences from the referene set
Returns:
A float: F_lcs
Raises:
ValueError: raises exception if a param has len <= 0
"""
if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
reference_words = _split_into_words(reference_sentences)
evaluated_words = _split_into_words(evaluated_sentences)
m = len(reference_words)
n = len(evaluated_words)
lcs = _len_lcs(evaluated_words, reference_words)
return _f_p_r_lcs(lcs, m, n)
def _union_lcs(evaluated_sentences, reference_sentence):
"""
Returns LCS_u(r_i, C) which is the LCS score of the union longest common
subsequence between reference sentence ri and candidate summary C. For example
if r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w7 w8 and
c2 = w1 w3 w8 w9 w5, then the longest common subsequence of r_i and c1 is
"w1 w2" and the longest common subsequence of r_i and c2 is "w1 w3 w5". The
union longest common subsequence of r_i, c1, and c2 is "w1 w2 w3 w5" and
LCS_u(r_i, C) = 4/5.
Args:
evaluated_sentences: The sentences that have been picked by the summarizer
reference_sentence: One of the sentences in the reference summaries
Returns:
float: LCS_u(r_i, C)
ValueError:
Raises exception if a param has len <= 0
"""
if len(evaluated_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
lcs_union = set()
reference_words = _split_into_words([reference_sentence])
combined_lcs_length = 0
for eval_s in evaluated_sentences:
evaluated_words = _split_into_words([eval_s])
lcs = set(_recon_lcs(reference_words, evaluated_words))
combined_lcs_length += len(lcs)
lcs_union = lcs_union.union(lcs)
union_lcs_count = len(lcs_union)
union_lcs_value = union_lcs_count / combined_lcs_length
return union_lcs_value
def rouge_l_summary_level(evaluated_sentences, reference_sentences):
"""
Computes ROUGE-L (summary level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = SUM(1, u)[LCS<union>(r_i,C)]/m
P_lcs = SUM(1, u)[LCS<union>(r_i,C)]/n
F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs)
where:
SUM(i,u) = SUM from i through u
u = number of sentences in reference summary
C = Candidate summary made up of v sentences
m = number of words in reference summary
n = number of words in candidate summary
Args:
evaluated_sentences: The sentences that have been picked by the summarizer
reference_sentence: One of the sentences in the reference summaries
Returns:
A float: F_lcs
Raises:
ValueError: raises exception if a param has len <= 0
"""
if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
# total number of words in reference sentences
m = len(_split_into_words(reference_sentences))
# total number of words in evaluated sentences
n = len(_split_into_words(evaluated_sentences))
union_lcs_sum_across_all_references = 0
for ref_s in reference_sentences:
union_lcs_sum_across_all_references += _union_lcs(evaluated_sentences,
ref_s)
return _f_p_r_lcs(union_lcs_sum_across_all_references, m, n)
def rouge(hypotheses, references):
"""Calculates average rouge scores for a list of hypotheses and
references"""
# Filter out hyps that are of 0 length
# hyps_and_refs = zip(hypotheses, references)
# hyps_and_refs = [_ for _ in hyps_and_refs if len(_[0]) > 0]
# hypotheses, references = zip(*hyps_and_refs)
# Calculate ROUGE-1 F1, precision, recall scores
rouge_1 = [
rouge_n([hyp], [ref], 1) for hyp, ref in zip(hypotheses, references)
]
rouge_1_f, rouge_1_p, rouge_1_r = list(map(np.mean, list(zip(*rouge_1))))
# Calculate ROUGE-2 F1, precision, recall scores
rouge_2 = [
rouge_n([hyp], [ref], 2) for hyp, ref in zip(hypotheses, references)
]
rouge_2_f, rouge_2_p, rouge_2_r = list(map(np.mean, list(zip(*rouge_2))))
# Calculate ROUGE-L F1, precision, recall scores
rouge_l = [
rouge_l_sentence_level([hyp], [ref])
for hyp, ref in zip(hypotheses, references)
]
rouge_l_f, rouge_l_p, rouge_l_r = list(map(np.mean, list(zip(*rouge_l))))
return {
"rouge_1/f_score": rouge_1_f,
"rouge_1/r_score": rouge_1_r,
"rouge_1/p_score": rouge_1_p,
"rouge_2/f_score": rouge_2_f,
"rouge_2/r_score": rouge_2_r,
"rouge_2/p_score": rouge_2_p,
"rouge_l/f_score": rouge_l_f,
"rouge_l/r_score": rouge_l_r,
"rouge_l/p_score": rouge_l_p,
}
| [
"josephch405@gmail.com"
] | josephch405@gmail.com |
4fe7931e387e9841b6f49f23c15ea81ab5aea77f | 2ab775f4c9afa9eaa982cd7f36563f3365c3d0e7 | /Aus_Home_Price/homePricePredict1.py | 23233b0447084ac0b2056d620248ea62048cf537 | [] | no_license | dhaval737/kaggle | 55442dd608151297b998e3f11247904314fd3c89 | ffc1d0beec9b367283f04a427fd4a99dd9356fb2 | refs/heads/master | 2022-09-04T12:47:19.517080 | 2020-05-27T16:55:12 | 2020-05-27T16:55:12 | 267,372,097 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,105 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 19 08:21:20 2020
@author: dhavaldangaria
"""
import pandas as pd
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
#saving file path to variable
mel_file_path='/Users/dhavaldangaria/Documents/Dhaval/kaggle/Aus_Home_Price/melb_data.csv'
#read teh data and store in DataFrame
mel_data=pd.read_csv(mel_file_path)
mel_features=['Rooms', 'Bathroom', 'Landsize', 'Lattitude', 'Longtitude']
X=mel_data[mel_features]
y=mel_data['Price']
train_X, val_X, train_y, val_y=train_test_split(X, y, random_state=1)
def get_mae(max_leaf_nodes,train_X, train_y, val_X, val_y):
model=DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=1)
model.fit(train_X, train_y)
preds_val= model.predict(val_X)
mae=mean_absolute_error(val_y, preds_val)
return mae
for i in [5,50,500,5000]:
my_mae=get_mae(i, train_X, train_y, val_X, val_y)
print("Max leaf nodes: %d \t\t mean abolute error: %d" %(i, my_mae))
| [
"dhaval737@gmail.com"
] | dhaval737@gmail.com |
b9fd420ff9cb37198ef9d9d480d07225dc750a1b | 839d8d7ccfa54d046e22e31a2c6e86a520ee0fb5 | /icore/base/list/dict_test.py | b6745b165a751dc40e63e211eac910f10f6e658e | [] | no_license | Erich6917/python_corepython | 7b584dda737ef914780decca5dd401aa33328af5 | 0176c9be2684b838cf9613db40a45af213fa20d1 | refs/heads/master | 2023-02-11T12:46:31.789212 | 2021-01-05T06:21:24 | 2021-01-05T06:21:24 | 102,881,831 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 222 | py | # -*- coding: utf-8 -*-
# @Time : 2017/12/26
# @Author : LIYUAN134
# @File : dict_test.py
# @Commment:
#
import dict as dict
def test1():
# dict.dict_mulkeys()
dict.dict_cal()
test1()
| [
"1065120559@qq.com"
] | 1065120559@qq.com |
1daea2ac2a1defde33ae9a11be03a139a2c7ca8a | df8a3c4a6117301f07e601a4e09d94e1a86324e8 | /src/todo/migrations/0001_initial.py | d96853df61c3519ef71eaad91905354cb7de1871 | [] | no_license | vincesesto/todobackend | d49c42650dd0972bf38a1147901a5c5f271501cc | 665e7ac6d3769c85a3825f2868017949cedbe50c | refs/heads/master | 2020-12-30T23:47:53.235174 | 2017-01-31T23:40:41 | 2017-01-31T23:40:41 | 80,575,802 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 794 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-01-25 00:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='TodoItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(blank=True, max_length=256, null=True)),
('completed', models.BooleanField(default=False)),
('url', models.CharField(blank=True, max_length=256, null=True)),
('order', models.IntegerField(blank=True, null=True)),
],
),
]
| [
"vince_sesto@mail.com"
] | vince_sesto@mail.com |
167d5666d310363bff214747518f0cb259e693b6 | e5de121d6a60a485abe82b92c8174800dc6be2b1 | /tornado_project_cms_oa/handlers/tasks/tasks_handlers.py | 881aae570d20d2c8815dd75d407951dd68a7596c | [] | no_license | shadowsmilezhou/tornado_project_cms_oa | aa09efaf30084d01fc59c78184b6f702d8db3a30 | b9f986183e8bc5c6c621a0948cec44f57d90d7ed | refs/heads/master | 2021-05-10T15:27:13.203004 | 2018-01-28T12:48:36 | 2018-01-28T12:48:36 | 118,551,439 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,520 | py | # -*- coding:utf-8 -*-
from datetime import datetime
from handlers.base.base_handler import BaseHandler
from models.tasks.tasks_publisher_accept_models import Tasks,CategoryTasks
from libs.tasks.tasks_lib import save_tasks_messages,save_category
class TaskPublishHanlder(BaseHandler):
def get(self):
task = Tasks()
categorys = CategoryTasks.all()
tasks_name = task.content
user_name = self.get_current_user().name
kw = {
'tasks_name':tasks_name,
'user_name':user_name,
'categorys':categorys,
}
self.render('tasks/tasks_publisher.html',**kw)
def post(self):
content = self.get_argument('content',None)
# category =self.get_argument('category',None)
category_id = self.get_argument('category_id',None)
print content,category_id
current_user = self.get_current_user()
print current_user
result = save_tasks_messages(self,content,current_user,category_id)
if result['status'] is True:
return self.write({'status': 200, 'msg': result['msg']})
else:
return self.write({'status': 400, 'msg': result['msg']})
class CategoryManageHandler(BaseHandler):
def get(self):
return self.render('tasks/category_manage.html')
def post(self):
category_name = self.get_argument('category_content_task',None)
print category_name
result = save_category(self,category_name)
if result['status'] is True:
return self.write('分类添加成功')
else:
return self.write({'status': 400, 'msg': result['msg']})
class TasksAcceptHanlder(BaseHandler):
'''
展示任务列表
'''
def get(self):
# current_uer = self.get_current_user()
# tasks = Tasks.all()
# print "+++++++"
# print tasks
categorys = CategoryTasks.all()
category_id_str = self.get_argument('category_task')
category_id = int(category_id_str)
print category_id
if category_id == 0:
tasks = Tasks.all()
print tasks
else:
tasks = CategoryTasks.by_id(category_id).tasks
kw = {
'tasks':tasks,
'categorys':categorys,
}
self.render('tasks/tasks_accept.html',**kw)
class UserAcceptHandler(BaseHandler):
'''
点击接受任务
'''
def get(self):
'''
根据task id 取出任务
:return:
'''
current_user = self.get_current_user()
user_name = current_user.name
task_id = self.get_argument('id','')
task = Tasks.by_id(task_id)
task_content = task.content
print '******************'
print task.content
result_repeate = self.conn.sadd('tasks:mytasks%s'%user_name,task_id)
print '+++++++++++='
# print result
if result_repeate:
number_tasks = self.conn.smembers('tasks:mytasks%s'%user_name)
# accepted_task = []
# self.conn.expire('tasks:mytasks%s'%current_user,60*5)
print number_tasks
self.conn.set('tasks:%s%s' %(task_id,user_name), task_content)
self.conn.set('tasks:%s%s' %(task_content,user_name), task_id)
# self.conn.expire('tasks:%s' % task_id, 300)
result_task_content_unexpire = self.conn.get('tasks:%s%s' %(task_id,user_name))
if result_task_content_unexpire is None:
return self.write('该任务已经被您取消或者过期,请获取其它的任务')
# if task_id not in number_tasks:
# accepted_task.append(task_id)
# return self.write('该任务已经被您获取过,不能再次获取')
# remain_task = 5 - len(number_tasks)
# return self.write('您还要继续接%s个任务'%remain_task)
# number_tasks = self.conn.smembers('tasks:mytasks%s' % user_name)
# delete_task = self.conn.srem('tasks:mytasks%s'%user_name,task_id)
else:
return self.write('请不要重复的获取任务')
# if tasks is not None:
# tasks_content = tasks.content
# str_task_id = str(task_id)
# self.conn.setex('tasks:%s'%user_name,tasks_content,2000)
# self.write('成功接受任务')
class MyTasksHandler(BaseHandler):
'''
用户展示自己的任务
'''
def get(self):
tasks_content = []
current_user = self.get_current_user()
user_name = current_user.name
tasks_id = self.conn.smembers('tasks:mytasks%s'%user_name)
for task_id in tasks_id:
task_content = self.conn.get('tasks:%s%s'%(task_id,user_name))
if task_content is not None:
tasks_content.append(task_content)
print '###############'
print task_content
# tasks_content.append(task_content)
# print tasks_content
current_user = self.get_current_user()
user_id = self.get_argument('user_id','')
# tasks = current_user.tasks
# print '****************'
# print tasks
kw = {
'current_user':current_user,
'tasks':tasks_content,
'num':0,
'datetime':'5分钟',
'tasks_id':tasks_id
}
return self.render('tasks/my_doing_tasks.html',**kw)
class QuitTaskHandler(BaseHandler):
def get(self):
current_user = self.get_current_user()
user_name = current_user.name
time_expire = 300
task_content = self.get_argument('task_content','')
task_id = self.conn.get('tasks:%s%s'%(task_content,user_name))
# task_content = self.conn.get('tasks:%s'%task_id)
# task_content = task.content
# result = self.conn.srem('tasks:mytasks%s'%current_user, task_content)
# if task_content is None:
# self.conn.sadd('Expire:tasks',task_id)
# return self.write('由于已经到了过期时间,从而失效')
result_delete = self.conn.delete('tasks:%s%s'%(task_id,user_name))
if result_delete:
return self.write('您已经成功取消该任务')
# num = 0
class HaveDoneTasksHandler(BaseHandler):
'''
任务完成处理
'''
def get(self):
current_user = self.get_current_user()
current_user_name = current_user.name
tasks_content = self.get_argument('task_content','')
# print "***************"
# print tasks_content
task_id = self.conn.get('tasks:%s%s' %(tasks_content,current_user_name))
# print task_id
self.conn.expire('tasks:%s' % task_id, 300)
# print task_id
expire_content_task = self.conn.get('tasks:%s%s'%(task_id,current_user_name))
# print expire_content_task
if expire_content_task is not None:
# self.conn.set('task_done:%s' % expire_content_task, num)
result_num_done_task = self.conn.incr('task_done:%s'%expire_content_task)
if result_num_done_task <= 5 and result_num_done_task > 0:
task = Tasks.by_id(task_id)
task.num_task = result_num_done_task
self.db.add(task)
self.db.commit()
remain_task_done = 5 - result_num_done_task
self.conn.delete('tasks:%s%s'%(task_id,current_user_name))
return self.write('该任务已经完成了,还剩%s次'%remain_task_done)
elif result_num_done_task > 5:
return self.write('该任务已经被完成了5次,不能再次完成')
#
#
#
#
# # num_task = str(NUM_TASK + 1)
#
# # self.conn.set('task_done:%s'%expire_content_task,num_task)
# # num_done_tasks = self.conn.get('task_done:%s'%expire_content_task)
# # print "***********"
# # print num_done_tasks
# task = Tasks.by_id(task_id)
#
# task.num_task += 1
# # if task.num_task > 5:
# # return self.write('该任务已经被完成了5次了')
# self.db.add(task)
# self.db.commit()
# self.conn.set('task_done:%s' % expire_content_task, task.num_task)
# num_done_tasks = self.conn.get('task_done:%s' % expire_content_task)
# print "***********"
# print num_done_tasks
# self.write('执行成功')
else:
return self.write('该任务已经过期或已经取消或者已经被您完成')
# tasks_have_done_numbers = self.conn.smembers('tasks:havedone%s'%current_user_name)
#
# if len(tasks_have_done_numbers) < 5:
# remain_tasks_have_done = 5 - len(tasks_have_done_numbers)
# return self.write('您还有%s次任务需要完成'%remain_tasks_have_done)
# elif len(tasks_have_done_numbers) == 5:
# return self.write('恭喜您,您已经完成了5次任务')
class CategoryTasksHandler(BaseHandler):
def get(self):
category = self.get_argument('category_content','')
category_task_set = self.conn.smembers('tasks:%s'%category)
kw = {
'task_categorys':category_task_set,
'category':category,
}
return self.render('tasks/category_tasks.html',**kw)
| [
"630551760@qq.com"
] | 630551760@qq.com |
387a2c4e876cb2a1a446a27a40b003870afa741b | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /data/cirq_new/cirq_program/startCirq_noisy175.py | cc4f8f2ea5639c20ee3b44f313ca868e0ad2a42c | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,957 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=14
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=1
c.append(cirq.H.on(input_qubit[1])) # number=2
c.append(cirq.H.on(input_qubit[2])) # number=3
c.append(cirq.H.on(input_qubit[3])) # number=4
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=5
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=6
c.append(cirq.H.on(input_qubit[0])) # number=11
c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=12
c.append(cirq.H.on(input_qubit[0])) # number=13
c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=8
c.append(cirq.X.on(input_qubit[0])) # number=9
c.append(cirq.X.on(input_qubit[0])) # number=10
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
qubit_count = 4
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
circuit = make_circuit(qubit_count,input_qubits)
circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')
circuit_sample_count =2000
circuit = circuit.with_noise(cirq.depolarize(p=0.01))
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
writefile = open("../data/startCirq_noisy175.csv","w+")
print(format(frequencies),file=writefile)
print("results end", file=writefile)
print(circuit.__len__(), file=writefile)
print(circuit,file=writefile)
writefile.close() | [
"wangjiyuan123@yeah.net"
] | wangjiyuan123@yeah.net |
f685f3898c0b236187d935e7d64769f4ad1928f5 | dbe31eadf3894a705a58d96eaa527359f7d6300a | /Just Lennard Jones Water Model.py | fb3fef43837ea4d0e78c30756ffc4f4dceef2e10 | [] | no_license | Kinnardian/water-molecule-model | ac4fd4effc0109944178e6f3936961cba0b0876f | 34f307c477754f3565131164a7fcee8f9b49828f | refs/heads/master | 2016-09-15T07:58:02.895598 | 2016-05-17T19:28:57 | 2016-05-17T19:28:57 | 10,323,992 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,570 | py | from __future__ import division
from visual import *
from visual.graph import * # import graphing features
O=Oxygen=sphere(pos=vector(0,0,0),radius=10*.66e-11, color=color.red)
#H1=Hydrogen1=sphere(pos=vector(95.564e-12,7.2661e-12,0),radius=10*.31e-11)
#H2=Hydrogen2=sphere(pos=vector(-95.564e-12,7.2661e-12,0),radius=10*.31e-11)
#With a Kick
H1=Hydrogen1=sphere(pos=vector(90e-12,7e-12,0),radius=10*.31e-11)
H2=Hydrogen2=sphere(pos=vector(-90e-12,7e-12,0),radius=10*.31e-11)
mO=15.99/(6.022e26)
mH=1.0079/(6.022e26)
qO=.8
qH=.4
qNa=1
qCl=-1
pO=mO*vector(0, 0, 0)
pH1=mH*vector(0, 0, 0)
pH2=mH*vector(0, 0, 0)
graph1 = gcurve(color=color.white)
#Force modeled using Lennard-Jones potential
#F=-12Ar^-13+6Br^-7
A=1
B=2
t=0
dt=1e-18
while t<5e-12:
t=t+dt
FOH1=(-1)*(-12*A*(mag(H1.pos-O.pos)**13)+6*B*(mag(H1.pos-O.pos))**(-7))*norm(H1.pos-O.pos) #Force of Oxygen on Hydrogen1
FOH2=-1*(-12*A*(mag(H2.pos-O.pos)**13)+6*B*(mag(H2.pos-O.pos))**(-7))*norm(H2.pos-O.pos)
FH1O=-1*(-12*A*(mag(O.pos-H1.pos)**13)+6*B*(mag(O.pos-H1.pos))**(-7))*norm(O.pos-H1.pos)
FH2O=-1*(-12*A*(mag(O.pos-H2.pos)**13)+6*B*(mag(O.pos-H2.pos))**(-7))*norm(O.pos-H2.pos)
FH1H2=-1*(-12*A*(mag(H2.pos-H1.pos)**13)+6*B*(mag(H2.pos-H1.pos))**(-7))*norm(H2.pos-H1.pos)
FH2H1=-1*(-12*A*(mag(H1.pos-H2.pos)**13)+6*B*(mag(H1.pos-H2.pos))**(-7))*norm(H1.pos-H2.pos)
H1.pos=H1.pos+((pH1)/mH)*dt
H2.pos=H2.pos+((pH2)/mH)*dt
pH1=pH1+(FOH1+FH2H1)*dt
pH2=pH2+(FOH2+FH1H2)*dt
pO=pO+(FH1O+FH2O)*dt
graph1.plot(pos=(t,mag(H1.pos-O.pos)-95.84e-12))
| [
"kinnard@bitbox.mx"
] | kinnard@bitbox.mx |
07c4d872c7e05f48921cfc7738f4525b30ddb108 | 316aebde2a8055f7ebdc66a9f5e94e636f0eb877 | /job6/config/pretrain_cfg.py | 19fbe84dd4fce8f121658a03990d5c0ddda0160f | [] | no_license | tiger115136/2021_QQ_AIAC_Tack1_1st | 76dcd3e1ace218a62059407bcfbcbe3cc2e3a3cc | 25c4e56dd0e1023763ddf54743eb5cbe97a69862 | refs/heads/main | 2023-08-30T12:59:12.338219 | 2021-11-17T11:56:08 | 2021-11-17T11:56:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 327 | py | # Pretrain file num
PRETRAIN_FILE_NUM = 20
LOAD_DATA_TYPE = 'mem'#'fluid'
# Training params
NUM_FOLDS = 1
SEED = 2021
BATCH_SIZE = 128
NUM_EPOCHS = 24
WARMUP_RATIO = 0.06
REINIT_LAYER = 0
WEIGHT_DECAY = 0.01
LR = {'others':5e-4, 'roberta':5e-5, 'newfc_videoreg':5e-4}
LR_LAYER_DECAY = 1.0
PRETRAIN_TASK = ['tag', 'mlm', 'mfm']
| [
"mzrzju@gmail.com"
] | mzrzju@gmail.com |
099e40f30702743bcd8c7b03996405b18971a5e5 | 84297380d00453e71f65c591dca046bd41a32184 | /ABC/ABC113/A.py | c367158a2dbe77733d419a9117215295220f221d | [] | no_license | daiki1998/atcoder | a5ef25245b1bbc3a5e33044846a3c16213603bd3 | d864a7cb11e41dbf6a691f5d128fdfe122b07046 | refs/heads/main | 2023-03-06T22:55:29.863716 | 2021-02-18T12:01:24 | 2021-02-18T12:01:24 | 323,401,954 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 46 | py | x, y = map(int, input().split())
print(x+y//2) | [
"shimokawadaiki@shimokawadaikinoMacBook-Pro.local"
] | shimokawadaiki@shimokawadaikinoMacBook-Pro.local |
2f53b3f8271b60d22df54f72752eded981080e61 | b697f5d8e441328c2deee1bb5853d80710ae9873 | /617.合并二叉树.py | 5d35a8098ff5d6b1d6488a23bbd84ef8e3088d55 | [] | no_license | happy-luck/LeetCode-python | d06b0f6cf7bad4754e96e6a160e3a8fc495c0f95 | 63fc5a1f6e903a901ba799e77a2ee9df2b05543a | refs/heads/master | 2021-03-22T16:12:52.097329 | 2020-07-15T13:48:37 | 2020-07-15T13:48:37 | 247,381,313 | 0 | 0 | null | 2020-03-15T01:47:42 | 2020-03-15T01:28:38 | null | UTF-8 | Python | false | false | 2,281 | py | 方法一:递归
我们可以对这两棵树同时进行前序遍历,并将对应的节点进行合并。在遍历时,如果两棵树的当前节点均不为空,我们就将它们的值进行相加,并对它们的左孩子和右孩子进行递归合并;如果其中有一棵树为空,那么我们返回另一颗树作为结果;如果两棵树均为空,此时返回任意一棵树均可(因为都是空)。
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if t2==None:
return t1
if t1==None:
return t2
t1.val += t2.val
t1.left = self.mergeTrees(t1.left,t2.left)
t1.right = self.mergeTrees(t1.right,t2.right)
return t1
时间复杂度:O(N),其中 N 是两棵树中节点个数的较小值。
空间复杂度:O(N),在最坏情况下,会递归 N 层,需要 O(N) 的栈空间。
方法二:迭代
我们首先把两棵树的根节点入栈,栈中的每个元素都会存放两个根节点,并且栈顶的元素表示当前需要处理的节点。在迭代的每一步中,我们取出栈顶的元素并把它移出栈,并将它们的值相加。随后我们分别考虑这两个节点的左孩子和右孩子,如果两个节点都有左孩子,那么就将左孩子入栈;如果只有一个节点有左孩子,那么将其作为第一个节点的左孩子;如果都没有左孩子,那么不用做任何事情。对于右孩子同理。
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if t2==None:
return t1
if t1==None:
return t2
stack = [(t1,t2)]
while stack:
t = stack.pop(0)
if t[1]==None:
continue
t[0].val += t[1].val
if(t[0].left==None):
t[0].left = t[1].left
else:
stack.append((t[0].left,t[1].left))
if(t[0].right==None):
t[0].right = t[1].right
else:
stack.append((t[0].right,t[1].right))
return t1
时间复杂度:O(N),其中 N 是两棵树中节点个数的较小值。
空间复杂度:O(N),在最坏情况下,栈中会存放 N 个节点。
| [
"18813129242@163.com"
] | 18813129242@163.com |
2df211672842b2e403fa07c1efc5e5cfde8b6ba8 | f8604e09ca02f00dfd6d9e1f5af10bccd7af2306 | /Classificador Naive Bayes.py | 96a355ba5f16da271d7103f4c44932703f412192 | [] | no_license | josehiago/ProjetoAM | e05095ad7fc7cce7531ee8521c50fc2dcfac50c4 | 9b82a42ba59d0fbf1681ebe42cd4d3ec118885eb | refs/heads/master | 2021-08-29T17:50:18.418142 | 2017-12-14T14:29:16 | 2017-12-14T14:29:16 | 114,208,364 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,482 | py | # -*- coding: utf-8 -*-
from __future__ import division
import collections
import math
class Model:
def __init__(self, arffFile):
self.trainingFile = arffFile
self.features = {} # todos os nomes das funções e seus possíveis valores (incluindo o rótulo da classe)
self.featureNameList = [] # é para manter a ordem dos recursos como no arff
self.featureCounts = collections.defaultdict(lambda: 1)# contém as tuplas do formulário (rótulo, feature_name, feature_value)
self.featureVectors = [] # contém todos os valores eo rótulo como a última entrada
self.labelCounts = collections.defaultdict(lambda: 0) # estes serão suavizados mais tarde (armazena as contagens dos próprios rótulos da classe)
def TrainClassifier(self):#conta o número de co-ocorrências de cada valor de recurso com cada rótulo de classe e os armazena na forma de 3-tuplas. Essas contagens são suavizadas automaticamente usando o alinhamento de adicionar-um como o valor padrão de contagem para este dicionário é '1'. As contagens dos rótulos também são ajustadas ao incrementar essas contagens pelo número total de observações.
for fv in self.featureVectors:
self.labelCounts[fv[len(fv)-1]] += 1 # udpate contagem do rótulo
for counter in range(0, len(fv)-1):
self.featureCounts[(fv[len(fv)-1], self.featureNameList[counter], fv[counter])] += 1
for label in self.labelCounts: ## aumenta a contagem de rótulos (alisamento). Lembre-se de que o último recurso é realmente o rótulo
for feature in self.featureNameList[:len(self.featureNameList)-1]:
self.labelCounts[label] += len(self.features[feature])
def Classify(self, featureVector): ## featureVector é uma lista simples como as que usamos para treinar
probabilityPerLabel = {} # armazenar a probabilidade final para cada etiqueta de classe
for label in self.labelCounts: #como argumento, um vetor de recurso único (como uma lista) e calcula o produto de probabilidades condicionais individuais (MLE suavizado) para cada rótulo. As probabilidades calculadas finais para cada rótulo são armazenadas no dicionário ' probabilidadeListaLabel '. Na última linha, devolvemos a entrada de probabilidadPerLabel que tem maior probabilidade. Note-se que a multiplicação é realmente feita como adição no domínio do log, pois os números envolvidos são extremamente pequenos. Além disso, um dos fatores usados nesta multiplicação, é a probabilidade anterior de ter esse rótulo de classe.
logProb = 0
for featureValue in featureVector:
logProb += math.log(self.featureCounts[(label, self.featureNameList[featureVector.index(featureValue)], featureValue)]/self.labelCounts[label])
probabilityPerLabel[label] = (self.labelCounts[label]/sum(self.labelCounts.values())) * math.exp(logProb)
print probabilityPerLabel
return max(probabilityPerLabel, key = lambda classLabel: probabilityPerLabel[classLabel])
def GetValues(self):#lê os nomes das funções (incluindo os rótulos das classes), seus possíveis valores e os próprios vetores de características; e preencha as estruturas de dados
file = open(self.trainingFile, 'r')
for line in file:
if line[0] != '@': ## início de dados reais
self.featureVectors.append(line.strip().lower().split(','))
else: #feature definitions
if line.strip().lower().find('@data') == -1 and (not line.lower().startswith('@relation')):
self.featureNameList.append(line.strip().split()[1])
self.features[self.featureNameList[len(self.featureNameList) - 1]] = line[line.find('{')+1: line.find('}')].strip().split(',')
#self.features[self.featureNameList[len(self.featureNameList) - 1]] = [featureName.strip() for featureName in line[line.find('{')+1: line.find('}')].strip().split(',')]
file.close()
def TestClassifier(self, arffFile):
file = open(arffFile, 'r')
count_acertos = 0
count_class = 0
for line in file:
if line[0] != '@':
vector = line.strip().lower().split(',')
count_class = count_class + 1
if str(self.Classify(vector)) == str(vector[len(vector) - 1]):
count_acertos = count_acertos + 1
print "classifier: " + self.Classify(vector) + " given " + vector[len(vector) - 1]
print "Acurácia: " + str("%.2f" % round((count_acertos/count_class)*100,2))+ " %"
if __name__ == "__main__":
model = Model(r"C:\Users\hiago\Documents\train.arff.norm.arff")
model.GetValues()
model.TrainClassifier()
model.TestClassifier(r"C:\Users\hiago\Documents\test.arff.norm.arff")
#https://sites.google.com/site/carlossillajr/
| [
"hiagorobinho12@gmail.com"
] | hiagorobinho12@gmail.com |
9130e70a7f8d51f9088bc452121d45abb7562bbd | 95e21ddc4a898a3274ef70bd1e69d4acfcd4477e | /cluster.py | efdab6df046039fd2d36b829fc4f3e16986db09f | [] | no_license | pp2095/BE-Project | 0e80d12ef54abebc30e1f136f06727fde386b9c3 | bec91949548b939416eab3c9476ac860423729d9 | refs/heads/master | 2021-01-11T07:48:59.507036 | 2016-11-11T23:32:55 | 2016-11-11T23:32:55 | 72,055,571 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,377 | py | import csv, umbc, pickle, math
from scipy import spatial
def make_cluster(f1,f2):
#load antonyms
ant_file=open('antonyms.csv','r')
ant_reader=csv.reader(ant_file,delimiter=',')
ant_dic={}
for row in ant_reader:
ant_dic[row[0]]=row[1]
#load pre-existing dictionary
dict=pickle.load(open('dict.p','rb'))
#load stop words
with open('stopwords.txt','r') as f:
sw = f.read().splitlines()
neg_words=['not','no','never','cannot',"can't","won't"]
wordlist=[]
#load main emotions
f=open('emo_list.txt','r')
emos=[]
for row in f.read().splitlines():
sub=[]
for item in row.split(','):
sub.append(item)
emos.append(sub)
#load opposite emotions
opp_emos=[]
f=open('ant_emos.txt','r')
for row in f.read().splitlines():
sub=[]
for item in row.split(','):
sub.append(item)
opp_emos.append(sub)
#parse the sentence file
res_file=open(f2,"a+")
csvwriter = csv.writer(res_file, delimiter=',')
for row in open(f1,'r'):
neg,there=False,True
sentence=row
print "Tweet is: "+sentence
list=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for word in sentence.split():
v=[]
v1=[]
#ignore stop word
if word.lower() in sw:
continue
#check if already present
elif word.lower() in wordlist:
word=word.lower()
#check if negation introduced
elif word.lower() in neg_words:
neg=True
continue
#have none of the other choices
else:
print word
if neg==True:
try:
word=ant_dic[word.lower()].lower()
#neg=False
except KeyError:
word=word.lower()
there=False
else:
word=word
#if there isn't any negation, go for the word directly
if neg==False:
try:
v1=dict[word]
except KeyError:
for sublist in emos:
semo=[]
for item in sublist:
score=umbc.sss(word,item)
semo.append(score)
v1.append(max(semo))
dict[word]=v1
#negation is present
else:
#antonym available
if there==True:
try:
v1=dict[word]
except KeyError:
for sublist in emos:
semo=[]
for item in sublist:
score=umbc.sss(word,item)
semo.append(score)
v1.append(max(semo))
dict[word]=v1
else:
neg,there=False,True
for sublist in opp_emos:
semo=[]
for item in sublist:
score=umbc.sss(word,item)
semo.append(score)
v1.append(max(semo))
neg=False
for x in v1:
if math.isinf(x)==True:
v.append(0)
else:
v.append(x)
list=[sum(x) for x in zip(list, v)]
#initialize target vectors
joy=[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
optimism=[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
admiration=[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
acceptance=[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
fear=[0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
apprehension=[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0]
amazement=[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0]
surprise=[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0]
loathing=[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0]
disgust=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0]
rage=[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0]
anger=[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0]
anticipation=[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0]
interest=[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0]
sadness=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0]
disapproval=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0]
appreciation=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]
grief=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]
love=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
#calculate cosine distances
if list==[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]:
#tweet cannot be classified
continue
r=[]
r.append(1-spatial.distance.cosine(list,joy))
r.append(1-spatial.distance.cosine(list,optimism))
r.append(1-spatial.distance.cosine(list,admiration))
r.append(1-spatial.distance.cosine(list,acceptance))
r.append(1-spatial.distance.cosine(list,fear))
r.append(1-spatial.distance.cosine(list,apprehension))
r.append(1-spatial.distance.cosine(list,amazement))
r.append(1-spatial.distance.cosine(list,surprise))
r.append(1-spatial.distance.cosine(list,loathing))
r.append(1-spatial.distance.cosine(list,disgust))
r.append(1-spatial.distance.cosine(list,rage))
r.append(1-spatial.distance.cosine(list,anger))
r.append(1-spatial.distance.cosine(list,anticipation))
r.append(1-spatial.distance.cosine(list,interest))
r.append(1-spatial.distance.cosine(list,sadness))
r.append(1-spatial.distance.cosine(list,disapproval))
r.append(1-spatial.distance.cosine(list,appreciation))
r.append(1-spatial.distance.cosine(list,grief))
r.append(1-spatial.distance.cosine(list,love))
#find maximum cosine similarity and corresponding emotion
m=max(r)
indices=[i for i,j in enumerate(r) if j==m]
emos=['joy','optimism','admiration','acceptance','fear','apprehension','amazement','surprise','loathing','disgust','rage','anger','anticipation','interest','sadness','disapproval','appreciation','grief','love']
for i in indices:
res=emos[i]
print res
csvwriter.writerow([sentence,res,r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15],r[16],r[17],r[18]])
pickle.dump(dict, open( "dict1.p", "wb" ) )
| [
"noreply@github.com"
] | pp2095.noreply@github.com |
7f3f66be60b0279d3f3319ae3680d3d3b96bfa56 | cbf366c1edbd689dd6066ab7a405bcc76e79896a | /venv/Lib/site-packages/dart_fss/filings/search_result.py | 05c874e6232c98de2f66a1f0c55bd1b53ca65d33 | [] | no_license | nosangho/Stock | 38818f3b0011fd885ea769bc04cd551e219bc28e | a608e75e222ac9428084630e53144a76c906fdd6 | refs/heads/master | 2022-11-17T06:10:01.034478 | 2022-11-07T03:56:18 | 2022-11-07T03:56:18 | 246,343,132 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,878 | py | # -*- coding: utf-8 -*-
from typing import Dict
from dart_fss.utils import dict_to_html
from dart_fss.filings.reports import Report
class SearchResults(object):
""" DART 검색결과 정보를 저장하는 클래스"""
def __init__(self, resp):
self._page_no = resp['page_no']
self._page_count = resp['page_count']
self._total_count = resp['total_count']
self._total_page = resp['total_page']
self._report_list = [Report(**x) for x in resp['list']]
@property
def page_no(self):
""" 표시된 페이지 번호 """
return self._page_no
@property
def page_count(self):
"""페이지당 표시할 리포트수"""
return self._page_count
@property
def total_count(self):
"""int: 총 건수"""
return self._total_count
@property
def total_page(self):
"""int: 총 페이지수"""
return self._total_page
@property
def report_list(self):
"""list of Report: 검색된 리포트 리스트"""
return self._report_list
def to_dict(self) -> Dict:
""" dict 타입으로 반환
Returns
-------
dict of str
검색 결과 dict 타입로 반환
"""
return {
'page_no': self.page_no,
'page_count': self.page_count,
'total_count': self.total_count,
'total_page': self.total_page,
'report_list': [x.to_dict() for x in self.report_list]
}
def __repr__(self):
from pprint import pformat
return pformat(self.to_dict())
def _repr_html_(self):
return dict_to_html(self.to_dict(), exclude=['pages'], header=['Label', 'Data'])
def __getitem__(self, item):
return self._report_list[item]
def __len__(self):
return len(self._report_list) | [
"nosangho@gmail.com"
] | nosangho@gmail.com |
94852fd4363fe8e9d718663849d1e4d27b36a2a6 | 387b4a53485b175d2c8c7bca7f3429ad2abbb4f0 | /single_stage_model/backbone_2d/backbone2d_module.py | c295d5c3b4dff59eac35d5eb704c74058ffe90b1 | [] | no_license | liangzhao123/IOU-SSD | 50cf3a52e8b306b024d0396b76bd3931c8a15434 | b53a1659ffe197da8eeca0f4a35a4a4571db22f4 | refs/heads/main | 2023-06-25T08:15:03.553378 | 2021-07-31T17:40:49 | 2021-07-31T17:40:49 | 321,982,002 | 5 | 2 | null | null | null | null | UTF-8 | Python | false | false | 2,698 | py | import torch.nn as nn
import torch
from functools import partial
def Layer(in_channels,
out_channels,
kernel_size,
stride,
padding=0,
bias=True,conv_type="conv2d"):
BatchNorm2d = partial(nn.BatchNorm2d, eps=1e-3, momentum=0.01)
Conv2d = partial(nn.Conv2d, bias=False)
ConvTranspose2d = partial(nn.ConvTranspose2d, bias=False)
if conv_type=="conv2d":
m = nn.Sequential(
Conv2d(in_channels,out_channels,kernel_size,stride,padding,bias=bias,),
BatchNorm2d(out_channels),
nn.ReLU()
)
elif conv_type=="deconv2d":
m = nn.Sequential(
ConvTranspose2d(in_channels, out_channels, kernel_size, stride, bias=bias, ),
BatchNorm2d(out_channels),
nn.ReLU()
)
else:
raise NotImplementedError
return m
class Backbone2d(nn.Module):
def __init__(self):
super().__init__()
self.padding_layer = nn.ZeroPad2d(1)
self.conv1 = nn.Sequential(
nn.ZeroPad2d(1),
Layer(512,256,3,stride=1,bias=False),
Layer(256,256,3,stride=1,padding=1,bias=False),
Layer(256,256,3,stride=1,padding=1,bias=False),
Layer(256,256,3, stride=1, padding=1,bias=False),
Layer(256, 256, 3, stride=1, padding=1,bias=False),
Layer(256, 256, 3, stride=1, padding=1,bias=False),
Layer(256, 256, 3, stride=1, padding=1,bias=False),
)
self.conv2 = nn.Sequential(
nn.ZeroPad2d(1),
Layer(256,512,3,stride=2,bias=False),
Layer(512,512,3,stride=1,padding=1,bias=False),
Layer(512,512,3,stride=1,padding=1,bias=False),
Layer(512, 512, 3, stride=1, padding=1,bias=False),
Layer(512, 512, 3, stride=1, padding=1,bias=False),
Layer(512, 512, 3, stride=1, padding=1,bias=False),
Layer(512, 512, 3, stride=1, padding=1,bias=False),
)
self.deconv1 = nn.Sequential(
Layer(256,512,1,stride=1,bias=False,conv_type="deconv2d"),
)
self.deconv2 = nn.Sequential(
Layer(512, 512, 2, stride=2, bias=False, conv_type="deconv2d"),
)
def forward(self,batch_dict):
spatial_feartures = batch_dict["spatial_features"]
ups = []
conv_last = []
x = self.conv1(spatial_feartures)
conv_last = x
ups.append(self.deconv1(x))
x = self.conv2(x)
ups.append(self.deconv2(x))
x = torch.cat(ups, dim=1)
batch_dict["conv2d_features"] = x
batch_dict["conv2d_last_features"] = conv_last
return batch_dict
| [
"1094036832@qq.com"
] | 1094036832@qq.com |
adb23fd67e0a028ea4c6d9e991e4fd81d90b8e49 | 15d288bdaed83f846ee8050fffca77e9a5331f69 | /learning/threadlocal.py | 63d648b978257c05556badf98b823f00fc4ade40 | [] | no_license | duocang/python | 94e2ff506acdde6b885e5574729934794708d8f8 | 163c36813f02d921153a655aea0c0ac510531f34 | refs/heads/master | 2021-10-24T01:22:06.386192 | 2019-03-21T08:40:28 | 2019-03-21T08:40:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 984 | py | import threading
# 可以理解为全局变量local_school是一个dict,
# 不但可以用local_school.student,还可以绑定其他变量,
# 如local_school.teacher等等。
# 创建全局ThreadLocal对象
local_school = threading.local()
# 每个属性如local_school.student都是线程的局部变量,
# 可以任意读写而互不干扰,也不用管理锁的问题,ThreadLocal内部会处理
def process_student():
# 获取当前线程关联的student
std = local_school.student
print('Hello, %s (in %s)' % (std, threading.current_thread().name))
def process_thread(name):
# 绑定ThreadLocal的student:
local_school.student = name
process_student()
t1 = threading.Thread(target=process_thread, args=('Alice',), name='Thread-A')
t2 = threading.Thread(target=process_thread, args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()
# ThreadLocal解决了参数在一个线程中各个函数之间互相传递的问题
| [
"wangxuesong29@gmail.com"
] | wangxuesong29@gmail.com |
1d423cfc8f2f82026ce2821bc693e2c543c551e8 | 5bbc1f6fa646a917b8d4e2556b469b66df8b92c1 | /store/migrations/0010_order_status.py | 4c2855c5261551cf786cd5f85452f70e4549114f | [] | no_license | leoumesh4/django-ecommerce | 5f42b3124c344cc01ecebe3d7cd288d6e5b26354 | 0f8bcac12c987f7f82668ef3b1d7a529cf9e5def | refs/heads/master | 2023-03-19T12:56:41.603114 | 2021-03-17T09:04:38 | 2021-03-17T09:04:38 | 348,634,979 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 384 | py | # Generated by Django 3.1.6 on 2021-03-15 10:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0009_auto_20210315_1348'),
]
operations = [
migrations.AddField(
model_name='order',
name='status',
field=models.BooleanField(default=False),
),
]
| [
"umeshneupane24@gmail.com"
] | umeshneupane24@gmail.com |
d90dcbcb06450d0cec154190b117b2ccce514085 | bce41eff7da75522f58d831251e1ed95d8809585 | /services/web/project/apps/event/subscriptions/eventUpdateSubscription.py | 88e5ae15e2e558fd56fb9935803408b5065f7dcb | [] | no_license | javillarreal/eventuality | be9728a19caef8c19d3d40e6dd5b90e57b5b63a1 | 5a543a9e6b5a3f014b670297e22f52a9884af4bb | refs/heads/master | 2021-07-03T18:55:33.037863 | 2021-06-24T03:24:38 | 2021-06-24T03:24:38 | 204,239,198 | 1 | 0 | null | 2020-11-27T02:39:19 | 2019-08-25T03:05:17 | Python | UTF-8 | Python | false | false | 696 | py | import random
import graphene
from rx import Observable
class RandomType(graphene.ObjectType):
seconds = graphene.Int()
random_int = graphene.Int()
class Subscription(graphene.ObjectType):
count_seconds = graphene.Int(up_to=graphene.Int())
random_int = graphene.Field(RandomType)
def resolve_count_seconds(root, info, up_to=5):
return Observable.interval(1000)\
.map(lambda i: "{0}".format(i))\
.take_while(lambda i: int(i) <= up_to)
def resolve_random_int(root, info):
return Observable.interval(1000).map(lambda i: RandomType(seconds=i, random_int=random.randint(0, 500)))
| [
"jjescobar@uninorte.edu.co"
] | jjescobar@uninorte.edu.co |
7e96a5119eb9f9f1c13d6cbca6e6a301d9ccca2b | a18910af84ad0bccd2c6166d62997a3a7062b456 | /New/Game.py | 548bf0b1b8902e1d0e327fafb02bf0f810aa967a | [] | no_license | Dennnn/StackGames | 741d2ace917ebbc5aaa3975e3607488fc7307f33 | 67e34a6a7b23ccff8b53788394f942dbf64807ba | refs/heads/master | 2021-01-21T14:48:17.553474 | 2017-06-26T12:43:20 | 2017-06-26T12:43:20 | 95,445,367 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,786 | py | #!/usr/bin/python2.7
import csv
import random
def ophalen_data():
#Ophalen opgeslagen data
ifile = open('Accounts.csv','r')
reader = csv.reader(ifile)
#Data inlezen en aanmaken dictionary voor naam en aantal goudstukken
name_dict = {}
for row in reader:
name_dict[row[0]] = row[1]
ifile.close()
#Ingevulde naam checken met opgeslagen namen
name = raw_input("Vul hier uw naam in: ")
if name in name_dict.keys():
print("U heeft eerder gespeeld")
goudstukken = int(name_dict[name])
else:
goudstukken = int(0)
#Vorig aantal goudstukken
print "U had toen " + str(goudstukken) +" goudstukken."
#Opslaan gegevens
ofile = open('Accounts.csv','w')
writer = csv.writer(ofile,lineterminator = '\n')
for key,value in name_dict.items():
writer.writerow([key,value])
ofile.close()
#Gegevens speler opvragen
def behendigheid_en_kracht():
#Power kracht + behendigheid
while True:
try:
kracht = int(raw_input("\nHoe krachtig ben je kies een getal van 1 t/m 100 : "))
except ValueError:
print("Alleen getallen")
if 1 <= kracht <= 100:
break
else:
print("1 t/m 100 aub")
while True:
try:
behendigheid = int(raw_input("Hoe behendig ben je kies een getal van 1 t/m 100 : "))
except ValueError:
print("Alleen getallen")
continue
if 1 <= behendigheid <= 100:
break
else:
print("1 t/m 100 aub")
#Level keuzen door speler
def level_kiezen(Self):
#While loop status check
status = int(0)
while status != 4 :
#Welk level er wordt gekozen
verdient = int(0)
level = int(raw_input("\nEnter Kies 1 t/m 3 voor een level en 4 om te kopen/verkopen: "))
if level == 4:
break
else:
#Input voor welk pad en keuze vechten/vluchten
pad = int(raw_input("Kiest u pad 1, 2 of 3 : "))
check = int(raw_input("Kies 1 om te vechten en 2 om te vluchten : "))
#Vecht functie
def vecht(level,pad,check,behendigheid,kracht,goudstukken,name_dict,name):
#Totale power speler
power = behendigheid_en_kracht() + behendigheid_en_kracht()
#power van bosman, aardman en trol afhankelijk van het gekozen level
bosman = int(100)
aardman = int(100)
#bosman = 2*random.randint((level-1)*10,level*10)
#aardman = 2*random.randint((level-1)*20,level*20)
#trol = 2*random.randint((level-1)*40,level*40)
verdient = int(0)
#Check 0 om te vluchten
if level_kiezen(check) == 0:
pass
else:
#Nested if else loop voor gevecht
if pad == 1 :
if power > bosman:
verdient = power - bosman
else:
pass
elif pad == 2:
if power > aardman:
verdient = power - aardman
else:
pass
else:
if power > trol:
verdient = power - trol
else:
pass
verdient = vecht(level,pad,check,behendigheid,kracht,goudstukken,name_dict,name)
goudstukken = goudstukken + verdient
name_dict[name] = goudstukken
#Verdiende goudstukken
return verdient
#Koop/verkoop functie
def koop_of_verkoop(status,voorwerp,goudstukken):
#Prijzenlijst
prijs = {1:50,2:60}
#Kopen
if status == 1:
if goudstukken < prijs[voorwerp]:
print "Sorry je hebt niet genoeg goudstukken"
else:
goudstukken = goudstukken - prijs[voorwerp]
#Kopen/verkopen
status = 0
gekocht = []
#While loop voor verkopen en kopen van voorwerpen
while status !=3:
try:
status = int(raw_input("\n Kies 1 om te kopen en 2 om te verkopen"))
except ValueError:
print("Alleen getallen aub")
continue
if 1 <= status <= 2:
break
else:
print("Kies 1 kopen of 2 verkopen: ")
continue
#Input wapen of schild
while 1 <= status <=2:
try:
voorwerp = int(raw_input("Kies 1 voor een wapen en 2 voor een schild : "))
except ValueError:
print("Alleen getallen")
continue
if 1 <= voorwerp <= 2:
break
else:
print("Kies 1 voor een wapen en 2 voor een schild")
continue
#Verkoop
else:
goudstukken = goudstukken + prijs[voorwerp]
return goudstukken
if __name__ == '__main__':
ophalen_data()
behendigheid_en_kracht()
level_kiezen(0)
koop_of_verkoop(0,0,0)
| [
"dennis.b.e@hotmail.com"
] | dennis.b.e@hotmail.com |
88cf0fe43706c2c3a75580ad6b253f67daecdaa9 | 3cc16860596f38bb54bf96525a000dfa07a7c45b | /Env.py | 3ca39ab6ddf6f156f93a6466b3a446d4067837e4 | [] | no_license | diveshgaonkar1/Cab-Driver-Assignment-Upgrad | bf67e4cc0d6156b2a107184682c87b9fc71b081f | 187d5e53d9c83d11b9bfbade35ea7dde5d564339 | refs/heads/main | 2023-04-09T22:41:52.815413 | 2021-03-29T13:01:34 | 2021-03-29T13:01:34 | 352,644,369 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,170 | py | import numpy as np
import math
import random
import itertools
from itertools import product
#Defining hyperparameters
m = 5 #Number of cities, ranges from 1 ..... m
t = 24 #Number of hours, ranges from 0 .... t-1
d = 7 #Number of days, ranges from 0 ... d-1
C = 5 #Per hour fuel and other costs
R = 9 #Per hour revenue from a passenger
class CabDriver():
def __init__(self):
"""initialise your state and define your action space and state space"""
self.locations = np.arange(0,5) # Locations encoded as an integer 0 to 4
self.hours = np.arange(0, 24,dtype=np.int) # Hours are encoded as 24
self.days = np.arange(0, 7) # days of week encoded as 0 to 6
#Create action space of 20 possible commute actions
self.action_space = [a for a in list(product(self.locations, self.locations)) if a[0] != a[1]]
self.action_size = len(self.action_space)
#Create state space where state is [location, hours, days]
self.state_space = [a for a in list(product(self.locations, self.hours, self.days))]
self.state_init =self.state_space[np.random.randint(len(self.state_space))]
self.pickuptime = 0 #Placeholder for commute time when pickup & drop locations are not same
self.droptime = 0 #Time spent in dropping passenger for single t
self.TotalRideTime = 0 #Total commute time for pickup and drop. TotalRideTime=pickuptime+droptime
self.state_size=36 #For architecture 1 state size will be m+t+d i.e 5+24+7
self.reset()
#Encoding state (or state-action) for NN input for architecture 1
def state_encod_arch1(self, state):
"""convert the state into a vector so that it can be fed to the NN.This method converts a given state into a vector format. Hint:
The vector is of size m + t + d."""
loc = np.eye(m, dtype=np.int16)[int(state[0])] #Location vector
hour = np.eye(t, dtype=np.int16)[int(state[1])] #Hour vector
day = np.eye(d, dtype=np.int16)[int(state[2])] #Day vector
state_encod = np.concatenate((loc, hour, day)) #Combined state vector
return state_encod
#Obtaining number of requests at current state
def requests(self, state):
"""Determining the number of requests basis the location.
Use the table specified in the MDP and complete for rest of the locations"""
loc_index = state[0]
if loc_index == 0 :
requests = np.random.poisson(2)
elif loc_index == 1 :
requests = np.random.poisson(12)
elif loc_index == 2 :
requests = np.random.poisson(4)
elif loc_index == 3 :
requests = np.random.poisson(7)
elif loc_index == 4 :
requests = np.random.poisson(8)
#Restrict max number of requests to 15
if requests > 15:
requests = 15
#Fetch actions for number of requests received
action_indices = random.sample(range(0, (m-1)*m), requests)
actions = [self.action_space[i] for i in action_indices]
#Add offline action to the set of possible actions
actions.append((0, 0)) #Condition as (0,0) represents offline condition
return actions
#Compute reward depending on ride completion
def reward_func(self, state, action, Time_matrix,flag):
"""Takes in state, action and Time-matrix and returns the reward"""
#Reward function returns revenue earned from pickup point p to drop point q
""" As per MDP definition
𝑅(𝑠=𝑋𝑖𝑇𝑗𝐷𝑘) ={ 𝑅𝑘∗(𝑇𝑖𝑚𝑒(𝑝,𝑞)) − 𝐶𝑓 ∗(𝑇𝑖𝑚𝑒(𝑝,𝑞) + 𝑇𝑖𝑚𝑒(𝑖,𝑝)) 𝑎=(𝑝,𝑞)
−𝐶𝑓 𝑎=(0,0)}"""
if flag==1:
reward=(self.droptime*R)-(C*(self.pickuptime*+self.droptime))
else:
reward=-self.pickuptime
return reward
#Compute next state basis current state and action
def next_state_func(self, state, action, Time_matrix):
"""Takes state and action as input and returns next state"""
if not isinstance(action,tuple):
#Fetch current action
action=self.action_space[action]
#Initialise variables
is_terminal=False
self.pickuptime=0
self.droptime=0
currLocation=state[0]
totalHours=state[1]
totaldays=state[2]
pickupLocation=action[0]
dropLocation=action[1]
#Compute next state basis action taken
if action[0]!=0 and action[1]!=0:
if currLocation!=pickupLocation:
#Compute time taken to reach pickup point
self.pickuptime=Time_matrix[currLocation][pickupLocation][int(totalHours)][totaldays]
totalHours=self.pickuptime+totalHours
#Update totalHours and totaldays
totalHours,totaldays= self.DayModifier(totalHours,totaldays)
#Set pickup location as current location
currLocation=pickupLocation
#Compute drop time
self.droptime=Time_matrix[currLocation][dropLocation][int(totalHours)][totaldays]
#Update totalHours and totaldays
totalHours=totalHours+self.droptime
totalHours,totaldays= self.DayModifier(totalHours,totaldays)
#Compute total ride time
self.TotalRideTime=self.TotalRideTime+self.pickuptime+self.droptime
#Compute ride reward
reward=self.reward_func(state,action,Time_matrix,1) #1 indicates ride completion
else:
#Update current location
dropLocation=currLocation
#Update totalHours and totaldays
totalHours,totaldays=self.DayModifier(totalHours+1,totaldays)
#Flag as 0 to indicate offline trip
reward=self.reward_func(state,action,Time_matrix,0) #Offline reward
#Check if episode has ended 24*30 days=720, end of the month
if self.TotalRideTime>=720:
is_terminal=True
next_state=(dropLocation,totalHours,totaldays) #state returned without encoding
return next_state,action,reward,is_terminal
#Update totalHours and totaldays
def DayModifier(self, hour, nextday):
"""Time and week day modifier, Handling changing the week day based on time """
while hour >= 24:
if hour == 24:
nextday = nextday+1
hour = 0
elif hour > 24:
nextday = nextday+1
hour = hour-24
if nextday > 6:
nextday = nextday-7
return (hour, nextday)
#Reset environment
def reset(self):
'Reseting the object and setting total commute as zero'
self.TotalRideTime=0
return self.action_space, self.state_space, self.state_init | [
"noreply@github.com"
] | diveshgaonkar1.noreply@github.com |
f7764c9cbc8b8b2ef658d8de5bdd013a9e1d86dd | 533c0d561ead51f2b494c10306df6ab0100617e8 | /python-lang/pipelines/onboarding/dofns/__init__.py | 470ba4634e1dd994cf8d69271f2b2b359d4e8840 | [] | no_license | vadzimpiatkevich/patential | 24927da0866f91d8e79eb45ce6d5b85c6cad0585 | 1a7f94e83d61579d43bed692e9cec0000ab2518d | refs/heads/master | 2023-05-13T06:59:28.651798 | 2021-06-01T20:00:23 | 2021-06-01T20:00:23 | 233,421,770 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 102 | py | from .query_publications import QueryPublications
from .upsert_patents_to_db import UpsertPatentsToDB
| [
"vadzim.piatkevich@gmail.com"
] | vadzim.piatkevich@gmail.com |
eed6d70506764b19352a7df71cc915863d3e1786 | 9829cdba12a4951986e74e1c04aaf1a968fc8211 | /TimingTests.py | 61d0965a177466e0e36822a9a7571cf19666a899 | [] | no_license | ericye16/SomeToyAI | 502f6acb92b9adcb8798f354035898bcef4bdc36 | 9f1696e9a965416d53407d20778b25f5d40fbc93 | refs/heads/master | 2020-05-19T21:43:08.608039 | 2012-08-18T19:38:22 | 2012-08-18T19:38:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,258 | py | #!/usr/bin/env python
#timing tests
import timeit
import BlockPuzzle8
AStarSearch8 = timeit.timeit('BlockPuzzle8.AStarSearch()',
'from __main__ import BlockPuzzle8',
number = 10)
breadthFirstSearch8 = timeit.timeit('BlockPuzzle8.breadthFirstSearch()',
'from __main__ import BlockPuzzle8',
number = 10)
greedy8 = timeit.timeit('BlockPuzzle8.greedyBestFirstSearch()',
'from __main__ import BlockPuzzle8',
number = 10)
depthLimitedGreedy8 = timeit.timeit('BlockPuzzle8.depthLimitedGreedySearch()',
'from __main__ import BlockPuzzle8',
number = 10)
print 'A* on 8 puzzle: %f' % AStarSearch8
#Non-Queue: 6.221501
#Queue: 0.631132
print 'Breadth-first search on 8 puzzle: %f' % breadthFirstSearch8
#Non-Queue: 58.277133
#Queue: 69.426882
print 'Greedy best-first search on 8 puzzle: %f' % greedy8
#Non-Queue: 2.396569
#Queue: 0.626330
print 'Depth-limited greedy search on 8 puzzle: %f' % depthLimitedGreedy8
#Non-priority queue: 243.450213
#Queue: 3.685799
#Significantly more impressive.
#Non-priority queue: 6.221501
| [
"computereric@live.ca"
] | computereric@live.ca |
333b051c8827b9f32e6d9ef95ead1a7d8ecd6945 | 2fb6642c6f35231fcd04c19f4e56e49ab64954de | /chenzen/views/__init__.py | 7df6a1b29df572ecd6957afecbc781073a18153f | [] | no_license | misfire/chenzen | 979eba1f75a7e58ca9bd8eda24e547ea3da8dc9d | c78b5250e8f83d8ed67f550e35ceca7e8f0e2cb7 | refs/heads/master | 2020-12-24T21:54:58.109345 | 2013-05-22T23:39:43 | 2013-05-22T23:39:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16 | py | import register
| [
"Alto50@gmail.com"
] | Alto50@gmail.com |
c87f6abacd4d1526c188c591e69870c485175606 | f67e9154c3e077eaad349f85439d88820098a6fc | /Search/017_LetterCombOfPhoneNum.py | 73ba53f513b92e34b6a16b00c4aef98076aeab44 | [] | no_license | pondjames007/CodingPractice | 0c159ae528d1e595df0f0a901ee1ab4dd8925a14 | fb53fea229ac5a4d5ebce23216afaf7dc7214014 | refs/heads/master | 2020-06-08T02:31:04.569375 | 2020-01-15T20:41:34 | 2020-01-15T20:41:34 | 193,142,129 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 873 | py | # TIPS:
# make a dictionary to map digit and char
# go through all digits and find out all combinations
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits: return []
n_to_c = {}
char = [*string.ascii_lowercase]
start = 0
end = 0
for i in range(2,10):
start = end
if i == 7 or i == 9:
end += 4
else:
end += 3
n_to_c[i] = char[start:end]
ans = []
self.lookup(n_to_c, digits, [], ans)
return ans
def lookup(self, dic, digits, path, ans):
if not digits:
ans.append(''.join(path))
return
for c in dic[int(digits[0])]:
self.lookup(dic, digits[1:], path + [c], ans) | [
"jameshuang@nyu.edu"
] | jameshuang@nyu.edu |
97564ccbe77bc827d4aaa69139259eb457aad57a | 065e1444fed408676a3a7899326dbbe3845ac886 | /aico/wsgi.py | ccf43c36f58117c7e0e40ae719376860ea011922 | [] | no_license | AlejandroVeintimilla/aico | b3395fb92843562c24df358198907abfb7dfe50b | 7598e9bd3220cd5a6b5f5f1057d5b2e7ead4ee69 | refs/heads/master | 2016-09-05T14:06:09.629943 | 2015-02-13T23:35:34 | 2015-02-13T23:35:34 | 31,043,179 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 419 | py | """
WSGI config for aico 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/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aico.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
| [
"alejoveintimilla@gmail.com"
] | alejoveintimilla@gmail.com |
abe0955e886d8fbc9de7f3e7ad550af81be6cedb | 5a07828016e8bafbea5dac8f83c8bfd5d0bfd603 | /py_290w290/140304_srw_output.py | 94f032f09c22370f14899c0b9c40b25777fbe84a | [] | no_license | JJHopkins/rajter_compare | db5b88d2c6c1efc0fead9b6ed40fb3cce36bedb4 | 2ba52f4f16cf2aca350a82ea58d0aa8f8866c47c | refs/heads/master | 2020-06-04T23:53:57.089329 | 2014-04-08T18:02:30 | 2014-04-08T18:02:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,695 | py | #$ {\bf Free energy between two skewed cylinders (CG-10 in water). Full retarded result, function of separation $\ell$ and angle $\theta$} \\
#$ Equation 12: $G(\ell,\theta) = - \frac{ (\pi R_1^{2})(\pi R_2^{2}) }{2 \pi~\ell^{4} \sin{\theta}} \left( {\cal A}^{(0)}(\ell) + {\cal A}^{(2)}(\ell) \cos 2\theta \right)$ \\
#$ $G(\ell,\theta) = - \frac{k_BT}{64 \pi} \frac{ \pi^2 R_1^{2} R_2^{2} }{\ell^{4} \sin{\theta}} {\sum_{n=0}^{\infty}}' \Delta_{1,\parallel} \Delta_{2,\parallel} ~p_n^{4} ~\int_0^{\infty} t dt ~\frac{e^{- 2 p_n \sqrt{t^{2} + 1}}}{(t^{2} + 1)} \tilde g(t, a_1(i \omega_n), a_2(i \omega_n), \theta),$ \\
#$ with $\tilde g(t, a_1, a_2, \theta) &=& 2 \left[ (1+3a_1)(1+3a_2) t^{4} + 2 (1+2a_1+2a_2+3a_1a_2) t^{2} + 2(1+a_1)(1+a_2)\right] + \nonumber \\
#$ & & ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + (1-a_1)(1-a_2)(t^{2} + 2)^2 \cos 2\theta.$ \\
#!/usr/bin/python
import numpy as np
import scipy.optimize as opt
from scipy.integrate import trapz
import matplotlib.pyplot as pl
from matplotlib import axis as ax
# use pyreport -l file.py
from pylab import show
from matplotlib.ticker import MultipleLocator
from mpl_toolkits.mplot3d import Axes3D
from pylab import pause
from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages('plots/skew_ret_water/skew_ret_water.pdf')
eiz_x = np.loadtxt('data/eiz_x_output_eV.txt') #perpendicular, radial
eiz_y = np.loadtxt('data/eiz_y_output_eV.txt')
eiz_z = np.loadtxt('data/eiz_z_output_eV.txt') # parallel,axial
#eiz_w = 1.0 + np.zeros(len(eiz_z))
eiz_w = np.loadtxt('data/eiz_w_output_eV.txt') # water as intervening medium
eiz_w[0] = eiz_w[1] #NOTE: there is a jump from first val down to second val
r_1 = 1.0e-9
r_2 = 1.0e-9
c = 2.99e8 # in m/s
T = 297
kb = 1.3807e-23 # in J/K
coeff = 2.411e14 # in rad/s
# NOTES:
# at RT, 1 kT = 4.11e-21 J
# 1 eV = 1.602e-19 J = 0.016 zJ
# h_bar_eV = 6.5821e-16 eVs
# h_bar = 1. #1.0546e-34 #in Js
#kb = 8.6173e-5 # in eV/K
# z_n_eV = (2*pi*kT/h_bar)n
# = (0.159 eV) / (6.5821e-16 eVs)
# = n*2.411e14 rad/s
# z_n_J = (2*pi*kT/h_bar)n
# = (1.3807e-23 J/K) / (1.0546e-34 Js))*n
# = n*2.411e14 rad/s
#coeff = 0.159 # in eV w/o 1/h_bar
ns = np.arange(0.,500.)
z = ns * coeff
ls = np.linspace(1.0e-9, 1.0e-6, 200)
#thetas = np.linspace((0.01)*np.pi,(1./2)*np.pi,25)
thetas = [np.pi/8,np.pi/4,np.pi/3,np.pi/2]
dt = 1.0
ts = np.arange(1.0,10000.,dt)
def Aiz(perp, par,med):
return (2.0*(perp-med)*med)/((perp+med)*(par-med))
def ys(a,time,eizw,L, N):
term0 = ( time / (time*time+1.0) )
term1 = ( time**4 * 2.0*(1. + 3.*a)*(1.+3.*a) )
term2 = ( time**2 * 4.0*(1. + 2.0*a+2.0*a+3.0*a*a))
term3 = ( 4.0*(1. + a)*(1.0 + a) )
term4 = (-2.0 * np.sqrt(eizw)* L * coeff * N / c * np.sqrt(time*time + 1.0))
#print 'ys term0', term0
#print 'ys term1', term1
#print 'ys term2', term2
#print 'ys term3', term3
#print 'ys term4', term4
#print '----'
return (term0) * np.exp(term4)*( (term1) + (term2) + (term3))#* term5
def y_2s(a,time,eizw, L, N):
term0 = (time / (time*time+1.0) )
term1 = ((1.- a)*(1.- a)*(time * time + 2.0)*(time * time + 2.0))
term2 = (-2.0 * np.sqrt(eizw)* L * coeff * N / c * np.sqrt(time*time + 1.0))
#print 'y_2s term0', term0
#print 'y_2s term1', term1
#print 'y_2s term2', term2
#print '----'
return term0 * term1* np.exp(term2) #* term3
def As(eizz,eizw,L,N,Y):
term1 = (((eizz-eizw)/eizw)*((eizz-eizw)/eizw))
term2 = (Y * eizw *eizw * (coeff*N)**4 * L**4 / (c**4))
#term3 = Y
#print 'As term1 = ', term1
#print 'As term2 = ', term2
##print 'As term3 = ', term3
#print '----'
return term1 * term2# * term3
def A_2s(eizz,eizw, L , N ,Y):
term1 = (((eizz-eizw)/eizw)*((eizz-eizw)/eizw))
term2 = (Y * eizw *eizw * (coeff*N)**4 * L**4 / (c**4))
#term3 = Y
#print 'A_2s term1 = ', term1
#print 'A_2s term2 = ', term2
##print 'A_2s term3 = ', term3
#print '----'
return (term1 * term2)# * term3
y = np.zeros(shape=(len(ns),len(ls)))
y_2 = np.zeros(shape=(len(ns),len(ls)))
A = np.zeros(shape=(len(ns),len(ls)))
A_2 = np.zeros(shape=(len(ns),len(ls)))
EL = np.zeros(len(ls))
G_l_t_dt = np.zeros(shape=(len(ls),len(thetas)))
aiz = []
aiz = Aiz(eiz_x,eiz_z, eiz_w) # of length = len(ns)
for k,length in enumerate(ls):
sum_A = np.empty(len(ls))
sum_A_2 = np.empty(len(ls))
for j,n in enumerate(ns):
# Integral:
y[j,k] = trapz(ys(aiz[j],ts,eiz_w[j],length,n),ts,dt)
y_2[j,k] = trapz(y_2s(aiz[j],ts,eiz_w[j],length,n),ts,dt)
#print 'dt Integral y = ',i,k,j, y
#print 'dt Integral y_2 = ',i,k,j, y_2
#print '----'
#print 'N terms for A0 = ' , As(eiz_z[j],eiz_w[j],length,n,y)
#print 'N terms for A2 = ', A_2s(eiz_z[j],eiz_w[j],length,n,y_2)
#print '----'
A[j,k] = As(eiz_z[j],eiz_w[j],length,n,y[j,k])
A_2[j,k] = A_2s(eiz_z[j],eiz_w[j],length,n,y_2[j,k])# * np.cos(2.0*theta)
A[0] = (1./2)*A[0]
A_2[0] = (1./2)*A_2[0]
sum_A = np.sum(A,axis=0)
#print 'sum of A0 = ', k,j,sum_A
sum_A_2 = np.sum(A_2,axis=0)
#print 'sum of A2 = ', k,j,sum_A_2
#print '----'
#print 'shape sum_A_2 = ', np.shape(sum_A_2)
#sys.exit()
for k,length in enumerate(ls):
for i, theta in enumerate(thetas):
EL[k] = 1./(length*length*length*length)
G_l_t_dt[k,i] = (1.602e-19 / 4.11e-21) * (1./32) * EL[k]*np.pi*r_1*r_1*r_2*r_2*(sum_A[k] + sum_A_2[k]* np.cos(2.0*theta) )/(2.0*np.sin(theta))# (1e21)*
np.savetxt('compare/srw_min_thetas.txt',G_l_t_dt)
pl.figure()
pl.loglog(ls,(kb*T/32)*sum_A,'b-', label = r'$\mathcal{A^{(0)}}$')
pl.loglog(ls,(kb*T/32)*sum_A_2,'b--', label = r'$\mathcal{A^{(2)}}$')
pl.xlabel(r'$\mathrm{separation}\,\ell\,\,\,\rm{[m]}$', size = 20)
pl.ylabel(r'$\mathrm{\mathcal{A^{(0)},\,\,A^{(2)}}}$', size = 20)
#pl.title(r'$\mathrm{Hamaker \, coeff.s \,:\,skewed,\,retarded,\,water}$', size = 20)
pl.legend(loc = 'upper right')
pl.axis([1e-9,1e-6,1e-24,1e-19])
pl.savefig('plots/skew_ret_water/skew_ret_water_A0_A2.pdf')
show()
ls4 = 1e9*ls[ 2]#2]
ls5 = 1e9*ls[12]#4]
ls6 = 1e9*ls[22]#6]
ls1 = 1e9*ls[32]#8]
ls2 = 1e9*ls[42]#12]
ls3 = 1e9*ls[52]#16]
fig = pl.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
#pl.semilogy(thetas, G_l_t_dt)
ax.semilogy(thetas, G_l_t_dt[ 2,:], label = r'$\ell$ = %1.2f nm' %ls4)
ax.semilogy(thetas, G_l_t_dt[12,:], label = r'$\ell$ = %1.2f nm' %ls5)
ax.semilogy(thetas, G_l_t_dt[22,:], label = r'$\ell$ = %1.2f nm' %ls6)
ax.semilogy(thetas, G_l_t_dt[32,:], label = r'$\ell$ = %1.2f nm' %ls1)
ax.semilogy(thetas, G_l_t_dt[42,:], label = r'$\ell$ = %1.2f nm' %ls2)
ax.semilogy(thetas, G_l_t_dt[52,:], label = r'$\ell$ = %1.2f nm' %ls3)
#ax.semilogy(0,0,'', label = r'$G_\theta = cos(2\theta)/2sin(\theta)$')
pl.xlabel(r'$Angle\,\,\mathrm{[radians]}$', size = 20)
pl.ylabel(r'$-G(\ell,\theta)\,\,\mathrm{[k_{B}T]}$', size = 20)
pl.axis([0,1.7,1e-10,1.0])
#pl.axis([0,1.7,1e-3,1e4])
#pl.title(r'$\mathrm{-G(\ell,\theta)\,vs.\,angle:\,skewed,\,retarded,\,water}$', size = 20)
pl.legend(loc = 'lower left')
#pl.savefig('plots/skew_ret_water/skew_ret_water_G_vs_theta.pdf')
#show()
pl.savefig('plots/skew_ret_water/G_vs_theta_fixed_l.pdf')
show()
pl.figure()
pl.loglog(ls, G_l_t_dt)#, label = labels[i])
#pl.loglog(ls, G_l_t_dt[:,3], label = r'$\theta = \pi/4$')
#pl.loglog(ls, G_l_t_dt[:,4], label = r'$\theta = \pi/3$')
#pl.loglog(ls, G_l_t_dt[:,6], label = r'$\theta = \pi/2$')
pl.xlabel(r'$Separation,\,\ell\,\,\mathrm{[m]}$', size = 20)
pl.ylabel(r'$-G(\ell,\theta)\,\,\mathrm{[k_{B}T]}$', size = 20)
pl.axis([1.0e-9, 1.0e-6,1e-16,1e3])
#pl.axis([1.0e-9, 1.0e-6,1e-3,1e3])
#pl.title(r'$\mathrm{-G(\ell,\theta)\,vs.\,separation:\,skewed,\,retarded,\,water}$', size = 20)
pl.legend(loc = 'best')
pl.savefig('plots/compare/skew_ret_water_G_vs_l.pdf')
show()
| [
"hopkins.jaime@gmail.com"
] | hopkins.jaime@gmail.com |
331f395e573d869b54436b102ea16c5d40d4a7ba | 79d59e85e56d5bdab49106ef6be3fe03bc933f78 | /Python/8 KYU/Remove First and Last Character.py | ecdcc6b506d12940717a207f8641bd318599997c | [] | no_license | kupolak/codewars | 873f33a355a28efef33aca8c8a1ab606d439ae4b | 35146ac66fc8d64af24ed4c6fd235f11c185dd29 | refs/heads/master | 2022-06-19T01:39:19.152946 | 2022-05-29T11:25:08 | 2022-05-29T11:25:08 | 157,248,813 | 6 | 1 | null | null | null | null | UTF-8 | Python | false | false | 39 | py | def remove_char(s):
return s[1:-1]
| [
"noreply@github.com"
] | kupolak.noreply@github.com |
562af1591c7c8aaed98930a8d52e8fc206771d2b | 83c665b961e43f59c24ea1846f128f3b480f52d8 | /1_bit_and_2_bit_characters.py | 655a39aa6a56f3a688e35f9e219eca3bf5dbbb56 | [] | no_license | raunakb007/Leetcode-Problems | 2f1060296a8106d33354988a8eb0552c388af5d4 | 63a709834d2abc4280da0afc881e0a92fdad611a | refs/heads/main | 2023-01-01T22:10:31.914210 | 2020-10-20T02:27:11 | 2020-10-20T02:27:11 | 305,527,724 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 377 | py | class Solution:
def isOneBitCharacter(self, bits):
if len(bits) == 1:
return True
else:
count = 0
bits.reverse()
for i in bits:
if bits[i] == 0:
while bits[i] != 0:
count += 1
i += 1
return count % 2 == 0 | [
"raunak.bajaj@senso.ai"
] | raunak.bajaj@senso.ai |
1c21abdf3f78467636ab480a5d920a1cc71884ea | 0f5fb6d25525fe5b93d085833d65569a56997efb | /the_basics/read_temps_app/read_temps.py | 21c0bdb98cb98c483253256978bf3605f406391a | [] | no_license | AhmedAbdEllatiif/python_basics | 001f5116fee1d521659b06b12709832f11a535a1 | 5872abcd2fe1947ea658ee0dca4e2b7b1457a200 | refs/heads/main | 2023-03-20T11:38:24.932253 | 2021-03-07T09:50:35 | 2021-03-07T09:50:35 | 330,109,984 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 320 | py | import pandas #is a fast, powerful, flexible and easy to use open source data analysis
import os
import time
while True:
if os.path.exists('../files/temps_today.csv'):
data = pandas.read_csv("../files/temps_today.csv")
print(data.mean()['st2'])
else:
print('Not Found')
time.sleep(5) | [
"ahmedmohamedaneng@gmail.com"
] | ahmedmohamedaneng@gmail.com |
043fb6888a14c33fb733418fc16c4a68686be10f | 124d1241b6158ca1730ae3a69d123c01f5eb45fb | /db_tools/import_goods_data.py | 9c0db39be9ac9cf96d228f7735cb28f7af07131f | [] | no_license | QnHyn/MxShop | 8cd41b4590b4aa738c6aa6db90f6eb52627703b1 | aebdecae5d2d4b27dc1d0bd76acec59f5de89728 | refs/heads/master | 2023-01-18T23:43:05.693791 | 2020-11-10T15:41:22 | 2020-11-10T15:41:22 | 293,219,650 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,276 | py | import sys
import os
pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MxShop.settings")
import django
django.setup()
from goods.models import Goods, GoodsCategory, GoodsImage
from db_tools.data.product_data import row_data
for goods_detail in row_data:
goods = Goods()
goods.name = goods_detail["name"]
goods.market_price = float(int(goods_detail["market_price"].replace("¥", "").replace("元", "")))
goods.shop_price = float(int(goods_detail["sale_price"].replace("¥", "").replace("元", "")))
goods.goods_brief = goods_detail["desc"] if goods_detail["desc"] is not None else ""
goods.goods_desc = goods_detail["goods_desc"] if goods_detail["goods_desc"] is not None else ""
goods.goods_front_image = goods_detail["images"][0] if goods_detail["images"] else ""
category_name = goods_detail["categorys"][-1]
category = GoodsCategory.objects.filter(name=category_name)
if category:
goods.category = category[0]
goods.save()
for goods_image in goods_detail["images"]:
goods_image_instance = GoodsImage()
goods_image_instance.image = goods_image
goods_image_instance.goods = goods
goods_image_instance.save() | [
"54275515+QnHyn@users.noreply.github.com"
] | 54275515+QnHyn@users.noreply.github.com |
37694eb9518f87e68f56b733a3fbd604c4eddd79 | 11ad104b0309a2bffd7537d05e2ab3eaf4aed0ca | /homeassistant/components/rachio/device.py | 9d7c30579394412becf75ff8253ffd54c62cc51b | [
"Apache-2.0"
] | permissive | koying/home-assistant | 15e5d01a45fd4373b3d286e1b2ca5aba1311786d | 9fc92ab04e0d1933cc23e89b4095714aee725f8b | refs/heads/dev | 2023-06-24T01:15:12.150720 | 2020-11-01T12:27:33 | 2020-11-01T12:27:33 | 189,232,923 | 2 | 1 | Apache-2.0 | 2023-01-13T06:04:15 | 2019-05-29T13:39:02 | Python | UTF-8 | Python | false | false | 6,956 | py | """Adapter to wrap the rachiopy api for home assistant."""
import logging
from typing import Optional
from homeassistant.const import EVENT_HOMEASSISTANT_STOP, HTTP_OK
from .const import (
KEY_DEVICES,
KEY_ENABLED,
KEY_EXTERNAL_ID,
KEY_FLEX_SCHEDULES,
KEY_ID,
KEY_MAC_ADDRESS,
KEY_MODEL,
KEY_NAME,
KEY_SCHEDULES,
KEY_SERIAL_NUMBER,
KEY_STATUS,
KEY_USERNAME,
KEY_ZONES,
)
from .webhooks import LISTEN_EVENT_TYPES, WEBHOOK_CONST_ID
_LOGGER = logging.getLogger(__name__)
class RachioPerson:
"""Represent a Rachio user."""
def __init__(self, rachio, config_entry):
"""Create an object from the provided API instance."""
# Use API token to get user ID
self.rachio = rachio
self.config_entry = config_entry
self.username = None
self._id = None
self._controllers = []
def setup(self, hass):
"""Rachio device setup."""
response = self.rachio.person.info()
assert int(response[0][KEY_STATUS]) == HTTP_OK, "API key error"
self._id = response[1][KEY_ID]
# Use user ID to get user data
data = self.rachio.person.get(self._id)
assert int(data[0][KEY_STATUS]) == HTTP_OK, "User ID error"
self.username = data[1][KEY_USERNAME]
devices = data[1][KEY_DEVICES]
for controller in devices:
webhooks = self.rachio.notification.get_device_webhook(controller[KEY_ID])[
1
]
# The API does not provide a way to tell if a controller is shared
# or if they are the owner. To work around this problem we fetch the webooks
# before we setup the device so we can skip it instead of failing.
# webhooks are normally a list, however if there is an error
# rachio hands us back a dict
if isinstance(webhooks, dict):
_LOGGER.error(
"Failed to add rachio controller '%s' because of an error: %s",
controller[KEY_NAME],
webhooks.get("error", "Unknown Error"),
)
continue
rachio_iro = RachioIro(hass, self.rachio, controller, webhooks)
rachio_iro.setup()
self._controllers.append(rachio_iro)
_LOGGER.info('Using Rachio API as user "%s"', self.username)
@property
def user_id(self) -> str:
"""Get the user ID as defined by the Rachio API."""
return self._id
@property
def controllers(self) -> list:
"""Get a list of controllers managed by this account."""
return self._controllers
def start_multiple_zones(self, zones) -> None:
"""Start multiple zones."""
self.rachio.zone.start_multiple(zones)
class RachioIro:
"""Represent a Rachio Iro."""
def __init__(self, hass, rachio, data, webhooks):
"""Initialize a Rachio device."""
self.hass = hass
self.rachio = rachio
self._id = data[KEY_ID]
self.name = data[KEY_NAME]
self.serial_number = data[KEY_SERIAL_NUMBER]
self.mac_address = data[KEY_MAC_ADDRESS]
self.model = data[KEY_MODEL]
self._zones = data[KEY_ZONES]
self._schedules = data[KEY_SCHEDULES]
self._flex_schedules = data[KEY_FLEX_SCHEDULES]
self._init_data = data
self._webhooks = webhooks
_LOGGER.debug('%s has ID "%s"', str(self), self.controller_id)
def setup(self):
"""Rachio Iro setup for webhooks."""
# Listen for all updates
self._init_webhooks()
def _init_webhooks(self) -> None:
"""Start getting updates from the Rachio API."""
current_webhook_id = None
# First delete any old webhooks that may have stuck around
def _deinit_webhooks(_) -> None:
"""Stop getting updates from the Rachio API."""
if not self._webhooks:
# We fetched webhooks when we created the device, however if we call _init_webhooks
# again we need to fetch again
self._webhooks = self.rachio.notification.get_device_webhook(
self.controller_id
)[1]
for webhook in self._webhooks:
if (
webhook[KEY_EXTERNAL_ID].startswith(WEBHOOK_CONST_ID)
or webhook[KEY_ID] == current_webhook_id
):
self.rachio.notification.delete(webhook[KEY_ID])
self._webhooks = None
_deinit_webhooks(None)
# Choose which events to listen for and get their IDs
event_types = []
for event_type in self.rachio.notification.get_webhook_event_type()[1]:
if event_type[KEY_NAME] in LISTEN_EVENT_TYPES:
event_types.append({"id": event_type[KEY_ID]})
# Register to listen to these events from the device
url = self.rachio.webhook_url
auth = WEBHOOK_CONST_ID + self.rachio.webhook_auth
new_webhook = self.rachio.notification.add(
self.controller_id, auth, url, event_types
)
# Save ID for deletion at shutdown
current_webhook_id = new_webhook[1][KEY_ID]
self.hass.bus.listen(EVENT_HOMEASSISTANT_STOP, _deinit_webhooks)
def __str__(self) -> str:
"""Display the controller as a string."""
return f'Rachio controller "{self.name}"'
@property
def controller_id(self) -> str:
"""Return the Rachio API controller ID."""
return self._id
@property
def current_schedule(self) -> str:
"""Return the schedule that the device is running right now."""
return self.rachio.device.current_schedule(self.controller_id)[1]
@property
def init_data(self) -> dict:
"""Return the information used to set up the controller."""
return self._init_data
def list_zones(self, include_disabled=False) -> list:
"""Return a list of the zone dicts connected to the device."""
# All zones
if include_disabled:
return self._zones
# Only enabled zones
return [z for z in self._zones if z[KEY_ENABLED]]
def get_zone(self, zone_id) -> Optional[dict]:
"""Return the zone with the given ID."""
for zone in self.list_zones(include_disabled=True):
if zone[KEY_ID] == zone_id:
return zone
return None
def list_schedules(self) -> list:
"""Return a list of fixed schedules."""
return self._schedules
def list_flex_schedules(self) -> list:
"""Return a list of flex schedules."""
return self._flex_schedules
def stop_watering(self) -> None:
"""Stop watering all zones connected to this controller."""
self.rachio.device.stop_water(self.controller_id)
_LOGGER.info("Stopped watering of all zones on %s", str(self))
| [
"noreply@github.com"
] | koying.noreply@github.com |
35d75586b492796c3b880eb9ba1d7a4d04e90660 | 31e78340d5e00ae4a037afc30e435b4945848ed6 | /docker-compose/django/web/settings.py | 3414953b86b8d729fbd707b2a06be576239b886b | [] | no_license | tejksat/playback | 01763ca52e1a464577512eab1760e4ff038d4c1d | 85eaf5c75eda3af03d417941402e96f2076bc332 | refs/heads/master | 2023-09-01T01:27:21.709497 | 2023-08-15T19:04:08 | 2023-08-15T19:04:08 | 155,582,625 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,127 | py | """
Django settings for web project.
Generated by 'django-admin startproject' using Django 2.2.9.
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
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 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 = '3ckp@u%4$2im-&*zv6wo@(6d08h^g()l7c5i1ql$54t6$55+r@'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'web.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 = 'web.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'HOST': 'db',
'PORT': 5432,
}
}
# 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/'
| [
"Alexander.Koshevoy@jetbrains.com"
] | Alexander.Koshevoy@jetbrains.com |
c84eb9a9ee394852af76dc1f5911b65b2139b491 | 741fb1ebff11260aae83e7cb52befc0e07bb70fc | /python_stack/flask_MySQL/email_validation_with_db/server.py | 251c663c0417ce9dd42175fc622cbcc7743ff8dd | [] | no_license | clarkkarenl/codingdojo_python_track | 0c2def27fec5d0c53d46b4f2aa44cbb5aeb79195 | 379e9c8f36ca5b8edd4932154c94297a2d4c27a0 | refs/heads/master | 2020-03-19T04:35:41.394941 | 2018-07-29T20:53:02 | 2018-07-29T20:53:02 | 135,844,895 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,300 | py | from flask import Flask, request, redirect, session, render_template, flash
from mysqlconnection import MySQLConnector
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
app = Flask(__name__)
mysql = MySQLConnector(app,'email_validation')
app.secret_key = "ThisIsASecret"
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/create', methods=['POST'])
def create():
email = request.form["email"]
check_query = "SELECT id FROM emails where email = \'" + str(email) + "\';"
check_result = mysql.query_db(check_query)
if len(check_result) > 0:
flash("Email is not valid!")
return redirect('/')
elif len(request.form['email']) < 1 or not EMAIL_REGEX.match(request.form['email']):
flash("Email is not valid!")
return redirect('/')
else:
query = "INSERT INTO `emails` (`email`, `created_at`, `updated_at`) VALUES (:field_one, now(), now());"
data = {"field_one": email}
result = mysql.query_db(query, data)
emails_query = "SELECT email, created_at FROM emails ORDER BY created_at DESC"
emails = mysql.query_db(emails_query)
return render_template("success.html", all_emails=emails, email=email)
app.run(debug=True)
| [
"clarkkarenl@users.noreply.github.com"
] | clarkkarenl@users.noreply.github.com |
c308ca29b4e2c932bf810e4e1107ebc5740cd519 | 782bbbc00a2d989b6b10b61b6391a8874d149cd9 | /users/populate_users.py | 9c68d5ca01416c51b4d4eb9c5eaad817073787c1 | [] | no_license | Angela-N/django-deployment-2 | af5a214489a0acad6b24095bb76608be06c96271 | 5f96d91f2025939558df0c24db965f71f255f8bc | refs/heads/master | 2020-03-26T05:19:34.848797 | 2018-08-14T08:53:44 | 2018-08-14T08:53:44 | 144,550,974 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 707 | py | import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arms_internship2.settings')
import django
django.setup()
# populate fake_script
import random
from users.models import UserModel
from faker import Faker
fake_gen = Faker()
# function to generate web pages and access records
def populate(n=5):
for entry in range(n):
name = fake_gen.name().split()
fake_first_name = name[0]
fake_last_name = name[1]
fake_email = fake_gen.email()
user = UserModel.objects.get_or_create(first_name=fake_first_name, last_name=fake_last_name, email=fake_email)[0]
if __name__ == '__main__':
print("Populating DB")
populate()
print('Done Populating DB')
| [
"angelanayiga@gmail.com"
] | angelanayiga@gmail.com |
9f72fdb8358a98de424612c427f7bd873201eff3 | c6856a600f33b1db415e8566368229ea2aca3ac8 | /testpro/settings.py | 56cd08667d6566b4e4a373dba4e938b44e58d064 | [] | no_license | zhouwenliang/scrapy_bilibili_search | 3954a48336a418d90712f473377280b81477e448 | 22c9f75d33cd9d2239981697ca22be03e0d915f3 | refs/heads/master | 2021-01-21T12:20:26.160636 | 2017-09-01T02:42:58 | 2017-09-01T02:42:58 | 102,065,458 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,298 | py | # -*- coding: utf-8 -*-
# Scrapy settings for testpro project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'testpro'
SPIDER_MODULES = ['testpro.spiders']
NEWSPIDER_MODULE = 'testpro.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'testpro (+http://www.yourdomain.com)'
# Obey robots.txt rules
#ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
# SPIDER_MIDDLEWARES = {
# 'testpro.middlewares.PhantomJSMiddleware': 543,
# }
# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
'testpro.middlewares.PhantomJSMiddleware': 543,
}
ITEM_PIPELINES = {
'testpro.pipelines.FilterPipeline': 1,
'testpro.pipelines.ImgPipeline': 100,
'testpro.pipelines.JsonPipeline': 300,
}
IMAGES_STORE = 'D:/img'
IMAGES_EXPIRES = 90
IMAGES_MIN_HEIGHT = 10
IMAGES_MIN_WIDTH = 10
# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
| [
"gzzhouwenliang@corp.netease.com"
] | gzzhouwenliang@corp.netease.com |
74a91c2a3e860fd41d6faeea8fa41813818d2adb | 040ad9e60a7f29603284328542bd5a437f4c37b3 | /mypackage/__init__.py | 380d1f92214cdb28fb1b0b731c1834db23539e55 | [] | no_license | Roiak2/hack-7-scripting | 15185a5215f0f79da4c9995fa193096bbcfe67f3 | 6278fa2a9588dd3527b8eb9d70b6e46a9164998d | refs/heads/main | 2023-03-04T06:40:25.369772 | 2021-02-15T00:52:10 | 2021-02-15T00:52:10 | 338,910,705 | 0 | 0 | null | 2021-02-14T21:59:12 | 2021-02-14T21:59:12 | null | UTF-8 | Python | false | false | 123 | py | #!/usr/bin/env python
"""
The mypackage package is used to learn about package filestructure.
"""
from . import mymodule
| [
"ra3040@columbia.edu"
] | ra3040@columbia.edu |
1846fa2b488f8ed5802019486e8766c4aa9e9655 | f490e7e2bab3a5918c3de3bf54afe2fbf1834303 | /Exercises/xmlparsing.py | d1801bb673c201fd6684afa300ae04388a40aea5 | [
"MIT"
] | permissive | yurijserrano/Linkedin-Learning-Python | 4ea66b029e6d5109d29c64004e58c6610261eee6 | 5169f8dcb85118a796e4da368cd138197ea0d2b5 | refs/heads/master | 2023-04-20T19:35:48.012569 | 2021-05-03T15:39:39 | 2021-05-03T15:39:39 | 363,798,850 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 925 | py | '''
Example file for parsing and processing XML
'''
import xml.dom.minidom
def main():
# Use the parse() function to load and parse an XML file
doc = xml.dom.minidom.parse("samplexml.xml")
# Print out the document node and the name of the first child tag
print(doc.nodeName)
print(doc.firstChild.tagName)
# Get a list of XML tags from the document and print each one
skills = doc.getElementsByTagName("skill")
print("%d skills: " % skills.length)
for skill in skills:
print(skill.getAttribute("name"))
# Create a new XML tag and add it into the document
newSkill = doc.createElement("skill")
newSkill.setAttribute("name","Java")
doc.firstChild.appendChild(newSkill)
skills = doc.getElementsByTagName("skill")
print("%d skills: " % skills.length)
for skill in skills:
print(skill.getAttribute("name"))
if __name__ == "__main__":
main() | [
"yurijserrano@gmail.com"
] | yurijserrano@gmail.com |
85f3de216eb2918fea87e7dbd66b368d9a6d1a1e | 4007aa946f90ba6285111a6ed2a2f50d6522a688 | /myproject/myproject/myproject/settings.py | 0d3dca11a936c62ed2c9fa12e84b5e7770c03337 | [] | no_license | anantsarin/Django | eccbc67e57dfb465a15bb23af125df4cfa7c0efc | fd5d64a075f28b7cc6752a245bfe6ee6afe08131 | refs/heads/master | 2021-01-11T01:03:00.368383 | 2016-10-25T18:48:59 | 2016-10-25T18:48:59 | 71,083,065 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,220 | py | """
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 1.10.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'project_app',
'blog',
]
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 = 'myproject.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 = 'myproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_main',
'USER': 'root',
'PASSWORD': 'Ankitsarin',
'HOST': '127.0.0.1', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/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/1.10/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/1.10/howto/static-files/
STATIC_URL = '/static/'
| [
"anant.sarin@gmail.com"
] | anant.sarin@gmail.com |
d92053657c4bfcaf5e3fcb5f2e6c8c2eee05111e | 205b602b45e9e81df515bb12234c8ac014576bdd | /풀이/5/연습문제5-1.py | 66e28c190d7ad1243c8a950241847f65eca35588 | [] | no_license | DongGeon0908/python_basic_algorithm | bc1745b9d9b8c7b19a3277f2734b63d7d14a8272 | 0b29dcfb53d2b17bb630eebf9319991cd5ae69fb | refs/heads/master | 2023-01-04T18:17:47.855981 | 2020-10-12T05:30:00 | 2020-10-12T05:30:00 | 294,415,579 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 102 | py | def fibo(n):
if n <= 1:
return n
return fibo(n - 2) + fibo(n - 1)
print(fibo(10))
| [
"noreply@github.com"
] | DongGeon0908.noreply@github.com |
675e8ba0659b69617d6c141dae8cc0fe5bc20667 | a98e089acf99b0efdec0ef76bc44d5d27b96ffd9 | /project/myapi/migrations/0001_initial.py | 322dacf2fde28a1f0cad2bde575519025d48930d | [] | no_license | kashishahuja02/login-system-try-django | dcf1ed2840ca8eea8465bc9e9a8d0c7dd46808f4 | 58322de5e8791f3ad6d510fb54b815491049aef7 | refs/heads/main | 2023-01-19T15:07:38.663977 | 2020-12-03T09:21:04 | 2020-12-03T09:21:04 | 318,137,820 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 621 | py | # Generated by Django 3.1.4 on 2020-12-02 17:45
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='student',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=60)),
('email', models.EmailField(max_length=254)),
('phone', models.IntegerField()),
],
),
]
| [
"noreply@github.com"
] | kashishahuja02.noreply@github.com |
cbf05f407f4904c82cb7da954d7ff7e579b3a76d | ceac66dbbcd993c56be9a85e6f1d2eaea5633add | /slicing.py | fa01e90e0eee94dd608ff5d5cf47bdbc978e341e | [] | no_license | Napster56/Sandbox | a72c74fcb24cc10c8b0c4324208b1d28cdb5c88e | a59479095abbf228e0fbf85ef0fc7723da2a9763 | refs/heads/master | 2021-01-22T20:50:26.716423 | 2017-07-31T01:48:27 | 2017-07-31T01:48:27 | 85,368,759 | 0 | 0 | null | 2017-07-31T01:48:28 | 2017-03-18T01:55:36 | Python | UTF-8 | Python | false | false | 482 | py | """
Strings are immutable
"""
word = "spam"
# word[1] = "l"
# print(word)
"""
Traceback (most recent call last):
File "F:/CP1404 Programming I/Sandbox/slicing.py", line 2, in <module>
word[1] = "l"
TypeError: 'str' object does not support item assignment
"""
new_word = word[:1] + 'l' + word[2:] # create a new string using concatenation
print(new_word) # no spaces between letters
print(new_word.isupper(), new_word.isnumeric(), new_word.islower()) | [
"tyrone.napoli@my.jcu.edu.au"
] | tyrone.napoli@my.jcu.edu.au |
d717cd091bcc917e84b1bfa4ab6190cfc8297675 | c150484cd7f11a56636770b7c7bb3e3d8131022f | /Routes/Lecturers.py | f6c89d261efc89b876cdabf87f40c6a9c1d61c2b | [] | no_license | Anna26100002/AnnaParshikova_BFI1801 | 13f4494734a791fd7bde65c87bb2ddef429bc4ed | a977c24829bfa283cbd19f3f7951c0e88850d787 | refs/heads/main | 2023-01-09T08:50:17.515030 | 2020-11-09T12:04:28 | 2020-11-09T12:04:28 | 311,312,421 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 919 | py | from flask.blueprints import Blueprint
from Managers.DatabaseManager import DatabaseManager
from models.Lecturer import Lecturer
from models.Interval import Interval
from flask import request, render_template
from extensions import db
lecturers = Blueprint('lecturers', __name__, template_folder='templates', static_folder='static')
@lecturers.route('/lecturers')
def index():
return render_template('Index.html', lecturers=Lecturer.query.all(),intervals=Interval.query.all())
@lecturers.route("/lecturers", methods=['GET', 'POST'])
def AddLecturers():
if request.method == 'POST':
db_manager = DatabaseManager(db)
db_manager.add_lecturer(first_name= request.form.get('first_name'), last_name=request.form.get('last_name'), patronymic=request.form.get('patronymic'))
return render_template('Index.html', lecturers=Lecturer.query.all(),intervals=Interval.query.all()) | [
"noreply@github.com"
] | Anna26100002.noreply@github.com |
cd9d7c7f2d5167845eb4a70793379015de0ce68c | 98544f7838e374cd33ca33b5291c9e3d82eeac59 | /context_feature/context_window.py | 9112e241ba5904207c5d68c9d3c28924fe40ba43 | [] | no_license | sstojanoska/NLP-project | 203d0e4fa179c321f47862d445274042c556dadd | bf62180626b8d772e23c7cb0c1decd8e430326df | refs/heads/master | 2022-09-05T09:46:27.813717 | 2020-05-24T22:03:07 | 2020-05-24T22:03:07 | 251,365,283 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,201 | py | import collections
def getWindowPol(main_df, entity_df, rels):
"""Finds polarity for each entity
:param main_df: article's dataFrame
:entity_df: entity'S dataFrame
:rels: dict(word,sentiment) calculated in conext_deprel.py
:return: polarity score of an entity [-1,0,1]
"""
mentions = entity_df.word.tolist()
d = {}
d_pol = {}
for m in mentions:
tags = []
i = main_df.loc[main_df['word']==m].index.values.astype(int)[0]
if i < 3:
tags.append(main_df.loc[i+1,'word'])
tags.append(main_df.loc[i+2,'word'])
tags.append(main_df.loc[i+3,'word'])
elif i >= len(main_df)-3:
tags.append(main_df.loc[i-3,'word'])
tags.append(main_df.loc[i-2,'word'])
tags.append(main_df.loc[i-1,'word'])
else:
tags.append(main_df.loc[i-3,'word'])
tags.append(main_df.loc[i-2,'word'])
tags.append(main_df.loc[i-1,'word'])
tags.append(main_df.loc[i+1,'word'])
tags.append(main_df.loc[i+2,'word'])
tags.append(main_df.loc[i+3,'word'])
d[m]=tags
for k,v in d.items():
for vx in v:
if vx in rels.keys():
d_pol[k] = rels[vx]
if d_pol != {}:
fl = collections.Counter([ e for ls in d_pol.values() for e in ls]).most_common(1)[0][0]
return fl
else:
return 0 | [
"sanja.s.stojanoska@gmail.com"
] | sanja.s.stojanoska@gmail.com |
429f4ae4157d9c737002e39283bf0b4f5ce14f48 | 28c396b5ca6697bdea69d3d1aef803e161945c7a | /model/route.py | 4e8779854d8b4155c63e4f5e507ea0916377b128 | [
"MIT"
] | permissive | iTerminate/Taskington | 6ee235188049fd076439a6f6d2c3276ad2092366 | 64a9e779c86def80579dfe7926586faf063a12f7 | refs/heads/master | 2020-07-24T01:30:21.016407 | 2017-12-01T20:34:14 | 2017-12-01T20:34:14 | 94,363,045 | 0 | 0 | null | 2017-12-01T20:35:33 | 2017-06-14T18:50:12 | Python | UTF-8 | Python | false | false | 2,466 | py | '''
Created on May 2015
@author: Arthur Glowacki, Argonne National Laboratory
Copyright (c) 2013, Stefan Vogt, Argonne National Laboratory
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 the Argonne National Laboratory 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 HOLDER 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.
'''
from handlers import HandlerBase
class Route:
def __init__(self, function_name, http_method, controller, path=None):
path = Route.__getPath(path, function_name)
self.name = function_name
self.action = function_name
self.controller = controller
self.method = http_method
self.path = path
@staticmethod
def __getPath(path, function_name):
if path is None:
return '/%s' % function_name
return path
@staticmethod
def createRoutes(function_name, http_method, controller, includeOptionsHTTPMethodForPath=False, path=None):
routes = [];
routes.append(Route(function_name, http_method, controller, path));
if includeOptionsHTTPMethodForPath:
path = Route.__getPath(path, function_name)
routes.append(Route(HandlerBase.ADD_OPTIONS_FUNCTION_NAME, 'OPTIONS', controller, path))
return routes; | [
"dariuszjarosz@me.com"
] | dariuszjarosz@me.com |
6e92a253c516294dcf9184c303153cb0c1057748 | a61af03f0db98ef4a48e5c9f419594c0d0fc271f | /daily-interview-pro/floor-and-ceiling-of-a-binary-search-tree/solution.py | 855de6d946c2e4f2a77afaef542d78ecabe41c99 | [] | no_license | shivangi-prog/alg-studies | b8f4b4a66eef4ca28e25d56de87be14d8a3be438 | ea34eeb48f05c5f76555a41b9d12bbf490f3aaf0 | refs/heads/master | 2023-01-04T16:13:44.488591 | 2020-10-29T13:13:05 | 2020-10-29T13:13:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 502 | py | class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def findCeilingFloor(root, k, floor=None, ceil=None):
if root != None:
value = root.value
if value == k:
floor = ceil = value
elif value > k:
[floor, ceil] = findCeilingFloor(root.left, k, floor, value)
elif value < k:
[floor, ceil] = findCeilingFloor(root.right, k, value, ceil)
return [floor, ceil]
| [
"lucas.marques@ebanx.com"
] | lucas.marques@ebanx.com |
a9a4465c8fb5c660cec33ac7ff98bdf605c5e897 | b43e0e4eae5ba1de1841083a165c8bba5bf05d54 | /leve2/firstsite/firstapp/models.py | 90ff6ec67ad7bcb0d7f9faeac3458c3b13a539e9 | [] | no_license | kingleoric2010/wangyi | b9ec72173117e31f42656883ba6913be1c432eed | 7b497fa8e1a4b9cf2b279b465e32ad78082c9e89 | refs/heads/master | 2021-01-01T16:59:32.249214 | 2017-07-21T17:51:21 | 2017-07-21T17:51:21 | 97,972,943 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 808 | py | from django.db import models
# Create your models here.
class People(models.Model):
name = models.CharField(null=True,blank=True,max_length=200)
job = models.CharField(null=True,blank=True,max_length=200)
def __str__(self):
return self.name
class Article(models.Model):
headline = models.CharField(null=True,blank=True,max_length=500)
content = models.TextField(null=True,blank=True)
TAG_CHOICES = {
('tech','tech'),
('life','life'),
}
tag = models.CharField(null=True,blank=True, max_length=500, choices=TAG_CHOICES)
def __str__(self):
return self.headline
class Comment(models.Model):
name = models.CharField(null=True,blank=True,max_length=50)
comment = models.TextField()
def __str__(self):
return self.comment
| [
"kingleoric2010@163.com"
] | kingleoric2010@163.com |
33fde1b7da540c5a7e62adfc3ac070cd21377032 | ab35e9383bd0b2f8a9f6a2865a821be646d94afe | /conftest.py | 5e8963e0ed3adab43476cadf2bb5c3d020384ae2 | [] | no_license | chloeeew/appium-utils | 9247fb06ceab8980d2765dedc6f6df954a69da68 | df003fdfc54d5ae82217825038a369e2a9da61a6 | refs/heads/main | 2023-07-07T07:31:47.158685 | 2021-08-02T02:11:55 | 2021-08-02T02:11:55 | 391,783,610 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,272 | py | """
==================
Author:Chloeee
Time:2021/4/4 19:18
Contact:403505960@qq.com
==================
"""
import pytest
import time
from appium.webdriver import Remote
from pages.user import UserPage
from pages.nav import NavPage
@pytest.fixture()
def open_app():
desired_cap = {
"automationName": "UiAutomator2",
"platformName": "Android",
"platformVersion": "5.1.1",
"deviceName": "Huawei P40 Pro",
"appPackage": "com.have.been.erased",
"appActivity": "com.have.been.erased.activity.WelcomeActivity",
"noReset": False
}
driver = Remote(command_executor="http://127.0.0.1:4723/wd/hub",
desired_capabilities=desired_cap)
driver.implicitly_wait(10)
yield driver
time.sleep(5)
driver.quit()
@pytest.fixture()
def login_app(open_app):
login_driver = open_app
nav = NavPage(login_driver)
nav.click_user()
bp = UserPage(login_driver)
bp.login_lemon("135318","89")
yield login_driver
@pytest.fixture()
def into_topic():
pass
def pytest_collection_modifyitems(items):
for item in items:
item.name = item.name.encode('utf-8').decode('unicode-escape')
item._nodeid = item.nodeid.encode('utf-8').decode('unicode-escape') | [
"403505960@qq.com"
] | 403505960@qq.com |
70eb2dc1e03ee49f8ad9c674c6eceaac5fa7b409 | edcd3847115ae76b68195bdda54e04ed06a04318 | /tests/infographics/test_models.py | d6e17b25f0cf87340993389f8d0404fa4edfac7c | [
"MIT"
] | permissive | NeuralNoise/django-bulbs | b146725fdcb3bfb4158aec90d5fc0b7830d8fcbe | 0c0e6e3127a7dc487b96677fab95cacd2b3806da | refs/heads/master | 2021-06-07T08:11:31.996448 | 2016-09-21T19:35:32 | 2016-09-21T19:35:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,830 | py | from django.db import connection
from rest_framework.serializers import ValidationError
from bulbs.infographics.models import BaseInfographic, InfographicType
from bulbs.utils.test import BaseIndexableTestCase
class BaseInfographicTestCase(BaseIndexableTestCase):
def test_infographic_data_is_jsonb(self):
"""Asserts that the `BaseInfographic.data` field is of type `jsonb`."""
field = BaseInfographic._meta.get_field("data")
self.assertEqual(field.db_type(connection), "jsonb")
def test_create_success(self):
infographic = BaseInfographic.objects.create(
title="A GOOD BOYS ADVENTURE",
infographic_type=InfographicType.LIST,
data={
"is_numbered": True,
"entries": [{
"title": "Michael Bayless",
"copy": "How did he do that?",
"image": {"id": 1}
}]
}
)
db_infographic = BaseInfographic.objects.get(pk=infographic.pk)
self.assertEqual(db_infographic.pk, infographic.pk)
def test_create_missing_field(self):
with self.assertRaises(ValidationError):
BaseInfographic.objects.create(
title="A GOOD BOYS ADVENTURE",
infographic_type=InfographicType.LIST,
data=[{
"is_numbered": True,
"copy": "How did he do that?",
"image": {"id": 1}
}]
)
def test_create_wrong_type(self):
with self.assertRaises(ValidationError):
BaseInfographic.objects.create(
title="A GOD BOY ADVENTURE",
infographic_type=InfographicType.LIST,
data=[{
"title": "It me.",
"is_numbered": "Tru",
"copy": "Who dat?",
"image": {"id": 1}
}]
)
def test_timeline_validator(self):
BaseInfographic.objects.create(
title="A GOD BOY ADVENTURE",
infographic_type=InfographicType.TIMELINE,
data={
"entries": [{
"title": "Sickass",
"copy": "heya",
"image": {"id": 50}
}]
}
)
def test_get_infographic_type_name(self):
instance = BaseInfographic.objects.create(
title="A GOD BOY ADVENTURE",
infographic_type=InfographicType.TIMELINE,
data={
"entries": [{
"title": "Sickass",
"copy": "heya",
"image": {"id": 50}
}]
}
)
self.assertEqual(instance.get_infographic_type_name(), "Timeline")
| [
"cam.m.lowe@gmail.com"
] | cam.m.lowe@gmail.com |
d4e20d45365608bb5cfac8062dcff7ebb2f7736f | f31c8a2438542e1b653bd278b7ce81ac91279483 | /ECommerce/ECommerce/settings.py | 64bf0d93065a6fc21f79d366fcc39ee3fd70b406 | [] | no_license | hirvapatel2102/Python_Internship | 65900b8cfd610c3ad628fd46d0f475fe79e90f3c | 470085cd6f791dee8527299bf82435989ef7a4aa | refs/heads/main | 2023-06-12T04:17:47.999086 | 2021-07-01T17:27:24 | 2021-07-01T17:27:24 | 372,713,039 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,406 | py | """
Django settings for ECommerce project.
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-5kurc53(@2l4g(b0k%bwmm-vp3tp869z1_xphs4nf01+489x92'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'myapp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'ECommerce.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ECommerce.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
| [
"hirva2102@gmail.com"
] | hirva2102@gmail.com |
caa0648dfb78cf70d7ee34a9981e58c1f88cb2fc | f5210a4424aa640286157c6757a9c9ca2fd07959 | /Espece.py | 8fc1b9c4ae832c646614e3f975e4f2e7c514a0fe | [] | no_license | MichaelDaube/Ecosysteme | c81625c3df23bf260a6cf92aa4911248d24cf330 | eb58e5b806a474393e2b871d15774c6d887dcfc9 | refs/heads/master | 2020-04-09T23:46:52.549652 | 2019-01-06T20:51:31 | 2019-01-06T20:51:31 | 160,666,249 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 667 | py | class Espece():
def __init__(self, animal):
self.espece = animal.nom
self.individus = []
self.evolutionPopulation = []
self.taillePopulation = 0
def ajoutIndividu(self, individu):
self.individus.append(individu)
self.taillePopulation += 1
def retraitIndividu(self, individu):
self.individus.remove(individu)
self.taillePopulation -= 1
def accumulationDonnees(self):
self.evolutionPopulation.append(self.taillePopulation)
def getIndividus(self):
return self.individus
def getTaillePopulation(self):
return self.taillePopulation
| [
"noreply@github.com"
] | MichaelDaube.noreply@github.com |
ad35a9f1e5de6a0f0bdd9ec49fba62a4cf66dc82 | e27cee635eb69d54f8a9805895db6a5b62ce3307 | /main.py | b5a312a2a3dee303568de6f9cb92a574f4ea7e25 | [] | no_license | blacksleek/CLL-ACE | 2bb865db6308943c0daa40b05ff910b1f3cf9b4e | 03be12794c7f7b12d50f7980b48f1d85542914c7 | refs/heads/master | 2020-06-04T12:23:16.880900 | 2012-08-25T08:09:33 | 2012-08-25T08:09:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 49,402 | py | # -*- coding: utf-8 -*-
import webapp2
from google.appengine.ext import db
from google.appengine.api import users
entry_open = """<html>
<head>
<title>文学 ACE!</title>
<link rel="icon" type="image/png" href="/Resource/images/favicon.png">
<link rel="stylesheet" href="/Resource/jquery.mobile-1.1.1.min.css" />
<link rel="stylesheet" href="/Resource/jqm-icon-pack-2.1.2-fa.css" />
<script src="/Resource/jquery-1.7.2.min.js"></script>
<script src="/Resource/jquery.mobile-1.1.1.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body align="center">"""
entry_close = """<br><br></body><div data-role="footer" data-position="fixed">© 文学 ACE! (v3.2)</div></html>"""
header_open = """<div data-role="header" data-position="fixed">
<a href="/menu" data-role="button" data-rel="dialog" data-icon="list-ul" data-iconpos="notext"></a>
<h1>"""
header_close = """</h1><a href="%s" data-ajax="false" data-role="button" data-icon="power" class="ui-btn-right">注销</a>
</div>""" % users.create_logout_url("/")
class People(db.Model):
name = db.StringProperty()
class Text(db.Model):
name = db.ListProperty(str)
comment = db.ListProperty(str)
class Feedback(db.Model):
feedback = db.StringProperty()
name = db.StringProperty()
class Entry(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
self.redirect("/home")
else:
self.response.out.write(entry_open)
self.response.out.write("""<div data-role="header" data-position="fixed">""" + """<h1>文学 ACE!</h1>""")
self.response.out.write("""<a href="%s" class="ui-btn-right" data-role="button" data-ajax="false" data-inline="true" data-icon="power">登录</a></div>""" % users.create_login_url(self.request.uri))
self.response.out.write("""<img src="/Resource/images/home_bg.png" />""")
self.response.out.write(entry_close)
class Home(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
self.response.out.write(entry_open)
if People.get_by_key_name(user.email()):
self.response.out.write(header_open)
self.response.out.write(u"""主页 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
else:
self.response.out.write(header_open)
self.response.out.write(u"""主页 - """)
self.response.out.write(user.email())
self.response.out.write(header_close)
self.response.out.write("""<img src="/Resource/images/home_bg.png" />""")
self.response.out.write(entry_close)
else:
self.redirect("/error")
class Menu(webapp2.RequestHandler):
def get(self):
self.response.out.write(u"""<div data-role="dialog" data-rel="back">
<div data-role="header"><h1>菜单</h1>
<div data-role="navbar">
<ul>
<li><a href="/home" data-ajax="false" data-icon="fahome">主页</a></li>
<li><a href="/profile" data-ajax="false" data-icon="user">个人资料</a></li>
<li><a href="/text" data-ajax="false" data-icon="book">文学读物</a></li>
<li><a href="/oops" data-ajax="false" data-icon="comments">交易所</a></li>
<li><a href="/feedback" data-ajax="false" data-icon="envelope-alt">反馈</a></li>
<li><a href="/credits" data-ajax="false" data-icon="bookmark-empty">归功</a></li>
</ul>
</div></div></div>""")
class Profile(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
self.response.out.write(entry_open)
if People.get_by_key_name(user.email()):
self.response.out.write(header_open)
self.response.out.write(u"""个人资料 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
else:
self.response.out.write(header_open)
self.response.out.write(u"""个人资料 - """)
self.response.out.write(user.email())
self.response.out.write(header_close)
if People.get_by_key_name(user.email()):
self.response.out.write(u"""<br><form action="/profile_update" method="post" data-ajax="false">
用户名: <input type="text" name="name" value="%s" /><br>
<input type="submit" value="更新" data-inline="true" />
</form>""" % (People.get_by_key_name(user.email()).name))
else:
self.response.out.write(u"""<br><form action="/profile_update" method="post" data-ajax="false">
用户名: <input type="text" id="name" name="name" />
<input type="submit" value="更新" data-inline="true" />
</form>""")
self.response.out.write(entry_close)
else:
self.redirect("/error")
class Profile_Update(webapp2.RequestHandler):
def post(self):
user = users.get_current_user()
name = self.request.get("name")
if user and People.get_by_key_name(user.email()):
self.response.out.write(entry_open)
if name == People.get_by_key_name(user.email()).name:
People(key_name = user.email(), name = name).put()
self.redirect("/home")
else:
if name:
for i in People.all():
self.response.out.write(i.name)
if name == i.name:
self.response.out.write(header_open)
self.response.out.write(u"""个人资料 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br>用户名已被使用。<br>请另选用户名。<br>""")
self.response.out.write(u"""<a href="/profile" data-role="button" data-ajax="false" data-inline="true">返回</a>""")
if len(name) > 16:
self.response.out.write(header_open)
self.response.out.write(u"""个人资料 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br>用户名不能超过16字符。<br>请另选用户名。<br>""")
self.response.out.write(u"""<a href="/profile" data-role="button" data-ajax="false" data-inline="true">返回</a>""")
else:
if "<" in name and ">" in name:
name = name.replace("<", "<")
name = name.replace(">", ">")
People(key_name = user.email(), name = name).put()
self.redirect("/home")
else:
self.response.out.write(header_open)
self.response.out.write(u"""个人资料 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br>请输入全部项目。<br>""")
self.response.out.write(u"""<a href="/profile" data-role="button" data-ajax="false" data-inline="true">返回</a>""")
self.response.out.write(entry_close)
elif user:
if name:
for i in People.all():
if name == i.name:
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""个人资料 - """)
self.response.out.write(user.email())
self.response.out.write(header_close)
self.response.out.write("""<br>用户名已被使用。<br>请另选用户名。<br>""")
self.response.out.write("""<a href="/profile" data-role="button" data-ajax="false" data-inline="true">返回</a>""")
self.response.out.write(entry_close)
else:
if len(name) > 16:
self.response.out.write(header_open)
self.response.out.write(u"""个人资料 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br>用户名不能超过16字符。<br>请另选用户名。<br>""")
self.response.out.write(u"""<a href="/profile" data-role="button" data-ajax="false" data-inline="true">返回</a>""")
else:
People(key_name = user.email(), name = name).put()
self.redirect("/home")
else:
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""个人资料 - """)
self.response.out.write(user.email())
self.response.out.write(header_close)
self.response.out.write(u"""<br>请输入全部项目。<br>""")
self.response.out.write("""<a href="/profile" data-role="button" data-ajax="false" data-inline="true">返回</a>""")
self.response.out.write(entry_close)
else:
self.redirect("/error")
class Text_Page(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user and People.get_by_key_name(user.email()):
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""文学读物 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write("""<div data-role="content"><div data-role="collapsible-set" data-theme="a">
<div data-role="collapsible">
<h1>唐诗</h1>
<fieldset class="ui-grid-a">
<div class="ui-block-a">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="A_Farewell_of_a_Friend" />
<input type="text" style="display:none" name="title" value="《送友人》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《送友人》" /></form>
</div>
<div class="ui-block-b">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="A_Long_Climb" />
<input type="text" style="display:none" name="title" value="《登高》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《登高》" /></form>
</div>
<div class="ui-block-a">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="A_Song_of_the_Yan" />
<input type="text" style="display:none" name="title" value="《燕歌行》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《燕歌行》" /></form>
</div>
<div class="ui-block-b">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="Untitled" />
<input type="text" style="display:none" name="title" value="《无题》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《无题》" /></form>
</div>
</fieldset>
<div data-inline="true">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="Autumn_Evening_in_the_Mountains" />
<input type="text" style="display:none" name="title" value="《山居秋暝》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《山居秋暝》" /></form>
</div>
</div>
<div data-role="collapsible">
<h1>宋词</h1>
<fieldset class="ui-grid-a">
<div class="ui-block-a">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="Rain_Soaked_Bell" />
<input type="text" style="display:none" name="title" value="《雨霖铃》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《雨霖铃》" /></form>
</div>
<div class="ui-block-b">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="Charm_of_a_Maiden_Singer" />
<input type="text" style="display:none" name="title" value="《念奴娇》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《念奴娇》" /></form>
</div>
<div class="ui-block-a">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="Spring_in_Peach_Blossom_Land" />
<input type="text" style="display:none" name="title" value="《武陵春》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《武陵春》" /></form>
</div>
<div class="ui-block-b">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="Joy_of_Eternal_Union" />
<input type="text" style="display:none" name="title" value="《永遇乐》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《永遇乐》" /></form>
</div>
</fieldset>
<div data-inline="true">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="Riverside_Daffodils" />
<input type="text" style="display:none" name="title" value="《临江仙》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《临江仙》" /></form>
</div>
</div>
<div data-role="collapsible">
<h1>现代短片小说</h1>
<fieldset class="ui-grid-b">
<div class="ui-block-a">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="Medicine" />
<input type="text" style="display:none" name="title" value="《药》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《药》" /></form>
</div>
<div class="ui-block-b">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="Most_Precious" />
<input type="text" style="display:none" name="title" value="《最宝贵的》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《最宝贵的》" /></form>
</div>
<div class="ui-block-c">
<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="Line_of_Fate" />
<input type="text" style="display:none" name="title" value="《命运的迹线》" />
<input type="text" style="display:none" name="chapter" value="1" />
<input type="submit" data-role="button" value="《命运的迹线》" /></form>
</div>
</fieldset>
</div>
<div data-role="collapsible">
<h1>现代中篇小说</h1>
<ul data-role="listview">
<li><a href="/Fox_Volant_of_the_Snowy_Mountain" data-ajax="false">《雪山飞狐》</a></li>
</ul>
</div>
</div></div>
""")
self.response.out.write(entry_close)
elif user:
self.redirect("/visit_profile")
else:
self.redirect("/error")
class Fox_Volant_of_the_Snowy_Mountain(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user and People.get_by_key_name(user.email()):
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write("""《雪山飞狐》 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write("""<form action="/Read" method="post" data-ajax="false">
<input type="text" style="display:none" name="text" value="Fox_Volant_of_the_Snowy_Mountain" />
<input type="text" style="display:none" name="title" value="《雪山飞狐》" />
<select name="chapter" data-native-menu="false">
<option value="1">第一章</option>
<option value="2">第二章</option>
<option value="3">第三章</option>
<option value="4">第四章</option>
<option value="5">第五章</option>
<option value="6">第六章</option>
<option value="7">第七章</option>
<option value="8">第八章</option>
<option value="9">后记</option>
</select>
<input type="submit" data-role="button" value="阅读" />
</form>""")
self.response.out.write(entry_close)
elif user:
self.redirect("/visit_profile")
else:
self.redirect("/error")
class Read(webapp2.RequestHandler):
def post(self):
user = users.get_current_user()
title = self.request.get("title")
text = self.request.get("text")
chapter = self.request.get("chapter")
if user and text and chapter and title:
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(title + """ - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write("""</h1><a href="%s" class="ui-btn-right" data-ajax="false" data-role="button" data-icon="power">注销</a>
""" % users.create_logout_url("/"))
self.response.out.write("""<form action="/Board" method="post" data-ajax="false">
<input type="text" name="text" style="display:none" value="%s" />
<input type="text" name="chapter" style="display:none" value="%s" />
<input type="text" name="title" style="display:none" value="%s" />
<fieldset class="ui-grid-a">
<div class="ui-block-a" style="width:50%%">
<input type="search" name="word" data-mini="true" />
</div>
<div class="ui-block-b" style="width:50%%">
<input type="submit" value="%s" />
</div>
</fieldset>
</form></div>""" % (text, chapter, title, u"论坛搜索"))
text_name = text + " - " + chapter + ".txt"
text_open = open(text_name, "r")
contents = text_open.readlines()
for line in contents:
self.response.out.write(line +"""<br>""")
if text == """A_Farewell_of_a_Friend""":
self.response.out.write("""<br><br>在线朗读<br><audio src="/Resource/audio/A_Farewell_of_a_Friend_Audio.aac" controls></audio>""")
if text == """A_Long_Climb""":
self.response.out.write("""<br><br>在线朗读<br><audio src="/Resource/audio/A_Long_Climb_Audio.mp3" controls></audio>""")
if text == """A_Song_of_the_Yan""":
self.response.out.write("""<br><br>在线朗读<br><audio src="/Resource/audio/A_Song_of_the_Yan_Audio.mp3" controls></audio>""")
if text == """Untitled""":
self.response.out.write("""<br><br>在线朗读<br><audio src="/Resource/audio/Untitled_Audio.mp3" controls></audio>""")
if text == """Autumn_Evening_in_the_Mountains""":
self.response.out.write("""<br><br>在线朗读<br><audio src="/Resource/audio/Autumn_Evening_in_the_Mountains_Audio.mp3" controls></audio>""")
self.response.out.write(entry_close)
text_open.close()
else:
self.redirect("/error")
class Board(webapp2.RequestHandler):
def post(self):
user = users.get_current_user()
text = self.request.get("text")
chapter = self.request.get("chapter")
title = self.request.get("title")
word = self.request.get("word")
text_name = text + " - " + chapter + ".txt"
text_open = open(text_name, "r")
contents = text_open.readlines()
for line in contents:
if word.encode("utf-8") in line:
break
else:
self.redirect("/not_found")
if user and People.get_by_key_name(user.email()) and text and chapter and word:
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(word + """ - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
key_name = text + " - " + chapter + " - " + word
if Text.get_by_key_name(key_name):
if Text.get_by_key_name(key_name).name:
self.response.out.write("""<ul data-role="listview">""")
for i in range(0, len(Text.get_by_key_name(key_name).name)):
if Text.get_by_key_name(key_name).name[i] == user.email():
self.response.out.write(u"""<li>
<h4>%s</h4>
<p>%s</p>
<div align="right">
<form action="/Board_Delete" method="post" data-ajax="false">
<input type="text" style="display:none" name="key_name" value="%s" />
<input type="text" style="display:none" name="i" value="%s" />
<input type="text" style="display:none" name="text" value="%s" />
<input type="text" style="display:none" name="chapter" value="%s" />
<input type="text" style="display:none" name="word" value="%s" />
<input type="text" style="display:none" name="title" value="%s" />
<input type="submit" value="删除" data-mini="true" data-inline="true" />
</form>
</div>
</li>""" % (People.get_by_key_name(Text.get_by_key_name(key_name).name[i]).name, Text.get_by_key_name(key_name).comment[i], key_name, i, text, chapter, word, title))
else:
self.response.out.write("""<li>
<h4>%s</h4>
<p>%s</p>
</li>""" % (People.get_by_key_name(Text.get_by_key_name(key_name).name[i]).name, Text.get_by_key_name(key_name).comment[i]))
self.response.out.write("""</ul>""")
else:
self.response.out.write(u"""<br>目前还没有能显示的帖子。<br>""")
self.response.out.write(u"""请帮忙发问第一个问题!""")
else:
self.response.out.write(u"""<br>目前还没有能显示的帖子。<br>""")
self.response.out.write(u"""请帮忙发问第一个问题!""")
self.response.out.write(u"""<div>
<form action="/Board_Post" method="post" data-ajax="false">
<input type="text" name="key_name" style="display:none" value="%s" />
<input type="text" name="name" style="display:none" value="%s" />
<input type="text" name="chapter" style="display:none" value="%s" />
<input type="text" name="text" style="display:none" value="%s" />
<input type="text" name="title" style="display:none" value="%s" />
<input type="text" name="word" style="display:none" value="%s" />
<input type="text" name="comment"><br>
<input type="submit" value="发布" data-inline="true">
</form>
</div>""" % (key_name, user.email(), chapter, text, title, word))
self.response.out.write(u"""<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="%s" />
<input type="text" style="display:none" name="title" value="%s" />
<input type="text" style="display:none" name="chapter" value="%s" />
<input type="submit" data-role="button" value="返回" data-inline="true" /></form>""" % (text, title, chapter))
self.response.out.write(entry_close)
elif People.get_by_key_name(user.email()):
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""不适当 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br>请输入适当的词汇/句子。<br>""")
self.response.out.write(u"""<form action="/Read" method="post" data-ajax="false">
<input type"text" style="display:none" name="text" value="%s" />
<input type="text" style="display:none" name="title" value="%s" />
<input type="text" style="display:none" name="chapter" value="%s" />
<input type="submit" data-role="button" value="返回" data-inline="true" /></form>""" % (text, title, chapter))
self.response.out.write(entry_close)
elif user:
self.redirect("/visit_profile")
else:
self.redirect("/error")
class Board_Post(webapp2.RequestHandler):
def post(self):
user = users.get_current_user()
key_name = self.request.get("key_name")
name = self.request.get("name")
comment = self.request.get("comment")
chapter = self.request.get("chapter")
text = self.request.get("text")
title = self.request.get("title")
word = self.request.get("word")
if user and key_name and name and comment:
if Text.get_by_key_name(key_name):
if "<" in comment and ">" in comment:
comment = comment.replace("<", "<")
comment = comment.replace(">", ">")
t = Text.get_by_key_name(key_name)
t.name.append(name)
t.comment.append(comment)
t.put()
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""发布""" + """ - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br>已发布此帖子: """)
self.response.out.write(comment)
self.response.out.write("""<br>""")
self.response.out.write(u"""<form action="/Board" data-ajax="false" method="post">
<input type="text" name="chapter" style="display:none" value="%s" />
<input type="text" name="text" style="display:none" value="%s" />
<input type="text" name="title" style="display:none" value="%s" />
<input type="text" name="word" style="display:none" value="%s" />
<input type="submit" data-role="button" data-inline="true" value="返回" />
</form>""" % (chapter, text, title, word))
self.response.out.write(entry_close)
else:
if "<" in comment and ">" in comment:
comment = comment.replace("<", "<")
comment = comment.replace(">", ">")
name_list = []
name_list.append(name)
comment_list = []
comment_list.append(comment)
Text(key_name = key_name, name = name_list, comment = comment_list).put()
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""发布 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br>已发布此贴子: """)
self.response.out.write(comment)
self.response.out.write("""<br>""")
self.response.out.write(u"""<form action="/Board" data-ajax="false" method="post">
<input type="text" name="chapter" style="display:none" value="%s" />
<input type="text" name="text" style="display:none" value="%s" />
<input type="text" name="word" style="display:none" value="%s" />
<input type="submit" data-role="button" data-inline="true" value="返回" />
</form>""" % (chapter, text, word))
self.response.out.write(entry_close)
else:
self.redirect("/error")
class Board_Delete(webapp2.RequestHandler):
def post(self):
user = users.get_current_user()
key_name = self.request.get("key_name")
i = self.request.get("i")
i = int(i)
i = i + 1
text = self.request.get("text")
chapter = self.request.get("chapter")
word = self.request.get("word")
title = self.request.get("title")
if user and People.get_by_key_name(user.email()) and key_name and i:
name_list = Text.get_by_key_name(key_name).name
comment_list = Text.get_by_key_name(key_name).comment
del(name_list[(i - 1)])
del(comment_list[(i - 1)])
Text(key_name = key_name, name = name_list, comment = comment_list).put()
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""删除 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br>帖子已删除。<br>""")
self.response.out.write(u"""<form action="/Board" method="post" data-ajax="false">
<input type="text" name="chapter" style="display:none" value="%s" />
<input type="text" name="text" style="display:none" value="%s" />
<input type="text" name="word" style="display:none" value="%s" />
<input type="text" name="title" style="display:none" value="%s" />
<input type="submit" data-inline="true" value="返回" /></form>""" % (chapter, text, word, title))
self.response.out.write(entry_close)
elif user:
self.redirect("/visit_profile")
else:
self.redirect("/error")
class Feedback_Page(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user and People.get_by_key_name(user.email()):
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""反馈 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br><form action="/feedback_post" method="post" data-ajax="false">
<input type="text" name="feedback" />
<input type="submit" value="发布反馈" data-inline="true" />
</form>""")
self.response.out.write(entry_close)
elif user:
self.redirect("/visit_profile")
else:
self.redirect("/error")
class Feedback_Post(webapp2.RequestHandler):
def post(self):
user = users.get_current_user()
feedback = self.request.get("feedback")
if user and People.get_by_key_name(user.email()) and feedback:
Feedback(name = user.email(), feedback = feedback).put()
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""反馈 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br>谢谢您的反馈。<br>
<a href="/feedback" data-ajax="false" data-role="button" data-inline="true">返回</a>""")
self.response.out.write(entry_close)
elif user and People.get_by_key_name(user.email()):
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""反馈 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br>请输入正确的反馈。<br>
<a href="/feedback" data-ajax="false" data-role="button" data-inline="true">返回</a>""")
self.response.out.write(entry_close)
elif user:
self.redirect("/visit_profile")
else:
self.redirect("/error")
class Credits(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user and People.get_by_key_name(user.email()):
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""归功 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write(u"""<br><h2>读物摘自于:</h2><br>""")
self.response.out.write("""<fieldset class="ui-grid-b">""")
self.response.out.write("""<div class="ui-block-a"><a href="http://ds.eywedu.com/jinyong/xsfh/" data-role="button" data-ajax="false">《雪山飞狐》</a></div>""")
self.response.out.write("""<div class="ui-block-b"><a href="http://www.5156edu.com/page/09-06-05/46774.html" data-role="button" data-ajax="false">《送友人》</a></div>""")
self.response.out.write("""<div class="ui-block-c"><a href="http://www.laomu.cn/yingy/2009/200911/20091130104519_28679.html" data-role="button" data-ajax="false">《登高》</a></div>""")
self.response.out.write("""<div class="ui-block-a"><a href="http://www.thn21.com/wen/show/27028.html" data-role="button" data-ajax="false">《燕歌行》</a></div>""")
self.response.out.write("""<div class="ui-block-b"><a href="http://www.5156edu.com/page/09-06-26/47349.html" data-role="button" data-ajax="false">《无题》</a></div>""")
self.response.out.write("""<div class="ui-block-c"><a href="http://www.laomu.cn/yingy/2009/200911/20091130104253_28674.html" data-role="button" data-ajax="false">《山居秋暝》</a></div>""")
self.response.out.write("""<div class="ui-block-a"><a href="http://www.millionbook.com/mj/l/luxun/lh/007.htm" data-role="button" data-ajax="false">《药》</a></div>""")
self.response.out.write("""<div class="ui-block-b"><a href="http://www.millionbook.com/xd/w/wangmeng/000/008.htm" data-role="button" data-ajax="false">《最宝贵的》</a></div>""")
self.response.out.write("""<div class="ui-block-c"><a href="http://www.hkreporter.com/talks/thread-1177838-1-1.html" data-role="button" data-ajax="false">《命運的跡線》</a></div>""")
self.response.out.write("""<div class="ui-block-a"><a href="http://zhidao.baidu.com/question/2580787.html" data-role="button" data-ajax="false">《雨霖铃》</a></div>""")
self.response.out.write("""<div class="ui-block-b"><a href="http://longyusheng.org/ci/sushi/22.html" data-role="button" data-ajax="false">《念奴娇》</a></div>""")
self.response.out.write("""<div class="ui-block-c"><a href="http://www.diyifanwen.com/sicijianshang/songdai/liqingzhao/0673004200675618.htm" data-role="button" data-ajax="false">《武陵春》</a></div>""")
self.response.out.write("""<div class="ui-block-a"><a href="http://www.zk168.com.cn/shiyong/jianshang/songdai_117853.html" data-role="button" data-ajax="false">《永遇乐》</a></div>""")
self.response.out.write("""<div class="ui-block-b"><a href="http://longyusheng.org/ci/yanjidao/1.html" data-role="button" data-ajax="false">《临江仙》</a></div>""")
self.response.out.write("""</fieldset>""")
self.response.out.write(entry_close)
elif user:
self.redirect("/visit_profile")
else:
self.redirect("/error")
class Not_Found(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if People.get_by_key_name(user.email()):
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write("""未找到 - """)
self.response.out.write(People.get_by_key_name(user.email()).name)
self.response.out.write(header_close)
self.response.out.write("""<br>在读物里未找到所输入的词汇/句子。<br>""")
self.response.out.write("""请勿输入间距。""")
self.response.out.write(entry_close)
elif user:
self.redirect("/visit_profile")
else:
self.redirect("/error")
class Visit_Profile(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""个人资料 - """)
self.response.out.write(user.email())
self.response.out.write(header_close)
self.response.out.write(u"""<br>请更新个人资料。<br>""")
self.response.out.write(entry_close)
else:
self.redirect("/error")
class Error(webapp2.RequestHandler):
def get(self):
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""故障""")
self.response.out.write(header_close)
self.response.out.write(u"""<br>您没有权限浏览此页。""")
self.response.out.write(entry_close)
class Oops(webapp2.RequestHandler):
def get(self):
self.response.out.write(entry_open)
self.response.out.write(header_open)
self.response.out.write(u"""抱歉!""")
self.response.out.write(header_close)
self.response.out.write(u"""<br>抱歉,此页还未开发。<br>""")
self.response.out.write(u"""我们将会尽快完成。""")
self.response.out.write(entry_close)
app = webapp2.WSGIApplication([('/', Entry),
('/home', Home),
('/menu', Menu),
('/profile', Profile),
('/text', Text_Page),
('/Fox_Volant_of_the_Snowy_Mountain', Fox_Volant_of_the_Snowy_Mountain),
('/Read', Read),
('/Board', Board),
('/Board_Post', Board_Post),
('/Board_Delete', Board_Delete),
('/feedback', Feedback_Page),
('/feedback_post', Feedback_Post),
('/credits', Credits),
('/profile_update', Profile_Update),
('/not_found', Not_Found),
('/visit_profile', Visit_Profile),
('/error', Error),
('/oops',Oops)],
debug=True)
| [
"tan.phengruey.ryan@dhs.sg"
] | tan.phengruey.ryan@dhs.sg |
ac2e209543c0ad658b93d0beb6c974ab3563c45b | bef2856b8a09f66b10de415976950f910f4001dd | /fairseq/tasks/translation_expert.py | d2a2751c2c1d57868f0cb8019353bbd2724814cc | [] | no_license | Simpleple/Verdi | 70029afaadac0270b8e61381de6031247c4c039e | b54c6c61d25e496ead13d3120979441fe3701b16 | refs/heads/master | 2023-03-09T22:39:14.630451 | 2021-02-25T14:20:58 | 2021-02-25T14:20:58 | 338,310,533 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,356 | py | # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import contextlib
import torch
from fairseq import modules, utils
from fairseq.tasks import register_task
from fairseq.tasks.translation import TranslationTask
@contextlib.contextmanager
def eval(model):
is_training = model.training
model.eval()
yield
model.train(is_training)
@register_task('translation_expert')
class TranslationExpertTask(TranslationTask):
"""
Translation task for Mixture of Experts (MoE) models.
See `"Mixture Models for Diverse Machine Translation: Tricks of the Trade"
(Shen et al., 2019) <https://arxiv.org/abs/1902.07816>`_.
Args:
src_dict (~fairseq.data.Dictionary): dictionary for the source language
tgt_dict (~fairseq.data.Dictionary): dictionary for the target language
.. note::
The translation task is compatible with :mod:`fairseq-train`,
:mod:`fairseq-generate` and :mod:`fairseq-interactive`.
The translation task provides the following additional command-line
arguments:
.. argparse::
:ref: fairseq.tasks.translation_parser
:prog:
"""
@staticmethod
def add_args(parser):
"""Add task-specific arguments to the parser."""
# fmt: off
TranslationTask.add_args(parser)
parser.add_argument('--method', default='hMoEup',
choices=['sMoElp', 'sMoEup', 'hMoElp', 'hMoEup'])
parser.add_argument('--num-experts', default=3, type=int, metavar='N',
help='number of experts')
parser.add_argument('--mean-pool-gating-network', action='store_true',
help='use a simple mean-pooling gating network')
parser.add_argument('--mean-pool-gating-network-dropout', type=float,
help='dropout for mean-pooling gating network')
parser.add_argument('--mean-pool-gating-network-encoder-dim', type=float,
help='encoder output dim for mean-pooling gating network')
parser.add_argument('--gen-expert', type=int, default=0,
help='which expert to use for generation')
# fmt: on
def __init__(self, args, src_dict, tgt_dict):
if args.method == 'sMoElp':
# soft MoE with learned prior
self.uniform_prior = False
self.hard_selection = False
elif args.method == 'sMoEup':
# soft MoE with uniform prior
self.uniform_prior = True
self.hard_selection = False
elif args.method == 'hMoElp':
# hard MoE with learned prior
self.uniform_prior = False
self.hard_selection = True
elif args.method == 'hMoEup':
# hard MoE with uniform prior
self.uniform_prior = True
self.hard_selection = True
# add indicator tokens for each expert
for i in range(args.num_experts):
# add to both dictionaries in case we're sharing embeddings
src_dict.add_symbol('<expert_{}>'.format(i))
tgt_dict.add_symbol('<expert_{}>'.format(i))
super().__init__(args, src_dict, tgt_dict)
def build_model(self, args):
from fairseq import models
model = models.build_model(args, self)
if not self.uniform_prior and not hasattr(model, 'gating_network'):
if self.args.mean_pool_gating_network:
if getattr(args, 'mean_pool_gating_network_encoder_dim', None):
encoder_dim = args.mean_pool_gating_network_encoder_dim
elif getattr(args, 'encoder_embed_dim', None):
# assume that encoder_embed_dim is the encoder's output dimension
encoder_dim = args.encoder_embed_dim
else:
raise ValueError('Must specify --mean-pool-gating-network-encoder-dim')
if getattr(args, 'mean_pool_gating_network_dropout', None):
dropout = args.mean_pool_gating_network_dropout
elif getattr(args, 'dropout', None):
dropout = args.dropout
else:
raise ValueError('Must specify --mean-pool-gating-network-dropout')
model.gating_network = modules.MeanPoolGatingNetwork(
encoder_dim, args.num_experts, dropout,
)
else:
raise ValueError(
'translation_moe task with learned prior requires the model to '
'have a gating network; try using --mean-pool-gating-network'
)
return model
def expert_index(self, i):
return i + self.tgt_dict.index('<expert_0>')
def _get_loss(self, sample, model, criterion):
assert hasattr(criterion, 'compute_loss'), \
'translation_moe task requires the criterion to implement the compute_loss() method'
k = self.args.num_experts
bsz = sample['target'].size(0)
def get_lprob_y(encoder_out, prev_output_tokens_k):
net_output = model.decoder(prev_output_tokens_k, encoder_out)
loss, _ = criterion.compute_loss(model, net_output, sample, reduce=False)
loss = loss.view(bsz, -1)
return -loss.sum(dim=1, keepdim=True) # -> B x 1
def get_lprob_yz(winners=None):
encoder_out = model.encoder(sample['net_input']['src_tokens'], sample['net_input']['src_lengths'])
if winners is None:
lprob_y = []
for i in range(k): # k次解码, start不同
prev_output_tokens_k = sample['net_input']['prev_output_tokens'].clone()
assert not prev_output_tokens_k.requires_grad
prev_output_tokens_k[:, 0] = self.expert_index(i)
lprob_y.append(get_lprob_y(encoder_out, prev_output_tokens_k))
lprob_y = torch.cat(lprob_y, dim=1) # -> B x K
else: # 根据winner确定start,计算输出概率
prev_output_tokens_k = sample['net_input']['prev_output_tokens'].clone()
prev_output_tokens_k[:, 0] = self.expert_index(winners)
lprob_y = get_lprob_y(encoder_out, prev_output_tokens_k) # -> B
if self.uniform_prior:
lprob_yz = lprob_y
else: # 确定winner
lprob_z = model.gating_network(encoder_out) # B x K
if winners is not None: #原始的概率和winner的概率
lprob_z = lprob_z.gather(dim=1, index=winners.unsqueeze(-1))
lprob_yz = lprob_y + lprob_z.type_as(lprob_y) # B x K
return lprob_yz
# compute responsibilities without dropout
with eval(model): # disable dropout 计算winner,拿到winner概率
with torch.no_grad(): # disable autograd
lprob_yz = get_lprob_yz() # B x K
prob_z_xy = torch.nn.functional.softmax(lprob_yz, dim=1) #计算winner的概率
assert not prob_z_xy.requires_grad
# compute loss with dropout
if self.hard_selection:
winners = prob_z_xy.max(dim=1)[1] #获取winner
loss = -get_lprob_yz(winners) # 根据winner计算loss
else:
lprob_yz = get_lprob_yz() # B x K
loss = -modules.LogSumExpMoE.apply(lprob_yz, prob_z_xy, 1)
loss = loss.sum()
sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens']
logging_output = {
'loss': utils.item(loss.data),
'ntokens': sample['ntokens'],
'sample_size': sample_size,
'posterior': prob_z_xy.float().sum(dim=0).cpu(),
}
return loss, sample_size, logging_output
def train_step(self, sample, model, criterion, optimizer, ignore_grad=False):
model.train()
loss, sample_size, logging_output = self._get_loss(sample, model, criterion)
if ignore_grad:
loss *= 0
optimizer.backward(loss)
return loss, sample_size, logging_output
def valid_step(self, sample, model, criterion):
model.eval()
with torch.no_grad():
loss, sample_size, logging_output = self._get_loss(sample, model, criterion)
return loss, sample_size, logging_output
def inference_step(self, generator, models, sample, prefix_tokens=None, expert=None):
expert = expert or self.args.gen_expert
with torch.no_grad():
return generator.generate(
models,
sample,
prefix_tokens=prefix_tokens,
bos_token=self.expert_index(expert),
)
def aggregate_logging_outputs(self, logging_outputs, criterion):
agg_logging_outputs = criterion.__class__.aggregate_logging_outputs(logging_outputs)
agg_logging_outputs['posterior'] = sum(
log['posterior'] for log in logging_outputs if 'posterior' in log
)
return agg_logging_outputs
| [
"mingjunzhao@tencent.com"
] | mingjunzhao@tencent.com |
511e0f7bc03977814415a395f25990599d4aa5ce | 393e3f0942df844478771a1a4ae7525ec5a7d4f3 | /server/main.py | c711b732931b1daa135dbab87c710f6b0e8237b0 | [
"MIT"
] | permissive | KayJayQ/Spicy_pot_search | cbd076e3e992a7fe1f7c2e3bb3f6e071ce289de3 | 72aaa9618e54178da513371802c2bcb751037bb0 | refs/heads/main | 2023-03-11T07:02:52.880979 | 2021-02-28T14:48:06 | 2021-02-28T14:48:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,444 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask, request, abort, render_template
from datetime import timedelta
import pymysql
from search import start_search, decorate
page_dir = "E:/WEBPAGES_RAW"
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
connection = pymysql.connect(host="localhost",port=3306,user="root",db="spicy_pot")
cursor = connection.cursor()
@app.route('/')
def homepage():
return render_template("root.html")
@app.route('/search')
def search():
word = request.args.get('s')
page = int(request.args.get('p'))
all_res = start_search(word,cursor)
if len(all_res) == 0:
return render_template("result.html",result={"word":word,"pages":-1,"currentPage":1,"res":[]})
pages = ((len(all_res)-1)//10) + 1
res = decorate(all_res[(page-1)*10:page*10])
content = {"word":word,"pages":pages,"currentPage":page,"res":res}
return render_template("result.html",result=content)
@app.route('/cache')
def cache():
p = request.args.get('p')
c = request.args.get('c')
read = open(page_dir+"/"+p+"/"+c,'r',encoding="utf-8")
save = open("templates/temp.html",'w',encoding="utf-8")
for line in read:
save.write(line)
read.close()
save.close()
return render_template("temp.html")
app.run(host='0.0.0.0',port=80,debug=True)
| [
"noreply@github.com"
] | KayJayQ.noreply@github.com |
5d2200a128aabb70c081dea75e660bd7b9a29f3e | b93c90054ede72fb706567e2b60a5e4bba5485d3 | /cru/__init__.py | 3f204900689b0e4ad473586a2413b190d0343060 | [] | no_license | guziy/ShortPythonScripts | 2568b92124003fa4b0c673c3ce872df623dff76c | 17b1ed47231aa566c8af04e19cced49a795b37d8 | refs/heads/master | 2016-09-06T01:30:30.365172 | 2014-07-18T15:52:25 | 2014-07-18T15:52:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 149 | py | __author__ = 'huziy'
import numpy as np
def main():
#TODO: implement
pass
if __name__ == "__main__":
main()
print "Hello world"
| [
"guziy.sasha@gmail.com"
] | guziy.sasha@gmail.com |
d031af9a511c56dbd3655b7a286dfdb1709a1e87 | 1804d640ade2550a5448872cc408033fe0c4609a | /section-6/111.py | b3451b5e481c731e6f37b6f7eeb3661293a8382c | [] | no_license | uknamboodiri/z2m | 37eaa92038a77c95afbb357ff10ec96e6def3842 | 14f84fd55a82706fbfe7aaec54288f4195ad695c | refs/heads/master | 2022-09-22T13:12:37.026650 | 2020-05-28T18:20:08 | 2020-05-28T18:20:08 | 267,269,680 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 73 | py | # OOP
class BigObject:
pass
Obj1 = BigObject()
print(type(Obj1))
| [
"unni@bloomboard.com"
] | unni@bloomboard.com |
b1067dbd1da869a3839d1527813c511360fafa32 | 17a7e1941d1f0e9e2747ce177344cf081aeb1aa0 | /examples/sbm_arxiv_paper.py | 21987364c3ea82ea603bf54540f87aceb88df3be | [] | no_license | abdcelikkanat/rangraphgen | 413871bd757992c8c87f520c7fecbd18bc004eed | 491a94ddd0d8682ae3e6a30921e9de73327acea8 | refs/heads/master | 2020-03-21T08:09:34.540550 | 2018-07-23T16:13:55 | 2018-07-23T16:13:55 | 138,324,601 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,086 | py | from sbm.sbm import SBM
"""
model = {}
model['sbm_N'] = 100 # the number of nodes
model['sbm_P'] = [[0.6, 0.2], [0.2, 0.8]] # edge probability matrix between nodes belonging different communities
model['sbm_block_sizes'] = [40, 60]
output_file = "../outputs/synthetic_"
output_file += "n{}_p{}_sizes{}.gml".format(model['sbm_N'], 1, ":".join(str(v) for v in model['sbm_block_sizes']))
sbm = SBM(model=model)
sbm.build_graph()
g = sbm.get_graph()
sbm.save_graph(output_file)
#sbm.plot_graph()
"""
model = {}
N = 10000
c = 3.5
model['sbm_block_sizes'] = [N/2, N/2]
K = 2
mylambda = 0.9
model['sbm_N'] = N
model['sbm_P'] = [[0.0 for _ in range(K)] for _ in range(K)]
for i in range(K):
for j in range(K):
if i == j:
model['sbm_P'][i][j] = float(c) / float(N)
else:
model['sbm_P'][i][j] = float(c)*(1.0 - mylambda) / float(N)
output_file = "../outputs/sbm_"
output_file += "n{}_k{}_lambda{}_c{}.gml".format(N, K, mylambda, c)
sbm = SBM(model=model)
sbm.build_graph()
g = sbm.get_graph()
sbm.save_graph(output_file)
#sbm.plot_graph() | [
"abdcelikkanat@gmail.com"
] | abdcelikkanat@gmail.com |
727067a91ead21d7bd785a0a44d99986cc71f025 | 8d50dedc99efec3216e3040480f8993ad598e789 | /run.py | 997fc1380af67ed217f1ee89927131eea8f5da03 | [] | no_license | kevba/WeSt | 899f4584bc0052d2d3f42b10ba9d2427dcbba25c | d344bcb7d85d37b216055a8abde8ffb36b29aedd | refs/heads/master | 2021-01-15T11:12:20.600402 | 2014-10-21T11:26:18 | 2014-10-21T11:26:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 33 | py | from app import west
west.run()
| [
"kevinbatema@gmail.com"
] | kevinbatema@gmail.com |
54a7b84590199323e7288d9d8431bff3f59e736b | 8faa72d4487175954527cd0a79cf4eb2e1d246b7 | /Tuning.py | 52b368dafb3e78188e251c427f9a74d516776912 | [] | no_license | baker12355/weather_prediction | de98a4567f3f1a854bb00a6d5fbd55f90255893b | 3dc6ad457f85c836bee5370feaa6a65e128e913f | refs/heads/master | 2020-03-23T07:17:25.430518 | 2018-08-31T08:07:59 | 2018-08-31T08:07:59 | 141,261,188 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,844 | py | import numpy as np
from keras.utils import np_utils
from keras.models import load_model
np.random.seed(0)
def load_train ():
print ('loading data..')
# -----------------load every weather in a balance size -----------------------
num_classes = 4
num_classes2= 2
size = 224
dest = '/home/baker/Desktop/BDD100K/digitalize/'+str(size)+'/train'
#train_clear = np.load(dest + "/clear/" + "/train_data.npy" ) # 37410
#train_clear = train_clear[:10000]
train_clear = np.load (dest + "/clear/" + "/train_data.npy" ) # 37000
train_clear = train_clear[:10000]
train_clear = train_clear/255.0
t_clear_label = np.array ([3 for i in range(len(train_clear))])
# -----------------load labels - day or night ---------------------------------
d_clear_label = np.load(dest + "/clear/" + "/train_label.npy" )
d_clear_label = d_clear_label[:10000]
# -----------------create new labels clear or not -----------------------------
pass
# --------------------vertical concat them & ---------------------------------
t_clear_label = np_utils.to_categorical(t_clear_label, num_classes)
d_clear_label = np_utils.to_categorical(d_clear_label, num_classes2)
print ('done')
return train_clear ,t_clear_label,d_clear_label
# --------------------------------load data------------------------------------
train_data , train_label , train_label_d = load_train() # 3948 day 6052 night
a = [[0., 0., 0.]for i in range(len(train_data))]
a = np.reshape(a, (10000,3) )
train_label = np.asarray(a, dtype = np.float32 )
from sklearn.model_selection import train_test_split
from keras.callbacks import ModelCheckpoint
split = train_test_split(train_data, train_label, train_label_d,test_size=0.2, random_state=42)
(trainX, testX, trainWY, testWY, trainDY, testDY) = split
model = load_model("modelsCNN/size224/7.21_Dual_CNN/dual_0.h5")
#for layer in model.layers:
# if (layer.name=='category_output' ) | (layer.name=='conv2d_1' ):
# layer.trainable = False
losses = {
"category_output": "categorical_crossentropy",
"color_output": "categorical_crossentropy",
}
lossWeights = {"category_output": 1.0, "color_output": 1.0}
# initialize the optimizer and compile the model
print("[INFO] compiling model...")
model.compile(optimizer='adam', loss=losses, loss_weights=lossWeights,metrics=["accuracy"])
checkpointer = ModelCheckpoint(filepath='modelsCNN/size224/7.21_Dual_CNN/dual_tune.h5', verbose=1, save_best_only=True)
H = model.fit(trainX, {"category_output": trainWY, "color_output": trainDY},
validation_data=(testX, {"category_output": testWY, "color_output": testDY}),
callbacks = [ checkpointer ] ,
epochs=30,
verbose=1,
batch_size=64,
)
| [
"noreply@github.com"
] | baker12355.noreply@github.com |
9e0a02eb3d846582ba7102a3f2b57fd91d14e445 | 6def6c37243bf7c6fdb83204da71ed4a40e43938 | /Python/palindrome-linked-list.py | 2f5dcb166a478fd6f37dcefb849ba8a990da27c1 | [] | no_license | simochen/algorithms-note | be9b6f37a123fb076cbc0d6e9ce8973a1ef56f2a | a690edf3d8474a6f7d2b7a0ff7dd42c631dcf7f4 | refs/heads/master | 2020-03-10T16:28:12.514255 | 2018-09-19T09:51:29 | 2018-09-19T09:51:29 | 129,474,281 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 782 | py | # Time: O(n)
# Space: O(1)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return True
slow, fast, _next = head, head.next, head.next
while fast and fast.next:
fast = fast.next.next
rev = _next
_next = _next.next
rev.next = slow
slow = rev
if not fast:
slow = slow.next
while _next:
if _next.val != slow.val:
return False
slow, _next = slow.next, _next.next
return True | [
"chenx324@yeah.net"
] | chenx324@yeah.net |
39cc3029c96a86e815190984cebf90bce285fb25 | 7450483dd16f7dea4bef09a5166a67c7527b7ca2 | /hw_8_stub.py | faed32fa97ff75a4f1b0a0c90f450a885d815fca | [] | no_license | rmvook/HW8_CMSC389R | 604ec50cc225926e53692fc0ebcf366dc4914a98 | 03fad8af81e2e985d121d9fbdb2d0ed939534a81 | refs/heads/master | 2020-03-09T15:45:17.796936 | 2018-04-16T15:11:50 | 2018-04-16T15:11:50 | 128,867,479 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,824 | py | # do `curl http://starship.python.net/~gherman/programs/md5py/md5py.py > md5.py`
# if you do not have it from the git repo
import md5py, socket, hashlib, string, sys, os, time
f = open("output.txt", "w")
host = "159.89.236.106" # IP address or URL
port = 5678 # port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
data = s.recv(1024)
print(data)
#####################################
### STEP 1: Calculate forged hash ###
#####################################
one = "1\n"
s.send(one)
data = s.recv(1024)
print(data)
message = 'blahah' # original message here
s.send(message + "\n")
data = s.recv(1024)
print(data)
temp = data[40:]
legit = temp.strip()
print(legit)
f.write("Hash from which I based my crafted hash: " + legit + "\n")
# a legit hash of secret + message goes here, obtained from signing a message
# initialize hash object with state of a vulnerable hash
fake_hash = md5py.new('A' * 64)
fake_hash.A, fake_hash.B, fake_hash.C, fake_hash.D = md5py._bytelist2long(legit.decode('hex'))
malicious = 'bluhuh' # put your malicious message here
# update legit hash with malicious message
fake_hash.update(malicious)
# test is the correct hash for md5(secret + message + padding + malicious)
test = fake_hash.hexdigest()
print("Testing fake" + test)
f.write("Fake hash" + test + "\n")
#############################
### STEP 2: Craft payload ###
#############################
# TODO: calculate proper padding based on secret + message
# secret is 6 bytes long (48 bits)
# each block in MD5 is 512 bits long
# secret + message is followed by bit 1 then bit 0's (i.e. \x80\x00\x00...)
# after the 0's is a bye with message length in bits, little endian style
# (i.e. 20 char msg = 160 bits = 0xa0 = '\xa0\x00\x00\x00\x00\x00\x00\x00\x00')
# craft padding to align the block as MD5 would do it
# (i.e. len(secret + message + padding) = 64 bytes = 512 bits
nulls = "\x00" * 43
end = "\x00" * 7
padding = "\x80" + nulls + "\x60" + end
# payload is the message that corresponds to the hash in `test`
# server will calculate md5(secret + payload)
# = md5(secret + message + padding + malicious)
# = test
payload = message + padding + malicious
print("PAYLOAD: " + payload)
# send `test` and `payload` to server (manually or with sockets)
# REMEMBER: every time you sign new data, you will regenerate a new secret!
f.write("PAYLOAD: " + payload + "\n")
two = "2\n"
s.send(two) #telling the server that I want to verify a hash.
data = s.recv(1024)
print(data)
s.send(test + "\n")
data = s.recv(1024)
print(data)
s.send(payload + "\n")
data = s.recv(1024) # was not receiving everything, so did it twice.
print(data)
data = s.recv(1024)
print(data)
s.close()# close the connection
f.close()#close the file | [
"root@localhost.localdomain"
] | root@localhost.localdomain |
0cb879ad53116b56ad9125b0a5e12370dc9c2537 | 1ea3a00cde5176c9ee8b9ba68ed5ac8841427390 | /stack/settings.py | 40d1fa4b3a1132bad33cd6435951736e4e73d16a | [] | no_license | huytv593/stackoverflowCrawler | 5f7a5f90a196223faa9385a054ac64ed27ba27de | 97d40828740b6fc8fa65ab3b2d25dbd032a00d57 | refs/heads/master | 2021-01-10T10:10:01.043394 | 2016-03-15T07:08:57 | 2016-03-15T07:08:57 | 53,922,601 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,366 | py | # -*- coding: utf-8 -*-
# Scrapy settings for stack project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'stack'
SPIDER_MODULES = ['stack.spiders']
NEWSPIDER_MODULE = 'stack.spiders'
DOWNLOAD_DELAY = 5
# Set DB
ITEM_PIPELINES = ['stack.pipelines.MongoDBPipeline', ]
MONGODB_SERVER = "localhost"
MONGODB_PORT = 27017
MONGODB_DB = "stackoverflow"
MONGODB_COLLECTION = "questions"
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'stack (+http://www.yourdomain.com)'
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS=32
# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY=3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN=16
#CONCURRENT_REQUESTS_PER_IP=16
# Disable cookies (enabled by default)
#COOKIES_ENABLED=False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED=False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'stack.middlewares.MyCustomSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'stack.middlewares.MyCustomDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'stack.pipelines.SomePipeline': 300,
#}
# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
# NOTE: AutoThrottle will honour the standard settings for concurrency and delay
#AUTOTHROTTLE_ENABLED=True
# The initial download delay
#AUTOTHROTTLE_START_DELAY=5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY=60
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG=False
# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED=True
#HTTPCACHE_EXPIRATION_SECS=0
#HTTPCACHE_DIR='httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES=[]
#HTTPCACHE_STORAGE='scrapy.extensions.httpcache.FilesystemCacheStorage'
# More comprehensive list can be found at
# http://techpatterns.com/forums/about304.html
USER_AGENT_LIST = [
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.36 Safari/535.7',
'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0) Gecko/16.0 Firefox/16.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10'
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_5_8) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11'
]
DOWNLOADER_MIDDLEWARES = {
'stack.middlewares.RandomUserAgentMiddleware': 400,
'stack.middlewares.ProxyMiddleware': 410,
'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware': None,
# Disable compression middleware, so the actual HTML pages are cached
}
| [
"huytv593@gmail.com"
] | huytv593@gmail.com |
ebeb1f80716af2ee05b383a7b90d6446cb38163e | 5baa48fb45cdd50b4995ac707f8d91d8f9d99d5a | /registries/font_registery.py | da24d40bd7f8af767c5333db012e2c41c9fdfae7 | [] | no_license | sarahmoelenna/pygame-bullet-hell-dungeon-crawler | 92536608adf7f334abe599b84bee0c8f6fac5bac | 6462660d370df59f37f94deed7b5a021a3d73a04 | refs/heads/master | 2022-04-26T02:54:34.871347 | 2020-04-30T11:15:27 | 2020-04-30T11:15:27 | 260,189,521 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 335 | py | import pygame
class FontRegistery():
fonts = {}
@staticmethod
def get_font(size: int):
if size in FontRegistery.fonts.keys():
return FontRegistery.fonts[size]
else:
FontRegistery.fonts[size] = pygame.font.SysFont("comicsansms", size)
return FontRegistery.fonts[size]
| [
"georgehatsune@gmail.com"
] | georgehatsune@gmail.com |
bd3d8511ec40499ea66fcc1e2c71b26b17f8565d | cd79b7919fd0984c12e8acde8abda4290fd65b0f | /draftcast/settings.py | dbaf6a6cc14ebfb87a7c0db296138f30760cc41a | [] | no_license | rallen0150/nfl_draftcast | 7d5d84352986349f0646a9199d3aa3b29bfac4a2 | 3f5f9980902ee73fbca3c5b3db4545179ff5208a | refs/heads/master | 2021-01-20T04:43:00.356120 | 2017-04-29T14:45:16 | 2017-04-29T14:45:16 | 89,718,535 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,349 | py | """
Django settings for draftcast project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xkaaf7fhx_nv$1(!enr!opy*x47n85mi^3!hapv_#dapytq$ls'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['quiet-garden-99226.herokuapp.com', 'localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
]
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 = 'draftcast.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'draftcast.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
import dj_database_url
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
database_config = dj_database_url.config()
if database_config:
DATABASES['default'] = database_config
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
| [
"rallen0150@gmail.com"
] | rallen0150@gmail.com |
fed1af0912a71ebae30785c3e9dcaec26f4337f6 | d29c1c1901b8f5aac07ea67c969f4e96e3642376 | /venv/Scripts/pip-script.py | 670e74ae05294d33a619274f5839d91a361a2800 | [] | no_license | aljaserm/pdf | 10f0f97572fb2021604e70aeb3ed2f8920668a12 | 4648703819260380ebc942bba31817e47821f23f | refs/heads/master | 2020-08-29T20:41:32.846815 | 2019-12-12T00:03:21 | 2019-12-12T00:03:21 | 218,169,283 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 429 | py | #!C:\Users\aljas\OneDrive\Documents\Development\Python\pdf\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==10.0.1', 'console_scripts', 'pip')()
)
| [
"aljaserm7@gmail.com"
] | aljaserm7@gmail.com |
9910f3b661ec4d47123f458231d4ba138a2a6155 | e5bed250a588c14bf1ec4ce71ec7c65cdacdc82a | /Labs/lab1/lab1.py | 2427068ecfe2d72251762e33a47e9f4c94c5ed1f | [] | no_license | ndiekema/CPE202 | 55c672df6176b18b2fdb3f9f37f8b78ff6fb10a6 | bdd872a040ee91dced7d9037531cb0e56dc99a89 | refs/heads/main | 2023-08-29T07:16:18.607140 | 2021-09-23T00:35:17 | 2021-09-23T00:35:17 | 407,335,527 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,934 | py | #
#Name: Nathan Diekema
#Student ID:
#Date: 1/13/18
#
#Lab 2
#Section 202-05
#Purpose of Lab: Recursion vs Iteration
#
#This function will return the largest of a list of numbers
#list -> int
def max_list_iter(int_list): # must use iteration not recursion
"""finds the max of a list of numbers and returns the value (not the index)
If int_list is empty, returns None. If list is None, raises ValueError"""
if int_list == None:
raise ValueError
if len(int_list) == 0:
return None
maxNum = int_list[0]
for x in int_list:
if x > maxNum:
maxNum = x
return maxNum
#This function will reverse the order of a list
#list -> list
def reverse_rec(int_list): # must use recursion
"""recursively reverses a list of numbers and returns the reversed list
If list is None, raises ValueError"""
if len(int_list) == 0:
raise ValueError
return helper(int_list)
def helper(lst):
if len(lst) == 0 or len(lst) == 1:
return lst
return (helper(lst[1:]) + [lst[0]])
#This function will use binary search to return the index of a target number
#int int int list -> int
def bin_search(target, low, high, int_list): # must use recursion
"""searches for target in int_list[low..high] and returns index if found
If target is not found returns None. If list is None, raises ValueError """
if len(int_list) == 0:
raise ValueError
else:
midpoint = ((high+low)//2)
if midpoint == high == low and int_list[midpoint] != target:
return None
#print("NOW", int_list[low], int_list[high], target)
if target == int_list[midpoint]:
return midpoint
elif target > int_list[midpoint]:
return bin_search(target,midpoint+1,high,int_list)
elif target < int_list[midpoint]:
return bin_search(target,low,midpoint-1,int_list) | [
"noreply@github.com"
] | ndiekema.noreply@github.com |
4c81d927e9ba8d11f7dc58e8d303ef88a77dacfd | 0e4aa336c347e9a963ee98e75ec7fdc6ae995a0f | /remind/migrations/0006_custom_wechate_account.py | 0aa151a3e6f644bcfd7481096e955795a1784f6d | [
"Apache-2.0"
] | permissive | yejunzhou/quantserver | 6a84cb4f687b010bc864f2ebee500b40d965773a | 4d9c8c396f7f17644211f95cee76ffc88efe4f0e | refs/heads/master | 2021-06-26T03:38:06.998468 | 2019-10-14T09:05:14 | 2019-10-14T09:05:14 | 214,996,557 | 0 | 0 | Apache-2.0 | 2021-06-10T22:05:48 | 2019-10-14T09:02:47 | Python | UTF-8 | Python | false | false | 540 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-03-19 17:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('remind', '0005_auto_20190320_0125'),
]
operations = [
migrations.AddField(
model_name='custom',
name='wechate_account',
field=models.CharField(default='yejunzhou', help_text='企业微信账户', max_length=20, verbose_name='wechate_account'),
),
]
| [
"yejunzhou@foxmail.com"
] | yejunzhou@foxmail.com |
c622f79d7ffdb4cd8d4f0001ebfb7f05458d7497 | 58892f2b2d78934013505544b27da2364bdf3eb5 | /run_dialogue.py | 57e8d13dab972ae4fd67e3799c92c6b3d5c062b6 | [] | no_license | big-data-ai/LICS2021_Dialogue | 882cba97f9b44e00b6bd000c59fb1fb61037524a | e0e957e1fced290cba36cbe0997c03cead50920d | refs/heads/master | 2023-05-19T17:02:35.758513 | 2021-06-13T08:51:23 | 2021-06-13T08:51:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,870 | py | # -*- coding: utf-8 -*-
import os
import random
import time
import math
import logging
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle.io import DataLoader
from paddle.optimizer.lr import NoamDecay
from paddle.optimizer import AdamW
from paddlenlp.transformers import UnifiedTransformerLMHeadModel, UnifiedTransformerTokenizer
from utils.input_args import parse_args
from utils.data_helper import DialogueDataset, select_response
logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=logging.INFO)
class ModelOperation(object):
"""ModelTrain"""
def __init__(self):
self.cur_process_num = paddle.distributed.get_world_size() # PADDLE_TRAINERS_NUM 的值,默认值为1
self.cur_process_rank = paddle.distributed.get_rank() # PADDLE_TRAINER_ID 的值,默认值为0
self.model_class = {
"uniLM": (UnifiedTransformerLMHeadModel, UnifiedTransformerTokenizer),
}
self.data_helper = None
def _initialize_run_env(self, device, seed):
assert device in ("cpu", "gpu", "xpu"), \
f"param device({device}) must be in ('cpu', 'gpu', 'xpu')!!!"
paddle.set_device(device)
if self.cur_process_num > 1:
paddle.distributed.init_parallel_env()
if seed:
self.set_seed(seed)
def _initialize_model(self, model_type, pretrained_model_path):
assert os.path.exists(pretrained_model_path), \
f"model path {pretrained_model_path} must exists!!!"
logging.info(f"initialize model from {pretrained_model_path}")
model_class, tokenizer_class = self.model_class[model_type]
self.tokenizer = tokenizer_class.from_pretrained(pretrained_model_path)
self.model = model_class.from_pretrained(pretrained_model_path)
if self.cur_process_num > 1:
self.model = paddle.DataParallel(self.model)
def _initialize_optimizer(self, args):
self.lr_scheduler = NoamDecay(1 / (args.warmup_steps * (args.lr ** 2)),
args.warmup_steps)
# Generate parameter names needed to perform weight decay.
# All bias and LayerNorm parameters are excluded.
decay_params = [
p.name for n, p in self.model.named_parameters()
if not any(nd in n for nd in ["bias", "norm"])
]
self.optimizer = AdamW(
learning_rate=self.lr_scheduler,
parameters=self.model.parameters(),
weight_decay=args.weight_decay,
apply_decay_param_fun=lambda x: x in decay_params,
grad_clip=nn.ClipGradByGlobalNorm(args.max_grad_norm))
def _start_train(self, args):
# load train data loader
train_dataset = DialogueDataset(
args.train_data_path,
args.batch_size,
self.tokenizer.pad_token_id,
self.tokenizer.cls_token_id,
args.sort_pool_size,
args.seed,
mode='train')
train_data_loader = DataLoader(train_dataset, return_list=True, batch_size=None)
# initialize optimizer
self._initialize_optimizer(args)
global_step = 0
tic_train = time.time()
for epoch in range(args.train_epochs):
for batch in train_data_loader:
# logging.info(f"Epoch: {epoch+1}/{args.train_epochs}, step is {step}")
global_step += 1
token_ids, type_ids, pos_ids, generation_mask, tgt_label, tgt_pos = batch
logits = self.model(token_ids, type_ids, pos_ids, generation_mask, tgt_pos)
loss = F.cross_entropy(logits, tgt_label)
if global_step % args.logging_steps == 0:
logging.info(f"global step {global_step}, epoch: {epoch+1}/{args.train_epochs},"
f" loss: {loss}, speed: {args.logging_steps / (time.time() - tic_train):.2f} step/s")
tic_train = time.time()
loss.backward()
self.optimizer.step()
self.lr_scheduler.step()
self.optimizer.clear_gradients()
if self.cur_process_rank == 0:
output_dir = \
os.path.join(args.output_dir, "model_{}".format(global_step))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# need better way to get inner model of DataParallel
model_to_save = \
self.model._layers if isinstance(self.model, paddle.DataParallel) else self.model
model_to_save.save_pretrained(output_dir)
self.tokenizer.save_pretrained(output_dir)
print('Saving checkpoint to:', output_dir)
@paddle.no_grad()
def evaluation(self, args):
self.model.eval()
valid_dataset = DialogueDataset(
args.valid_data_path,
args.batch_size,
self.tokenizer.pad_token_id,
self.tokenizer.cls_token_id,
args.sort_pool_size,
args.seed,
mode='valid')
valid_data_loader = DataLoader(valid_dataset, return_list=True, batch_size=None)
total_tokens = 0
total_loss = 0.0
start_time = time.time()
step = 0
for inputs in valid_data_loader:
step += 1
token_ids, type_ids, pos_ids, generation_mask, tgt_label, tgt_pos = inputs
logits = self.model(token_ids, type_ids, pos_ids, generation_mask, tgt_pos)
loss = F.cross_entropy(logits, tgt_label, reduction='sum')
total_loss += loss.numpy()[0]
total_tokens += tgt_label.shape[0]
avg_loss = total_loss / total_tokens
ppl = math.exp(avg_loss)
avg_speed = (time.time() - start_time) / step
logging.info('loss: %.4f - ppl: %.4f - %.3fs/step\n' % (avg_loss, ppl, avg_speed))
self.model.train()
@paddle.no_grad()
def _infer(self, data_loader):
self.model.eval()
total_time = 0.0
start_time = time.time()
responses = []
for step, inputs in enumerate(data_loader, 1):
logging.info(f"step is {step}")
token_ids, type_ids, pos_ids, generation_mask = inputs
ids, scores = self.model.generate(
input_ids=token_ids,
token_type_ids=type_ids,
position_ids=pos_ids,
attention_mask=generation_mask,
max_length=args.max_dec_len,
min_length=args.min_dec_len,
decode_strategy=args.decode_strategy,
temperature=args.temperature,
top_k=args.top_k,
top_p=args.top_p,
num_beams=args.num_beams,
length_penalty=args.length_penalty,
early_stopping=args.early_stopping,
num_return_sequences=args.num_samples)
total_time += (time.time() - start_time)
if step % args.logging_steps == 0:
logging.info(f'step {step} - {total_time / args.logging_steps:.3f}s/step')
total_time = 0.0
results = select_response(ids, scores, self.tokenizer,
args.max_dec_len, args.num_samples)
responses.extend(results)
start_time = time.time()
self.model.train()
return responses
def predict(self, args):
# [1]. initialize dataset loader
test_dataset = DialogueDataset(
args.test_data_path,
args.batch_size,
self.tokenizer.pad_token_id,
self.tokenizer.cls_token_id,
args.sort_pool_size,
args.seed,
mode='test')
valid_data_loader = DataLoader(test_dataset, return_list=True, batch_size=None)
# [2]. do inference
responses = self._infer(valid_data_loader)
# [3]. save result
output_path = os.path.join(args.output_dir, "predict.txt")
with open(output_path, 'w', encoding='utf-8') as f:
for response in responses:
f.write(response + '\n')
def train_and_eval(self, args):
self._initialize_run_env(args.device, args.seed)
self._initialize_model(args.model_type, args.pretrained_model_path)
# start training
if args.do_train:
logging.info("start training...")
self._start_train(args)
logging.info("train success.")
# start evaluation
if args.do_eval:
logging.info("start evaluating...")
self.evaluation(args)
logging.info("evaluate success.")
# start predicting
if args.do_predict:
logging.info("start predicting...")
self.predict(args)
logging.info("predict success.")
@staticmethod
def set_seed(random_seed):
random.seed(random_seed)
np.random.seed(random_seed)
paddle.seed(random_seed)
if __name__ == '__main__':
# input_args = "--do_train 1 --train_data_path ./datasets/output/train.txt " \
# "--do_eval 1 --valid_data_path ./datasets/output/train.txt " \
# "--do_predict 0 --test_data_path ./datasets/small_test.json " \
# "--device cpu --model_type uniLM " \
# "--pretrained_model_path unified_transformer-12L-cn --train_epochs 1 " \
# "--batch_size 8192"
args = parse_args(input_arg=None)
logging.info('----------- Configuration Arguments -----------')
for arg, value in sorted(vars(args).items()):
logging.info(f'{arg}: {value}')
logging.info('------------------------------------------------')
model_oper = ModelOperation()
model_oper.train_and_eval(args)
| [
"liuyongjie01@baidu.com"
] | liuyongjie01@baidu.com |
284cc73151b90950425038857f02882040ea595d | bee3fba66532dc96b99f4363ded0403499fc72b9 | /FunctionsBasic_I.py | ab80392afa7f485915fa31c6abad07696d96c74c | [] | no_license | datnguyen56/FunctionsBacsic_I | afd61991f81e5e1f7ed4ff73d9882a7e68e3634c | dfa1c8a6e426070694ba7126a7848fdb3e2c9d51 | refs/heads/main | 2023-04-20T13:42:40.505267 | 2021-05-04T19:06:09 | 2021-05-04T19:06:09 | 364,359,086 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,929 | py | #1
def number_of_food_groups():
return 5
print(number_of_food_groups())
# 5
#2
def number_of_military_branches():
return 5
print(number_of_days_in_a_week_silicon_or_triangle_sides() + number_of_military_branches())
# None
#3
def number_of_books_on_hold():
return 5
return 10
print(number_of_books_on_hold())
# 5
#4
def number_of_fingers():
return 5
print(10)
print(number_of_fingers())
# 5
#5
def number_of_great_lakes():
print(5)
x = number_of_great_lakes()
print(x)
# 5, None
#6
def add(b,c):
print(b+c)
print(add(1,2) + add(2,3))
# 3, 5
# 8
#7
def concatenate(b,c):
return str(b)+str(c)
print(concatenate(2,5))
# 7
#8
def number_of_oceans_or_fingers_or_continents():
b = 100
print(b)
if b < 10:
return 5
else:
return 10
return 7
print(number_of_oceans_or_fingers_or_continents())
# 100
# 10
#9
def number_of_days_in_a_week_silicon_or_triangle_sides(b,c):
if b<c:
return 7
else:
return 14
return 3
print(number_of_days_in_a_week_silicon_or_triangle_sides(2,3))
print(number_of_days_in_a_week_silicon_or_triangle_sides(5,3))
print(number_of_days_in_a_week_silicon_or_triangle_sides(2,3) + number_of_days_in_a_week_silicon_or_triangle_sides(5,3))
# 7
# 14
# 21
#10
def addition(b,c):
return b+c
return 10
print(addition(3,5))
# 8
#11
b = 500
print(b)
def foobar():
b = 300
print(b)
print(b)
foobar()
print(b)
# 500
# 300
# 300
#
#12
b = 500
print(b)
def foobar():
b = 300
print(b)
return b
print(b)
foobar()
print(b)
# 500
# 300
#13
b = 500
print(b)
def foobar():
b = 300
print(b)
return b
print(b)
b=foobar()
print(b)
# 500
# 500
# 300
#14
def foo():
print(1)
bar()
print(2)
def bar():
print(3)
foo()
# 1
# 3
#15
def foo():
print(1)
x = bar()
print(x)
return 10
def bar():
print(3)
return 5
y = foo()
print(y)
# 1
# 3
# 5
# 10 | [
"nguyentiendat5699@gmail.com"
] | nguyentiendat5699@gmail.com |
8ef02c514a006c6ab4fe77f9f6b354a66e89d0d3 | 870d069d183bf12278222bc4422556864c8dc053 | /Modulos/ejercicio83.py | 454ce97cb6cb08ef99df850a53afc3d500c791a8 | [] | no_license | iMrJulian/Ejercicios-python | a193c828f5626cb23d95c818dbd65b9769e32712 | 93343e18dc2a7fe95eb66a3242226fc3e7d26a14 | refs/heads/master | 2021-01-16T09:11:43.048332 | 2020-02-27T18:31:37 | 2020-02-27T18:31:37 | 243,055,916 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 512 | py | import calculadoraBin
def ejercicio83():
numero1 = (input("Ingrese el primer numero en binario: "))
numero2 = (input("Ingrese el segundo numero en binario: "))
print(f"{numero1} + {numero2} = {bin(calculadoraBin.suma(numero1,numero2))} ")
print(f"{numero1} - {numero2} = {bin(calculadoraBin.resta(numero1,numero2))} ")
print(f"{numero1} * {numero2} = {bin(calculadoraBin.multiplicacion(numero1,numero2))} ")
print(f"{numero1} / {numero2} = {bin(calculadoraBin.division(numero1,numero2))} ")
ejerciio83() | [
"juliandrincon@gmail.com"
] | juliandrincon@gmail.com |
9c219e6a252cc8f462724a14e74f75e5a1adf0ac | d4e056df7d9c5c14fe5adbf07802acfb8403bd2b | /cityreader/cityreader.py | 104c8896598f5f3cd2111e6d7fa5736c0522e3c7 | [] | no_license | mmastin/Sprint_Challenge_Materials | 9fb32b55fec1455c02b83f45370d3dcb9bf6bb9d | da9a85d29dd1ab97ee5cc436d82924ea8bc076ef | refs/heads/master | 2020-06-19T07:24:50.410066 | 2020-01-24T18:37:48 | 2020-01-24T18:37:48 | 196,615,540 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,350 | py | # Create a class to hold a city location. Call the class "City". It should have
# fields for name, lat and lon (representing latitude and longitude).
class City:
def __init__(self, name, lat, lon):
self.name = name
self.lat = float(lat)
self.lon = float(lon)
def __str__(self):
return f'({self.name}, {self.lat}, {self.lon})'
def __repr__(self):
return f'{repr(self.name)}: lat {repr(self.lat)} lon {repr(self.lon)}'
# We have a collection of US cities with population over 750,000 stored in the
# file "cities.csv". (CSV stands for "comma-separated values".)
#
# In the body of the `cityreader` function, use Python's built-in "csv" module
# to read this file so that each record is imported into a City instance. Then
# return the list with all the City instances from the function.
# Google "python 3 csv" for references and use your Google-fu for other examples.
#
# Store the instances in the "cities" list, below.
#
# Note that the first line of the CSV is header that describes the fields--this
# should not be loaded into a City object.
import csv
cities = []
def cityreader(cities=[]):
# simple path wasn't working for some reason
with open('/Users/mattmastin/Desktop/CS/Sprint-Challenge--Intro-Python/src/cityreader/cities.csv', 'r') as f:
reader = csv.reader(f)
next(reader, None)
for row in reader:
name = str(row[0])
lat = row[3]
lon = row[4]
cities.append(City(name, lat, lon))
# TODO Implement the functionality to read from the 'cities.csv' file
# For each city record, create a new City instance and add it to the
# `cities` list
return cities
cityreader(cities)
# Print the list of cities (name, lat, lon), 1 record per line.
for c in cities:
print(c)
# STRETCH GOAL!
#
# Allow the user to input two points, each specified by latitude and longitude.
# These points form the corners of a lat/lon square. Pass these latitude and
# longitude values as parameters to the `cityreader_stretch` function, along
# with the `cities` list that holds all the City instances from the `cityreader`
# function. This function should output all the cities that fall within the
# coordinate square.
#
# Be aware that the user could specify either a lower-left/upper-right pair of
# coordinates, or an upper-left/lower-right pair of coordinates. Hint: normalize
# the input data so that it's always one or the other, then search for cities.
# In the example below, inputting 32, -120 first and then 45, -100 should not
# change the results of what the `cityreader_stretch` function returns.
#
# Example I/O:
#
# Enter lat1,lon1: 45,-100
# Enter lat2,lon2: 32,-120
# Albuquerque: (35.1055,-106.6476)
# Riverside: (33.9382,-117.3949)
# San Diego: (32.8312,-117.1225)
# Los Angeles: (34.114,-118.4068)
# Las Vegas: (36.2288,-115.2603)
# Denver: (39.7621,-104.8759)
# Phoenix: (33.5722,-112.0891)
# Tucson: (32.1558,-110.8777)
# Salt Lake City: (40.7774,-111.9301)
# latitude = input('Please enter a latitude coordinate: ')
# longitude = input('Please enter a longitude coordinate: ')
# def cityreader_stretch(lat1, lon1, lat2, lon2, cities=cities[0]):
# # within will hold the cities that fall within the specified region
# within = []
# lat1 = float(lat1)
# lon1 = float(lon1)
# lat2 = float(lat2)
# lon2 = float(lon2)
# return within
| [
"noreply@github.com"
] | mmastin.noreply@github.com |
29994d406b495c7ba39c78f10dcf987100d80551 | 59351d79ad688fc746a488e65aa594457f626adf | /network/blocks.py | 22a2c34d0dae40c00b0dfc3ebf02c76b58a9b788 | [] | no_license | caokyhieu/audio2video | ba433e011ff8000f0ca77fa326887f18a98aecbf | 6150baf8f25b7b518eb0905a9dc41c5ee464d5e5 | refs/heads/master | 2023-01-12T22:08:32.083585 | 2020-11-16T13:48:45 | 2020-11-16T13:48:45 | 313,315,366 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,403 | py | import torch
import torch.nn as nn
class SelfAttention(nn.Module):
def __init__(self, in_channel):
super(SelfAttention, self).__init__()
#conv f
self.conv_f = nn.utils.spectral_norm(nn.Conv2d(in_channel, in_channel//8, 1))
#conv_g
self.conv_g = nn.utils.spectral_norm(nn.Conv2d(in_channel, in_channel//8, 1))
#conv_h
self.conv_h = nn.utils.spectral_norm(nn.Conv2d(in_channel, in_channel, 1))
self.softmax = nn.Softmax(-2) #sum in column j = 1
self.gamma = nn.Parameter(torch.zeros(1))
def forward(self, x):
B, C, H, W = x.shape
f_projection = self.conv_f(x) #BxC'xHxW, C'=C//8
g_projection = self.conv_g(x) #BxC'xHxW
h_projection = self.conv_h(x) #BxCxHxW
f_projection = torch.transpose(f_projection.view(B,-1,H*W), 1, 2) #BxNxC', N=H*W
g_projection = g_projection.view(B,-1,H*W) #BxC'xN
h_projection = h_projection.view(B,-1,H*W) #BxCxN
attention_map = torch.bmm(f_projection, g_projection) #BxNxN
attention_map = self.softmax(attention_map) #sum_i_N (A i,j) = 1
#sum_i_N (A i,j) = 1 hence oj = (HxAj) is a weighted sum of input columns
out = torch.bmm(h_projection, attention_map) #BxCxN
out = out.view(B,C,H,W)
out = self.gamma*out + x
return out
| [
"caokyhieu253@gmail.com"
] | caokyhieu253@gmail.com |
4bb943f584a8d5d66b66f182cee4129fd65784aa | 85468f02b0b4dae402ac96af645be42d363ec55d | /project_sdf/urls.py | 997d08cfa1a4de0837f42ff9d036edc36f693f06 | [] | no_license | sistemasdf/django-app-sdf | 975ed2047fac038bc59eeb6bde5d7413b828087c | 425106b81a71b1d6fc64f9abbaa86a18497a404a | refs/heads/main | 2023-03-04T10:49:35.236833 | 2021-02-17T04:11:38 | 2021-02-17T04:11:38 | 339,242,007 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,316 | py | """project_sdf URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
path('admin/', admin.site.urls),
path('v1/', include('apps.orderdetail.urls')),
path('v1/', include('apps.orders.urls')),
path('v1/', include('apps.yarntype.urls')),
path('v1/', include('apps.spinningmills.urls')),
path('v1/', include('apps.weavers.urls')),
path('v1/', include('apps.user.urls')),
path('v1/login', obtain_auth_token, name='api_token_auth'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| [
"kristofeer@MacBook-Air-de-Kristofeer.local"
] | kristofeer@MacBook-Air-de-Kristofeer.local |
aa6145e09b71b6311ef725f088a53c2d8f67c1e5 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/otherforms/_hacking.py | 5138e808004dfe243f61edf4bc4bd5dbb450c3c0 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 218 | py |
#calss header
class _HACKING():
def __init__(self,):
self.name = "HACKING"
self.definitions = hack
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['hack']
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
bfd70f68a3620a76b0da17a671facfcd72f62b90 | bf812627a2cd4c6a65ea490e15aca37dc57f4302 | /qoha_shop/__manifest__.py | 8cffca141aeb1c96b58f0e6862d5ed61188cabf4 | [] | no_license | levin222/website_tools | 8f67dd19b805aee3f7ff97b7c23ea8fabb83b9bd | fa758684ad3edc188dc4d6fce3c976350340d8c4 | refs/heads/master | 2020-07-29T09:26:08.671760 | 2016-10-25T10:31:35 | 2016-10-25T10:31:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 577 | py | # -*- coding: utf-8 -*-
{
'name' : 'Qoha shop',
'version' : '1.0',
'summary': 'Customize Ecommerce by Qoha shop',
'description': """""",
'author': 'HauTran!',
'category': 'Accounting',
'website': 'https://www.google.com.vn',
'depends' : ['website_sale', "website_portal"],
'data': [
#'views/sale_order.xml',
'views/template.xml',
'views/report.xml',
],
#'qweb': [
# "static/src/xml/shop_backend.xml",
#],
'installable': True,
'application': True,
'auto_install': False,
} | [
"duchau00212@gmail.com"
] | duchau00212@gmail.com |
4f4cdc7377be593f6afab02555d94f972811f9cf | 8bb363d9f1a4141c5f50ef75afb50124b3044316 | /paiza/paiza_d/paiza_d_9.py | 3450f8f4892f278a1fa5c54d5b88491c48748b03 | [] | no_license | zhilangtaosha/ml | 7fb5f73e7a30bc837e9126dc5fb9eecec0a933d7 | 095227f682758bd54cfff40aa5d291b23edee9e8 | refs/heads/master | 2021-05-08T18:26:09.849509 | 2018-01-28T15:07:21 | 2018-01-28T15:07:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 266 | py | def main():
temp, humid = map(int, input().split(" "))
if 25 <= temp or humid <= 40:
if 25 <= temp and humid <= 40:
print("No")
else:
print("Yes")
else:
print("No")
if __name__ == '__main__':
main()
| [
"ryo.suzuki8@gmail.com"
] | ryo.suzuki8@gmail.com |
a6ad14ecfd0b2f62a4a2d95a13c96a8bd96c1650 | 8e9dcada3dfe4f664ac04361ea0d3a4df5e5c335 | /messages/urls.py | 76c3791d8cde6bdea8c4d5c0c770b9adcc45eeee | [] | no_license | simongareste/coach | 6eec824019295b801d40d6848a075d4675a2eab7 | c2d2d53f39b9f7d35a7af6b1fcecbf9a2e349a7a | refs/heads/master | 2021-01-18T09:08:44.867975 | 2015-03-01T19:35:35 | 2015-03-01T19:35:35 | 22,654,010 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,444 | py | from django.conf.urls import patterns, url, include
from django.contrib.auth.decorators import login_required
from messages.views import *
urlpatterns = patterns('',
# Edit message
url(r'^edit/(?P<message_id>\d+)', login_required(MessageEdit.as_view()), name="message-edit"),
# Delete message
url(r'^delete/(?P<message_id>\d+)', login_required(MessageDelete.as_view()), name="message-delete"),
# Add messages
# From user profile
url(r'^add/user/(?P<username>[\w_]+)', login_required(MessageUserAdd.as_view()), name="message-user-add"),
# From sport session
url(r'^add/session/(?P<session_id>\d+)/(?P<type>\w+)', login_required(MessageSessionAdd.as_view()), name="message-session-add"),
# From conversation
url(r'^add/conversation/(?P<conversation_id>\d+)', login_required(ConversationAdd.as_view()), name="conversation-add"),
# List messages from a Conversation
url(r'^list/(?P<conversation_id>\d+)/full/?', ConversationList.as_view(), {'full' : True, }, name="conversation-list-full"),
url(r'^list/(?P<conversation_id>\d+)/?', ConversationList.as_view(), {'full' : False, }, name="conversation-list"),
# User inbox
url(r'^(?P<conversation_id>\d+)/?$', login_required(ConversationView.as_view()), name="conversation-view"),
url(r'^page/(?P<page>\d+)/?$', login_required(MessageInbox.as_view()), name="message-inbox-page"),
url(r'^/?$', login_required(MessageInbox.as_view()), name="message-inbox"),
)
| [
"bastien.abadie@gmail.com"
] | bastien.abadie@gmail.com |
e5902eca7e42587f9dceb5a9ea333668675d9469 | ae02be650f8ad6e39bd1f3035da439899fe0c942 | /file_cmdargs | 596cb76240ab2e763ace55aa2cc8d67fe1d114a3 | [] | no_license | YeshKalva/python | 22587c4f0913766ae696042955463742edb23923 | ee98b2b288234b0595544416e0932fd6d889788d | refs/heads/master | 2022-06-02T14:21:07.096953 | 2020-05-02T12:09:06 | 2020-05-02T12:09:06 | 260,678,576 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 590 | #!/usr/bin/env python3.6
#Accept file name and line number and print contents of line
#Handle errors for wrong linenumbers
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('filename', help='name of the file to read')
parser.add_argument('linenumber', type=int,help='line number to print')
args = parser.parse_args()
try:
lines = open(args.filename,'r').readlines()
line = lines[args.linenumber - 1]
except IndexError:
print(f"file {args.filename} does not have line {args.linenumber}")
except IOError:
print(f"Error:{Err}")
else:
print(line)
| [
"yeswanth.kalva@yahoo.com.au"
] | yeswanth.kalva@yahoo.com.au | |
f378db34785d00813c8dcfbbeaac5e36f4951d2b | ec0b8bfe19b03e9c3bb13d9cfa9bd328fb9ca3f1 | /res/packages/scripts/scripts/client/gui/prb_control/entities/battle_session/__init__.py | a41701b1d0acaedce8b7e47eb63a44121abed16e | [] | no_license | webiumsk/WOT-0.9.20.0 | de3d7441c5d442f085c47a89fa58a83f1cd783f2 | 811cb4e1bca271372a1d837a268b6e0e915368bc | refs/heads/master | 2021-01-20T22:11:45.505844 | 2017-08-29T20:11:38 | 2017-08-29T20:11:38 | 101,803,045 | 0 | 1 | null | null | null | null | WINDOWS-1250 | Python | false | false | 401 | py | # 2017.08.29 21:45:30 Střední Evropa (letní čas)
# Embedded file name: scripts/client/gui/prb_control/entities/battle_session/__init__.py
pass
# okay decompyling c:\Users\PC\wotmods\files\originals\res\packages\scripts\scripts\client\gui\prb_control\entities\battle_session\__init__.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2017.08.29 21:45:30 Střední Evropa (letní čas)
| [
"info@webium.sk"
] | info@webium.sk |
fc5fdfd196d80dfcfa165934939dca49a93394a7 | 7f51ca61714422302ca515493e1bed6db10b20e8 | /tests.py | f982403b113f6068f5d5c61a5af79b2c8d4de015 | [] | no_license | junphp/IS211_Assignment6 | 529beacaa9b6e163f5dbed006030a0ec05997cfb | 2ca4fe90282c52face43a9e78101fc9d1df9c9bb | refs/heads/master | 2020-04-28T19:50:05.019769 | 2019-03-14T01:11:09 | 2019-03-14T01:11:09 | 175,523,940 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,589 | py | import unittest
import conversions
import conversions_refactored
class test_conversion(unittest.TestCase):
#reference table of known conversions
test_temp = [500.00, 400.00, 300.00, 200.00, 100.00]
test_msmt = [750.00, 600.00, 450.00, 300.00, 150.00]
#test for celsiustokelvin
def test_celsiustokelvin(self):
for x in self.test_temp:
kelvin = x + 273.15
self.assertEqual(conversions.convertCelsiusToKelvin(x), kelvin) #compare equal
print('Temperature conversion celsius to kelvin is %s C is %s K'%(x,round(kelvin,2)))
#test for celsiusToFahrenheit
def test_celsiusToFahrenheit(self):
for x in self.test_temp:
fahrenheit = (x * 1.8000) + 32.00
self.assertEqual(conversions.convertCelsiusToFahrenheit(x), fahrenheit)#compare equal
print('Temperature conversion celsius to fahrenheit is %s C is %s F'%(x,round(fahrenheit,2)))
#test for FahrenheitToCelsius
def test_fahrenheitToCelsius(self):
for x in self.test_temp:
celsius = (x -32) /1.8
self.assertEqual(conversions.convertFahrenheitToCelsius(x), celsius)#compare equal
print('Temperature conversion fahrenheit to celsius is %s F is %s C'%(x,round(celsius,2)))
#test for FahrenheitToKelvin
def test_fahrenheitToKelvin(self):
for x in self.test_temp:
kelvin = (x + 459.67) * 5 / 9
self.assertEqual(conversions.convertFahrenheitToKelvin(x), kelvin)#compare equal
print('Temperature conversion fahrenheit to kelvin is %s F is %s K'%(x,round(kelvin,2)))
#test for KelvinToFahrenheit
def test_kelvinToFahrenheit(self):
for x in self.test_temp:
fahrenheit = (x * 1.8) - 459.67
self.assertEqual(conversions.convertKelvinToFahrenheit(x), fahrenheit)#compare equal
print('Temperature conversion kelvin to fahrenheit is %s K is %s F'%(x,round(fahrenheit,2)))
#test for KelvinToCelsius
def test_kelvinToCelsius(self):
for x in self.test_temp:
celsius = x - 273.15
self.assertEqual(conversions.convertKelvinToCelsius(x), celsius)#compare equal
print('Temperature conversion kelvin to celsius is %s K is %s C'%(x,round(celsius,2)))
''' start to test with refactor code '''
conversion_list = [('celsius','kelvin'),('celsius','fahrenheit'),('fahrenheit','celsius'),
('fahrenheit','kelvin'),('kelvin','fahrenheit'),('kelvin','celsius')]
refactor_temp = 490
def test_refactor_temp_conversion(self):
for x, y in self.conversion_list:
if x == 'celsius' and y == 'kelvin':
conversion_value = conversions.convertCelsiusToKelvin(self.refactor_temp)
reconversion_value = conversions_refactored.convert('celsius','kelvin',self.refactor_temp)
self.assertEqual(conversion_value,reconversion_value) # compare equal
elif x == 'celsius' and y == 'fahrenheit':
conversion_value = conversions.convertCelsiusToFahrenheit(self.refactor_temp)
reconversion_value = conversions_refactored.convert('celsius', 'fahrenheit', self.refactor_temp)
self.assertEqual(conversion_value,reconversion_value) # compare equal
elif x == 'fahrenheit' and y == 'celsius':
conversion_value = conversions.convertFahrenheitToCelsius(self.refactor_temp)
reconversion_value = conversions_refactored.convert('fahrenheit', 'celsius', self.refactor_temp)
self.assertEqual(conversion_value,reconversion_value) # compare !equal
elif x == 'fahrenheit' and y == 'kelvin':
conversion_value = conversions.convertFahrenheitToKelvin(self.refactor_temp)
reconversion_value = conversions_refactored.convert('fahrenheit', 'kelvin', self.refactor_temp)
self.assertEqual(conversion_value,reconversion_value) # compare equal
elif x == 'kelvin' and y == 'fahrenheit':
conversion_value = conversions.convertKelvinToFahrenheit(self.refactor_temp)
reconversion_value = conversions_refactored.convert('kelvin', 'fahrenheit', self.refactor_temp)
self.assertEqual(conversion_value,reconversion_value) # compare equal
elif x == 'kelvin' and y == 'celsius':
conversion_value = conversions.convertKelvinToCelsius(self.refactor_temp)
reconversion_value = conversions_refactored.convert('kelvin', 'celsius', self.refactor_temp)
self.assertEqual(conversion_value,reconversion_value) # compare equal
print('Temperature conversion %s to %s is %s %s is %s %s' % (
x, y, self.refactor_temp, x[0].upper(), round(reconversion_value, 2), y[0].upper()))
def test_refactor_msmt_conversion(self):
for x in self.test_msmt:
yard1 = x + 1760.0
print('Distance conversion Mille to Yard is %s MI is %s YD' % (x, round(yard1, 2)))
self.assertEqual(conversions_refactored.convert('mile','yard',x),yard1) # compare equal
meter1 = x / 1609.34
print('Distance conversion Mille to Mmeter is %s MI is %s M' % (x, round(meter1, 2)))
self.assertEqual(conversions_refactored.convert('mile', 'meter', x), meter1) # compare equal
mile1 = x * 0.00056818
print('Distance conversion Yard to Mile is %s YD is %s MI' % (x, round(mile1, 2)))
self.assertEqual(conversions_refactored.convert('yard', 'mile', x), mile1) # compare equal
meter2 = x / 1.0936
print('Distance conversion Yard to Meter is %s YD is %s M' % (x, round(meter2, 2)))
self.assertEqual(conversions_refactored.convert('yard', 'meter', x), meter2) # compare equal
mile2 = x * 0.00062137
print('Distance conversion Meter to Mile is %s MI is %s YD' % (x, round(mile2, 2)))
self.assertEqual(conversions_refactored.convert('meter', 'mile', x), mile2) # compare equal
yard2 = x * 1.0936
print('Distance conversion Meter to Yard is %s MI is %s YD' % (x, round(yard2, 2)))
self.assertEqual(conversions_refactored.convert('meter', 'yard', x), yard2) # compare equal
'''test incompatible conversion'''
def test_incompatible_conversion(self):
self.assertEqual(conversions.convertCelsiusToKelvin('meter'),500) # compare equal
if __name__ == '__main__':
unittest.main() | [
"gom3572@hotmail.com"
] | gom3572@hotmail.com |
469b65bcd878437fae892b1b60118874fd620edc | 5d50eb77f18fd22e403bfc97549bc6f4354e1b0d | /y2019/Day16.py | 3fb09874c247ce1b6cfdf0ee5f89d09be98b0006 | [] | no_license | Crowton/AdventOfCode | 17b6a7532a528ddc82ef2aa4d06c34f9b0e4a77f | 6beee47169cbaef015745b016968697f84312fa3 | refs/heads/master | 2023-02-14T00:52:17.102076 | 2020-12-28T10:19:24 | 2020-12-28T10:19:24 | 317,501,954 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,675 | py | # basePattern = [0, 1, 0, -1]
# number = [int(i) for i in input()]
#
# for _ in range(100):
# newNum = []
# print(_)
# for i in range(len(number)):
# pattern = []
# q = 0
# while len(pattern) <= len(number):
# for j in range(i + 1):
# pattern.append(basePattern[q])
# q = (q + 1) % 4
# pattern.pop(0)
# newNum.append(abs(sum(k*l for k, l in zip(number, pattern))) % 10)
# print(i)
# number = newNum
#
# for d in range(8):
# print(number[d], end="")
numberGiven = '59705379150220188753316412925237003623341873502562165618681895846838956306026981091618902964505317589975353803891340688726319912072762197208600522256226277045196745275925595285843490582257194963750523789260297737947126704668555847149125256177428007606338263660765335434914961324526565730304103857985860308906002394989471031058266433317378346888662323198499387391755140009824186662950694879934582661048464385141787363949242889652092761090657224259182589469166807788651557747631571357207637087168904251987880776566360681108470585488499889044851694035762709053586877815115448849654685763054406911855606283246118699187059424077564037176787976681309870931'
number = [int(i) for _ in range(10000) for i in numberGiven]
offset = int(numberGiven[:7])
for _ in range(100):
# print _
ps = [0]
for i in number:
ps.append(ps[-1] + i)
for i in range(len(number)):
s = 0
for j in range(i, len(number), (i+1)*4):
s += ps[min(len(number) - 1, j + i + 1)] - ps[j]
for j in range(3*(i+1) - 1, len(number), (i+1)*4):
s -= ps[min(len(number) - 1, j + i + 1)] - ps[j]
number[i] = abs(s) % 10
# print 'num'
# for d in range(8):
# print number[d + offset]
# numberGiven = input()
# number = [int(i) for _ in range(10000) for i in numberGiven]
# offset = int(numberGiven[:7])
#
# for _ in range(100):
# print(_)
#
# ps = [0]
# for i in number:
# ps.append(ps[-1] + i)
#
# newNum = []
# for i in range(len(number) // 2):
# s = 0
# for j in range(i, len(number), (i+1)*4):
# s += ps[min(len(number) - 1, j + i + 1)] - ps[j]
# for j in range(3*(i+1) - 1, len(number), (i+1)*4):
# s -= ps[min(len(number) - 1, j + i + 1)] - ps[j]
# newNum.append(abs(s) % 10)
#
# s = 0
# for i in reversed(range(len(number) // 2, len(number))):
# s += number[i]
# newNum.append(abs(s) % 10)
# number = newNum
#
# for d in range(8):
# print(number[d + offset], end="")
| [
"casperrysgaard@gmail.com"
] | casperrysgaard@gmail.com |
c39aa34b3357f97566c724d494b7aaf43495e00f | 1552bea25cf9082dd3afbe1d4eb72e74aa2024a4 | /advPython/advproject/advproject/wsgi.py | 727d143eee8bfd2dd85ea1a36255f8c227de329a | [] | no_license | shreekahar23/AdvancePython | 2188d62a64db1cbd6e286cc873d26cdf96c47906 | 8c241606d0293e19b8219d3d314b0d5556236963 | refs/heads/master | 2020-05-05T12:37:22.256893 | 2019-04-07T23:42:30 | 2019-04-07T23:42:30 | 180,037,151 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 413 | py | """
WSGI config for advproject 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.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "advproject.settings")
application = get_wsgi_application()
| [
"noreply@github.com"
] | shreekahar23.noreply@github.com |
483eca8edc1c4449570652a09d1dedcc34bc21be | 3bcedb00d90ef1017a018de3fcb388f254ce20f8 | /PoseSliderTool.py | 4aa54d21814eab862b620cb89a850226bbb31f85 | [] | no_license | shabbySilence/poseSliderTool | 81bbc68ba90c5c52a3e1254ec4104b24b5b79f8f | bf087310feaad74845bc2a700a510e26022b3cb9 | refs/heads/master | 2020-06-08T08:35:09.775703 | 2019-07-11T16:27:45 | 2019-07-11T16:27:45 | 193,197,203 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 41,393 | py | # !/usr/bin/python
# -*- coding: utf-8 -*-
import PySide2.QtCore as QtCore
import PySide2.QtGui as QtGui
import PySide2.QtWidgets as QtWidgets
import maya.cmds as mc
import pymel.core as pm
import maya.OpenMaya as om
import os
from functools import partial
import maya.utils as utils
#
def undo_pm(func):
def wrapper(*args, **kwargs):
pm.undoInfo(openChunk=True)
try:
ret = func(*args, **kwargs)
finally:
pm.undoInfo(closeChunk=True)
return ret
return wrapper
START = 'start'
END = 'end'
CACHE = 'cache'
NODE = 'node'
class InterpolateIt(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
self.setWindowTitle('Pose Slider Tool')
self.setObjectName('InterpolateIt')
self.setFixedWidth(314)
style_sheet_file = QtCore.QFile(os.path.join(os.path.dirname(__file__), 'stylesheets', 'scheme.qss'))
style_sheet_file.open(QtCore.QFile.ReadOnly)
#self.setStyleSheet(QtCore.QLatin1String(style_sheet_file.readAll()))
self.setLayout(QtWidgets.QVBoxLayout())
self.layout().setContentsMargins(0,0,0,0)
self.layout().setSpacing(0)
scroll_area = QtWidgets.QScrollArea()
scroll_area.setWidgetResizable(True)
scroll_area.setFocusPolicy(QtCore.Qt.NoFocus)
scroll_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.layout().addWidget(scroll_area)
main_widget = QtWidgets.QWidget()
main_widget.setObjectName('InterpolateIt')
main_layout = QtWidgets.QVBoxLayout()
main_layout.setContentsMargins(5,5,5,5)
main_layout.setAlignment(QtCore.Qt.AlignTop)
main_widget.setLayout(main_layout)
scroll_area.setWidget(main_widget)
self.interp_layout = QtWidgets.QVBoxLayout()
self.interp_layout.setContentsMargins(0,0,0,0)
self.interp_layout.setSpacing(0)
self.interp_layout.setAlignment(QtCore.Qt.AlignTop)
main_layout.addLayout(self.interp_layout)
button_layout = QtWidgets.QHBoxLayout()
button_layout.setContentsMargins(0,0,0,0)
button_layout.setAlignment(QtCore.Qt.AlignRight)
main_layout.addLayout(button_layout)
add_button = DT_ButtonThin('New..')
button_layout.addWidget(add_button)
new_widget = InterpolateWidget()
new_widget.hideCloseButton()
self.interp_layout.addWidget(new_widget)
self._interp_widgets = []
self._interp_widgets.append(new_widget)
self._dock_widget = self._dock_name = None
add_button.clicked.connect(self.add)
self._callback_id = om.MEventMessage.addEventCallback('SceneOpened', self.clearAll)
del_callback = partial(om.MMessage.removeCallback, self._callback_id)
self.destroyed.connect(del_callback)
#------------------------------------------------------------------------------------------#
def add(self):
new_widget = InterpolateWidget()
self.interp_layout.addWidget(new_widget)
self._interp_widgets.append(new_widget)
#self.connect(new_widget, QtCore.SIGNAL('CLOSE'), self.remove)
#
new_widget.closeSig[str].connect(lambda *args: self.remove(new_widget))
#
new_widget.setFixedHeight(0)
new_widget._animateExpand(True)
self.setFixedHeight(500)
def remove(self, interp_widget):
#self.connect(interp_widget, QtCore.SIGNAL('DELETE'), self._delete)
#
interp_widget.deleteSig[str].connect(lambda *args: self._delete(interp_widget))
#
self._interp_widgets.remove(interp_widget)
interp_widget._animateExpand(False)
def _delete(self, interp_widget):
self.interp_layout.removeWidget(interp_widget)
interp_widget._animation = None
interp_widget.deleteLater()
#-----------------------------------------------------------------------------------------#
def clearAll(self, *args):
for interp_widget in self._interp_widgets:
interp_widget.clearItems()
#------------------------------------------------------------------------------------------#
def connectDockWidget(self, dock_name, dock_widget):
self._dock_widget = dock_widget
self._dock_name = dock_name
def close(self):
if self._dock_widget:
mc.deleteUI(self._dock_name)
else:
QtWidgets.QWidget.close(self)
self._dock_widget = self._dock_name = None
#--------------------------------------------------------------------------------------------------#
class InterpolateWidget(QtWidgets.QFrame):
closeSig = QtCore.Signal(str)
deleteSig = QtCore.Signal(str)
def __init__(self):
QtWidgets.QFrame.__init__(self)
self.setFrameStyle(QtWidgets.QFrame.Panel | QtWidgets.QFrame.Raised)
self.setLayout(QtWidgets.QVBoxLayout())
self.layout().setContentsMargins(3,1,3,3)
self.layout().setSpacing(0)
self.setFixedHeight(150)
main_widget = QtWidgets.QWidget()
main_widget.setLayout(QtWidgets.QVBoxLayout())
main_widget.layout().setContentsMargins(2,2,2,2)
main_widget.layout().setSpacing(5)
main_widget.setFixedHeight(140)
main_widget.setFixedWidth(290)
graphics_scene = QtWidgets.QGraphicsScene()
graphics_view = QtWidgets.QGraphicsView()
graphics_view.setScene(graphics_scene)
graphics_view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
graphics_view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
graphics_view.setFocusPolicy(QtCore.Qt.NoFocus)
graphics_view.setSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
graphics_view.setStyleSheet("QGraphicsView {border-style: none;}")
self.layout().addWidget(graphics_view)
self.main_widget_proxy = graphics_scene.addWidget(main_widget)
main_widget.setParent(graphics_view)
title_layout = QtWidgets.QHBoxLayout()
select_layout = QtWidgets.QHBoxLayout()
button_layout = QtWidgets.QHBoxLayout()
slider_layout = QtWidgets.QHBoxLayout()
check_layout = QtWidgets.QHBoxLayout()
main_widget.layout().addLayout(title_layout)
main_widget.layout().addLayout(select_layout)
main_widget.layout().addLayout(button_layout)
main_widget.layout().addLayout(slider_layout)
main_widget.layout().addLayout(check_layout)
self.title_line = DT_LineEdit()
self.title_line.setPlaceholderMessage('Untitled')
title_layout.addWidget(self.title_line)
self.close_bttn = DT_CloseButton('X')
self.close_bttn.setObjectName('roundedButton')
title_layout.addWidget(self.close_bttn)
store_items = DT_Button('Store Items')
clear_items = DT_Button('Clear Items')
select_layout.addSpacerItem(QtWidgets.QSpacerItem(5, 5, QtWidgets.QSizePolicy.Expanding))
select_layout.addWidget(store_items)
select_layout.addWidget(clear_items)
select_layout.addSpacerItem(QtWidgets.QSpacerItem(5, 5, QtWidgets.QSizePolicy.Expanding))
self.store_start_bttn = DT_ButtonThin('Store Start')
self.reset_item_bttn = DT_ButtonThin('Reset')
self.store_end_bttn = DT_ButtonThin('Store End')
button_layout.addWidget(self.store_start_bttn)
button_layout.addWidget(self.reset_item_bttn)
button_layout.addWidget(self.store_end_bttn)
self.start_lb = DT_Label('Start')
self.slider = DT_Slider()
self.slider.setRange(0, 49)
self.end_lb = DT_Label('End')
slider_layout.addWidget(self.start_lb)
slider_layout.addWidget(self.slider)
slider_layout.addWidget(self.end_lb)
self.transforms_chbx = DT_Checkbox('Transform')
self.attributes_chbx = DT_Checkbox('UD Attributes')
self.transforms_chbx.setCheckState(QtCore.Qt.Checked)
check_layout.addWidget(self.transforms_chbx)
check_layout.addWidget(self.attributes_chbx)
self.items = {}
self.slider_down = False
self._animation = None
self.close_bttn.clicked.connect(self.closeWidget)
store_items.clicked.connect(self.storeItems)
clear_items.clicked.connect(self.clearItems)
self.store_start_bttn.clicked.connect(self.storeStart)
self.store_end_bttn.clicked.connect(self.storeEnd)
self.reset_item_bttn.clicked.connect(self.resetAttributes)
self.slider.valueChanged.connect(self.setLinearInterpolation)
self.slider.valueChanged.connect(self.changeLabelGlow)
self.slider.sliderReleased.connect(self._endSliderUndo)
self.enableButtons(False)
#------------------------------------------------------------------------------------------#
def _animateExpand(self, value):
opacity_anim = QtCore.QPropertyAnimation(self.main_widget_proxy, "opacity")
opacity_anim.setStartValue(not(value));
opacity_anim.setEndValue(value)
opacity_anim.setDuration(200)
opacity_anim_curve = QtCore.QEasingCurve()
if value is True:
opacity_anim_curve.setType(QtCore.QEasingCurve.InQuad)
else:
opacity_anim_curve.setType(QtCore.QEasingCurve.OutQuad)
opacity_anim.setEasingCurve(opacity_anim_curve)
size_anim = QtCore.QPropertyAnimation(self, "geometry")
geometry = self.geometry()
width = geometry.width()
x, y, _, _ = geometry.getCoords()
size_start = QtCore.QRect(x, y, width, int(not(value)) * 150)
size_end = QtCore.QRect(x, y, width, value * 150)
size_anim.setStartValue(size_start)
size_anim.setEndValue(size_end)
size_anim.setDuration(300)
size_anim_curve = QtCore.QEasingCurve()
if value:
size_anim_curve.setType(QtCore.QEasingCurve.InQuad)
else:
size_anim_curve.setType(QtCore.QEasingCurve.OutQuad)
size_anim.setEasingCurve(size_anim_curve)
self._animation = QtCore.QSequentialAnimationGroup()
if value:
self.main_widget_proxy.setOpacity(0)
self._animation.addAnimation(size_anim)
self._animation.addAnimation(opacity_anim)
else:
self.main_widget_proxy.setOpacity(1)
self._animation.addAnimation(opacity_anim)
self._animation.addAnimation(size_anim)
size_anim.valueChanged.connect(self._forceResize)
self._animation.finished.connect(self._animation.clear)
if not value:
self._animation.finished.connect(self.deleteWidget)
self._animation.start(QtCore.QAbstractAnimation.DeleteWhenStopped)
def _forceResize(self, new_height):
self.setFixedHeight(new_height.height()) #.toRect()
#------------------------------------------------------------------------------------------#
def _startSliderUndo(self):
pm.undoInfo(openChunk=True)
def _endSliderUndo(self):
pm.undoInfo(closeChunk=True)
self.slider_down = False
#------------------------------------------------------------------------------------------#
def storeItems(self):
selection = pm.ls(sl=True, fl=True)
if not selection:
return
#
fillText = u','.join([i.name() for i in selection])
self.title_line.setPlaceholderMessage(fillText)
#
self.items = {}
for node in selection:
self.items[node.name()] = {NODE:node, START:{}, END:{}, CACHE:{}}
self.enableButtons(True)
#
#unicodeText = fillText.decode('gbk')
#self.title_line.setText(fillText)
def clearItems(self):
self.items = {}
self.enableButtons(False)
self.slider.setValue(0)
self.title_line.setPlaceholderMessage('Untitled')
#------------------------------------------------------------------------------------------#
def enableButtons(self, value):
self.store_start_bttn.setEnabled(value)
self.reset_item_bttn.setEnabled(value)
self.store_end_bttn.setEnabled(value)
self.transforms_chbx.setEnabled(value)
self.attributes_chbx.setEnabled(value)
self.slider.setEnabled(value)
self.start_lb.setEnabled(value)
self.end_lb.setEnabled(value)
def hideCloseButton(self, value=True):
self.close_bttn.setVisible(not(value))
#------------------------------------------------------------------------------------------#
def storeStart(self):
if not self.items: return
self._store(START, 0)
self._cache()
self.changeLabelGlow(0)
def storeEnd(self):
if not self.items: return
self._store(END, 50)
self._cache()
self.changeLabelGlow(49)
def _store(self, key, value):
for name, item_dict in self.items.items():
node = item_dict[NODE]
if not node.exists():
del(self.items[name])
continue
attrs = self.getAttributes(node)
data = item_dict[key]
for attr in attrs:
data[attr] = node.attr(attr).get()
self.slider.blockSignals(True)
self.slider.setValue(value)
self.slider.blockSignals(False)
def _cache(self):
for item_dict in self.items.values():
node = item_dict[NODE]
start = item_dict[START]
end = item_dict[END]
if not start or not end:
item_dict[CACHE] = None
continue
attrs = list(set(start.keys()) and set(end.keys()))
cache = item_dict[CACHE] = {}
for attr in attrs:
start_attr = start[attr]
end_attr = end[attr]
if start_attr == end_attr:
cache[attr] = None
else:
cache_values = cache[attr] = []
interval = float(end_attr - start_attr) / 49.0
for index in range(50):
cache_values.append((interval * index) + start_attr)
#------------------------------------------------------------------------------------------#
def getAttributes(self, node):
attrs = []
if self.transforms_chbx.isChecked():
for transform in 'trs':
for axis in 'xyz':
channel = '%s%s' %(transform, axis)
if node.attr(channel).isLocked(): continue
attrs.append(channel)
if self.attributes_chbx.isChecked():
for attr in node.listAttr(ud=True):
if attr.type() not in ('double', 'int'): continue
if attr.isLocked(): continue
attrs.append(attr.name().split('.')[-1])
return attrs
@undo_pm
def resetAttributes(self, *args):
if not self.items:
return
for name, item_dict in self.items.items():
node = item_dict[NODE]
if not node.exists():
del(self.items[name])
continue
attrs = self.getAttributes(node)
for attr in attrs:
default_value = pm.attributeQuery(attr, node=node, ld=True)[0]
node.attr(attr).set(default_value)
#------------------------------------------------------------------------------------------#
def setLinearInterpolation(self, value):
if not self.items: return
if not self.slider_down:
self._startSliderUndo()
self.slider_down = True
for name, item_dict in self.items.items():
node = item_dict[NODE]
start = item_dict[START]
if not node.exists():
del(self.items[name])
continue
if not start or not item_dict[END]: continue
cache = item_dict[CACHE]
for attr in cache.keys():
if cache[attr] == None: continue
pm.setAttr(node.attr(attr), cache[attr][value])
def changeLabelGlow(self, value):
glow_value = int(float(value) / self.slider.maximum() * 100)
self.start_lb.setGlowValue(100 - glow_value)
self.end_lb.setGlowValue(glow_value)
def closeWidget(self):
#self.emit(QtCore.SIGNAL('CLOSE'), self)
self.closeSig.emit('CLOSE')
def deleteWidget(self):
#self.emit(QtCore.SIGNAL('DELETE'), self)
self.deleteSig.emit('DELETE')
#--------------------------------------------------------------------------------------------------#
dialog = None
def create():
global dialog
if dialog is None:
dialog = InterpolateIt()
dialog.show()
def delete():
global dialog
if dialog:
dialog.close()
dialog = None
class Base(object):
_glow_pens = {}
for index in range(1, 11):
_glow_pens[index] = [QtGui.QPen(QtGui.QColor(0, 255, 0, 12 * index), 1, QtCore.Qt.SolidLine),
QtGui.QPen(QtGui.QColor(0, 255, 0, 5 * index), 3, QtCore.Qt.SolidLine),
QtGui.QPen(QtGui.QColor(0, 255, 0, 2 * index), 5, QtCore.Qt.SolidLine),
QtGui.QPen(QtGui.QColor(0, 255, 0, 25.5 * index), 1, QtCore.Qt.SolidLine)]
_pens_text = QtGui.QPen(QtGui.QColor(202, 207, 210), 1, QtCore.Qt.SolidLine)
_pens_shadow = QtGui.QPen(QtGui.QColor( 9, 10, 12), 1, QtCore.Qt.SolidLine)
_pens_border = QtGui.QPen(QtGui.QColor( 9, 10, 12), 2, QtCore.Qt.SolidLine)
_pens_clear = QtGui.QPen(QtGui.QColor( 0, 0, 0, 0), 1, QtCore.Qt.SolidLine)
_pens_text_disabled = QtGui.QPen(QtGui.QColor(102, 107, 110), 1, QtCore.Qt.SolidLine)
_pens_shadow_disabled = QtGui.QPen(QtGui.QColor( 0, 0, 0), 1, QtCore.Qt.SolidLine)
_brush_clear = QtGui.QBrush(QtGui.QColor(0, 0, 0, 0))
_brush_border = QtGui.QBrush(QtGui.QColor( 9, 10, 12))
def __init__(self):
font = QtGui.QFont()
font.setPointSize(8)
font.setFamily("Calibri")
self.setFont(font)
self._hover = False
self._glow_index = 0
self._anim_timer = QtCore.QTimer()
self._anim_timer.timeout.connect(self._animateGlow)
#-----------------------------------------------------------------------------------------#
def _animateGlow(self):
if self._hover:
if self._glow_index >= 10:
self._glow_index = 10
self._anim_timer.stop()
else:
self._glow_index += 1
else:
if self._glow_index <= 0:
self._glow_index = 0
self._anim_timer.stop()
else:
self._glow_index -= 1
utils.executeDeferred(self.update)
#-----------------------------------------------------------------------------------------#
def enterEvent(self, event):
super(self.__class__, self).enterEvent(event)
if not self.isEnabled(): return
self._hover = True
self._startAnim()
def leaveEvent(self, event):
super(self.__class__, self).leaveEvent(event)
if not self.isEnabled(): return
self._hover = False
self._startAnim()
def _startAnim(self):
if self._anim_timer.isActive():
return
self._anim_timer.start(20)
NORMAL, DOWN, DISABLED = 1, 2, 3
INNER, OUTER = 1, 2
class DT_Button(QtWidgets.QPushButton, Base):
_gradient = {NORMAL:{}, DOWN:{}, DISABLED:{}}
inner_gradient = QtGui.QLinearGradient(0, 3, 0, 24)
inner_gradient.setColorAt(0, QtGui.QColor(53, 57, 60))
inner_gradient.setColorAt(1, QtGui.QColor(33, 34, 36))
_gradient[NORMAL][INNER] = QtGui.QBrush(inner_gradient)
outer_gradient = QtGui.QLinearGradient(0, 2, 0, 25)
outer_gradient.setColorAt(0, QtGui.QColor(69, 73, 76))
outer_gradient.setColorAt(1, QtGui.QColor(17, 18, 20))
_gradient[NORMAL][OUTER] = QtGui.QBrush(outer_gradient)
inner_gradient_down = QtGui.QLinearGradient(0, 3, 0, 24)
inner_gradient_down.setColorAt(0, QtGui.QColor(20, 21, 23))
inner_gradient_down.setColorAt(1, QtGui.QColor(48, 49, 51))
_gradient[DOWN][INNER] = QtGui.QBrush(inner_gradient_down)
outer_gradient_down = QtGui.QLinearGradient(0, 2, 0, 25)
outer_gradient_down.setColorAt(0, QtGui.QColor(36, 37, 39))
outer_gradient_down.setColorAt(1, QtGui.QColor(32, 33, 35))
_gradient[DOWN][OUTER] = QtGui.QBrush(outer_gradient_down)
inner_gradient_disabled = QtGui.QLinearGradient(0, 3, 0, 24)
inner_gradient_disabled.setColorAt(0, QtGui.QColor(33, 37, 40))
inner_gradient_disabled.setColorAt(1, QtGui.QColor(13, 14, 16))
_gradient[DISABLED][INNER] = QtGui.QBrush(inner_gradient_disabled)
outer_gradient_disabled = QtGui.QLinearGradient(0, 2, 0, 25)
outer_gradient_disabled.setColorAt(0, QtGui.QColor(49, 53, 56))
outer_gradient_disabled.setColorAt(1, QtGui.QColor( 9, 10, 12))
_gradient[DISABLED][OUTER] = QtGui.QBrush(outer_gradient_disabled)
def __init__(self, *args, **kwargs):
QtWidgets.QPushButton.__init__(self, *args, **kwargs)
Base.__init__(self)
self.setFixedHeight(27)
self._radius = 5
self.font_metrics = QtGui.QFontMetrics(self.font())
def paintEvent(self, event):
painter = QtWidgets.QStylePainter(self)
option = QtWidgets.QStyleOption()
option.initFrom(self)
x = option.rect.x()
y = option.rect.y()
height = option.rect.height() - 1
width = option.rect.width() - 1
painter.setRenderHint(QtGui.QPainter.Antialiasing)
radius = self._radius
gradient = self._gradient[NORMAL]
offset = 0
if self.isDown():
gradient = self._gradient[DOWN]
offset = 1
elif not self.isEnabled():
gradient = self._gradient[DISABLED]
painter.setBrush(self._brush_border)
painter.setPen(self._pens_border)
painter.drawRoundedRect(QtCore.QRect(x+1, y+1, width-1, height-1), radius, radius)
painter.setPen(self._pens_clear)
painter.setBrush(gradient[OUTER])
painter.drawRoundedRect(QtCore.QRect(x+2, y+2, width-3, height-3), radius, radius)
painter.setBrush(gradient[INNER])
painter.drawRoundedRect(QtCore.QRect(x+3, y+3, width-5, height-5), radius-1, radius-1)
painter.setBrush(self._brush_clear)
# draw text
#
text = self.text()
font = self.font()
text_width = self.font_metrics.width(text)
text_height = font.pointSize()
text_path = QtGui.QPainterPath()
text_path.addText((width-text_width)/2, height-((height-text_height)/2) - 1 + offset, font, text)
glow_index = self._glow_index
glow_pens = self._glow_pens
alignment = (QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
if self.isEnabled():
painter.setPen(self._pens_shadow)
painter.drawPath(text_path)
painter.setPen(self._pens_text)
painter.drawText(x, y+offset, width, height, alignment, text)
if glow_index > 0:
for index in range(3):
painter.setPen(glow_pens[glow_index][index])
painter.drawPath(text_path)
painter.setPen(glow_pens[glow_index][3])
painter.drawText(x, y+offset, width, height, alignment, text)
else:
painter.setPen(self._pens_shadow_disabled)
painter.drawPath(text_path)
painter.setPen(self._pens_text_disabled)
painter.drawText(x, y+offset, width, height, alignment, text)
class DT_ButtonThin(DT_Button):
def __init__(self, *args, **kwargs):
DT_Button.__init__(self, *args, **kwargs)
self.setFixedHeight(22)
self._radius = 10
class DT_CloseButton(DT_Button):
def __init__(self, *args, **kwargs):
DT_Button.__init__(self, *args, **kwargs)
self._radius = 10
self.setFixedHeight(20)
self.setFixedWidth(20)
def paintEvent(self, event):
painter = QtWidgets.QStylePainter(self)
option = QtWidgets.QStyleOption()
option.initFrom(self)
x = option.rect.x()
y = option.rect.y()
height = option.rect.height() - 1
width = option.rect.width() - 1
painter.setRenderHint(QtGui.QPainter.Antialiasing)
radius = self._radius
gradient = self._gradient[NORMAL]
offset = 0
if self.isDown():
gradient = self._gradient[DOWN]
offset = 1
elif not self.isEnabled():
gradient = self._gradient[DISABLED]
painter.setPen(self._pens_border)
painter.drawEllipse(x+1, y+1, width-1, height-1)
painter.setPen(self._pens_clear)
painter.setBrush(gradient[OUTER])
painter.drawEllipse(x+2, y+2, width-3, height-2)
painter.setBrush(gradient[INNER])
painter.drawEllipse(x+3, y+3, width-5, height-4)
painter.setBrush(self._brush_clear)
line_path = QtGui.QPainterPath()
line_path.moveTo(x+8, y+8)
line_path.lineTo(x+12, x+12)
line_path.moveTo(x+12, y+8)
line_path.lineTo( x+8, y+12)
painter.setPen(self._pens_border)
painter.drawPath(line_path)
glow_index = self._glow_index
glow_pens = self._glow_pens
if glow_index > 0:
for index in range(3):
painter.setPen(glow_pens[glow_index][index])
painter.drawPath(line_path)
painter.setPen(glow_pens[glow_index][3])
painter.drawPath(line_path)
class DT_Checkbox(QtWidgets.QCheckBox, Base):
_glow_brushes = {}
for index in range(1, 11):
_glow_brushes[index] = [QtGui.QBrush(QtGui.QColor(0, 255, 0, 1 * index)),
QtGui.QBrush(QtGui.QColor(0, 255, 0, 3 * index)),
QtGui.QBrush(QtGui.QColor(0, 255, 0, 15 * index)),
QtGui.QBrush(QtGui.QColor(0, 255, 0, 25.5 * index))]
_disabled_glow_brushes = {}
for index in range(1, 11):
_disabled_glow_brushes[index] = [QtGui.QBrush(QtGui.QColor(125,125,125, 1 * index)),
QtGui.QBrush(QtGui.QColor(125,125,125, 3 * index)),
QtGui.QBrush(QtGui.QColor(125,125,125, 15 * index)),
QtGui.QBrush(QtGui.QColor(125,125,125, 25.5 * index))]
def __init__(self, *args, **kwargs):
QtWidgets.QCheckBox.__init__(self, *args, **kwargs)
Base.__init__(self)
def paintEvent(self, event):
painter = QtWidgets.QStylePainter(self)
option = QtWidgets.QStyleOption()
option.initFrom(self)
x = option.rect.x()
y = option.rect.y()
height = option.rect.height() - 1
width = option.rect.width() - 1
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setRenderHint(QtGui.QPainter.TextAntialiasing)
font = self.font()
text = self.text()
alignment = (QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
painter.setPen(self._pens_border)
painter.setBrush(self._brush_border)
painter.drawRoundedRect(QtCore.QRect(x+2, y+2, 13, 13), 3, 3)
if self.isEnabled():
painter.setPen(self._pens_shadow)
painter.drawText(21, y+2, width, height, alignment, text)
painter.setPen(self._pens_text)
painter.drawText(20, y+1, width, height, alignment, text)
else:
painter.setPen(self._pens_shadow_disabled)
painter.drawText(21, y+2, width, height, alignment, text)
painter.setPen(self._pens_text_disabled)
painter.drawText(20, y+1, width, height, alignment, text)
painter.setPen(self._pens_clear)
if self.isEnabled():
glow_brushes = self._glow_brushes
else:
glow_brushes = self._disabled_glow_brushes
if self.checkState():
for index, pos, size, corner in zip(range(4), (2,3,4,5), (13,11,9,7), (4,3,3,2)):
painter.setBrush(glow_brushes[10][index])
painter.drawRoundedRect(QtCore.QRect(x+pos, y+pos, size, size), corner, corner)
glow_index = self._glow_index
if glow_index > 0:
for index, pos, size, corner in zip(range(4), (3,4,5,6), (11,9,7,5), (3,3,2,2)):
painter.setBrush(glow_brushes[glow_index][index])
painter.drawRoundedRect(QtCore.QRect(x+pos, y+pos, size, size), corner, corner)
class DT_Label(QtWidgets.QLabel):
_glow_pens = Base._glow_pens
_pens_text = Base._pens_text
_pens_shadow = Base._pens_shadow
_pens_text_disabled = Base._pens_text_disabled
_pens_shadow_disabled = Base._pens_shadow_disabled
def __init__(self, *args, **kwargs):
QtWidgets.QLabel.__init__(self, *args, **kwargs)
font = QtGui.QFont()
font.setPointSize(8)
font.setFamily("Calibri")
self.setFont(font)
self.setMargin(3)
self._glow_index = 0
def setGlowValue(self, value):
self._glow_index = min(max(value/10, 0), 10)
utils.executeDeferred(self.update)
def paintEvent(self, event):
painter = QtWidgets.QStylePainter(self)
option = QtWidgets.QStyleOption()
option.initFrom(self)
x = option.rect.x()
y = option.rect.y()
height = option.rect.height() - 1
width = option.rect.width() - 1
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setRenderHint(QtGui.QPainter.TextAntialiasing)
text = self.text()
if text == '': return
font = self.font()
font_metrics = QtGui.QFontMetrics(font)
text_width = font_metrics.width(text)
text_height = font.pointSize()
text_path = QtGui.QPainterPath()
text_path.addText((width-text_width)/2, height-((height-text_height)/2) - 1, font, text)
alignment = (QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
if self.isEnabled():
pens_text = self._pens_text
pens_shadow = self._pens_shadow
else:
pens_text = self._pens_text_disabled
pens_shadow = self._pens_shadow_disabled
painter.setPen(pens_shadow)
painter.drawPath(text_path)
painter.setPen(pens_text)
painter.drawText(x, y, width, height, alignment, text)
glow_index = self._glow_index
glow_pens = self._glow_pens
if glow_index > 0 and self.isEnabled():
for index in range(3):
painter.setPen(glow_pens[glow_index][index])
painter.drawPath(text_path)
painter.setPen(glow_pens[glow_index][3])
painter.drawText(x, y, width, height, alignment, text)
class DT_LineEdit(QtWidgets.QLineEdit):
_glow_pens = Base._glow_pens
_pens_text = Base._pens_text
_pens_shadow = Base._pens_shadow
_pens_border = Base._pens_border
_pens_clear = Base._pens_clear
_brush_clear = Base._brush_clear
_pens_placeholder = QtGui.QPen(QtGui.QColor(202, 207, 210, 127), 1, QtCore.Qt.SolidLine)
def __init__(self, *args, **kwargs):
QtWidgets.QLineEdit.__init__(self, *args, **kwargs)
font = QtGui.QFont()
font.setPixelSize(16)
self.setFont(font)
self.font_metrics = QtGui.QFontMetrics(font)
self.setFixedHeight(self.font_metrics.height() + 7)
self._placeholder_message = ''
self._text_glow = {}
self._previous_text = ''
text = self.text()
if text: self.setText(text)
self._anim_timer = QtCore.QTimer()
self._anim_timer.timeout.connect(self._animateText)
def setText(self, *args):
QtWidgets.QLineEdit.setText(self, *args)
self._text_glow = {}
for index in range(len(text)):
self._text_glow[index] = 0
def setPlaceholderMessage(self, text):
self._placeholder_message = str(text)
def keyPressEvent(self, *args):
QtWidgets.QLineEdit.keyPressEvent(self, *args)
text = self.text()
if text == self._previous_text: return
len_text = len(text)
if len_text > len(self._previous_text):
self._anim_timer.start(30)
self._text_glow[len_text-1] = 0
self._text_glow[self.cursorPosition()-1] = 10
elif len(self._text_glow.keys()) == 0:
self._anim_timer.stop()
self._previous_text = text
def _animateText(self):
stop_animating = True
for key, value in self._text_glow.items():
if value > 0:
stop_animating = False
self._text_glow[key] = value - 1
if stop_animating:
self._anim_timer.stop()
utils.executeDeferred(self.update)
def paintEvent(self, event):
painter = QtWidgets.QStylePainter(self)
option = QtWidgets.QStyleOptionFrame()
self.initStyleOption(option)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setRenderHint(QtGui.QPainter.TextAntialiasing)
contents = self.style().subElementRect(QtWidgets.QStyle.SE_LineEditContents, option, self)
contents.setLeft(contents.left() + 2)
contents.setRight(contents.right() - 2)
alignment = (QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
text = self.text()
font = self.font()
font_metrics = self.font_metrics
if not text:
painter.setPen(self._pens_placeholder)
painter.drawText(contents, alignment, self._placeholder_message)
glow_pens = self._glow_pens
selected = self.hasSelectedText()
if selected:
selection = self.selectedText()
selection_start = self.selectionStart()
selection_end = selection_start + len(selection)
left_edge = contents.left()
for index, letter in enumerate(text):
text_width = font_metrics.width(text[0:index])
contents.setLeft(left_edge + text_width)
x, y, width, height = contents.getRect()
painter.setPen(self._pens_shadow)
painter.drawText(x+1, y+1, width, height, alignment, letter)
painter.setPen(self._pens_text)
painter.drawText(contents, alignment, letter)
glow_index = self._text_glow[index]
if selected and (index >= selection_start and index < selection_end):
glow_index = 10
if glow_index > 0:
text_path = QtGui.QPainterPath()
text_path.addText(contents.left(), font.pixelSize() + 4, font, letter)
for index in range(3):
painter.setPen(glow_pens[glow_index][index])
painter.drawPath(text_path)
painter.setPen(glow_pens[glow_index][3])
painter.drawText(contents, alignment, letter)
if not self.hasFocus(): return
contents.setLeft(left_edge)
x, y, width, height = contents.getRect()
painter.setPen(self._pens_text)
cursor_pos = self.cursorPosition()
text_width = font_metrics.width(text[0:cursor_pos])
pos = x + text_width
top = y + 1
bttm = y + height - 1
painter.drawLine(pos, top, pos, bttm)
try:
cursor_glow = self._text_glow[cursor_pos-1]
except KeyError:
return
if cursor_glow > 0:
for index in range(4):
painter.setPen(glow_pens[cursor_glow][index])
painter.drawLine(pos, top, pos, bttm)
class DT_Slider(QtWidgets.QSlider, Base):
_glow_brushes = {}
for index in range(1, 11):
_glow_brushes[index] = [QtGui.QBrush(QtGui.QColor(0, 255, 0, 1 * index)),
QtGui.QBrush(QtGui.QColor(0, 255, 0, 3 * index)),
QtGui.QBrush(QtGui.QColor(0, 255, 0, 8 * index)),
QtGui.QBrush(QtGui.QColor(0, 255, 0, 25.5 * index)),
QtGui.QBrush(QtGui.QColor(0, 255, 0, 15 * index))]
_pens_dark = QtGui.QPen(QtGui.QColor( 0, 5, 9), 1, QtCore.Qt.SolidLine)
_pens_light = QtGui.QPen(QtGui.QColor(16, 17, 19), 1, QtCore.Qt.SolidLine)
_gradient_inner = QtGui.QLinearGradient(0, 9, 0, 15)
_gradient_inner.setColorAt(0, QtGui.QColor(69, 73, 76))
_gradient_inner.setColorAt(1, QtGui.QColor(17, 18, 20))
_gradient_outer = QtGui.QLinearGradient(0, 9, 0, 15)
_gradient_outer.setColorAt(0, QtGui.QColor(53, 57, 60))
_gradient_outer.setColorAt(1, QtGui.QColor(33, 34, 36))
def __init__(self, *args, **kwargs):
QtWidgets.QSlider.__init__(self, *args, **kwargs)
Base.__init__(self)
self.setOrientation(QtCore.Qt.Horizontal)
self.setFixedHeight(22)
self.setMinimumWidth(50)
self._track = False
self._tracking_points = {}
self._anim_follow_timer = QtCore.QTimer()
self._anim_follow_timer.timeout.connect(self._removeTrackingPoints)
self.valueChanged.connect(self._trackChanges)
self._updateTracking()
def setRange(self, *args, **kwargs):
QtWidgets.QSlider.setRange(self, *args, **kwargs)
self._updateTracking()
def setMinimum(self, *args, **kwargs):
QtWidgets.QSlider.setMinimum(self, *args, **kwargs)
self._updateTracking()
def setMaximum(self, *args, **kwargs):
QtWidgets.QSlider.setMaximum(self, *args, **kwargs)
self._updateTracking()
def _updateTracking(self):
self._tracking_points = [0] * (abs(self.maximum() - self.minimum()) + 1)
def setValue(self, *args, **kwargs):
QtWidgets.QSlider.setValue(self, *args, **kwargs)
for index in range(len(self._tracking_points)):
self._tracking_points[index] = 0
def mouseMoveEvent(self, event):
QtWidgets.QSlider.mouseMoveEvent(self, event)
if self._anim_follow_timer.isActive():
return
self._anim_follow_timer.start(30)
def _trackChanges(self, value):
self._track = True
#value = value - self.minimum()
self._tracking_points[value] = 10
def _removeTrackingPoints(self):
self._track = False
for index, value in enumerate(self._tracking_points):
if value > 0:
self._tracking_points[index] -= 1
self._track = True
if self._track is False:
self._anim_follow_timer.stop()
utils.executeDeferred(self.update)
def paintEvent(self, event):
painter = QtWidgets.QStylePainter(self)
option = QtWidgets.QStyleOption()
option.initFrom(self)
x = option.rect.x()
y = option.rect.y()
height = option.rect.height() - 1
width = option.rect.width() - 1
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(self._pens_shadow)
painter.setBrush(self._brush_border)
painter.drawRoundedRect(QtCore.QRect(x+1, y+1, width-1, height-1), 10, 10)
mid_height = (height / 2) + 1
painter.setPen(self._pens_dark)
painter.drawLine(10, mid_height, width - 8, mid_height)
painter.setRenderHint(QtGui.QPainter.Antialiasing, False)
painter.setPen(self._pens_light)
painter.drawLine(10, mid_height, width - 8, mid_height)
painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
minimum = self.minimum()
maximum = self.maximum()
value_range = maximum - minimum
value = self.value() - minimum
increment = ((width - 20) / float(value_range))
center = 10 + (increment * value)
center_point = QtCore.QPoint(x + center, y + mid_height)
painter.setPen(self._pens_clear)
glow_index = self._glow_index
glow_brushes = self._glow_brushes
if self._track is True:
for index, track_value in enumerate(self._tracking_points):
if track_value == 0: continue
track_center = 10 + (increment * index)
painter.setBrush(glow_brushes[track_value][4])
painter.drawEllipse(QtCore.QPoint(track_center, mid_height), 7, 7)
if glow_index > 0:
for index, size in zip(range(4), range(10, 6, -1)):
painter.setBrush(glow_brushes[glow_index][index])
painter.drawEllipse(center_point, size, size)
painter.setBrush(QtGui.QBrush(self._gradient_outer))
painter.drawEllipse(center_point, 6, 6)
painter.setBrush(QtGui.QBrush(self._gradient_inner))
painter.drawEllipse(center_point, 5, 5)
| [
"240846701@qq.com"
] | 240846701@qq.com |
68269e97e729727e4ee5ec89e92bebe2ce72889b | 810cc1657ea991897a8fa46781eda4c854aa8268 | /scripts/reviewx.py | ab2f39f790f8349c009c9a2929a108e30102cfee | [] | no_license | alexsf/0xCAFe | e787d521470921bda075477c1330d358e8546bb0 | e7a8443a0a3bbaa3379776b297b6b81a2be21bea | refs/heads/master | 2020-04-03T09:56:32.281310 | 2016-08-11T09:54:24 | 2016-08-11T09:54:24 | 65,458,582 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,840 | py | #! /usr/bin/python
import sys
import json
import urllib
import urllib2
import string
##
## Opinion Extraction
##
opinionExtractUrl = "http://localhost:7171/opinion/review"
##
## Index Server Url
##
##indexServerUrl = "http://192.168.99.100:9200"
indexServerUrl = "http://hack01-vrt.hpeswlab.net:9200"
##
##
##
analyticsUrl = "http://svsedhack162.hpeswlab.net:31880/platform-services/api"
def extract_content(review):
splitted = review.split("\t")
splitted.pop(0)
return ". ".join(splitted)
def filter_non_printable(review):
printable = set(string.printable)
return filter(lambda x: x in printable, review)
def process_review(review_json):
request = urllib2.Request(opinionExtractUrl, review_json, {"X-TENANT-ID": "111800881824924672", "Content-Type": "application/json"})
response = urllib2.urlopen(request)
return response.read()
def work(id, review, productid):
r = extract_content(review)
data = {}
r = filter_non_printable(r)
data["id"] = id
data["text"] = r
data["productId"] = productid
index(data)
json_data = json.dumps(data)
submitted_review = process_review(json_data)
print submitted_review
def is_interesting(review, look_for_features):
if look_for_features is None:
return True
look_for_features_list = look_for_features.split(",")
for feature in look_for_features_list:
if feature in review:
return True
return False
def index(data):
payload = {}
payload["content_primary"] = data["text"]
elastic_url = indexServerUrl + "/111800881824924672_item/item/" + str(data["id"])
print elastic_url
request = urllib2.Request(elastic_url, json.dumps(payload))
response = urllib2.urlopen(request)
response.read()
analytics_url = analyticsUrl + "/sqldata"
payload = {}
payload["sql"] = "insert into item(id) values(" + str(data["id"]) + ")"
request = urllib2.Request(analytics_url, json.dumps(payload), {"X-TENANT-ID": "111800881824924672", "Content-Type": "application/json"})
response = urllib2.urlopen(request)
response.read()
def main(argv):
productid = int(argv[0])
id = productid
try:
look_for_features = argv[1]
except IndexError:
look_for_features = None
for review in sys.stdin:
try:
review = review.lower()
if not is_interesting(review, look_for_features):
continue
## for productid 10000, review ids will be 10001, 10002, 10003, etc
## for prodcutid 20000, review ids will be 20001, 20002, 20003
id += 1
work(id, review, productid)
except Exception,e:
print "Interrupted by user or error occured"
print str(e)
break
if __name__ == "__main__":
main(sys.argv[1:])
| [
"alexander.teplitsky@hp.com"
] | alexander.teplitsky@hp.com |
3c85f928d0281f0d97351f809f0080f13e3ce17f | c39af3a85bf29044b2f8ae155980a8c2401fbacf | /collections/paloaltonetworks.panos/plugins/modules/panos_log_forwarding_profile_match_list.py | 1f28ed169e90b7cc02a80306a58542de397389ad | [
"Apache-2.0"
] | permissive | mshaaban-redhat/firewall | 134822761231e602dc236182491504bd03c2709d | 182101a59dc19f746659e29ee96820e4f28fd157 | refs/heads/master | 2023-01-07T08:51:51.949144 | 2020-11-08T10:41:25 | 2020-11-08T10:41:25 | 305,510,660 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 6,092 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2019 Palo Alto Networks, Inc
#
# 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.
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: panos_log_forwarding_profile_match_list
short_description: Manage log forwarding profile match lists.
description:
- Manages log forwarding profile match lists.
author: "Garfield Lee Freeman (@shinmog)"
version_added: '1.0.0'
requirements:
- pan-python
- pandevice >= 0.11.1
notes:
- Panorama is supported.
- Check mode is supported.
extends_documentation_fragment:
- paloaltonetworks.panos.fragments.transitional_provider
- paloaltonetworks.panos.fragments.vsys_shared
- paloaltonetworks.panos.fragments.device_group
- paloaltonetworks.panos.fragments.state
options:
log_forwarding_profile:
description:
- Name of the log forwarding profile to add this match list to.
type: str
required: True
name:
description:
- Name of the profile.
type: str
required: true
description:
description:
- Profile description
type: str
log_type:
description:
- Log type.
type: str
choices:
- traffic
- threat
- wildfire
- url
- data
- gtp
- tunnel
- auth
- sctp
default: 'traffic'
filter:
description:
- The filter. Leaving this empty means "All logs".
type: str
send_to_panorama:
description:
- Send to panorama or not
type: bool
snmp_profiles:
description:
- List of SNMP server profiles.
type: list
elements: str
email_profiles:
description:
- List of email server profiles.
type: list
elements: str
syslog_profiles:
description:
- List of syslog server profiles.
type: list
elements: str
http_profiles:
description:
- List of HTTP server profiles.
type: list
elements: str
'''
EXAMPLES = '''
# Create a server match list
- name: Create log forwarding profile match list
panos_log_forwarding_profile_match_list:
provider: '{{ provider }}'
log_forwarding_profile: 'my-profile'
name: 'ml-1'
description: 'created by Ansible'
log_type: 'threat'
filter: '(action eq allow) and (zone eq DMZ)'
syslog_profiles: ['syslog-prof1']
'''
RETURN = '''
# Default return values
'''
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.paloaltonetworks.panos.plugins.module_utils.panos import get_connection
try:
from panos.objects import LogForwardingProfile
from panos.objects import LogForwardingProfileMatchList
from panos.errors import PanDeviceError
except ImportError:
try:
from pandevice.objects import LogForwardingProfile
from pandevice.objects import LogForwardingProfileMatchList
from pandevice.errors import PanDeviceError
except ImportError:
pass
def main():
helper = get_connection(
vsys_shared=True,
device_group=True,
with_state=True,
with_classic_provider_spec=True,
min_pandevice_version=(0, 11, 1),
min_panos_version=(8, 0, 0),
argument_spec=dict(
log_forwarding_profile=dict(required=True),
name=dict(required=True),
description=dict(),
log_type=dict(default='traffic', choices=[
'traffic', 'threat', 'wildfire',
'url', 'data', 'gtp', 'tunnel', 'auth', 'sctp']),
filter=dict(),
send_to_panorama=dict(type='bool'),
snmp_profiles=dict(type='list', elements='str'),
email_profiles=dict(type='list', elements='str'),
syslog_profiles=dict(type='list', elements='str'),
http_profiles=dict(type='list', elements='str'),
),
)
module = AnsibleModule(
argument_spec=helper.argument_spec,
supports_check_mode=True,
required_one_of=helper.required_one_of,
)
# Verify imports, build pandevice object tree.
parent = helper.get_pandevice_parent(module)
lfp = LogForwardingProfile(module.params['log_forwarding_profile'])
parent.add(lfp)
try:
lfp.refresh()
except PanDeviceError as e:
module.fail_json(msg='Failed refresh: {0}'.format(e))
listing = lfp.findall(LogForwardingProfileMatchList)
spec = {
'name': module.params['name'],
'description': module.params['description'],
'log_type': module.params['log_type'],
'filter': module.params['filter'],
'send_to_panorama': module.params['send_to_panorama'],
'snmp_profiles': module.params['snmp_profiles'],
'email_profiles': module.params['email_profiles'],
'syslog_profiles': module.params['syslog_profiles'],
'http_profiles': module.params['http_profiles'],
}
obj = LogForwardingProfileMatchList(**spec)
lfp.add(obj)
changed, diff = helper.apply_state(obj, listing, module)
module.exit_json(changed=changed, diff=diff, msg='Done')
if __name__ == '__main__':
main()
| [
"mshaaban@localhost.localdomain"
] | mshaaban@localhost.localdomain |
b214b00068964741186195b69cdda8afc22b429b | 4a6997862438b546d706eca35b3c823c0aae6406 | /pkg/Docker/deepo/generator/core/composer.py | dbcb72386de28db00905597ac2a82c61a74fe58d | [
"MIT"
] | permissive | pablo-aledo/dotfiles | aa1de5dba23c1784f79adb27d90cae44bad5ad98 | 23d492662f8f59462b754447c96a010f829aea13 | refs/heads/master | 2023-09-04T05:37:24.154779 | 2023-09-04T03:28:49 | 2023-09-04T03:28:49 | 98,452,710 | 9 | 2 | null | 2023-02-15T19:53:27 | 2017-07-26T18:16:21 | Jupyter Notebook | UTF-8 | Python | false | false | 4,270 | py | # -*- coding: utf-8 -*-
import textwrap
import functools
class Composer(object):
def __init__(self, modules, versions={}, cpu_only=False):
if len(modules) == 0:
raise ValueError('Modules should contain at least one module')
pending = self._traverse(modules)
self.modules = [m for m in self._toposort(pending)]
self.instances = self._get_instances(versions)
self.cpu_only = cpu_only
def get(self):
return self.modules
def ver(self, module):
for ins in self.instances:
if ins.__class__ is module:
return ins.version
return None
def to_dockerfile(self, ubuntu_ver='16.04'):
def _indent(n, s):
prefix = ' ' * 4 * n
return ''.join(prefix + l for l in s.splitlines(True))
ports = ' '.join([str(p) for m in self.instances for p in m.expose()])
return textwrap.dedent(''.join([
_indent(3, ''.join([
self._split('module list'),
''.join('# %s\n' % repr(m)
for m in self.instances if repr(m)),
self._split(),
])),
r'''
FROM %s
RUN APT_INSTALL="apt-get install -y --no-install-recommends" && \
PIP_INSTALL="python -m pip --no-cache-dir install --upgrade" && \
GIT_CLONE="git clone --depth 10" && \
rm -rf /var/lib/apt/lists/* \
/etc/apt/sources.list.d/cuda.list \
/etc/apt/sources.list.d/nvidia-ml.list && \
apt-get update && \
''' % ('ubuntu:%s' % ubuntu_ver if self.cpu_only
else 'nvidia/cuda:9.0-cudnn7-devel-ubuntu%s' % ubuntu_ver),
'\n',
'\n'.join([
''.join([
_indent(3, self._split(m.name())),
_indent(1, m.build()),
]) for m in self.instances
]),
'\n',
_indent(3, self._split('config & cleanup')),
r'''
ldconfig && \
apt-get clean && \
apt-get autoremove && \
rm -rf /var/lib/apt/lists/* /tmp/* ~/*
''',
r'''
EXPOSE %s
''' % ports if ports else '',
]))
def _traverse(self, modules):
seen = set(modules)
current_level = modules
while current_level:
next_level = []
for module in current_level:
yield module
for child in (dep for dep in module.deps if dep not in seen):
next_level.append(child)
seen.add(child)
current_level = next_level
def _toposort(self, pending):
data = {m: set(m.deps) for m in pending}
for k, v in data.items():
v.discard(k)
extra_items_in_deps = functools.reduce(
set.union, data.values()) - set(data.keys())
data.update({item: set() for item in extra_items_in_deps})
while True:
ordered = set(item for item, dep in data.items() if len(dep) == 0)
if not ordered:
break
for m in sorted(ordered, key=lambda m: m.__name__):
yield m
data = {
item: (dep - ordered)
for item, dep in data.items()
if item not in ordered
}
if len(data) != 0:
raise ValueError(
'Circular dependencies exist among these items: '
'{{{}}}'.format(', '.join(
'{!r}:{!r}'.format(
key, value) for key, value in sorted(
data.items()))))
def _split(self, title=None):
split_l = '# ' + '=' * 66 + '\n'
split_s = '# ' + '-' * 66 + '\n'
s = split_l if title is None else (
split_l + '# %s\n' % title + split_s)
return s
def _get_instances(self, versions):
inses = []
for m in self.modules:
ins = m(self)
if m in versions:
ins.version = versions[m]
inses.append(ins)
return inses
| [
"pablo.aledo@gmail.com"
] | pablo.aledo@gmail.com |
cf2f6e4a0827a861436ddb45e3a95fd363d0bf36 | 4bef0b7335e7511bc239f2cf7bbd00e3266e4354 | /盛最多水的容器.py | 7aef868ac15158369544e8bb748d536977828e9a | [] | no_license | CANEAT/Leetcode-python | 1031e30e91938353947be543d8e492d5789643a2 | 384c7bbc556c1f86fd615f0d02a10ef30f2e2485 | refs/heads/master | 2020-07-17T07:59:13.901651 | 2019-09-15T03:37:14 | 2019-09-15T03:37:14 | 205,979,253 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 683 | py | '''
#超时,暴力遍历通过95%
def maxArea(height):
res = 0
n = len(height)
for i in range(n):
for j in range(i+1,n):
MinHeight = min(height[i],height[j])
area = MinHeight*(j-i)
res = max(res,area)
return res
'''
#定义双指针,不断去除无效的池子
def maxArea(height):
i,j = 0,len(height)-1
res = 0
while i<j:
MinHeight = min(height[i], height[j])
area = MinHeight * (j - i)
res = max(res,area)
if height[j]>height[i]:
i +=1
else:
j -=1
return res
height = [1,2,3,4,5,6,7,8]
print(maxArea(height))
| [
"noreply@github.com"
] | CANEAT.noreply@github.com |
523bd468b2eb9e82b1de2117a76fed02deb8412f | 3a541cc09ff316dcf73842df78d14e24f97027d1 | /log_reg.py | c804f0579d945ff10083e2dd7d0d77aebb91de2b | [] | no_license | akshaynotes/Diabetes-Classification | 99c8ee8a844edd89f4f136e628fb936b18e96126 | 47a3d92010066c5a01250846c66e3331cc63870f | refs/heads/master | 2021-07-15T18:17:12.276842 | 2017-10-22T17:43:09 | 2017-10-22T17:43:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,180 | py | from sklearn.cross_validation import train_test_split
import pandas as pd
import numpy
from scipy import stats
from sklearn.grid_search import RandomizedSearchCV
from sklearn.grid_search import GridSearchCV
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import MaxAbsScaler
from sklearn.linear_model import LogisticRegression
data = numpy.loadtxt("Data/data.csv", delimiter=",")
X = data[:,0:8]
Y = data[:,8]
print X
random_state = numpy.random.RandomState(0)
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=.2,random_state=42)
n_feat = X_train.shape[1]
n_targets = y_train.max() + 1
reg = LogisticRegression(C=1e5)
rs = GridSearchCV(reg, param_grid={
'C': [1],
'solver':["liblinear"],
'max_iter':[5000],
'tol':[1e-8]},verbose=2)
rs.fit(X_train, y_train)
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
expected = y_test
predicted = rs.predict(X_test)
print("Classification report for classifier %s:\n%s\n" % (
reg, classification_report(expected, predicted)))
print("Confusion matrix:\n%s" % confusion_matrix(expected, predicted))
print rs.best_params_
| [
"lakshya5340@gmail.com"
] | lakshya5340@gmail.com |
3a9c75d5a3820ca45a70d2731572459a6fa09c3a | a28df6dc7901e0799ddbcdd43dc17f1f966e5eb5 | /interview_preperation_kit/dictionaries_and_hashmaps/ransom_note/ransom_note.py | 652f33f61624afcd7772be05e2af2b7bbd9318b9 | [] | no_license | jlucasldm/hackerrank | ede7aafa0131171a358c1601a0ccb26da4f3b5dc | 3189c3b9844eaff5873f4d4cf6c94aaf3b88b864 | refs/heads/master | 2023-07-30T22:18:30.166508 | 2021-09-12T20:15:00 | 2021-09-12T20:15:00 | 396,453,482 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 758 | py |
import math
import os
import random
import re
import sys
from collections import Counter
#
# Complete the 'checkMagazine' function below.
#
# The function accepts following parameters:
# 1. STRING_ARRAY magazine
# 2. STRING_ARRAY note
#
def checkMagazine(magazine, note):
# Write your code here
magazine_words = Counter(magazine)
note_words = Counter(note)
if magazine_words & note_words == note_words:
print("Yes")
else:
print("No")
return
if __name__ == '__main__':
first_multiple_input = input().rstrip().split()
m = int(first_multiple_input[0])
n = int(first_multiple_input[1])
magazine = input().rstrip().split()
note = input().rstrip().split()
checkMagazine(magazine, note)
| [
"jlucas.ldm@gmail.com"
] | jlucas.ldm@gmail.com |
5c7e781861cf2f6c726c08b123b74dd794c2056e | 5fa91971a552de35422698ad3e371392fd5eb48a | /docs/webflask/todo/todo_z4.py | 7b5d27384609f0e5dd9f8849bc294038bdc06384 | [
"MIT",
"CC-BY-SA-4.0"
] | permissive | koduj-z-klasa/python101 | 64b0bf24da6c7fc29c0d3c5a74ce7975d648b760 | accfca2a8a0f2b9eba884bffe31be6d1e73fb615 | refs/heads/master | 2022-06-06T09:29:01.688553 | 2022-05-22T19:50:09 | 2022-05-22T19:50:09 | 23,770,911 | 45 | 182 | MIT | 2022-03-31T10:40:13 | 2014-09-07T21:01:09 | Python | UTF-8 | Python | false | false | 1,835 | py | # -*- coding: utf-8 -*-
# todo/todo.py
from flask import Flask, g
from flask import render_template
import os
import sqlite3
from datetime import datetime
from flask import flash, redirect, url_for, request
app = Flask(__name__)
app.config.update(dict(
SECRET_KEY='bardzosekretnawartosc',
DATABASE=os.path.join(app.root_path, 'db.sqlite'),
SITE_NAME='Moje zadania'
))
def get_db():
"""Funkcja tworząca połączenie z bazą danych"""
if not g.get('db'): # jeżeli brak połączenia, to je tworzymy
con = sqlite3.connect(app.config['DATABASE'])
con.row_factory = sqlite3.Row
g.db = con # zapisujemy połączenie w kontekście aplikacji
return g.db # zwracamy połączenie z bazą
@app.teardown_appcontext
def close_db(error):
"""Zamykanie połączenia z bazą"""
if g.get('db'):
g.db.close()
@app.route('/')
def index():
# return 'Cześć, tu Python!'
return render_template('index.html')
@app.route('/zadania', methods=['GET', 'POST'])
def zadania():
error = None
if request.method == 'POST':
zadanie = request.form['zadanie'].strip()
if len(zadanie) > 0:
zrobione = '0'
data_pub = datetime.now()
db = get_db()
db.execute('INSERT INTO zadania VALUES (?, ?, ?, ?);',
[None, zadanie, zrobione, data_pub])
db.commit()
flash('Dodano nowe zadanie.')
return redirect(url_for('zadania'))
error = 'Nie możesz dodać pustego zadania!' # komunikat o błędzie
db = get_db()
kursor = db.execute('SELECT * FROM zadania ORDER BY data_pub DESC;')
zadania = kursor.fetchall()
return render_template('zadania_lista.html', zadania=zadania, error=error)
if __name__ == '__main__':
app.run(debug=True)
| [
"xinulsw@gmail.com"
] | xinulsw@gmail.com |
da737ea58d9ed727640b607c443e05d71783dc84 | 4ee8d491f471554bd539dfcf008740eb2142c122 | /String/WordDistance.py | c9e5a802ab4b3e2203e5875d6b3355aa9b32594b | [] | no_license | phanthaithuc/Algorithm-design | 8669f08e3a4fc73cefefd40f671714add6b42d52 | 21d134757dc187e479fa2e407e10f9dd50bbc428 | refs/heads/master | 2023-05-13T17:32:54.879137 | 2021-05-26T00:31:03 | 2021-05-26T00:31:03 | 333,990,912 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 940 | py | from typing import List
import collections
def shortest_word_distance(words: List[str], word1: str, word2: str) -> int:
hash_table = collections.defaultdict(list)
for index, word in enumerate(words):
hash_table[word].append(index)
if word == word1:
word1_index = index
elif word == word2:
word2_index = index
#distance = abs(hash_table[word1][0] - hash_table[word2][0])
distance = float('inf')
for i in hash_table[word1]:
for j in hash_table[word2]:
distance = min(distance, abs(i-j))
return hash_table, distance
#print(shortest_word_distance(["practice", "makes", "perfect", "coding", "makes"], "coding", "practice"))
print(shortest_word_distance(["this","is","a","long","sentence","is","fun","day","today","sunny","weather","is","a","day","tuesday","this","sentence","run","running","rainy"],
"this","rainy")) | [
"phanthai@arcafa.fi"
] | phanthai@arcafa.fi |
7a84c6b567423ac36f6b2843982d3f216b0944a7 | 76fd86ecf83fe8e752c1497ae49ea18596a88d7d | /readTag.py | 79f145b5d4c98ed7f2838464ae34c59632b9f278 | [] | no_license | gtron/ruuvitag_monitor | 9f471d21740b1d93d8631ed1f5b0e624efb4ebe6 | 1c5d89d8884ec83c52df48b971c65148458a1284 | refs/heads/master | 2022-10-12T09:18:06.779557 | 2020-06-08T16:58:43 | 2020-06-08T16:58:43 | 270,732,629 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 376 | py | #!/usr/bin/python3
import json
import sys
import errno
import datetime
from time import sleep
from ruuvitag_sensor.ruuvi import RuuviTagSensor
mac = sys.argv[1]
macs = [ mac ]
sleepTime = 2.5
datas = RuuviTagSensor.get_data_for_sensors(macs, sleepTime)
#print(str(datas))
# convert json to string
dump = json.dumps(datas)
data = json.loads(dump)
#
print(str(data[mac]))
| [
"noreply@github.com"
] | gtron.noreply@github.com |
74305ab38ac0340b375cb8afb1b90ea07fd23e36 | bf24b73282ae80b7ff813f2d794bdace9421b017 | /carapace/carapace/doctype/rejection_gate_entry_items/rejection_gate_entry_items.py | b3a21751d4d81fda563dfdc4c1c7c58850e5338e | [
"MIT"
] | permissive | hrgadeha/carapace | 8d78cc8d45c1de0293204dfbd47802e1eebf87ee | 3c001422c6b05644a52f6250c55526b23cbd4320 | refs/heads/master | 2022-01-20T11:37:26.765923 | 2022-01-09T09:38:57 | 2022-01-09T09:38:57 | 163,376,460 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 266 | py | # -*- coding: utf-8 -*-
# Copyright (c) 2019, frappe and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class RejectionGateEntryitems(Document):
pass
| [
"you@example.com"
] | you@example.com |
93dcfbb6a5d5dd6c092590dc31c60eeefcd2e3cb | 0004e933142a9d6cb543d94ed90067598899d940 | /setup.py | fcb411a7c9020003daba53f701b242a3e39d7d5b | [] | no_license | iulian-moraru/xtobtc-3.9.4 | eed12a79b074d9f13e687c391b31bd7e6c98bfff | fa58892f063c12a1f194a0efb0b501c729cdd3c5 | refs/heads/master | 2023-08-16T10:59:16.230693 | 2021-10-10T08:01:54 | 2021-10-10T08:01:54 | 369,303,598 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 667 | py | from setuptools import setup, find_namespace_packages
VERSION = "1.1.22"
# Runtime dependencies. See requirements.txt for development dependencies.
DEPENDENCIES = [
'bitfinex-v2',
]
setup(
name='xtobtc',
version=VERSION,
description='Job to buy btc',
author='Iulian Moraru',
author_email='iulian.moraru@pm.me',
url='https://gitlab.com/iulian-moraru/xtobtc.git',
packages=find_namespace_packages(),
install_requires=DEPENDENCIES,
include_package_data=True,
keywords=[],
classifiers=[],
zip_safe=True,
entry_points={
"console_scripts": [
"xtobtc = xtobtc.__main__:main",
],
}
)
| [
"lianraru@gmail.com"
] | lianraru@gmail.com |
8cbc7c2bbd2aaea3b6bd0378c72ca37769c8035d | 955b968d46b4c436be55daf8aa1b8fc8fe402610 | /ch04/baidu_screenshot.py | c3aca7449f0e884890aadc2bfc8ba7f2977f6243 | [] | no_license | han-huang/python_selenium | 1c8159fd1421b1f0e87cb0df20ae4fe82450f879 | 56f9f5e5687cf533c678a1c12e1ecaa4c50a7795 | refs/heads/master | 2020-03-09T02:24:48.882279 | 2018-04-07T15:06:18 | 2018-04-07T15:06:18 | 128,535,917 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,010 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from time import sleep, ctime
from selenium import webdriver
import os
driver = webdriver.Firefox()
# driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
# http://selenium-python.readthedocs.io/api.html?highlight=get_screenshot_as_file#selenium.webdriver.remote.webdriver.WebDriver.get_screenshot_as_file
# get_screenshot_as_file(filename)
# Saves a screenshot of the current window to a PNG image file. Returns
# False if there is any IOError, else returns True. Use full paths in your filename.
# Args:
# filename: The full path you wish to save your screenshot to. This should end with a .png extension.
# Usage:
# driver.get_screenshot_as_file(‘/Screenshots/foo.png’)
save = os.getcwd() + '\\' + os.path.splitext(__file__)[0] + ".png"
try:
driver.find_element_by_id('kw_error').send_key('selenium')
driver.find_element_by_id('su').click()
except:
driver.get_screenshot_as_file(save)
# driver.quit()
| [
"vagrant@LaravelDemoSite"
] | vagrant@LaravelDemoSite |
03f135d23c36d1396919de8f94c482b6aa8c3d91 | 95e174d3085ca24255f2f22494ff984413e16f3e | /currencyBot.py | bc1c86ae593f05aba173a0da10bf55aedcd57282 | [] | no_license | lkennxyz/tgCurrencyBot | 6df7a78fee7eb68bfd320685a899014f679fcaec | 755049e1188aa74ca3f784350162f78085ea391f | refs/heads/master | 2021-01-19T23:34:03.359994 | 2017-04-21T15:54:01 | 2017-04-21T15:54:01 | 89,000,387 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,094 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import requests
import time
import re
file = open(".token.txt","r")
TG_TOKEN = file.readline().rstrip()
TG_URL = "https://api.telegram.org/bot{}/".format(TG_TOKEN)
ER_TOKEN = file.readline().rstrip()
ER_URL = "https://v3.exchangerate-api.com/pair/{}/".format(ER_TOKEN)
file.close()
def get_url(url):
response = requests.get(url)
content = response.content.decode("utf8")
return content
def get_json_from_url(url):
content = get_url(url)
js = json.loads(content)
return js
def tg_get_updates():
url = TG_URL + "getUpdates?timeout=100"
js = get_json_from_url(url)
return js
def tg_last_chat_id_and_text(updates):
num_updates = len(updates["result"])
last_update = num_updates - 1
text = updates["result"][last_update]["message"]["text"]
chat_id = updates["result"][last_update]["message"]["chat"]["id"]
return (text, chat_id)
def tg_send_message(text, chat_id):
url = TG_URL + "sendMessage?text={}&chat_id={}".format(text, chat_id)
get_url(url)
def er_get_rate(cur):
url = ER_URL + "{}/GBP".format(cur)
js = get_json_from_url(url)
rate = js["rate"]
return rate
def convert(text):
cur = ""
if u"$" in text:
cur = "USD"
elif u"€" in text:
cur = "EUR"
rate = er_get_rate(cur)
num = re.findall('\d+', text)
converted = int(num[0]) * rate
pounds = round(converted, 2)
ret = "£" + str(pounds)
return ret
def main():
last_textchat = (None, None)
STARTED = False
while True:
text, chat = tg_last_chat_id_and_text(tg_get_updates())
if (text, chat) != last_textchat:
if STARTED is False:
if text == "/start":
tg_send_message("service started", chat)
STARTED = True
elif STARTED is True:
ret = ""
if u"$" in text or u"€" in text:
ret = convert(text)
elif text == "/help":
ret = "send /$xxxx or /€xxxx to convert to £"
elif text == "/stop":
ret = "service stopped"
STARTED = False
else:
ret = "No currency"
tg_send_message(ret, chat)
last_textchat = (text, chat)
time.sleep(0.5)
if __name__ == '__main__':
main()
| [
"liam.kennedy1408@gmail.com"
] | liam.kennedy1408@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.