seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
11194223295 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Use this to execute the differential kinematics
controller in our kinecontrol paper.
'''
from __future__ import print_function
import Sofa
import math
import sys, os
import time
import logging
import datetime
import numpy as np
from utils import *
from config import *... | robotsorcerer/superchicko | sofa/python/kinecontrol/diff_kine_controller.py | diff_kine_controller.py | py | 11,135 | python | en | code | 0 | github-code | 36 |
43221995512 | # 1
from selenium import webdriver
from math import log, sin
browser = webdriver.Chrome()
# Открыть страницу http://suninjuly.github.io/get_attribute.html
browser.get('http://suninjuly.github.io/get_attribute.html')
# Найти на ней элемент-картинку/ Взять у этого элемента значение атрибута valuex
valuex = browser.fin... | Rzktype/StepikPythonCourses | Module 2/lesson2-1_step7_anotherDecisions.py | lesson2-1_step7_anotherDecisions.py | py | 2,614 | python | ru | code | 0 | github-code | 36 |
25446749830 | """
Run correlation analysis asking if lucidity during the dream task influenced reported wakeup time.
"""
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pingouin as pg
import utils
################################################################################
# SETUP
#########... | remrama/wakeup | wakeup_lucidity.py | wakeup_lucidity.py | py | 2,944 | python | en | code | 0 | github-code | 36 |
22767714265 | import sys
import random
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
##################################################################################################################################
##########################################################################################... | maal22/Tesis_Licenciatura | tesis_Egolf_ergodicidad4_2.py | tesis_Egolf_ergodicidad4_2.py | py | 10,416 | python | es | code | 0 | github-code | 36 |
26626836853 | import astropy.units as u
from astropy.coordinates.sky_coordinate import SkyCoord
from astropy.units import Quantity
from astropy.table import Table
from scipy import stats
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
import astropy.coordinates as asc
import numpy as np
import random
import csv... | spacer730/Gaia_research | Overdensities-Propermotion-Graph.py | Overdensities-Propermotion-Graph.py | py | 3,287 | python | en | code | 0 | github-code | 36 |
33210794674 | from enum import Enum
from typing import List
import numpy as np
import torch
from nemo import logging
from nemo.backends.pytorch.nm import DataLayerNM
from nemo.core.neural_types import *
__all__ = ['MultiDataLayer', 'DataCombination']
class DataCombination(Enum):
CROSSPRODUCT = 1
ZIP = 2
class MultiDat... | cppxaxa/ICAN.ShapeShifter | ICAN.ShapeShifter.Worker/nemo/backends/pytorch/common/multi_data.py | multi_data.py | py | 4,014 | python | en | code | 0 | github-code | 36 |
12954890166 | #!/usr/bin/env python
import os
import re
import sys
import json
import random
import argparse
from checks import cors
from checks import cookie
from core.requester import requester
from core.colors import red, green, white, info, bad, end
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--url', help='ur... | s0md3v/meta | meta.py | meta.py | py | 2,604 | python | en | code | 37 | github-code | 36 |
18132978929 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
import re
import matplotlib.pyplot as plt
import keras
from tensorflow import keras
from keras.layers import Dense, SimpleRNN, Input, Embedding
from keras.models import Sequential
from keras.optimizers import Adam
from keras.preprocessing.text im... | Sautenko-Andrey/ML_practice | RNN_words_predict.py | RNN_words_predict.py | py | 9,910 | python | ru | code | 0 | github-code | 36 |
12256071208 | # 3. Добавьте в пакет, созданный на семинаре шахматный модуль. Внутри него напишите код, решающий задачу о 8 ферзях.
# Известно, что на доске 8×8 можно расставить 8 ферзей так, чтобы они не били друг друга.
ROWS = 8
COLS = 8
START_POINT = 0
def creating_chessboard() -> list:
return [['_' for _ in range(ROWS)] fo... | BespilotNick/Python_DE | Seminar_6/chess_mod_var_1.py | chess_mod_var_1.py | py | 1,457 | python | ru | code | 0 | github-code | 36 |
25014074159 | from collections import defaultdict
import yaml
import json
def redial_config(path,data_type):
def _entity_kg_process(opt, SELF_LOOP_ID=185):
edge_list = [] # [(entity, entity, relation)]
for entity in range(opt['n_entity']):
if str(entity) not in opt['entity_kg']:
cont... | Oran-Ac/LOT-CRS | src/utils/config.py | config.py | py | 3,493 | python | en | code | 1 | github-code | 36 |
18690677704 | from analyzer.SentiWordNetScores import SentiWordNetScores
ADJECTIVE_CLASS_NAME = "adjective"
POSITIVE_CLASS_NAME = "positive"
NEGATIVE_CLASS_NAME = "negative"
NOUN_CLASS_NAME = "noun"
class AdjectiveUse:
"""contains information about an adjective, what it refers to and the context in which it is used"""
se... | MMthesis2019/ReviewAnalyzer | analyzer/AdjectiveUse.py | AdjectiveUse.py | py | 2,941 | python | en | code | 0 | github-code | 36 |
6821894680 |
import pandas as pd
from flask import Flask
from flask import render_template
import logging
import json
import os
import glob
from tools import *
data = loadData()
neg = "marian"
t = "Gorras_rotas"
firsts = [data["negs"][neg]["images"][t][x]["images"][0]
for x in data["negs"][neg]["images"][t].keys()]
... | Paradis4432/wsbot | web/tempTest.py | tempTest.py | py | 2,133 | python | en | code | 0 | github-code | 36 |
35919702620 | import difflib
import redis
from pymongo import MongoClient, ASCENDING
client = MongoClient('mongodb+srv://Alex:goit123@utcluster.zrkwr.mongodb.net/myFirstDatabase?retryWrites=true&w=majority')
def command_assistant():
commands = ['add', 'show', 'delete', 'show_all', 'exit', 'update'] # list... | AlexUtchenko/goit-python | WEB10/PA_Mongo_Redis.py | PA_Mongo_Redis.py | py | 4,755 | python | en | code | 0 | github-code | 36 |
30722582331 | #baekjoon_23757_2021고려대학교 프로그래밍 경시대회
#=== import module ===#
import heapq
import sys
input = sys.stdin.readline
#=== variable declare ===#
#=== Function define ===#
#=== main function ===#
N,M = map(int,input().split());
presents = list(map(int,input().split()));
wishNum = list(map(int,input().split()));
q = [];
... | Hoony0321/Algorithm | 2021_12/10/baekjoon_23757.py | baekjoon_23757.py | py | 662 | python | en | code | 0 | github-code | 36 |
28986020651 | EXPECTED_TEST_ANSWER_PART1 = [15]
EXPECTED_TEST_ANSWER_PART2 = [12]
OP_MOVES = ["A", "B", "C"]
YOUR_MOVES = ["X", "Y", "Z"]
def get_shape_score(move):
"""
Determine the move's score (not if you win or lose)
"""
if move == "A" or move == "X":
# Rock
return 1
elif move == "B" or mov... | SocialFinanceDigitalLabs/AdventOfCode | solutions/2022/pughmds/day02/__main__.py | __main__.py | py | 1,808 | python | en | code | 2 | github-code | 36 |
19066422289 | name = ""
contact = ""
enrollno = ""
username = ""
quiz_choice = ""
questions = {
"python": [
{
'question': 'What is Python?',
'options': ['A type of snake', 'A programming language', 'A bird', 'A dessert'],
'correct_answer': 'A programming language',
... | Himanshu-dy/Intern-Army | Online Quiz System.py | Online Quiz System.py | py | 3,975 | python | en | code | 0 | github-code | 36 |
5238797489 | from sklearn.tree import DecisionTreeClassifier
from DataUtils import getTokens, modelfile_path, vectorfile_path
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer
def getDataFromFile(filename):
with open(filename, "r", encoding="utf8") as f:
inputurls, y = [], []
for... | zzhdbw/WebsiteClassification-main | cheater_classifier_ML/predict.py | predict.py | py | 1,076 | python | en | code | 1 | github-code | 36 |
15680325535 | import random
number = random.randint(1, 10)
tries = 3
def get_input(prompt_text, type, **kwargs):
user_res = input(prompt_text)
if type(user_res) == type:
print(f"Your response is incorrect. Please provide a value of type {type}")
return get_input(prompt_text, type, kwargs)
user_res = ... | csukel/rest-api-flask-and-python | python-refresher/11_loops/code.py | code.py | py | 1,188 | python | en | code | 0 | github-code | 36 |
8472917150 | #!/usr/bin/python3
##
##
import os,sys,re
import requests
import time
# Global variables
BASE_URL = "https://api.thousandeyes.com"
USERNAME = "your_username"
PASSWORD = "your_password"
API_TOKEN = None
def get_api_token():
global API_TOKEN
auth_endpoint = BASE_URL + "/v6/auth/login"
data = {
"u... | babywyrm/sysadmin | pyth3/api/check_revoke_.py | check_revoke_.py | py | 2,547 | python | en | code | 10 | github-code | 36 |
17811464587 | import boto3
from pprint import pprint
import time
aws_console=boto3.session.Session()
ec2_console=aws_console.resource('ec2', region_name='us-east-1')
# #ec2_console.start_instances(instance_id=['i-06186ed7e182cc28b'])
# response=ec2_console.describe_instances(InstanceIds=['i-06186ed7e182cc28b'])
# #pprint(response... | SachinPitale/AWS_Lambda | 05-waiters/01-ec2-status.py | 01-ec2-status.py | py | 868 | python | en | code | 0 | github-code | 36 |
15317046420 | #!/usr/bin/env python3
# encoding: utf-8
import string
CODE = """
Cbcq Dgyk!
Dmeybh kce cew yrwyg hmrylyaqmr:
rylsjb kce y Nwrfml npmepykmxyqg lwcjtcr!
Aqmimjjyi:
Ynyb
"""
def main():
alphabet = list(string.ascii_lowercase)
solution = ""
for i in range(len(CODE)):
char = CODE[i]
if cha... | Psychol0g1st/ScriptLanguages | L3/rejtelyes_uzenet.py | rejtelyes_uzenet.py | py | 826 | python | en | code | 0 | github-code | 36 |
15166686250 | from matplotlib import pyplot as plot
plot.rcParams [ "savefig.facecolor" ] = "w"
plot.rcParams [ "savefig.edgecolor" ] = "b"
lab_value , title_numb = 'Lab_None' , 0
def setLab ( text = None ) :
global lab_value
if text : lab_value = text
print ( 'lab value:' , lab_value )
def save () :
global t... | AmalLight/deepL_RL | saveFigure.py | saveFigure.py | py | 2,204 | python | en | code | 0 | github-code | 36 |
13159739208 | #!/usr/bin/python
import main.distribution as worker
if __name__ == '__main__':
server = worker.Server()
server.check_probe()
availability, performance = server.get_warning_from_baseline()
server.notify_me(data=availability, type='availability')
server.notify_me(data=performance, type='performance... | pdeesawat4887/python-cgi-monitor | server/running_server.py | running_server.py | py | 322 | python | en | code | 0 | github-code | 36 |
3650201755 | import random
from users import users
from random import randrange
from datetime import timedelta,datetime
#LEVEL TIMESTAMP METHOD API STATUS USERID
def random_date(start= datetime.now()-timedelta(days=120), end=datetime.now()):
"""
This function will return a random datetime between two datetime
object... | Prashantpx-17237/Datahub | datascripts/serverlog.py | serverlog.py | py | 1,666 | python | en | code | 0 | github-code | 36 |
15903708519 | import os
import numpy as np
path = os.path.dirname(os.path.realpath(__file__))
def bingo(numbers:list, boards:list, play2loose:bool=False):
def play(boards, number):
for b in range(len(boards)):
for r in range(5):
for c in range(5):
if boards[b][r][c] == nu... | coolafabbe/AdventOfCode2021 | Mikel/Day4/main.py | main.py | py | 2,792 | python | en | code | 0 | github-code | 36 |
7228924054 | import json
import logging
import os
from uuid import uuid4
from sqlalchemy import and_
from log import Msg
from helper import Now, model_to_dict, Http_error, value, check_schema
from .model import Event
from user.controller import get_profile
def add(data, username, db_session):
logging.info(Msg.START)
re... | nsmseifi/Bellezza | event/controller.py | controller.py | py | 3,930 | python | en | code | 0 | github-code | 36 |
70879441703 | class NameTooShortError(Exception):
def __init__(self, message="Name must be more than 4 characters"):
self.message = message
super().__init__(message)
class MustContainAtSymbolError(Exception):
def __init__(self, message="Email must contain @"):
self.message = message
... | AngelValAngelov/Python-Advanced-Exercises | Exercise Error Handling/2. Email Validator.py | 2. Email Validator.py | py | 1,284 | python | en | code | 0 | github-code | 36 |
22811929801 | from flask import Flask, render_template
from gevent.pywsgi import WSGIServer
from strategy_thread import StrategyThread
import atexit
from apscheduler.schedulers.background import BackgroundScheduler
from copy import deepcopy
import time
import pandas as pd
#########################################################... | zQuantz/Logma | ibapi/ui/retrace.py | retrace.py | py | 2,714 | python | en | code | 0 | github-code | 36 |
32736730593 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 3/9/19 7:49 PM
# @Author : zchai
import itertools
import os
import torch
from allennlp.data.dataset_readers.seq2seq import Seq2SeqDatasetReader
from allennlp.data.iterators import BucketIterator
from allennlp.data.token_indexers import SingleIdTokenIndexer
fr... | adamsZQ/couplet_generator | couplet_generator/seq2seq_allen.py | seq2seq_allen.py | py | 4,703 | python | en | code | 0 | github-code | 36 |
18114969380 | #!/usr/bin/env python3
from enum import Enum
from io import BytesIO
from itertools import count
from struct import pack
import csv
import sys
usage = 'To use this script, run it in a directory containing csv files generated by par2csv. It will compile them back into a new EARTH2150.par in the same directory.'
clas... | InsideEarth2150/Programming | Tools/Community Tools/Ninetailed/earth-2150/csv2par.py | csv2par.py | py | 8,490 | python | en | code | 1 | github-code | 36 |
8128484100 | import electra_class
from transformers import ElectraForQuestionAnswering, ElectraTokenizer
model_name = "ahotrod/electra_large_discriminator_squad2_512"
model = ElectraForQuestionAnswering.from_pretrained(model_name)
tokenizer = ElectraTokenizer.from_pretrained(model_name)
while(True):
context = input("Enter Tar... | gale2307/Jarvis | electra_test.py | electra_test.py | py | 754 | python | en | code | 1 | github-code | 36 |
4397820007 | import os
from shutil import copyfile
from unittest.mock import patch, Mock
import pytest
from ow import migrate
class TestMigrateUnit(object):
def test_includeme(self):
config = Mock()
migrate.includeme(config)
config.scan.assert_called_with('ow.migrate')
@patch('ow.migrate.run_mig... | openworkouts/OpenWorkouts | ow/tests/test_migrate.py | test_migrate.py | py | 5,768 | python | en | code | 5 | github-code | 36 |
20324223182 | from pymongo import MongoClient
def get_db(database):
"""
A quick way to get MongoDb Client link
"""
clientmg=MongoClient()
db=clientmg[database]
return db
db=get_db("foundation")
plist=db.process.find({},{"price":1,"qtt":2})
for p in plist:
ttlamt=float(float(p["price"])*float(p["qtt"]))
db.process.update({"_i... | raynardj/terminus | major/mongo/pricefloat.py | pricefloat.py | py | 372 | python | en | code | 0 | github-code | 36 |
24500666134 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Helper functions and classes."""
from typing import Callable, Iterable, List, Mapping, Tuple, Type
import string
import functools
_registry = dict()
_printable = set(string.printable)
class MultiMethod:
"""
Representation of an overloaded method.
Takes ... | learnitall/glo | glo/helpers.py | helpers.py | py | 7,497 | python | en | code | 0 | github-code | 36 |
17111518684 | class Solution(object):
def longestCommonPrefix(self, strs):
"""
:param strs: List[str]
:return: str
"""
if not strs:
return ""
for i in range(len(strs[0])):
for str in strs:
if len(str) <= i or strs[0][i] != str[i]:
... | yannweb/yanns_code | code/014.py | 014.py | py | 1,310 | python | en | code | 1 | github-code | 36 |
12728217384 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: mo-mo-
#
# Created: 08/09/2018
# Copyright: (c) mo-mo- 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
... | mo-mo-666/AtCoder | legacy/ABC_109/D2.py | D2.py | py | 1,502 | python | en | code | 0 | github-code | 36 |
29378709444 | from flask import Blueprint, request, session
from database.service.location import Location as LocationSvc
from database.service.user import User as UserSvc
from database.service.device import Device as DeviceSvc
from database.service.property import Property as PropertySvc
from database.service.exceptions import NoRe... | Wolfie-Home/webserver2 | wolfie_home/api_mqtt.py | api_mqtt.py | py | 2,763 | python | en | code | 6 | github-code | 36 |
9194439636 | # coding: utf-8
"""
Lightly API
Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501
OpenAPI spec version: 1.0.0
Contact: support@lightly... | tibe97/thesis-self-supervised-learning | lightly/openapi_generated/swagger_client/models/job_status_data.py | job_status_data.py | py | 9,149 | python | en | code | 2 | github-code | 36 |
7535863812 | from django.test import TestCase, Client, tag
from djangoplicity.media.models import Video
@tag('frontpage')
class TestFrontPageApp(TestCase):
fixtures = ['test/pages', 'test/media', 'test/announcements', 'test/releases', 'test/highlights']
def setUp(self):
self.client = Client()
def test_homepa... | esawebb/esawebb | webb/frontpage/tests.py | tests.py | py | 990 | python | en | code | 0 | github-code | 36 |
1429552952 | n = int(input())
a = [int(input()) for _ in range(n)]
imax = max(a)
b = sorted(a)
#print(imax)
for i in range(n):
if not a[i] == imax:
print(imax)
else:
print(b[n-2]) | nawta/atcoder_archive | atcoder.jp/abc134/abc134_c/Main.py | Main.py | py | 191 | python | en | code | 0 | github-code | 36 |
27187104573 | import sys
import pandas as pd
from run_vcp import run_vcp
def main(params, vcmd, protocol_name):
# Get model_ndx
ndx = params.model_ndx
num_models = params.shape[0]
for i in range(num_models):
run_vcp(params.iloc[i, 1:14], model_ndx=ndx[i], vc_data=vcmd, protocol_name=protocol_name)
if __... | dtilley/EA_fit_to_AP_set | main_run_vcp.py | main_run_vcp.py | py | 667 | python | en | code | 0 | github-code | 36 |
42154845618 | # 연속된 부분 수열의 합
def solution(sequence, k):
answer = []
left,right=0,1
max_seq=len(sequence)+1
prefix_sum=[0]*(max_seq)
tmp=0
for i in range(0,len(sequence)):
tmp+=sequence[i]
prefix_sum[i+1]=tmp
while left<right and right<len(prefix_sum):
current_v=(prefix_sum[right]-p... | FeelingXD/algorithm | programers/178870.py | 178870.py | py | 592 | python | en | code | 2 | github-code | 36 |
23420574740 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('stock', '0201_auto_20160926_1614'),
]
operations = [
migrations.RenameField(
model_name='transferenciastock',
... | pmmrpy/SIGB | stock/migrations/0202_auto_20160926_1825.py | 0202_auto_20160926_1825.py | py | 1,333 | python | es | code | 0 | github-code | 36 |
72201720423 | import argparse
import transformers
from transformers import AutoModel, AutoTokenizer
import numpy as np
import torch
import logging
from pathlib import Path
from os.path import exists
import os
import pandas as pd
from tqdm import tqdm
from datasets import load_dataset
from transformers import AutoTokenizer, DataColl... | RishanthRajendhran/influenceFunctions | model.py | model.py | py | 13,479 | python | en | code | 0 | github-code | 36 |
24185040460 | # for 目标 in 表达式: 最常搭配range,break,continue;
# 循环体
favour = "yanchao"
for i in favour:
print(i, end="-") # end=是用来连接
member = ["小甲鱼", "小布丁", "小乌龟", "王八"]
for each in member:
print(each, len(each)) # len是计算长度并返回;
# range()内置函数,语法:range([start,]stop[,step=1]),这个BIF有3个参数,用中括号扩起来的是表示可选;
# step默认是1,如果是2,则从开始的那个... | hewuling001/python-learn | index8.py | index8.py | py | 1,871 | python | zh | code | 1 | github-code | 36 |
25059204376 | import numpy as np
from mat import A2195_T84
def get_sphere_mass(r, p, material):
# for a given pressure and target stress allowable, this function gets
# mass of a material
A = 4*np.pi*r**2
t = get_hoop_t(r, p, material)
m = A*t*material.get("rho")
return m
def get_hoop_t(r, p, material):
... | C08-System-Design/WP5 | test.py | test.py | py | 964 | python | en | code | 0 | github-code | 36 |
41797269228 | from django.core.management.base import BaseCommand
from django.conf import settings
import requests
import json
import telebot
from telebot import types
from crypton.models import Profile
from preferences import preferences
bot = telebot.TeleBot(settings.TOKEN)
coins = {
'BTC': ['btc', 'bitcoin', 'биткоин'],
... | iterweb/test_bot | crypton/management/commands/tg_bot.py | tg_bot.py | py | 2,340 | python | en | code | 0 | github-code | 36 |
13404192861 | import warnings, logging, os, sys
warnings.filterwarnings('ignore',category=FutureWarning)
logging.disable(logging.WARNING)
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import json
import tensorflow as tf
from utils import *
from arguments import get_args_many
args = get_args_many()
MDIR = args.MDIR
n2d_layers ... | gjoni/trRosetta | network/predict_many.py | predict_many.py | py | 4,388 | python | en | code | 192 | github-code | 36 |
42305321529 | import sqlite3
import DepartmentStudentAmounts as dsa
Database = sqlite3.connect('Identities')
items = Database.cursor()
"""class used to validate the adding none year group specific items
Attributes
-----------
private Attributes
---> name item
---> average
---> department
"""
class v... | newton124/code | AddingItem.py | AddingItem.py | py | 5,597 | python | en | code | 0 | github-code | 36 |
29884273423 | """[Recommend] iPhone 13 Again"""
def main():
"""iPhone 13 Again"""
model = input()
capacity = input()
result = ""
case1 = capacity == '128 GB' or capacity == '256 GB' or capacity == '512 GB'
case2 = capacity == '128 GB' or capacity == '256 GB' or \
capacity == '512 GB' or capacity == '1... | DefinitelyNotJay/ejudge | Iphone13.py | Iphone13.py | py | 1,043 | python | en | code | 0 | github-code | 36 |
8651855944 | import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
service... | PCPuja/FirstGit | Waits.py | Waits.py | py | 2,198 | python | en | code | 0 | github-code | 36 |
31320163241 | import pandas as pd
import pymongo
from .metacritic_scrape import scrape_game_page
from .pandas_functions import clean_df
from selenium.webdriver import Firefox
import random
import time
mc = pymongo.MongoClient()
db =mc['game_recommender']
reviews_coll = db['reviews']
games=db['games']
#omc=pymongo.MongoClient()
#cb... | loeschn/Video-Game-Recommender | Notebooks/notebook_src/make_preference_matrix.py | make_preference_matrix.py | py | 2,145 | python | en | code | 0 | github-code | 36 |
74050766504 | from parlai.utils.safety import OffensiveLanguageClassifier
from parlai.utils.safety import OffensiveStringMatcher
from parlai.utils.testing import skipUnlessBPE, skipUnlessGPU
import unittest
DEFINITELY_GOOD = [
'hey how are you',
'what is your name?',
'i like to play sports',
'i have a horse',
]
PR... | facebookresearch/ParlAI | tests/nightly/gpu/test_safety_modules.py | test_safety_modules.py | py | 1,247 | python | en | code | 10,365 | github-code | 36 |
29580682652 | #!/usr/local/bin/py
import argparse
import hashlib
import logging
import os
import oss2 # pip install oss2
import re
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger('oss2').setLevel(logging.WARNING)
logging.basicConfig(
level=logging.INFO,
format='[%(asctime)s][%(levelname)s] %(messa... | mitnk/oss-sync | sync.py | sync.py | py | 12,601 | python | en | code | 0 | github-code | 36 |
28525524930 | import pygame, time, random
from cars import car
from things import thing
from shooting_thing import shoot
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
random_color = (random.ra... | maoriole/car-game | game_car.py | game_car.py | py | 10,448 | python | en | code | 0 | github-code | 36 |
9044988683 | from __future__ import annotations
from abc import abstractmethod, ABC
from typing import Optional
from api.mvc.controller.content_model.i_content_model_controller import IContentModelController
from api.mvc.controller.project.i_project_controller import IProjectController
from api.mvc.controller.property.i_property_... | seedbaobab/alfresco_helper | api/mvc/controller/data/data_controller.py | data_controller.py | py | 13,805 | python | en | code | 0 | github-code | 36 |
1529604811 | import pandas as pd
df = pd.read_csv('HappinessIndex.csv')
dff = pd.DataFrame(df)
#Country with largest population
col = "pop2022"
max_pop = dff.loc[dff[col].idxmax()]
print("Country with the largest population and its corresponding rank, happines index in 2020 and 2021: ")
print( max_pop)
#Country with smallest popu... | sabb7296/Assignment-Stage1 | Asm_Stage1/Data Summaries/HI_summary.py | HI_summary.py | py | 740 | python | en | code | 0 | github-code | 36 |
28522011627 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
from urbansim.gridcell.has_SSS_buildings import has_SSS_buildings as gridcell_has_SSS_buildings
from variable_functions import my_attribute_label
c... | psrc/urbansim | urbansim/zone/has_SSS_buildings.py | has_SSS_buildings.py | py | 2,176 | python | en | code | 4 | github-code | 36 |
20658918357 | """Computes eigenvalues and eigenvectors of the PMI similarity matrices for a given attribute type. Saves the results of this along with kMeans clustering of the attributes, and the assignment of graph nodes to clusters."""
import pickle
import time
import numpy as np
import pandas as pd
import optparse
from scipy.spa... | jeremander/Gplus | factor_attr_mat.py | factor_attr_mat.py | py | 11,356 | python | en | code | 2 | github-code | 36 |
28224836636 | import random
from string import ascii_letters
from typing import Any, Generator
def data_stream_gen(
total_length: int | None = None, element_length: int = 100
) -> Generator[str, None, None]:
if total_length is None:
total_length == float("inf")
idx = 0
while idx < total_length:
elem... | HomayoonAlimohammadi/Training | DailyProblem/2_7_2022.py | 2_7_2022.py | py | 1,104 | python | en | code | 2 | github-code | 36 |
44392387615 | import falcon
from routes.user import UserRoutes
from routes.workspace import WorkspaceRoutes
from routes.display import DisplayRoutes
from routes.token import TokenRoutes
from routes.scene import SceneRoutes
from routes.slide import SlideRoutes
from falcon.http_status import HTTPStatus
class HandleCORS(object):
def ... | Silassales/Displayly | backend/main.py | main.py | py | 1,942 | python | en | code | 0 | github-code | 36 |
33040434381 | import asyncio
import dataclasses
import time
from secrets import token_bytes
from typing import Callable, Dict, List, Optional, Tuple, Set
from blspy import AugSchemeMPL, G2Element
from chiabip158 import PyBIP158
import chia.server.ws_connection as ws
from chia.consensus.block_creation import create_unfinished_block... | snight1983/chia-rosechain | chia/full_node/full_node_api.py | full_node_api.py | py | 61,930 | python | en | code | 369 | github-code | 36 |
9556425028 | def gen(num):
while num > 0:
yield num
num -=1
return
if __name__ == "__main__":
# gen(): generator function
# g: generator object
g = gen(5)
first = next(g)
for i in g:
print(i) | viperyl/Notes | Book/Temp/example1.py | example1.py | py | 232 | python | en | code | 3 | github-code | 36 |
15215617350 | # -*- coding: utf-8 -*-
from get_data import getData
import numpy as np
import matplotlib.pyplot as plt
from lung_mask import getLungMask
from keras.models import Model
from keras.layers import Input, BatchNormalization, Activation, Dropout
from keras.layers.convolutional import Conv3D, Conv3DTranspose
from keras.la... | franciscapessanha/Pulmonary-nodules-analysis | CNN_segmentation_3D.py | CNN_segmentation_3D.py | py | 12,525 | python | en | code | 1 | github-code | 36 |
21203385181 | from pyramid_promosite.models import (
DBSession,
Page,
)
from pyramid.view import view_config
@view_config(route_name='admin',
renderer='admin/index.jinja2',
permission="authenticated")
def admin(request):
pages = DBSession.query(Page).filter(Page.orign_page_id == 0).\
... | uralbash/pyramid_promosite | pyramid_promosite/views/admin.py | admin.py | py | 386 | python | en | code | 12 | github-code | 36 |
38092864913 | import abc
import collections
import copyreg
import enum
import functools
import inspect
import logging
import operator
import random
import string
import typing
from .. import _exception, _struct
from . import series
if typing.TYPE_CHECKING:
from forml.io import dsl
LOGGER = logging.getLogger(__name__)
class... | formlio/forml | forml/io/dsl/_struct/frame.py | frame.py | py | 30,727 | python | en | code | 103 | github-code | 36 |
10837351756 | def fun(s):
# return True if s is a valid email, else return False
username = s.split("@")[0] if "@" in s else ""
website = s.split("@")[1] if "@" in s else ""
extension = website.split(".")[1] if "." in website else ""
website = website.split(".")[0] if "." in website else ""
if not len(usernam... | sidorkinandrew/python-coding | hackerrank/functionals_01_map_and_lambda.py | functionals_01_map_and_lambda.py | py | 1,092 | python | en | code | 0 | github-code | 36 |
27479122996 | import machine
import socket
import network
import uhashlib
import ubinascii
# Configurações do dispositivo
LED_PIN = 2
MANUFACTURER = "ESP32-SmartLock"
MODEL = "SSL01"
DEVICE_ID = "BE4ADCD4-E8FA-40B0-ACB5-2B2B25B5B9"
ESSID = "ESP32-SmartLock-06"
WIFI_PASS = "12345678"
DEFAULT_TOKEN = "ACB5"
TOKEN_FILE =... | elderofz1on/ZionArchive | Projetos/SmartLock/SmartLock06.py | SmartLock06.py | py | 4,817 | python | en | code | 0 | github-code | 36 |
39989734557 | #%%
import os
from transformers import pipeline, AutoTokenizer
def EvalModel(modelname, input_words, author_name=None, out_lines_number=None, temperature=None):
model = os.path.join("models", modelname)
tokenizer = AutoTokenizer.from_pretrained("GroNLP/gpt2-small-italian")
pipe = pipeline("text-generation"... | AndPazzaglia/xEleonora2 | utils/EvalModel.py | EvalModel.py | py | 444 | python | en | code | 0 | github-code | 36 |
22219470819 | import random
def modular_exponential(a, d, n):
if(d == 0):
return 1
if(a == 0):
return 0
#Verify if d is even
if(d % 2 == 0):
x = modular_exponential(a, d / 2, n)
x = (x * x) % n
else:
x = modular_exponential(a, d - 1, n)
x = ((a % n) * (x % n)) %... | Vitorka/maratona | PrimeorNot.py | PrimeorNot.py | py | 1,955 | python | en | code | 0 | github-code | 36 |
72387880423 | # -*- coding:utf-8 -*-
from scrapy import Spider
from scrapy.selector import Selector
from qhpage.items import QhpageItem
class QhpageSpider(Spider):
name = "qhpage"
allowed_domains = ["stackoverflow.com"]
start_urls = [
"http://stackoverflow.com/questions?pagesize=50&sort=newest",
]
def ... | yangaoquan/qhpage | qhpage/spiders/qhspider.py | qhspider.py | py | 796 | python | en | code | 2 | github-code | 36 |
38790072566 | """Module for Bresenham kernel"""
import numpy as np
from copa_map.util.occ_grid import OccGrid
import cv2
class KernelGrid(OccGrid):
"""Class for creating an occupation map with widened walls"""
def __init__(self, base_occ_map: OccGrid, digitize_size=0.2, num_of_borders=2):
"""
Constructor
... | MarvinStuede/copa-map | src/copa_map/kernel/kernel_grid.py | kernel_grid.py | py | 3,359 | python | en | code | 0 | github-code | 36 |
21290035402 | import sqlalchemy as sqla
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, sql
import psycopg2
import re
import os
import matplotlib.pyplot as plt
import matplotlib.patches as patch
from matplotlib.patches import Patch
import matplotlib.lines as mlines
import numpy as np
import math
def ... | JonothorDarry/PostgreProject | flaskk/alchlib.py | alchlib.py | py | 10,498 | python | en | code | 0 | github-code | 36 |
41810977534 | # Reid Nguyen | Number Game | 02/01/2023
import random
randNum = random.randint (1,100)
print (randNum)
atemmpt = 0
play = True
guess = input("Welcome to Number Guesser, Try to Guess a Number Between 1 and 100 in as Few Tries as Posible: ")
inLoop = True
while guess != randNum:
if (str(guess).isdigit() == False):
... | Reid-Dzung/A-3-Programming-Portfolio | src/NumberGame.py | NumberGame.py | py | 1,224 | python | en | code | 0 | github-code | 36 |
31773538373 | import pygame
pygame.init()
tela = pygame.display.set_mode((800, 600))
imgNave = pygame.image.load("Spacepack/Rocket.png")
imgNave = pygame.transform.scale(imgNave, (200,100))
imgUFO = pygame.image.load("Spacepack/UFOBoss.png")
imgUFO = pygame.transform.scale(imgUFO, (200,200))
rect_nave = imgNave.get_rect()
r... | rafaelleal/extensaoPythonPygame | script3.py | script3.py | py | 1,453 | python | en | code | 0 | github-code | 36 |
27697116 | from enum import Enum
from typing import List
from datetime import datetime
from typing import Optional
class FileType(Enum):
PDF = "pdf"
LINK = "link"
DIRECTORY = "directory"
GITHUB = "github"
GENERIC = "generic"
class File:
def __init__(
self,
id: str,
name: str,
... | Kitenite/llm-kb | server/src/datasource/file_system.py | file_system.py | py | 5,030 | python | en | code | 31 | github-code | 36 |
14076267942 | DATA_FILE = './data/day21.txt'
def get_allergens(line):
return line[line.index('contains') + 8:line.index(')')].replace(' ', '').split(',')
def get_foods(line):
return set((line[:line.index(' (')].split(' ')))
def get_allergen_map(lines):
allergen_map = {}
for line in lines:
allergens = ge... | rnewstead1/advent-2020 | day21.py | day21.py | py | 2,810 | python | en | code | 0 | github-code | 36 |
6937535017 | # -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["RotationModel"]
import numpy as np
from scipy.optimize import minimize
from scipy.linalg import cho_factor, cho_solve
import celerite
from celerite import modeling
from .pld import PLDModel
from .gp import get_simple_gp, get_rotati... | dfm/rotate | rotate/model.py | model.py | py | 7,231 | python | en | code | 3 | github-code | 36 |
16558040325 | import network # Importar librerías necesarias
import socket
import time
import secrets # Librería con las credenciales de tu red Wi-Fi
from machine import Pin
#Asignación de pin para el LED
led = Pin(15, Pin.OUT)
# Configuración de red Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.config(pm = 0... | LuisSkap/ServerRaspberryPiPICO | Led_1.py | Led_1.py | py | 3,618 | python | en | code | 1 | github-code | 36 |
7730783737 | import random
def rating_file(name):
with open('rating.txt', 'r') as file:
for line in file:
user, points = line.split()
if user == name:
return points
return 0
def game(points, option):
if option == "":
option = ['paper', 'scissors', 'rock']
... | cubusgg/rock-paper-scissors | game.py | game.py | py | 1,957 | python | en | code | 0 | github-code | 36 |
8984579354 | mapping_test_data = [
{
"product": "glibc",
"version": "2.31",
"version_strings": [
"GLIBC 2.31",
"The following command substitution is needed to make ldd work in SELinux",
"environments where the RTLD might not have permission to write to the",
]... | chinvib66/cve-bin-tool | test/test_data/glibc.py | glibc.py | py | 555 | python | en | code | null | github-code | 36 |
42998550666 | from __future__ import annotations
#
# SSL wrap socket for PyOpenSSL.
# Mostly copied from
#
# https://github.com/shazow/urllib3/blob/master/urllib3/contrib/pyopenssl.py
#
# and added OCSP validator on the top.
import logging
import time
from functools import wraps
from inspect import getfullargspec as get_args
from s... | snowflakedb/snowflake-connector-python | src/snowflake/connector/ssl_wrap_socket.py | ssl_wrap_socket.py | py | 4,486 | python | en | code | 511 | github-code | 36 |
7209789987 | """Functionality related to listing and querying apps"""
import os
import subprocess
import logging
import time
import re
from typing import Optional
from bundle.bundle import Bundle, InvalidBundle
from binary.binary import Binary
from extern.tools import tool_named, call_sbpl
def all_apps(at: str = "/Applications"... | 0xbf00/maap | misc/app_utils.py | app_utils.py | py | 8,464 | python | en | code | 8 | github-code | 36 |
19751656745 | import requests
import json
import yaml
import os
from bs4 import BeautifulSoup
# set URLS for APIs
proPublica_DataTable_url = (
"https://api.propublica.org/congress/v1/bills/search.json?query={}&sort=date"
)
proPublica_bill_url = "https://api.propublica.org/congress/v1/116/bills/{}.json"
proPublica_SENATE_member... | jon-behnken/reform-project | code/powertools/main.py | main.py | py | 3,180 | python | en | code | 0 | github-code | 36 |
71075549545 | class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
res, current, numbers = [], [], 0
for w in words:
if numbers + len(w) + len(current) > maxWidth:
if len(current) == 1:
res.append(current[0]+' '*(maxWidth-num... | nango94213/Leetcode-solution | 68-text-justification/68-text-justification.py | 68-text-justification.py | py | 949 | python | en | code | 2 | github-code | 36 |
5049725299 | import configparser
import time
from operator import attrgetter
from pathlib import Path
from typing import Dict, List, Optional, Union
import numpy as np
import torch
import tensorrt_llm
import tensorrt_llm.logger as logger
from tensorrt_llm._utils import pad_vocab_size, str_dtype_to_np
from tensorrt_llm.mapping imp... | NVIDIA/TensorRT-LLM | examples/gptj/weight.py | weight.py | py | 40,329 | python | en | code | 3,328 | github-code | 36 |
8325185032 | import re
def getWholeIngreSet(recipe):
""" find the common pattarn for calculable ingredients which usually start with a number
, for example: '1 cup unsalted butter'
"""
pat = "[0-9]"
COMMA = ','
RECIPE = recipe
wholeIngreSet = set()
with open(RECIPE,'r') as fin:
for line... | twu38/Calorie_Counter | IngredientHandle.py | IngredientHandle.py | py | 1,594 | python | en | code | 0 | github-code | 36 |
540233672 | import torch
import numpy as np
import encoding_tree
import time
import copy
def find(x, parent, dep):
if parent[x] == -1:
dep[x] = 0
return dep[x]
if (dep[x] > 0):
return dep[x]
dep[x] = find(parent[x], parent, dep) + 1
return dep[x]
def get_tree(input_):
data, k = input... | zzq229-creator/entpool | data/graph2tree.py | graph2tree.py | py | 1,985 | python | en | code | 0 | github-code | 36 |
29620128812 | import mysql.connector
import json
# pip3 install mysql-connector-python
# 连接数据库
config = {
'user': 'root',
'password': 'xxx',
'host': '192.168.137.129',
'port': '3306',
'database': 'db_example'
}
json_data = {}
with open('./data.json', 'r', encoding='utf8')as fp:
json_data = json.load(fp)[0]
... | hua345/myBlog | python/mysql/index.py | index.py | py | 6,087 | python | en | code | 0 | github-code | 36 |
74128345063 | #!/usr/bin/python3
"""Error code #0"""
import urllib.request
import urllib.error
import sys
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit(1)
url = sys.argv[1]
try:
with urllib.request.urlopen(url) as response:
decode_response = response.read().decode('utf-8')
... | GreenMoCh/alx-higher_level_programming | 0x11-python-network_1/3-error_code.py | 3-error_code.py | py | 441 | python | en | code | 0 | github-code | 36 |
17013470871 | import datetime
from components import line_bot_api
from utils import utils_database
import json
from linebot.models import (
TextSendMessage,
)
def get_event_info(event):
event_dict = event.message.as_json_dict()
timestamp = float(event.timestamp/1000)
dt_object = datetime.datetime.fromt... | jialiang8931/WRA06-Volunteer-LineBot | src/utils/utils_common.py | utils_common.py | py | 3,726 | python | en | code | 0 | github-code | 36 |
40890241642 |
"""
Python utils for RFC calls to SAP NetWeaver System
"""
import sys
if sys.version < '2.4':
print('Wrong Python Version (must be >=2.4) !!!')
sys.exit(1)
# load the native extensions
import nwsaprfcutil
import sapnwrfc.rfc
from struct import *
from string import *
import re
from types import *
#from copy... | piersharding/python-sapnwrfc | sapnwrfc/__init__.py | __init__.py | py | 5,163 | python | en | code | 26 | github-code | 36 |
42229554921 | def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
def print_armstrong(lower,upper):
for num in range(lower, upper + 1):
len_1 = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
... | puneetbawa/python-me2sem | assign2.py | assign2.py | py | 3,183 | python | en | code | 0 | github-code | 36 |
18903378632 | from os import makedirs
from os.path import join, dirname, isfile
from uuid import uuid4
from json import dumps
from logging import getLogger
from uchicagoldrtoolsuite import log_aware
from uchicagoldrtoolsuite.core.lib.bash_cmd import BashCommand
from uchicagoldrtoolsuite.core.lib.convenience import log_init_attempt,... | uchicago-library/uchicagoldr-toolsuite | uchicagoldrtoolsuite/bit_level/lib/techmdcreators/fitscreator.py | fitscreator.py | py | 4,907 | python | en | code | 0 | github-code | 36 |
70519989225 | import sys
sys.path.append('path/to/SPFlow')
import numpy as np
import pandas as pd
from spn.structure.Base import Context
from spn.algorithms.oSLRAU import oSLRAU, oSLRAUParams
from spn.structure.leaves.parametric.Parametric import Gaussian, In_Latent
from spn.algorithms.LearningWrappers import learn_parametric
from ... | c0derzer0/oSLRAU_and_RSPN | oSLRAU_run.py | oSLRAU_run.py | py | 3,323 | python | en | code | 0 | github-code | 36 |
73881856745 | import sys
import os
from numpy.lib.arraysetops import isin
from argparse import ArgumentParser
sys.path.insert(1, './tendims')
sys.path.insert(2, './complexity')
sys.path.insert(3, './sentiment')
sys.path.insert(4, './empathy')
import logging
import json
import numpy as np
import wget
import pickle
import oyaml as ya... | Gabryxx7/nlp-flask-server | nlp_flask_server.py | nlp_flask_server.py | py | 20,471 | python | en | code | 2 | github-code | 36 |
31324286848 | #!/usr/bin/python3
import sqlite3
from itertools import chain
conn = sqlite3.connect('vexdb.db')
curs = conn.cursor()
ItyToId=dict()
for row in curs.execute('SELECT id, "Ity_" || btype || nbits AS cenum FROM IRType'):
ItyToId[row[1]]=row[0]
curs.execute('DELETE FROM AiOpSig')
conn.commit()
ItyToId['ity_RMo... | EmmetCaulfield/valgrind | arinx/hacking/insert-opsigs.py | insert-opsigs.py | py | 1,236 | python | en | code | 0 | github-code | 36 |
13511349013 | import tensorflow as tf
import numpy as np
import cifar
def get_value(a):
for i in range(0,len(a)):
if a[i] == 1.0: return i
return -1
m = cifar.cifar("/home/lr/workspace/python/ai/data/cifar-10-batches-py/","/home/lr/workspace/python/ai/model/cifar_cnn/model.ckpt")
m.open()
datas = m.next_datas(5000... | angelbruce/NN | tfk/hello.2.py | hello.2.py | py | 1,232 | python | en | code | 0 | github-code | 36 |
31112021799 | """ Store packages in GCS """
import io
import json
import logging
import os
import posixpath
from datetime import timedelta
from google.auth import compute_engine
from google.auth.transport import requests
from google.cloud import storage
from pyramid.settings import asbool
from pypicloud.models import Package
from... | ambitioninc/pypicloud | pypicloud/storage/gcs.py | gcs.py | py | 8,167 | python | en | code | null | github-code | 36 |
18913829283 | import heapq
class Solution:
def maximumRobots(
self, charge_times: list[int], running_costs: list[int], budget: int
) -> int:
n = len(charge_times)
max_consecutive = 0
sum_running_costs = 0
max_charge_times: list[tuple[int, int]] = []
left = right = 0
... | lancelote/leetcode | src/maximum_number_of_robots_within_budget.py | maximum_number_of_robots_within_budget.py | py | 1,031 | python | en | code | 3 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.