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 |
|---|---|---|---|---|---|---|---|---|---|---|
scripts/add_to_page.py | N9199/IIC3253-2021-1 | 0 | 6623551 | #!/usr/bin/python3
import os
import re
from datetime import datetime
os.chdir(os.path.dirname(__file__))
enunciados = list(map(lambda x: int(
x[9:-4]), filter(lambda x: x[-4:] == ".pdf", os.listdir("../pdfs/Enunciados"))))
soluciones = list(map(lambda x: int(
x[8:-4]), filter(lambda x: x[-4:] == ".pdf", os.l... | #!/usr/bin/python3
import os
import re
from datetime import datetime
os.chdir(os.path.dirname(__file__))
enunciados = list(map(lambda x: int(
x[9:-4]), filter(lambda x: x[-4:] == ".pdf", os.listdir("../pdfs/Enunciados"))))
soluciones = list(map(lambda x: int(
x[8:-4]), filter(lambda x: x[-4:] == ".pdf", os.l... | en | 0.507772 | #!/usr/bin/python3 # Note: index 6 for update date, indices in [9,len(curr)-3] are for display list | 2.467906 | 2 |
dof_conf/core/tests/test_views.py | DevOfFuture/dof-conf | 3 | 6623552 | <filename>dof_conf/core/tests/test_views.py
from django.shortcuts import reverse
from dof_conf.core.tests import TestCase
class TestHome(TestCase):
def test_should_render(self):
url = reverse('core:home')
response = self.get(url)
self.assertEqual(response.status_code, 200)
self.... | <filename>dof_conf/core/tests/test_views.py
from django.shortcuts import reverse
from dof_conf.core.tests import TestCase
class TestHome(TestCase):
def test_should_render(self):
url = reverse('core:home')
response = self.get(url)
self.assertEqual(response.status_code, 200)
self.... | none | 1 | 2.250946 | 2 | |
webapi/servidorapi/migrations/0001_initial.py | aecheverria40/proyectomoviles | 0 | 6623553 | <reponame>aecheverria40/proyectomoviles
# Generated by Django 2.1.3 on 2018-11-13 07:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(s... | # Generated by Django 2.1.3 on 2018-11-13 07:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | en | 0.738631 | # Generated by Django 2.1.3 on 2018-11-13 07:02 | 1.715448 | 2 |
core/calculators/tests/test_order_calculator.py | stanwood/traidoo-api | 3 | 6623554 | import itertools
from decimal import Decimal
import pytest
from core.calculators.order_calculator import OrderCalculatorMixin
pytestmark = pytest.mark.django_db
def test_item_price_calculation():
item = OrderCalculatorMixin.Item(amount=3, price=10, vat=20, count=2, seller=1)
price_value = item.value
a... | import itertools
from decimal import Decimal
import pytest
from core.calculators.order_calculator import OrderCalculatorMixin
pytestmark = pytest.mark.django_db
def test_item_price_calculation():
item = OrderCalculatorMixin.Item(amount=3, price=10, vat=20, count=2, seller=1)
price_value = item.value
a... | none | 1 | 2.462162 | 2 | |
orders/views.py | RohanIRathi/Product-Management-System | 0 | 6623555 | <gh_stars>0
from datetime import datetime
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from home.models import User
from products.models import Product
from .models import Order, OrderProduct
# Create your views here.
def get_distributor_orders(requ... | from datetime import datetime
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from home.models import User
from products.models import Product
from .models import Order, OrderProduct
# Create your views here.
def get_distributor_orders(request):
if r... | en | 0.968116 | # Create your views here. | 2.074186 | 2 |
replica/core.py | TimeWz667/replica | 0 | 6623556 | import numpy as np
import pandas as pd
from scipy.integrate import solve_ivp
import os
import json
from numba import njit
__author__ = '<NAME>'
__all__ = ['Parameters', 'trm2dy', 'simulate', 'output_posterior']
@njit
def trm2dy(trm, y):
dy = np.zeros_like(y)
ns = len(y)
for src in range(ns):
for... | import numpy as np
import pandas as pd
from scipy.integrate import solve_ivp
import os
import json
from numba import njit
__author__ = '<NAME>'
__all__ = ['Parameters', 'trm2dy', 'simulate', 'output_posterior']
@njit
def trm2dy(trm, y):
dy = np.zeros_like(y)
ns = len(y)
for src in range(ns):
for... | en | 0.230896 | # post.Message['Trace'].to_csv(out_path + '/post_trace.csv') | 2.253931 | 2 |
grslra/spaces.py | clemenshage/grslra | 0 | 6623557 | <gh_stars>0
from abc import ABCMeta, abstractmethod
import numpy as np
from tools import msin, mcos
class SpaceMeta:
__metaclass__ = ABCMeta
@abstractmethod
def get_G(self, grad, X):
# this function returns the projected gradient
pass
@abstractmethod
def get_H(self, G, gamma, tau... | from abc import ABCMeta, abstractmethod
import numpy as np
from tools import msin, mcos
class SpaceMeta:
__metaclass__ = ABCMeta
@abstractmethod
def get_G(self, grad, X):
# this function returns the projected gradient
pass
@abstractmethod
def get_H(self, G, gamma, tauH):
... | en | 0.709197 | # this function returns the projected gradient # this function computes the search direction from the current projected gradient and the past search direction # this function updates the variable using the search direction and the step size # this function transports an element along H into the tangent space at distanc... | 2.786428 | 3 |
ChordServer (alt.)/peer.py | hoanhan101/chord | 1 | 6623558 | <filename>ChordServer (alt.)/peer.py<gh_stars>1-10
#!/usr/bin/env python3
"""
peer.py - A Peer acts as a Server and a Client
Author:
- <NAME> (<EMAIL>)
- <NAME> (<EMAIL>)
Date: 11/15/2017
"""
import zerorpc
from chord_instance import ChordInstance
from const import *
from utils import *
f... | <filename>ChordServer (alt.)/peer.py<gh_stars>1-10
#!/usr/bin/env python3
"""
peer.py - A Peer acts as a Server and a Client
Author:
- <NAME> (<EMAIL>)
- <NAME> (<EMAIL>)
Date: 11/15/2017
"""
import zerorpc
from chord_instance import ChordInstance
from const import *
from utils import *
f... | en | 0.753508 | #!/usr/bin/env python3 peer.py - A Peer acts as a Server and a Client Author: - <NAME> (<EMAIL>) - <NAME> (<EMAIL>) Date: 11/15/2017 # append to a local list and join the first instance (can be anyone in the list) # update the instance list locally # update other instance list using RPC as well ... | 2.950428 | 3 |
ap/models.py | edithamadi/Awwwards | 0 | 6623559 | <reponame>edithamadi/Awwwards<gh_stars>0
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Projects(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key = True)
title = models.TextField(max_length = 20, default="title here... | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Projects(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key = True)
title = models.TextField(max_length = 20, default="title here")
landing_page_image = models.ImageF... | en | 0.374589 | # Create your models here. # link_to_live_site = models.URLField(max_length=250,default = ) | 2.308125 | 2 |
nrc/nrc/extensions/failLogger.py | SkyTruth/scraper | 2 | 6623560 |
import StringIO
from datetime import datetime
import smtplib
import traceback
from scrapy import signals
from scrapy import log
from nrc import settings
class FailLogger(object):
@classmethod
def from_crawler(cls, crawler):
ext = cls()
crawler.signals.connect(ext.spider_error, signal=signa... |
import StringIO
from datetime import datetime
import smtplib
import traceback
from scrapy import signals
from scrapy import log
from nrc import settings
class FailLogger(object):
@classmethod
def from_crawler(cls, crawler):
ext = cls()
crawler.signals.connect(ext.spider_error, signal=signa... | en | 0.726257 | # email on first exception | 2.392714 | 2 |
src/inference.py | aidotse/d2seabirds | 0 | 6623561 | # Some basic setup:
import torch, torchvision
# Setup detectron2 logger
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import numpy as np
import os, json, cv2, random
from skimage.io import imread
from skimage.segmentation import mark_boundaries
from sk... | # Some basic setup:
import torch, torchvision
# Setup detectron2 logger
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import numpy as np
import os, json, cv2, random
from skimage.io import imread
from skimage.segmentation import mark_boundaries
from sk... | en | 0.738856 | # Some basic setup: # Setup detectron2 logger # import some common libraries # import some common detectron2 utilities # Only one sequence will be considered. Just one video. # Paths with multiple images # Get datasets #if id == 0: # record['annotations']=[] #ipdb.set_trace() # Extract class #return props[0].bbox # ... | 2.113851 | 2 |
aioscrapy/middleware/middleware_extension.py | conlin-huang/aio-scrapy | 13 | 6623562 | <reponame>conlin-huang/aio-scrapy
"""
The Extension Manager
See documentation in docs/topics/extensions.rst
"""
from .middleware import MiddlewareManager
from scrapy.utils.conf import build_component_list
class ExtensionManager(MiddlewareManager):
component_name = 'extension'
@classmethod
... | """
The Extension Manager
See documentation in docs/topics/extensions.rst
"""
from .middleware import MiddlewareManager
from scrapy.utils.conf import build_component_list
class ExtensionManager(MiddlewareManager):
component_name = 'extension'
@classmethod
def _get_mwlist_from_settings(cls... | en | 0.494707 | The Extension Manager
See documentation in docs/topics/extensions.rst | 1.613875 | 2 |
esque_wire/protocol/serializers/api/controlled_shutdown_response.py | real-digital/esque-wire | 0 | 6623563 | <gh_stars>0
###############################################################
# Autogenerated module. Please don't modify. #
# Edit according file in protocol_generator/templates instead #
###############################################################
from typing import Dict
from ...structs.api.contro... | ###############################################################
# Autogenerated module. Please don't modify. #
# Edit according file in protocol_generator/templates instead #
###############################################################
from typing import Dict
from ...structs.api.controlled_shutdow... | de | 0.58148 | ############################################################### # Autogenerated module. Please don't modify. # # Edit according file in protocol_generator/templates instead # ############################################################### | 1.516159 | 2 |
s3/py/dijkstra2.py | lisiynos/lisiynos.github.io | 1 | 6623564 | <gh_stars>1-10
# -*- utf-8 -*-
# <NAME>
from tkinter import Pack
N, M, start = map(int, input().split())
E = [] * N
for i in range(M):
f, t, w = map(int, input().split())
# Неориентированный граф
E[f].append((t, w))
E[t].append((f, w))
INF = 10 ** 10 # Бесконечность
d = [INF] * N # Кратчайшее расст... | # -*- utf-8 -*-
# <NAME>
from tkinter import Pack
N, M, start = map(int, input().split())
E = [] * N
for i in range(M):
f, t, w = map(int, input().split())
# Неориентированный граф
E[f].append((t, w))
E[t].append((f, w))
INF = 10 ** 10 # Бесконечность
d = [INF] * N # Кратчайшее расстояние до первой... | ru | 0.991109 | # -*- utf-8 -*- # <NAME> # Неориентированный граф # Бесконечность # Кратчайшее расстояние до первой вершины # Когда нашли кратчайший путь -> красим вершину # Предыдущая вершина # Добавляем новую вершину # Пересчитываем пути через вершину add # Ищем минимум # Трёхмерная динамика во Флойде # [k][i][j] - используя вершины... | 2.776426 | 3 |
pyclitr.py | jrenslin/pyclitr | 0 | 6623565 | <filename>pyclitr.py<gh_stars>0
#! /usr/bin/env python3
# ^
######## Import ########
import os, sys, uuid, json, pwd, copy
from datetime import datetime
######## Functions ########
def json_dump (inp):
return json.dumps(inp, sort_keys=True, indent=2)
def create_json_file (filename):
handle = open (filename + '.jso... | <filename>pyclitr.py<gh_stars>0
#! /usr/bin/env python3
# ^
######## Import ########
import os, sys, uuid, json, pwd, copy
from datetime import datetime
######## Functions ########
def json_dump (inp):
return json.dumps(inp, sort_keys=True, indent=2)
def create_json_file (filename):
handle = open (filename + '.jso... | en | 0.745842 | #! /usr/bin/env python3 # ^ ######## Import ######## ######## Functions ######## # Set basic variables # Check if pyclitr has been initialized for this directory # Display edits if there are any # Check whether this issue is pending or completed # Check whether this issue is pending or completed # Check whether this is... | 2.548967 | 3 |
src/contexts/kms/computed_data/infrastructure/persistence/AllAlgorithmComputedDataRepository.py | parada3desu/foxy-key-broker | 0 | 6623566 | <filename>src/contexts/kms/computed_data/infrastructure/persistence/AllAlgorithmComputedDataRepository.py<gh_stars>0
import sys
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from cryptography.hazmat.primitives import hashes, hmac
from cryptography.hazmat.primitives._serialization import PublicFo... | <filename>src/contexts/kms/computed_data/infrastructure/persistence/AllAlgorithmComputedDataRepository.py<gh_stars>0
import sys
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from cryptography.hazmat.primitives import hashes, hmac
from cryptography.hazmat.primitives._serialization import PublicFo... | es | 0.84531 | # Key generation # Key derivation # Contraseña basada en key derivation # Data sensitiva para cifrar # Encriptación usando AES GCM # https://pycryptodome.readthedocs.io/en/latest/src/cipher/aes.html # Mensaje transmitido # ciphertext: resultado de los datos cifrados, # tag: Codigo de autenticacion de mensajes MAC # non... | 1.851135 | 2 |
cvpysdk/activateapps/inventory_manager.py | CommvaultEngg/cvpysdk | 35 | 6623567 | # -*- coding: utf-8 -*-
# --------------------------------------------------------------------------
# Copyright Commvault Systems, 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
#
# ... | # -*- coding: utf-8 -*-
# --------------------------------------------------------------------------
# Copyright Commvault Systems, 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
#
# ... | en | 0.641736 | # -*- coding: utf-8 -*- # -------------------------------------------------------------------------- # Copyright Commvault Systems, 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 # # ... | 1.622338 | 2 |
src/metarl/envs/ml_wrapper.py | icml2020submission6857/metarl | 2 | 6623568 | from metaworld.benchmarks import ML1, ML10, ML45
class ML1WithPinnedGoal(ML1):
"""A wrapper of ML1 environment that retains goals across pickling and unpickling.
`env = ML1.get_train_tasks('task-name')` gives an environment that internally keeps 50 pre-generated variants of
this task, and `env.sample_task(... | from metaworld.benchmarks import ML1, ML10, ML45
class ML1WithPinnedGoal(ML1):
"""A wrapper of ML1 environment that retains goals across pickling and unpickling.
`env = ML1.get_train_tasks('task-name')` gives an environment that internally keeps 50 pre-generated variants of
this task, and `env.sample_task(... | en | 0.879184 | A wrapper of ML1 environment that retains goals across pickling and unpickling. `env = ML1.get_train_tasks('task-name')` gives an environment that internally keeps 50 pre-generated variants of this task, and `env.sample_task(1)` will return one of these variants. However, these variants cannot survive pickl... | 2.379863 | 2 |
catalog/views.py | matteostori/FerrariCatalog | 0 | 6623569 | <reponame>matteostori/FerrariCatalog
from os import listdir
from os.path import join
from django.shortcuts import render
from django.views import generic
from FerrariCatalog.settings import BASE_DIR, STATIC_URL
from .models import Car, Pilot
# Create your views here.
def index(request):
"""View function for ho... | from os import listdir
from os.path import join
from django.shortcuts import render
from django.views import generic
from FerrariCatalog.settings import BASE_DIR, STATIC_URL
from .models import Car, Pilot
# Create your views here.
def index(request):
"""View function for home page of site."""
# Generate c... | en | 0.853968 | # Create your views here. View function for home page of site. # Generate counts of some of the main objects # Render the HTML template index.html with the data in the context variable #about page #simple view for listing all cars (paginated) #detailed view of each car #simple view for listing all pilots (paginated) #d... | 2.4016 | 2 |
app/src/main/python/test.py | zhongens/AcousticSensing | 0 | 6623570 | import math
import random
import numpy
def get_random():
return random.randint(1, 100)
def get_sqrt(x):
return math.sqrt(x)
def calculator(x,y,ope):
print("enter python")
if ope == "+":
return x + y
elif ope == "-":
return x - y
elif ope == "*":
return x * y
elif... | import math
import random
import numpy
def get_random():
return random.randint(1, 100)
def get_sqrt(x):
return math.sqrt(x)
def calculator(x,y,ope):
print("enter python")
if ope == "+":
return x + y
elif ope == "-":
return x - y
elif ope == "*":
return x * y
elif... | none | 1 | 3.614145 | 4 | |
code/data_owner_2/tests/test_paillier.py | ClarkYan/msc-thesis | 7 | 6623571 | import random
from nose.tools import assert_raises
import paillier
def test_invmod():
assert_raises(ValueError, paillier.invmod, 0, 7)
assert paillier.invmod(1, 7) == 1
p = 101
for i in range(1, p):
iinv = paillier.invmod(i, p)
assert (iinv * i) % p == 1
def test_keys_int():
priv ... | import random
from nose.tools import assert_raises
import paillier
def test_invmod():
assert_raises(ValueError, paillier.invmod, 0, 7)
assert paillier.invmod(1, 7) == 1
p = 101
for i in range(1, p):
iinv = paillier.invmod(i, p)
assert (iinv * i) % p == 1
def test_keys_int():
priv ... | none | 1 | 2.242623 | 2 | |
catkin_ws/src/beginner_tutorials/scripts/message.py | NevzatBOL/ROS-Beginner | 2 | 6623572 | <filename>catkin_ws/src/beginner_tutorials/scripts/message.py
#!/usr/bin/env python
import rospy
from beginner_tutorials.msg import Num
def talker():
rospy.init_node('message_talker',anonymous=True)
pub = rospy.Publisher('talker',Num)
r = rospy.Rate(10)
msg = Num()
msg.num = 4
while not ro... | <filename>catkin_ws/src/beginner_tutorials/scripts/message.py
#!/usr/bin/env python
import rospy
from beginner_tutorials.msg import Num
def talker():
rospy.init_node('message_talker',anonymous=True)
pub = rospy.Publisher('talker',Num)
r = rospy.Rate(10)
msg = Num()
msg.num = 4
while not ro... | ru | 0.26433 | #!/usr/bin/env python | 2.462111 | 2 |
setup.py | pavoljuhas/diffpy.Structure | 19 | 6623573 | <filename>setup.py
#!/usr/bin/env python
"""Objects for storage and manipulation of crystal structure data.
Packages: diffpy.structure
"""
import os
import re
import sys
from setuptools import setup, find_packages
# Use this version when git data are not available, like in git zip archive.
# Update when tagging a... | <filename>setup.py
#!/usr/bin/env python
"""Objects for storage and manipulation of crystal structure data.
Packages: diffpy.structure
"""
import os
import re
import sys
from setuptools import setup, find_packages
# Use this version when git data are not available, like in git zip archive.
# Update when tagging a... | en | 0.633419 | #!/usr/bin/env python Objects for storage and manipulation of crystal structure data. Packages: diffpy.structure # Use this version when git data are not available, like in git zip archive. # Update when tagging a new release. # determine if we run with Python 3. # versioncfgfile holds version data for git commit ha... | 1.959879 | 2 |
backend/medicar/tests/fixture.py | WesGtoX/medicar | 2 | 6623574 | <reponame>WesGtoX/medicar<filename>backend/medicar/tests/fixture.py
import factory
from faker import Faker
from medicar.models import (
Specialty, Doctor, Agenda, MedicalAppointment
)
fake = Faker(['pt_BR'])
class SpecialtyFactory(factory.django.DjangoModelFactory):
"""Fixture for creating a Specialty"""
... | import factory
from faker import Faker
from medicar.models import (
Specialty, Doctor, Agenda, MedicalAppointment
)
fake = Faker(['pt_BR'])
class SpecialtyFactory(factory.django.DjangoModelFactory):
"""Fixture for creating a Specialty"""
class Meta:
model = Specialty
name = factory.Faker('w... | en | 0.898762 | Fixture for creating a Specialty Fixture for creating a Doctor Fixture for creating an Agenda Fixture for creating a Medical Appointment | 2.223432 | 2 |
test_iterator.py | sangeeth98/brute-force-on-zipfiles | 0 | 6623575 | <reponame>sangeeth98/brute-force-on-zipfiles<gh_stars>0
import itertools, zipfile, time
import concurrent.futures
options = 'abcdefghijklmnopqrstuvwxyz0123456789'
#combos made to range from 1 character to 8#
combos = itertools.product((options),repeat = 3)
# x = iter(combos)
# def printnext(it):
# print(next(it))
... | import itertools, zipfile, time
import concurrent.futures
options = 'abcdefghijklmnopqrstuvwxyz0123456789'
#combos made to range from 1 character to 8#
combos = itertools.product((options),repeat = 3)
# x = iter(combos)
# def printnext(it):
# print(next(it))
# return 0
# with concurrent.futures.ThreadPoolExecu... | en | 0.776674 | #combos made to range from 1 character to 8# # x = iter(combos) # def printnext(it): # print(next(it)) # return 0 # with concurrent.futures.ThreadPoolExecutor() as executor: # result = [executor.submit(printnext, x) for _ in range(200)] | 3.002462 | 3 |
slide_12.py | JakeRoggenbuck/strategy_presentation_numpy | 0 | 6623576 | <gh_stars>0
# Not runnable
key = "<KEY>"
request_headers = {"X-TBA-Auth-Key": key}
{"X-TBA-Auth-Key": "<KEY>"}
| # Not runnable
key = "<KEY>"
request_headers = {"X-TBA-Auth-Key": key}
{"X-TBA-Auth-Key": "<KEY>"} | en | 0.791515 | # Not runnable | 1.396844 | 1 |
tierpsy/analysis/compress_add_data/getAdditionalData.py | mgh17/tierpsy-tracker | 9 | 6623577 | """
# -*- coding: utf-8 -*-
Created on Thu Dec 17 10:10:35 2015
@author: ajaver
"""
import os
import stat
import xml.etree.ElementTree as ET
import tables
import numpy as np
import csv
from collections import OrderedDict
#%% Read/Store the XML file with the pixel size and fps info
def storeXMLInfo(info_file, masked... | """
# -*- coding: utf-8 -*-
Created on Thu Dec 17 10:10:35 2015
@author: ajaver
"""
import os
import stat
import xml.etree.ElementTree as ET
import tables
import numpy as np
import csv
from collections import OrderedDict
#%% Read/Store the XML file with the pixel size and fps info
def storeXMLInfo(info_file, masked... | en | 0.792479 | # -*- coding: utf-8 -*- Created on Thu Dec 17 10:10:35 2015 @author: ajaver #%% Read/Store the XML file with the pixel size and fps info # if it is empty the xml create a node and exit # read the xml and exit # Read the scale conversions, we would need this when we want to convert the pixels into microns #%% Read/Stor... | 2.262056 | 2 |
commitroll/commitable.py | claybrooks/commitroll | 0 | 6623578 | <reponame>claybrooks/commitroll<gh_stars>0
from functools import wraps
COMMIT="1__commit"
NO_COMMIT="2__no_commit"
COMMIT_ALL="3__commit_all"
SAVE_STATE="4__save_state"
def Commit(func):
setattr(func, COMMIT, True)
return func
def NoCommit(obj):
setattr(obj, NO_COMMIT, True)
return obj
def CommitAll... | from functools import wraps
COMMIT="1__commit"
NO_COMMIT="2__no_commit"
COMMIT_ALL="3__commit_all"
SAVE_STATE="4__save_state"
def Commit(func):
setattr(func, COMMIT, True)
return func
def NoCommit(obj):
setattr(obj, NO_COMMIT, True)
return obj
def CommitAll(obj):
setattr(obj, COMMIT_ALL, True)
... | none | 1 | 2.574703 | 3 | |
intropyproject-classify-pet-images/print_results.py | petercm/AIPND-revision | 0 | 6623579 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# */AIPND-revision/intropyproject-classify-pet-images/print_results.py
#
# PROGRAMMER: petercm
# DATE CREATED: 01/03/2019
# REVISED DATE:
# PURPOSE: Create a function print_results that prints the results statistics
# from the results statistics dictionary (result... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# */AIPND-revision/intropyproject-classify-pet-images/print_results.py
#
# PROGRAMMER: petercm
# DATE CREATED: 01/03/2019
# REVISED DATE:
# PURPOSE: Create a function print_results that prints the results statistics
# from the results statistics dictionary (result... | en | 0.7831 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- # */AIPND-revision/intropyproject-classify-pet-images/print_results.py # # PROGRAMMER: petercm # DATE CREATED: 01/03/2019 # REVISED DATE: # PURPOSE: Create a function print_results that prints the results statistics # from the results statistics dictionary (result... | 3.124228 | 3 |
kitsune/karma/migrations/0001_initial.py | navgurukul-shivani18/kitsune | 929 | 6623580 | <filename>kitsune/karma/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
migrations.swappable_depe... | <filename>kitsune/karma/migrations/0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
migrations.swappable_depe... | en | 0.769321 | # -*- coding: utf-8 -*- | 1.747541 | 2 |
contacts/migrations/0012_auto_20190418_0543.py | martbln/django-service-boilerplate | 18 | 6623581 | <filename>contacts/migrations/0012_auto_20190418_0543.py
# Generated by Django 2.1.7 on 2019-04-18 05:43
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import pik.core.models.uided
import simple_history.models
import core.fields
class Migration(migrations.... | <filename>contacts/migrations/0012_auto_20190418_0543.py
# Generated by Django 2.1.7 on 2019-04-18 05:43
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import pik.core.models.uided
import simple_history.models
import core.fields
class Migration(migrations.... | en | 0.620975 | # Generated by Django 2.1.7 on 2019-04-18 05:43 | 1.593965 | 2 |
castanea/utils/with_none.py | YusukeSuzuki/castanea | 0 | 6623582 | <gh_stars>0
import tensorflow as tf
class WithNone:
def __enter__(self): pass
def __exit__(self,t,v,tb): pass
def device_or_none(x):
return WithNone() if x is None else tf.device(x)
| import tensorflow as tf
class WithNone:
def __enter__(self): pass
def __exit__(self,t,v,tb): pass
def device_or_none(x):
return WithNone() if x is None else tf.device(x) | none | 1 | 2.574156 | 3 | |
sample-viewer-api/src/static/data/compile_cvisb_data/config.py | cvisb/cvisb_data | 2 | 6623583 | # Config file to specify the inputs / outputs of CViSB data compilation
from datetime import datetime
today = datetime.today().strftime('%Y-%m-%d')
DATADIR = "/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/"
# [INPUTS] ---------------------------------------------------------------------------... | # Config file to specify the inputs / outputs of CViSB data compilation
from datetime import datetime
today = datetime.today().strftime('%Y-%m-%d')
DATADIR = "/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/"
# [INPUTS] ---------------------------------------------------------------------------... | en | 0.484559 | # Config file to specify the inputs / outputs of CViSB data compilation # [INPUTS] ---------------------------------------------------------------------------------------------- # --- id dictionary --- # --- patients --- # ACUTE_IDS_FILE = f"{DATADIR}/input_data/patient_rosters/additional_IDdict_v3_2019-10-23.csv" # -... | 1.908799 | 2 |
main.py | gchrupala/imaginet | 7 | 6623584 | <filename>main.py
#!/usr/bin/env python
from __future__ import division
import sys
sys.path.append('/home/gchrupala/repos/Passage')
sys.path.append('/home/gchrupala/repos/neuraltalk')
from passage.layers import Embedding, SimpleRecurrent, LstmRecurrent, GatedRecurrent #, Dense
from layers import *
from passage.costs im... | <filename>main.py
#!/usr/bin/env python
from __future__ import division
import sys
sys.path.append('/home/gchrupala/repos/Passage')
sys.path.append('/home/gchrupala/repos/neuraltalk')
from passage.layers import Embedding, SimpleRecurrent, LstmRecurrent, GatedRecurrent #, Dense
from layers import *
from passage.costs im... | en | 0.501562 | #!/usr/bin/env python #, Dense # With pairs we'd get duplicate images! # candidates are identical to Y_pred #distances = D.cosine_distance(Y_pred, Y_pred) # exclude self # Validation data # if args.init_model is not None: # model_init = cPickle.load(open(args.init_model)) # def values(ps): # return [ p... | 1.973251 | 2 |
2018/day-02/day2.py | smolsbs/aoc | 1 | 6623585 | <reponame>smolsbs/aoc<filename>2018/day-02/day2.py<gh_stars>1-10
import sys
import itertools
with open('input', 'r') as fp:
data = [x.strip('\n') for x in fp.readlines()]
def part1(data):
a, b = 0, 0
for line in data:
s = {}
for ch in line:
if ch not in s:
s[ch] ... | import sys
import itertools
with open('input', 'r') as fp:
data = [x.strip('\n') for x in fp.readlines()]
def part1(data):
a, b = 0, 0
for line in data:
s = {}
for ch in line:
if ch not in s:
s[ch] = 1
else:
s[ch] += 1
if 2 in ... | en | 0.393049 | # length of any string | 3.11987 | 3 |
Condenser_Designer.py | li-fulin/Refrigeration-Condenser-Desginer | 0 | 6623586 | import CoolProp.CoolProp as CP
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Constant Parameters
RC = 80 #kW
Tevap = 5 #Degree Celsius
Tcond = 45 #Degree Celsius
Twi = 30 #Water inlet temp; Degree Celsius
Twe = 35 #Water outlet temp; Degree Celsius
Do = 0.016 #Pipe outer diameter;... | import CoolProp.CoolProp as CP
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Constant Parameters
RC = 80 #kW
Tevap = 5 #Degree Celsius
Tcond = 45 #Degree Celsius
Twi = 30 #Water inlet temp; Degree Celsius
Twe = 35 #Water outlet temp; Degree Celsius
Do = 0.016 #Pipe outer diameter;... | en | 0.583195 | # Constant Parameters #kW #Degree Celsius #Degree Celsius #Water inlet temp; Degree Celsius #Water outlet temp; Degree Celsius #Pipe outer diameter; m #Pipe inner diameter; m #Heat Rejection Ratio; Qcond/Qevap #Thermal conductivity of copper; J/mK #number of pipes #number of pass #refrigerant #Number of vertical flow #... | 3.236319 | 3 |
openapi_python_client/openapi_parser/openapi.py | acgray/openapi-python-client | 0 | 6623587 | from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, Generator, Iterable, List, Optional, Set
from .errors import ParseError
from .properties import EnumProperty, ListProperty, Property, property_from_dict
from .reference import Reference
from... | from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, Generator, Iterable, List, Optional, Set
from .errors import ParseError
from .properties import EnumProperty, ListProperty, Property, property_from_dict
from .reference import Reference
from... | en | 0.795454 | The places Parameters can be put when calling an Endpoint Create a string which is used to import a reference A bunch of endpoints grouped under a tag that will become a module Parse the openapi paths data to get EndpointCollections by tag Describes a single endpoint on the server Return form_body_reference Return form... | 2.527715 | 3 |
distributed/scripts/instances_validator.py | jina-ai/stress-test | 4 | 6623588 | <gh_stars>1-10
import sys
import time
import requests
import yaml
try:
with open('_instances.yaml') as f:
e2e_ip_dict = yaml.safe_load(f)
except FileNotFoundError:
raise Exception('Please make sure the previous step has created the instances.yaml file')
total_time_to_wait = 120
init_time = time.time(... | import sys
import time
import requests
import yaml
try:
with open('_instances.yaml') as f:
e2e_ip_dict = yaml.safe_load(f)
except FileNotFoundError:
raise Exception('Please make sure the previous step has created the instances.yaml file')
total_time_to_wait = 120
init_time = time.time()
check_until =... | none | 1 | 2.582436 | 3 | |
Pasture_Growth_Modelling/initialisation_support/explore_harvest_parameters.py | Komanawa-Solutions-Ltd/SLMACC-2020-CSRA | 0 | 6623589 | """
Author: <NAME>
Created: 23/11/2020 11:02 AM
"""
import ksl_env
import pandas as pd
import numpy as np
import os
# add basgra nz functions
ksl_env.add_basgra_nz_path()
from check_basgra_python.support_for_tests import get_lincoln_broadfield, get_woodward_weather, _clean_harvest
from basgra_python import run_ba... | """
Author: <NAME>
Created: 23/11/2020 11:02 AM
"""
import ksl_env
import pandas as pd
import numpy as np
import os
# add basgra nz functions
ksl_env.add_basgra_nz_path()
from check_basgra_python.support_for_tests import get_lincoln_broadfield, get_woodward_weather, _clean_harvest
from basgra_python import run_ba... | en | 0.407268 | Author: <NAME> Created: 23/11/2020 11:02 AM # add basgra nz functions # set filler values # set flag to not harvest # set filler values # set filler values # start harvesting at the same point | 2.224565 | 2 |
get_spotify_info.py | tanelso2/favorite-albums-webapp | 0 | 6623590 | <reponame>tanelso2/favorite-albums-webapp
# coding: utf-8
import base64
import configparser
import json
import requests
import sys
import urllib.parse
def get_client_values(file_loc=None):
if file_loc is None:
file_loc = sys.argv[1]
config = configparser.ConfigParser()
config.read(file_loc)
ret... | # coding: utf-8
import base64
import configparser
import json
import requests
import sys
import urllib.parse
def get_client_values(file_loc=None):
if file_loc is None:
file_loc = sys.argv[1]
config = configparser.ConfigParser()
config.read(file_loc)
return config["Spotify"]["client_id"], config... | en | 0.833905 | # coding: utf-8 # Needed to get past the Love Pts 1 & 2 double album. # Part 2 is merely meh # For debugging errors: # print(f'{album} by {artist}') #Preserve all the images. # Just in case I want to add logic to switch # to smaller images on smaller devices | 3.006002 | 3 |
setup.py | allanlwu/allangdrive | 0 | 6623591 | import setuptools
setuptools.setup(
name="allangdrive",
version='0.1.0',
url="https://github.com/allanlwu/allangdrive",
author="<NAME>",
description="Jupyter extension to allow user to sync files to Google Drive",
packages=setuptools.find_packages(),
install_requires=[
'notebook',
... | import setuptools
setuptools.setup(
name="allangdrive",
version='0.1.0',
url="https://github.com/allanlwu/allangdrive",
author="<NAME>",
description="Jupyter extension to allow user to sync files to Google Drive",
packages=setuptools.find_packages(),
install_requires=[
'notebook',
... | none | 1 | 1.680476 | 2 | |
web_app/services/basilica_service.py | diegoarriola1/twitoff-pt5 | 0 | 6623592 | <filename>web_app/services/basilica_service.py<gh_stars>0
# web_app/services/basilica_services.py
import basilica
import os
from dotenv import load_dotenv
load_dotenv() # parese the .env file for environment variables
BASILICA_API_KEY = os.getenv("BASILICA_API_KEY")
connection = basilica.Connection(BASILICA_API_K... | <filename>web_app/services/basilica_service.py<gh_stars>0
# web_app/services/basilica_services.py
import basilica
import os
from dotenv import load_dotenv
load_dotenv() # parese the .env file for environment variables
BASILICA_API_KEY = os.getenv("BASILICA_API_KEY")
connection = basilica.Connection(BASILICA_API_K... | en | 0.677756 | # web_app/services/basilica_services.py # parese the .env file for environment variables | 2.20524 | 2 |
EDA/compress_audio/__init__.py | W210-Audio-Upscaling/Audio-Upscaling | 0 | 6623593 | from ffmpy import FFmpeg
import os, glob
class Normalize_Audio():
def __init__(self):
''' Constructor for this class. '''
pass
def normalize(infile,bitrate):
filename=os.path.splitext(os.path.split(infile)[1])[0]
filepath=os.path.dirname(infile)+"\\normalized"
tr... | from ffmpy import FFmpeg
import os, glob
class Normalize_Audio():
def __init__(self):
''' Constructor for this class. '''
pass
def normalize(infile,bitrate):
filename=os.path.splitext(os.path.split(infile)[1])[0]
filepath=os.path.dirname(infile)+"\\normalized"
tr... | en | 0.727852 | Constructor for this class. | 2.988053 | 3 |
CodeWars/Unique_number.py | srisrinu1/Interview-solved | 46 | 6623594 | <filename>CodeWars/Unique_number.py
###This one is from a problem I soved on codewars in my beginner level
#Qustion
'''There is an array with some numbers. All numbers are equal except for one. Try to find it!
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
It’s guaranteed that array conta... | <filename>CodeWars/Unique_number.py
###This one is from a problem I soved on codewars in my beginner level
#Qustion
'''There is an array with some numbers. All numbers are equal except for one. Try to find it!
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
It’s guaranteed that array conta... | en | 0.909465 | ###This one is from a problem I soved on codewars in my beginner level #Qustion There is an array with some numbers. All numbers are equal except for one. Try to find it! find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 It’s guaranteed that array contains at least 3 numbers. The tests cont... | 3.962338 | 4 |
manage.py | zjmeow/HelloFlask | 0 | 6623595 | #coding:utf8
from flask_migrate import MigrateCommand , Migrate
from app import create_app,db
from flask_script import Manager
app = create_app()
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)
if __name__ == '__main__':
app.run(host='0.0.0.0')
# manager.run()
| #coding:utf8
from flask_migrate import MigrateCommand , Migrate
from app import create_app,db
from flask_script import Manager
app = create_app()
manager = Manager(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)
if __name__ == '__main__':
app.run(host='0.0.0.0')
# manager.run()
| ru | 0.232704 | #coding:utf8 # manager.run() | 1.887012 | 2 |
jinete/storers/sets.py | garciparedes/rider | 5 | 6623596 | <filename>jinete/storers/sets.py
"""The set of definitions to use more than one storer at the same time."""
from __future__ import (
annotations,
)
import logging
from typing import (
TYPE_CHECKING,
)
from .abc import (
Storer,
)
if TYPE_CHECKING:
from typing import (
Set,
Type,
... | <filename>jinete/storers/sets.py
"""The set of definitions to use more than one storer at the same time."""
from __future__ import (
annotations,
)
import logging
from typing import (
TYPE_CHECKING,
)
from .abc import (
Storer,
)
if TYPE_CHECKING:
from typing import (
Set,
Type,
... | en | 0.83209 | The set of definitions to use more than one storer at the same time. Store a resulting solution trough multiple storers. This implementation is an intermediate tool to combine multiple storers. Construct a new object instance. :param storer_cls_set: The storer classes to be used to store the problem solut... | 2.950994 | 3 |
mux_python/models/referrer_domain_restriction.py | ryan-alley/mux-python | 0 | 6623597 | # coding: utf-8
"""
Mux API
Mux is how developers build online video. This API encompasses both Mux Video and Mux Data functionality to help you build your video-related projects better and faster than ever before. # noqa: E501
The version of the OpenAPI document: v1
Contact: <EMAIL>
Generated b... | # coding: utf-8
"""
Mux API
Mux is how developers build online video. This API encompasses both Mux Video and Mux Data functionality to help you build your video-related projects better and faster than ever before. # noqa: E501
The version of the OpenAPI document: v1
Contact: <EMAIL>
Generated b... | en | 0.652085 | # coding: utf-8 Mux API Mux is how developers build online video. This API encompasses both Mux Video and Mux Data functionality to help you build your video-related projects better and faster than ever before. # noqa: E501 The version of the OpenAPI document: v1 Contact: <EMAIL> Generated by: https:... | 2.004935 | 2 |
main.py | thanapolbig/python_API | 0 | 6623598 | <gh_stars>0
from typing import Optional
import sqlite3
from fastapi import FastAPI
app = FastAPI()
print("go to swagger =>> http://1172.16.31.10:8000/docs")
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"... | from typing import Optional
import sqlite3
from fastapi import FastAPI
app = FastAPI()
print("go to swagger =>> http://1172.16.31.10:8000/docs")
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": it... | none | 1 | 2.665626 | 3 | |
cube_analysis/moments.py | e-koch/CubeAnalysis | 4 | 6623599 | <reponame>e-koch/CubeAnalysis<filename>cube_analysis/moments.py
from spectral_cube import SpectralCube
from spectral_cube.lower_dimensional_structures import Projection
import numpy as np
import astropy.units as u
from astropy.io import fits
from astropy.wcs import WCS
from astropy import log
from astropy.convolution ... | from spectral_cube import SpectralCube
from spectral_cube.lower_dimensional_structures import Projection
import numpy as np
import astropy.units as u
from astropy.io import fits
from astropy.wcs import WCS
from astropy import log
from astropy.convolution import Gaussian1DKernel
from astropy.utils.console import Progres... | en | 0.714619 | Return the velocity at the peak of a spectrum. # in_memory=False, num_cores=1, Calculate the peak velocity surface of a spectral cube # Open the cube to get some properties for the peak velocity # array # Now read in the source mask # if in_memory: # gener = [(cube[:, y, x], kern) # for y, x in zip(y_p... | 2.185622 | 2 |
src/service.py | wisrovi/chat_telegram_gpt3 | 0 | 6623600 | <gh_stars>0
# -*- coding: utf-8 -*-
# !pip install python-telegram-bot
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters)
from config import TOKEN_TELEGRAM as config
from gpt3 import getAnswer as gpt3
from files import writeSession as session
def start(update, context):
context.bot.send_... | # -*- coding: utf-8 -*-
# !pip install python-telegram-bot
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters)
from config import TOKEN_TELEGRAM as config
from gpt3 import getAnswer as gpt3
from files import writeSession as session
def start(update, context):
context.bot.send_message(upda... | es | 0.969596 | # -*- coding: utf-8 -*- # !pip install python-telegram-bot # obtengo el id_usuario # obtengo el mensaje del usuario # miro si hay un log previo cargado en cache, sino creo el cache para este usuario # le pido a la IA una respuesta al comentario del usuario # guardo el cache para este usuario # respondo al usuario # res... | 2.608485 | 3 |
graph_test.py | QMH-TMY/Arithmetic | 0 | 6623601 | <reponame>QMH-TMY/Arithmetic
# -*- coding:UTF8 -*-
#!/usr/bin/python
#Shieber on 2018/8/8
#图及其结构
from graph import Graph
from queue import Queue,PriorityQueue
#********************问题1****************************************#
def buildCharGraph(wordFile):
'''字梯圖'''
wdLis = {}
graph = Graph()
wfile = op... | # -*- coding:UTF8 -*-
#!/usr/bin/python
#Shieber on 2018/8/8
#图及其结构
from graph import Graph
from queue import Queue,PriorityQueue
#********************问题1****************************************#
def buildCharGraph(wordFile):
'''字梯圖'''
wdLis = {}
graph = Graph()
wfile = open(wordFile,'r')
for lin... | zh | 0.621372 | # -*- coding:UTF8 -*- #!/usr/bin/python #Shieber on 2018/8/8 #图及其结构 #********************问题1****************************************# 字梯圖 #去掉换行符 #G,d = buildCharGraph("wordfile.txt") #print(G.getVertices()) #print(G.getEdge()) #print(d.keys()) #*******解决方案********# 字梯图解决方案:广度优先搜索,时间复杂度:O(V+E) #加入队列 打印出任意字回到原始字的路径 #****... | 3.424286 | 3 |
DataPipeline/transform.py | kelleyjean/condenast-de-project | 0 | 6623602 | import pandas as pd
import csv
import glob
from datetime import datetime
pickle_path = 'pickle_files'
pickle_files = glob.glob(pickle_path + '/*.pkl')
pitstops_df = pd.read_pickle(pickle_path + './pit_stops.csv.pkl')
races_df = pd.read_pickle(pickle_path + './races.csv.pkl')
driver_df = pd.read_pickle(pickle_path + '... | import pandas as pd
import csv
import glob
from datetime import datetime
pickle_path = 'pickle_files'
pickle_files = glob.glob(pickle_path + '/*.pkl')
pitstops_df = pd.read_pickle(pickle_path + './pit_stops.csv.pkl')
races_df = pd.read_pickle(pickle_path + './races.csv.pkl')
driver_df = pd.read_pickle(pickle_path + '... | en | 0.863017 | #merges pitstops and races on raceId to bring in race name # group data to get average duration and write to csv file #pseudo logic: #a year (int64) is passed through the function which selects the season to run the analysis #select min(season_year_race_date) and max(season_year_race_date) #create two columns, the driv... | 3.271378 | 3 |
cutvideo2frames.py | Talegqz/phased_based-motion__disentanglement | 1 | 6623603 | <filename>cutvideo2frames.py
import numpy as np
import cv2
from PIL import Image
import os
def deal_video():
cap = cv2.VideoCapture('data/cinesmall.avi')
a = 0
frams = []
while(cap.isOpened()):
ret, frame = cap.read()
a+=1
# pic.show()
if ret == True:
fram... | <filename>cutvideo2frames.py
import numpy as np
import cv2
from PIL import Image
import os
def deal_video():
cap = cv2.VideoCapture('data/cinesmall.avi')
a = 0
frams = []
while(cap.isOpened()):
ret, frame = cap.read()
a+=1
# pic.show()
if ret == True:
fram... | en | 0.192178 | # pic.show() # pic = pic.resize((64,64)) # cv2.imshow('frame',frame) | 2.941422 | 3 |
charybdis/user/models.py | gitter-badger/charybdis | 0 | 6623604 | <filename>charybdis/user/models.py
from uuid import uuid4
from passlib.hash import pbkdf2_sha512
from slugify import slugify
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref
from ..app import db
from ..domain.models import Domain
from... | <filename>charybdis/user/models.py
from uuid import uuid4
from passlib.hash import pbkdf2_sha512
from slugify import slugify
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref
from ..app import db
from ..domain.models import Domain
from... | none | 1 | 2.47512 | 2 | |
apps/external_apps/dbtemplates/cache.py | indro/t2c | 3 | 6623605 | import os
from django.conf import settings
from django.core.cache import cache
from django.template import TemplateDoesNotExist
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import smart_unicode, force_unicode
class BaseCacheBackend(object):
"""
Base class for custom cache ... | import os
from django.conf import settings
from django.core.cache import cache
from django.template import TemplateDoesNotExist
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import smart_unicode, force_unicode
class BaseCacheBackend(object):
"""
Base class for custom cache ... | en | 0.619798 | Base class for custom cache backend of dbtemplates to be used while subclassing. Set DBTEMPLATES_CACHE_BACKEND setting to the Python path to that subclass. Loads a template from the cache with the given name. Saves the given template content with the given name in the cache. Removes the template with the given... | 2.17045 | 2 |
examples/raspi/output_sensor_data.py | WeHaus/WeHaus_NodeJS_Client | 0 | 6623606 | #!/usr/bin/python
import sys
import Adafruit_DHT
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
print('{0:0.1f},{1:0.1f}'.format(temperature, humidity))
| #!/usr/bin/python
import sys
import Adafruit_DHT
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
print('{0:0.1f},{1:0.1f}'.format(temperature, humidity))
| ru | 0.258958 | #!/usr/bin/python | 2.642467 | 3 |
tests/requests_compat/test_api.py | mwoss/httpx | 1 | 6623607 | <reponame>mwoss/httpx
"""Test compatibility with the Requests high-level API."""
import pytest
import requests
@pytest.mark.copied_from(
"https://github.com/psf/requests/blob/v2.22.0/tests/test_requests.py#L61-L70"
)
def test_entrypoints():
requests.session
requests.session().get
requests.session().he... | """Test compatibility with the Requests high-level API."""
import pytest
import requests
@pytest.mark.copied_from(
"https://github.com/psf/requests/blob/v2.22.0/tests/test_requests.py#L61-L70"
)
def test_entrypoints():
requests.session
requests.session().get
requests.session().head
requests.get
... | en | 0.949581 | Test compatibility with the Requests high-level API. #L61-L70" #L72", # Not really an entry point, but people rely on it. # noqa: F401 | 2.329088 | 2 |
AMLS_19-20_ZHIDIAN_XIE_SN16077117/face_landmarks.py | RawTimmy/AMLSassignment19_20 | 1 | 6623608 | import os
import numpy as np
from keras.preprocessing import image
import cv2
import dlib
# PATH TO ALL IMAGES
# global basedir_celeba, basedir_cartoon, image_paths_celeba, image_paths_cartoon, target_size
global basedir_celeba, basedir_celeba_test, image_paths_celeba, image_paths_celeba_test, target_size
basedir_cel... | import os
import numpy as np
from keras.preprocessing import image
import cv2
import dlib
# PATH TO ALL IMAGES
# global basedir_celeba, basedir_cartoon, image_paths_celeba, image_paths_cartoon, target_size
global basedir_celeba, basedir_celeba_test, image_paths_celeba, image_paths_celeba_test, target_size
basedir_cel... | en | 0.726333 | # PATH TO ALL IMAGES # global basedir_celeba, basedir_cartoon, image_paths_celeba, image_paths_cartoon, target_size # basedir_cartoon = './Datasets/cartoon_set' # images_dir_cartoon = os.path.join(basedir_cartoon,'img') # how to find frontal human faces in an image using 68 landmarks. These are points on the face such... | 2.953247 | 3 |
src/python/WMQuality/Emulators/PyCondorAPI/MockPyCondorAPI.py | khurtado/WMCore | 21 | 6623609 | from __future__ import (division, print_function)
from builtins import object
class MockPyCondorAPI(object):
"""
Version of Services/PyCondor intended to be used with mock or unittest.mock
"""
def __init__(self, *args, **kwargs):
print("Using MockPyCondorAPI")
def getCondorJobsSummary(se... | from __future__ import (division, print_function)
from builtins import object
class MockPyCondorAPI(object):
"""
Version of Services/PyCondor intended to be used with mock or unittest.mock
"""
def __init__(self, *args, **kwargs):
print("Using MockPyCondorAPI")
def getCondorJobsSummary(se... | en | 0.78907 | Version of Services/PyCondor intended to be used with mock or unittest.mock Mock a condor query for the job summary Given a job/schedd constraint, return a list of jobs attributes or None if the query to condor fails. check whether job limit is reached in local schedd | 2.945413 | 3 |
docs/conf.py | titilambert/sphinxjp.themes.revealjs | 1 | 6623610 | # -*- coding: utf-8 -*-
#
# -- General configuration -----------------------------------------------------
source_suffix = '.rst'
master_doc = 'index'
project = u'sphinx theme for reveal.js'
copyright = u'2013, tell-k'
version = '0.1.1'
# -- Options for HTML output --------------------------------------------------... | # -*- coding: utf-8 -*-
#
# -- General configuration -----------------------------------------------------
source_suffix = '.rst'
master_doc = 'index'
project = u'sphinx theme for reveal.js'
copyright = u'2013, tell-k'
version = '0.1.1'
# -- Options for HTML output --------------------------------------------------... | en | 0.599509 | # -*- coding: utf-8 -*- # # -- General configuration ----------------------------------------------------- # -- Options for HTML output --------------------------------------------------- # -- HTML theme options for `revealjs` style ------------------------------------- # Set the lang attribute of the html tag. Default... | 1.232244 | 1 |
src/etl/speech_stats.py | dmegbert/prez-speech | 0 | 6623611 | from concurrent.futures import ThreadPoolExecutor, as_completed
from statistics import median
from psycopg2.extras import execute_values
import textstat
from sklearn.feature_extraction.text import CountVectorizer
from textblob import TextBlob
from src.db_utils import safe_cursor
def get_speech_stats(speech_id):
... | from concurrent.futures import ThreadPoolExecutor, as_completed
from statistics import median
from psycopg2.extras import execute_values
import textstat
from sklearn.feature_extraction.text import CountVectorizer
from textblob import TextBlob
from src.db_utils import safe_cursor
def get_speech_stats(speech_id):
... | none | 1 | 2.70919 | 3 | |
operations/operation.py | zylamarek/dataset-tools | 0 | 6623612 | from dataset import Dataset
class Operation:
def __init__(self, path_in, prepend_name='', is_sequence=False, keep_filenames=False, cache_out=False):
self.prepend_name = prepend_name
if path_in[-1] == '/' or path_in[-1] == '\\':
path_in = path_in[:-1]
self.path_in = path_in
... | from dataset import Dataset
class Operation:
def __init__(self, path_in, prepend_name='', is_sequence=False, keep_filenames=False, cache_out=False):
self.prepend_name = prepend_name
if path_in[-1] == '/' or path_in[-1] == '\\':
path_in = path_in[:-1]
self.path_in = path_in
... | none | 1 | 2.890172 | 3 | |
house/admin.py | SnailJin/house | 0 | 6623613 | <reponame>SnailJin/house
# -*- coding: utf-8 -*-
'''
Created on 2015年4月20日
@author: jin
'''
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from house.models import UserProfile
class UserProfileAdmin(admin.ModelAdmin):
pass
admin.site... | # -*- coding: utf-8 -*-
'''
Created on 2015年4月20日
@author: jin
'''
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from house.models import UserProfile
class UserProfileAdmin(admin.ModelAdmin):
pass
admin.site.register(UserProfile, Us... | zh | 0.643388 | # -*- coding: utf-8 -*- Created on 2015年4月20日 @author: jin | 1.60344 | 2 |
src/pairwise.py | sawyerWeld/PrefGAN | 0 | 6623614 | # pairwise.py
# The goal of this class is to take a batch of preferences and return either
# a matrix of their pairwise probabilities or a flattened vector of them
import readPreflib as pref
import numpy as np
import math
# Acts on a set of SOI vote tuples
def pairwise_from_votes(votes, num_candidates):
n = nu... | # pairwise.py
# The goal of this class is to take a batch of preferences and return either
# a matrix of their pairwise probabilities or a flattened vector of them
import readPreflib as pref
import numpy as np
import math
# Acts on a set of SOI vote tuples
def pairwise_from_votes(votes, num_candidates):
n = nu... | en | 0.83887 | # pairwise.py # The goal of this class is to take a batch of preferences and return either # a matrix of their pairwise probabilities or a flattened vector of them # Acts on a set of SOI vote tuples # print(vote) # print('~',after) # print(a_succ_b, b_succ_a) # Acts on a single np array # This one gives a negative one ... | 3.226279 | 3 |
profiles_api/serializers.py | UsamaNaseerBaig/django_rest_api | 0 | 6623615 | <reponame>UsamaNaseerBaig/django_rest_api<filename>profiles_api/serializers.py
from rest_framework import serializers
from profiles_api import models
class HelloSerializer(serializers.Serializer):
"""Serializers namefield for testing our api view """
name = serializers.CharField(max_length = 10)
class UserPro... | from rest_framework import serializers
from profiles_api import models
class HelloSerializer(serializers.Serializer):
"""Serializers namefield for testing our api view """
name = serializers.CharField(max_length = 10)
class UserProfileSerializer(serializers.ModelSerializer):
"""Serializer a user profile O... | en | 0.707246 | Serializers namefield for testing our api view Serializer a user profile Object Create and return a new user Serializer profile feed item | 2.58332 | 3 |
hosts-ldif/hosts-ldif.py | hfuru/mreg-tools | 0 | 6623616 | import argparse
import configparser
import io
import os
import pathlib
import sys
import fasteners
import requests
parentdir = pathlib.Path(__file__).resolve().parent.parent
sys.path.append(str(parentdir))
import common.connection
import common.utils
from common.utils import error, updated_entries
from common.LDIFu... | import argparse
import configparser
import io
import os
import pathlib
import sys
import fasteners
import requests
parentdir = pathlib.Path(__file__).resolve().parent.parent
sys.path.append(str(parentdir))
import common.connection
import common.utils
from common.utils import error, updated_entries
from common.LDIFu... | none | 1 | 2.207468 | 2 | |
gbe_browser/models-example.bk.py | whyrg/GlobalBiobankEngine | 0 | 6623617 | import scidbpy
import lookups
import utils
import numpy
db = scidbpy.connect()
gene_names = ['RUNX3'] # Set to None to get all genes
icds = ['HC49', 'HC382'] # Set to None to get all ICDs
# SciDB lookups
# ---
# return 1-dimension NumPy arrays
gene_variant = lookups.get_gene_variant(db, gene_names=... | import scidbpy
import lookups
import utils
import numpy
db = scidbpy.connect()
gene_names = ['RUNX3'] # Set to None to get all genes
icds = ['HC49', 'HC382'] # Set to None to get all ICDs
# SciDB lookups
# ---
# return 1-dimension NumPy arrays
gene_variant = lookups.get_gene_variant(db, gene_names=... | en | 0.620622 | # Set to None to get all genes # Set to None to get all ICDs # SciDB lookups # --- # return 1-dimension NumPy arrays #print(variant_icd[numpy.where(variant_icd['pos'] == 25243960)]) # List of attributes available in each array # --- # Some attributes will have `null` and `val` sub-attributes. `null` # stores the SciDB ... | 2.671485 | 3 |
setup.py | 02strich/django-auth-kerberos | 18 | 6623618 | #!/usr/bin/env python
from setuptools import setup, find_packages
import sys
if sys.platform.startswith("win"):
pykerberos = 'kerberos-sspi>=0.2'
else:
pykerberos = 'pykerberos>=1.1.10'
setup(
name="django-auth-kerberos",
version="1.2.5",
description="Kerberos authentication backend for Django",
... | #!/usr/bin/env python
from setuptools import setup, find_packages
import sys
if sys.platform.startswith("win"):
pykerberos = 'kerberos-sspi>=0.2'
else:
pykerberos = 'pykerberos>=1.1.10'
setup(
name="django-auth-kerberos",
version="1.2.5",
description="Kerberos authentication backend for Django",
... | ru | 0.26433 | #!/usr/bin/env python | 1.410067 | 1 |
mode/examples/Basics/Math/Noise3D/Noise3D.pyde | timgates42/processing.py | 1,224 | 6623619 | <reponame>timgates42/processing.py
"""
Noise3D.
Using 3D noise to create simple animated texture.
Here, the third dimension ('z') is treated as time.
"""
increment = 0.01
# The noise function's 3rd argument, a global variable that increments
# once per cycle
zoff = 0.0
# We will increment zoff differently than xof... | """
Noise3D.
Using 3D noise to create simple animated texture.
Here, the third dimension ('z') is treated as time.
"""
increment = 0.01
# The noise function's 3rd argument, a global variable that increments
# once per cycle
zoff = 0.0
# We will increment zoff differently than xoff and yoff
zincrement = 0.02
def ... | en | 0.751031 | Noise3D. Using 3D noise to create simple animated texture. Here, the third dimension ('z') is treated as time. # The noise function's 3rd argument, a global variable that increments # once per cycle # We will increment zoff differently than xoff and yoff # Optional: adjust noise detail here # noiseDetail(8,0.65f) # ... | 3.868169 | 4 |
pollers/poll-w1.py | JeffreyPowell/pi-van-mon | 0 | 6623620 | #!/usr/bin/python
import time
import datetime
import os
import yaml
config = yaml.safe_load(open("/home/pi/bin/van/config.yaml"))
#print( config )
for device in config['devices']['w1']:
#print( device )
add = str(config['devices']['w1'][device]['add'])
try:
x=1
except:
pass
#... | #!/usr/bin/python
import time
import datetime
import os
import yaml
config = yaml.safe_load(open("/home/pi/bin/van/config.yaml"))
#print( config )
for device in config['devices']['w1']:
#print( device )
add = str(config['devices']['w1'][device]['add'])
try:
x=1
except:
pass
#... | en | 0.885981 | #!/usr/bin/python #print( config ) #print( device ) # Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before. # Read all of the text in the file. # Close the file now that the text has been read. # Split the text with new lines (\n) and select the second line. # S... | 3.01116 | 3 |
evaluators/dialog/__init__.py | kaniblu/vhda | 3 | 6623621 | __all__ = ["BLEUEvaluator", "DistinctEvaluator", "SentLengthEvaluator",
"RougeEvaluator", "EmbeddingEvaluator", "DialogLengthEvaluator",
"WordEntropyEvaluator", "LanguageNoveltyEvaluator",
"StateEntropyEvaluator", "StateCountEvaluator",
"DistinctStateEvaluator", "StateNovelty... | __all__ = ["BLEUEvaluator", "DistinctEvaluator", "SentLengthEvaluator",
"RougeEvaluator", "EmbeddingEvaluator", "DialogLengthEvaluator",
"WordEntropyEvaluator", "LanguageNoveltyEvaluator",
"StateEntropyEvaluator", "StateCountEvaluator",
"DistinctStateEvaluator", "StateNovelty... | none | 1 | 1.175738 | 1 | |
Exercises of Python courses World1-2 and 3/ex039 - Alistamento Militar.py | RafaFurla/Python-Exercises | 1 | 6623622 | <reponame>RafaFurla/Python-Exercises<gh_stars>1-10
from datetime import date
d = int(input('In what day did you birth? '))
m = int(input('In what month did you birth? '))
y = int(input('In what year did you birth? '))
td = date.today().day
tm = date.today().month
ty = date.today().year
if ty < y+18:
difm = (12 - tm... | from datetime import date
d = int(input('In what day did you birth? '))
m = int(input('In what month did you birth? '))
y = int(input('In what year did you birth? '))
td = date.today().day
tm = date.today().month
ty = date.today().year
if ty < y+18:
difm = (12 - tm + m) / 12
dif = (y+18-1-ty+difm) // 1
prin... | none | 1 | 3.908863 | 4 | |
win_or_lost_each_day.py | hvnobug/stock | 3,401 | 6623623 | <reponame>hvnobug/stock
# -*-coding=utf-8-*-
__author__ = 'Rocky'
'''
http://30daydo.com
Contact: <EMAIL>
'''
'''
记录每天的盈亏情况 完成度100%
'''
import pandas as pd
import os
import tushare as ts
import datetime
def getCodeFromExcel(filename):
#从excel表中获取代码, 并且补充前面几位000
#获取股票数目
df=pd.read_excel(filename)
code_l... | # -*-coding=utf-8-*-
__author__ = 'Rocky'
'''
http://30daydo.com
Contact: <EMAIL>
'''
'''
记录每天的盈亏情况 完成度100%
'''
import pandas as pd
import os
import tushare as ts
import datetime
def getCodeFromExcel(filename):
#从excel表中获取代码, 并且补充前面几位000
#获取股票数目
df=pd.read_excel(filename)
code_list = df['证券代码'].values
... | zh | 0.270093 | # -*-coding=utf-8-*- http://30daydo.com Contact: <EMAIL> 记录每天的盈亏情况 完成度100% #从excel表中获取代码, 并且补充前面几位000 #获取股票数目 #后面学会了map函数,可以直接搞定 #print(percentage) #settlement=df[df['code'==code]]['settlement'].values #percentage=df[df['code'==code].index]['changepercent'].values #返回四舍五入的结果 #s2=pd.DataFrame({'当天涨幅':percentage_list}) #... | 3.036712 | 3 |
AutoExamSys/SystemModel/UsersClass/teacher.py | Yb-Z/COMP2411_GP | 0 | 6623624 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pandas as pd
'''
Functions
1. Get personal info.
...
TODO
'''
class Teacher(object):
def __init__(self, config):
self.id;
| #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pandas as pd
'''
Functions
1. Get personal info.
...
TODO
'''
class Teacher(object):
def __init__(self, config):
self.id;
| en | 0.253096 | #!/usr/bin/env python # -*- coding: UTF-8 -*- Functions 1. Get personal info. ... TODO | 2.645635 | 3 |
control_limits/__init__.py | papelero/control-limit-search | 0 | 6623625 | from .src import ControlLimits, plot_control_limits
| from .src import ControlLimits, plot_control_limits
| none | 1 | 1.032779 | 1 | |
tools/LoadAndFindIntelligibility.py | MaryamHoss/BESD | 0 | 6623626 | <reponame>MaryamHoss/BESD
# this will load noisy, clean and different predictions
import os, sys
import h5py as hp
import matplotlib.pyplot as plt
sys.path.append('../')
import tensorflow as tf
import numpy as np
sound_len = 87552 # 218880
from TrialsOfNeuralVocalRecon.tools.calculate_intelligibility import find_i... | # this will load noisy, clean and different predictions
import os, sys
import h5py as hp
import matplotlib.pyplot as plt
sys.path.append('../')
import tensorflow as tf
import numpy as np
sound_len = 87552 # 218880
from TrialsOfNeuralVocalRecon.tools.calculate_intelligibility import find_intel
from TrialsOfNeuralVo... | en | 0.399003 | # this will load noisy, clean and different predictions # 218880 #load noisy file #test_path= 'C:/Users/hoss3301/work/TrialsOfNeuralVocalRecon/data/Cocktail_Party/Normalized/' #test_path='D:/data/EEG processed data/luca way' #exp_folder='C:/Users/hoss3301/work/TrialsOfNeuralVocalRecon/experiments/CC/sisdr/with my chang... | 1.795098 | 2 |
codes_/1021_Remove_Outermost_Parentheses.py | SaitoTsutomu/leetcode | 0 | 6623627 | # %% [1021. Remove Outermost Parentheses](https://leetcode.com/problems/remove-outermost-parentheses/)
# 問題:一番外側の括弧を取り除け
class Solution:
def removeOuterParentheses(self, S: str) -> str:
res, n = "", 0
for s in S:
if s == "(":
if n:
res += "("
... | # %% [1021. Remove Outermost Parentheses](https://leetcode.com/problems/remove-outermost-parentheses/)
# 問題:一番外側の括弧を取り除け
class Solution:
def removeOuterParentheses(self, S: str) -> str:
res, n = "", 0
for s in S:
if s == "(":
if n:
res += "("
... | en | 0.2928 | # %% [1021. Remove Outermost Parentheses](https://leetcode.com/problems/remove-outermost-parentheses/) # 問題:一番外側の括弧を取り除け | 3.490901 | 3 |
model/model.py | codeKgu/BiLevel-Graph-Neural-Network | 20 | 6623628 | <reponame>codeKgu/BiLevel-Graph-Neural-Network
import torch.nn as nn
from config import FLAGS
from model.layers_factory import create_layers
class Model(nn.Module):
def __init__(self, data, config_layer_type='layer'):
super(Model, self).__init__()
self.train_data = data
self.interaction_... | import torch.nn as nn
from config import FLAGS
from model.layers_factory import create_layers
class Model(nn.Module):
def __init__(self, data, config_layer_type='layer'):
super(Model, self).__init__()
self.train_data = data
self.interaction_num_node_feat = data.dataset.interaction_num_no... | en | 0.720737 | # assume pred layer is second to last layer # Go through each layer except the last one. # acts = [self._get_ins(self.layers[0])] # may get KeyError/ValueError | 2.36872 | 2 |
miniFBFlask/queries.py | timruet/DBS_Project | 0 | 6623629 | <reponame>timruet/DBS_Project
import psycopg2
DATABASE = "postgres"
USER = "postgres"
PASSWORD = "<PASSWORD>"
def get_user_data_based_on_user_id(user_id):
conn = None
result = None
try:
conn = psycopg2.connect(host="localhost", database=DATABASE, user=USER, password=PASSWORD)
cur =... | import psycopg2
DATABASE = "postgres"
USER = "postgres"
PASSWORD = "<PASSWORD>"
def get_user_data_based_on_user_id(user_id):
conn = None
result = None
try:
conn = psycopg2.connect(host="localhost", database=DATABASE, user=USER, password=PASSWORD)
cur = conn.cursor()
cur.ex... | none | 1 | 3.278111 | 3 | |
database/database.py | AivGitHub/clutcher | 0 | 6623630 | import sqlite3
import pathlib
from clutcher import settings
from database import exception
class Row(sqlite3.Row):
def __init__(self, *args, **kwargs):
super(Row, self).__init__()
def get(self, attr, default_value: str = None) -> str:
try:
return self[attr]
except IndexEr... | import sqlite3
import pathlib
from clutcher import settings
from database import exception
class Row(sqlite3.Row):
def __init__(self, *args, **kwargs):
super(Row, self).__init__()
def get(self, attr, default_value: str = None) -> str:
try:
return self[attr]
except IndexEr... | en | 0.368847 | CREATE TABLE %s torrent ( id integer PRIMARY KEY, name text NOT NULL, torrent_path text, path_to_save text, ... | 2.743338 | 3 |
tools/toolchain_tester/toolchain_config.py | eseidel/native_client_patches | 4 | 6623631 | <reponame>eseidel/native_client_patches
# Copyright 2008 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
#
# Config file for various nacl compilation scenarios
#
import os
import sys
TOOLCHAIN_CONFIGS = {}
class ... | # Copyright 2008 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
#
# Config file for various nacl compilation scenarios
#
import os
import sys
TOOLCHAIN_CONFIGS = {}
class ToolchainConfig(object):
def __init__(... | de | 0.721475 | # Copyright 2008 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. # # Config file for various nacl compilation scenarios # ###################################################################### # ######################... | 2.008743 | 2 |
fsl/models/torch/__init__.py | yanncalec/few-shot-learning-benchmark | 0 | 6623632 | """PyTorch implementation.
"""
from .prototypical_networks import ProtoNet
| """PyTorch implementation.
"""
from .prototypical_networks import ProtoNet
| en | 0.5801 | PyTorch implementation. | 1.110532 | 1 |
app/enhanced_mapper/__init__.py | mappercore/mapper-core | 1 | 6623633 | <reponame>mappercore/mapper-core
from .cover import *
from .node import *
from .oracle import *
from .graph import *
from .mapper import *
# from .converter import *
from .visualization import * | from .cover import *
from .node import *
from .oracle import *
from .graph import *
from .mapper import *
# from .converter import *
from .visualization import * | en | 0.394251 | # from .converter import * | 0.937203 | 1 |
testbed_image/testbed_image.py | terop/env-logger | 0 | 6623634 | #!/usr/bin/env python3
"""A script for downloading the current FMI Testbed image. Prints an empty string on failure
and a filename where the latest Testbed image is stored on success."""
# See PIP requirements from testbed_image_requirements.txt
import sys
from datetime import datetime
import requests
from bs4 impor... | #!/usr/bin/env python3
"""A script for downloading the current FMI Testbed image. Prints an empty string on failure
and a filename where the latest Testbed image is stored on success."""
# See PIP requirements from testbed_image_requirements.txt
import sys
from datetime import datetime
import requests
from bs4 impor... | en | 0.632281 | #!/usr/bin/env python3 A script for downloading the current FMI Testbed image. Prints an empty string on failure and a filename where the latest Testbed image is stored on success. # See PIP requirements from testbed_image_requirements.txt Downloads the latest FMI Testbed image. Returns the image data on success an... | 2.716533 | 3 |
math/linereflection.py | mengyangbai/leetcode | 0 | 6623635 | class Solution:
def isReflected(self, points):
if (not points):
return True
dic = {}
sumx = 0
lenwithoutdup = 0
for point in points:
if point[1] not in dic:
dic[point[1]] = {point[0]}
sumx += point[0]
... | class Solution:
def isReflected(self, points):
if (not points):
return True
dic = {}
sumx = 0
lenwithoutdup = 0
for point in points:
if point[1] not in dic:
dic[point[1]] = {point[0]}
sumx += point[0]
... | en | 0.269796 | #print sumx, lenwithoutdup # two pointers #print lst[i], avgx, lst[j] | 3.23208 | 3 |
irrd/rpki/notifications.py | mirceaulinic/irrd | 94 | 6623636 | import itertools
import logging
from collections import defaultdict
from typing import Dict, List, Set
from irrd.conf import get_setting
from irrd.rpki.status import RPKIStatus
from irrd.rpsl.parser import RPSLObject
from irrd.rpsl.rpsl_objects import rpsl_object_from_text
from irrd.storage.database_handler import Dat... | import itertools
import logging
from collections import defaultdict
from typing import Dict, List, Set
from irrd.conf import get_setting
from irrd.rpki.status import RPKIStatus
from irrd.rpsl.parser import RPSLObject
from irrd.rpsl.rpsl_objects import rpsl_object_from_text
from irrd.storage.database_handler import Dat... | en | 0.855802 | Notify the owners/contacts of newly RPKI invalid objects. Expects a list of objects, each a dict with their properties. Contacts are resolved as any mnt-nfy, or any email address on any tech-c or admin-c, of any maintainer of the object. One email is sent per email address. # For each source, a multi-s... | 2.382303 | 2 |
Python/Ex028.py | renato-rt/Python | 0 | 6623637 | <gh_stars>0
from time import sleep
from random import randint
print('\033[1;34;47m-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\033[m')
print('Vou pensar em um número entre 0 e 5. Tente advinhar...')
print('\033[1;34;47m-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\033[m')
user = int(input('Em qual ... | from time import sleep
from random import randint
print('\033[1;34;47m-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\033[m')
print('Vou pensar em um número entre 0 e 5. Tente advinhar...')
print('\033[1;34;47m-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\033[m')
user = int(input('Em qual número estou... | none | 1 | 3.683389 | 4 | |
src/day10_mp.py | dev-mbusch/adventofcode2020 | 0 | 6623638 | <reponame>dev-mbusch/adventofcode2020
with open("input_files\day10_input_mp.txt") as file:
input = [int(value) for value in file.read().split("\n")]
# input = '''28
# 33
# 18
# 42
# 31
# 14
# 46
# 20
# 48
# 47
# 24
# 23
# 49
# 45
# 19
# 38
# 39
# 11
# 1
# 32
# 25
# 35
# 8
# 17
# 7
# 9
# 4
# 2
# 34
# 10
# 3'''
# ... | with open("input_files\day10_input_mp.txt") as file:
input = [int(value) for value in file.read().split("\n")]
# input = '''28
# 33
# 18
# 42
# 31
# 14
# 46
# 20
# 48
# 47
# 24
# 23
# 49
# 45
# 19
# 38
# 39
# 11
# 1
# 32
# 25
# 35
# 8
# 17
# 7
# 9
# 4
# 2
# 34
# 10
# 3'''
# input = input.split("\n")
# input = [i... | en | 0.528251 | # input = '''28 # 33 # 18 # 42 # 31 # 14 # 46 # 20 # 48 # 47 # 24 # 23 # 49 # 45 # 19 # 38 # 39 # 11 # 1 # 32 # 25 # 35 # 8 # 17 # 7 # 9 # 4 # 2 # 34 # 10 # 3''' # input = input.split("\n") # input = [int(value) for value in input] # print(input) # add charging outlet # add device's built in adapter # Part 2 # cut list... | 3.358563 | 3 |
app.py | jhanley-com/google-cloud-run-getting-started-python-flask | 5 | 6623639 | <reponame>jhanley-com/google-cloud-run-getting-started-python-flask<filename>app.py
import os
import logging
from flask import Flask
# Change the format of messages logged to Stackdriver
logging.basicConfig(format='%(message)s', level=logging.INFO)
app = Flask(__name__)
@app.route('/')
def home():
html = """
<html... | import os
import logging
from flask import Flask
# Change the format of messages logged to Stackdriver
logging.basicConfig(format='%(message)s', level=logging.INFO)
app = Flask(__name__)
@app.route('/')
def home():
html = """
<html>
<head>
<title>
Google Cloud Run - Sample Python Flask Example
</title>
</... | en | 0.301468 | # Change the format of messages logged to Stackdriver <html> <head> <title> Google Cloud Run - Sample Python Flask Example </title> </head> <body> <p>Hello Google Cloud Run World!</p> <a href="https://cloud.google.com/run/" target="_blank">Google Cloud Run Website</a> </body> </html> | 2.683525 | 3 |
tests/test_OcsGenericEntityCli.py | lsst-ts/ts_ocs_sequencer | 0 | 6623640 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# +
# import(s)
# -
from OcsGenericEntityCli import *
# +
# +
# __doc__ string
# _
__doc__ = """test of OcsGenericEntityCli"""
# +
# function: test_cli()
# -
def test_cli():
cli = None
try:
cli = OcsGenericEntityCli()
except OcsGenericEntityExcepti... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# +
# import(s)
# -
from OcsGenericEntityCli import *
# +
# +
# __doc__ string
# _
__doc__ = """test of OcsGenericEntityCli"""
# +
# function: test_cli()
# -
def test_cli():
cli = None
try:
cli = OcsGenericEntityCli()
except OcsGenericEntityExcepti... | en | 0.260135 | #!/usr/bin/env python # -*- coding: utf-8 -*- # + # import(s) # - # + # + # __doc__ string # _ test of OcsGenericEntityCli # + # function: test_cli() # - # + # function: test_parse_cli() # - | 2.265396 | 2 |
signals/signals/apps/related/models.py | gonzaloamadio/django-signals2 | 0 | 6623641 | from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
class RelatedModel(models.Model):
"""
Abstract model with basic info
"""
title = models.CharField(max_length=128, db_index=True, verbose_name='Name')
company = models.ForeignKey... | from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
class RelatedModel(models.Model):
"""
Abstract model with basic info
"""
title = models.CharField(max_length=128, db_index=True, verbose_name='Name')
company = models.ForeignKey... | en | 0.837208 | Abstract model with basic info Proposals of jobs Now we are not adding any new field. But we leave it open | 2.38551 | 2 |
Backdoor/server.py | Cyzerx/Penetration-testing-with-Python3 | 0 | 6623642 | <filename>Backdoor/server.py<gh_stars>0
import socket
import termcolor
import json
import os
def reliable_recv():
data = ''
while True:
try:
data = data + target.recv(1024).decode().rstrip()
return json.loads(data)
except ValueError:
continue
def reliable_se... | <filename>Backdoor/server.py<gh_stars>0
import socket
import termcolor
import json
import os
def reliable_recv():
data = ''
while True:
try:
data = data + target.recv(1024).decode().rstrip()
return json.loads(data)
except ValueError:
continue
def reliable_se... | en | 0.651109 | \n quit --> Quit session with the Target clear --> Clear the Screen cd *Directory Name* --> Changes directory on target system upload *File Name* --> Upload file ... | 2.613954 | 3 |
part2/ch11_protocol_buffer/pbuf_message_pb2.py | sorrowhill/17techs | 8 | 6623643 | <reponame>sorrowhill/17techs
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pbuf_message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as... | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pbuf_message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobu... | en | 0.481983 | # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: pbuf_message.proto # @@protoc_insertion_point(imports) # @@protoc_insertion_point(class_scope:Object2) # @@protoc_insertion_point(class_scope:Object) # @@protoc_insertion_point(class_scope:ProtobufMessage) # @@protoc_insertion_... | 1.324672 | 1 |
Sampling-Techniques/code.py | navinsingh1977/ga-learner-dsmp-repo | 0 | 6623644 | # --------------
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
# Code starts here
df = pd.read_csv(path)
#print(df.head())
df.INCOME = df.INCOME.str.replace('$','').str.replace(',','')
df.HOME_VAL = df.HOME_VAL.str.rep... | # --------------
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
# Code starts here
df = pd.read_csv(path)
#print(df.head())
df.INCOME = df.INCOME.str.replace('$','').str.replace(',','')
df.HOME_VAL = df.HOME_VAL.str.rep... | en | 0.434965 | # -------------- # Code starts here #print(df.head()) # Code ends here # -------------- # Code starts here # Code ends here # -------------- # Code starts here # Code ends here # -------------- # Code starts here # Code ends here # -------------- # code starts here # Code ends here # -------------- # code starts here #... | 3.03362 | 3 |
api/resolver.py | Babylonpartners/tf-bridge | 26 | 6623645 | from .tensor_bridge import \
classify, regress, predict, multi_inference, get_model_metadata
OP_DICT = {
'Classify': classify,
'Regress': regress,
'Predict': predict,
'MultiInference': multi_inference,
'GetModelMetadata': get_model_metadata
}
def tensor_bridge_api_resolver(operation_id):
... | from .tensor_bridge import \
classify, regress, predict, multi_inference, get_model_metadata
OP_DICT = {
'Classify': classify,
'Regress': regress,
'Predict': predict,
'MultiInference': multi_inference,
'GetModelMetadata': get_model_metadata
}
def tensor_bridge_api_resolver(operation_id):
... | none | 1 | 1.965883 | 2 | |
scripts/SaveRun.py | jeizenga/shasta | 0 | 6623646 | <reponame>jeizenga/shasta
#!/usr/bin/python3
import os
import shutil
import sys
# Get from the arguments the list of input fasta files and check that they all exist.
helpMessage = "This script copies a run to directories dataOnDisk and DataOnDisk."
if not len(sys.argv)==1:
print(helpMessage)
exit(1)
if not ... | #!/usr/bin/python3
import os
import shutil
import sys
# Get from the arguments the list of input fasta files and check that they all exist.
helpMessage = "This script copies a run to directories dataOnDisk and DataOnDisk."
if not len(sys.argv)==1:
print(helpMessage)
exit(1)
if not os.path.lexists('data'):
... | en | 0.622196 | #!/usr/bin/python3 # Get from the arguments the list of input fasta files and check that they all exist. | 2.962282 | 3 |
exercises_cv/mundo03/exCV079.py | BeatrizAlcantara/study_repository | 0 | 6623647 | # 79 Faça um programa que o usuário forneca vários valores numericos, e cadastre-os em uma lista. Caso o número já exista, ele não será adicionado. No fim, serão exibidos todos os valores únicos digitados, em ordem crescente.
def Main079():
numeros = list()
resposta = 's'
while resposta in ['S','s']:
... | # 79 Faça um programa que o usuário forneca vários valores numericos, e cadastre-os em uma lista. Caso o número já exista, ele não será adicionado. No fim, serão exibidos todos os valores únicos digitados, em ordem crescente.
def Main079():
numeros = list()
resposta = 's'
while resposta in ['S','s']:
... | pt | 0.997955 | # 79 Faça um programa que o usuário forneca vários valores numericos, e cadastre-os em uma lista. Caso o número já exista, ele não será adicionado. No fim, serão exibidos todos os valores únicos digitados, em ordem crescente. | 4.065845 | 4 |
matrix.py | RobinNash/Matrix | 0 | 6623648 | <reponame>RobinNash/Matrix<gh_stars>0
## matrix ##
## June, 2021 ##
## By <NAME> ##
'''
This module contains Matrix, Vector, and RowOp classes.
Matrix objects store entries as fractions and implement matrix operations.
Matrix also does more like RREF function implements Gaussian elimination/row reduction to return
a ma... | ## matrix ##
## June, 2021 ##
## By <NAME> ##
'''
This module contains Matrix, Vector, and RowOp classes.
Matrix objects store entries as fractions and implement matrix operations.
Matrix also does more like RREF function implements Gaussian elimination/row reduction to return
a matrix in reduced row echelon form.
Vec... | en | 0.757431 | ## matrix ## ## June, 2021 ## ## By <NAME> ## This module contains Matrix, Vector, and RowOp classes. Matrix objects store entries as fractions and implement matrix operations. Matrix also does more like RREF function implements Gaussian elimination/row reduction to return a matrix in reduced row echelon form. Vector ... | 3.966724 | 4 |
07_RSI/ch03/tostr.py | zzz0072/Python_Exercises | 0 | 6623649 | <gh_stars>0
#!/usr/bin/env python3
def toStr(num, base):
digitStr = "0123456789ABCDEF"
if num < base:
return digitStr[num]
else:
return toStr(num // base, base) + digitStr[num % base]
if __name__ == "__main__":
print(toStr(1200, 10))
print(toStr(255, 16))
| #!/usr/bin/env python3
def toStr(num, base):
digitStr = "0123456789ABCDEF"
if num < base:
return digitStr[num]
else:
return toStr(num // base, base) + digitStr[num % base]
if __name__ == "__main__":
print(toStr(1200, 10))
print(toStr(255, 16)) | fr | 0.221828 | #!/usr/bin/env python3 | 3.819789 | 4 |
common/templatetags/tools.py | riderflo85/common-framework | 0 | 6623650 | # coding: utf-8
from django.http import QueryDict
from django.template import Library
from django.utils.formats import localize
register = Library()
@register.filter(name='meta')
def filter_meta(instance, key):
"""
Récupération d'une métadonnée sur une instance
:param key: Clé
:return: Valeur
""... | # coding: utf-8
from django.http import QueryDict
from django.template import Library
from django.utils.formats import localize
register = Library()
@register.filter(name='meta')
def filter_meta(instance, key):
"""
Récupération d'une métadonnée sur une instance
:param key: Clé
:return: Valeur
""... | fr | 0.926917 | # coding: utf-8 Récupération d'une métadonnée sur une instance :param key: Clé :return: Valeur Parse une date ou un datetime dans n'importe quel format :param value: Date ou datetime au format texte :param options: Options de parsing (au format query string) :return: Date ou datetime Permet de récup... | 2.031891 | 2 |