index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
992,900 | 7fd3d5cec5d4d5853f5fa194febfadb20704e9a8 | # a is a dynamic reference to an object in memory
# When a new value is assigned to it the reference changes to a separate address with a new type
a = 'hello'
# This is type of the object that A is referencing
# Each object will therefore show a different memory id and type
print(type(a))
print(hex(id(a)))
a = 10
print... |
992,901 | 2d522dc71b4a5f3057ef12d5fc5f236ea3be0955 | import logging
import socket
import threading
import time
from .proto.packet import Packet
from .proto.opttypes import OptionType
from .proto.dhcpmsg import MessageType
def sync_worker(address, on_success, on_fail, oneshot=False, macaddr=None, relay_ip=None):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGR... |
992,902 | da944694ff047f624d64de52ac13e63009ed9254 | version https://git-lfs.github.com/spec/v1
oid sha256:9f1e36400c7a0181064505a629459283e8643f0cc3d2624aab902416bb2637c2
size 6912
|
992,903 | 729448647d778dfdff48850061ebd7b8a2cb1636 | # Programme testant si une année saisie est bissextile ou non
import os
annee = input("Saisissez une année : ") # On attend qu'une année à tester soit fournit
annee = int(annee) # Risque d'erreur si l'utilisateur n'a pas saisi un nombre
if annee % 400 == 0 or (annee % 4 == 0 and annee % 100 != 0):
... |
992,904 | 5ce5e39927d0c6366a76a8627c2b4b142c86418a | #
#
# Source: "Брутим архивы ZIP/RAR используя python."
# https://codeby.net/threads/brutim-arxivy-zip-rar-ispolzuja-python.65986/
# It was written on python 2.x
# time python3 brutilka.py -f evil.zip -d dictionary
# time python3 brutilka.py -f evil.rar -d dictionary
#
import zipfile
im... |
992,905 | 19aece2bf4daa748038e75a9b3ef09fca403d617 |
add_library('controlp5')
cp5 = None
slider1 = None
def setup():
global cp5, slider1
size(500,500)
cp5 = ControlP5(this)
slider1 = (
cp5
.addSlider("slider")
.setSize(200,20)
.setPosition(20,20)
.setRange(0,255))
slider1.label = "Background"
def dr... |
992,906 | 882c128d09f03967ba2e42515a10a13cf5cd9ef1 | #!/usr/bin/env python2.7
# Copyright 2013, ARM Limited
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this li... |
992,907 | ff620ee4066c10e3ada0c46e82eb6e8871add3d2 | from common import constants
from ..task import celery_app
from ..util.SpiderWorker import SpiderWorker
@celery_app.task(ignore_result=True)
def job_task():
for career in SpiderWorker().career_spider():
urls = [constants.HOME_URL + career + '?page={}&ka=page-{}'.format(page, page) for page in range(1, 31)... |
992,908 | 83d582c0da4bbad29d94e7fcfa7d28d31bb6336b | # coding:utf-8
import pytest
@pytest.fixture(scope='class', autouse=True)
@pytest.mark.run(order=1)
def open_browser():
print('\n打开浏览器...')
@pytest.fixture()
@pytest.mark.run(order=2)
def test_login(request):
user = request.param['user']
pwd = request.param['pwd']
print('登录中...')
if user == 'a1'... |
992,909 | 651ecca843803efaddb8d9fe0bab1f071806acaf | # -*- coding: utf-8 -*-
from django.test import TestCase
from catalogapp import api
from catalogapp import models
class SpecFieldsTest(TestCase):
def test_create(self):
api.sections.create("Name", "slug")
section = api.sections.get(1)
test_query = {
"field_type": "BooleanFiel... |
992,910 | d157fae0001ac7198e368285311d474e37cdf1d4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
# Libraries
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gio, Gtk, GdkPixbuf
import os
import sys
import subprocess
import gettext
import locale
import controls
import socket
el = gettext.translation('base', 'locale', fallback=True)
el... |
992,911 | b40f39b6dd2767b2bb978ef176b9a51d72b97414 | """
Leetcode Problem 001: Two Sum
Author: Richard Coucoules
Solved: 2019-11-04
"""
class Solution:
def twoSum(self, nums, target):
numDict = {}
for idx, num in enumerate(nums):
numDict[num] = idx
for idx, num in enumerate(nums):
addend = target - num
if addend in numDict and numDict[addend] != idx:
... |
992,912 | 3fcf9a2f49c1833aa5d1b146fcea69884c16ad58 | from abc import abstractmethod
from typing import Iterable, Dict, Any
from datasets import Dataset
from cheese.pipeline import Pipeline
from cheese.utils import safe_mkdir
import pandas as pd
class DatasetPipeline(Pipeline):
"""
Base class for any pipeline thats data destination is a datasets.Dataset object... |
992,913 | fc7e504b7814edbb128015084fc4e23b4aa948a6 | from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
import copy
from core.detection_input import DetectionAugmentation, AnchorTarget2D
class Resize2DImageBboxMask(DetectionAugmentation):
"""
input: image, ndarray(h, w, rgb)
gt_bbox, ndarry(n, 5)
... |
992,914 | 31635d03f41801a79c5ec3e14bb9a68b435de9d3 | my_pizzas = ['pepperoni', 'beef', 'bacon', 'durian']
friend_pizzas = my_pizzas[:]
my_pizzas.append('fruit')
friend_pizzas.append('vegetables')
print("My favorite pizzas are:")
for pizza in my_pizzas:
print(pizza)
print("\nMy friend's favorite pizzas are:")
for pizza in friend_pizzas:
print(pizza)
|
992,915 | 5afc1c07aea46980ba80dd60f365ef0291008a59 | import unittest
import tempfile
from pathlib import Path
import geowombat as gw
from geowombat.data import l8_224077_20200518_B2
from geowombat.data import l8_224077_20200518_B4
import numpy as np
import xarray as xr
def shift(data: xr.DataArray, x: int, y: int) -> xr.DataArray:
return (
(
... |
992,916 | 574cf12432b15e3b3bae07827a038918684d5f60 | # why am i outputting the wrong string at the same time as the right
if char in text:
print(text)
|
992,917 | d506b0a7caf23f861ad15490e16bf77397916bab | from Dataset import CustomImageDataset
from Sampler import ImbalancedDatasetSampler
from Model import AIST_model
from Loss import FocalLoss
from Run_model import model_generator
import torch
import torch.optim as optim
from torch.utils.data import DataLoader, random_split
import torchvision.transforms as transf... |
992,918 | 0618011bf007b92251d4a019b37c071558d31180 | from django.conf.urls import patterns, include, url
from django.conf import settings
from rest_framework.urlpatterns import format_suffix_patterns
import views
urlpatterns = patterns('',
url(r'^students/$',
views.StudentList.as_view(), name='student-list'),
url(r'^students/(?P<pk>[0-9]+)/$',
v... |
992,919 | 754153ad893ba982919acfbe265841668fd5ab42 | z = max(arr) |
992,920 | 8e9f9d5bf166d601e74423ce4130759a4c94f8b1 | import random, sys
file_word = open('C:/Users/Dmoho/Desktop/list_word.txt', 'r+')
str_word = file_word.read()
list_word = str_word.split(',')
rand_word = random.choice(list_word)
len_rand_word = int(len(rand_word))
count, bottom_line, str_line, guess = 0, "_", "", bool
for i in range(len_rand_word):
str_line += bot... |
992,921 | d84791cc1f130e94981e55457a146efac22d7dad | # dp[i][j]: the longest palindromic subsequence's length of substring(i, j)
# State transition:
# dp[i][j] = dp[i+1][j-1] + 2 if s.charAt(i) == s.charAt(j)
# otherwise, dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1])
# Initialization: dp[i][i] = 1
class Solution(object):
def longestPalindromeSubseq(self, s):
... |
992,922 | e4373c111a3ebd8b8b756b39ac44fd09fb0ed44c | '''
Filename: inputMain.py
Function:
This script handles inputs and parses the input and calls the appropriate function
Possible flags:
1. -i
2. -f <input filename> | diff -u <comparison output filename> -
3. nothing
4. else
'''
import sys
import utils as utils
from main import intMode, fileMode
if __name__ == '__ma... |
992,923 | 41410cb571c0fe027bd200a2b3a75ce70f66ab47 | #!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run magic-with-5-cards
# code { background: transparent; white-space: nowrap; } code.r { color: red; } code.b { color: #163e69; } table { border-collapse: collapse; } th, td { border: 1px solid #163e69; padding: 5px; } th, td:first-... |
992,924 | 4229d2bf79edb8f1502b88608d3e5881a53d0c88 | import os
exe = '~/arch/scattering/master/bin/fit_spectrum '
input_file=' minimise_chipt_su3_op4.ini.xml '
mass_file=' ../masses.ini.xml '
"""to run Dave's spec list"""
spec_list=' ../djwilson_spec_list/spec_final_elastic.list'
"""to run my spec list"""
spec_list=' ../spec_final_elastic.list'
rel_dir=' /'
cmd=ex... |
992,925 | 8766d14752b44dbb3ea085156d28ebfb74d9e988 | """Tests for github_webhook.webhook"""
from __future__ import print_function
import pytest
import werkzeug
import json
try:
from unittest import mock
except ImportError:
import mock
from github_webhook.webhook import Webhook
@pytest.fixture
def mock_request():
with mock.patch("github_webhook.webhook.r... |
992,926 | 59a85b2a2b9944e5ad6035cae7bab1abc62f9ea9 | from django.db import models
from django.contrib.auth.models import User
from django.core.validators import RegexValidator,MaxValueValidator, MinValueValidator
from datetime import datetime
import ast
#-------------------------------------------------------------------------------------------
class MacAddress(model... |
992,927 | 294d727ebbd36f1ffea205e028534cb34271934a | import numpy as np
import pickle
import matplotlib
from matplotlib import rc
rc('text', usetex=True)
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.rcParams['lines.linewidth']=1.5
plt.rcParams['axes.facecolor']='w'
c... |
992,928 | 5fb84372f582c5ae87a1b79178eaa1d6403251aa | #! /usr/bin/env python
import numpy as np
import argparse
import pyfits
from scipy.ndimage.interpolation import shift as sc_shift
#from shift import shift as fft_shift
import os
from pyds9 import pydisplay
def shift(filename, xs, ys, refFile,noShift=False):
f = pyfits.open(filename)
header = f[0].header
... |
992,929 | d1af718078e2fee3f47391397e2c5d0eb3451f1b | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 12:29:15 2019
@author: yanxi
"""
import numpy as np
# -------- part 1 conversion --------
def cart2pol(data):
s = data.shape
assert s[-1] == 2
# x and y
t = data.reshape(-1,2)
res = np.zeros_like(t)
# rho
res[:,0] = np.sqrt(t[:,0]**2 + t... |
992,930 | 433309a96166d4fb14e4d8984a59f635be2f91dd | #!/usr/bin/env python
# go to the tree file and pick out all the paths that have hits greater
# than the cutoff and convert the entries to edge definitions.
import sys
import re
import Parameters
import operator
import string
def runme2(fid,infile,outfile):
fin = open(infile,'r')
fout = open(outfile,'w')
... |
992,931 | 22d880148a076c2b715a994bf3bbb44a288b4276 | """ Test script to visualize some of the random Curve data.
@author Graham Taylor
"""
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append('code')
sys.path.append('code/util')
from util import get_data_path, dispims, tile_raster_images
from util.serialization import dese... |
992,932 | a1fd8a0836bcdb570bd6cc3ade920867c951b72c | import random
# number guessing game
counter = 0
name = input('NAME PLEASE: ')
while True:
#1. computer chooses a random number between 1 and 10
r = random.randint(1,5)
#2. ask user to enter a number then print it out
number = input("please enter a number: ")
number = int(number)
#3.... |
992,933 | 4fdf4ab3620229006335c49d53a73793b665bc8e | test_article = { u'entrezajax': { u'error': False},
u'result': [ { u'MedlineCitation':
{ u'Article': { u'Abstract': { u'AbstractText': [ u"We have identified multiple distinct splicing enhancer elements within protein-coding sequences of the constitutively spliced human beta... |
992,934 | 325f67c2d96ef9d0884417e17e1371514ca12238 |
# TODO: move
def read_stat(self,layer,stat):
assert False, 'not yet modified'
if self is None:
path_model_load = config_glb.path_model_load
path_stat_r = config_glb.path_stat
else:
path_model_load = self.path_model_load
path_stat_r = self.conf.path_stat
#path_sta... |
992,935 | d7f5a390aef095c80ac06f34fc78c5acabbc4eb6 | #!/usr/bin/env python3
lines = open('input').read().splitlines()
count = 0
for line in lines:
r_a_p = line.split()
min_max = r_a_p[0].split("-")
letter = r_a_p[1][0]
password = r_a_p[2]
if (password[int(min_max[0]) - 1] == letter) != (password[int(min_max[1]) - 1] == letter):
count += 1
pri... |
992,936 | 5d52c16fd32bfc765ef1f08e82f19f034da9f645 | replace_with = {'ṭ': 't',
'ᵈ': 'd',
'ḍ': 'ɖ',
'ɡ': 'g',
'ᶢ': 'g',
'ḿ': 'm',
'ᵐ': 'm',
'ᶬ': 'ɱ',
'ṅ': 'n',
'ǹ': 'n',
'ⁿ': 'n',
'ṉ': 'n',
... |
992,937 | 33c6f66875422c9c5a25513e08f1a771b737c01d | from django.shortcuts import render
# from summary.models import SumItems
from confirm.models import PSumItems
from twilio.rest import Client
from django.contrib.auth.models import User
from datetime import date
def myorders(request):
if request.user.is_superuser:
if request.method == 'POST':
... |
992,938 | 160b75886b7daff70df1a53c50340d73d1ebefff |
def USE_PPHT
def MAX_NUM_LINES 200
# include "opencv2/core/core.hpp"
# include "opencv2/highgui/highgui.hpp"
# include "opencv2/imgproc/imgproc.hpp"
import cv2
import MSAC
def help() :
pass
# cout << "/*\n"
# << " ******************************************************************************************... |
992,939 | 0d61bf0ecc9171394e6014ff496f7647f0cbfdc9 | # cascadingMenus.py
# imports ====================================
from tkinter import *
from tkinter import ttk
# menus are not part of ttk
# tkinter ====================================
root = Tk()
root.title('My New App')
root.geometry('240x140')
# tell Tk object that each meunu in interface should not be
# of the... |
992,940 | 4b53af99516979102da3973b70f276a815d34f82 | while True:
login = input("Enter your login")
if login == "First":
print("Greetings, First")
else:
print("Error, wrong login")
again = input("Try again?")
if again in ["Yes", "yes", "Y", "y"]:
continue
else:
break |
992,941 | ef7f5d95b522f3f8b8504407c4527c3407f02a61 | use_names = []
if use_names:
for use_name in use_names:
if use_name == 'admin':
print("Hello admin,would you like to see a status report?")
else:
print("hello Eric,thank you for logging in again.")
else:
print("We need to find some users!")
|
992,942 | baa0314491823a10f9e859e2c4249f0dd7364414 | #!/usr/bin/py
data_gathered = {}
data_gathered['info'] = [
# 'Name',
# 'Version',
# 'Release_date',
# 'Nbproc',
# 'Process_num',
# 'Pid',
# 'Uptime',
# 'Uptime_sec',
# 'Memmax_MB',
# 'Ulimit-n',
# 'Maxsock',
# 'Maxconn',
# 'Hard_maxconn',
# 'CurrConns',
# 'C... |
992,943 | 1f06e24d72d9d2e6c135be20fa0190795f695b64 | import json
import subprocess
PARSER_DIR = "~/Programming/tools/stanford-parser-2012-11-12"
TAGGER_DIR = "~/Programming/tools/stanford-postagger-2012-11-11/"
PHRASES_FILE = "../data/phrases"
gold = []
with open('../data/gold_labels.json') as f:
gold = json.loads(f.read())
with open(PHRASES_FILE, 'w') as f:
for p... |
992,944 | c054e9c21ef555e6f9fe7d877ff3ed9449454a21 |
# coding: utf-8
# In[1]:
# globals
Alphabet = {}
Tests = []
def init():
with open("alphabet.txt") as f:
AlphabetRaw = " ".join(f.readlines())
alphalist = AlphabetRaw.split()
i = 0
while i < len(alphalist):
Alphabet[alphalist[i]] = alphalist[i+1]
i += 2
for i in range(4)... |
992,945 | 0ecf7e40defcaa5c299c83cf1af8fe7e118c8b38 | """
data-upload.py
Author: Jonathan Whitaker
Email: jon.b.whitaker@gmail.com
Date: April 21, 2016
data-upload.py is an integral part of the AirU toolchain, serving as the script
which uploads the collected data from the AirU station. This script is designed
to run using a Cron.
"""
def fetch_data(excludeNonPollutan... |
992,946 | afd3a72b6186ac4cb0272f8b082566e7e0524393 | from keras.layers import *
from keras.models import *
import keras.backend as K
class DeepFM():
def __init__(self):
self.cat_vars = ["Cat1", "Cat2", "Cat3", "Cat4", "Cat5"] # List of All Categorical Variables Names
self.cat_levels = [2, 5, 6, 3, 50] # List of All Categorical Variables Levels
... |
992,947 | fba66d4e3c6b933b3337e67d1dcf98b4a4b3eaf4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: lisnb
# @Date: 2015-05-07 22:59:04
# @Last Modified by: lisnb
# @Last Modified time: 2015-05-10 01:37:05
class Solution:
"""
@param A: A positive integer which has N digits, A is a string.
@param k: Remove k digits.
@return: A string
""... |
992,948 | 8c198e6b2fe13c9c3ac72da1996e1130e4b31ca8 | # 最大公約数
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
# 最小公倍数
def lcm(a, b):
return a * b // gcd(a, b)
N = int(input())
A = list(map(int, input().split()))
mod = 10 ** 9 + 7
lcm_val = A[0]
for a in A[1:]:
lcm_val = lcm(lcm_val, a)
ans = 0
for a in A:
ans += lcm_val // a
print(an... |
992,949 | bd11ae6d6f70210db1a75f6fd450baf62e549a90 | from kivymd.app import MDApp
from kivymd.uix.textfield import MDTextFieldRect
from kivymd.uix.boxlayout import BoxLayout
from kivymd.uix.button import MDRaisedButton
from kivymd.uix.screen import MDScreen
from kivy.core.window import Window
from kivymd.uix.gridlayout import GridLayout
from kivymd.uix.boxlayout i... |
992,950 | e7f79cf4aac685f72983457c52adb8517eba18a7 | from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import ReplyKeyboardMarkup
import requests
import json
from telegram.replykeyboardremove import ReplyKeyboardRemove
updater = Updater('449150567:AAFwxZjQO_BrE1RVe4qH467vIiDlRD7Hu24')
states = {}
id_global_1 = -1
def get_genre_l... |
992,951 | d606c712cfcf14cb0e47630638c61da124ec9759 | """
Author: Arsene Bwasisi
Description: This program will transform a given grid of numbers
to where the rows become the column and vice versa.
"""
def get_col(grid, n):
""" Return list of values from column n in grid."""
if grid == []:
return grid
return [grid[0][n]] +... |
992,952 | f71a57f2365187ebc3e26898bd06b137a31dd346 | date_data=[[[('企业', 1283), ('防控', 1066), ('组织', 1038), ('社会', 846), ('工作', 832), ('协会', 738), ('服务', 705), ('复工', 666), ('复产', 466), ('会员', 413), ('行业', 404), ('积极', 399), ('捐赠', 391), ('开展', 361), ('提供', 352), ('物资', 334), ('慈善', 314), ('防疫', 311), ('肺炎', 300), ('行业协会', 295), ('中国', 292), ('商会', 255), ('抗疫', 251), ('通... |
992,953 | 426e37a039a32a6ad3e3c79f71407ef3cf4cf599 | """Automatically build a multiconformer residue"""
import numpy as np
import argparse
import logging
import copy
import os
import sys
import time
from string import ascii_uppercase
from . import Structure
from .structure import residue_type
def parse_args():
p = argparse.ArgumentParser(description=__doc__)
p... |
992,954 | 0de152fadb0b3b4c3111caabf129881df0e2be33 | from django.utils.translation import gettext_lazy as _
from rest_framework import exceptions as rf_exceptions
from rest_framework import serializers
from waldur_core.structure.models import CUSTOMER_DETAILS_FIELDS
from waldur_core.structure.serializers import (
CountrySerializerMixin,
ProjectDetailsSerializerM... |
992,955 | 3e3283931c7c7b23099d3a9f1c5dd6ac2ccd310a | import numpy as np
import collections
import os
def read_words(conf):
words = []
for file in os.listdir(conf["directory"]):
with open(os.path.join(conf["directory"], file), 'r') as f:
for line in f.readlines():
tokens = line.split()
# NOTE Currently, only sen... |
992,956 | f75cd630178c9bdac06be62122eb3251fc1a4169 | from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from thornode_client.api.health_check_api import HealthCheckApi
from thornode_client.api.keygen__keysign_api import KeygenKeysignApi
from thornode_client.api.network_api import NetworkApi
from thornode_client.api.nodes_api import Nod... |
992,957 | 6de2b9ba31bfa6482625729f893d1a535a5a8370 | class SegTree:
def __init__(self, init_list, seg_func, id_el):
self.id_el = id_el
self.seg_func = seg_func
n = len(init_list)
self.next_pow_of_2 = 2**(n-1).bit_length()
self.tree = [self.id_el]*2*self.next_pow_of_2
for i in range(n):
self.tree[self.next_p... |
992,958 | 24df5a008f43e2091633e3173a163206a1de2463 | # -*- coding: utf-8 -*-
"""
Database of C-Mod shots, corresponding atomic lines, times of interest, THT for Hirex-Sr data access, etc..
@author: sciortino
"""
from builtins import str
def get_shot_info(shot, imp_override=None):
''' Function to output key information for BSFC fitting of atomic lines '''
if... |
992,959 | fe61f3b4ffe02f42d47d5bf0d0305b16330b87b8 | import random
def gamewin(comp, you):
if(comp == you):
return None
elif(comp == "Rock"):
if(you == "s"):
return False
elif(you == "p"):
return True
elif(comp == "Paper"):
if(you == "r"):
return False
elif(you == "s"):
... |
992,960 | c5be0c79bcd4364316b79a263f51cde27068c3cd | #!/usr/bin/python
# -*- coding: utf-8 -*-
#元组一旦初始化,就不可更改
print '今天我们学习:%s' % '元组tuple'
classmates = ('Tom','John','Lili','merry')
print '打印元组',classmates
print '打印元组的长度',len(classmates)
print '打印元组第2个元素',classmates[1]
print '-------------元组tuple中文---------------'
#定义一个元素的元组时需使用下列样式消除歧义
hanzi = ('汉字',)
#下面的输出结果很有意思,中... |
992,961 | 46f60b0983f72cd11fdd7732eb00662c20283ba5 | #!/usr/bin/env python
"""Fetches diesel prices"""
import paho.mqtt.client as paho # pip install paho-mqtt
import time
import logging
import sys
import requests
from pathlib import Path
from config import *
from secrets import *
FREQUENCY = 3600 # 1h
TIMEOUT = 10 #sec
def fetch_data():
# 73ce263a-8b6a-4b3... |
992,962 | 5dd095a02e7bdc04c3217b80b3c3f6c5995a6ad0 | import pygame
class GameObj(pygame.sprite.Sprite):
def __init__(self, x, y, image=None):
super().__init__()
if image:
self.image = pygame.image.load(image).convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = x
... |
992,963 | 1a4ea63660e511d25a4d8ad88f2fa95a2e5b7f89 | from django.apps import AppConfig as OAppConfig
from proso.django.enrichment import register_object_type_enricher
class AppConfig(OAppConfig):
name = 'proso_user'
def ready(self):
register_object_type_enricher(['user_question'], 'proso_user.json_enrich.user_answers')
|
992,964 | 7909fc8d175132d6c567ca1c0faabe1dfbf4098a | import numpy as np
import load
import utils.sampling as smp
import matplotlib.pyplot as plt
def gm2code(arr, info):
"""
arr originally is a reference to the object from the outside.
But later in "arr = arr / info.pboxsize + 0.5",
the arr is a new
"""
return (arr / info.pboxsize + 0.5)# * 0.99... |
992,965 | 1479fdffa8fcba073a26fd1e14abf4a7f4ddf4e7 | try:
with open('sad.txt', mode='r') as input_file:
print(input_file.read())
except FileNotFoundError as err:
print('Oop!! File does not exists')
|
992,966 | aaf3190604ff70d71cadee1707fd790a66cace49 | # Improve the implementation of Question 3, reusing the basic class DynamicalModel defined in q7
import q7_rumor_simulation as q7
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
class LogisticGrowthModel(q7.DynamicalModel):
# basic settings and initial conditions
def __init__(self, step_si... |
992,967 | 51578bf6e9155dacbf9807b247049ccfed952d76 | from expression import Expression
def main():
exp = Expression("2 / 3 * 4")
print exp.solve(None)
if __name__ == '__main__':
main()
|
992,968 | cd187eebf6d512291bb18ab69102e66cb6bc92d9 | from .general_obj import General
from .message import Message, MessageStatus
from .bft import ByzantineMessages
|
992,969 | a2802311a5672cd1886a349b5df9aca682286f4d | import numpy as np
from tensorflow.keras.models import Sequential,load_model
from tensorflow.keras.layers import Dense, Conv2D,MaxPooling2D,Dropout,Flatten
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from tensorflow.keras.callbacks import ModelCheckpoint
from sklearn.model_selection import KFold,... |
992,970 | ea19d2715e3be1a51a51fc8d8a2446f77dbf0dd2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
import websockets
async def send_data(url,data):
"""
:parm url url wanted to connect (str)
:parm data data wanted to send out
"""
async with websockets.connect(url) as socket:
await socket.send(data)
data = await soc... |
992,971 | bc8bc25e38e3a0d1bf5df936b9f7bdbdb88515c7 | class User:
def __init__(self,name,email):
self.name = name
self.email = email
self.account_balance = 0
#methods
def make_deposit(self,amount):
self.account_balance += amount
return self
def make_withdrawal(self,amount):
self.account_balance -= amount
... |
992,972 | 452f8bc3d8fb70333befe087477a0b0a8d22864a | # -*- coding: utf-8 -*-
"""
@propertyの動作を確認するためのサンプルコード。
"""
class FixedResistance(object):
def __init__(self, ohms):
self._ohms = ohms
self._voltage = 0
self._current = 0
@property
def ohms(self):
return self._ohms
@ohms.setter
def ohms(self, value):
... |
992,973 | e14a9a7358128061104e8ca055dbea85fe9257bf | import anvil.node_types as nt
import anvil.runtime as rt
from base_test import TestBase, clean_up_scene
class TestBaseCurve(TestBase):
def setUp(self):
super(TestBaseCurve, self).setUp()
self.null_transform = nt.Transform.build()
class TestCurveBuild(TestBaseCurve):
@clean_up_scene
def t... |
992,974 | 47bddbe06ef59bd37b39490cb78ab7fdce6149e9 | #!/usr/bin/python
n = input()
ar = map(int, raw_input().split())
res = [0] * (max(ar) - min(ar) + 1)
for i in ar:
res[i-1] += 1
print res.index(max(res)) + 1
|
992,975 | 75959e6058535e0ac96b440cd96cc0f383c4944e | from typing import Optional
from sqlmodel import SQLModel, Field, create_engine, Session
engine = create_engine(url="sqlite:///users.db", echo=True)
class User(SQLModel, table=True):
id:Optional[int] = Field(None, primary_key=True)
username: str
password:str
def get_session():
with Session(engine) as... |
992,976 | 76196993beb6de2c6b5a2f77a82b3876bb3aca00 | #!/usr/bin/python
# -*- coding:utf-8 -*-
while True:
x = [i for i in range(10) if i%2 == 0]
print x
break
else:
print "It's over"
print "end"
|
992,977 | 6a9911fb9cb5cd251bb5a8f811f81c47b8f83ce4 | def prenet(inputs, num_units=None, dropout_rate=0, is_training=True, scope="prenet", reuse=None):
with tf.variable_scope(scope, reuse=reuse):
outputs = tf.layers.dense(inputs, units=num_units[0], activation=tf.nn.relu, name="dense1")
outputs = tf.layers.dropout(outputs, rate=dropout_rate, trainin... |
992,978 | 0aeb58463fd2ac23bc4e78eda872e533e90cc243 | import pickle
def psave(a):
pickle.dump(a, open("debug/save.p", "wb"))
def popen(a):
return pickle.load("debug.save", wb) |
992,979 | 574cc6c156ca98d1ac600db2e4cdcadeb0d2211c | from os import path, mkdir
import nrrd
import numpy as np
import matplotlib.pyplot as plt
# sample code for opening PET and CT files in nrrd format, cutting the head region, printing some data from the header,
# and saving them again.
def sample_stack(stack, rows=6, cols=6, start_with=10, show_every=3):
fig, ax... |
992,980 | 16aed2d56a2174767146a4a40f3618ca1e881eef | """
Classes for Neural Net learning via NEAT
NeuroEvolution of Augmenting Topologies
Video that inspired this entire machine-learning project:
https://www.youtube.com/watch?v=qv6UVOQ0F44
Original NEAT paper (that I didn't read):
http://nn.cs.utexas.edu/downloads/papers/stanley.ec02.pdf
"""
from __future__ impor... |
992,981 | f59f5b02c71801a6bed3e359ddfac18711da543d | from tkinter import *
def calc():
try:
value = eval(entry.get())
entry.delete(0,END)
Entry.insert(entry,0,'= '+str(value))
except:
entry.delete(0,END)
Entry.insert(entry,0,"ERROR")
def clr():
entry.delete(0,END)
def insert(txt):
if... |
992,982 | 377ca4caa42fb8869c796b9ad21b24437d65200f | print("Hello World\a");
print("Hello World\b");
print("Hello World\cx");
print("Hello World\C-x");
print("Hello World\e");
print("Hello World\f");
print("Hello World\M-\C-x");
print("Hello World\n");
print("Hello World\756");
print("Hello World\r");
print("Hello World\s");
print("Hello World\t");
print("Hello World\v")... |
992,983 | d87b253695c109e77fb9bfc743970147edad5c62 | import socket
import time
from PyQt5.QtCore import QTimer, QThread
import queue
import logging
import pyaudio
import threading
logging.basicConfig(format="%(message)s", level=logging.INFO)
class AudioRec(QThread):
def __init__(self, threadChat):
super().__init__()
self.threadChat = threadChat
... |
992,984 | 1c25c7fdc846346b6d8409c3a1e3959b74f3c356 | # Search Function
import re
line = "Welcome to PYTHON World By Keshav Kummari"
searchObj = re.search(r'(.*)python(.*)',line,re.M|re.I)
if searchObj:
print(searchObj.group())
print(searchObj.groups())
else:
print("No Match Found!") |
992,985 | 7f46a69dcc918142b4c0c756768125d69b649167 | from django.conf.urls import patterns, url
from apps.pcvblog.views import EntryCreate, EntryList, EntryUpdate, TagJSON
urlpatterns = patterns('',
url(r'entry/list/$', EntryList.as_view(), name='entry_list'),
url(r'entry/create/$', EntryCreate.as_view(), name='entry_create'),
url(r'entry/(?P<pk>\d+)/$', Ent... |
992,986 | bae56b01ae55c90502679b80f504921a8ee1ef57 | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7
DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(... |
992,987 | f7e2233c43491cd681d4701c82c3831c8c70cdbe | import sys
import urllib2
import urllib
from bs4 import BeautifulSoup
import re
import urlparse
import os
def main():
downloadSongsInFolder(sys.argv[1])
def downloadSongsInFolder(folder):
print folder
response = urllib2.urlopen(folder)
html = response.read()
dom = BeautifulSoup(html,"html.parser")
links = dom... |
992,988 | a980198c4bf76493edbc060e67bb9e177aee07b1 | info={'name':'egon','age':18,'sex':'male'}
# #本质info=dict({'name':'egon','age':18,'sex':'male'})
#
print(info['age'])
print("age" in info)
# info['height']=1.80
#
# print(info)
#
# for key in info:
# print(key)
#字典的key必须是不可变类型,也成为可hash类型
# info={(1,2):'a'}
# print(info[(1,2)])
#字典常用的方法(优先掌握)
# info={'name':'eg... |
992,989 | 282575a432159ab1bb77c75eacde6368516e82b5 | from django.db import models
from django.contrib.postgres.fields import JSONField
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from opencivicdata.core.models import Jurisdiction
from opencivicdata.legislative.models import LegislativeSession... |
992,990 | 447a149ae9f2f1186ee3dfe1d483c0ce47fdc974 | # 3. Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
dct = {1: "Зима", 2: "Зима", 3: "Весна", 4: "Весна", 5: "Весна", 6: "Лето", 7: "Лето", 8: "Лето", 9: "Осень",
10: "Осень", 11: "... |
992,991 | b21ab7a6ab8a6cf206ed8a8f4cfed76e5e3d50b6 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
# horizon工程目录
HORIZON_HOME = "/home/dengjy/horizon"
# runserver时使用的端口
SERVER_PORT = "8093"
# runserver时是否启用: ip netns exec haproxy ...
IS_NEED_IP_NETNS = True
# 常量
PUBLIC_LOCAL_SETTINGS = "/usr/share/openstack-dashboard/openstack_dashboard/local/loca... |
992,992 | b3dcf8ef8b47e8bcac2d33fc137ff52fe36eb88f | #!/usr/bin/env python
#
# Patrick Jenkins 1/7/2011
#
# Parse the query string portion of a URL into name and value pairs.
#
# Example:
# parse_qs "parse_qs "sourceid=chrome&ie=UTF-8&q=patrick+jenkins""
from sys import argv
from urlparse import parse_qs
url_parts = parse_qs(argv[1])
for key, val in url_parts.items():... |
992,993 | bf45617dafa562af48cb63d9e231049dfd2b834f |
a=abs(3)
b=cmp
print a
print b(1,2) |
992,994 | 0c53cdc2a4075b06b144c14406fd356b7df1adfe | #Author(s) - Mukund Manikarnike
from igraph import *
from random import randint
import scipy
import scipy.stats
#Read from the anonymized edge list that was created
anonymizedEdgeListFile = open("anonymized_edge_list.csv", 'r')
#Create a graph object for the graph that has been created
graph = Graph()
graph.add_ver... |
992,995 | e95880c40c7594445b446b31d964db11f2a44dc4 | import numpy as np
import pandas as pd
from lsst.sims.skybrightness import SkyModel
import lsst.sims.skybrightness_pre as sb
from lsst.sims.utils import raDec2Hpid, m5_flat_sed, Site, _approx_RaDec2AltAz
import healpy as hp
import sqlite3
import ephem
import sys
__all__ = ['mjd2night', 'obs2sqlite']
class mjd2night(... |
992,996 | 8a893edb2d72354aa36e82c3325711a8eb4b73f7 | __author__ = 'Joe Linn'
from .abstract import AbstractQuery
import pylastica.script
class CustomScore(AbstractQuery):
def __init__(self, script=None, query=None):
"""
@param script:
@type script: str or dict or pylastica.script.Script
@param query:
@type query: str or pyla... |
992,997 | 117593e0a28fbd83acc8ae5972d344a9025c5ddf | #!/usr/bin/python
# -*- coding : utf-8 -*-
import os, sys
import os.path
import setting
class IngentiaError:
def __init__(self):
self.msg = ''
self.detail = ''
self.url = ''
def __str__(self):
return "%s \n %s \n %s\n" % (self.url, self.msg, self.detail)
class Reporter:
... |
992,998 | 159b7269b3520d49faf549097c42bc303c9d1caa |
from math import sqrt
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def getPoint(self):
return self.x, self.y
def getNormal(self):
return Point(self.y, -self.x)
def getMagnitude(self):
return sqrt(self.x ** 2 + self.y ** 2)
def getUnit(self):
m = self.getM... |
992,999 | d8cac68ea2741bc426a516189a948cdf1bb48cd4 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import cv2
import argparse
from PIL import Image, ImageChops
from framing_helper import trim
from metricas_qualidade import metricas_qualidade
def crop_first_half(image):
#print("[INFO] Importando imagem de entrada ...\n")
# Import image
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.