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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
29624814063 | '''
反转单链表和双链表
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class DoubleListNode(object):
def __init__(self, x):
self.val = x
self.next = None
self.last = None
class Solution(object):
def rever... | wangxinyufighting/algorithom | CodingInterViewGuide/chapter2_list/question4_reverseList.py | question4_reverseList.py | py | 890 | python | en | code | 0 | github-code | 1 |
22056165678 | import json
import os
import click
from twarc.decorators2 import FileSizeProgressBar
from twarc.expansions import ensure_flattened
@click.command()
@click.option(
'--granularity',
'-g',
type=click.Choice(
['year', 'month', 'day', 'hour', 'minute', 'second'],
case_sensitive=False
),
... | JoanMassachs/twarc-divide | twarc_divide.py | twarc_divide.py | py | 1,448 | python | en | code | 1 | github-code | 1 |
73944536672 | import neurals.data_generation_config as dgc
import neurals.distancefield_utils as df
import model.param as model_param
import copy
import numpy as np
import open3d as o3d
import os
from scipy.spatial.transform import Rotation as scipy_rot
import torch.utils.data
# Each file correspond to a pointcloud
class SmallData... | Ericcsr/synthesize_pregrasp | neurals/dataset.py | dataset.py | py | 6,968 | python | en | code | 8 | github-code | 1 |
8283091296 | # https://github.com/SwarnadeepGhosh
# Six Days Weather Forecast using Python and MetaWeather API
import requests
import time
API_ROOT = 'https://www.metaweather.com'
API_LOCATION = '/api/location/search/?query=' # + city
API_WEATHER = '/api/location/' # + woeid
def print_pause(printable_data):
tim... | SwarnadeepGhosh/Python-Small-Projects | weather_forecast_by_MetaWeather_API.py | weather_forecast_by_MetaWeather_API.py | py | 2,828 | python | en | code | 0 | github-code | 1 |
39538997457 | # -*- coding: utf-8 -*-
# @Author: kivensu
# @Date: 2018-11-19 16:13:28
# @Last Modified by: kivensu
# @Last Modified time: 2018-11-19 16:18:21
# @Email: 749243884@qq.com
prompt = "\nPlease enter the name of city you hava visted: "
prompt += "\n(Enter 'quit' when you are finished.)"
while True:
city = str(inpu... | kivensu/learnpython3 | InputAndWhileCircular/cities.py | cities.py | py | 435 | python | en | code | 0 | github-code | 1 |
70629734115 | import copy
import time
class Problem(object):
def __init__(self, initial):
self.initial = initial
self.type = len(initial)
self.height = int(self.type/3)
def goal_test(self, state):
total = sum(range(1, self.type+1))
for row in range(self.type):
if (len(... | behzad-ost/AI-Sudoku | RBFS_sudoku.py | RBFS_sudoku.py | py | 4,064 | python | en | code | 0 | github-code | 1 |
4517378954 | from lesson09HW.classes.connection_to_db import ConnectionToDB
from lesson09HW.classes.planet import Planet
class PlanetController:
def add_planet(self, planet):
connection_to_db = ConnectionToDB()
current_connection = connection_to_db.get_connection()
cursor = current_connection.cursor()... | su1gen/python-homework | lesson09HW/controllers/planet_controller.py | planet_controller.py | py | 2,854 | python | en | code | 0 | github-code | 1 |
39285486469 | import cv2 as cv
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cm as cm
from time import sleep
import numpy as np
face_detector = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
def show_points(room_size,tracked_points,cam_position,pad=2):
room_width = roo... | PrateekMunjal/Face-detection-webcam-opencv | utils.py | utils.py | py | 1,252 | python | en | code | 1 | github-code | 1 |
70271059555 | # -*- coding: utf-8 -*-
# This software and supporting documentation are distributed by
# Institut Federatif de Recherche 49
# CEA/NeuroSpin, Batiment 145,
# 91191 Gif-sur-Yvette cedex
# France
#
# This software is governed by the CeCILL license version 2 under
# French law and abiding by the rules... | brainvisa/axon | python/brainvisa/data/qt4gui/databaseCheckGUI.py | databaseCheckGUI.py | py | 17,800 | python | en | code | 0 | github-code | 1 |
34469832330 | def is_exist(m, d):
if m <= 12 and d <= 31:
if m == 2 and d <= 28:
return True
elif (m % 2 == 0 and m != 2) and d <= 30:
return True
elif (m % 2 != 0 or m == 8) and d <= 31:
return True
return False
m, d = map(int, input().split())
if is_exist(m, d)... | yeafla530/algorithms | 코드트리/NM/2021년날짜의유무.py | 2021년날짜의유무.py | py | 360 | python | en | code | 0 | github-code | 1 |
11936950572 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 11 14:18:28 2018
@author: shuyun
"""
from sklearn.metrics import classification_report
import scikitplot as skplt
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.metrics import confusion_matrix
import os
import re
import matplotlib
impor... | stevenleejun/automl_pred_lily | utils/utils_model_ana.py | utils_model_ana.py | py | 7,746 | python | en | code | 0 | github-code | 1 |
40141140508 | '''
문제
-수직선 위에 N개의 좌표 X1, X2, ..., XN이 있다. 이 좌표에 좌표 압축을 적용하려고 한다.
Xi를 좌표 압축한 결과 X'i의 값은 Xi > Xj를 만족하는 서로 다른 좌표의 개수와 같아야 한다.
X1, X2, ..., XN에 좌표 압축을 적용한 결과 X'1, X'2, ..., X'N를 출력해보자.
입력
-첫째 줄에 N이 주어진다.
둘째 줄에는 공백 한 칸으로 구분된 X1, X2, ..., XN이 주어진다.
출력
-첫째 줄에 X'1, X'2, ..., X'N을 공백 한 칸으로 구분해서 출력한다.
예제 입력 1
-5
2 4 -10 4 -... | kkangmen/TIL | Baekjoon/Baekjoon_step_problem/12_정렬/10_좌표 압축/10. 좌표 압축.py | 10. 좌표 압축.py | py | 1,029 | python | ko | code | 0 | github-code | 1 |
8316907207 | import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
class RF_plotter(object):
def __init__(self,features,target,model):
'''
:param featu... | LLNL/Sedov-ML | sedov_common/plotters/random_forest_plotter.py | random_forest_plotter.py | py | 6,513 | python | en | code | 5 | github-code | 1 |
1046566195 | # _*_ coding:utf8 _*_
import numpy as np
import tensorflow as tf
from ncfmain import *
data = np.load('data/test_data.npy').item()
print(data['user'][:10])
dataset = tf.data.Dataset.from_tensor_slices(data)
dataset = dataset.shuffle(10000).batch(100)
user = tf.ones(name='user',shape=[None,],dtype=tf.int32)
item = tf.... | Johnwei386/Warehouse | ML/DL/ncf/nfc_demo.py | nfc_demo.py | py | 2,206 | python | en | code | 3 | github-code | 1 |
42447191423 | import json
import os
from logic.payment_method import PaymentMethod
PATH = os.getcwd()
DIR_DATA = PATH + '{0}data{0}'.format(os.sep)
class PaymentMethodController(object):
def __init__(self):
self.file = '{0}{1}'.format(DIR_DATA, 'payment.json')
def add(self, payment_method: PaymentMethod = PaymentM... | ISCODEVUTB/vms | controller/payment_method_controller.py | payment_method_controller.py | py | 1,038 | python | en | code | 0 | github-code | 1 |
40081764036 | from queue import PriorityQueue
class Graph:
def __init__(self):
self.nodes = set()
self.edges = {}
def add_node(self, node):
self.nodes.add(node)
def add_edge(self, start, end, distance):
self.edges.setdefault(start, []).append((end, distance))
... | tanmayjad984/Artificial-Intelligence | 3b_Astarshortdist.py | 3b_Astarshortdist.py | py | 2,054 | python | en | code | 1 | github-code | 1 |
2513105859 | import ape
from ape import Contract, reverts
from utils.checks import check_strategy_totals
from utils.utils import days_to_secs
import pytest
def test__set_uni_fees(
asset,
strategy,
management,
aave,
weth,
):
# Everything should start as 0
assert strategy.uniFees(aave, weth) == 0
ass... | mil0xeth/yearn-v3-AAVE-Delta-Neutral-st-yCRV | tests/test_access.py | test_access.py | py | 2,248 | python | en | code | 0 | github-code | 1 |
41979836202 | import random, sys, time
###########################################################################
# #
# Implement a hash table from scratch! (⑅•ᴗ•⑅) #
# ... | namika2000/STEP_homework | week2/homework1/hashtable.py | hashtable.py | py | 12,130 | python | en | code | 0 | github-code | 1 |
40255164302 | '''数据模块'''
'''
学生选课系统
时间;2020-4-27
版本:1.0.0
作者:刘江
'''
# 开头文档写出 普通用户、课程的保存方式
# 管理员 事先设置好管理员账号密码
# 管理员功能:查看有哪些商品信息
# 增加或删除商品,
# 用户
# 注册 :用户名和密码注册,没有注册过用户的才可以注册成功
# 登录 :用户名和密码登录,登录成功进入选课界面
# 修改登录密码:输入旧密码,再输入新密码
# 查看:查看购物车
# 加购:加入购物车,下次查看可以看到
# 登录前,输入4位验证码才可以执行后续功能
# 定义一个列表,保存一个用户
u1 = ["admin", "123456", "昵称1"]
u2 = ["us... | liujiang9/python0421 | 作业/zuoye01/taobao/shuju.py | shuju.py | py | 1,557 | python | zh | code | 1 | github-code | 1 |
27772819097 | import lbp_face_recognition
from Tkinter import *
import tkFileDialog
from Tkinter import Label,Tk
from PIL import Image, ImageTk
class home:
def __init__(self,master):
lbp_face_recognition.train()
self.master=master
self.f=Frame(master,width=1000,height=600)
self.f.pro... | sudo-sunil/GUI_LLFR | gui.py | gui.py | py | 1,687 | python | en | code | 0 | github-code | 1 |
26447563690 | import os
import sys
import curtin.util as util
from . import populate_one_subcmd
from curtin.log import LOG
def system_upgrade_main(args):
# curtin system-upgrade [--target=/]
if args.target is None:
args.target = "/"
exit_code = 0
try:
util.system_upgrade(target=args.target,
... | rom1212/maas-guide | deploy/curtin-extract/curtin/commands/system_upgrade.py | system_upgrade.py | py | 1,071 | python | en | code | 0 | github-code | 1 |
13042112688 | import pytest
import requests_mock
import datetime
from dateutil.tz import tzutc
from iotile.cloud.cloud import IOTileCloud
from iotile.cloud.config import link_cloud
from iotile.core.dev.config import ConfigManager
from iotile.core.dev.registry import ComponentRegistry
from iotile.core.exceptions import ArgumentError,... | iotile/coretools | iotile_ext_cloud/test/test_login.py | test_login.py | py | 6,110 | python | en | code | 14 | github-code | 1 |
15103968278 | from django.shortcuts import render
from django.shortcuts import redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from... | eruzetaien/PBPtugas2 | todolist/views.py | views.py | py | 3,925 | python | en | code | 0 | github-code | 1 |
5872705859 | # Вспомогательные функции для получения времени пешего похода до метро и коородинат объекта
import requests
import json
import time
from random import randint
from sklearn import metrics
import numpy as np
def regression_results(y_true, y_pred):
# Regression metrics
explained_variance=metrics.explained_varia... | levchCode/MoscowEstate | processing/metro_coords.py | metro_coords.py | py | 2,075 | python | en | code | 1 | github-code | 1 |
13635080325 | import curses
import random
from typing import Tuple, Set
def get_draw_range(
pointer_pos: Tuple[int, int],
map_size: Tuple[int, int],
window_size: Tuple[int, int],
buffer: int
) -> Tuple[range, range]:
# set pointer pos
pointer_y, pointer_x = pointer_pos
# set window... | akibancha/pyaar | src/interface/render_map.py | render_map.py | py | 4,100 | python | en | code | 1 | github-code | 1 |
15571487589 | from urllib.parse import urlsplit
from django.contrib.sites.models import Site
from django.templatetags.static import static
from ..core.utils import build_absolute_uri
def get_email_context():
site: Site = Site.objects.get_current()
logo_url = build_absolute_uri(static("images/logo-light.svg"))
send_em... | croolicjah/saleor-platform | saleor/saleor/core/emails.py | emails.py | py | 779 | python | en | code | 1 | github-code | 1 |
28478344307 | #Module for GUI for the client, A.K.A player 1
import tkinter as tk
from gameboard import BoardClass
import socket
class GUI():
def __init__(self):
self.canvasSetup()
#This is the string variable for the user to enter player 2's IP address
self.IPSV = tk.StringVar(self.root, va... | MegSanta/TicTacToe | TicTacToe/GUI1.py | GUI1.py | py | 17,715 | python | en | code | 0 | github-code | 1 |
38110755308 | import pytest
from rested.test.fixtures import database
# pytestmark = pytest.mark.django_db
db = database(reset_sequences=False, autouse=True)
def test_ping(rest):
response = rest.get('/ping')
assert response.status == 200
assert response.data == {"data": "pong"}
| mochi-ai/rested | rested/templates/default/tests/test_marker.py | test_marker.py | py | 280 | python | en | code | 1 | github-code | 1 |
28911695063 | import numpy as np
import plotly.graph_objects as go
import numpy as np
from PIL import Image
from scipy.interpolate import interpn
img = Image.open("Earth_Diffuse_6K.jpg")
imgdata = np.asarray(img)
factor = 30
lats = np.linspace(0, np.pi, int(imgdata.shape[0]/factor)) # this is actually latitude + 90
lons = np.lins... | utat-ss/FINCH-Orbit | earth sphere plotly.py | earth sphere plotly.py | py | 877 | python | en | code | 0 | github-code | 1 |
36038871583 | def isAnagram(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(s): return False
counter = {}
for char in s:
if char in counter:
counter[char] += 1
else:
counter[char] = 1
for char in t:
if not char in counter:
... | zhaoxy92/leetcode | 242_valid_anagram.py | 242_valid_anagram.py | py | 458 | python | en | code | 0 | github-code | 1 |
74064928674 | import torch
def initialize_layer(layer, type = "normal", gain=0.02):
classname = layer.__class__.__name__
if hasattr(layer, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
if type == 'normal':
torch.nn.init.normal_(layer.weight.data, 0.0, gain)
elif... | Cli98/tep-repo | Networks/initialization.py | initialization.py | py | 2,198 | python | en | code | 0 | github-code | 1 |
72239244193 | # script dftensor1.py
import numpy as np
import tensorflow as tf
import pandas as pd
import sys
import json
#TRAIN_DATA_URL = "https://storage.googleapis.com/applied-dl/heart.csv"
#TEST_DATA_URL = "https://storage.googleapis.com/tf-datasets/titanic/eval.csv"
#csv_file = tf.keras.utils.get_file("heart.csv",TRAIN_DATA... | Debdulalm2016/py3ml | src/dftensor1.py | dftensor1.py | py | 1,909 | python | en | code | 0 | github-code | 1 |
74532598432 | import openai, sys
openai.api_key = "Your API key"
with open(str(sys.argv[1])) as f:
content = f.read()
completion = openai.ChatCompletion.create(
model = "gpt-3.5-turbo",
temperature = 0.2,
max_tokens = 3333,
messages = [
{"role": "system", "content": "You are a computer programmer"},
... | yefeiw/chatgpt-jiuzhang | api/chatgpt.py | chatgpt.py | py | 419 | python | en | code | 0 | github-code | 1 |
15657594401 | def area_triangulo(b, h):
"""
Função calcula área (cm²) de um triângulo
:param b: Valor da base do triângulo informado pelo usuário
:param h: Valor da altura do triângulo informado pelo usuário
:return: Cálculo da área do triângulo
"""
a = (b * h) / 2
return a
while True:
base = fl... | PlinioCE/infinitypythononline | aula01_python_ativ02_area_tri.py | aula01_python_ativ02_area_tri.py | py | 817 | python | pt | code | 0 | github-code | 1 |
31310933138 |
import os, sys
# check if running under python3
if sys.version_info < (3, 0):
sys.stdout.write("DENIED: requires Python 3.x\n")
sys.exit(1)
else:
import axelrod as axl
from play import *
from display import *
from lists import *
def add_strategy(players, tournaments, args = []):
print(Emphasis.BOLD + "Availabl... | paulojlgouveia/rc_project | part_II/srs/main.py | main.py | py | 2,587 | python | en | code | 0 | github-code | 1 |
11510553212 | # Released under the MIT License. See LICENSE for details.
#
"""Defines ScoreBoard Actor and related functionality."""
from __future__ import annotations
import weakref
from typing import TYPE_CHECKING
import bascenev1 as bs
if TYPE_CHECKING:
from typing import Any, Sequence
class _Entry:
def __init__(
... | efroemling/ballistica | src/assets/ba_data/python/bascenev1lib/actor/scoreboard.py | scoreboard.py | py | 15,161 | python | en | code | 468 | github-code | 1 |
10327528775 | from itertools import product
import networkx as nx
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from .tools import transform_ts
from .generator import node_name
class VAR():
def __init__(self, p):
self.p = p
self.is_fitted = False
def fit(self, ts_... | danthe96/CIoTS | CIoTS/simple_var.py | simple_var.py | py | 4,928 | python | en | code | 3 | github-code | 1 |
34855282431 | #!/usr/bin/env python3
# f = open("puzzle_test.txt","r")
f = open("puzzle.txt","r")
lines = f.readlines()
paths = {}
for line in lines:
v1, v2 = line[:-1].split("-")
if v1 not in paths:
paths[v1] = []
paths[v1].append(v2)
if v2 not in paths:
paths[v2] = []
paths[v2].append(v1)
numPaths = 0
visited = {}
isTw... | vanjo9800/AdventOfCode2021 | 12/paths.py | paths.py | py | 912 | python | en | code | 1 | github-code | 1 |
25646973960 | import arxiv
import urllib
import pdfx
import re
import spacy
from spacy.lang.fr.examples import sentences
from xml.sax.saxutils import escape
import sys
def after_references(mypdftext):
keyword1 = 'References'
keyword2 = 'REFERENCES'
keyword3 = 'R EFERENCES'
keyword4 = 'Reference'
keyword5='[1]' ... | Caojerem/Projet_fil_rouge_SIO_2022 | Docker/fil_rouge.py | fil_rouge.py | py | 2,426 | python | en | code | 0 | github-code | 1 |
2511575168 | '''
Created on Sep 20, 2015
@author: Cuyler Quint <deanquint@gmail.com>
Tic Tac Toe
Requirements
-python version 1.7
-pygame version 1.9
Description:
This is a clone of the famous tic tac Toe
with implemetation of a computer to play agaisnt
at three different levels.
... | cuylerquint/TTT | TTT/src/Game.py | Game.py | py | 8,421 | python | en | code | 0 | github-code | 1 |
30800252698 | def find_it(seq):
odd_n=None
for x in seq:
n=seq.count(x)
if n%2 !=0:
odd_n=x
return odd_n
def find_it2(seq):
return [x for x in seq if seq.count(x)%2!=0][0]
if __name__ == '__main__':
sqe=[20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]
print(find_it2(sqe))
| kirtast/Codewars | find_odd_numer.py | find_odd_numer.py | py | 307 | python | en | code | 0 | github-code | 1 |
73811257633 | import json
import math
import sys
import operator
model_file = sys.argv[1]
test_file = sys.argv[2]
f_test = open(test_file, 'r')
f_model = open(model_file, 'r')
#sys.stdout = open("spam.out", 'w')
Dict = json.load(f_model)
d = {}
P_c = {}
classes = []
N = 0 #total number of documents
correct = 0
k = int(Dict['~_V... | dingyi567/CSCI-544 | hw1/nbclassify.py | nbclassify.py | py | 1,542 | python | en | code | 2 | github-code | 1 |
30023824445 | def cost(cave, y, x):
return cave[y][x][1] if x>=0 and y>=0 else 9999999999999999999999999
def printCave(cave, costOnly):
for r in cave:
if costOnly:
for v in r:
print(v[0], end="")
print()
else:
print(r)
def computePathCost(cave)... | leopold-lll/adventOfCode-2021 | day15_Chiton/day15.py | day15.py | py | 2,241 | python | en | code | 0 | github-code | 1 |
1857536637 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 14:41:11 2019
@author: Kumail
"""
import pandas
import numpy as np
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
dataset = pandas.read_csv("../datasets/iris.csv")
array = dataset.values
X = array[:,0:4]
Y = array[:,4]
valida... | KumailP/machine-learning-dsu | linear-models/LogisticRegression.py | LogisticRegression.py | py | 1,257 | python | en | code | 1 | github-code | 1 |
32689227188 | from django.conf.urls import patterns, url
from users import views
urlpatterns = patterns('',
url(r'^$',views.index, name='index'),
url(r'^(?P<user_id>\d+)/$', views.detail, name='detail'),
url(r'^attendance/$', views.attendance, name='attendance'),
url(r'^notifications/$', views.notifications, name='n... | dissipator/campsia | users/urls.py | urls.py | py | 432 | python | en | code | 0 | github-code | 1 |
27195496579 | import mesa
from agents import TreeAgent, Seed
from model import DispersalModel
from mesa.visualization.modules import CanvasGrid, ChartModule
from pointpats import PointPattern
import pointpats.quadrat_statistics as qs
def get_mean_nnd(self):
coords_seeds = []
for (agents, x, y) in self.grid.coord_ite... | higuchip/density-dependent-mortality | server.py | server.py | py | 2,262 | python | en | code | 0 | github-code | 1 |
43316806554 | from tkinter import Tk
__all__=['copy','paste','clear']
__author__='Calvin(Martin)Adyezik adyezik@gmail.com'
__doc__="""simple Module to work with clipboard based on tkinter -Python 3"""
__name__='Xclipboard'
def copy(text):
"""copy text to clipboard """
try:
root=Tk()
root.withdraw()
... | adyezik/Xclipboard | Xclipboard.py | Xclipboard.py | py | 894 | python | en | code | 2 | github-code | 1 |
35360372876 | import cv2
import numpy as np
import dlib
import matplotlib.pyplot as plt
import sys
import face_recognition
import imutils.face_utils
from imutils import face_utils
#import imutils.face_utils
#image read
imq = cv2.imread('C:\\Users\\moham\\Pictures\\cv_DP2jpg.jpg', 0)
#image show
cv2.imshow('image', img)
#image show ... | Ziaf007/Attendance-using-Facial_recognition | Detection.py | Detection.py | py | 2,226 | python | en | code | 0 | github-code | 1 |
33277836844 | # -*-coding:utf-8-*-
__author__ = 'hank'
import os
import json
class ReadConfig(object):
def __init__(self):
self.local = os.path.abspath('.')
self.father_path = os.path.dirname(self.local)
self.json_path = self.father_path + "/config/"
def read_json(self, json_name):
json_nam... | hansenzhf/first | lib/read_config.py | read_config.py | py | 486 | python | en | code | 0 | github-code | 1 |
36170840461 | import logging
from typing import List
from volatility3.framework import renderers, exceptions, interfaces
from volatility3.framework.configuration import requirements
from volatility3.framework.interfaces import plugins
from volatility3.framework.layers import intel
vollog = logging.getLogger(__name__)
class Stati... | volatilityfoundation/volatility3 | volatility3/plugins/windows/statistics.py | statistics.py | py | 3,720 | python | en | code | 1,879 | github-code | 1 |
6203153530 | import os, unittest, numpy as np
from saspt.parameters import StateArrayParameters
from saspt.constants import RBME
class TestStateArrayParameters(unittest.TestCase):
def setUp(self):
self.kwargs = dict(pixel_size_um=0.16, frame_interval=0.01,
focal_depth=0.7, splitsize=10, sample_size=200,
... | alecheckert/saspt | tests/test_parameters.py | test_parameters.py | py | 885 | python | en | code | 6 | github-code | 1 |
36694454341 | from time import time
import pennylane as qml
from scipy.optimize import minimize
import networkx as nx
from .unitaries import (
hypercube_mixer,
phase_shift,
circulant_mixer,
diagonal_pauli_decompose,
complete_eigenvalues,
)
def gen_graph(qubits, seed, prob = 0.25):
# for smaller graphs, incr... | John-J-Tanner/Quantum_Benchmarking | pennylane/benchmark/qaoa_maxcut.py | qaoa_maxcut.py | py | 7,745 | python | en | code | 1 | github-code | 1 |
33049652214 | from django.shortcuts import render
from trino.dbapi import connect
from trino.auth import BasicAuthentication
import pandas as pd
from core.models import Item
import numpy as np
# Create your views here.
conn = connect(host="tcp.cheerful-maggot.dataos.app",
port="7432",
auth=BasicAuthent... | ramesh-tmdc/sample | views.py | views.py | py | 2,609 | python | en | code | 0 | github-code | 1 |
981247697 | double_list = []
my_list = [1, 2, 3]
# using normal operation
print("Using normal operataion")
for item in my_list:
double_list.append(item * 2)
print(double_list)
# using list comprehensive
print("List comprenensive")
double_list = [item * 3 for item in my_list]
print(double_list)
# accessing elements of list us... | tilakpoudel/BooksManager | python_stuff/list_comprehensive.py | list_comprehensive.py | py | 999 | python | en | code | 2 | github-code | 1 |
8530369547 | # Fatorial 1 forma 'while'
from math import factorial
n = int(input('Digite um número para\ncalcular sua fatorial: '))
f = factorial(n)
print('O fatorial de {} é {}'.format(n, f))
# Fatorial 2 forma 'while'
n = int(input('Digite um número para\ncalcular sua fatorial: '))
c = n
f = 1
print('Calculando {}! = '.format(n)... | jabes-christian/Curso-Python | Python-Exercícios&Aulas/Ex060 - Cálculo do Fatorial.py | Ex060 - Cálculo do Fatorial.py | py | 731 | python | pt | code | 0 | github-code | 1 |
40923701936 | # -*- encoding: utf-8 -*-
import numpy as np
def resize_img(a,scale):
new_a = np.zeros((np.array(a.shape)*scale))
for i in xrange(scale):
for j in xrange(scale):
new_a[i::scale,j::scale]=a
return new_a
| mariecpereira/IA369Z | deliver/functions_will/resize_img.py | resize_img.py | py | 236 | python | en | code | 1 | github-code | 1 |
26597490747 | from rest_framework import viewsets, decorators, status
from rest_framework.response import Response
from django.db import transaction
from geoplaces.models import Place
from geoplaces.serializers import PlaceSerializer, PlaceIncreaseRatingSerializer
from geoplaces.filters import GeoPlacesFilter
class PlaceViewSet(v... | marqueewinq/klubok | klubok/geoplaces/views.py | views.py | py | 1,575 | python | en | code | 0 | github-code | 1 |
35813740191 | """
Distributor, Layout, Transform, and Transpose class definitions.
"""
import logging
from mpi4py import MPI
import numpy as np
import itertools
from collections import OrderedDict
from ..tools.cache import CachedMethod, CachedAttribute
from ..tools.config import config
from ..tools.array import prod
from ..tools.g... | DedalusProject/dedalus | dedalus/core/distributor.py | distributor.py | py | 36,686 | python | en | code | 376 | github-code | 1 |
6661308948 | from django.contrib import admin
from django.urls import path, include
urlpatterns = [
#?sessão de administração padrão do django
path('admin/', admin.site.urls),
#?rotas para os apps
path('', include('Rest_app.urls')),
#?rotas de autentificação do rest_framework
path('api-auth/', include('rest... | Rip4568/veiculo_django_project | Veiculos_project/urls.py | urls.py | py | 405 | python | pt | code | 0 | github-code | 1 |
73026235875 | # Best Worst
# Partioning O(n) O(n)
# # of times O(log n) O(n) depends on the pivot
# Total O(n log(n)) O(n^2)
# Space O(log(n)) O(n)
def quick_sort(array, start, end):
if start >= end: return
boundary = partition(array, start, end)
quick_sort(... | zalogarciam/data-structures-and-algorithms | Sort/QuickSort.py | QuickSort.py | py | 826 | python | en | code | 0 | github-code | 1 |
40967112979 | from collections import deque
from lib.Intcode2 import Intcode
from lib.utils import print_array
SIZE = 30
xy = [[-1] * SIZE for i in range(SIZE)]
with open("data/19.txt") as f:
_program = list(map(int, f.readline().split(",")))
min_x = 0
max_x = 0
y = 0
count = 0
MIN_SIZE = 100
size_flag = False
arr_y = []
... | szerlak/advent_of_code | 2019/19.py | 19.py | py | 1,242 | python | en | code | 1 | github-code | 1 |
6668321784 | import math
from argparse import ArgumentParser
from datetime import timedelta as delta
import numpy as np
import pytest
from parcels import (
AdvectionEE,
AdvectionRK4,
AdvectionRK45,
FieldSet,
JITParticle,
ParticleSet,
ScipyParticle,
Variable,
timer,
)
ptype = {'scipy': ScipyPar... | OceanParcels/parcels | docs/examples/example_stommel.py | example_stommel.py | py | 8,324 | python | en | code | 250 | github-code | 1 |
73116298915 | class Solution:
def __init__(self):
self.cache = {} # end potision's sum
def max_subarray_ends_at(self, nums, index) -> int:
if index == 0:
return nums[0]
if index in self.cache:
return self.cache[index]
res = max(
nums[index],
s... | eliteGoblin/sky_ladder | sessions/chujisuanfa/53.py | 53.py | py | 716 | python | en | code | 0 | github-code | 1 |
34908001056 |
num = int(input("enter the number="))
def factorial(n):
return 1 if n == 1 or 0 else n * factorial(n - 1)
print('factorial of', num, 'is =', factorial(num))
def Largest(arr, n):
max = arr[0]
for i in range(1, n):
if arr[i] > max:
max = arr[i]
return max
arr = [94, 6, 87, 57]
n... | AnshumaJain/MasteringPython | _need_cleanup/basic.py | basic.py | py | 432 | python | en | code | 0 | github-code | 1 |
15356429984 | #!/usr/bin/env python3
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from std_msgs.msg import Float64MultiArray
import socket
import time
import pickle
class ContInputPublisher(Node):
# inputs = [float(0), float(0), float(0), float(0)]
def __init__(self):
super().__init__("co... | jmoya34/BILL-EE | ros2_billee_pkg/operations/pi_scripts/antenna_reciver.py | antenna_reciver.py | py | 2,286 | python | en | code | 7 | github-code | 1 |
30167513486 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 15 23:23:16 2021
@author: Ruich
"""
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
visited = {
}
for i in nums:
v... | RuichengGeng/LeetCode | 46Permutations/Solution.py | Solution.py | py | 865 | python | en | code | 0 | github-code | 1 |
41480978477 | # There is no quick and easy approach to remove a character from a string. Instead we have 'naive' approach that allows you to remove all occurrences of a character. It is specifically useful want you to clean some log files.
# NAIVE APPROACH
# Just traverse the string and create a new string one character at a time ex... | Folzi99/ItP_Trinket_Exercises-main | ItP_Trinket_Exercises-main/Self Learning Materials/String/String_Removing.py | String_Removing.py | py | 833 | python | en | code | 0 | github-code | 1 |
32858455165 | import mysql.connector
import random
import tabulate
class Db_connection:
def __init__(self):
self.connection=mysql.connector.connect(host='localhost',
user='root',
password='123134',
... | vjkmr0898/programs | programs/clothing.py | clothing.py | py | 9,958 | python | en | code | 0 | github-code | 1 |
9191488071 | import numpy as np
import os
import argparse
#import torch
#import torch.nn as nn
from sklearn.linear_model import LinearRegression
import math
import random
from utils import *
'''
def quantize(data,pred,error_bound):
radius=32768
diff = data - pred
quant_index = (int) (abs(diff)/ error_bound) + 1
... | Meso272/NNpredictor | multilevel_selective_compress_2d_deprecated.py | multilevel_selective_compress_2d_deprecated.py | py | 24,070 | python | en | code | 0 | github-code | 1 |
3195507573 | class Solution(object):
def minSwaps(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ones = sum(nums)
# sz = len(nums)
s = 0
zeros = 0
res = float('inf')
for e in range(len(nums) + ones - 1):
end = e % len(nums)
... | niufenjujuexianhua/Leetcode | 2134-minimum-swaps-to-group-all-1s-together-ii/2134-minimum-swaps-to-group-all-1s-together-ii.py | 2134-minimum-swaps-to-group-all-1s-together-ii.py | py | 703 | python | en | code | 0 | github-code | 1 |
411750400 | # pylint: disable=W0621,C0114,C0116,W0212,W0613
import pathlib
from typing import cast, Optional
import pytest
import pytest_mock
from dae.genotype_storage.genotype_storage_registry import \
get_genotype_storage_factory
from dae.duckdb_storage.duckdb_genotype_storage import \
DuckDbGenotypeStorage
from dae.t... | iossifovlab/gpf | dae/dae/duckdb_storage/tests/test_parquet_layout_scans.py | test_parquet_layout_scans.py | py | 3,959 | python | en | code | 1 | github-code | 1 |
73169942114 | from pathlib import Path
import pandas as pd
import csv
from collections import OrderedDict
import numpy as np
import sys
import argparse
import os
import re
import plotly.express as px
#import Levenshtein
class count_spacers:
def __init__(self,prefix,input_file, fastq_file, output_file, gRNA_len):
pr... | tengbozhang/iCRISEE | icrisee/count_sg.py | count_sg.py | py | 6,474 | python | en | code | 0 | github-code | 1 |
28410222567 | from typing import Optional
import unittest
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.global_max = float("-inf")
def postOrderTraversal(self, root: Optiona... | teimurjan/leetcode | max-path-sum.py | max-path-sum.py | py | 1,353 | python | en | code | 0 | github-code | 1 |
6493966912 | from msrest.service_client import ServiceClient
from msrest import Configuration, Serializer, Deserializer
from .version import VERSION
from .operations.int_model_operations import IntModelOperations
from . import models
class AutoRestIntegerTestServiceConfiguration(Configuration):
"""Configuration for AutoRestIn... | testormoo/autorest.ansible | test/vanilla/Expected/AcceptanceTests/BodyInteger/fixtures/acceptancetestsbodyinteger/auto_rest_integer_test_service.py | auto_rest_integer_test_service.py | py | 1,664 | python | en | code | 0 | github-code | 1 |
18379379442 | from concurrent.futures import ThreadPoolExecutor
from os.path import splitext
from PIL import Image, ImageFile
from tkinter.filedialog import *
import os.path
ImageFile.LOAD_TRUNCATED_IMAGES = True
files = askopenfilenames()
def convert_image(file):
with Image.open(file) as im:
output_path = s... | Genos-Noctua/Scripts | JPEG.py | JPEG.py | py | 636 | python | en | code | 0 | github-code | 1 |
29674030395 | from pynaoqi_mate import Robot
from configuration import PepperConfiguration
import qi
#virtualRobotConfig = PepperConfiguration("Porter")
#myRobot = Robot(virtualRobotConfig)
class TakePictureExample():
def __init__(self):
self.config = PepperConfiguration("Porter")
robot = Robot(self.config)
... | tschibu/hslu-roblab-floorguide | examples/3dCamera.py | 3dCamera.py | py | 593 | python | en | code | 0 | github-code | 1 |
7466181156 | from one_hot_encoder import fit_transform
import unittest
class TestOneHotEncoder(unittest.TestCase):
def test_cities_list(self):
"""This test - cities from the work example"""
cities = ['Moscow', 'New York', 'Moscow', 'London']
actual = fit_transform(cities)
expected = [
... | VasenkovArtem/Python_4 | issue-03/test_one_hot_encoder.py | test_one_hot_encoder.py | py | 2,854 | python | en | code | 0 | github-code | 1 |
15043765898 | from typing import List, Tuple
import pathlib
import copy
import numpy as np
import networkx as nx
from tqdm.auto import tqdm
from defdap import ebsd
from defdap.quat import Quat
from beta_reconstruction.crystal_relations import (
unq_hex_syms, hex_syms, unq_cub_syms, burg_trans
)
def calc_beta_oris(alpha_ori: ... | LightForm-group/beta-reconstruction | beta_reconstruction/reconstruction.py | reconstruction.py | py | 25,051 | python | en | code | 1 | github-code | 1 |
16166437404 | import mongoengine
ROOT_URLCONF = 'parkkeeper.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
MIDDLEWARE_CLASSES = [
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middle... | telminov/django-park-keeper | test_settings.py | test_settings.py | py | 1,121 | python | en | code | 4 | github-code | 1 |
43147707682 |
MUT_PB = 0.05 # mutate probability
N_COLS = 100 # number of cols (nodes) in a single-row CGP
LEVEL_BACK = N_COLS # how many levels back are allowed for inputs in CGP
MU = 7 # List for Mu is number of parents used to breed next generation
LAMBDA = 20 ... | jordankiesler/foragingRobots | finalProject/settings.py | settings.py | py | 642 | python | en | code | 0 | github-code | 1 |
10155952607 | import time
import argparse
import json
import tqdm
import torch
import numpy as np
import torch.nn.functional as F
from sklearn.metrics import roc_auc_score, f1_score
from model.model import Model
from model.data import get_data_frames, create_graph, create_hetero_graph, create_data_loaders
def train(model, optimize... | mbekmyrz/newsrec | main.py | main.py | py | 12,722 | python | en | code | 1 | github-code | 1 |
552195300 | import pandas as pd
import tqdm
import numpy as np
import codecs
import glob
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, f1_score
from sklearn.linear_model import LogisticRegression
import random
import matplotlib.pyplot as plt
import sys
from sklearn import p... | terne/thesis | logreg_experiments/old/all_data_logistic_regression.py | all_data_logistic_regression.py | py | 10,456 | python | en | code | 0 | github-code | 1 |
6712255038 | import curses
import math
import sys
import logging as log
from pprint import pformat
class Menu:
DIRECTION_UP = 'UP'
DIRECTION_DOWN = 'DOWN'
def __init__(self, layout, border=True):
self.win = curses.newwin(layout[0],
layout[1],
... | nadr0/branch-delete | menu.py | menu.py | py | 7,999 | python | en | code | 2 | github-code | 1 |
27265662633 | """
Réalise une jointure spatiale entre deux DataFrame et en résulte une table de
liaison.
Par exemple, la table résultante peut donner la concordance entre les anciens
et les nouveaux biotopes.
@params old_df: GeoDataFrame
@params new_df: GeoDataFrame
@returns: GeoDataFrame
"""
def jointure(old_df, new_df):
# In... | VenziaTurmoil/Biotopes_updates | construction_liason.py | construction_liason.py | py | 1,409 | python | fr | code | 0 | github-code | 1 |
8329722268 | '''
Coin Change Problem Implementation using Dynamic Programming (Bottom-Up Approach)
Problem:
Given coins of certain denominations with unlimited quantity and a total,
what is the minimum number of coins would be needed to form that total.
Time complexity:
Space complexity:
'''
def coinchange():
# given lis... | darrenche/Algorithm-Implementations | coinchange.py | coinchange.py | py | 2,511 | python | en | code | 0 | github-code | 1 |
40270074978 | #!/usr/bin/python3
import os
import argparse
import time
import urllib.request
import email.mime.text
import socket
import getpass
import subprocess
def lookup_mac_vendor(mac_address):
result = ""
if mac_address:
for i in range(3):
vendor = None
try:
# Only firs... | cheretbe/notes | files/dhcp/on_dhcp_lease.py | on_dhcp_lease.py | py | 3,273 | python | en | code | 3 | github-code | 1 |
36656366554 | import re
def addfirst_calc(expr):
add_re = r'\b(\d+?)\b\s+\+\s+\b(\d+?)\b'
m = re.search(add_re, expr)
while m:
result = int(m.group(1)) + int(m.group(2))
add_replace = r'\b%s\b' % m.group(0).replace('+', '\+')
expr = re.sub(add_replace, str(result), expr)
m = re.search(add_re, expr)
mult_re ... | gerrowadat/adventofcode | 2020/18/18-2.py | 18-2.py | py | 1,057 | python | en | code | 1 | github-code | 1 |
44976337574 | # -*- codeing = utf-8 -*-
# @Time : 2021/5/9 21:41
# @File :校内赛识别图形最终版本.py
# @Software : PyCharm
import cv2 as cv
def detectShape(img):
# 查找轮廓,cv2.RETR_ExTERNAL=获取外部轮廓点, CHAIN_APPROX_NONE = 得到所有的像素点
contours, hierarchy = cv.findContours(img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
# 循环轮廓,判断每一个形状... | ChangYu-beginner/The-visual-program | 校内赛识别图形最终版本.py | 校内赛识别图形最终版本.py | py | 3,663 | python | en | code | 1 | github-code | 1 |
39053043656 | nim = [[1, 1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1], [1, 1], [1]]
player1 = "Human 1"
player2 = "Computer 2"
players = player1, player2
def make_move(row, number):
if row < 0 or row >= len(nim):
print("Bad row")
return False
elif number <= len(nim[row]) and number > 0:
for i in range(num... | picrin/nim_game | rough_solution.py | rough_solution.py | py | 2,279 | python | en | code | 0 | github-code | 1 |
19267862140 | #!/usr/bin/python3
import argparse
import sys
def parse_file(f):
grammar = {
'N': [],
'Sigma': [],
'S': 'S',
'P': []
}
for i in range(3):
line = f.readline()
line = line.rstrip()
idx = line.find(' = ')
s = line[:idx]
elements = lin... | mapaaa/rdp-generator | main.py | main.py | py | 7,755 | python | en | code | 0 | github-code | 1 |
30191121102 | def solve(intervals):
# CODE HERE
# sorting according to start time
intervals.sort(key = lambda x: x[0])
kat = []
for inter in intervals:
if not kat or kat[-1][1] < inter[0]:
kat.append(inter)
else:
kat[-1][1] = max(kat[-1][1], inter[1])
... | DevMatrix1/dsa-practice | Python/chandu/Merge_Intervals.py | Merge_Intervals.py | py | 332 | python | en | code | 13 | github-code | 1 |
73285165795 | import copy
from math import log
from cmath import e
class ProgressState:
def __init__(self, progress, word=None):
self.progress = progress
self.word = word
def getLegalActions(self, agentIndex):
"""
Returns the legal actions for the agent specified.
"""
if ... | cheunjm/harvard-courses | CS182/Intelflash/progress.py | progress.py | py | 2,311 | python | en | code | 1 | github-code | 1 |
10645242083 | import tushare as ts
import numpy as np
import matplotlib.pyplot as plt
import random
import math
import datetime
import tushare as ts
import pymysql
import stock_one
# p = stock_one.oneday('sh.600123', '20150102', '20210218')
# print(p)
# exit()
starttime = '20170102'
endtime = '20210218'
all = []
a = ['SH.6002... | moon142857/TradeDoor | stock_all.py | stock_all.py | py | 2,046 | python | en | code | 0 | github-code | 1 |
38033746083 | import numpy as np
import pandas as pd
import pickle
from flask import Flask ,app ,request ,jsonify ,render_template ,url_for
app=Flask(__name__)
reg_model=pickle.load(open('regm.pkl','rb')) #load regression model
scaler=pickle.load(open('scale.pkl','rb')) #load scaling model
@app.route('/')
def home()... | sanchayvashist/boston_house | app.py | app.py | py | 1,532 | python | en | code | 0 | github-code | 1 |
27031089250 | from win10toast import ToastNotifier
import feedparser
import time
toaster = ToastNotifier()
def getNews():
url = "https://www.youm7.com/rss/SectionRss?SectionID=203" #url rss
feed = feedparser.parse("https://www.youm7.com/rss/SectionRss?SectionID=203") #Get all feed from rss
for item in feed["entries"]:... | peterramsis/RssNotify | main.py | main.py | py | 514 | python | en | code | 0 | github-code | 1 |
33757081947 | from veca.env_manager import EnvOrchestrator
if __name__ == "__main__":
# Executing the Environment Orchestrator process at another server.
env = EnvOrchestrator(
ip = "127.0.0.1", # ip and port of remote Envionment Orchestrator master
port = 8872, # Exposed port of Environment Orches... | GGOSinon/VECA | example_envorchestrator.py | example_envorchestrator.py | py | 477 | python | en | code | 9 | github-code | 1 |
3898644156 | import discord
import random
import os
import csv
import paralleldots
from datetime import datetime
import asyncio
#please make you have installed the packages or just run on replit
from discord_components import *
from discord.ext.commands import bot
from discord.utils import get
from discord.ext import commands, task... | Limbo-Hacks/Mr-Limbo-bot | main.py | main.py | py | 21,202 | python | en | code | 3 | github-code | 1 |
35131163454 | '''
The following codes are from https://github.com/d-li14/mobilenetv2.pytorch
Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
- msr_init: net parameter initialization.
- progress_bar: progress bar mimic xlua.progress.
'''
import errno
import o... | snudm-starlab/FALCON2 | src/imagenetutils/misc.py | misc.py | py | 2,761 | python | en | code | 40 | github-code | 1 |
39004911406 | #!/usr/bin/python3
"""
Function that appends a string at the end of a file
"""
def append_write(filename="", text=""):
"""
return file and a string append
"""
with open(filename, 'a') as f:
txt = f.write(text)
f.closed
return (txt)
| mwaskagi/alx-higher_level_programming | 0x0B-python-input_output/2-append_write.py | 2-append_write.py | py | 268 | python | en | code | 1 | github-code | 1 |
3890081887 | """
Created on Fri Nov 8 23:23:22 2019
@author: Pratiksha
"""
# app.py for Scara Web App
from flask import Flask, render_template, request
from data import Articles
import cv2
from pyzbar import pyzbar
app = Flask(__name__)
Articles = Articles()
S = []
@app.route('/')
def index():
return ren... | PratikshaJain37/Scara-Hack36 | app.py | app.py | py | 1,492 | python | en | code | 1 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.