seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
7366582703 | #Código para sortear valores e organizá-los utilizando itemgetter da biblioteca operator, criando um ranking de vencedores
from time import sleep
from random import randint
from operator import itemgetter
classificação = ()
jogos = {'jogador1': randint(1,6),
'jogador2': randint(1,6),
'jogador3': ra... | mateuzh/Python | desafio091.py | desafio091.py | py | 694 | python | pt | code | 0 | github-code | 6 |
21215598425 | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from django.utils.translation import gettext as _
from django.db.models.manager import BaseManager
import plotly.offline as plotly
import plotly.graph_objs as go
from reports import utils
def weight_change(
actual_weights: BaseManager, percentile_... | babybuddy/babybuddy | reports/graphs/weight_change.py | weight_change.py | py | 3,806 | python | en | code | 1,766 | github-code | 6 |
72782974907 | import _pickle as pickle
import numpy as np
from mtqt_source import MTQTSource
from pathlib import Path
from pyrocko import orthodrome
import tensorflow_probability as tfp
import waveform_processing as wp
tfd = tfp.distributions
pi = np.pi
def find_closest_grid_point(lat_ev, lon_ev, depth_ev, path_models=None,
... | braunfuss/BNN-MT | cnn_util.py | cnn_util.py | py | 6,023 | python | en | code | 9 | github-code | 6 |
10819501559 | import yaml
import librosa
import numpy as np
import os
sr = 22050
namesong = 'LizNelson_Rainfall'
def merge_stems(namesong):
# Merge all instrumental stems into 1 mix and all vocal stems into 1 mix
stream = open("./MedleyDB_sample/Audio/" + namesong + "/" + namesong + "_METADATA.yaml", "r")
... | moulinleo/Voice-Isolation | merge_stems.py | merge_stems.py | py | 2,850 | python | en | code | 0 | github-code | 6 |
2277882687 | import random
import time
import discord
from discord.ext import commands
import utils
class Misc(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def profile(self, ctx, user: discord.Member = None):
""" Get information about a Discord user.
Argument 'user', if sp... | SkippyTheSnake/Discord-bot | cogs/misc.py | misc.py | py | 3,962 | python | en | code | 0 | github-code | 6 |
16800280781 | class Book:
def __init__(self,id,name,isbn,page_count,issued,author,year):
self.id = id
self.name = name
self.isbn = isbn
self.page_count = page_count
self.issued = issued
self.author = author
self.year = year
def doIssue(self):
self.iss... | ale90bsas/library-python-mongodb | book.py | book.py | py | 775 | python | en | code | 0 | github-code | 6 |
28475246683 | import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
import math
import numpy as np
from tensorflow.keras.regularizers import l2
tf.keras.backend.set_learning_phase(1)
conv_init = tf.keras.initializers.Var... | qwerasdf887/Keras-Efficientnet | MBConv.py | MBConv.py | py | 12,100 | python | en | code | 0 | github-code | 6 |
10230251745 | import json
import numpy as np
from eval_list import eval_list
import evals.data
from evals.registry import registry
np.random.seed(42)
min_samples_per_dataset = 50
n_test_samples = 10
seen = set()
datarows = []
for eval in registry.get_evals("*"):
if eval.key not in eval_list or eval.key in seen:
conti... | openai/evals | evals/elsuite/self_prompting/scripts/dataset/compile_data.py | compile_data.py | py | 2,868 | python | en | code | 12,495 | github-code | 6 |
43105564820 | import random
def flip_coin():
"""
returns a coin flip- random integer between 0 and 1
if 1 - the coin lands on head
if 0 - the coin lands on tail
"""
return random.randint(0,1) #equal chance of being on head or tails
def monte_carlo(n):
"""
performs a monte_carlo simulation of a co... | jzhanay001/Python-Bootcamp | week_two/coin.py | coin.py | py | 977 | python | en | code | 0 | github-code | 6 |
14149764666 | class LinkedList:
def __init__(self):
self.length = 0
self.head = None
def print_backward(self):
print("[", end="")
if self.head is not None:
self.head.print_backward()
print("]")
def add_first(self, cargo):
node = Node(cargo)
node.next ... | Tomasz-Kluczkowski/Education-Beginner-Level | THINK LIKE A COMPUTER SCIENTIST FOR PYTHON 3/CHAPTER 24 LINKED LISTS/linked_list.py | linked_list.py | py | 2,148 | python | en | code | 0 | github-code | 6 |
18003897185 | import torch
import torch.nn as nn
from torch.nn import Parameter
from torch.distributions import Normal
from algo.pn_utils.maniskill_learn.utils.torch import ExtendedModule
from ..builder import DENSEHEADS
class GaussianHeadBase(ExtendedModule):
def __init__(self, scale_prior=1, bias_prior=0, dim_action=None, ep... | PKU-EPIC/UniDexGrasp | dexgrasp_policy/dexgrasp/algo/pn_utils/maniskill_learn/networks/dense_heads/gaussian.py | gaussian.py | py | 2,881 | python | en | code | 63 | github-code | 6 |
38793898315 | # import tensorflow libraries
import tensorflow as tf
import numpy as np
# import opencv and find webcam
import cv2
cap = cv2.VideoCapture(0)
if not(cap.isOpened()):
print("Can't find webcam, shutting down...")
quit()
# set resolution of camera capture
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 960.0)
cap.set(cv2.CAP_... | OSUrobotics/object_detection | mainfile.py | mainfile.py | py | 2,379 | python | en | code | 0 | github-code | 6 |
30881965405 | # -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages
version = '0.9.4'
long_description = (
open('README.rst').read()
+ '\n' +
open(os.path.join('docs', 'HISTORY.rst')).read()
+ '\n')
setup(name='plone.jsonapi.routes',
version=version,
description="Plone JSON API... | collective/plone.jsonapi.routes | setup.py | setup.py | py | 1,641 | python | en | code | 12 | github-code | 6 |
70986505148 | #!/usr/bin/env python3
"""
Created on Thu Mar 13 9:31:11 2020
@author: Hanrui Wu
"""
import pysam
import sys
import gzip
def read_cell_names1(pathseq_bam_file, write_bac):
seqbam = pysam.AlignmentFile(pathseq_bam_file, "rb",threads=36)
read_name_pathseq = open(write_bac,'w')
total_pathseq_reads=0
tota... | FredHutch/invadeseq | bin/UMI_matrix.py | UMI_matrix.py | py | 20,709 | python | en | code | 1 | github-code | 6 |
33126934610 | import pandas as pd
from tools.readFile import read_excl
# 读取excel中指定列整列元素,返回一个集合
def readExcelData(filePath, column):
df = pd.read_excel(filePath, usecols=[column - 1]) # 指定读取的列
df_list = df.values.tolist()
backList = []
for i in df_list:
backList.append(i[0])
if len(backList) == 0:
... | linhe-demo/sync_dataTable | tools/readExcel.py | readExcel.py | py | 632 | python | en | code | 5 | github-code | 6 |
20946824389 | import datetime
from pysolar import solar
# Calculate the altitude and azimuth of the sun given the location and the time
def sun_pos(payload):
# Input variables
lat = payload["lat"] # Lattitude (deg)
lon = payload["lon"] # Longitude (deg)
epoch = payload["epoch"] # time (Linux epoch in seconds)
... | bsamadi/metadata-processor | app/sun_pos.py | sun_pos.py | py | 727 | python | en | code | 0 | github-code | 6 |
6422355002 | from django.urls import path
from . import views
urlpatterns = [
path('account', views.account, name="account"),
path('profile', views.prifile, name="profile"),
path('signup', views.sign_up, name="signup"),
path('signin', views.sign_in, name="signin"),
path('signout', views.sign_out, name="signout"),
] | aposgial/Project_E3 | happy_traveller/register/urls.py | urls.py | py | 315 | python | en | code | 0 | github-code | 6 |
39747449584 | """Training and Predicting Cifar10 with Mutant Networks.
The networks mutate their architecture using genetic algorithms.
Author: Lucas David -- <ld492@drexel.edu>
Licence: MIT License 2016 (c)
"""
import logging
import artificial as art
import numpy as np
import tensorflow as tf
from artificial.utils.experiments i... | lucasdavid/unicamp-ia004-neural-networks-2 | mutant-networks/experiments/cifar-hill-climbing/experiment.py | experiment.py | py | 3,372 | python | en | code | 0 | github-code | 6 |
19342659029 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.utils import clip_grad_norm_
from torch.utils.data import DataLoader
import torchvision.models as models
from torch.autograd import Variable, grad
from copy import deepcopy
from tqdm import tq... | clarenceluo78/ActiveAD | models/nets_waal.py | nets_waal.py | py | 10,208 | python | en | code | 0 | github-code | 6 |
858377764 | from __future__ import division
from vistrails.core.bundles.pyimport import py_import
import vistrails.core.requirements
from vistrails.gui.modules.source_configure import SourceConfigurationWidget
from PyQt4 import QtCore, QtGui
from vistrails.gui.theme import CurrentTheme
def TextEditor(parent=None):
try:
... | VisTrails/VisTrails | vistrails/gui/modules/string_configure.py | string_configure.py | py | 4,614 | python | en | code | 100 | github-code | 6 |
39911776352 | import os
import re
import json
import pickle
import kss
import pandas as pd
from tqdm import tqdm
from elasticsearch import Elasticsearch
from torch.utils.data import DataLoader, TensorDataset
from datasets import load_metric, load_from_disk, load_dataset, Features, Value, Sequence, DatasetDict, Dataset
from sentence_... | TEAM-IKYO/Open-Domain-Question-Answering | code/prepare_dataset.py | prepare_dataset.py | py | 12,138 | python | en | code | 24 | github-code | 6 |
18164621881 | import json
# Read the network.json file
with open("network.json", "r") as f:
network = json.load(f)
# Create a set to store all pairs (a, b) such that a follows b but b doesn't follow back a
pairs = set()
# Iterate over all users in the network
for user, data in network.items():
# Get the list of... | GOVINDFROMINDIA/Twitter-Scam-Victims | GraphEvaluation.py | GraphEvaluation.py | py | 1,265 | python | en | code | 0 | github-code | 6 |
11464862154 | import speech_recognition as sr
from requests import get
from bs4 import BeautifulSoup
from gtts import gTTS
from paho.mqtt import publish
import os
##### CONFIGURAÇÕES #####
with open('arquivoConfiguraGoogleSpeech.json') as credenciais_google:
credenciais_google = credenciais_google.read()
executaAcao = False
se... | cicerojmm/assistentePessoalIoT | veronica/veronica.py | veronica.py | py | 3,705 | python | pt | code | 2 | github-code | 6 |
12300846904 | """
This example illustrates how to display the tree of a single TreeGrower for
debugging purpose.
"""
from sklearn.datasets import make_classification
import numpy as np
from pygbm.binning import BinMapper
from pygbm.grower import TreeGrower
from pygbm import plotting
rng = np.random.RandomState(0)
n_samples = int... | ogrisel/pygbm | examples/plot_performance_profile_single_small_tree.py | plot_performance_profile_single_small_tree.py | py | 1,076 | python | en | code | 175 | github-code | 6 |
24494832097 | import requests
import pandas as pd
from bs4 import BeautifulSoup as bs
def get_spy():
url = 'https://www.slickcharts.com/sp500'
request = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
soup = bs(request.text, "lxml")
stats = soup.find('table', class_='table table-hover table-borderless t... | reesecake/td_api | util/IndexInfo.py | IndexInfo.py | py | 520 | python | en | code | 0 | github-code | 6 |
9790495928 | from django.core.files.storage import FileSystemStorage
from django.http import FileResponse
from django.http import HttpResponseBadRequest
from django.http import HttpResponseNotFound
from django.http import JsonResponse
from rest_framework import mixins
from rest_framework import viewsets
from rest_framework.decorato... | wiksla/f5-bigip-journeys-app | journeys/backend/views.py | views.py | py | 8,720 | python | en | code | 0 | github-code | 6 |
36152977435 | import os, sys, logging
from flask import Blueprint, current_app
from flask import request, jsonify
ml_model_bp = Blueprint('ml_model_bp', __name__) # create a Blueprint object
# create 'index' view for testing purposes
@ml_model_bp.route('/', methods=["GET", "POST"])
def index():
return "ML model service is run... | bhavenp/docker_sentiment_analysis | ml_service/ml_model_api/ml_model_blueprint.py | ml_model_blueprint.py | py | 1,355 | python | en | code | 0 | github-code | 6 |
72067619709 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 9 13:31:37 2022
@author: basile
"""
import pandas as pd
df = pd.DataFrame(columns=['index', 'prenom', 'nom', 'email', 'groupe', 'mystere'])
df.to_csv('priants.csv', index=False)
import streamlit as st
input = st.text_input("text", key="text")
... | BasileR29/chapelet_tournant | test.py | test.py | py | 422 | python | en | code | 0 | github-code | 6 |
13913894709 | from __future__ import annotations as _annotations
from typing import TYPE_CHECKING
import pytest
from watchfiles import watch
from watchfiles.main import _default_force_polling
if TYPE_CHECKING:
from .conftest import SetEnv
class MockRustNotify:
@staticmethod
def watch(*args):
return 'stop'
... | samuelcolvin/watchfiles | tests/test_force_polling.py | test_force_polling.py | py | 2,551 | python | en | code | 1,336 | github-code | 6 |
29125164138 | from django.conf.urls import include, patterns, url
view_location = 'customProfile.views'
urlpatterns = patterns(view_location,
# Views
url(r'^(?P<username>[-\w]+)/', include(patterns(view_location,
url(r'^$', 'profileRedirect', {'redirect_url': 'artist:about'}, name='home'),
url(r'^news/$', '... | TimBest/ComposersCouch | artist/urls.py | urls.py | py | 2,864 | python | en | code | 1 | github-code | 6 |
20232075182 | from tradingview.client import TradingViewWebSocketClient, fetch_japan_symbols
from datetime import datetime
client = TradingViewWebSocketClient()
symbols = fetch_japan_symbols()
client.add_symbols(symbols[:100])
# client.add_symbols(['TSE:4689'])
for x in client.fetch_ohlc(past_bar=302):
print(datetime.fromtime... | otomarukanta/tradingview | example_ohlc.py | example_ohlc.py | py | 341 | python | en | code | 0 | github-code | 6 |
41664319378 | import random
import tkinter as tk
import tkinter.messagebox
import pandas as pd
from tkinter import ttk
from tkinter import *
# import unidecode
from tkinter import PhotoImage
LARGE_FONT = ("Courier", 20, "bold")
MEDIUM_FONT = ("Courier", 15)
BACKGROUND_COLOR = "#6699CC"
# BACKGROUND_COLOR_ALT = "#B1DDC6"
class La... | wRajter/teddy_spricht_vSK | main.py | main.py | py | 7,699 | python | en | code | 0 | github-code | 6 |
41675138600 | # 부녀회장이 될 테야
"""
5 1 7 28 84 210
4 1 6 21 56 126
3 1 5 15 35 70
2 1 4 10 20 35
1 1 3 6 10 15
0 1 2 3 4 5 (0층)
1 2 3 4 5
"""
import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
floor = int(input())
room = int(input())
info = [[0 for _ in ran... | jisupark123/Python-Coding-Test | baekjoon/2022-6/bronze/2775.py | 2775.py | py | 589 | python | en | code | 1 | github-code | 6 |
72743743228 | import os
import boto3
import json
from app.shared.clients.secret_manager import SecretManager
def _map_to_auth_response(principal, resource, effect):
statement = {
"Action": "execute-api:Invoke",
"Effect": effect,
"Resource": resource
}
policy_document = {
"Version": "201... | ishwar2303/graphidot-serverless-backend | app/functions/basic_authorizer/basic_authorizer.py | basic_authorizer.py | py | 989 | python | en | code | 0 | github-code | 6 |
24512005131 | import datetime as dt
import warnings
import numpy as np
import pandas as pd
from asgiref.sync import async_to_sync
from dateutil.parser import parse
from django.core.cache import cache
from django.utils import timezone
from apps.integration.tasks.sockets.get_kws_object import get_kws_object
warnings.filterwarnings(... | finbyz/trading_child | apps/integration/tasks/sockets/option_websocket.py | option_websocket.py | py | 3,575 | python | en | code | 0 | github-code | 6 |
3642629983 | from utils.transformers_utils import SiameseRobertaModel,TrainerLogger,get_preds,compute_metrics,update_metrics
import numpy as np
import pandas as pd
from transformers import RobertaTokenizerFast,RobertaConfig,TrainingArguments
from datasets import Dataset,DatasetDict #!pip install datasets
import evaluate ... | matisyo/vulnerability_detection | Notebooks/8. Transformers Classifier.py | 8. Transformers Classifier.py | py | 4,686 | python | en | code | 0 | github-code | 6 |
8845375190 | from fastapi import APIRouter, Depends
from fastapi_pagination import Page, Params
from src.admins.dependencies import get_groups_service, get_valid_group
from src.admins.models import Group
from src.admins.schemas import CreateGroupSchema, GroupOut
from src.admins.services import GroupService
router = APIRouter()
... | Qwizi/fastapi-sourcemod | sourcemod_api/src/admins/views/groups.py | groups.py | py | 1,015 | python | en | code | 0 | github-code | 6 |
36994780654 | # -*- coding:utf-8 -*-
from __future__ import print_function
from __future__ import division
import tensorflow as tf
import numpy as np
from tqdm import tqdm
import os
import sys
import shutil
import time
from utils import get_logger
import network
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
sys.path.append('../..')
fr... | shelleyHLX/cail | models/Attention_Textcnn/train.py | train.py | py | 9,638 | python | en | code | 77 | github-code | 6 |
26244830544 | from __future__ import absolute_import, print_function
import unittest
import poker
testdata = ["5H 5C 6S 7S KD 2C 3S 8S 8D TD",
"5D 8C 9S JS AC 2C 5C 7D 8S QH",
"2D 9C AS AH AC 3D 6D 7D TD QD",
"4D 6S 9H QH QC 3D 6D 7H QD QS",
"2H 2D 4C 4D 4S 3C 3D 3S 9S 9D"]
testwinne... | tak0kada/procon | project euler/python/50/54/poker/tests/test_poker.py | test_poker.py | py | 882 | python | en | code | 0 | github-code | 6 |
42810587556 | import numpy as np
# Color palette
palette = {
0: (0, 0, 0), # Undefined (black)
1: (255, 255, 255), # Impervious surfaces (white)
2: (0, 0, 255), # Buildings (dark blue)
3: (0, 128, 0), # Vegetation (light green)
4: (255, 0, 0), # Water (re... | nshaud/DeepNetsForEO | OSM/labels.py | labels.py | py | 987 | python | en | code | 468 | github-code | 6 |
28726581501 | import logging
import feedparser
import requests
from .. import read_list
log = logging.getLogger(__name__)
class VideoFeed:
def __init__(self, known_path, url):
self.url = url
self.read_list = read_list.ReadList(known_path, url)
def is_new(self, item):
return self.read_list.is_new... | EliseAv/tubeforme | video_feeds/_base.py | _base.py | py | 1,334 | python | en | code | 0 | github-code | 6 |
29644952837 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
"""DESCRIPTION
This module is a list of coding exercises. The intention
is to emulate some functions from other languages.
"""
#==================================================================
# Generate a list of divisors
#====... | arthur-schopenhauer/Mathematica_Notebooks | trivial_functions.py | trivial_functions.py | py | 6,732 | python | en | code | 0 | github-code | 6 |
7775796221 | class Node:
def __init__(self, item):
self.data = item
self.next = None
class LinkedList:
def __init__(self):
self.nodeCount = 0
self.head = None
self.tail = None
def __repr__(self):
if self.nodeCount == 0:
return 'LinkedList: empty'
s ... | lowelllll/DataStructure | LinkedList/linked_list.py | linked_list.py | py | 2,577 | python | en | code | 0 | github-code | 6 |
71493772028 | '''
2D Multiple Circles Problem
'''
from lsdo_genie import Genie2D
from lsdo_genie.utils.geometric_shapes import Multi_circle
import numpy as np
num_surface_pts = 25
centers = [[-13.,-0.5],[-7.,2.],[2.,0.],[10.,-4.]]
radii = [2.,2.,4.,3.]
geom_shape = Multi_circle(centers,radii)
surface_points = geom_shape.surface_p... | LSDOlab/lsdo_genie | examples/2D_examples/ex_circles.py | ex_circles.py | py | 758 | python | en | code | 0 | github-code | 6 |
14098850969 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Few more things we might wanna work out here.
Our lack of the module :mod:`inspect` is pretty surprising.
Refer to either `IPython.core.oinspect` or `xonsh.inspectors`
for some good uses of the std lib module.
"""
from pprint import pformat
from pygments import highl... | farisachugthai/dynamic_ipython | default_profile/extensions/extension_inspect.py | extension_inspect.py | py | 2,946 | python | en | code | 7 | github-code | 6 |
17178723426 | import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objects as go
import plotly.express as px
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
import pickle
st.set_page_config(page_title="Air Quality... | vavald/MDA_streamlit | pages/6_💨_AirQuality.py | 6_💨_AirQuality.py | py | 5,860 | python | en | code | 0 | github-code | 6 |
11704116245 | import platform
from tkinter import filedialog
from web3 import Web3
from web3.contract import Contract
from web3.providers.rpc import HTTPProvider
from solcx import install_solc
install_solc(version='latest')
from solcx import compile_source
import subprocess
import os
import tkinter as tk
from PIL import Image, Image... | MassimilianoPiccinini/SoftwareSecurity-Blockchain | src/offchain.py | offchain.py | py | 23,961 | python | en | code | 1 | github-code | 6 |
19707336879 | # # # -*- coding: utf-8 -*-
# # # @Time :2021/3/22 20:56
# # # @Author :huangzg28153
# # # @File :test.py
# # # @Software :PyCharm
# # import numpy as np
# # import pandas as pd
# # # type = [0,1,1,1,2,0,1,0,1,2,2,0]
# # # ser = [0,1,2,3,4,5,6,0,1,2,3,4]
# # # layer = [0,0,0,0,0,1,1,0,0,0,0,1]
# # # samp... | hzg0601/cn-annotation | HGT_OAG_cn-annotation/codes/test.py | test.py | py | 10,935 | python | en | code | 0 | github-code | 6 |
72621252988 | hargaBarang = int(input("Masukkan Harga Barang: "))
uang = int(input("Masukkan Uang Anda: "))
kembalian = uang - hargaBarang
pecahan_uang = [100000, 50000, 20000, 10000, 5000, 2000, 1000]
if hargaBarang > uang:
print("uang anda tidak cukup, dilarang utang disini!")
exit()
for pecahan in pecahan_uang:
ju... | ArdiansyahAsrifah/LAB_AP_09 | H071231016/Praktikum-3/nomor02.py | nomor02.py | py | 502 | python | id | code | 0 | github-code | 6 |
18790221797 | import torch
import decord
from decord import cpu, gpu
from tqdm import tqdm
import json
import os
import random
import numpy as np
import pickle
def sample_frames(num_frames, vlen, sample='rand', fix_start=None):
acc_samples = min(num_frames, vlen)
intervals = np.linspace(start=0, stop=vlen, num=acc_samples ... | MILVLG/anetqa-code | clipbert/sample_imgs_clipbert.py | sample_imgs_clipbert.py | py | 2,196 | python | en | code | 6 | github-code | 6 |
690172059 | '''Refazendo Progressão Aritmética com While'''
print('=-='*20)
print('Progressão Aritmética')
print('=-='*20)
primeiro = int(input('Digite o primeiro termo da progressão: '))
razao = int(input('Digite a razão para a progressão: '))
termo = primeiro
cont = 1
total = 0
mais = 10
while mais != 0:
total = t... | thaisouza30/Exercicios-Python3-Curso-em-Video | ex062.py | ex062.py | py | 617 | python | pt | code | 0 | github-code | 6 |
39503714070 | # The file is object for VICON. This is effective method for storing and
# accesing information about the vicon objects
import numpy as np
import os
from VICONMath import transformations as transferOp
from VICONFileOperations import rwOperations
class ObjectVicon:
"""The class is object is base class for VICONTra... | hmnaik/smartbarn-mocap | VICONSystem/objectVicon.py | objectVicon.py | py | 7,219 | python | en | code | 1 | github-code | 6 |
14132002645 | from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DateTime, Float, UniqueConstraint, Index
from sqlalchemy.orm import relationship
from src.models import Base
class GpsRecord(Base):
__tablename__ = "gps_record"
id = Column(Integer, primary_key=True, index=True)
datetime = Column(DateT... | jmcastellote/whereabouts | src/gps_record/model.py | model.py | py | 1,126 | python | en | code | 0 | github-code | 6 |
15912701941 |
"""
Class to deal with the pooling problem (differing amounts of tweets for various days)
"""
import torch
from torch import nn, tensor
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#device = torch.device("cpu")
# will we have a device setting here? to ensure that the data is being processed... | biirving/michinaga | src/utils/pooling.py | pooling.py | py | 1,583 | python | en | code | 2 | github-code | 6 |
32898453966 | from __future__ import print_function
import unittest
import numpy
import irbasis
from irbasis_util.two_point_basis import *
from irbasis_util.four_point import *
from irbasis_util.internal import *
from irbasis_util.regression import *
from atomic_limit import *
def G1_iw_pole_f(n, pole, beta):
return 1/(1J * ... | shinaoka/irbasis_utility | test/python/four_point_test.py | four_point_test.py | py | 4,357 | python | en | code | 6 | github-code | 6 |
74884399227 | # -*- coding: utf-8 -*-
import re
import sqlite3
from collections import defaultdict
import requests
import gnupg
class OTCDB(object):
gpg_file = 'GPG.db'
rating_file = 'RatingSystem.db'
def __init__(self, path):
self.path = path
self.trusted = {}
def open_db(self):
gpg_path = '{0}/{1}'.format(self.path,... | extempore/deedbundler | deedbundler/otc.py | otc.py | py | 3,668 | python | en | code | 8 | github-code | 6 |
31460291272 | '''
颜色特征向量
||
(赋权颜色直方向量 拼接 赋权颜色矩向量)
// \\
归一化颜色直方向量 归一化颜色矩向量
// ... | heqisen199966/pythonProject2 | work2/colorStraight.py | colorStraight.py | py | 5,049 | python | zh | code | 0 | github-code | 6 |
3035513185 | # given two strings A and B, write a function to return a list of
# all start indices within A where the substring of A is an
# anagram of B. for example, if A = "abcdcbac" and B = "abc" then
# you want to return [0,4,5] since those are the starting indices
# of substrings of A that are anagrams of B
A = 'abcdcbac'
... | estimatrixPipiatrix/decision-scientist | key_algos/anagram_substring.py | anagram_substring.py | py | 838 | python | en | code | 0 | github-code | 6 |
17286729620 | import cv2
import imutils
import numpy as np
cv2.namedWindow("MyImage")
img = cv2.imread("img.jpg")
# translated = imutils.translate(img, 25, -75)
# rotated = imutils.rotate(img, 45)
img = imutils.resize(img, width=600)
# url_images = imutils.url_to_image(
# "https://www.google.com/images/branding/googlelogo/2x/... | osoulim/Computer-Vision | Python/Week3/pre_proccess.py | pre_proccess.py | py | 532 | python | en | code | 0 | github-code | 6 |
17573160892 | from flask import Flask, render_template, request, redirect, session, flash
from mysqlconnection import connectToMySQL
import json
app = Flask(__name__)
@app.route("/")
def index():
mysql = connectToMySQL("leads_and_clients_db")
query = "SELECT concat(clients.first_name, ' ', clients.last_name) as name, count... | aaronfennig/pythonDjango | flask/flask_mysql/leads_and_clients/server.py | server.py | py | 963 | python | en | code | 0 | github-code | 6 |
40510581064 | #Avem hardcodat punctele prin care algoritmul detecteaza forma obiectului
myVar = {
'1': {'Points': 3, 'Form': 'Triunghi'},
'2': {'Points': 4, 'Form': ['Patrat', 'Dreptunghi']},
'3': {'Points': 5, 'Form': 'Pentagon'},
'4': {'Points': 6, 'Form': 'Hexagon'},
'5': {'Points': 7, 'Form': 'Heptagon'},
... | ConstantinescuAndrei/ShapeDetection | shapeList.py | shapeList.py | py | 1,233 | python | ro | code | 0 | github-code | 6 |
14852199031 | # coding: utf-8
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.criterions import FairseqCriterion, register_criterion
from fairseq.criterions.label_smoothed_cross_entropy import LabelSmoothedCrossEntropyCriterion, label_smoothed_nll_loss
def root_... | jack-and-rozz/speculative_sampling | fairseq/extensions/criterions/spacefusion_loss.py | spacefusion_loss.py | py | 10,265 | python | en | code | 0 | github-code | 6 |
15067404413 | from django.shortcuts import render, redirect
from .forms import Registration, Login
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from .models import *
from .custom_manager import CustomUserManager
from django.contrib import messages
import uuid
from django.conf import... | leenabadgujar/Online_Tiffin_Service | CustomUser/views.py | views.py | py | 4,317 | python | en | code | 0 | github-code | 6 |
86572452967 | #!/usr/bin/env python3
"""
Check for and replace aliases with their new names from vk.xml
"""
import argparse
import pathlib
import subprocess
import sys
import xml.etree.ElementTree as et
THIS_FILE = pathlib.Path(__file__)
CWD = pathlib.Path.cwd()
VK_XML = THIS_FILE.parent / 'vk.xml'
EXCLUDE_PATHS = [
VK_XML.re... | sailfishos-mirror/mesa | src/vulkan/registry/update-aliases.py | update-aliases.py | py | 6,150 | python | en | code | 1 | github-code | 6 |
72331237629 |
import datacube
from datacube.api import *
# basic stuff.
from collections import defaultdict
import time
from datetime import datetime
import json
# dc data comes out as xray arrays
import xarray as xr
import xarray.ufuncs
# gdal related stuff.
import gdal
from gdalconst import *
# np for arrays
import numpy as n... | ceos-seo/Data_Cube_v2 | ui/django_site_v2/data_cube_ui/utils/data_access_api.py | data_access_api.py | py | 11,474 | python | en | code | 26 | github-code | 6 |
34953476775 | from django.shortcuts import render_to_response
from read_num.models import get_seven_read_data, get_today_hot_data, get_yesterday_hot_data
from django.contrib.contenttypes.models import ContentType
from blog.models import Blog
from django.utils import timezone
from django.db.models import Sum
from django.core.cache im... | shane-constantine/mysite | mysite/views.py | views.py | py | 1,499 | python | en | code | 0 | github-code | 6 |
21355104515 | #
# @lc app=leetcode.cn id=762 lang=python3
#
# [762] 二进制表示中质数个计算置位
#
# @lc code=start
class Solution:
def countPrimeSetBits(self, left: int, right: int) -> int:
primes = {2,3,5,7,11,13,17,19,23,29,31}
def get_bits(n):
cnt = 0
while n!=0:
n &= (n-1)
... | Alex-Beng/ojs | FuckLeetcode/762.二进制表示中质数个计算置位.py | 762.二进制表示中质数个计算置位.py | py | 478 | python | en | code | 0 | github-code | 6 |
3602691667 |
"""
Description:
使用 Bokeh,基于各国家创建一个 CPI 和童工数据的散点图。
拓展:
Bokeh(http://bokeh.pydata.org/)是一个 Python 绘图库,能够用相当简单的命令来绘制更
复杂的图表类型。如果想要创建一个条形图、散点图或时间序列图,尝试Bokeh,看看是
否合适。使用 Bokeh,基于各国家创建一个 CPI 和童工数据的散点图。
"""
from bokeh.plotting import figure, show, output_file
# NOTE: You'll need to have 'africa_cpi_cl' table from Chapte... | lafitehhq/PythonBook | Python-03数据处理/Reference/code/chp10-presentation-数据展示/chart_bokeh_使用Bokeh绘图1.0.py | chart_bokeh_使用Bokeh绘图1.0.py | py | 1,776 | python | zh | code | 2 | github-code | 6 |
2990307783 | import time
import turtle
from drawing.draw import draw_from_function
from drawing.util import (
write_function_name,
clear_screen,
fill_background,
set_up_screen,
)
from breed.babies import BabyMaker
from plants.plants import (
tree,
daisy,
cyclamen,
foxglove,
generated_flower,
... | SimonCarryer/mutant_flowers | draw_flower.py | draw_flower.py | py | 514 | python | en | code | 6 | github-code | 6 |
74363301949 | #!/usr/bin/python3
'''
A Simple addition module
'''
def add_integer(a, b=98):
''' a function that add two integers or floats. '''
if type(a) is not int and type(a) is not float:
raise TypeError('a must be an integer')
if type(b) is not int and type(b) is not float:
raise TypeError('b must ... | ugwujustine/alx-higher_level_programming | 0x07-python-test_driven_development/0-add_integer.py | 0-add_integer.py | py | 484 | python | en | code | 0 | github-code | 6 |
16786521432 | from flask import render_template, flash, redirect, url_for, request, jsonify, current_app, g, send_from_directory
from flask_login import login_required, login_user, logout_user, current_user
from app import db
from app.helper import clean_list, normalize, convertArrayToString, convertStringToArray, prepFullAddressSea... | iamjasonkuo/househunt | app/project/routes.py | routes.py | py | 14,693 | python | en | code | 0 | github-code | 6 |
41685965854 | from utils import Position
import copy
import pickle
def load_cache(file: str) -> dict:
try:
with open(file, 'rb') as f:
cache = pickle.load(f)
except FileNotFoundError:
cache = {}
return cache
def save_cache(cache, file: str):
with open(file, 'wb') as f:
pickle.... | Epico-Coder/TicTacToe | ai.py | ai.py | py | 2,357 | python | en | code | 0 | github-code | 6 |
33230034244 | # EKF SLAM - adding one landmark.
#
# slam_09_b_slam_add_landmark
# Claus Brenner, 20 JAN 13
from lego_robot import *
from math import sin, cos, pi, atan2, sqrt
from numpy import *
from slam_f_library import write_cylinders, write_error_ellipses
class ExtendedKalmanFilterSLAM:
def __init__(self, state,... | jfrascon/SLAM_AND_PATH_PLANNING_ALGORITHMS | 06-SLAM/CODE/slam_09_b_slam_add_landmark_question.py | slam_09_b_slam_add_landmark_question.py | py | 10,329 | python | en | code | 129 | github-code | 6 |
4135669430 | #!/usr/bin/env python3
# Covariance Calculation from doc2vec model
import numpy as np
import gensim.models
import gensim
import sys
import pickle
from helpers import get_name
def compute_covariance_matrix(model_name, to_json=True):
model = gensim.models.Doc2Vec.load(model_name)
doctags = list(model.docvecs.... | papachristoumarios/sade | sade/corrcoef.py | corrcoef.py | py | 930 | python | en | code | 8 | github-code | 6 |
3549042262 | from django import forms
from catalog.models import Category, Product
class ProductAdminForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'slug','brand','sku','price','old_price',\
'is_active','is_bestseller','is_featured','quantity',\
'descri... | Hamfri/shopping | catalog/forms.py | forms.py | py | 626 | python | en | code | 0 | github-code | 6 |
10190974986 | import numpy as np
import neural
import random
#my_seed = 95
#random.seed(my_seed)
#np.random.seed(my_seed)
# Load data
f = open('seeds_dataset.csv', 'r')
features = []
labels = []
rows = f.readlines()
for row in rows:
values = [float(x) for x in row.split(',')]
features.append(values[:-1]) # Ignore last column
l... | peterapps/NumpyNeural | seeds2.py | seeds2.py | py | 1,713 | python | en | code | 0 | github-code | 6 |
30357262081 | from threading import Thread
from time import sleep
from traits.api import HasTraits, Int, Button
from traitsui.api import View, Item, VGroup
class ThreadDemo(HasTraits):
# The thread specific counters:
thread_0 = Int()
thread_1 = Int()
thread_2 = Int()
# The button used to start the threads run... | enthought/traitsui | traitsui/examples/demo/Advanced/Multi_thread_demo.py | Multi_thread_demo.py | py | 1,376 | python | en | code | 290 | github-code | 6 |
5469207228 | #ライブラリ、モジュールをインポート
import pandas as pd
import openpyxl as px
from openpyxl.formatting.rule import CellIsRule
from openpyxl.styles import Color, PatternFill
#ブック名入力
tdname=input('testdataName?')
edname=input('editordataName?')
#読み込んだブックの同じテストのデータをDataFrameに格納
td=pd.read_excel(tdname,header=1,sheet_name=0)
ed=pd.read_e... | kobayu0902art/work_snippets | reshape/reshape_v1.4_1.py | reshape_v1.4_1.py | py | 2,175 | python | ja | code | 0 | github-code | 6 |
70929712188 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 6 17:20:25 2023
@author: Gilberto
"""
""
# streamlit_app.py
import io
import base64
import streamlit as st
import pandas as pd
from datetime import datetime
from mortgagestyle_v2 import MortgageStyle
from straightline_v2 import StraightLineAmortization
f... | gdelacruzv/Amortization_calculator | Amortization_app_V4.py | Amortization_app_V4.py | py | 8,584 | python | en | code | 0 | github-code | 6 |
70940682109 |
#this is how to get code output in py
print(
"This is my first code in python. Hello python")
#this is how to declare a variable
# variable has a name then after an equal sign the value
subject_name = "Tom"
another_name = "Jerry"
there_shows_name = subject_name + " & " + another_name
print("This is a cartoon show n... | ahmadbinraees/basicConcepts | src/basic.py | basic.py | py | 1,664 | python | en | code | 0 | github-code | 6 |
39614840706 | #!/usr/bin/env python3
import sys
import os
import time
from datetime import datetime
import textwrap
import argparse
import platform
try:
import influxdb
except ImportError:
print("Trying to Install required module: influxdb\n")
os.system('python3 -m pip install influxdb')
time.sleep(5)
def fioinput(ip, po... | philcanman/fio-to-influxdb | fio_to_influxdb.py | fio_to_influxdb.py | py | 9,043 | python | en | code | 1 | github-code | 6 |
75131855228 |
from datetime import datetime
import pymysql
import json as j
import flask as f
from flask import Flask, redirect
from flask import request
from flask import send_from_directory
from flaskext.mysql import MySQL
app=Flask(__name__, static_url_path="")
#Povezivanje sa bazom(parametri)
mysql=MySQL(... | haribate98/Android | FlaskZaProjekat/main.py | main.py | py | 3,497 | python | en | code | 1 | github-code | 6 |
43956557150 | from flask import flash
from db import db
# Feedback function for registered users
def feedback(user_id, message):
sql = "INSERT INTO messages (user_id, message) VALUES (:user_id, :message)"
db.session.execute(sql, {"user_id":user_id, "message":message})
db.session.commit()
flash("Kiitos palautteestasi... | asianomainen/tsoha-s2020-tuntivarausjarjestelma | messages.py | messages.py | py | 909 | python | en | code | 0 | github-code | 6 |
30353743561 | # Author: Varun Hiremath <varun@debian.org>
# Enthought library imports.
from traits.api import Instance, Enum
from traitsui.api import View, Group, Item
from tvtk.api import tvtk
# Local imports
from mayavi.filters.filter_base import FilterBase
from mayavi.core.pipeline_info import PipelineInfo
###################... | enthought/mayavi | mayavi/filters/extract_vector_components.py | extract_vector_components.py | py | 2,728 | python | en | code | 1,177 | github-code | 6 |
30791829002 | from scipy.fftpack import dct, idct
# implement 2D DCT
def dct2(a):
return dct(dct(a.T, norm='ortho').T, norm='ortho')
# implement 2D IDCT
def idct2(a):
return idct(idct(a.T, norm='ortho').T, norm='ortho')
import cv2
import numpy as np
import matplotlib.pylab as plt
# read lena RGB image a... | NadiaFaramarzi/ClassicalObjectDetection | Codes/DCT(discrete cosine transform).py | DCT(discrete cosine transform).py | py | 1,048 | python | en | code | 0 | github-code | 6 |
44593105346 | # script to create scatter plot for mean intensity ranking in three emotion
# categories. refer to readme for more information about survey and ranking
# task.
# 18 November 2018, Pulkit Singh
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
#------------------------------------------------... | pulkitsingh/IW-Emoji-Intensity | Emotion Word Survey/Word Intensity Ranking/Scatter plots mean/intensityRanking_mean.py | intensityRanking_mean.py | py | 2,743 | python | en | code | 0 | github-code | 6 |
654986927 | #!/usr/bin/env python
import argparse
from .. import view_container
def tobool(inp):
return inp.lower() in ('y', '1', 'ok', 't')
parser = argparse.ArgumentParser(description='Display datasets in h5 or n5/zarr container.')
parser.add_argument('path', type=str, help='path to container')
parser.add_argument('--nd... | constantinpape/heimdall | heimdall/scripts/view_container.py | view_container.py | py | 1,184 | python | en | code | 20 | github-code | 6 |
21940354299 | r"""Format notebooks using the TensorFlow docs style.
Install the tensorflow-docs package:
$ python3 -m pip install -U [--user] git+https://github.com/tensorflow/docs
Usage:
$ python3 -m tensorflow_docs.tools.nbfmt [options] notebook.ipynb [...]
See the TensorFlow notebook template:
https://github.com/tensorflow/doc... | tensorflow/docs | tools/tensorflow_docs/tools/nbfmt/__main__.py | __main__.py | py | 9,543 | python | en | code | 5,917 | github-code | 6 |
71245917627 | import time
import numpy as np
from testing import Ptot
import matplotlib.pyplot as plt
if __name__ == "__main__":
div = int(1e4)
# number of tests
Q = int(8e6)//div
# population size
N = int(40e6)//div
R = 0
Ip_arr = np.arange(500, 3000)
# FNR variations
Ptot_a... | lubo93/disease-testing | sampling/testing_analytical_replacement_true_CA.py | testing_analytical_replacement_true_CA.py | py | 881 | python | en | code | 2 | github-code | 6 |
21313993250 | class CryptoTool:
def DecypherFromTranslation(self, Message, CryptedKey, UncryptedKey):
Message = Message.upper()
CryptedKey = CryptedKey.upper()
UncryptedKey = UncryptedKey.upper()
Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
translatedAlphabet = ""
result = ""
f... | yenshin/test-proto-tuto | CryptoTool/cryptotool.py | cryptotool.py | py | 1,847 | python | en | code | 0 | github-code | 6 |
74147618108 | # coding:utf-8
"""
Django administration setup
@author: Sébastien Renard <Sebastien.Renard@digitalfox.org>
@license: AGPL v3 or newer (http://www.gnu.org/licenses/agpl-3.0.html)
"""
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from billing.models import ClientBill, SupplierB... | digitalfox/pydici | billing/admin.py | admin.py | py | 2,334 | python | en | code | 122 | github-code | 6 |
16906648825 | '''Пример использования функции filter.'''
from random import randint
lst = [randint(1, 10) for el in range(1, 10)]
print(f"Начальный список: {lst}")
# Вариант решения без функции filter
# Создаем новый список только с четными элементами списка lst
new_lst = []
for el in lst:
if el % 2 == 0:
new_lst.appen... | AlexLep1n/Python | lesson-6/app_3.py | app_3.py | py | 705 | python | ru | code | 0 | github-code | 6 |
1544319758 |
from fastapi import FastAPI, UploadFile, Form,File
import cloudinary
import cloudinary.uploader
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Confi... | naman360/courtledger | scripts/main.py | main.py | py | 961 | python | en | code | 0 | github-code | 6 |
15206133090 | """Tests for utils."""
import unittest
import torch
from chemicalx.utils import segment_softmax
class TestPipeline(unittest.TestCase):
"""Test the utils."""
def test_segment_softmax(self):
"""Set up the test case with some data."""
logit = torch.FloatTensor([-0.5, -2.5, 0.5, 1.5])
... | AstraZeneca/chemicalx | tests/unit/test_utils.py | test_utils.py | py | 789 | python | en | code | 672 | github-code | 6 |
1976029717 | from django.db import models
from equipas.models import Equipa
# Create your models here.
class Campeonato(models.Model):
campeonato_id = models.AutoField(primary_key=True)
modalidade = models.ForeignKey('Modalidade', models.DO_NOTHING)
nome = models.CharField(max_length=100)
epoca = models.CharField(m... | OliveiraRP/django-webapp | src/webapp/campeonatos/models.py | models.py | py | 1,039 | python | pt | code | 0 | github-code | 6 |
31131850381 | import jwt
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import requests
import time
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
# GLOBALS
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,... | BoogieManN8/FootballTrainerHelper | main.py | main.py | py | 5,139 | python | en | code | 0 | github-code | 6 |
18132737377 | # In this project, I'm going to desgin a user infterface for translating difference languages in real time
# Library Used: google trans, textblob
import googletrans
import textblob
import customtkinter
from tkinter import END
# Adding languages
language = googletrans.LANGUAGES
translator = googletrans.Translator()
... | JayChen1060920909/Projects | Real Time Translation.py | Real Time Translation.py | py | 2,191 | python | en | code | 1 | github-code | 6 |
3844969159 | #! /usr/bin/python2
import pefile
import os
import array
import math
import pickle
import time
# from sklearn.externals import joblib
import joblib
import sys
from .ModulePredict import data_extraction
from .XKendworld import pure_import
import pymongo
import hashlib
myclient = pymongo.MongoClient('DATABASE_URL')
mydb... | fadzniaidil/imawa | malwr/CheckingFile.py | CheckingFile.py | py | 3,102 | python | en | code | 1 | github-code | 6 |
28900645911 |
from keras.models import *
from keras.layers import *
import keras
from dlblocks.keras_utils import allow_growth , showKerasModel
allow_growth()
from dlblocks.pyutils import env_arg
import tensorflow as tf
from Utils import Trainer
class GiretTwoCell(keras.layers.Layer):
def __init__(self, cell_1 , cell_2 , nHi... | divamgupta/mtl_girnet | sequence_labeling/girnet.py | girnet.py | py | 3,916 | python | en | code | 6 | github-code | 6 |
17396933652 | from django.http import HttpResponse
def hello(req):
return HttpResponse('Hello, World !!')
def hello_html(req):
src = []
src.append('<!doctype html>')
src.append('<html>')
src.append('<head>')
src.append('<meta charset="utf-8">')
src.append('<title>Hello, World</title>')
src.append('</h... | RyoJ/hellopython | hello/views.py | views.py | py | 853 | python | en | code | 0 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.