max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111
values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
processNodeModule.py | taxusyew/Hash | 0 | 6621351 | # coding=utf-8
import os
def renameDir(curDir):
# 获得当前目录下的所有文件、文件夹
curDirs = os.listdir(curDir)
print os.listdir(curDir)
index = 0
newDirs = []
newDir = ''
# 切换为当前文件夹
os.chdir(curDir)
# 遍历当前目录下的所有文件
for single_dir in curDirs:
... | # coding=utf-8
import os
def renameDir(curDir):
# 获得当前目录下的所有文件、文件夹
curDirs = os.listdir(curDir)
print os.listdir(curDir)
index = 0
newDirs = []
newDir = ''
# 切换为当前文件夹
os.chdir(curDir)
# 遍历当前目录下的所有文件
for single_dir in curDirs:
... | zh | 0.960839 | # coding=utf-8 # 获得当前目录下的所有文件、文件夹 # 切换为当前文件夹 # 遍历当前目录下的所有文件 # 只处理文件夹 # python list 没有 push,用 append 代替 # 递归处理子文件夹 # 如果当前 | 2.931539 | 3 |
center_tools/raspberry.py | likicese/center-tools | 0 | 6621352 | <reponame>likicese/center-tools
from django.http import HttpResponse
from django.shortcuts import render_to_response
import os
def raspberry(request):
return render_to_response("raspberry.html")
def operation(request):
request.encoding="utf-8"
message = "啥也没有"
if request.GET["op"] == "重启":
# m... | from django.http import HttpResponse
from django.shortcuts import render_to_response
import os
def raspberry(request):
return render_to_response("raspberry.html")
def operation(request):
request.encoding="utf-8"
message = "啥也没有"
if request.GET["op"] == "重启":
# message = os.system("sudo reboot"... | en | 0.086933 | # message = os.system("sudo reboot") # message = os.system("sudo shutdown now") | 2.366019 | 2 |
src/gtcl-for-python/input.py | konekato/gtcl | 3 | 6621353 | <filename>src/gtcl-for-python/input.py
import validate
import config
def dow_input():
while True:
dow = input()
if validate.is_dow(dow):
return dow
else:
print('月〜土で、 火 のように入力してください。')
def period_input():
while True:
period = input()
if validat... | <filename>src/gtcl-for-python/input.py
import validate
import config
def dow_input():
while True:
dow = input()
if validate.is_dow(dow):
return dow
else:
print('月〜土で、 火 のように入力してください。')
def period_input():
while True:
period = input()
if validat... | none | 1 | 3.387628 | 3 | |
8.py | flpcan/project_euler | 0 | 6621354 | <reponame>flpcan/project_euler<gh_stars>0
# Online Python - IDE, Editor, Compiler, Interpreter
code = """73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
6689664895... | # Online Python - IDE, Editor, Compiler, Interpreter
code = """73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62... | ru | 0.347641 | # Online Python - IDE, Editor, Compiler, Interpreter 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 622298934233... | 1.537408 | 2 |
knget/dirtycode.py | urain39/KngetPy | 4 | 6621355 | """It's works, but i think it is dirty.
See also: https://github.com/benjaminp/six/issues/142
"""
try:
''.format_map({})
except AttributeError: # Python < 3.2
import string
def format_map(format_string, mapping, _format=string.Formatter().vformat):
return _format(format_string, None, mapping)
... | """It's works, but i think it is dirty.
See also: https://github.com/benjaminp/six/issues/142
"""
try:
''.format_map({})
except AttributeError: # Python < 3.2
import string
def format_map(format_string, mapping, _format=string.Formatter().vformat):
return _format(format_string, None, mapping)
... | en | 0.778498 | It's works, but i think it is dirty. See also: https://github.com/benjaminp/six/issues/142 # Python < 3.2 #XXX works on CPython 2.6 # http://stackoverflow.com/questions/2444680/how-do-i-add-my-own-custom-attributes-to-existing-built-in-python-types-like-a/2450942#2450942 # Python 3.2+ | 2.404113 | 2 |
lib/add_relation_rbn_to_fn_lu.py | cltl/Dutch_FrameNet_Lexicon | 0 | 6621356 | """
Exploit translation relation between monosemous Dutch and English lemmas
Usage:
add_relation_rbn_to_fn_lu.py --config_path=<config_path> --input_folder=<input_folder> --use_wn_polysemy=<use_wn_polysemy> --pos=<pos> --verbose=<verbose>
Options:
--config_path=<config_path>
--input_folder=<input_folder> sh... | """
Exploit translation relation between monosemous Dutch and English lemmas
Usage:
add_relation_rbn_to_fn_lu.py --config_path=<config_path> --input_folder=<input_folder> --use_wn_polysemy=<use_wn_polysemy> --pos=<pos> --verbose=<verbose>
Options:
--config_path=<config_path>
--input_folder=<input_folder> sh... | en | 0.434173 | Exploit translation relation between monosemous Dutch and English lemmas Usage: add_relation_rbn_to_fn_lu.py --config_path=<config_path> --input_folder=<input_folder> --use_wn_polysemy=<use_wn_polysemy> --pos=<pos> --verbose=<verbose> Options: --config_path=<config_path> --input_folder=<input_folder> should... | 2.631911 | 3 |
segmentation/train.py | deltaautonomy/delta_perception | 1 | 6621357 | <reponame>deltaautonomy/delta_perception
r"""Main Training script for ICNet"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import tensorflow as tf
from google.protobuf import text_format
from builders import model_builder
from builders... | r"""Main Training script for ICNet"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import tensorflow as tf
from google.protobuf import text_format
from builders import model_builder
from builders import dataset_builder
from protos impor... | en | 0.788069 | Main Training script for ICNet # Distributed training settings # Training configuration settings # default to 5 min # might want to cut this down # Debug flag | 2.133142 | 2 |
publications/htlatex-font-converter.py | nushio3/nushio3.github.io | 0 | 6621358 | <reponame>nushio3/nushio3.github.io<filename>publications/htlatex-font-converter.py
#!/usr/bin/env python
# run this script at path:
# /usr/share/texmf/tex4ht/ht-fonts/unicode/cjk/utf8
def convert(n):
try:
fni = 'utf8song{:02x}.htf'.format(n)
fno = 'udmj{:02x}.htf'.format(n)
with(open(fni,... | #!/usr/bin/env python
# run this script at path:
# /usr/share/texmf/tex4ht/ht-fonts/unicode/cjk/utf8
def convert(n):
try:
fni = 'utf8song{:02x}.htf'.format(n)
fno = 'udmj{:02x}.htf'.format(n)
with(open(fni,'r')) as fpi:
con = fpi.read().split('\n')
con[0] = 'udmj{:... | en | 0.449595 | #!/usr/bin/env python # run this script at path: # /usr/share/texmf/tex4ht/ht-fonts/unicode/cjk/utf8 | 2.916396 | 3 |
preprocessing/prep.py | SkTim/DRS | 0 | 6621359 | # lhy
# 2017.4
import re
import json
import cPickle
def str_rep(text, rep):
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
return text
def add_relation(text, d_words):
pattern = re... | # lhy
# 2017.4
import re
import json
import cPickle
def str_rep(text, rep):
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
return text
def add_relation(text, d_words):
pattern = re... | en | 0.292964 | # lhy # 2017.4 # print(len(match)) # recs = [' '.join([d_words[movie_list[x]] for x in y]) for y in recs_list] # self.d_words_all = self.d_words.copy() # n_w = len(self.d_words) # for enti in self.d_enti: # self.d_words_all[enti] = 'entity%s' % str(n_w) # n_w += 1 # return '' # print(len(line)) # relation =... | 3.071045 | 3 |
tests/unit/models/ar.py | RaenonX/Jelly-Bot-API | 5 | 6621360 | from typing import Tuple, Dict, Any, Type, List
from datetime import datetime
from bson import ObjectId
from django.utils import timezone
from extutils.color import ColorFactory
from flags import AutoReplyContentType, ModelValidityCheckResult
from models import (
Model, AutoReplyModuleModel, AutoReplyContentModel... | from typing import Tuple, Dict, Any, Type, List
from datetime import datetime
from bson import ObjectId
from django.utils import timezone
from extutils.color import ColorFactory
from flags import AutoReplyContentType, ModelValidityCheckResult
from models import (
Model, AutoReplyModuleModel, AutoReplyContentModel... | en | 0.722807 | # Some exception may happen when setting the value, this is the expected behavior # If the content can be set, it should invalidate the model Only testing if the content can be outputted without exception. | 2.125171 | 2 |
ruledxml/tests/test_order.py | meisterluk/ruledxml | 0 | 6621361 | <reponame>meisterluk/ruledxml<filename>ruledxml/tests/test_order.py
#!/usr/bin/env python3
import io
import unittest
import ruledxml
from . import utils
class TestRuledXmlOrder(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src:
... | #!/usr/bin/env python3
import io
import unittest
import ruledxml
from . import utils
class TestRuledXmlOrder(unittest.TestCase):
def test_030(self):
result = io.BytesIO()
with open(utils.data('030_source.xml')) as src:
ruledxml.run(src, utils.data('030_rules.py'), result)
wi... | fr | 0.221828 | #!/usr/bin/env python3 | 2.376512 | 2 |
main.py | jh-jeong/selective-convolution | 23 | 6621362 | <reponame>jh-jeong/selective-convolution<filename>main.py
from __future__ import division
import sys
import json
import os
import time
import math
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim
import models
from datasets import get_dataset
from utils import Logger
from ut... | from __future__ import division
import sys
import json
import os
import time
import math
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim
import models
from datasets import get_dataset
from utils import Logger
from utils import AverageMeter
from utils import save_checkpoint
... | en | 0.626182 | Computes the precision@k for the specified values of k # Switch to train mode # Compute gradient and do SGD step # Measure elapsed time # Measure accuracy and record loss # Switch to eval mode # Measure elapsed time # Measure accuracy and record loss # Configure parameters to optimize # Define loss function (criterion)... | 2.351619 | 2 |
commands/help.py | GAM-2-5-2021/GAMbot | 0 | 6621363 | <filename>commands/help.py
import os
import sys
import discord
from discord.ext import commands
class Help(commands.Cog, name="help"):
def __init__(self, bot):
self.bot = bot
@commands.command(name="help")
async def help(self, context):
"""
Ispisuje sve komande bota.
"""
prefix = '#'
if not isinstance(... | <filename>commands/help.py
import os
import sys
import discord
from discord.ext import commands
class Help(commands.Cog, name="help"):
def __init__(self, bot):
self.bot = bot
@commands.command(name="help")
async def help(self, context):
"""
Ispisuje sve komande bota.
"""
prefix = '#'
if not isinstance(... | sr | 0.205251 | Ispisuje sve komande bota. # Default discord.py help komanda | 2.689829 | 3 |
the_ends/EquationCollection.py | Kevincavender/The-Ends | 1 | 6621364 | from the_ends.EquationErrorCheck import EquationErrorCheck
import re
class EquationCollection:
"""
This Class is for interacting with metadata of the equations entered as a string
Example of equations and variables dictionaries
block_number : used for the solution order of the equations
error: u... | from the_ends.EquationErrorCheck import EquationErrorCheck
import re
class EquationCollection:
"""
This Class is for interacting with metadata of the equations entered as a string
Example of equations and variables dictionaries
block_number : used for the solution order of the equations
error: u... | en | 0.704283 | This Class is for interacting with metadata of the equations entered as a string Example of equations and variables dictionaries block_number : used for the solution order of the equations error: used for giving specific error results to the user variables and equations are cross listed to allow for s... | 3.975167 | 4 |
python_image_object_detection/scratch_research.py | shanedevane/python-image-object-detection | 1 | 6621365 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as plt
import timeit
"""
- parse an image and extract as much object data as possible
- ie. instead of calling out to a API?
- how many edges? (high edges = high detail, city or crowd scene?)
- taken during day or night
- ho... | # -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as plt
import timeit
"""
- parse an image and extract as much object data as possible
- ie. instead of calling out to a API?
- how many edges? (high edges = high detail, city or crowd scene?)
- taken during day or night
- how much pixesl i... | en | 0.563212 | # -*- coding: utf-8 -*- - parse an image and extract as much object data as possible - ie. instead of calling out to a API? - how many edges? (high edges = high detail, city or crowd scene?) - taken during day or night - how much pixesl in foreground vs background - color mean # img = cv2.imread(IMAGE_RESOURCE, cv2.IMR... | 2.998214 | 3 |
dotaenv/dota_runner.py | niksaz/dota2-replay-recorder | 0 | 6621366 | <reponame>niksaz/dota2-replay-recorder
import time
import subprocess
import pyautogui as gui
def make_sure_dota_is_launched():
if _is_dota_launched():
# _bring_into_focus()
return
# bring up spotlight search
gui.hotkey('command', 'space')
time.sleep(1)
# search for steam (assumin... | import time
import subprocess
import pyautogui as gui
def make_sure_dota_is_launched():
if _is_dota_launched():
# _bring_into_focus()
return
# bring up spotlight search
gui.hotkey('command', 'space')
time.sleep(1)
# search for steam (assuming it is already launched)
gui.typew... | en | 0.841723 | # _bring_into_focus() # bring up spotlight search # search for steam (assuming it is already launched) # search for Dota 2 in the library # press play # start # create lobby # start game # Press keys to speed up Dota 2 launching # bring up the menu # disconnect # confirm it # exit # confirm it and wait for complete clo... | 2.621089 | 3 |
mysite/core/admin.py | pybites/myreadinglist | 1 | 6621367 | <filename>mysite/core/admin.py
from django.contrib import admin
from .models import Book, Search, Like, Status
admin.site.register(Book)
admin.site.register(Search)
admin.site.register(Like)
admin.site.register(Status)
| <filename>mysite/core/admin.py
from django.contrib import admin
from .models import Book, Search, Like, Status
admin.site.register(Book)
admin.site.register(Search)
admin.site.register(Like)
admin.site.register(Status)
| none | 1 | 1.436373 | 1 | |
scripts/quest/q25500e.py | G00dBye/YYMS | 54 | 6621368 | <filename>scripts/quest/q25500e.py<gh_stars>10-100
# Created by MechAviv
# Quest ID :: 25500
# Eclipse and Sunfire
sm.setSpeakerID(1032209)
LIGHT = sm.getQuestEx(25502, "light")
DARK = sm.getQuestEx(25502, "dark")
sm.sendSayOkay("I guess you're not quite ready to fully control Light and Darkness. Why don't you practic... | <filename>scripts/quest/q25500e.py<gh_stars>10-100
# Created by MechAviv
# Quest ID :: 25500
# Eclipse and Sunfire
sm.setSpeakerID(1032209)
LIGHT = sm.getQuestEx(25502, "light")
DARK = sm.getQuestEx(25502, "dark")
sm.sendSayOkay("I guess you're not quite ready to fully control Light and Darkness. Why don't you practic... | en | 0.535596 | # Created by MechAviv # Quest ID :: 25500 # Eclipse and Sunfire #b" + str(LIGHT) + " times#k and Eclipse #b" + str(DARK) + " times#k.") | 1.553737 | 2 |
Bmw_cars/Bmw.py | kchaitugit96/Projects | 0 | 6621369 | <filename>Bmw_cars/Bmw.py
class Bmw:
def __init__(self):
self.models=['i8','x2','x6']
def models_bmw(self):
print("models are :")
for models in self.models:
print(models)
beamer=Bmw()
beamer.models_bmw()
| <filename>Bmw_cars/Bmw.py
class Bmw:
def __init__(self):
self.models=['i8','x2','x6']
def models_bmw(self):
print("models are :")
for models in self.models:
print(models)
beamer=Bmw()
beamer.models_bmw()
| none | 1 | 2.677627 | 3 | |
perfect_fit_prospectus/views.py | froddd/great-international-ui | 1 | 6621370 | import boto3
from botocore.exceptions import ClientError
from django.http import HttpResponseRedirect, Http404
from django.conf import settings
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import FormView, TemplateView
from django.views.generic.base import View
from django.ur... | import boto3
from botocore.exceptions import ClientError
from django.http import HttpResponseRedirect, Http404
from django.conf import settings
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import FormView, TemplateView
from django.views.generic.base import View
from django.ur... | none | 1 | 1.797042 | 2 | |
Codewars/8kyu/all-star-code-challenge-number-18/Python/solution1.py | RevansChen/online-judge | 7 | 6621371 | # Python - 3.6.0
str_count = lambda string, letter: string.count(letter)
| # Python - 3.6.0
str_count = lambda string, letter: string.count(letter)
| fi | 0.099875 | # Python - 3.6.0 | 2.701595 | 3 |
analytic_functions.py | jlmonge/FlaskDatabaseQuery | 0 | 6621372 | <reponame>jlmonge/FlaskDatabaseQuery
#this file will contain all the functions that we use to create the data that we will pass to the graphs
from datetime import date
from decimal import Decimal, DecimalException
# ----- check_float() -----
# Helper function for analytics, used for input validation.
# Passes in the ... | #this file will contain all the functions that we use to create the data that we will pass to the graphs
from datetime import date
from decimal import Decimal, DecimalException
# ----- check_float() -----
# Helper function for analytics, used for input validation.
# Passes in the value to be tested.
# Makes no extern... | en | 0.751442 | #this file will contain all the functions that we use to create the data that we will pass to the graphs # ----- check_float() ----- # Helper function for analytics, used for input validation. # Passes in the value to be tested. # Makes no external function calls. # Checks the value can be expressed as a floating point... | 3.342618 | 3 |
todoserver.py | jadelonghans/todoServer | 0 | 6621373 | <filename>todoserver.py
#!/anaconda3/bin/python
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
import json
import re
# datetimestamp according to RFC3339, 2019-06-11
"""
Tested at https://www.regextester.com/96683
9999-12-09T16:39:57-08:00
1937-01-01T12:00:27.87+00:20
199... | <filename>todoserver.py
#!/anaconda3/bin/python
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse
import json
import re
# datetimestamp according to RFC3339, 2019-06-11
"""
Tested at https://www.regextester.com/96683
9999-12-09T16:39:57-08:00
1937-01-01T12:00:27.87+00:20
199... | en | 0.586843 | #!/anaconda3/bin/python # datetimestamp according to RFC3339, 2019-06-11 Tested at https://www.regextester.com/96683 9999-12-09T16:39:57-08:00 1937-01-01T12:00:27.87+00:20 1990-12-31T23:59:60Z 1985-04-12T23:20:50.52Z 1996-12-09T16:39:57-08:00 1996-12-09T16:39:57+08:00 # print (self.path, path_elements) # get all regist... | 2.743539 | 3 |
src/frames/add_unit_frame.py | GolovPavel/ValueConverter | 1 | 6621374 | <gh_stars>1-10
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showerror
import util
from constants.frames import MAIN_FRAME_NAME
from model.unit import Unit
class AddUnitFrame(tk.Frame):
def __init__(self, root, controller):
tk.Frame.__init__(self, root)
self.control... | import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showerror
import util
from constants.frames import MAIN_FRAME_NAME
from model.unit import Unit
class AddUnitFrame(tk.Frame):
def __init__(self, root, controller):
tk.Frame.__init__(self, root)
self.controller = controlle... | none | 1 | 2.743537 | 3 | |
rpa/__init__.py | hiroki0525/sokupad-rpa-api | 0 | 6621375 | from abc import ABC, abstractmethod
from entity.state import RpaState
from infra.sokupad_client import SokupadClient
class AbstractRpa(ABC):
def __init__(self, state: RpaState):
self._client = SokupadClient()
self._state = state
def run(self):
try:
self.start()
... | from abc import ABC, abstractmethod
from entity.state import RpaState
from infra.sokupad_client import SokupadClient
class AbstractRpa(ABC):
def __init__(self, state: RpaState):
self._client = SokupadClient()
self._state = state
def run(self):
try:
self.start()
... | none | 1 | 2.826391 | 3 | |
scripts/stacked_autoencoder.py | sylvan5/deep-learning-theano | 0 | 6621376 | <reponame>sylvan5/deep-learning-theano
#coding: utf-8
import os
import timeit
import numpy as np
import theano
import theano.tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
from logistic_sgd import LogisticRegression, load_data
from mlp import HiddenLayer
from denoising_autoencoder import De... | #coding: utf-8
import os
import timeit
import numpy as np
import theano
import theano.tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
from logistic_sgd import LogisticRegression, load_data
from mlp import HiddenLayer
from denoising_autoencoder import DenoisingAutoencoder
class StackedDenois... | ja | 0.998239 | #coding: utf-8 # 隠れ層オブジェクトのリスト # 自己符号化器のリスト # パラメータのリスト # 隠れ層の数 # 学習データのミニバッチ(入力データと正解ラベル)を表すシンボル # これまでの実装と違って複数のメソッド内で使うので属性にしている # ネットワークを構築 # 隠れ層の数だけループして積み上げていく # ユニット数 # 隠れ層への入力データ # 多層パーセプトロンの隠れ層 # fine-tuningで重みを更新するため # 自己符号化器だが重みは多層パーセプトロンの隠れ層と共有 # そのため自己符号化器のparamsはない # 自己符号化器で重みとバイアスの初期値を求めたあとfine-tuningでその... | 2.187195 | 2 |
rcbi/rcbi/spiders/InfiniteFPV.py | tannewt/rcbuild.info-scrape | 2 | 6621377 | import scrapy
from scrapy import log
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from rcbi.items import Part
STOCK_STATE_MAP = {"available-on-backorder": "backordered",
"in-stock": "in_stock",
"out-of-stock": "out_of_stock"}
class I... | import scrapy
from scrapy import log
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from rcbi.items import Part
STOCK_STATE_MAP = {"available-on-backorder": "backordered",
"in-stock": "in_stock",
"out-of-stock": "out_of_stock"}
class I... | none | 1 | 2.622585 | 3 | |
fdk_client/platform/models/WebhookValidator.py | kavish-d/fdk-client-python | 0 | 6621378 | """Class Validators."""
from marshmallow import fields, Schema
from marshmallow.validate import OneOf
from ..enums import *
from ..models.BaseSchema import BaseSchema
class WebhookValidator:
class getSubscribersByCompany(BaseSchema):
page_no = fields.Int(required=False)
page... | """Class Validators."""
from marshmallow import fields, Schema
from marshmallow.validate import OneOf
from ..enums import *
from ..models.BaseSchema import BaseSchema
class WebhookValidator:
class getSubscribersByCompany(BaseSchema):
page_no = fields.Int(required=False)
page... | en | 0.802057 | Class Validators. | 2.255635 | 2 |
flow_models/tests/fit.py | piotrjurkiewicz/flow_stats | 9 | 6621379 | <reponame>piotrjurkiewicz/flow_stats
#!/usr/bin/python3
import argparse
import numpy as np
import scipy.stats
from ..fit import fit_mix
from ..lib.mix import to_json
from ..lib.util import logmsg, measure_memory
def test(max_iter):
logmsg("genpareto lognorm")
a = scipy.stats.genpareto.rvs(1.450289555235508... | #!/usr/bin/python3
import argparse
import numpy as np
import scipy.stats
from ..fit import fit_mix
from ..lib.mix import to_json
from ..lib.util import logmsg, measure_memory
def test(max_iter):
logmsg("genpareto lognorm")
a = scipy.stats.genpareto.rvs(1.450289555235508, 16, 23.204632883768134, 500000)
... | fr | 0.386793 | #!/usr/bin/python3 | 2.157041 | 2 |
example/tests/basket/test_basket_models.py | icvntechstudio/django-salesman | 222 | 6621380 | <reponame>icvntechstudio/django-salesman
import pytest
from django.db import transaction
from django.db.models.deletion import ProtectedError
from salesman.basket.models import BASKET_ID_SESSION_KEY, Basket, BasketItem
from shop.models import Phone, PhoneVariant, Product
@pytest.mark.django_db
def test_get_or_create... | import pytest
from django.db import transaction
from django.db.models.deletion import ProtectedError
from salesman.basket.models import BASKET_ID_SESSION_KEY, Basket, BasketItem
from shop.models import Phone, PhoneVariant, Product
@pytest.mark.django_db
def test_get_or_create_basket_from_request(rf, django_user_mode... | en | 0.762984 | # test session basket created # test user basket created # session basket is merged and deleted # test multiple baskets merge, 1 should be left # 10% discount modifier is already active # test add to basket # test remove from basket # trigger storing `_cached_items`. # fail silently no item remove # test basket clear #... | 2.269507 | 2 |
exercise806.py | vchatchai/python101 | 0 | 6621381 | <filename>exercise806.py<gh_stars>0
def a(n):
even = n % 2
if n == 1 :
return 1
elif n == 2:
return 2
else :
if even == 0 and n > 0:
return a(n/2) + (a(n/2)%10)
elif even == 1 and n > 0:
return a(int((n-1)/2)-1)*((n-1)/2)
print(a(5)) | <filename>exercise806.py<gh_stars>0
def a(n):
even = n % 2
if n == 1 :
return 1
elif n == 2:
return 2
else :
if even == 0 and n > 0:
return a(n/2) + (a(n/2)%10)
elif even == 1 and n > 0:
return a(int((n-1)/2)-1)*((n-1)/2)
print(a(5)) | none | 1 | 3.557302 | 4 | |
model/bottleneck_layer.py | deep-spin/explainable-qe-shared-task | 5 | 6621382 | from functools import partial
import torch
from entmax import entmax15, sparsemax, entmax_bisect
from model.utils import masked_average
class BottleneckSummary(torch.nn.Module):
def __init__(
self,
hidden_size,
aggregation='none',
kv_rep='embeddings',
alpha=1.0,
c... | from functools import partial
import torch
from entmax import entmax15, sparsemax, entmax_bisect
from model.utils import masked_average
class BottleneckSummary(torch.nn.Module):
def __init__(
self,
hidden_size,
aggregation='none',
kv_rep='embeddings',
alpha=1.0,
c... | en | 0.762112 | # for p in self.parameters(): # if p.dim() > 1: # torch.nn.init.xavier_uniform_(p) Produce an estimation by adding a bottleneck computation on top of hidden states from selected layers. Args: hidden_states: selected hidden states with shape of (bs, ts, hdim) embeddings: outp... | 2.121845 | 2 |
classification_models/keras_applications/__init__.py | lewlin/classification_models | 6 | 6621383 | <reponame>lewlin/classification_models
import keras
from .keras_applications.keras_applications import *
set_keras_submodules(
backend=keras.backend,
layers=keras.layers,
models=keras.models,
engine=keras.engine,
utils=keras.utils,
)
| import keras
from .keras_applications.keras_applications import *
set_keras_submodules(
backend=keras.backend,
layers=keras.layers,
models=keras.models,
engine=keras.engine,
utils=keras.utils,
) | none | 1 | 1.240423 | 1 | |
ACME/utility/circshift.py | mauriziokovacic/ACME | 3 | 6621384 | <filename>ACME/utility/circshift.py
import numpy
import torch
from .isnumpy import *
from .istorch import *
def circshift(tensor, k, dim=None):
"""
Circularly shifts the input tensor k times along the given dimension
Parameters
----------
tensor : Tensor
the input tensor
k : int
... | <filename>ACME/utility/circshift.py
import numpy
import torch
from .isnumpy import *
from .istorch import *
def circshift(tensor, k, dim=None):
"""
Circularly shifts the input tensor k times along the given dimension
Parameters
----------
tensor : Tensor
the input tensor
k : int
... | en | 0.615704 | Circularly shifts the input tensor k times along the given dimension Parameters ---------- tensor : Tensor the input tensor k : int the number of shifts to perform dim : int (optional) the dimension along the shift is performed (default is None) Returns ------- ... | 3.323942 | 3 |
config/utils/cache.py | CaladBlogBaal/Victorique | 0 | 6621385 | <reponame>CaladBlogBaal/Victorique
import asyncio
import enum
from functools import wraps
from lru import LRU
# pretty much taken from https://gist.github.com/dlebech/c16a34f735c0c4e9b604
class Strategy(enum.Enum):
lru = 1
raw = 2
def _wrap_coroutine_storage(cache_dict, key, future):
async def wrap... | import asyncio
import enum
from functools import wraps
from lru import LRU
# pretty much taken from https://gist.github.com/dlebech/c16a34f735c0c4e9b604
class Strategy(enum.Enum):
lru = 1
raw = 2
def _wrap_coroutine_storage(cache_dict, key, future):
async def wrapper():
val = await future
... | en | 0.588404 | # pretty much taken from https://gist.github.com/dlebech/c16a34f735c0c4e9b604 #{f.__name__}#{repr((args, kwargs))}" | 2.62684 | 3 |
__init__.py | muriloventuroso/skill-self-esteem | 0 | 6621386 | from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill, intent_handler
class SelfEsteemSkill(MycroftSkill):
def __init__(self):
super(SelfEsteemSkill, self).__init__(name="SelfEsteemSkill")
@intent_handler(IntentBuilder("BeautifulIntent").require("Beautiful").optional("p... | from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill, intent_handler
class SelfEsteemSkill(MycroftSkill):
def __init__(self):
super(SelfEsteemSkill, self).__init__(name="SelfEsteemSkill")
@intent_handler(IntentBuilder("BeautifulIntent").require("Beautiful").optional("p... | none | 1 | 2.511087 | 3 | |
142-Linked-List-Cycle-II/solution02.py | Eroica-cpp/LeetCode | 7 | 6621387 | #!/usr/bin/python
# ==============================================================================
# Author: <NAME> (<EMAIL>)
# Date: Jun 19, 2015
# Question: 142-Linked-List-Cycle-II
# Link: https://leetcode.com/problems/linked-list-cycle-ii/
# ================================================================... | #!/usr/bin/python
# ==============================================================================
# Author: <NAME> (<EMAIL>)
# Date: Jun 19, 2015
# Question: 142-Linked-List-Cycle-II
# Link: https://leetcode.com/problems/linked-list-cycle-ii/
# ================================================================... | en | 0.578615 | #!/usr/bin/python # ============================================================================== # Author: <NAME> (<EMAIL>) # Date: Jun 19, 2015 # Question: 142-Linked-List-Cycle-II # Link: https://leetcode.com/problems/linked-list-cycle-ii/ # ================================================================... | 3.907689 | 4 |
tests/plugins/test_vrtbe.py | hymer-up/streamlink | 5 | 6621388 | import unittest
from streamlink.plugins.vrtbe import VRTbe
class TestPluginVRTbe(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
# LIVE
"https://www.vrt.be/vrtnu/kanalen/canvas/",
"https://www.vrt.be/vrtnu/kanalen/een/",
"https://www.vrt... | import unittest
from streamlink.plugins.vrtbe import VRTbe
class TestPluginVRTbe(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
# LIVE
"https://www.vrt.be/vrtnu/kanalen/canvas/",
"https://www.vrt.be/vrtnu/kanalen/een/",
"https://www.vrt... | ja | 0.32285 | # LIVE # VOD | 2.619053 | 3 |
src/subcommands/listers/list_projects.py | kevin3/cwl-ica | 8 | 6621389 | <gh_stars>1-10
#!/usr/bin/env python3
"""
List all projects registered in <CWL_ICA_REPO_PATH>/config/projects.yaml
"""
from classes.command import Command
from utils.logging import get_logger
import pandas as pd
from utils.repo import get_tenant_yaml_path, read_yaml, get_project_yaml_path
import os
import sys
from ut... | #!/usr/bin/env python3
"""
List all projects registered in <CWL_ICA_REPO_PATH>/config/projects.yaml
"""
from classes.command import Command
from utils.logging import get_logger
import pandas as pd
from utils.repo import get_tenant_yaml_path, read_yaml, get_project_yaml_path
import os
import sys
from utils.errors impo... | en | 0.595095 | #!/usr/bin/env python3 List all projects registered in <CWL_ICA_REPO_PATH>/config/projects.yaml Usage: cwl-ica [options] list-projects help cwl-ica [options] list-projects [--tenant-name=<"tenant_name">] Description: List all available projects, if --tenant-name is not set then tenants from all projects ar... | 2.613485 | 3 |
auth/users/views.py | Shamsherocode/docker-django-nginx-gunicorn | 0 | 6621390 | <reponame>Shamsherocode/docker-django-nginx-gunicorn
from encodings import utf_8
from urllib import response
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import UserSerializer
from users.m... | from encodings import utf_8
from urllib import response
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import UserSerializer
from users.models import User
from rest_framework.exceptions impo... | en | 0.968116 | # Create your views here. | 2.176442 | 2 |
game/abstract.py | Adeon18/Chess.ucu | 0 | 6621391 | '''
a module representing BoardADT and abstract pieces for bot
'''
from pprint import pprint
from copy import deepcopy
from settings import LETTERS
letters = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7}
letters2 = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h'}
old_boards = []
def... | '''
a module representing BoardADT and abstract pieces for bot
'''
from pprint import pprint
from copy import deepcopy
from settings import LETTERS
letters = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7}
letters2 = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h'}
old_boards = []
def... | en | 0.869091 | a module representing BoardADT and abstract pieces for bot convert position in chess notation to standart list indexes convert standart list indexes to the chess notation board data type which contains all the information about the chess game initialise an empty board # print("here") # print(piece.pos, piece.color) # p... | 3.800457 | 4 |
useless_data.py | pan93412/tgggbot | 3 | 6621392 | '''
這裡放置一些已經廢棄的程式碼,如果您有需要您可以
從這個 useless_data 倉庫取走可能對你而言有用的程
式碼。
您可以標註借用此處代碼,或者不標註。但若您標註了
,我將因此而開心。
當你決定開始取用此處的程式碼時,本資料庫不擔保程式
碼皆可使用,使用前請測試,而非盲目直接套用(除非你
只是打算用來增加程式碼行數,而不是實際拿來使用)。
'''
# 預計移除
"""
def answerInlineQuery(self, getUpdates, results):
'''
如果不是 Inline 訊息,回傳 False。
若是,回傳 True 並發送 re... | '''
這裡放置一些已經廢棄的程式碼,如果您有需要您可以
從這個 useless_data 倉庫取走可能對你而言有用的程
式碼。
您可以標註借用此處代碼,或者不標註。但若您標註了
,我將因此而開心。
當你決定開始取用此處的程式碼時,本資料庫不擔保程式
碼皆可使用,使用前請測試,而非盲目直接套用(除非你
只是打算用來增加程式碼行數,而不是實際拿來使用)。
'''
# 預計移除
"""
def answerInlineQuery(self, getUpdates, results):
'''
如果不是 Inline 訊息,回傳 False。
若是,回傳 True 並發送 re... | zh | 0.791775 | 這裡放置一些已經廢棄的程式碼,如果您有需要您可以 從這個 useless_data 倉庫取走可能對你而言有用的程 式碼。 您可以標註借用此處代碼,或者不標註。但若您標註了 ,我將因此而開心。 當你決定開始取用此處的程式碼時,本資料庫不擔保程式 碼皆可使用,使用前請測試,而非盲目直接套用(除非你 只是打算用來增加程式碼行數,而不是實際拿來使用)。 # 預計移除 def answerInlineQuery(self, getUpdates, results): ''' 如果不是 Inline 訊息,回傳 False。 若是,回傳 True 並發送 results 陣列。 ... | 2.944703 | 3 |
server/api/preprocessing/file_preprocessor.py | JBris/dolphin_segmentation | 1 | 6621393 | import os
import shutil
import tarfile
import zipfile
from decouple import config
from pathlib import Path
from api.services.file_select import FileType
from api.services.validation.file import check_valid_image
#zip | tar | dir | images
def _add_preprocessing_metadata(data, files):
return {
"name": dat... | import os
import shutil
import tarfile
import zipfile
from decouple import config
from pathlib import Path
from api.services.file_select import FileType
from api.services.validation.file import check_valid_image
#zip | tar | dir | images
def _add_preprocessing_metadata(data, files):
return {
"name": dat... | ky | 0.130193 | #zip | tar | dir | images # while not os.path.isdir(out_dir): out_dir = Path(out_dir).stem | 2.573249 | 3 |
bites/analyse/analyse_utils.py | sschrod/BITES | 3 | 6621394 | <reponame>sschrod/BITES<filename>bites/analyse/analyse_utils.py
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
from bites.model.BITES_base import BITES
from bites.model.CFRNet_base import CFRNet
from bites.model.DeepSurv_base import DeepSurv
from bit... | import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
from bites.model.BITES_base import BITES
from bites.model.CFRNet_base import CFRNet
from bites.model.DeepSurv_base import DeepSurv
from bites.utils.eval_surv import EvalSurv
from lifelines import KaplanM... | en | 0.573885 | Find factual and counterfactual prediction: Value at 50% survival probability Find factual and counterfactual prediction: Value at 50% survival probability Find factual and counterfactual prediction: Value at 50% survival probability #plt.figure(figsize=(8, 2.7)) #kmf.plot(c=colors[0]) #kmf_cf.plot(c=colors[1]) # Calcu... | 1.925095 | 2 |
amin_function.py | Infernolia/Computational_Statistics | 0 | 6621395 | import numpy as np
a = np.array(
[
[50,10,30],
[60,5,40],
[70,80,90]
]
)
# return minimum element from all the dimension
print(np.amin(a))
#minimum from each column (axis=0 means column-wise operation)
print(np.amin... | import numpy as np
a = np.array(
[
[50,10,30],
[60,5,40],
[70,80,90]
]
)
# return minimum element from all the dimension
print(np.amin(a))
#minimum from each column (axis=0 means column-wise operation)
print(np.amin... | en | 0.850133 | # return minimum element from all the dimension #minimum from each column (axis=0 means column-wise operation) #minimum from each row (axis=1 means row-wise operation) | 4.194852 | 4 |
mjdir/commands/turbomole.py | aimat-lab/jobdir_queue_submit | 0 | 6621396 | <filename>mjdir/commands/turbomole.py
import os
# import ase
# Example Commands
TURBOMOLE_SLURM_HEADERS = {"int-nano": ''.join(['module purge\n',
# 'export PARA_ARCH=SMP\n',
'export PARNODES=$SLURM_NPROCS\n',
... | <filename>mjdir/commands/turbomole.py
import os
# import ase
# Example Commands
TURBOMOLE_SLURM_HEADERS = {"int-nano": ''.join(['module purge\n',
# 'export PARA_ARCH=SMP\n',
'export PARNODES=$SLURM_NPROCS\n',
... | en | 0.337835 | # import ase # Example Commands # 'export PARA_ARCH=SMP\n', # 'export TURBODIR=/shared/software/chem/TURBOMOLE/TURBOMOLE-V7.4.1\n', # 'export PATH=$TURBODIR/scripts:$PATH\n', # 'export PATH=$TURBODIR/bin/`sysname`:$PATH\n', # 'export OMP_NUM_THREADS=$SLURM_NPROCS\n' # 'export PARA_ARCH=SMP\n', # 'export TURBODIR=/share... | 1.702964 | 2 |
students/forms.py | estudeplus/perfil | 0 | 6621397 | <gh_stars>0
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Student
fields = ['name', 'student_id', 'email', 'password'] | from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Student
fields = ['name', 'student_id', 'email', 'password'] | none | 1 | 2.3682 | 2 | |
pirates/quest/QuestIndicatorNodeItem.py | itsyaboyrocket/pirates | 3 | 6621398 | # uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.quest.QuestIndicatorNodeItem
from pirates.quest.QuestIndicatorNode import QuestIndicatorNode
class QuestIndicatorNodeItem(Quest... | # uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.quest.QuestIndicatorNodeItem
from pirates.quest.QuestIndicatorNode import QuestIndicatorNode
class QuestIndicatorNodeItem(Quest... | en | 0.524772 | # uncompyle6 version 3.2.0 # Python bytecode 2.4 (62061) # Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] # Embedded file name: pirates.quest.QuestIndicatorNodeItem | 2.14559 | 2 |
handlers/groups.py | ghowland/deployman | 0 | 6621399 | <filename>handlers/groups.py
"""
sysync: handlers: groups
Module installing groups
"""
from utility.log import Log
from utility.error import Error
from utility.run import Run, RunOnCommit
from utility.os_compatibility import GetFileStatInfo
# Commands we will use to manage groups
COMMAND_GROUP_EXISTS = 'egrep -i "... | <filename>handlers/groups.py
"""
sysync: handlers: groups
Module installing groups
"""
from utility.log import Log
from utility.error import Error
from utility.run import Run, RunOnCommit
from utility.os_compatibility import GetFileStatInfo
# Commands we will use to manage groups
COMMAND_GROUP_EXISTS = 'egrep -i "... | en | 0.648859 | sysync: handlers: groups Module installing groups # Commands we will use to manage groups Returns the key used for the Work List/Data work_key # Returns List, always a single item for this handler # Does this group exist? # If this group doesnt exist, add it # -- Add Options -- # UID # Add the group name | 2.272938 | 2 |
problems/prob7/prob7.py | w1ldy0uth/Project-Euler | 1 | 6621400 | #!/usr/bin/env python3
# -*- coding: UTF=8 -*-
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that
the 6th prime is 13.
What is the 10 001st prime number?
"""
def isPrime(n):
if n % 2 == 0:
return n == 2
d = 3
while d * d <= n and n % d != 0:
d += 2
re... | #!/usr/bin/env python3
# -*- coding: UTF=8 -*-
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that
the 6th prime is 13.
What is the 10 001st prime number?
"""
def isPrime(n):
if n % 2 == 0:
return n == 2
d = 3
while d * d <= n and n % d != 0:
d += 2
re... | en | 0.893213 | #!/usr/bin/env python3 # -*- coding: UTF=8 -*- By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? | 4.334476 | 4 |
holiday/objoriented.py | daveshed/Euler | 0 | 6621401 | <filename>holiday/objoriented.py
import random
import sys
TOLERANCE = 0.00001
class Day:
def __init__(self, date):
self.date = date
class Holiday(Day):
holiday = True
class WorkDay(Day):
holiday = False
class Calendar:
def __init__(self, n_days):
self.n_days = n_days
se... | <filename>holiday/objoriented.py
import random
import sys
TOLERANCE = 0.00001
class Day:
def __init__(self, date):
self.date = date
class Holiday(Day):
holiday = True
class WorkDay(Day):
holiday = False
class Calendar:
def __init__(self, n_days):
self.n_days = n_days
se... | en | 0.700591 | # look out for index error # print("spawning Emperor with birthdate {}".format(birthdate)) | 3.448435 | 3 |
mysql_cluster_manager/src/mysql_cluster_manager.py | jnidzwetzki/mysql-ha | 8 | 6621402 | <filename>mysql_cluster_manager/src/mysql_cluster_manager.py<gh_stars>1-10
#!/usr/bin/env python3
"""This file is part of the MySQL cluster manager"""
import os
import sys
import logging
import argparse
from mcm.actions import Actions
from mcm.consul import Consul
from mcm.mysql import Mysql
from mcm.proxysql import... | <filename>mysql_cluster_manager/src/mysql_cluster_manager.py<gh_stars>1-10
#!/usr/bin/env python3
"""This file is part of the MySQL cluster manager"""
import os
import sys
import logging
import argparse
from mcm.actions import Actions
from mcm.consul import Consul
from mcm.mysql import Mysql
from mcm.proxysql import... | en | 0.683134 | #!/usr/bin/env python3 This file is part of the MySQL cluster manager # Parse args # Configure logging # Check for all needed env vars # Perform operations | 1.763867 | 2 |
src/roslaunch_monitor/launch_widget.py | nilsbore/roslaunch_monitor | 17 | 6621403 | #!/usr/bin/env python
# Copyright (c) 2011, <NAME>, TU Darmstadt
# 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
# not... | #!/usr/bin/env python
# Copyright (c) 2011, <NAME>, TU Darmstadt
# 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
# not... | en | 0.611497 | #!/usr/bin/env python # Copyright (c) 2011, <NAME>, TU Darmstadt # 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 # noti... | 1.152571 | 1 |
dqo/query_generator/guided.py | danield137/deep_query_optimzation | 0 | 6621404 | <gh_stars>0
import logging
import os
import time
from collections import defaultdict
from queue import Queue
from typing import Tuple, Callable, Dict, Optional
import numpy as np
from dqo import log_utils
from dqo.db.clients import DatabaseClient
from dqo.db.models import Database
from dqo.lab.query_executor import Q... | import logging
import os
import time
from collections import defaultdict
from queue import Queue
from typing import Tuple, Callable, Dict, Optional
import numpy as np
from dqo import log_utils
from dqo.db.clients import DatabaseClient
from dqo.db.models import Database
from dqo.lab.query_executor import QueryExecutor... | en | 0.839311 | # todo: add cardinality considerations :param db_client: :param target: a tuple with (min, max) values to consider a "hit" :param stop_early: if true, returns done on first occurrence of a "hit" :param max_steps: limit number of steps :param cb: ball back to allow extra work on query, ru... | 2.106559 | 2 |
fixture/session.py | technodeath/pyth | 0 | 6621405 | <filename>fixture/session.py
class SessionHelper:
def __init__(self, app):
self.app = app
def logout(self):
wd = self.app.wd
wd.find_element_by_link_text("Sign out").click()
def login(self, username, password):
wd = self.app.wd
self.app.open_home_page()
wd.... | <filename>fixture/session.py
class SessionHelper:
def __init__(self, app):
self.app = app
def logout(self):
wd = self.app.wd
wd.find_element_by_link_text("Sign out").click()
def login(self, username, password):
wd = self.app.wd
self.app.open_home_page()
wd.... | none | 1 | 2.528485 | 3 | |
index.py | Pedroh1510/Video-maker-python | 2 | 6621406 | <gh_stars>1-10
import os
from robots.userInput import user
from robots.text import robotText
# # from robots.voice import robotVoice
from robots.images import robotImages
from robots.userInputEnv import userEnv
from robots.video import robotVideo
from robots.youtube import robotYoutube
from robots.state import loadCont... | import os
from robots.userInput import user
from robots.text import robotText
# # from robots.voice import robotVoice
from robots.images import robotImages
from robots.userInputEnv import userEnv
from robots.video import robotVideo
from robots.youtube import robotYoutube
from robots.state import loadContent
import json... | en | 0.482346 | # # from robots.voice import robotVoice # robotVoice() # print(json.dumps(loadContent()['sentences'], indent=2)) # print(json.dumps(loadContent()['sentences'])) | 2.174827 | 2 |
tests/haskell/partialParallelSimpleAdd.py | David-Durst/aetherling | 10 | 6621407 | from aetherling.modules.reduce import DefineReduceSequential, DefineReduceParallelWithIdentity, renameCircuitForReduce
from aetherling.modules.register_any_type import DefineRegisterAnyType
from aetherling.modules.term_any_type import TermAnyType
from aetherling.modules.noop import DefineNoop
from magma.backend.coreir_... | from aetherling.modules.reduce import DefineReduceSequential, DefineReduceParallelWithIdentity, renameCircuitForReduce
from aetherling.modules.register_any_type import DefineRegisterAnyType
from aetherling.modules.term_any_type import TermAnyType
from aetherling.modules.noop import DefineNoop
from magma.backend.coreir_... | none | 1 | 1.545103 | 2 | |
src/service/ssm.py | neovasili/aws-codebuild | 4 | 6621408 | <gh_stars>1-10
import boto3
import logging
class SSMService:
def __init__(self, region: str, logger: logging.Logger):
self.__logger = logger
self.ssm_client = boto3.client("ssm", region_name=region)
def get_buildspec_override_feature_flag(self):
try:
response = self.ssm_c... | import boto3
import logging
class SSMService:
def __init__(self, region: str, logger: logging.Logger):
self.__logger = logger
self.ssm_client = boto3.client("ssm", region_name=region)
def get_buildspec_override_feature_flag(self):
try:
response = self.ssm_client.get_param... | none | 1 | 2.015529 | 2 | |
contrib/discodex/lib/discodex/restapi/serdes.py | kostis/disco | 1 | 6621409 | """
Serializers/Deserializers are the main tools for automatic RESTful APIs.
Users can use the builtins automagically or define their own.
"""
from django.core import serializers
class SerDes(object):
"""
Base class for a serializer/deserializer. Methods are implemented just for demonstration, should use a su... | """
Serializers/Deserializers are the main tools for automatic RESTful APIs.
Users can use the builtins automagically or define their own.
"""
from django.core import serializers
class SerDes(object):
"""
Base class for a serializer/deserializer. Methods are implemented just for demonstration, should use a su... | en | 0.838493 | Serializers/Deserializers are the main tools for automatic RESTful APIs. Users can use the builtins automagically or define their own. Base class for a serializer/deserializer. Methods are implemented just for demonstration, should use a subclass. # Convenience singletons | 2.865008 | 3 |
Debugging/01 - exceptions.py | Piraato/Learn-Python | 0 | 6621410 | <gh_stars>0
# Throwing custom exceptions
#raise Exception('Now you really broke the program!')
'''
This results in the following Traceback:
Exception: Now you really broke the program!
'''
# Inside a function
def brokenCalculator(num1, operator, num2):
if len(operator) != 1:
raise Exception('Invalid ope... | # Throwing custom exceptions
#raise Exception('Now you really broke the program!')
'''
This results in the following Traceback:
Exception: Now you really broke the program!
'''
# Inside a function
def brokenCalculator(num1, operator, num2):
if len(operator) != 1:
raise Exception('Invalid operator')
... | en | 0.833223 | # Throwing custom exceptions #raise Exception('Now you really broke the program!') This results in the following Traceback: Exception: Now you really broke the program! # Inside a function # Prints the exception for every input given in the for loop | 4.188064 | 4 |
flag_gen/to_string.py | benwernicke/crygen | 0 | 6621411 | with open("example.h", "r") as fh:
for line in fh:
line = line.strip()
print(f'"{line}\\n"')
| with open("example.h", "r") as fh:
for line in fh:
line = line.strip()
print(f'"{line}\\n"')
| none | 1 | 2.749815 | 3 | |
bootstrap_customizer/middleware.py | johnfraney/django-bootstrap-customizer | 46 | 6621412 | <gh_stars>10-100
from django.utils.deprecation import MiddlewareMixin
from bootstrap_customizer.models import BootstrapTheme
class BootstrapThemeMiddleware(MiddlewareMixin):
"""
Middleware that sets `bootstrap_theme_updated` attribute to request object.
"""
def process_request(self, request):
... | from django.utils.deprecation import MiddlewareMixin
from bootstrap_customizer.models import BootstrapTheme
class BootstrapThemeMiddleware(MiddlewareMixin):
"""
Middleware that sets `bootstrap_theme_updated` attribute to request object.
"""
def process_request(self, request):
theme = Bootstr... | en | 0.743911 | Middleware that sets `bootstrap_theme_updated` attribute to request object. | 1.952919 | 2 |
klee.py | TCatshoek/AISTRTestcaseEvaluator | 0 | 6621413 | from multiprocessing import Pool
from itertools import chain
import subprocess
import re
import os
import time
import datetime
# Use multiprocessing here since it is quite slow, and we can easily evaluate multiple testcases at the same time
def worker(args):
testcase, problem_path, mtime = args
found_errors =... | from multiprocessing import Pool
from itertools import chain
import subprocess
import re
import os
import time
import datetime
# Use multiprocessing here since it is quite slow, and we can easily evaluate multiple testcases at the same time
def worker(args):
testcase, problem_path, mtime = args
found_errors =... | en | 0.890607 | # Use multiprocessing here since it is quite slow, and we can easily evaluate multiple testcases at the same time # Figure out start timestamp | 2.801365 | 3 |
cybo/data/dataset_readers/dataset_reader.py | bo-ke/cybo | 2 | 6621414 | <gh_stars>1-10
# -*- coding: utf-8 -*-
'''
@author: kebo
@contact: <EMAIL>
@version: 1.0
@file: dataset_reader.py
@time: 2020/12/16 22:25:09
这一行开始写关于本文件的说明与解释
'''
import json
import tensorflow as tf
from collections import Iterator
from pydantic import BaseModel
from typing import List, Dict
from cybo.common.logge... | # -*- coding: utf-8 -*-
'''
@author: kebo
@contact: <EMAIL>
@version: 1.0
@file: dataset_reader.py
@time: 2020/12/16 22:25:09
这一行开始写关于本文件的说明与解释
'''
import json
import tensorflow as tf
from collections import Iterator
from pydantic import BaseModel
from typing import List, Dict
from cybo.common.logger import logger... | zh | 0.189132 | # -*- coding: utf-8 -*- @author: kebo @contact: <EMAIL> @version: 1.0 @file: dataset_reader.py @time: 2020/12/16 22:25:09 这一行开始写关于本文件的说明与解释 # return {"input_ids": tf.int32, "label": tf.int32} | 2.336034 | 2 |
ex102.py | Gustavo-Dev-Web/python | 0 | 6621415 | def fatorial(inicio,show):
from math import factorial
for c in range(inicio,0,-1):
if show:
print(f'{c}',end=' ')
if c > 1:
print('x ',end='')
else:
print('= ',end='')
print(factorial(inicio))
return factorial(inicio)
fator... | def fatorial(inicio,show):
from math import factorial
for c in range(inicio,0,-1):
if show:
print(f'{c}',end=' ')
if c > 1:
print('x ',end='')
else:
print('= ',end='')
print(factorial(inicio))
return factorial(inicio)
fator... | none | 1 | 3.812068 | 4 | |
AdvBox/attacks/gradient_method.py | csdongxian/PaddleSleeve | 0 | 6621416 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | en | 0.84651 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app... | 2.306589 | 2 |
native.py | hclivess/qtrader | 14 | 6621417 | <gh_stars>10-100
from qtrade_client.api import QtradeAPI
def load_credentials():
with open("secret") as authfile:
return authfile.read()
# String is of the format "[key_id]:[key]"
client_native = QtradeAPI("https://api.qtrade.io", key=load_credentials())
# result = client.post("/v1/user/sell_limit", am... | from qtrade_client.api import QtradeAPI
def load_credentials():
with open("secret") as authfile:
return authfile.read()
# String is of the format "[key_id]:[key]"
client_native = QtradeAPI("https://api.qtrade.io", key=load_credentials())
# result = client.post("/v1/user/sell_limit", amount="1", price="... | en | 0.646758 | # String is of the format "[key_id]:[key]" # result = client.post("/v1/user/sell_limit", amount="1", price="0.0001", market_id=12) # print(result) # Only closed orders # Print all orders before ID 25 # Print all orders after ID 25 | 2.551647 | 3 |
schema_org_web_scanner/src/d1_schema_scan/asgi.py | DataONEorg/d1_ncei_adapter | 1 | 6621418 | """
ASGI entrypoint. Configures Django and then runs the application
defined in the ASGI_APPLICATION setting.
"""
import os
import channels.routing
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "d1_schema_scan.settings_deploy")
django.setup()
application = channels.routing.get_default_application()
| """
ASGI entrypoint. Configures Django and then runs the application
defined in the ASGI_APPLICATION setting.
"""
import os
import channels.routing
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "d1_schema_scan.settings_deploy")
django.setup()
application = channels.routing.get_default_application()
| en | 0.7872 | ASGI entrypoint. Configures Django and then runs the application defined in the ASGI_APPLICATION setting. | 1.786749 | 2 |
import_osm_metadata.py | ckurze/mongodb-knowledge-graph | 0 | 6621419 | import requests
import pymongo
import re
from pprint import pprint
import json
from pyld import jsonld
# Semantic Description of OpenStreetMap: https://wiki.openstreetmap.org/wiki/OSM_Semantic_Network
# API doc for tags in Openstreetmap: https://taginfo.openstreetmap.org/taginfo/apidoc#api_4_keys_all
# Need the att... | import requests
import pymongo
import re
from pprint import pprint
import json
from pyld import jsonld
# Semantic Description of OpenStreetMap: https://wiki.openstreetmap.org/wiki/OSM_Semantic_Network
# API doc for tags in Openstreetmap: https://taginfo.openstreetmap.org/taginfo/apidoc#api_4_keys_all
# Need the att... | en | 0.437455 | # Semantic Description of OpenStreetMap: https://wiki.openstreetmap.org/wiki/OSM_Semantic_Network # API doc for tags in Openstreetmap: https://taginfo.openstreetmap.org/taginfo/apidoc#api_4_keys_all # Need the attributes of the classes (tags to use in combination): https://wiki.openstreetmap.org/wiki/Tag%3Asubstation%3... | 2.557505 | 3 |
testing/test_bytecode.py | shendel/hippyvm | 1 | 6621420 |
from hippy.objspace import getspace
from hippy.phpcompiler import compile_php
from hippy.bytecode import unserialize
from testing.test_interpreter import MockInterpreter
class TestBytecode(object):
def test_basic_serialize(self):
source = "<? $a = 3; var_dump($a);?>"
space = getspace()
bc ... |
from hippy.objspace import getspace
from hippy.phpcompiler import compile_php
from hippy.bytecode import unserialize
from testing.test_interpreter import MockInterpreter
class TestBytecode(object):
def test_basic_serialize(self):
source = "<? $a = 3; var_dump($a);?>"
space = getspace()
bc ... | en | 0.149446 | <? function f($a) { return $a + 4; } echo f(3); ?> <? class X { function __construct() { $this->x = 3; } } $x = new X(); echo $x->x; ?> | 2.322146 | 2 |
junk.py | cclauss/asyncio_hacks | 1 | 6621421 | class Channel(object):
def __init__(self, server, name, channel_id, members=None):
self.server = server
self.name = name
self.id = channel_id
self.members = members or []
def __eq__(self, compare_str):
if compare_str in (self.id, self.name) or "#" + compare_str == self.n... | class Channel(object):
def __init__(self, server, name, channel_id, members=None):
self.server = server
self.name = name
self.id = channel_id
self.members = members or []
def __eq__(self, compare_str):
if compare_str in (self.id, self.name) or "#" + compare_str == self.n... | none | 1 | 2.992568 | 3 | |
clean-registry-images.py | lowang-bh/registry | 6 | 6621422 | #!/usr/bin/env python
"""
this is a registry manipulator, can do following:
- list all images (including layers)
- delete images
- all except last N images
- all images and/or tags
#
run
registry.py -h
to get more help
#
important: after removing the tags, run the garbage collector
on your registry host:
docker-compos... | #!/usr/bin/env python
"""
this is a registry manipulator, can do following:
- list all images (including layers)
- delete images
- all except last N images
- all images and/or tags
#
run
registry.py -h
to get more help
#
important: after removing the tags, run the garbage collector
on your registry host:
docker-compos... | en | 0.647358 | #!/usr/bin/env python this is a registry manipulator, can do following: - list all images (including layers) - delete images - all except last N images - all images and/or tags # run registry.py -h to get more help # important: after removing the tags, run the garbage collector on your registry host: docker-compose -f ... | 2.453487 | 2 |
src/touri_core/scripts/touri_core/touri.py | sudo-prakhar/touri_ros-1 | 0 | 6621423 | #!/usr/bin/env python
"""
TouRI Robot Base Code
"""
__author__ = "<NAME>"
__mail__ = "<EMAIL>"
__copyright__ = "NONE"
# -----------------------------------------------------------------------------
import rospy
from stretch_body.robot import Robot
from touri_mani.msg import TeleopMani
from touri_nav.msg impor... | #!/usr/bin/env python
"""
TouRI Robot Base Code
"""
__author__ = "<NAME>"
__mail__ = "<EMAIL>"
__copyright__ = "NONE"
# -----------------------------------------------------------------------------
import rospy
from stretch_body.robot import Robot
from touri_mani.msg import TeleopMani
from touri_nav.msg impor... | en | 0.126218 | #!/usr/bin/env python TouRI Robot Base Code # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # TouRI_bot # ----------------------... | 2.34576 | 2 |
hydrocarbon_problem/env/env_test.py | lollcat/Aspen-RL | 1 | 6621424 | <gh_stars>1-10
import numpy as np
import time
from hydrocarbon_problem.api.api_base import BaseAspenDistillationAPI
from hydrocarbon_problem.env.env import AspenDistillation
def make_fake_agent(env: AspenDistillation):
def fake_agent(obs):
del(obs)
discrete_spec, continuous_spec = env.action_spec... | import numpy as np
import time
from hydrocarbon_problem.api.api_base import BaseAspenDistillationAPI
from hydrocarbon_problem.env.env import AspenDistillation
def make_fake_agent(env: AspenDistillation):
def fake_agent(obs):
del(obs)
discrete_spec, continuous_spec = env.action_spec()
disc... | en | 0.857245 | This test runs multiple environment episodes, running some simple sanity checks along the way. # api = FakeDistillationAPI() # this can be changed to AspenAPI to test with Aspen # this can be changed to AspenAPI to test with Aspen # choose not to seperate # if we don't seperate then the created states are black, 0... | 2.529789 | 3 |
app/dashboard/layout.py | salukadev/FDM-Mini-Project | 0 | 6621425 | from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
from ..Plots import alzheimer_clusterringPlot as ac
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import os
# navbar =
fig2 = ac.alzheimer_clusterPlot()
fig2.update_layout({
"plot_bgcolor": "rgba(0, 0, ... | from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
from ..Plots import alzheimer_clusterringPlot as ac
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import os
# navbar =
fig2 = ac.alzheimer_clusterPlot()
fig2.update_layout({
"plot_bgcolor": "rgba(0, 0, ... | en | 0.280307 | # navbar = #data retrieval alzheimer #data retrieval covid 19 # covidPatients = covidlength[covidlength['infectionProb'].str.contains(1)] #pie chart plot #covid plots # "coloraxis" : "red" # html.P( # "Some quick example text to build on the card title and make " # "up the bulk of the card's content.", # cl... | 2.514503 | 3 |
ormar/queryset/actions/__init__.py | dudil/ormar | 0 | 6621426 | from ormar.queryset.actions.filter_action import FilterAction
from ormar.queryset.actions.order_action import OrderAction
__all__ = ["FilterAction", "OrderAction"]
| from ormar.queryset.actions.filter_action import FilterAction
from ormar.queryset.actions.order_action import OrderAction
__all__ = ["FilterAction", "OrderAction"]
| none | 1 | 1.169389 | 1 | |
api/common/decorators.py | khashimakhun/projectNew | 5 | 6621427 | <gh_stars>1-10
import json
import logging
from django.http import HttpResponse
from api.common.exceptions import BotException
def handle_exception(method):
def method_wrapper(*args, **kwargs):
try:
return method(*args, **kwargs)
except Exception as ex:
exception_message = s... | import json
import logging
from django.http import HttpResponse
from api.common.exceptions import BotException
def handle_exception(method):
def method_wrapper(*args, **kwargs):
try:
return method(*args, **kwargs)
except Exception as ex:
exception_message = str(ex)
... | none | 1 | 2.332335 | 2 | |
tests.py | ltblueberry/directory-sorter | 0 | 6621428 | import unittest
from os import path, listdir
from directory_sorter import main as script
from directory_sorter import messages
class ScriptTest(unittest.TestCase):
def test_dir_empty(self):
exit_message = script(None)
self.assertEqual(exit_message, messages.NONE_DIR)
def test_dir_not_found(s... | import unittest
from os import path, listdir
from directory_sorter import main as script
from directory_sorter import messages
class ScriptTest(unittest.TestCase):
def test_dir_empty(self):
exit_message = script(None)
self.assertEqual(exit_message, messages.NONE_DIR)
def test_dir_not_found(s... | en | 0.864268 | # check there are no files in directory | 3.176763 | 3 |
python_boilerplate_test01/tests/test_os_utils.py | czbiohub/python_boilerplate_test01 | 0 | 6621429 | import os
import pytest
def test_sanitize_path():
from python_boilerplate_test01.os_utils import sanitize_path
test = sanitize_path('.')
true = os.path.abspath('.')
assert test == true
def test_maybe_add_slash():
from python_boilerplate_test01.os_utils import maybe_add_slash
test = maybe_... | import os
import pytest
def test_sanitize_path():
from python_boilerplate_test01.os_utils import sanitize_path
test = sanitize_path('.')
true = os.path.abspath('.')
assert test == true
def test_maybe_add_slash():
from python_boilerplate_test01.os_utils import maybe_add_slash
test = maybe_... | none | 1 | 2.383559 | 2 | |
src/python/transducer_data.py | dptam/neural_wfst | 0 | 6621430 | '''
| Filename : transducer_data.py
| Description : Functions that return the data fe to the transducer.
| Author : <NAME>
| Created : Tue Dec 8 17:50:51 2015 (-0500)
| Last-Updated: Thu Dec 31 01:08:44 2015 (-0500)
| By: <NAME>
| Update #: 22
'''
import codecs
import numpy
import string
impo... | '''
| Filename : transducer_data.py
| Description : Functions that return the data fe to the transducer.
| Author : <NAME>
| Created : Tue Dec 8 17:50:51 2015 (-0500)
| Last-Updated: Thu Dec 31 01:08:44 2015 (-0500)
| By: <NAME>
| Update #: 22
'''
import codecs
import numpy
import string
impo... | en | 0.785239 | | Filename : transducer_data.py | Description : Functions that return the data fe to the transducer. | Author : <NAME> | Created : Tue Dec 8 17:50:51 2015 (-0500) | Last-Updated: Thu Dec 31 01:08:44 2015 (-0500) | By: <NAME> | Update #: 22 Helper function The BOS_CHAR is added to the left por... | 3.130865 | 3 |
projects/nncrystal/utils/msgpack_file_loader.py | nncrystals/detectron2 | 0 | 6621431 | from typing import List
import msgpack
def load_msgpack_data(file_path):
"""
load msgpack from path and return generator returning stored frame data
"""
with open(file_path, "rb") as f:
unpacker = msgpack.Unpacker(f)
for unpacked in unpacker:
yield unpacked
def load_ima... | from typing import List
import msgpack
def load_msgpack_data(file_path):
"""
load msgpack from path and return generator returning stored frame data
"""
with open(file_path, "rb") as f:
unpacker = msgpack.Unpacker(f)
for unpacked in unpacker:
yield unpacked
def load_ima... | en | 0.412784 | load msgpack from path and return generator returning stored frame data :param file_path: :param offsets: :param index_list: optional prebuilt index :return: :param file_path: :return: offset index | 2.958694 | 3 |
django_nlf/__init__.py | hodossy/django-nlf | 0 | 6621432 | <reponame>hodossy/django-nlf
from .antlr import DjangoNLFLanguage, LanguageSyntaxError
from .types import Lookup, Operation, Expression, CompositeExpression, CustomFunction
__version__ = "0.0.1"
| from .antlr import DjangoNLFLanguage, LanguageSyntaxError
from .types import Lookup, Operation, Expression, CompositeExpression, CustomFunction
__version__ = "0.0.1" | none | 1 | 1.415344 | 1 | |
src/checkrs/market.py | timothyb0912/checkrs | 2 | 6621433 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Functions for plotting simulated vs observed market shares of each alternative.
"""
from __future__ import absolute_import
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sbn
from .plot_utils import _label_despine_save_and_show_plot
f... | # -*- coding: utf-8 -*-
"""
Functions for plotting simulated vs observed market shares of each alternative.
"""
from __future__ import absolute_import
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sbn
from .plot_utils import _label_despine_save_and_show_plot
from .utils impo... | en | 0.703528 | # -*- coding: utf-8 -*- Functions for plotting simulated vs observed market shares of each alternative. Creates dataframes needed for the market share plot. Parameters ---------- x : 1D ndarray. Should contain the values of the discrete random value for each alternative for each observation... | 3.416118 | 3 |
qcengine/programs/dftd4.py | MolSSI/dqm_compute | 105 | 6621434 | <gh_stars>100-1000
"""
Harness for the DFT-D4 dispersion correction.
This implementation interfaces with the dftd4 Python-API, which provides
native support for QCSchema.
Therefore, this harness only has to provide a thin wrapper to integrate dftd4.
"""
from typing import Dict
from qcelemental.models import AtomicIn... | """
Harness for the DFT-D4 dispersion correction.
This implementation interfaces with the dftd4 Python-API, which provides
native support for QCSchema.
Therefore, this harness only has to provide a thin wrapper to integrate dftd4.
"""
from typing import Dict
from qcelemental.models import AtomicInput, AtomicResult
f... | en | 0.700361 | Harness for the DFT-D4 dispersion correction. This implementation interfaces with the dftd4 Python-API, which provides native support for QCSchema. Therefore, this harness only has to provide a thin wrapper to integrate dftd4. Calculation harness for the DFT-D4 dispersion correction. Check for the availability of the ... | 2.120245 | 2 |
instrument.py | alkamid/lab-suite | 0 | 6621435 | <reponame>alkamid/lab-suite
import visa
rm = visa.ResourceManager()
class Instrument():
def __init__(self, address=None, identificator=None):
if address != None:
self.instr = rm.open_resource(address)
elif identificator != None:
self.find_instrument(identificator)
def ... | import visa
rm = visa.ResourceManager()
class Instrument():
def __init__(self, address=None, identificator=None):
if address != None:
self.instr = rm.open_resource(address)
elif identificator != None:
self.find_instrument(identificator)
def find_instrument(self, instr_... | none | 1 | 2.689002 | 3 | |
python code/CNCController.py | bsbrl/craniobot | 4 | 6621436 | <filename>python code/CNCController.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 19 14:41:05 2017
@author: Franklin
"""
import serial
import time
import json
from pointGen import pointGen
class CNCController():
def assignPort(self,port):
if port.lower() == 'default':
... | <filename>python code/CNCController.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 19 14:41:05 2017
@author: Franklin
"""
import serial
import time
import json
from pointGen import pointGen
class CNCController():
def assignPort(self,port):
if port.lower() == 'default':
... | en | 0.845374 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Fri May 19 14:41:05 2017 @author: Franklin #change this com port to the com port of your tinyG #self.port = '/dev/tty.usbserial-DN01XFHI' #This checks the connection state of the Serial port #If ser doesn't exist, print Open serial port. #return flag #This open... | 2.613891 | 3 |
concurrency/futures/futures_test_share_object.py | scotthuang1989/Python-3-Module-of-the-Week | 2 | 6621437 | <reponame>scotthuang1989/Python-3-Module-of-the-Week<filename>concurrency/futures/futures_test_share_object.py
"""
test if share state is possible
"""
from concurrent import futures
from multiprocessing import Manager
share_list =[]
def task(n):
print(n)
share_list.append(n)
with futures.ThreadPoolExecutor... | """
test if share state is possible
"""
from concurrent import futures
from multiprocessing import Manager
share_list =[]
def task(n):
print(n)
share_list.append(n)
with futures.ThreadPoolExecutor(max_workers=2) as ex:
print('main: starting')
ex.submit(task, 1)
ex.submit(task, 2)
ex.submit(... | en | 0.925656 | test if share state is possible # must use Manager as proxy | 3.411826 | 3 |
api/resources.py | aeisenbarth/am-segmentation | 3 | 6621438 | import re
import falcon
import json
ALLOWED_IMAGE_TYPES = (
'image/png',
)
_UUID_PATTERN = re.compile(
'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
)
def validate_image_type(req, resp, resource, params):
if req.content_type not in ALLOWED_IMAGE_TYPES:
msg = f'Image type not all... | import re
import falcon
import json
ALLOWED_IMAGE_TYPES = (
'image/png',
)
_UUID_PATTERN = re.compile(
'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
)
def validate_image_type(req, resp, resource, params):
if req.content_type not in ALLOWED_IMAGE_TYPES:
msg = f'Image type not all... | en | 0.311764 | # Always validate untrusted input! # class AblationMaskCollection(object): # # def __init__(self, task_manager): # self._task_manager = task_manager # # def on_get(self, req, resp): # mask_docs = [{'href': f'/masks/{fn}'} # for fn in self._image_store.list_masks()] # ... | 2.435816 | 2 |
LoremPizzum/products/urls.py | BruhMano/LoremPizzum | 0 | 6621439 | <filename>LoremPizzum/products/urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('',index,name = 'index'),
path('menu/',menu,name ="menu"),
path('menu/<int:ids>/',product_details,name = "product"),
] | <filename>LoremPizzum/products/urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('',index,name = 'index'),
path('menu/',menu,name ="menu"),
path('menu/<int:ids>/',product_details,name = "product"),
] | none | 1 | 1.807526 | 2 | |
trailTracer/scripts/trailTracerLib.py | Colin-Lundquist/trailTracer | 1 | 6621440 | from imutils.video import WebcamVideoStream
import time
import signal
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Signal Handlers
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def shutdown():
fan.set(on=0)
tilt_servo.disable()
servo_data.seek(0,0)
servo_data.writelines([str(int(pa... | from imutils.video import WebcamVideoStream
import time
import signal
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Signal Handlers
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def shutdown():
fan.set(on=0)
tilt_servo.disable()
servo_data.seek(0,0)
servo_data.writelines([str(int(pa... | en | 0.354634 | #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Signal Handlers #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Video Setup #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # notify user #video = VideoStream(src=0).start() # start camera stream # allow camera ... | 2.646439 | 3 |
platalea/__init__.py | gchrupala/platalea | 1 | 6621441 | <reponame>gchrupala/platalea
import configargparse
configargparse.init_argument_parser(name='platalea', default_config_files=['config.ini', 'config.yml'])
parser = configargparse.get_argument_parser(name='platalea')
parser.add_argument('--data_root', env_var='PLATALEA_DATA_ROOT',
action='store', de... | import configargparse
configargparse.init_argument_parser(name='platalea', default_config_files=['config.ini', 'config.yml'])
parser = configargparse.get_argument_parser(name='platalea')
parser.add_argument('--data_root', env_var='PLATALEA_DATA_ROOT',
action='store', default='/roaming/gchrupal/data... | none | 1 | 1.984767 | 2 | |
leetcode/687_longest_univalue_path/687_longest_univalue_path.py | ryangillard/misc | 0 | 6621442 | <gh_stars>0
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.max_longest = 0
def longestUnivaluePath(self, root):
"""
... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.max_longest = 0
def longestUnivaluePath(self, root):
"""
:type root... | en | 0.46731 | # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None :type root: TreeNode :rtype: int | 3.863636 | 4 |
core/model/layers.py | pjenpoomjai/LipNet | 22 | 6621443 | <gh_stars>10-100
from keras import backend as k
from keras.layers import Input
from keras.layers.convolutional import Conv3D, ZeroPadding3D
from keras.layers.core import Activation, Dense, Flatten, Lambda, SpatialDropout3D
from keras.layers.normalization import BatchNormalization
from keras.layers.pooling import MaxPoo... | from keras import backend as k
from keras.layers import Input
from keras.layers.convolutional import Conv3D, ZeroPadding3D
from keras.layers.core import Activation, Dense, Flatten, Lambda, SpatialDropout3D
from keras.layers.normalization import BatchNormalization
from keras.layers.pooling import MaxPooling3D
from keras... | none | 1 | 2.488911 | 2 | |
src/tfexp/cli.py | MArpogaus/tensorflow-experiments | 0 | 6621444 | #!env python3
# AUTHOR INFORMATION ##########################################################
# file : cli.py
# brief : [Description]
#
# author : <NAME>
# date : 2020-04-06 15:21:06
# COPYRIGHT ###################################################################
# Copyright 2020 <NAME>
#
# Licensed under the Apach... | #!env python3
# AUTHOR INFORMATION ##########################################################
# file : cli.py
# brief : [Description]
#
# author : <NAME>
# date : 2020-04-06 15:21:06
# COPYRIGHT ###################################################################
# Copyright 2020 <NAME>
#
# Licensed under the Apach... | en | 0.256983 | #!env python3 # AUTHOR INFORMATION ########################################################## # file : cli.py # brief : [Description] # # author : <NAME> # date : 2020-04-06 15:21:06 # COPYRIGHT ################################################################### # Copyright 2020 <NAME> # # Licensed under the Apach... | 1.705909 | 2 |
solax_modbus/sensor.py | Zeppen/homsassistant-solax-modbus | 22 | 6621445 | from homeassistant.const import CONF_NAME
from homeassistant.core import callback
from homeassistant.components.sensor import SensorEntity
import logging
from typing import Optional, Dict, Any
import homeassistant.util.dt as dt_util
from .const import ATTR_MANUFACTURER, DOMAIN, SENSOR_TYPES, GEN3_X1_SENSOR_TYPES, GE... | from homeassistant.const import CONF_NAME
from homeassistant.core import callback
from homeassistant.components.sensor import SensorEntity
import logging
from typing import Optional, Dict, Any
import homeassistant.util.dt as dt_util
from .const import ATTR_MANUFACTURER, DOMAIN, SENSOR_TYPES, GEN3_X1_SENSOR_TYPES, GE... | en | 0.692296 | Representation of an SolaX Modbus sensor. Initialize the sensor. Register callbacks. Return the name. Return the state of the sensor. | 2.000091 | 2 |
lib/music21/musicxml/fromMxObjects.py | lasconic/randomsheetmusic | 2 | 6621446 | <reponame>lasconic/randomsheetmusic<filename>lib/music21/musicxml/fromMxObjects.py
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: musicxml/fromMxObjects.py
# Purpose: Translate from MusicXML mxObjects to music21 objects
#
# Authors: <N... | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: musicxml/fromMxObjects.py
# Purpose: Translate from MusicXML mxObjects to music21 objects
#
# Authors: <NAME>
# <NAME>
#
# Copyright: Copyright © 2010-2013 <NAME> and the ... | en | 0.661207 | # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: musicxml/fromMxObjects.py # Purpose: Translate from MusicXML mxObjects to music21 objects # # Authors: <NAME> # <NAME> # # Copyright: Copyright © 2010-2013 <NAME> and the m... | 2.236394 | 2 |
.conky_hud/dbus-mon.py | sacooper/dotfiles | 0 | 6621447 | <gh_stars>0
#! /bin/env/python
from gi.repository import GLib
import subprocess
import dbus
import datetime
import threading
import time
from dbus.mainloop.glib import DBusGMainLoop
messages = []
messages_map = {}
counter = 1
cco = 1
def curTime():
ts = datetime.datetime.timestamp(datetime.datetime.now())
r... | #! /bin/env/python
from gi.repository import GLib
import subprocess
import dbus
import datetime
import threading
import time
from dbus.mainloop.glib import DBusGMainLoop
messages = []
messages_map = {}
counter = 1
cco = 1
def curTime():
ts = datetime.datetime.timestamp(datetime.datetime.now())
return ts
d... | en | 0.412424 | #! /bin/env/python # print(win_title) | 2.305195 | 2 |
teilab/__meta__.py | iwasakishuto/TeiLab-BasicLaboratoryWork-in-LifeScienceExperiments | 0 | 6621448 | <gh_stars>0
#coding: utf-8
__all__ = [
"__copyright__", "__version__", "__license__",
"__author__", "__author_address__", "__author_twitter__",
"__documentation__", "__github__",
"__principal_investigator__", "__labcolor__",
]
__copyright__ = "Copyright (C) 2021 <NAME>"
__version__ = "2... | #coding: utf-8
__all__ = [
"__copyright__", "__version__", "__license__",
"__author__", "__author_address__", "__author_twitter__",
"__documentation__", "__github__",
"__principal_investigator__", "__labcolor__",
]
__copyright__ = "Copyright (C) 2021 <NAME>"
__version__ = "2021S" # Spri... | en | 0.670829 | #coding: utf-8 # Spring Semester # ====== This is a joke, hahaha ======== # # # __labcolor__ = "⚫" # # # ====================================== # | 1.878402 | 2 |
chess/board.py | vanditkaria/chess | 20 | 6621449 | import chess
import table
def evaluate_board(board):
return sum(
piece_value(board.piece_at(square), square)
if board.piece_at(square) is not None else 0
for square in chess.SQUARES)
def piece_value(piece, square):
symbol = piece.symbol()
is_white = not symbol.islower()
row... | import chess
import table
def evaluate_board(board):
return sum(
piece_value(board.piece_at(square), square)
if board.piece_at(square) is not None else 0
for square in chess.SQUARES)
def piece_value(piece, square):
symbol = piece.symbol()
is_white = not symbol.islower()
row... | none | 1 | 3.513822 | 4 | |
src/simple_bot_handler.py | cltl/chatbot | 0 | 6621450 | import requests
class BotHandler:
def __init__(self, token):
self.token = token
self.api_url = "https://api.telegram.org/bot{}/".format(token)
def get_messages(self, offset=None, timeout=200):
""" Function to get all messages sent to the bot """
method = 'getUpdates'
p... | import requests
class BotHandler:
def __init__(self, token):
self.token = token
self.api_url = "https://api.telegram.org/bot{}/".format(token)
def get_messages(self, offset=None, timeout=200):
""" Function to get all messages sent to the bot """
method = 'getUpdates'
p... | en | 0.78359 | Function to get all messages sent to the bot Function to send a message from the bot to a specific user Function to get the last message sent to the bot by a specific user | 3.046944 | 3 |