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
6425932746
# 회사원 Demi는 가끔은 야근을 하는데요, 야근을 하면 야근 피로도가 쌓입니다. # 야근 피로도는 야근을 시작한 시점에서 남은 일의 작업량을 제곱하여 더한 값입니다. # Demi는 N시간 동안 야근 피로도를 최소화하도록 일할 겁니다. # Demi가 1시간 동안 작업량 1만큼을 처리할 수 있다고 할 때, 퇴근까지 남은 N 시간과 각 일에 대한 작업량 works에 대해 # 야근 피로도를 최소화한 값을 리턴하는 함수 solution을 완성해주세요. # 제한 사항 # works는 길이 1 이상, 20,000 이하인 배열입니다. # works의 원소는 50...
script-brew/2019_KCC_Summer_Study
programmers/Lv_3/MaengSanha/noOvertime.py
noOvertime.py
py
1,382
python
ko
code
0
github-code
6
41409285856
import json estudantes = [] professores = [] disciplinas = [] turmas = [] matriculas = [] def main(): while True: print("Menu Principal") print("1. Estudantes") print("2. Disciplinas") print("3. Professores") print("4. Turmas") print("5. Matrículas") ...
enzupain/Python-Projetos
sistema gerenciamento academico.py
sistema gerenciamento academico.py
py
18,786
python
pt
code
0
github-code
6
31221042600
'''num=int(input("the number below 30 is:")) if num>0 and num<10: print("the number is between 0to 10") if num>=10 and num<20: #PROMPT METHOD print("the number is between 10to 20") if num>=20 and num<30: print("the number is between 20to 30")''' a= int(input(...
Manikantakalla123/training-phase1
range.py
range.py
py
596
python
en
code
0
github-code
6
10620073145
#!/usr/bin/python import unittest import sys sys.path.insert(0, '../src') from Weapon import Weapon from Character import Character from Clock import Clock from Dice import Dice class WeaponTest(unittest.TestCase): def setUp(self): sut_skills = [] sut_ability_set = {} sut_cooldown_set = {...
jaycarson/fun
app/tst/WeaponTest.py
WeaponTest.py
py
1,076
python
en
code
0
github-code
6
7160469481
import skfuzzy as fuzz from skfuzzy import control as ctrl import numpy as np import matplotlib.pyplot as plt def v(d, a): return np.sqrt((d * 9.81) / np.sin(2 * np.radians(a))) def main(): x_distance = np.arange(1, 100, 5) x_angle = np.arange(1, 90, 1) distance = ctrl.Antecedent(x_distance, 'dista...
DonChaka/PSI
Fuzzy/fuzzy_easy.py
fuzzy_easy.py
py
2,354
python
en
code
0
github-code
6
72033875709
import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('forestfires.csv') pd.plotting.scatter_matrix(dataset) X = dataset.iloc[:,0:12].values y = dataset.iloc[:,-1].values dataset.isnull().sum() dataset.info() temp = pd.DataFrame(X[:,[2,3]]) temp_month = pd.get_du...
Manavendrasingh/ML-code
forestfire.py
forestfire.py
py
1,103
python
en
code
0
github-code
6
5345020806
import email.utils import json import os import smtplib import ssl from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from pathlib import Path import jinja2 from dotenv import load_dotenv send_user = "" load_dotenv() class SendEmailController: def __init__(self): pass ...
nguyendoantung/e-maintenance-system
back-end/service/utils/email/EmailController.py
EmailController.py
py
3,978
python
en
code
0
github-code
6
1633248512
from builtins import next from builtins import range import os import datetime from xml.sax.saxutils import quoteattr import sys import logging import random import glob from itertools import cycle from flask import Blueprint, url_for, Response, stream_with_context, send_file, \ jsonify from werkzeug.datastructure...
cmusatyalab/opendiamond
opendiamond/dataretriever/augment_store.py
augment_store.py
py
6,831
python
en
code
19
github-code
6
655282827
import argparse import os import torch import torch_em from torch_em.model import AnisotropicUNet ROOT = '/scratch/pape/mito_em/data' def get_loader(datasets, patch_shape, batch_size=1, n_samples=None, roi=None): paths = [ os.path.join(ROOT, f'{ds}.n5') for ds in datasets ...
constantinpape/torch-em
experiments/unet-segmentation/mitochondria-segmentation/mito-em/challenge/embeddings/train_embeddings.py
train_embeddings.py
py
4,556
python
en
code
42
github-code
6
11499299532
import requests,json def ranking(duration="daily",ranking_type="break",offset=0,lim=20,unit=False): try: resp = requests.get(f'https://w4.minecraftserver.jp/api/ranking?type={ranking_type}k&offset={offset}&lim={lim}&duration={duration}') data_json = json.loads(resp.text) rank_list = list(dat...
nekorobi-0/seichi_ranking
seichi_ranking.py
seichi_ranking.py
py
3,146
python
en
code
2
github-code
6
26042467106
from __future__ import annotations import logging from abc import ABCMeta from dataclasses import dataclass from pants.core.util_rules.environments import EnvironmentNameRequest from pants.engine.environment import EnvironmentName from pants.engine.fs import MergeDigests, Snapshot, Workspace from pants.engine.goal im...
pantsbuild/pants
src/python/pants/core/goals/generate_snapshots.py
generate_snapshots.py
py
3,031
python
en
code
2,896
github-code
6
30827334271
import json import os class FileUtils: @staticmethod def readJsonFile(filePath): with open(filePath, 'r', encoding='utf-8') as file: jsonData = json.load(file) return jsonData @staticmethod def writeJsonFile(filePath, jsonData): with open(filePath, 'w', encoding='u...
Danny0515/Portfolio-crawler
src/main/utils/FileUtils.py
FileUtils.py
py
622
python
en
code
0
github-code
6
29852066628
__author__ = "Rohit N Dubey" from django.conf.urls import patterns, include, url from django.contrib import admin from views import Ignite from . import prod urlpatterns = patterns('', url(r'^ui/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': prod.UI_ROOT, }), url(r'^api/pool...
salran40/POAP
ignite/urls.py
urls.py
py
805
python
en
code
0
github-code
6
9777903968
import math from django.db import models from django.db.models.signals import pre_save, post_save from apps.addresses.models import Address from apps.carts.models import Cart from apps.billing.models import BillingProfile from main.utils import unique_order_id_generator # ORDER STATUS OPTIONS ORDER_STATUS_CHOICES = (...
ehoversten/Ecommerce_Django
main/apps/orders/models.py
models.py
py
4,469
python
en
code
2
github-code
6
73100458107
# Network Traffic Analyzer: # Analyze network packet captures for anomalies and threats. # pip install pyshark ''' Python script that reads a Wireshark PCAP file and performs basic security analysis, such as identifying suspicious traffic, detecting port scans, and checking for potential security threats. The scrip...
Cnawel/greyhat-python
wireshark/traffice_analyzer.py
traffice_analyzer.py
py
1,415
python
en
code
0
github-code
6
41858795618
############################################################################################# # Foi feita uma estatística em cinco cidades brasileiras para coletar dados sobre acidentes # # de trânsito. Foram obtidos os seguintes dados: # # a) Código da cidade; ...
nralex/Python
3-EstruturaDeRepeticao/exercício40.py
exercício40.py
py
2,234
python
pt
code
0
github-code
6
15363352723
# ABC095 - C a,b,c,x,y = [int(x) for x in input().split()] ans = 0 ans += min((a+b)*min(x,y),c*2*min(x,y)) # 先ずmin(x,y)個まで買うときのパターンを考える if x == y: print(ans) exit() if x > y: # 足りないピザの情報を記録 rest = ["x",max(x,y)-min(x,y)] else: rest = ["y",max(...
idylle-cynique/atcoder_problems
AtCoder Beginners Contest/ABC095-C.py
ABC095-C.py
py
513
python
en
code
0
github-code
6
12959904969
from .declarative import ( declarative, get_declared, get_members, ) from .dispatch import dispatch from .evaluate import ( evaluate, evaluate_recursive, evaluate_recursive_strict, evaluate_strict, get_callable_description, matches, ) from .namespace import ( EMPTY, flatten, ...
jlubcke/tri.declarative
lib/tri_declarative/__init__.py
__init__.py
py
6,981
python
en
code
17
github-code
6
30886261452
######### import statements for sample_models.py ########### from keras import backend as K from keras.models import Model from keras.layers import (BatchNormalization, Conv1D, Dense, Input, TimeDistributed, Activation, Bidirectional, SimpleRNN, GRU, LSTM) ################################ ########### import...
MdAbuNafeeIbnaZahid/English-Speech-to-Text-Using-Keras
speech-recognition-neural-network/train.py
train.py
py
31,706
python
en
code
6
github-code
6
28892210067
import os import time def log(filename, text): """ Writes text to file in logs/mainnet/filename and adds a timestamp :param filename: filename :param text: text :return: None """ path = "logs/mainnet/" if not os.path.isdir("logs/"): os.makedirs("logs/") if not os.path.isdi...
Devel484/Equalizer
API/log.py
log.py
py
871
python
en
code
4
github-code
6
32028505345
#x = int(input()) #y = int(input()) #z = int(input()) #n = int(input()) # #array = [] #for valuex in range(0,x+1): # for valuey in range (0,y+1): # for valuez in range (0,z+1): # if (valuex + valuey + valuez ==n): # continue # else: # array.append([value...
Andreius-14/Notas_Mini
3.Python/Hackerrank/array.py
array.py
py
899
python
en
code
0
github-code
6
6309221669
# this sets your path correctly so the imports work import sys import os sys.path.insert(1, os.path.dirname(os.getcwd())) from api import QuorumAPI import json # this library will let us turn dictionaries into csv files import csv STATES = { 'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas', ...
wynonna/from_GWC_laptop
quorum-gwc-master/project_2/main.py
main.py
py
5,060
python
en
code
0
github-code
6
37559653754
from selenium import webdriver import time # Have to change the path according to where your chromedriver locate PATH = "C:\Program Files (x86)\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.get("http://ec2-54-208-152-154.compute-1.amazonaws.com/") arrayOfBar = [] arrayLeftBowl = [] arrayRight...
LiyaNorng/Fetch-Rewards-Coding-Exercise
FakeGold.py
FakeGold.py
py
2,344
python
en
code
1
github-code
6
60822349
""" scrapy1.5限制request.callback and request.errback不能为非None以外的任何非可调用对象,导致一些功能无法实现。这里解除该限制 """ from scrapy import Request as _Request from scrapy.http.headers import Headers class Request(_Request): def __init__(self, url, callback=None, method='GET', headers=None, body=None, cookies=None, meta=No...
ShichaoMa/structure_spider
structor/custom_request.py
custom_request.py
py
1,255
python
en
code
29
github-code
6
24452709455
import json import os import random from nonebot import on_keyword, logger from nonebot.adapters.mirai2 import MessageSegment, Bot, Event tarot = on_keyword({"塔罗牌"}, priority=5) @tarot.handle() async def send_tarot(bot: Bot, event: Event): """塔罗牌""" card, filename = await get_random_tarot() image_dir = ...
mzttsaintly/Warfarin-bot
warfarin/plugins/Tarot/__init__.py
__init__.py
py
1,590
python
en
code
1
github-code
6
32509281023
import torch import torch.nn as nn # nn.linear 라이브러리를 사용하기 위해 import # F.mse(mean squared error) <- linear regression, LOSS Function 존재 # Classification problem에서 사용하는 loss function : Cross-Entropy import torch.nn.functional as F import torch.optim as optim # SGD, Adam, etc.최적화 라이브러리 # 임의 데이터 생성 # 입력이 1, 출력이 1...
JEONJinah/Shin
multi_varialbe_LR.py
multi_varialbe_LR.py
py
2,761
python
ko
code
0
github-code
6
38958650130
import os if not os.path.exists('./checkpoints'): os.makedirs('./checkpoints') if not os.path.exists('./model'): os.makedirs('./model') #Simulation configuration MAX_EPISODE = 500 TS = 1e-3 CLR_DECAY = 0 ALR_DECAY = 0 # Hyper-parameters WARMUP = False EPS_WARM = 5 #Learning strategies PANDA = True TRAIN ...
giuliomattera/Cartpole-RL-agents-control-ros-bridge-for-simulink
rl_connection/src/config.py
config.py
py
328
python
en
code
6
github-code
6
18307407152
import importlib.util as iutil import os from datetime import datetime from time import perf_counter from uuid import uuid4 import numpy as np import yaml from aequilibrae.distribution.ipf_core import ipf_core from aequilibrae.context import get_active_project from aequilibrae.matrix import AequilibraeMatrix, Aequili...
AequilibraE/aequilibrae
aequilibrae/distribution/ipf.py
ipf.py
py
10,544
python
en
code
140
github-code
6
32483785153
import random from collections import Counter import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule, Scale, bias_init_with_prob, normal_init from mmcv.runner import force_fp32 import nltk from nltk.cluster.kmeans import KMeansClusterer from mmdet.core import (anchor_ins...
johnran103/mmdet
test_dy_conv.py
test_dy_conv.py
py
5,635
python
en
code
1
github-code
6
17940292131
from sklearn.metrics import confusion_matrix, roc_auc_score import json import numpy as np def general_result(y_true, y_score, threshold=0.6): def pred(score, best_thresh): label = 0 if score > best_thresh: label = 1 return label y_score = np.array(y_score) if len(y_scor...
jingmouren/antifraud
antifraud/metrics/normal_function.py
normal_function.py
py
2,233
python
en
code
0
github-code
6
71567880507
class Zoo: __animals = 0 def __init__(self, name): self.name = name self.mammals =[] self.fishes = [] self.birds = [] def add_animal(self, species, name): if species == 'mammal': self.mammals.append(name) elif species == 'fish': self.f...
lorindi/SoftUni-Software-Engineering
Programming-Fundamentals-with-Python/6.Objects and Classes/4_zoo.py
4_zoo.py
py
1,179
python
en
code
3
github-code
6
36396554295
""" Compare catalogs of candidates and benchmarks. """ from __future__ import annotations # __all__ = ['*'] __author__ = "Fernando Aristizabal" from typing import Iterable, Optional, Callable, Tuple import os import pandas as pd from rioxarray import open_rasterio as rxr_or import xarray as xr import dask.dataframe ...
NOAA-OWP/gval
src/gval/catalogs/catalogs.py
catalogs.py
py
9,027
python
en
code
14
github-code
6
1547074247
from settings import * # Import Data df = pd.read_csv("data/mpg_ggplot2.csv") # Draw Stripplot fig, ax = plt.subplots(figsize=(16, 10), dpi=80) sns.stripplot(df.cty, df.hwy, jitter=0.25, size=8, ax=ax, linewidth=.5) # Decorations plt.title('Use jittered plots to avoid overlapping of points', fontsize=22) plt.show()
Rygor83/Plotting_with_python
05.py
05.py
py
320
python
en
code
1
github-code
6
29643271631
# -*- coding: utf-8 -*- # (c) 2015 Alfredo de la Fuente - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import models, fields, api from dateutil.relativedelta import relativedelta class ProcurementOrder(models.Model): _inherit = 'procurement.order' @api.multi def ...
odoomrp/odoomrp-wip
procurement_plan/models/procurement.py
procurement.py
py
5,931
python
en
code
119
github-code
6
35093472448
import pygame, sys, operator, random, time from pygame.locals import * # Global variables WIDTH = 800 HEIGHT = 500 SUB_SPEED = 3 BUBBLE_MAX_SPEED = 1 TIME_LIMIT = 30 BONUS_SCORE = 1500 BLACK = (0, 0, 0) BLUE = (12,34,56) RED = (255,0,0) WHITE = (255,255,255) x_sub = 40 y_sub = 250 score = 0 game_end = time.time() + ...
nicoseng/bubble_blaster
test.py
test.py
py
7,112
python
en
code
0
github-code
6
9799846415
# CSC_120 Logbook : Pg 9, Exercise 4 # Start Program # Variable declaration and initialization v = 512 w = 282 x = 47.48 y = 5 # Calculation phase z = (v - w) / (x + y) # Outputs the result of the computation print("The result of the computation is : ", z) # End Program
Muhdal-Amin/CSC_120_pg9
compute/compute.py
compute.py
py
277
python
en
code
0
github-code
6
20269902024
import os.path import math import numpy import json import bz2 import platereader from platereader.replicate import Replicate from platereader.statusmessage import StatusMessage, Severity from platereader.csvunicode import CsvFileUnicodeWriter, CsvFileUnicodeReader from platereader.parser import tecan, bioscreen clas...
platereader/gathode
platereader/plate.py
plate.py
py
71,939
python
en
code
4
github-code
6
648697707
import numbers import time from itertools import product import numpy as np import torch try: from tqdm import tqdm except ImportError: def tqdm(x): return x def product1d(inrange): for ii in inrange: yield ii def slice_to_start_stop(s, size): """For a single dimension with a give...
constantinpape/3d-unet-benchmarks
bench_util/inference.py
inference.py
py
7,760
python
en
code
3
github-code
6
29007933984
# Databricks notebook source from pyspark.sql.functions import expr, col import pyspark.sql.functions as fn sampleEmployee = spark.read.format("csv").option("header","true").load("dbfs:/FileStore/shared_uploads/bhaskar.dakoori072@gmail.com/us_500.csv") # COMMAND ---------- employeeDF = sampleEmployee.withColumn('web'...
bhaskar553/DatabricksAssignment
Vaccine Drive Assignment.py
Vaccine Drive Assignment.py
py
2,302
python
en
code
0
github-code
6
31273796258
#This file contains helpers that help the process of the assembler #Helps to get the name of the new file def fix_name(line, op = "//"): opIndx = line.find(op) if opIndx == -1: #Doesnt found the op return line elif opIndx == 0: #The comment is on the beginning of the line return ...
fcortesj/Computer_Architecture
proyectos/06/src/utils.py
utils.py
py
1,823
python
en
code
0
github-code
6
43734225885
# -*- coding: utf-8 -*- """ Created on Mon May 10 19:03:44 2021 @author: Samael Olascoaga @email: olaskuaga@gmail.com """ import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt df = pd.read_csv('drugbank.csv') overlap = [] for i in range(0, 1000000): set1 = s...
Olascoaga/Senotherapy
bootstrapping_targets.py
bootstrapping_targets.py
py
938
python
en
code
1
github-code
6
21419147973
import numpy as np from os.path import join from psbody.mesh import Mesh from fitting.landmarks import load_embedding, landmark_error_3d, mesh_points_by_barycentric_coordinates, load_picked_points from fitting.util import load_binary_pickle, write_simple_obj, safe_mkdir, get_unit_factor import open3d as o3d import argp...
qdmy/flame-fitting
modify_pointcloud.py
modify_pointcloud.py
py
11,254
python
en
code
0
github-code
6
30353219011
from os.path import abspath from io import BytesIO import copy # Local imports. from common import TestCase, get_example_data class TestOptionalCollection(TestCase): def test(self): self.main() def do(self): ############################################################ # Imports. ...
enthought/mayavi
integrationtests/mayavi/test_optional_collection.py
test_optional_collection.py
py
4,072
python
en
code
1,177
github-code
6
28300388553
import pandas as pd from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # Load the datasets regular_season_results = pd.read_csv('MRegularSeasonDetailedResults.csv') tournament_results = pd.read_csv('MNCAATourneyDetaile...
lakshayMahajan/March-Madness-ML
madness.py
madness.py
py
4,404
python
en
code
0
github-code
6
30138290765
# !/usr/local/python/bin/python # -*- coding: utf-8 -*- # (C) Wu Dong, 2020 # All rights reserved # @Author: 'Wu Dong <wudong@eastwu.cn>' # @Time: '2020-04-09 14:39' """ 演示自定义响应类 """ # sys import json # 3p from flask import Flask from pre_request import BaseResponse from pre_request import pre, Rule class CustomRespo...
Eastwu5788/pre-request
examples/example_flask/example_response.py
example_response.py
py
1,281
python
en
code
55
github-code
6
14149751216
def freq_table(sentence): """Returns a table with occurences of each letter in the string. Case insensitive""" sentence = sentence.lower() sentence = sentence.replace(" ", "") letter_dict = {} for letter in sentence: letter_dict[letter] = letter_dict.get(letter, 0) + 1 keys_list = list(...
Tomasz-Kluczkowski/Education-Beginner-Level
THINK LIKE A COMPUTER SCIENTIST FOR PYTHON 3/CHAPTER 20 DICTIONARIES/string frequency table.py
string frequency table.py
py
505
python
en
code
0
github-code
6
37091297903
#!/usr/bin/python from __future__ import print_function import negspy.coordinates as nc import sys import argparse from itertools import tee def pairwise(iterable): "s -> (s0, s1), (s2, s3), (s4, s5), ..." a = iter(iterable) return zip(a, a) def main(): parser = argparse.ArgumentParser(description="...
pkerpedjiev/negspy
scripts/chr_pos_to_genome_pos.py
chr_pos_to_genome_pos.py
py
3,851
python
en
code
9
github-code
6
13767499463
import os import pytest from stips import stips_data_base # from stips.utilities import SelectParameter # from stips.utilities.utilities import GetParameter @pytest.fixture(autouse=True) def pre_post_test(): # Setup config file environment variable config_param = None if "stips_config" in os.environ: ...
spacetelescope/STScI-STIPS
stips/utilities/tests/test_config.py
test_config.py
py
2,091
python
en
code
12
github-code
6
10211319525
# -*- coding: utf8 -*- from django.test import TestCase from django.apps import apps from blog.models import ExecuteStatus, Tag from blog.models import TestCase as TC from django.contrib.auth.models import User import datetime import os class TestCaseModelTestCase(TestCase): def setUp(self): #apps.get_app...
charleszh/rf-web
DjangoDemo/blog/tests/test_models.py
test_models.py
py
1,209
python
en
code
0
github-code
6
15565393240
import logging import os from typing import List from plumbum import cmd, local from pathlib import Path import doit from doit.action import CmdAction from constants import DEFAULT_DB, DB_USERNAME, DB_PASSWORD, VERBOSITY_DEFAULT logging.basicConfig() logger = logging.getLogger("dodo") logger.setLevel(logging.DEBUG) ...
karthik-ramanathan-3006/15-799-Special-Topics-in-Database-Systems
dodos/dodo.py
dodo.py
py
7,577
python
en
code
0
github-code
6
8927274924
from datetime import datetime as dt from datetime import timedelta import pickle import time import dask.dataframe as dd from dask.distributed import as_completed, worker_client import numpy as np import pandas as pd import requests import s3fs BUCKET = "insulator-citi-bikecaster" INSULATOR_URLS = [ "https://api...
EthanRosenthal/citi-bikecaster-model
calcs.py
calcs.py
py
4,374
python
en
code
0
github-code
6
27646567910
import http.server from colorama import Fore, Style import os import cgi HOST_NAME = '127.0.0.1' # Kali IP address PORT_NUMBER = 80 # Listening port number class MyHandler(http.server.BaseHTTPRequestHandler): # MyHandler defines what we should do from the client / target def do_GET(s): # If we got a G...
zAbuQasem/Misc
http reverse shell/Server.py
Server.py
py
2,367
python
en
code
6
github-code
6
9238631713
# -*- coding: utf-8 -*- """ Created on Wed Mar 6 17:18:39 2019 @author: akshaf """ import numpy as np data1 = [[1,2,3,4],[5,6,7,8],["ab","c","d","d"]] print("data1",data1) type(data1) a = np.array(data1) a type(a) # This give numpy array data1.__class__ # similar to type(data1) function a.__class__ # similar to t...
akshafmulla/PythonForDataScience
Basics_of_Python/Code/16 Numpy.py
16 Numpy.py
py
936
python
en
code
0
github-code
6
32312362218
from osgeo import gdal import numpy as np # calculating SAVI and NDVI noDataVal = -28672 def calculate_ndvi(nir, red): valid_mask = (nir != noDataVal) & (red != noDataVal) ndvi_band = np.where(valid_mask, (nir - red) / (nir + red), np.nan) return ndvi_band # Function to calculate SAVI def calculate_savi(n...
dustnvan/ET_goes16
goes_export_geotiff/export_savi_ndvi.py
export_savi_ndvi.py
py
2,866
python
en
code
0
github-code
6
10389322209
import glob import os from os import path as op import cv2 import numpy as np from torch.utils.data import DataLoader from pathlib import Path from PIL import Image, ImageFilter from detection.dummy_cnn.dataset import BaseBillOnBackGroundSet from tqdm import tqdm from sewar.full_ref import sam as sim_measure from iter...
KaraLandes/BachelorsProject
Repo/compare_data_similarity.py
compare_data_similarity.py
py
8,019
python
en
code
0
github-code
6
23396456749
''' locals() 函数会以字典类型返回当前位置的全部局部变量。 对于函数, 方法, lambda 函式, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True。 语法 locals() 函数语法: locals() 参数 无 返回值 返回字典类型的局部变量 1 不要修改locals()返回的字典中的内容;改变可能不会影响解析器对局部变量的使用。 2 在函数体内调用locals(),返回的是自由变量。修改自由变量不会影响解析器对变量的使用。 3 不能在类区域内返回自由变量。 ''' def test_py(arg): z=1 print(locals()) test_py(6) #输出...
tyutltf/Python_funs
locals函数详解.py
locals函数详解.py
py
952
python
zh
code
20
github-code
6
71345155708
#!/usr/bin/env python import unittest import copy from ct.cert_analysis import base_check_test from ct.cert_analysis import extensions from ct.crypto.asn1 import oid from ct.crypto.asn1 import types from ct.crypto import cert def remove_extension(certificate, ex_oid): # If given extension exists in certificate, t...
kubeup/archon
vendor/github.com/google/certificate-transparency/python/ct/cert_analysis/extensions_test.py
extensions_test.py
py
2,258
python
en
code
194
github-code
6
33229423614
# For each cylinder in the scan, find its ray and depth. # 03_c_find_cylinders # Claus Brenner, 09 NOV 2012 from pylab import * from lego_robot import * # Find the derivative in scan data, ignoring invalid measurements. def compute_derivative(scan, min_dist): jumps = [ 0 ] for i in xrange(1, len(scan)...
jfrascon/SLAM_AND_PATH_PLANNING_ALGORITHMS
01-GETTING_STARTED/CODE/slam_03_c_find_cylinders_question.py
slam_03_c_find_cylinders_question.py
py
2,747
python
en
code
129
github-code
6
31282202503
# pylint: disable=missing-docstring # pylint: disable=invalid-name import functools import re # import unicodedata from string import punctuation as PUNCTUATIONS import numpy as np from doors.dates import get_timestamp SPECIAL_PUNCTUATIONS = PUNCTUATIONS.replace("_", "") def not_is_feat(col): return not is_fe...
chechir/doors
doors/strings.py
strings.py
py
4,406
python
en
code
0
github-code
6
8963786234
#!/usr/bin/env python3 import multiprocessing from queue import Empty import subprocess import Robocode import os, os.path from datetime import datetime import sys import time # This class knows about Robocode and the Database. def recommendedWorkers(): cpus = multiprocessing.cpu_count() if cp...
mojomojomojo/di-arena
lib/BattleRunner.py
BattleRunner.py
py
4,617
python
en
code
0
github-code
6
34688027576
#!/usr/bin/python def modular_helper(base, exponent, modulus, prefactor=1): c = 1 for k in range(exponent): c = (c * base) % modulus return ((prefactor % modulus) * c) % modulus def fibN(n): phi = (1 + 5 ** 0.5) / 2 return int(phi ** n / 5 ** 0.5 + 0.5) # Alternate problem solutions start...
pkumar0508/project-euler
alternate_solutions.py
alternate_solutions.py
py
4,179
python
en
code
0
github-code
6
40409186941
#!/usr/bin/env python3 # unit_test/cisco/nxos/unit_test_nxos_vlan.py our_version = 107 from ask.common.playbook import Playbook from ask.common.log import Log from ask.cisco.nxos.nxos_vlan import NxosVlan ansible_module = 'nxos_vlan' ansible_host = 'dc-101' # must be in ansible inventory log = Log('unit_test_{}'.form...
allenrobel/ask
unit_test/cisco/nxos/unit_test_nxos_vlan.py
unit_test_nxos_vlan.py
py
1,944
python
en
code
2
github-code
6
22461213731
import xarray as xr import numpy as np #Este script baixa os dados do hycom para os períodos selecionados para o experimento GLBv0.08/expt_53.X #Importante: Por conta da estruturas dos servidores OpenDAP, e preciso baixar o dado por cada passo de tempo para postriormente concaternar #Para concatenar, selecionar os ar...
Igoratake/Hycom_Opendap
baixa_hycom_2014_frente_Pontual.py
baixa_hycom_2014_frente_Pontual.py
py
2,248
python
pt
code
0
github-code
6
73789786749
valores = [[],[]] for n in range(0,7): v = int(input('digite um valor: ')) if v%2==0: valores[0].append(v) elif v%2!=0: valores[1].append(v) valores[0].sort() valores[1].sort() print(f'os valores pares foram: {valores[0]}' ) print(f'os valores impares foram: {valores[1]}' )
Kaue-Marin/Curso-Python
pacote dowlond/curso python/exercicio85.py
exercicio85.py
py
302
python
pt
code
0
github-code
6
71971288509
from kubeflow.fairing.cloud.docker import get_docker_secret from kubeflow.fairing.constants import constants import json import os def test_docker_secret_spec(): os.environ["DOCKER_CONFIG"] = "/tmp" config_dir = os.environ.get('DOCKER_CONFIG') config_file_name = 'config.json' config_file = os.path.joi...
kubeflow/fairing
tests/unit/cloud/test_docker.py
test_docker.py
py
578
python
en
code
336
github-code
6
69894822589
from airflow import DAG from airflow.operators.bash_operator import BashOperator import datetime as dt from airflow.utils.dates import days_ago default_args = { 'owner': 'gregh', 'start_date': days_ago(0), 'email': ['myemail@gmail.com'], 'email_on_failure': True, 'email_on_retry': True, 'retri...
gregh13/Data-Engineering
Projects/Capstone Project/Task 5/Part Two - Apache Airflow ETL/process_web_log.py
process_web_log.py
py
1,221
python
en
code
0
github-code
6
21354655285
# # @lc app=leetcode.cn id=438 lang=python3 # # [438] 找到字符串中所有字母异位词 # # @lc code=start class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: def s2vec(s): vec = [0]*26 for c in s: vec[ord(c)-ord('a')] += 1 return tuple(vec) pvec = s...
Alex-Beng/ojs
FuckLeetcode/438.找到字符串中所有字母异位词.py
438.找到字符串中所有字母异位词.py
py
801
python
en
code
0
github-code
6
72056615229
spend_data = open("env_spending_ranks.csv") ranks = [[] for _ in range(5)] for i, line in enumerate(spend_data): if i == 0: continue else: temp = line.strip().split(',') for j, element in enumerate(temp): if j % 3 == 0: ranks[j//3].append(element) # 0: 2011, ...
jamesryan094/us_aqi_data_wrangling
ranks_per_year.py
ranks_per_year.py
py
1,172
python
en
code
1
github-code
6
20444657924
from selenium import webdriver from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup import time import csv class Scraper: def __init__(self, url): self.driver = webdriver.Chrome("./chromedriver", options=self.set_chrome_options()) self.url = url self.open_url...
RasbeeTech/Web-Scraper
scraper.py
scraper.py
py
3,381
python
en
code
1
github-code
6
6606609236
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: candirow = len(matrix) - 1 for row in range(len(matrix)): if(matrix[row][0] > target): if(row == 0): return False candirow = row - 1 b...
JeongGod/Algo-study
leehyowonzero/12week/search-a-2d-matrix.py
search-a-2d-matrix.py
py
603
python
en
code
7
github-code
6
19705123014
# -*- coding: utf-8 -*- case = 0 while True: N, Q = [int(x) for x in input().split()] if not Q and not N: break case += 1 print(f"CASE# {case}:") marbles = [] for _ in range(N): marbles.append(int(input())) marbles.sort() for i in range(Q): fi...
caioopra/4o-Semestre-CCO
paradigmas/2-python_multiparadigma/atividade2/1025.py
1025.py
py
526
python
en
code
0
github-code
6
43216721070
import os import shlex import subprocess import numpy as np import pandas as pd from SentiCR.SentiCR.SentiCR import SentiCR def clean_data(df): df = df.copy() # fill all rows with corresponding discussion link df[df['discussion_link'] == ""] = np.NaN df['discussion_link'] = df['discussion_link'].fill...
saramangialavori/AutomatingCodeReview3.0
manual_inspection/build_oracle.py
build_oracle.py
py
6,785
python
en
code
0
github-code
6
18388623624
## Első feladat for i in range(1,10): print(1/i) ## Második feladat hatvany=int(input("Kérem a hatvány alapot:")) kitevo=int(input("Kérem a hatvány kitevőt:")) hatvanyertek=(hatvany**kitevo) print(hatvanyertek) ## Harmadik feladat while True: szam=int(input("Kérek egy pozitív számot: ")) if szam<=0: ...
matyast/estioraimunka
feladat.py
feladat.py
py
700
python
hu
code
0
github-code
6
43597436816
# string: ordered, ____, text representation # init from timeit import default_timer as timer movie_name = "The murder on the orient express" # single quote fav_quote = 'That\'s what she said' # print(fav_quote) # double quote fav_quote = "That's what she said" # print(fav_quote) quote = "Where should I go? \ To th...
akshitone/fy-mca-class-work
DivB/string.py
string.py
py
2,834
python
en
code
1
github-code
6
18757756190
import argparse import cv2 # ArgParse é usado para captar argumentos passados na chamada do .py no CMD ap = argparse.ArgumentParser() # Aqui definimos a label do argumento esperado ap.add_argument("-i", "--image", required=True, help= "Path to the image") # Criamos um dicionário que receberá os valores...
CarlosAlfredoOliveiraDeLima/Practical-Python-and-OpenCV-Book
01 - load_display_save.py
01 - load_display_save.py
py
1,041
python
pt
code
0
github-code
6
6118401140
''' Урок 2. Парсинг HTML. BeautifulSoup, MongoDB Необходимо собрать информацию о вакансиях на вводимую должность (используем input) с сайтов Superjob(необязательно) и HH(обязательно). Приложение должно анализировать несколько страниц сайта (также вводим через input). Получившийся список должен содержать в себе миниму...
XYI7I/GeekBrains
AI/Method_collecting_Internet_data/Lesson2/lesson2.py
lesson2.py
py
10,254
python
ru
code
0
github-code
6
21998861864
n=int(input()) arr=list(map(int,input().split())) sof=0 sos=0 for i in range(n): if(i<n//2): sof+=arr[i] else: sos+=arr[i] print(abs(sof-sos))
Lavanya18901/codemind-python
difference_between_sum_of_first_half_and_second_half_in_an_array.py
difference_between_sum_of_first_half_and_second_half_in_an_array.py
py
158
python
en
code
0
github-code
6
71484733948
def is_finish(x, y): return x == 4 l = list(range(4)) cnt = 0 a = set(range(10)) assert(len(a & set(l)) == 4) print(*l) cnt += 1 X, Y = map(int, input().split()) if is_finish(X, Y): exit(0) for i in range(4): not_in = a - set(l) for n in not_in: tmpl = l[:] tmpl[i] = n assert(le...
knuu/competitive-programming
yukicoder/yuki355.py
yuki355.py
py
1,137
python
en
code
1
github-code
6
31356164054
import os import argparse import re import textwrap default_mpi_function_list = [ "int MPI_Init(int *argc, char ***argv)", "int MPI_Finalize(void)", "int MPI_Comm_rank(MPI_Comm comm, int *rank)", "int MPI_Comm_size(MPI_Comm comm, int *size)", "int MPI_Send(const void *buf, int count, MPI_Datatype d...
cea-hpc/selFIe
src/parse_mpi.py
parse_mpi.py
py
9,164
python
en
code
16
github-code
6
18798291843
import matplotlib.pyplot as plt import random import numpy as np from IPython.display import display, clear_output import time def head_home(x, y): """ Head home down and to the left. Parameters ---------- x : float Horizontal coordinate. y : float Vertical coor...
msu-cmse-courses/cmse202-F22-data
code_samples/ant_function.py
ant_function.py
py
4,304
python
en
code
1
github-code
6
14868890436
from django.views.generic.base import TemplateView from albums.forms import FileForm from albums.models import Album, File from core.decorators import view_decorator from core.views import ResourceView class AlbumPage(TemplateView): template_name = "albums/main.html" def expose(view): view.expose = True ...
qrees/backbone-gallery
albums/views.py
views.py
py
508
python
en
code
0
github-code
6
20156935479
from flask import request def validate_id(id): # if not found in params if (id is None): raise TypeError("Request params (id) not found") # if description params is empty if not id: raise ValueError("id is empty") # if not integer if not isinstance(id, int): rais...
adriangohjw/cz2006-software-engineering
contracts/point_contracts.py
point_contracts.py
py
1,360
python
en
code
0
github-code
6
38815716976
import argparse import asyncio import csv import functools import gc import hashlib import http.client import importlib import io import math import platform import re import socket import statistics import sys import textwrap import time import urllib.parse from typing import Callable, Awaitable, Tuple, Iterable, Opti...
ska-sa/pyconza2020-httpbench
httpbench.py
httpbench.py
py
8,026
python
en
code
4
github-code
6
25073375848
import math def f(a:float, b:float, c:float) -> float: if a==0: raise Exception("a no puede ser cero") if b*b< 4*a*c: raise Exception("Esos valores dan un resultado complejo") try: d=(-b + math.sqrt(b*b - 4*a*c))/(2*a) except: print("Hay un error") return d a=0 b=3 c=-3 print(f(a,b,c))
Gohan2021/ProgAplicada
tarea_2023_0227.py
tarea_2023_0227.py
py
313
python
es
code
0
github-code
6
10819469391
import numpy as np import argparse import imutils import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i","--image",required = True, help="Path of Image File") args = vars(ap.parse_args()) #image = cv2.imread("image.png") print("Path: ", args["image"]) image = cv2.imread(args["image"]) # find all the 'black' ...
Pallavi04/ComputerVision
FindShapes/shape.py
shape.py
py
837
python
en
code
0
github-code
6
27022143594
from pymongo import MongoClient import pprint from urllib.request import urlopen from bs4 import BeautifulSoup class Data_extraction_creation: def __init__(self): self.source="" self.search="" self.search_length=0 def getting_source(self): #client=MongoClient("mongodb://127.0...
Harkishen-Singh/Uber-App-Record-Analysis
creating databasse copy.py
creating databasse copy.py
py
7,444
python
en
code
0
github-code
6
21892483057
#!/bin/python3 import os import sys # # Complete the xorMatrix function below. # #define GET_BIT(x, bit) (((x)>>(bit)) & 1ULL) def xorMatrix(m, first_row): m = m - 1 for j in range(63, -1, -1): if((m>>j) & 1 == 1): intialRow = first_row.copy() ...
shady236/HackerRank-Solutions
Algorithms/XOR Matrix/XOR Matrix.py
XOR Matrix.py
py
803
python
en
code
0
github-code
6
29381018111
import copy import tempfile import yaml import re import os import constellation.vault as vault from constellation.util import ImageReference def read_yaml(filename): with open(filename, "r") as f: dat = yaml.load(f, Loader=yaml.SafeLoader) dat = parse_env_vars(dat) return dat def config_build(...
reside-ic/constellation
constellation/config.py
config.py
py
4,914
python
en
code
0
github-code
6
10252651311
from secuenciales.colaprioridad import * from secuenciales.pila import Pila import copy class nodoGrafo: def __init__(self, nodo_padre, torreA, torreB, torreC): self.torreA = torreA self.torreB = torreB self.torreC = torreC self.padre = nodo_padre self.nivel = self.calcular...
difer19/Estructuras-de-Datos
GrafosA_Star.py
GrafosA_Star.py
py
7,942
python
es
code
0
github-code
6
26040958016
from __future__ import annotations import logging from dataclasses import dataclass from pants.backend.python.subsystems.twine import TwineSubsystem from pants.backend.python.target_types import PythonDistribution from pants.backend.python.util_rules.pex import PexRequest, VenvPex, VenvPexProcess from pants.core.goal...
pantsbuild/pants
src/python/pants/backend/python/goals/publish.py
publish.py
py
7,218
python
en
code
2,896
github-code
6
24957977468
#!/usr/bin/python3 '''Post the compositions in a given directory filtered or not by a basename now one ehr per composition ''' import json import logging import requests from url_normalize import url_normalize import sys import argparse import os from typing import Any,Callable import re from json_tools import diff ...
crs4/TO_OPENEHR_CONVERTER
COMPOSITIONS_UPLOADER/CompositionUploader.py
CompositionUploader.py
py
11,566
python
en
code
0
github-code
6
23213929420
""" IMU 6-DOF Acceleration - imu_accel_x - imu_accel_y - imu_accel_z Angular speed - imu_gyro_x - imu_gyro_y - imu_gyro_z """ import numpy as np from numpy.linalg import inv from scipy.spatial.transform import Rotation as rot """ X: states: - pitch - roll - yaw (not used) - bias angul...
toshiharutf/Kalman_Filter_GNS_INS
ins_filter_full_state_demo.py
ins_filter_full_state_demo.py
py
5,133
python
en
code
6
github-code
6
28800553771
import os import pytest import pathlib import numpy as np import pandas as pd from math import isclose from cytominer_eval.operations import mp_value from cytominer_eval.utils.mpvalue_utils import ( calculate_mp_value, calculate_mahalanobis, ) # Load CRISPR dataset example_file = "SQ00014610_normalized_feat...
cytomining/cytominer-eval
cytominer_eval/tests/test_operations/test_mp_value.py
test_mp_value.py
py
3,230
python
en
code
7
github-code
6
34218646786
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 6 12:31:40 2023 @author: tillappel """ from arc import * from IPython.display import display, HTML import numpy as np import scipy.constants as sc import matplotlib.pyplot as plt def find_largest_c3(n,n_2, l0, j0): largest_c3_d0 = 0 larges...
tappelnano/RydbergPTG
ARC C3_C6 calc.py
ARC C3_C6 calc.py
py
7,589
python
en
code
0
github-code
6
34565307158
from random import random, randint from collections import deque from math import sin, cos MAXVAL = 200 MAXINSTR = 12 def new_random_code(length): return [ (randint(0, MAXINSTR)) if random() > 0.5 else (randint(MAXINSTR + 1, MAXVAL)) for _ in range(length) ] def point_mutate(code): cod...
gwfellows/trees
grow.py
grow.py
py
2,644
python
en
code
0
github-code
6
5355406850
from odoo import models, fields, api class StockProductionLot(models.Model): _inherit = "stock.production.lot" is_flower = fields.Boolean(related='product_id.is_flower', readonly=True) water_ids = fields.One2many("flower.water", "serial_id") @api.model_create_multi def create(self, vals_list): ...
omar99emad/flower-shop
models/stock_production_lot.py
stock_production_lot.py
py
1,586
python
en
code
0
github-code
6
74190845628
# -*- coding: utf-8 -*- __author__ = "ALEX-CHUN-YU (P76064538@mail.ncku.edu.tw)" from word2vec import Word2Vec as w2v import MySQLdb import numpy as np from bert_embedding import BertEmbedding import codecs import re # Entity to Vector class E2V_BERT: # init def __init__(self): self.db = MySQLdb.connect(host = "127...
Alex-CHUN-YU/Recommender-System
main_embedding/e2v_bert.py
e2v_bert.py
py
9,420
python
en
code
0
github-code
6
31237691124
# 3: Создайте программу “Медицинская анкета”, где вы запросите у пользователя следующие данные: имя, фамилия, возраст и вес. # Выведите результат согласно которому: # Пациент в хорошем состоянии, если ему до 30 лет и вес от 50 и до 120 кг, # Пациенту требуется заняться собой, если ему более 30 и вес меньше 50 или больш...
dreaminkv/python-basics
practical-task-1/practical-task-3.py
practical-task-3.py
py
1,573
python
ru
code
0
github-code
6
36522225710
from sys import setrecursionlimit import threading RECURSION_LIMIT = 10 ** 9 STACK_SIZE = 2 ** 26 setrecursionlimit(RECURSION_LIMIT) threading.stack_size(STACK_SIZE) def dfs(v, used, g, answer): used[v] = 1 for u in g[v]: if used[u] == 0: dfs(u, used, g, answer) answer.append(v) de...
AverPower/Algorithms_and_Structures
10. Graphs - 1/Task D.py
Task D.py
py
1,435
python
en
code
0
github-code
6
30354475241
import setuptools from setuptools import Command try: import numpy from numpy.distutils.command import build, install_data, build_src from numpy.distutils.core import setup HAS_NUMPY = True except ImportError: HAS_NUMPY = False from distutils.command import build, install_data from distutil...
enthought/mayavi
setup.py
setup.py
py
16,576
python
en
code
1,177
github-code
6