index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
16,900
c45fc8515e812ef055855ee49ac60e791352f40a
import cv2 import numpy as np import os import socket import time from datetime import datetime import threading import urllib.request import pymysql.cursors # DB ํ•ธ๋“ค ๋ฏธ๋ฆฌ ํ•ด๋‘๊ธฐ #conn = pymysql.connect(host='192.168.0.111', user='%', password='',db='smartvideophone',charset='utf8mb4') conn = pymysql.connect(hos...
16,901
8212c72f4f8e46bdf33f107c2551f757966a54f0
import tkinter import random import time import ISSM_Snowflake CLOUD_COLOR = '#f0f8ff' BACKGROUND = '#b0c4de' FLAKE_COLOR = '#f0ffff' CANVAS_WIDTH = 800 CANVAS_HEIGHT = 600 NUM_BINS = 10 NUM_CLOUDS = 7 BIN_HEIGHT = 0.75 TO_FALL = 100 TAG = 'snowflake' class GlacierApplication: def __init__(...
16,902
3c8d30cae53e45dd20d570fac23db51c1fa9d362
import json import requests response = requests.get(' https://www.nbrb.by/api/exrates/rates/dynamics/145?startDate=2021-6-18&endDate=2021-6-25') data = json.loads(response.text) print(data) def average(data_): summa = 0 days = 0 for i in data_: summa += i['Cur_OfficialRate'] days += 1 ...
16,903
9eabed2908b21b1766967fbdeeb40276726cef70
import pygame import sys class Runnable(object): def __init__(self): self.running = True self.run_result = None def stop(self, result=None): self.run_result = result self.running = False def run(self): undermouse = None saved_background = self.surf.copy() ...
16,904
e3d34cc2ec504a3b8e550a8a604b0f195276bb18
# Generated by Django 3.1.2 on 2020-11-03 00:40 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CurrentWx', fields=[ ('date', models.DateFi...
16,905
96502a546598329a9ebba731ec48a211c397a84f
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import time import os import TransformingAutoEncoder class Trainer(): def __init__(self, model, learning_rate, weight_decay, momentum, batch_size, total_steps, ckptdir, logdir): self.model = model ...
16,906
1bb876f801693edf8e776d17f0a62feb3de0bd0f
___author__ = 'Fernando Garcia Barrera__Andres Baron__Kevin Ruiz_Corregido' import math import matplotlib.pylab as plt import wave import pyaudio class Seno: wavearray = [] def __init__(self, frecuencia, sampling, bits, time, max): self.SamplingRate = sampling self.NumeroBit = b...
16,907
9bccfc4524a91393d24fc17c9f0af8b3342b291c
# -*- coding: utf-8 -*- """Console script for pycloud.""" import sys import click from pycloud.logger import configure_logger, get_logger, ALLOWED_LOG_LEVELS from pycloud.core.provisioners.plan_executor import PlanExecutor from pycloud.core.config import PyCloudConfig from pycloud.core.keypair_storage import KeyPairS...
16,908
e875d314f9da3c52575d0d187484e339fbc730f5
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ejemplo.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) db.Model.metadata.reflect(db.engine) class Clients(db.Model): __table__ = db.Model.metadata.ta...
16,909
7378136891330b756ebefed301bb3d0468cfe4be
from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.sites.shortcuts import get_current_site from django.contrib.auth import login, authenticate from .forms import SignupForm from .forms import SettingForm from django.contrib...
16,910
3db8b205f6fcec5ea7a55f16d3183d16d6adcf7b
# ECRYPT BY Boy HamzaH # Subscribe Cok Chanel YouTube Gua Anjing # Dan Jangan Lupa Follow Github Gua exec(eval((lambda ____,__,_ : ____.join([_(___) for ___ in __]))('',[95, 95, 105, 109, 112, 111, 114, 116, 95, 95, 40, 39, 109, 97, 114, 115, 104, 97, 108, 39, 41, 46, 108, 111, 97, 100, 115],chr))(eval((lambda ____,__,...
16,911
79ce429b39c0467514121d5f48b960b28b5448f6
# coding:utf-8 #Imports import os os.system('clear') from random import randint #Variables saldo = 100 apuesta = 0 salir_apuesta = False #Surt per pantalla el teu saldo. print "Tu saldo inicial:", saldo #Condiciรณ d'entrada al bucle. while (salir_apuesta == False) : #Elegim la cantitat a apostar. apuesta = inp...
16,912
623161f5e1a81dfcc049236e32369c2077bc314b
from PIL import Image, ImageDraw, ImageFont import string import random def get_generate_authenticode(): # ่Žทๅ–้šๆœบๆ•ฐ letters = ''.join([random.choice(string.ascii_letters) for i in range(4)]) # ็ป˜ๅˆถๅ›พ็‰‡ width = 100 height = 40 im = Image.new('RGB', (width, height), (255, 255, 255)) #ๆ–‡ๅญ—็”ปๅ›พ dr =...
16,913
b97851a715aea71fe57d1db57a94baf37a0c954d
import itertools def is_pangram(sentence): sentence = str(sentence) final_set = set(c.lower() for c in sentence if c.isalpha()) return len(final_set) == 26
16,914
b015af9beab7eb01dc7c5d619be11c14f9468759
import logging import random, string from django.http import Http404 from django.db import transaction from rest_framework import generics from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from mangopay.resources import Natural...
16,915
9943614eaed310fa26eebce2df56e27a73abbd16
# encoding: utf-8 import os import requests import unittest import twork_env class TworkTestCase(unittest.TestCase): """UnitTestBase For TworkApp """ def setUp(self): env_mode = os.environ['PY_TEST_ENV_TWDEMO'] self.run_env = twork_env.ENV[env_mode] self.run_host = self.run_env...
16,916
03ded613b7813d398679db85cd5a3c3bf1a75f98
import numpy as np import pandas as pd import sys """ Takes the spect_HEART.csv file and changes the label such that outliers are -1 and inliers are 1. """ def fix_label(df): """ Fits the label column such that outliers are -1 and inliers are 1. """ df_label = df['OVERALL_DIAGNOSIS'] df_label.r...
16,917
b119120d58c58a4dc92eddc9e06fb2f92d26dc40
import jinja2 import json import logging import os import urllib2 import webapp2 import config JINJA_ENV = jinja2.Environment( loader=jinja2.FileSystemLoader([ os.path.dirname(__file__) + '/../templates', os.path.dirname(__file__) + '/../static', ])) def jinja_include(filename): return jinja2.M...
16,918
4d7a3f0a2e90b23428126d8696d96c3e68bf48b8
from threading import Thread, Semaphore, RLock from time import sleep from random import randint from collections import deque class SimpleQueue: def __init__(self, size): self.queue = deque() self.reader = Semaphore(0) self.writer = Semaphore(size) self.lock = RLock() def put...
16,919
392d06ac6ef2fbf26726e5a4023527f92342d41d
import re from enum import IntEnum, auto class Version(IntEnum): v1 = auto() v2 = auto() v3 = auto() v3_2 = auto() # original v1 # datetime,username,manufacturer,serial,name,macaddress full_line_v1 = re.compile('^([^,]+),([^,]+),(.*),([\- A-Za-z0-9]*),' '([^...
16,920
7661870871260212b405cf89322dea80cf11a1ad
import asyncio, time, ssl, pathlib,json from aiohttp import web # ัั‚ะฐะฒะธะป pip3 install aiohttp import db_log, sdk import JsonDataBase as jdb class Server(asyncio.Protocol): async def req_post(request): # ะพะฑั€ะฐะฑะพั‚ั‡ะธะบ ะทะฐะฟั€ะพัะฐ POST print('connected, operation = POST') params = request.query p...
16,921
3a3644f9bea7a464f6369fa41b5fea26f5e469fd
# -*- coding: utf-8 -*- a = 1 h = a times = 0 while h < 380000000000: h = h * 2 times += 1 print(times)
16,922
22b2b0cc544db3f28179f2ce8374acd991e86718
# -*- coding:utf-8 -*- ''' class Person: number = 0 def __init__(self,name,gender,age): self.name = name self.gender = gender self.age = age Person.number += 1 def displayPerson(self): print('Name:',self.name,"Gender:",self.gender,'Age:',self.age) def displayNumber(self): print('Total number:',Person.nu...
16,923
7fe920974a57fb4155ae7ee6047e2291dea3ea9b
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import mimetypes import os import posixpath import stat from django.contrib.staticfiles import finders from django.http import Http404, HttpResponseRedirect, HttpResponseNotModified, FileResponse from django.shortcuts import redirect fro...
16,924
b380d1b5646a6139c13921f3064a9006b5a3e209
n=int(input()) current=0 maxi=0 while n>0: rem=n%2 if rem is 1: current+=1 if current>maxi: maxi=current else: current = 0 n=n//2 print(maxi)
16,925
d7617cf3b0d61eef929494fcbdc91b9ef99959aa
hello_str = "Hello world" # 1.็ปŸ่ฎกๅญ—็ฌฆไธฒ็š„้•ฟๅบฆ print(len(hello_str)) # 2.็ปŸ่ฎกๆŸไธ€ไธชๅฐ๏ผˆๅญ๏ผ‰ๅญ—็ฌฆไธฒๅ‡บ็Žฐ็š„ๆฌกๆ•ฐ print(hello_str.count("o")) # 3.ๆŸไธ€ไธชๅญๅญ—็ฌฆไธฒๅ‡บ็Žฐ็š„ไฝ็ฝฎ print(hello_str.index("e")) # for i in range(1,5): # print(i) # i_list = [1,2,3,4] # for i in i_list: # print(i)
16,926
344b6aa3f35a9c7b55ec8b3648a6b731a4a8d174
import socket IP = input("ip to send data: ") PORT = input("ip's port to send data: ") data = b(input("data to send: ")) sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.sendto(data,(IP,PORT))
16,927
3dd2feaee2763ccf1f9e81d58e11d5ae4277ac2e
# featureA 1.0 # ๅˆๅนถdevelop
16,928
e85455a4f82980bdf708acfa8eaaed7877e78914
import math from collections import Counter from Project.StringExtractor import strExtractParse def entropy(s): '''Calculates the entropy value for s.''' p,lns = Counter(s), float(len(s)) return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) def strEntropy(s): '''Calculates entropy ...
16,929
5db9d4966cd74736590334b25e3ed74a377cd985
import csv from django.shortcuts import render from django.http import HttpResponse from django.views.generic.base import View import urllib.request import json from parser4.models import Twogis class View(View): def parse(request, *args, **kwargs): response = HttpResponse(content_type='text/csv') ...
16,930
675fddf03f1a63946f52817a2c07e2a1323e2b61
from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.contrib.gis.db import models as gis_models from django.contrib.gis import forms from django.contrib.gis.geos import Point from location_field.models.spatial import Locat...
16,931
0797159247b870844c86d782050161d13dbf5db5
import os import sys import asyncio import json from utils import scan_json import traceback import time import config import time loop = asyncio.get_event_loop() clients = {} process_conn = None log_time = 0 log_buffer = [] def response(conn, **res): if not conn: return # print("response="+repr(res)) con...
16,932
b60c35fc74ee322d3fa29f545f931d0640d87206
#! /usr/bin/env python # coding: utf-8 # Author: Joรฃo S. O. Bueno # Copyright (c) 2009 - Fundaรงรฃo CPqD # License: LGPL V3.0 # adapted for Python 3.9; copy_dependencies() and find_module_files() # added by Yul Kang from types import ModuleType, FunctionType from typing import Sequence import sys, os, shutil from imp...
16,933
6534cbb0c9a67a655c9537f4aa05f159767c7e7b
import threading import uuid import re import requests import reversion from django.conf import settings from django.contrib.auth import get_user_model from django.urls import reverse_lazy from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.con...
16,934
2a38b4a30d56678cafa1ce3f963526b8b156e48e
# Time Complexity : O(n^2) # Space Complexity O(n) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach ''' Since postorder is left right root therefore the last element of the postorder list will be root using...
16,935
8e1f3fcb4bcc421a56653a4940224a089538f6d1
from flask import Flask, request, redirect, session, render_template, Response, make_response from flask_cors import CORS, cross_origin from flask_basicauth import BasicAuth from datetime import datetime from time import gmtime, strftime, mktime from twilio.twiml.voice_response import Gather, VoiceResponse, Say import ...
16,936
7616942530ecb1e4ebd932e59b5c27338010eb3a
from pyrep.robots.mobiles.nonholonomic_base import NonHolonomicBase class TurtleBot(NonHolonomicBase): def __init__(self, count: int = 0): super().__init__(count, 2, 'turtlebot')
16,937
48ce690b6aba42c4003adec8d3200ea081bb5643
"""empty message Revision ID: 35405a9f16c4 Revises: Create Date: 2017-04-29 11:36:24.682258 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '35405a9f16c4' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
16,938
10bdece86c8f954d525c1def6775fecd018faec0
#!/usr/bin/env python3 #coding:utf-8 import json import os import numpy as np from tqdm import tqdm from nltk import tokenize from rake_nltk import Rake import re from Scripts.MyModel.util import * '''import spacy nlp = spacy.load("en_core_web_sm") doc = nlp("Apple is looking at buying U.K. startup for $1 billion") f...
16,939
dec87f29cfaf2d454919e346e665030c87190fee
#!/usr/bin/env python """Parse the JSON output of the Anchore Grype command.""" import json import logging import os import sys class ParseGrypeJSON(): """Parse the JSON output from Anchore Grype.""" def __init__(self): """Create a ParseGrypeJSON object.""" if 'LOG_LEVEL' in os.environ: ...
16,940
c26b811c4f07a54e4aa2c4582880eb59a3a192f4
import cv2 as cv import argparse global isDrawing global start_coords global storage # Classes class CommandStorage: storage = [] def to_string(self): print("Command storage state: ") for i, command in enumerate(self.storage): print("Command " + str(i) + ": X1:{0} Y1:{1} X2:{2} Y...
16,941
c9686f08f796af7ad78d1ac1276c7da5675dac82
import time import webbrowser import os import random #create text file youtubeLinks.txt if it does not exist already if os.path.isfile("youtubeLinks.txt") == False: print("No videos present. Creating file.") flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY makeFile = os.open("youtubeLinks.txt", flags) wit...
16,942
295132da1ff1b01018d48cfe2f66dcbb97974609
import json import os class DbCredentials: def __init__(self): ''' Currently set up to use VCAP but may need to adapt to use json line ''' dbinfo = json.loads(os.environ['VCAP_SERVICES'])['sqldb'][0] dbcred = dbinfo["credentials"] self.db = dbcred['...
16,943
46ac43221f3e74157507635ab8365476659f6033
# -*- coding: utf-8 -*- import scrapy from slugify import slugify import os import sys import json from urllib.parse import urlparse, urljoin import datetime as dt import re date = '{}.{}.{}'.format(dt.datetime.now().year,dt.datetime.now().month,dt.datetime.now().day) folder_name = os.getcwd()+'/../data/adondevivir/'+...
16,944
9de6798dbaaa4e622a3fe8407593108088349b6d
# ๐Ÿšจ Don't change the code below ๐Ÿ‘‡ print("Welcome to life time left before 90!") age = input("What is your current age? ") # ๐Ÿšจ Don't change the code above ๐Ÿ‘† #Write your code below this line ๐Ÿ‘‡ timeleft = 90 - int(age) x = 365 * timeleft y = 52 * timeleft z = 12 * timeleft print("+++++++++++++++++++++++++++++++++++...
16,945
04fd7612d9f3436104590d8ce528ccd501afdcb3
from datetime import timedelta from .base import AbstractCombinedNode from ebu_tt_live.clocks.media import MediaClock from ebu_tt_live.documents.converters import EBUTT3EBUTTDConverter from ebu_tt_live.documents import EBUTTDDocument, EBUTT3Document class EBUTTDEncoder(AbstractCombinedNode): _ebuttd_converter =...
16,946
40074ce52e976b646a817e4bd50b9e43f644a590
import os import numpy as np def getUsers(usersFile): users = open(usersFile, "r") users = users.read().split('\n') users = users[0:len(users)-1] return users def getGT(gtFile): gt = open(gtFile, "r") gt_lines = gt.read().split('\n') gt_lines = gt_lines[0:len(gt_lines) - 1] gt_users...
16,947
e2697f4532bd4bd985dd43c03889f6592753519e
import cv2 import numpy as np import sys file_name = "video.mp4" file_name = sys.argv[1] cap = cv2.VideoCapture(file_name) cnt = 0 while (cap.isOpened()): cnt += 1 ret, frame = cap.read() cv2.imwrite("frame{}.jpg".format(cnt), frame) if cv2.waitKey(20) == 27 or 0xFF == ord('q'): break cap.re...
16,948
b8515010e10d403afbe7f8f087ec2a4627af3b3b
#!/usr/bin/python # -*- coding:utf-8 -*- import urllib2 import logging import json class FacebookApi(object): def __init__(self, appid=None, secret=None): self.appid = appid self.secret = secret self.status = True # True:success self.message = None self.data = None ...
16,949
c55d79c0cb9d68ebc7150c94e969f12c4f3d0795
days = int(input('O carro foi alugado por quantos dias? ')) kms = float(input('Quandos Km foram rodados? ')) totalPrice = (60 * days) + (0.15 * kms) print('Total a pagar:', totalPrice)
16,950
be636e80a54f281835333c38dbdec2fd7de7d79d
# -*- coding:utf-8 -*- import re def change_scor(scor): if scor: return scor else: return 'ๆ— ๆณ•่Žทๅ–ๅˆ†ๆ•ฐ' def change_publish(url): return re.sub('\s', '', url) def change_price(url): if len(url) > 1: return url[1] + url[0] else: if 'ๅ…ƒ' in url[0]: return url...
16,951
3eafc3eba5d66b08670e2407cf3f2f2853f81bd5
from collections import defaultdict as dd def get_single_doc(path): for line in open(path): if "Mean Singleton Coverage" in line: return float(line.split()[-1]) raise ValueError("Missing field!") def get_raw_doc(path): for line in open(path): if "Mean Raw Coverage" in line: ...
16,952
5f027707e317bf82df674018c196446b5c70cd9d
from django.contrib.auth.models import User from django.db.models import Count, Case, When, Avg from django.test import TestCase from store.models import Book, UserBookRelation from store.serializers import BooksSerializer class BookSerializerTestCase(TestCase): def test_ok(self): user1 = User.objects.c...
16,953
79bd17d5d9068c9e069d5b725abb40c6481170d8
#!/usr/bin/python import os import shutil import time from IPython.display import Image # import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.utils.data imp...
16,954
6d7a894475f69081cc0dd763ea8f98ba81c3660e
a = 4 S = 0 for i in range(4): S += i print(S)
16,955
71686234e785f07ea8ac87757899b263eeaf4bac
from fanstatic import Library from fanstatic import Resource from js.jquery import jquery from arche.interfaces import IViewInitializedEvent from arche.interfaces import IBaseView from arche.fanstatic_lib import main_css voteit_site_lib = Library('voteit_site', 'static') voteit_site_css = Resource(voteit_site_lib, 'c...
16,956
5981ae861e0199551689c66ccb9f8955e7676a1b
from datetime import datetime from django.db import models from users.models import UserProfile from music.models import Music, Video # Create your models here. class MusicComment(models.Model): """ ้Ÿณไน่ฏ„่ฎบ """ music = models.ForeignKey( Music, on_delete=models.CASCADE, ...
16,957
3bbefb390825720e9bd5aa1dacc848b001338dad
# CCC 2014 Junior 4: Party Invitation # # relatively straight forward 1D array processing # (element removal and modulo arithmetic) # file = open ("j4.5.in", "r") k = int(file.readline()) #create friends array [1...k] friends = [] for i in range (k): friends.append(i+1) m = int(file.readline()) for round in ran...
16,958
9b78691bfd9676fb6d320111afb7603530e830f0
nome = input("Informe seu nome: ") valor = float(input("Informe um valor: ")) #Mรฉtodo 1 saida = "{};{}".format(nome.upper(), valor) print("Saรญda formatada:", saida)
16,959
e33756da1245568a6f9aa6e47ffbd0780f2607f3
from core.check import Check from utils.loggers import log from utils import rand import string import requests import urlparse import os class Twig(Check): render_tag = '{{%(payload)s}}' header_tag = '{{%(header)s}}' trailer_tag = '{{%(trailer)s}}' contexts = [ { 'level': 1, 'prefix': '""}}'...
16,960
5d2644ad626cfcbb5ae93467e0da49f61835ee65
from .models import List, Friends, FriendRequest def user_lists(request): try: user_lists = List.objects.filter(user=request.user) return {'user_lists': user_lists} except TypeError: return {'user_lists': ()} def shared_lists(request): try: shared_lists = List.objects.fi...
16,961
9a5d2df267aa8c673ab68c6f87695c3c35804c56
"""Utilities for opencv library""" from __future__ import print_function from __future__ import absolute_import import cv2 class single_threaded_opencv(object): # pylint: disable=invalid-name ''' Context manager that disables IPP for deterministic results and sets number of threads to 0 to avoid hanging...
16,962
b4413709cff39be5a94c1c1209fed402363826e2
#!/usr/bin/python # Author: Sakshi Shrivastava # Email: sshriva3@uncc.edu ## The file demonstrates: ## 1. Adding rooms and walls to the environment (refer to buildWorld.py as well) ## 2. Setting up a robot ## 3. Perform collision checking ## 4. Modify the robot configurations and visualize ...
16,963
58282d57d9ec5fa4bba8172eb711950a9ebcfcf4
#!C:\Python34\python ''' def test_function(a,b) : return a*b a = input('input a: ') b = input('input b: ') c = test_function(int(a),int(b)) print (a ,"*",b ,"=",c) ''' ### input / output control ## define valuable ### control ## function ## string a = input ('test :') print ('this is',a)
16,964
46d6285e142429c25f298a6bdff965f2d39c7f57
# # PySNMP MIB module HP-ICF-ARP-PROTECT (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-ARP-PROTECT # Produced by pysmi-0.3.4 at Wed May 1 13:33:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
16,965
0be416d15dfe11f59e91b28fb2b54ab180b33bcd
import os import platform import sys import requests from metaflow import util from metaflow.decorators import StepDecorator from metaflow.exception import MetaflowException from metaflow.metadata import MetaDatum from metaflow.metadata.util import sync_local_metadata_to_datastore from metaflow.metaflow_config import...
16,966
324629e37c2735f5ad5485b730623a9cdb543d61
# Generated by Django 2.1.4 on 2019-02-09 15:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Disc', fields=[ ...
16,967
0a5c3b083ba9d3a65a033bba7438963c26c1225b
import os import re import string import json import subprocess from time import time from warnings import warn from argparse import ArgumentParser from pathlib import Path BASE_DIR = Path(__file__).resolve().parent RESOURCES_DIR = BASE_DIR / "resources" def main(): parser = ArgumentParser() parser.add_argum...
16,968
7531465ebf18c8b3ff1ce7a5fb84c1d459e6d60a
import os import warnings import astropy.units as u import numpy as np from astropy.time import Time from sora.config import input_tests from sora.config.decorators import deprecated_alias from .utils import calc_fresnel warnings.simplefilter('always', UserWarning) class LightCurve: """Defines a Light Curve. ...
16,969
4fff13d8d3db77a58234167d0dc1279f2ec53ae2
# coding: utf-8 # ## 1. Requirements # In[1]: import os import random import numpy as np import pandas as pd from math import sqrt from sklearn.metrics import mean_squared_error from sklearn.preprocessing import MinMaxScaler import torch import torch.nn as nn import torch.utils.data import torch.optim as optim ...
16,970
3adbdb85ffe40c132bd0a5ded677626980d999d2
from pytest import approx from sklearn.impute import SimpleImputer import pandas as pd import numpy as np from sklearn.pipeline import FeatureUnion, Pipeline from sklearn.preprocessing import StandardScaler, LabelBinarizer from sklearn.base import BaseEstimator, TransformerMixin def test_imputer(): pip1 = Pipelin...
16,971
ec64e5f606aac7736f2742b73f789e330233c66b
from typing import List def shift_right(nums: List[int], index: int) -> None: for i in range(len(nums) - 1, index, -1): nums[i] = nums[i - 1] def merge(nums1: List[int], m: int, nums2: List[int], n: int) -> None: i = 0 j = 0 while i < m + n: if i - j == m and j < n: nums1[i...
16,972
3bad219541ca57a3d858a6cc75a85fea4b6bc55c
N, A, B = map(int, input().split()) if N*A >= B: r = B else: r = N*A print(int(r))
16,973
c914b791b2a476c5a22c2bea9690de82b027e5a2
# -*- coding: utf-8 -*- # Scrapy settings for show_scraper project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'show_scraper' SPIDER_MODULES = ['show_scraper...
16,974
071e6d0f4755489b0b9f0b820b9471ae2d2c8cc1
def StringCompression(string): start = string[0] count = 1 compressed = '' for i in range(1, len(string)): if string[i] == start: count += 1 else: compressed += start + str(count) start = string[i] count = 1 return compressed print(Str...
16,975
7483a19ad9bee91a9dbb2753138f02fb4a293786
#!/usr/bin/env python import rospy from std_msgs.msg import Float64MultiArray import time def talker(): hip_data = [0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0] knee_data = [1.05, 1.1, 1.15, 1.2, 1.25, 1.3, 1.35, 1.4, 1.45, 1.5] pub = rospy.Publisher('/debug', Float64MultiArray, queue_size =...
16,976
2d22be0fa66c853a17ee9abbf9d6da00846849c9
import subprocess from subprocess import PIPE proc = subprocess.run("date", shell=True, stdout=PIPE, stderr=PIPE, text=True) date = proc.stdout print('STDOUT: {}'.format(date))
16,977
95ebabfe5647ea15cee699e51a95cf0938e33ede
# -*- coding: cp1254 -*- #!/usr/bin/python def onlar_basamagi(sayi): a=sayi/10 b=a%10 if b<7 and b>3: return True else: return False
16,978
2987c1646f88b4e38c724e67032f63c577557654
#Marcella Petrucci #petrucma@oregonstate.edu ######################## #Program Description # This program uses the Nearest Neighbor algorithm # to find the approximate solution to the Traveling Salesman Problem. # # the program takes a list of vertices as coordinate pairs, identified by an integer # and processes them...
16,979
1c9e6ecf94330f7297d424b3aca09f279e6d56c5
# -*- coding: utf-8 -*- """ Created on Thu Apr 2 12:22:19 2020 @author: Casanova """ import random print("Bienvenue sur la machine ร  sous de Julien !") fruits = ["ananas", "cerise", "orange", "pasteque", "pomme_dore"] p = [0.2,0.25,0.40,0.1,0.05] prix = { "orange":5, "cerise":15, "ananas"...
16,980
a1041c5d78a187a6cce36e5b8fafce0c8d9f7d9c
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-01-18 14:25:45 # @Author : robin (robin.zhu@nokia.com) # @Description : import os import json def json2txt(json_filename): txt_filename = json_filename + ".txt" new_fp = open(txt_filename,mode='w') date_list = [] jsonfile_fp = file(json_filename) d...
16,981
e21617141cbe7615bcc5b55d74388f0f5458596f
#!/usr/bin/env python # swmiditp-stream.py: Stream MIDI RDF triples import mido import uuid from rdflib import Graph, Namespace, RDF, Literal, URIRef from datetime import datetime import time import sys # if len(sys.argv) < 2: # print """\ # Usage: swmiditp-stream.py <midi input device>""" # exit(1) midi_in...
16,982
81caf113515dbe621cffe174b55f79365383cb31
import os from nose.tools import eq_ from moban.plugins import BaseEngine from moban.jinja2.engine import Engine from moban.jinja2.extensions import jinja_global def test_globals(): output = "globals.txt" test_dict = dict(hello="world") jinja_global("test", test_dict) path = os.path.join("tests", "f...
16,983
e0a59c127a31ae9daba88fc92687e7cde6081a2a
import re message = "some message having 123-555-999 nummbers. Call 111-333-111" # regex basics till line 20 # we pass raw string to compile() # call re.compile() function to create regex object phoneregex = re.compile(r'\d\d\d-\d\d\d-\d\d\d') # d for digit match_object = phoneregex.search(message) # search() creates...
16,984
775772f39a66096d7ffdb3834eda548747bae865
import unittest from queue import PriorityQueue def mergeSortedArrays(arrays): mapArrayIdToRunningIdx = {} ans = [] for i in range(0, len(arrays)): mapArrayIdToRunningIdx[i] = 0 # insert initial values into funnel # Each element in funnel is in type (value, currRunningIdx, arrayId) fu...
16,985
748b61f6eabf347820c4015e19f605eeb2968ba3
""" @COMPANY WHALE @AUTHOR ChenZhou @DESC This is the realization of POI Searcher using AMap API. @DATE 2019/09 """ import requests import time import random import math import json import logging import pandas as pd class POISearcher: # for selected <types> please refer to <coderef/amap_poicode.xlsx>, seperated...
16,986
faaa1b07b44070f3e5c8175405f6bc8573fb0bd1
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymongo from scrapy.conf import settings # # class XiciPipeline(object): def __init__(self): host=settings['...
16,987
9fd995fd14453695686b6206a340801ca2772611
#!/usr/bin/python import os import sys import subprocess import json sys.path.insert(0, os.path.join(os.environ['CHARM_DIR'], 'lib')) from charmhelpers.core import ( hookenv, host, ) hooks = hookenv.Hooks() log = hookenv.log SERVICE = 'gluu-server' RIPO = 'http://repo.gluu.org/GLUU/ubuntu/pool/gluu/Gluu-CE...
16,988
5b1ab5b453f42d76240735e7c8c3580d65babb7b
import sqlite3, random db_path = 'test.db' trainers = ['Youngster Joey', 'Sabrina', 'Red', 'Steven', 'Allister'] # Connect to a database def connect_db(path): conn = sqlite3.connect(path) # Convert tuples to dictionaries conn.row_factory = sqlite3.Row return (conn, conn.cursor()) # Show dog name and...
16,989
d7fec18603a437ccfa8b12f8b1b577a27d6cd91a
# -*- coding:utf-8 -*- # _all_ = ['read'] # ๅชๆœ‰moneyๅ˜้‡ๅฏไปฅไฝฟ็”จ print('in demo.py') money = 10000 def read(): print('in read',money) if __name__ == '__main__': print('run the demo') print(__name__) #__main__
16,990
ee893b8b6ec097781f5c61df4b437ef998ac5aed
# SPDX-FileCopyrightText: 2021 phearzero for Telluric Guru # SPDX-License-Identifier: MIT import time import board import analogio import adafruit_bme680 from simpleio import map_range from minipb import Wire buffer = Wire(( ('temperature', 'f'), ('altitude', 'f'), ('sea_level_pressure', 'f'), ('repli...
16,991
5c8de81d285c587c0ad122775ce04df9aa56e830
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, struct import sys import traceback import json import time reload(sys) sys.setdefaultencoding('utf-8') """ ESBoost%d%s: %d msg_len msg """ ip = '192.168.86.39' port = 12711 client_socket = None def init(): global client_socket client_soc...
16,992
20505cc64a6684cb4f92364c27961ba54cf427ef
def addition(num1 , num2): ''' adding two numbers''' sum = num1 + num2 return(sum) addition(5 , 6)
16,993
52edd7acd863094c3553e5cbbdc16b474110ff5c
#!/usr/bin/env python import re, os path = r"." main_dir = os.listdir(path) log = open("log.txt", "w") file_types = ['*.xlsx', '*.xls', '*.xlsm', '*.docx', '*.doc', '*.msg', '*.xlsb', '*.pdf', '*.zip'] file_type_sans_dot = [f.strip('*.') for f in file_types] # print(file_type_sans_dot) def search(): # ugly...
16,994
40443c8f391def9da3385888875991f2e2a063be
import os basedir=os.path.abspath(os.path.dirname(__file__)) class Config(object): ADMIN='si' DEBUG=True SQLALCHEMY_DATABASE_URI="" class DevConfig(Config): SQLALCHEMY_DATABASE_URI='sqlite:///' + os.path.join(basedir, 'data.db') HEADERS={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64...
16,995
7458226d5885a4bb30fb9e5685160a0762baf4b0
import logging.config import os from time import sleep log_path = './logs' if not os.path.exists(log_path): os.makedirs(log_path) CONF_LOG = "./log_conf" logging.config.fileConfig(CONF_LOG); # ้‡‡็”จ้…็ฝฎๆ–‡ไปถ # print(logging.config.fileConfig(CONF_LOG)) logger = logging.getLogger('applog') if __name__ == '__main__': ...
16,996
02e29c34b8c1b4bc720cf100e1aaf134b52d25c3
def avg(grades): ''' Returns an average of a list. Raises an AssertionError if it is given an empty list for grades ''' assert not len(grades) == 0, 'no grades data' return sum(grades) / len(grades) print(avg([5, 6, 7])) print(avg([]))
16,997
e42bcfcdce170df86ca342c13a4d50c9482ac350
import os from flask import Flask from flask_restful import Api from flask_jwt import JWT from security import authenticate, identity from werkzeug.contrib.fixers import ProxyFix from resources.user import UserRegister from resources.item import Item, ItemList from datetime import timedelta from resources.store import...
16,998
944d433d4da9a755a7ac4b5e98bb5f9e86390512
import numpy as np import tensorflow as tf from sklearn.preprocessing import OneHotEncoder mnist = tf.keras.datasets.mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = np.reshape(X_train, (X_train.shape[0], -1)) X_test = np.reshape(X_test, (X_test.shape[0], -1)) y_train = y_train.reshape(len(y...
16,999
6308c0f567c5e4996f803c2ed23b54da4ae79601
import random import sys def game(name, ch): u_score = 0 c_score = 0 chances = int(input("\nEnter the number of chances: ")) while chances>0: user = input(f"\n{name}, Enter your choice: ") comp = random.choice(ch) if user in ch: print(f"Computer has selected {comp}"...