index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
985,000
5c846b3f0ce0d4e019f29302d6ed1f5f4d320c74
#!/usr/bin/python # -*- coding: utf8 -*- # ################################################################################ # ## Redistributions of source code must retain the above copyright notice # ## DATE: 2011-11-27 # ## AUTHOR: SecPoint ApS # ## MAIL: info@secpoint.com # ## SITE: http://www.secpoint.com ...
985,001
37a3f098a300346b80592cdca43d0cca0b80faf7
# # CS1010FC --- Programming Methodology # import random import copy from numpy.ma import absolute import constants class Logic: """ Has the "logic" of the grid It can move/merge the grid (when user/AI wants to go in a sertain direction this class will perform the movement of the data/matrix/grid...
985,002
50cbfdc495fb477dc4ae7ea8610eba7ca4caa1b6
import time import torch import torch.multiprocessing as mp import numpy as np import os from A3C_Cnt.model import A3C_MLP, A3C_CONV from A3C_Cnt.env import create_env from A3C_Cnt.test import test from A3C_Cnt.train import train from A3C_Cnt.shared_optim import SharedRMSprop, SharedAdam os.environ["OMP_NUM_THREADS"]...
985,003
c5e4ded89f63031ad130eaa53e2977745f0f3d08
from Tkinter import * import tkFileDialog import tkMessageBox import os import string import time import datetime import csv import numpy import calendar from scipy import stats from scipy import optimize from scipy import linspace import math import pylab as P from matplotlib.backends.backend_pdf import PdfPages impo...
985,004
d38bb9dc2d06e9153e0c08d14c394a5ac0f37b73
import sys import io from argument_engine.nd_lookups import * class NaturalDeduction: # checked-x:2020-Nov-10 def __init__(self, premise_in_a_list, conclusion_is_a_formula): self.premise = premise_in_a_list \ if any(isinstance(item, Formula) for item in premise_in_a_list) \ el...
985,005
b31bd82c9301386b2d4a2045736363e0e42c3996
import numpy as np import pandas as pd import matplotlib.pyplot as plt from non_ai.generic_functions import * import math class Markowitz: def __init__(self): self.codes_df = pd.DataFrame() # Train DataFrame self.codes = [] # Portfolio Asset...
985,006
4273c00a4980cb0e0e99fde86bcad4fdf3b725f1
# -*- coding: utf-8 -*- # @Time : 2019/5/21,021 9:31 # @Author : 徐缘 # @FileName: v1.7ceshi.py # @Software: PyCharm """ 大会战 采集部分 从dahuizhan.xlsx上次记录至昨日。 三部分: 1、SQM 2、ELK 3、普天拨测 打包命令: pyinstaller -F -i img\dahuizhan.ico web\llz_indicators\dahuizhan\dahuizhan.py """ import web.webCrawler.webcrawler as ww i...
985,007
5d90faf6105bdc39eb0eb5d7633c7380467a3024
import random import numpy as np from FactoredStruct import FactoredStruct from FactoredMDP import FactoredMDP class SmallTaxiDomain( FactoredMDP ): def __init__( self ): super().__init__( 4, 2, [3, 3, 5, 3, 6] ) # create reward structure scope = np.array( [0, 1, 2, 4] ) params = np.zeros( self.nelements(...
985,008
af7cf741e2570641dc7d6affda7d164609d0b883
""" Majority Element: An element that occurs in the array more than n/2 times. For size 5 -> 3, 6 -> 4 """ import math """Solution: """ def majority_element(a) -> int: n = len(a) for i in range(n): curr_count = 1 for j in range(i+1, n): if a[i] == a[j]: curr_count...
985,009
09dec98baeb079f36955e8c1904981d3c4e2aa69
""" An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from a to b, including a and b. Find the minimum size of a set S such that for every integer interval A in intervals, the intersection of S with A has size at least 2. Example 1: Input: intervals = [[1, 3], [1, 4], [2, 5], [3, 5]...
985,010
d9d08ddfe894124de1d93062f65fc890504b5dda
cantidad=float(input("Introduce la cantidad a invertir: ")) interes=float(input("Introduzca el interes anual: ")) anos=int(input("Introduzca la cantidad de años: ")) for i in range(anos): cantidad *= 1 + interes / 100 print("Capital tras " + str(i+1) + " años: " + str(round(cantidad, 2)))
985,011
e30035c6deb06684917f282c00a0004a1c39c1f5
coins = [1, 2, 5, 10, 20, 50, 100, 200] def solution(n): table = [[]] * (n + 1) for i in range(n + 1): table[i] = [[]] * (len(coins)) table[i][0] = 1 for i in range(n + 1): for j in range(1, len(coins)): table[i][j] = table[i][j - 1] if coins[j] <= i: ...
985,012
5a29c9fde4b8b4069c072a386cf839c41288b51e
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 27 22:08:41 2019 @author: YuxuanLong """ import numpy as np """ # feature engineering # data filtering and selection """ def cal_mask(mask_999, index): """ Generate mask for croping the redundant feature (-999s) """ mask = np.all(m...
985,013
4832b385e64223c548dd6b97513d128e74bbba6d
#!/usr/bin/env python # -*-encoding:UTF-8-*- # 通用视图类 # 简单的通用视图类 from django.http import HttpResponse from django.views.generic import View class MyView(View): def get(self,request,*args,**kwargs): return HttpResponse('Hello World!') # 可以向模板中传递变量值的通用类 from django.views.generic.base import TemplateView c...
985,014
d5fa986f1edf2a9d316d9f2fd2e83afa0b5a39aa
import re """Find a string where there is space character \b around the word, beginning with 7,8 or 9 followed by 9 digits""" test_str = 'call me at 7234597890 or 5780948489 ' regex_pattern = re.compile(r'\b[^789]\d+\b') reg_result = regex_pattern.search(test_str) print(reg_result.group() if reg_result else "No matc...
985,015
b5b40f395bdacc640088008402bd8c1a3cc1cb26
from functools import lru_cache def permutations(xs): if len(xs) == 1: return [xs] return [ [xs[i]] + p for i in range(len(xs)) for p in permutations(xs[:i]+xs[i+1:]) ]
985,016
2eee2569c8f6eabe767e84807d3b76a0dda97051
import os import random from termcolor import colored, cprint from colors import * score = 0 lines = 29 columns = 29 grid = [] for row in range(lines): grid.append([]) for col in range(columns): if ((row == 0) or (col == 0) or (row == lines - 1) or (col == columns - 1)): ...
985,017
5d904d3bc4b1c97c5d5b6333df76488d7f8dec6d
import parameters from ortools.constraint_solver import pywrapcp import sys class Solver: solver = None decision_builder = None data = None # -- VARS x_var = dict() # employee -> dict(): shift -> variable we_var = dict() # employee -> dict(): int representing week -> variable all_v...
985,018
13a0cb67134be6c04d8f4e612e5ecaa6ec8d7680
# -*- coding: utf-8 -*- """ Created on Sun Apr 1 19:28:42 2018 @author: Administrator """ from selenium import webdriver import time import csv #Simulated browser login driver = webdriver.Chrome(executable_path='chromedriver.exe') driver.get("https://www.investing.com/search/?q=crude%20oil&tab=news") time.sleep(100...
985,019
5b42e61d05ea03a0f5902091bf8db31b710e85b8
# Generated by Django 3.0.2 on 2020-02-13 05:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('classes', '0001_initial'), ('management', '0001_initial'), ] operations = [ mig...
985,020
1ecab2532b0ef0acd8fb69fb192b0557b35050f5
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'TelaBuscarOs.ui' # # Created by: PyQt5 UI code generator 5.13.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QDesktopWidget class Ui_TelaBuscarOs(object):...
985,021
d047160b60e7827d27dc981cfd8f0f4fc15b7396
""" Helper script for checking status of interfaces This script contains re-usable functions for checking status of interfaces on SONiC. """ import logging from transceiver_utils import all_transceivers_detected def parse_intf_status(lines): """ @summary: Parse the output of command "show interface descripti...
985,022
df06c88b06bbad7b24c3a910ebb11f2a32b7247b
""" @Author : jiaojie @Time : 2020/4/5 22:40 @Desc : """ """ 元组 元组的定义:用()表示 元组是不可变类型的数据,定义了之后不能对里面的元素进行修改 元组的方法: count():用来计算指定元素的个数 index():查找指定元素的下标 元组可以下标取值和切片 注意点: 1.空元组定义:() 2.元组中只要一个元素:(xxx,)或者(xxx), 元组内部元素修改:特殊情况 元组内部有可变类型的元素的时候,内部的可变类型是可以修改 """ tu = () print(type(tu)) tu1 = (11, 22, 33, 'a', 'bb') ...
985,023
5d7e94b531308adb7477bbda0da19e29735f4233
from django.contrib import admin from .models import learn # Register your models here. admin.site.register(learn)
985,024
f4eb806c6c6e7e9ab624eed0963319a5ff33372c
""" https://www.hackerrank.com/challenges/time-conversion """ import sys time = input().strip() hourStr, minStr, secStr = time.split(":") if "AM" in time and hourStr == "12": hourStr = "00" elif "PM" in time and hourStr != "12": hourStr = str(int(hourStr) + 12) print(hourStr + ":" + minStr + ":" + secSt...
985,025
5c5fb172382cae82d6dac0966f8dda0eb6124c29
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-11-16 18:40 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sosokan', '0004_auto_20161116_1339'), ] operations = [ migrations.RemoveField( ...
985,026
6832eecc87150fa873d05c14e4165cb627eee9a7
from zmqlocker import LockerClient import time import argparse parser = argparse.ArgumentParser() parser.add_argument("--request", dest="request", action="store_true") parser.add_argument("--release", dest="release", action="store_true") parser.add_argument("--jobid", help="the id of the job requesting the GPU") args ...
985,027
4866cfd363278edb803f6c665198aaf7807d8822
# tests test_img = [ [225, 000, 000], [000, 225, 000], [000, 000, 225], [225, 225, 000], [225, 000, 000], [225, 000, 000], [225, 225, 225], [000, 225, 000], [000, 225, 000] ] fade_1 = [[45, 0, 0], [0, 45, 0], [0, 0, 45], [45, 45, 0], [225, 0, 0], [45, 0, 0], [45, 45, 45], [0, 45, 0], [0,...
985,028
06e2c380f4a670e2c1e8c382dfbaa7f7d0b0e314
import numpy as np from keras.models import load_model from keras.preprocessing import image model = load_model('model.h5') # summarize model model.summary() imagename = "56_100.jpg" test_image = image.load_img(imagename, target_size=(64, 64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(...
985,029
093e99bdf3ffc7267169181b66ded973181e11bd
import pytest import mock import connexion from src import launch @pytest.fixture(scope='module') def client(): flask_app = connexion.FlaskApp(__name__) with flask_app.app.test_client() as c: yield c @pytest.fixture() def user_role(): return 'collaborator' def test_get_health(client): # GIVE...
985,030
2b9497eac7018a44c650c45dafe15871a77a08a8
from rest_framework import serializers from .models import Urlspage class PageSerializer(serializers.ModelSerializer): class Meta: model = Urlspage fields = ('id', 'name', 'is_valid', 'created_at')
985,031
f3df0e48db12986528d15bdea5819930a7a59df0
version https://git-lfs.github.com/spec/v1 oid sha256:cbded24addb8cbc2b69e4ea3c7e7f9b4eecfcb21e6fc06008d8feb7f12e605a2 size 795
985,032
bd11e4163c3f429803566ada44576646f617531a
from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext as _ from easy_thumbnails.fields import ThumbnailerImageField class User(AbstractUser): """Inheriting User model with unique EmailField.""" email = models.EmailField(unique=True, erro...
985,033
6d1aab734995bd692e531a9f21eab70f30a04c81
import requests import io import zipfile import pandas as pd import numpy as np import matplotlib.pyplot as plt def getAndExtractZip(url): # yields (filename, file-like object) pairs response = requests.get(url) with zipfile.ZipFile(io.BytesIO(response.content)) as thezip: for zipinfo in thezip.in...
985,034
19b37f932ff3670edbe331386f944b155a151b77
print "MAIL MODULE INIT" from folderTree import * from mailList import * from mailMessage import * from imapSettings import * from smtpSettings import *
985,035
52aa3f03fc4537114b7fcb82da443964bb3d0f6e
import time #Ex.1 # def action_decorator(func): # def inner(value): # print(func.__name__, 'is canceled!') # return inner #Ex.2 # def action_decorator(func): # def inner(value): # start = time.time() # func(value) # print(time.time() - start, ' sec - exec time'...
985,036
17a530854d9cf2f05d8222f9661e6156f1361f05
#!/usr/bin/env python # DickServ IRC Bot - Developed by acidvegas in Python (https://acid.vegas/dickserv) # wolfram.py from xml.etree import ElementTree as etree import config import httplib def ask(query): params = httplib.data_encode({'input':query, 'appid':config.api.wolfram_api_key}) data = httplib.get_sou...
985,037
42604182a263d62f4781c1e1368bb931cdf097ce
import pytest from scripts.generate_pipeline import get_diff # # function get_diff tests # @pytest.mark.parametrize( "file_contents,expected_result", [ ( """test.py folder_a/test.tf folder_a/folder_b/test.txt""", ["test.py", "folder_a/test.tf", "folder_a/folde...
985,038
194d5df9f64c3dc402a5dae7a78599d284182f29
import sys from graphviz import Digraph def plot(genotype, filename): g = Digraph( format="pdf", edge_attr=dict(fontsize="20", fontname="times"), node_attr=dict( style="filled", shape="rect", align="center", fontsize="20", height...
985,039
fdafa9a79f72fbea0ab2722d1b2c6b3e52ffa397
# -*- coding: utf-8 -*- print("Hello World!") result = 1+ 2 result = 1+3 print(result) for i in range(2,20,5): print(i,end="-") list1 = [1,2,3,4] for item in list1: print(item) tuple1 = (12,"String",13.6,"String2") tuple2 = (30,50,9) print(tuple1) print(tuple1[0]) tuple3 = tupl...
985,040
c68897ffeb7c6e13968c4f654e20b88845892b15
from starcluster.clustersetup import ClusterSetup from starcluster.logger import log class ModuleInstaller(ClusterSetup): def run(self, nodes, master, user, user_shell, volumes): for node in nodes: log.info("Installing and setting up modules support on %s " % (node.alias)) node.ssh.execute('wget -c -P Downloa...
985,041
f66ebec494e6da5515ab563f6cd51b5c7007b9c4
""" Unpacking a Sequence into Separate Variables """ p = (4, 5) x, y = p print(x) print(y) print() data = ['acme', 50, 91.1, (2012, 12, 21)] name, shares, price, date = data print(name) print(date) name, shares, price, (year, mon, day) = data print(name) print(year) print(mon) print(day) print() # Unpacking works wit...
985,042
23c4c6893ecb4709821a3aab7d21da0d0ba0be37
# -*- coding: utf-8 -*- from django import forms class DocumentForm(forms.Form): fileLink = forms.FileField( label='Select a file' ) company = forms.CharField(widget=forms.HiddenInput()) class EditDocumentForm(forms.Form): op_file = forms.FileField( label='Select a file', req...
985,043
d6b7d7b1e72d7e58f52259bb1464173e41250fb9
import os import shutil try: import subprocess32 as subprocess except Exception: import subprocess import requests import requests.exceptions from pandaharvester.harvestercore.plugin_base import PluginBase from pandaharvester.harvestercore import core_utils from pandaharvester.harvestermover import mover_util...
985,044
97b0b66d52631c0e13a41934bb725bc4de873db7
import random, time from pyglet.window.key import MOTION_UP, MOTION_DOWN, MOTION_LEFT, MOTION_RIGHT from env.snake_env import SnakeEnv def interact(): """ Human interaction with the environment """ env = SnakeEnv() done = False r = 0 action = random.randrange(4) delay_time = 0.2 ...
985,045
1ad2b5e7333655a418c4fe91104aa57a3a1064e3
import numpy as np class Team: def __init__(self, name='', elo_home=1500, elo_away=1500, gp=0, gc=0, points=0, matches=0, wins=0, losses=0): self.name = name #home elo self.elo_home = np.array([], dtype=int) self.elo_home= np.hstack((self.elo_home,elo_home)) #away elo ...
985,046
a6c374edebbce625e66e427584ea73cb03a7ccdd
n=input("請輸入正整數:") prime=[2] for i in range(3,int(n)+1): test=True for j in range(len(prime)): if i%prime[j]==0: test=False break if (prime[j]**2)>i: break if test: prime.append(i) list1=[] for i in range(len(n)): for j in range(i,len(n)): ...
985,047
ee803fab7a7fffff4b690f78b73f558b3e65dff4
badIngredients = ["Octinoxate", "Oxybenzone", "Benzophenone-3", "Avobenzone", "benzophenone", "Cylcopentasiloxane", "Cyclomethicone", "Formaldehyde", "Diazolidinyl", "urea", "DMDM", "Hydantoin", "Hydroxymethylglycinate", "Methylisothiazolinone", "Octyl", "methoxy...
985,048
01eafef3d84c2bd6ed2ebe7dba86846ab55d3a4f
import sys, os, platform from src.pnc import Environment from src.imaging_derivs import DataVector from src.plotting import roi_to_vtx from src.utils import get_states_from_brain_map import numpy as np # %% plotting import seaborn as sns import matplotlib.pyplot as plt from nilearn import plotting from src.plotting im...
985,049
58b2d9a2467bc40b3f7738a1ea9829fb65b350e4
import csv import random from collections import defaultdict def load_data(filename): quotes = [] with open(filename, 'rb') as f: reader = csv.reader(f, delimiter= ';') for line in reader: parsedQuote = line[0].split(' ') author = line[1] quotes.append([par...
985,050
e4a198d0482bbc029aa293e83885f7cf752e0928
#Heres that one we looked at in Python Tutor. houses = ["Eric's house", "Kenny's house", "Kyle's house", "Stan's house"] # Each function call represents an elf doing his work def deliver_presents_recursively(houses): # Worker elf doing his work if len(houses) == 1: house = houses[0] print("D...
985,051
1c440e92369afff3bf0bf45df7bb9918322b3ab0
# -*- encoding: utf-8 -*- import redis import falcon from .exception import NotRedisException class MiddleWare(object): def __init__(self, conn): self.conn = conn def process_resource(self, req, resp, resource, params): path = req.path content = req.stream.read() key = '{}:{}'...
985,052
144081281bd53e7bb5d9655a02a174fa68fddb3b
# coding: utf-8 import csv fichier1 = "concordia1.csv" f1 = open(fichier1) devoir = csv.reader(f1) # Nombre de caractères dans les titres longTitre = len(devoir[2]) print(longTitre) # Maîtrise ou doctorat for these in devoir: if "M." in devoir[6]: these = "maîtrise" else: these = "doctorat" print(these)
985,053
bfd7ae4cdb24b37daab99bf9f56d9b5e9c2b13d3
#! /usr/bin/env python from MDAnalysis import * from math import * import argparse import numpy as np from scipy.interpolate import griddata import matplotlib.pyplot as plt from scipy import interpolate import matplotlib.pyplot as plt parser = argparse.ArgumentParser(description="Make triangle") parser.add_argument(...
985,054
4b1f7de3ef80cbedc2bfa249e1e708ceba6d39de
# -*- coding: utf-8 -*- """ Created on Mon Mar 9 12:26:49 2020 @author: Mr.Vakili """ import numpy as np import cv2 file=cv2.VideoCapture('hw.avi') while True: #start getting frames _,frame = file.read() frame_gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) frame_blur=cv2.GaussianBlur(f...
985,055
d0b211f544e5c79f4d96045189e50af86e1bb27b
from django.db import models from django.conf import settings from django_extensions.db.models import TimeStampedModel from .constants import ContactType class PhoneBook(TimeStampedModel): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_le...
985,056
da8629b5d1de7b4297b1417924cd1015c5d2da2b
import os import numpy as np import torch from torch import Tensor from torch.autograd import Variable def logit(x): eps = 1e-6 x = x.clamp(eps, 1. - eps) p = torch.reciprocal(x) - 1. return -torch.log(p) def logit_logit_gate(s, g): """ :param s: :param g: :return: logit(sigmoid(m) ...
985,057
6f4f61dceea274151e64fc511b935abe11226b70
import functions # Input Data Person1 = [['9:00', '10:30'], ['12:00', '13:00'], ['16:00', '18:00']] Person1_Avail = [['9:00', '20:00']] Person2 = [['10:00', '11:30'], ['12:30', '14:30'], ['14:30', '15:00'], ['16:00', '17:00']] Person2_Avail = [['10:00', '18:30']] Duration = 30 def Arrange_Meeting(Person1, Person1_...
985,058
c78de733bce2dd3aed949e5396b68f0a0fd75601
''' PROBLEM STATEMENT as taken from the following Hacker Rank link https://www.hackerrank.com/challenges/birthday-cake-candles/problem You are in-charge of the cake for your niece's birthday and have decided the cake will have one candle for each year of her total age. When she blows out the candles, she’ll only be a...
985,059
606611a0448348e41cb5a7689d3246e268550e6e
from django.contrib.auth.decorators import user_passes_test def check_user(user): return not user.is_authenticated user_logout_required=user_passes_test(check_user, '/', None) def auth_user_should_not_access(viewfunc): return user_logout_required(viewfunc)
985,060
d85e198580ce9d97e08de86a8422cf1918c5c360
import random import score #define deck class Deck(): def __init__(self): self.card_list=list() def deck_generator(self): suits=['Heart', 'Diamond', 'Club', 'Spade'] cards=['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'K', 'Q', 'J', 'Ace'] for suit in suits: f...
985,061
f80f994f50b51f896f998f56fdc05a5db98fbe74
"""Create Database for IMF-data. Update Database with IMF-data ==================================================================== create_db - creates sqlite3 database file (param name - path to new db-file); it reads needed indicators list from csv-file (param 'indi_file' - path to file, file must hav...
985,062
c5fc4c91096c124aa3d9efe70a7e2e0e168e4632
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import imp import os import unittest __version__ = '1.2.0' __version_info__ = (1, 2, 0) def _import_from(mod, path, mod_dir=None): """ Imports a module from a specific path :param mod: A unicode ...
985,063
8d52ec3a77ac63b6ef6bd2d857105227b7d05f22
# # # def pic_speed(v): return (77385000.0/2)/(16*(v+1)) def ax12_speed(v): return 2000000.0/(v+1) if __name__ == "__main__": pairs = [] # generate all pairs for pv in range(0,256): for av in range(0,256): p_speed = pic_speed(pv) a_speed = ax12_speed(av) ...
985,064
01be98d443879a307589b0d0f931c08ed1ae63c0
#! /usr/bin/env python # coding:utf-8 print "How old are you ?" age = raw_input() print " You are %r years old." %(age)
985,065
8a3c4b34098c75fc8176e9b8672d1b89eaf29dfa
import os import configuration class remove_user(): def __init__(self, user): self.user = user def remove(self): os.system("sudo userdel %s" % self.user) print "deleted user" os.system("sudo rm -r /home/%s" % self.user) print "Deleted home dir" os.system("sudo groupdel %s-group" % self.user) print "D...
985,066
d28fb28a41a9bc8292c60e513b50de465f28e009
#!/usr/bin/env python import datetime import errno import logging import os import pwd import random import signal import subprocess import sys import time from time import sleep from scapy.all import sr1, TCP, IP, Raw, hexdump, sr, send, conf, L3RawSocket, rdpcap, Scapy_Exception from scapy_http.http import HTTPRes...
985,067
2cf6048c242014cb4c6c2c8fbc2aa124b398f29f
from imports import * class FF(torch.nn.Module): def __init__(self, in_flat_dim, up1, out_dim, h1, h2): super(FF, self).__init__() self.flat_dim = up1 * up1 * in_flat_dim self.up0 = torch.nn.UpsamplingBilinear2d(scale_factor=up1) self.linear1 = torch.nn.Linear(up1 * up1 * in_flat_di...
985,068
bc0a9e3fb61c8524af76cf0d2d68ca6a584b8699
n,k=map(int,input().split()) a=list(map(int,input().split())) p=0 for i in range(len(a)): if(a[i]%k==0 and a[i]//k > p): p=a[i]//kint else: print() print(p)
985,069
dbf86a19457331afd8ae2ee8333fac03bd2d5607
# -*- coding: utf-8 -*- # Copyright 2018-2019 Mateusz Klos # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
985,070
0c4336f2d93b5ead9a30e34aa4e57e0bb942c073
#!/usr/bin/python # encoding: UTF-8 import json import string import time import urllib2 import MySQLdb from codepkg import mod_config BASE_URL = "http://lvyou.baidu.com/destination/ajax/jingdian?format=ajax&surl=" def getSpotsCount(url): req = urllib2.Request(url) #print req res_data = urllib2.urlopen...
985,071
1c0d417138b0302b21254a9531f812534d15524e
from setuptools import setup ''' # local install python setup.py install # local developer install python setup.py develop #registering on PyPI python setup.py register #create a source distribution python setup.py sdist # upload the source distribution tp PyPI python setup.py sdist upload ''' setup(name='...
985,072
d7be7b9bab25cdd59f55017a5913662cb544ed33
class Dog(): #Class object attributes species = 'Mammal' def __init__(self, breed, name, spots): self.breed = breed self.name = name self.spots = spots my_dog = Dog(breed="poodle", name = "FEFE", spots = True) print(f"My dog is named {my_dog.name}. He is a {my_dog.breed}. Does he...
985,073
340123ad88a39dc75e63a6f35b2cba44229ad000
# -*- coding: utf-8 -*- # This file is part of ScapeList. # # ScapeList is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ScapeList ...
985,074
c33fa33fe9cc2a86578dc1b5445ab5b9eb2e6ed2
# Solution to https://leetcode.com/problems/reverse-integer/ class Solution: def reverse(self, x: int) -> int: if x < 0: result = int(str(x)[:0:-1]) * -1 else: result = int(str(x)[::-1]) if result < pow(-2, 31) or result > pow(2, 31) - 1: return 0 ...
985,075
5e8a7e0d00f39389610ee065f431dac5ff76cd2c
from typing import List, Tuple def knight_tours(board: List[List[int]], curr: Tuple[int, int], count: int) -> -1: """ Currently this only solves a knight tour for a specific starting point. """ if count == len(board) ** 2: return deltas = [ (2, 1), (1, 2), (-2, 1),...
985,076
35ba9114068783d2b2d17c74abbf712eee042729
import time import datetime import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, date2num import numpy as np import subprocess as sp import time import sys import os from itertools import groupby fdate = sp.check_output(['date','--date','-1 days','+%Y%m%d'...
985,077
1bfb66081bed58b309e3a581b34f403d9f68548c
from jpath4.query import data as d def jpath_to_json(value, strict=False): """ Converts the specified JPath data into Python objects/lists/numbers/etc representing the data. The resulting data is suitable for passing into Python's json.dumps. If strict is true, object keys are required to be ...
985,078
3672e0e2ceaf06262312259b7e314f3ad0c352b1
from sampleapp.worker import name as webjob_name import os import sys import shutil if __name__ == "__main__": try: wwwroot = os.environ['WEBROOT_PATH'] src_path = os.path.join(wwwroot, 'sampleapp', 'worker', 'run.py') dest_dir = os.path.join(wwwroot, 'App_Data', 'jobs', 'continuous', webjo...
985,079
6f5e5e001f6c214647fb5fe5ac948b6d3b461716
#!/usr/bin/python import random import sys import getopt from math import sqrt import math nauticalMilePerLat = 60.00721 nauticalMilePerLongitude = 60.10793 rad = math.pi / 180.0 milesPerNauticalMile = 1.15078 def read_coords(coord_file): ''' read the coordinates from file and return the distance matrix. ...
985,080
bf812b6f75924afeb32e3c7bf0889b56c511e980
# İnheritance (KALITIM) : Miras alma # Person => name,lastname,age ,eat(),run(),drink() #Student(Person),Teacher(Person) # Animal=> Dog(Animal),Cat(Animal) class Person(): def __init__(self,fname,lname): self.firstname=fname self.lastname=lname print("Person created") def whoA...
985,081
86190a87fd7f4a3e8e0ed1ccf7624071a7a67b58
from compound.o.oH import * db_gases = ["H2", "He", "N2", "O2", "O3", "F2", "Cl2", "Ne", "Ar", "Kr", "Xe", "Og", "NH3", "SiH4", "CO", "CO2", "N2O", "NO", "NO2", "SO2", "H2S", "CH2=C=CH2", "CH2=CH-CH=CH2"] def is_gase(comp: 'Compound'): if comp.formula.value in db_gases: return True elif comp.comp_typ...
985,082
3c755049117467bf4b5343a98eb5b9da14678081
class Solution(object): def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ if len(s) < 4 or len(s) > 12: return [] ans = [] temp = [] temp.append(s[:1]) recur_IP(ans, temp, s[1:], 0) temp.pop() ...
985,083
3e6396c39e72afa92778a17ad12edc4079583116
import collections import systems import scales import sformat SECTIONS_ORDER = ["front", "center", "rear"] SYSTEMS_ORDER = ["1","2","3","4","5","6","core"] SECTION_SCOPE_ALIASES = { "front": { "dr": "front_dr" }, "center": { "dr": "center_dr" }, "rear": { "dr": "rear_dr" }} def add_values_d...
985,084
e43142cffad32a73234044a8aabb2de09e34492d
from ConfigParser import SafeConfigParser class abstract_parser: def retrieve_parser(self, filename): parser = SafeConfigParser() parser.read(filename) return parser def parse(self, filename): raise NotImplementedError
985,085
7b52f7025b0c82a73f6b53d81115e74edfcb024d
import pyfirmata, os, time, threading, os.path, sys from roasts.models import Roast, RoastSnapshot THERMO_ENV_DATA = 0x0A THERMO_BEAN_DATA = 0x0B def debug(str): print str class Roaster: """ RoasterBoard is an Arduino firmata client communicating with the hardware roaster itself. """ def __init_...
985,086
a72fec2c015d4054780e66e38184f6b304f36a98
import numpy as np import DtoF as DF import JONSWAP as J import OmegaTheta as OT import rieneckerfenton as RF def create_gauss(kx,ky,**kwargs): return 0 def create_jonswap(kx,ky,**kwargs): #-- The Jonswap Parameters Param = kwargs.get('Param',None) Nx = len(kx) Ny = len(ky) omega, theta = ...
985,087
d08eec0cbf25f868fa04841bf489d28f27af42d4
#!/usr/bin/env python3 def fibs(maxnumber): fib1, fib2 = 1, 2 while fib1 < maxnumber: yield fib1 fib1, fib2 = fib2, fib1 + fib2 print(sum(f for f in fibs(4000000) if f % 2 == 0))
985,088
d512aba7e621a30f8ba7eb5e46f0952ab67c3c61
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split np.random.seed(0) n = 15 x = np.linspace(0,10,n) + np.random.randn(n)/5 y = np.sin(x)+x/6 + np.random.randn(n)/10 X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0) # You can use this funct...
985,089
54725795ec472d357ccaf1372592f6de339b100d
#!/usr/bin/env python3 import xmlrpc.client import ssl import os import sys import gettext DEBUG=True class UMount: def __init__(self): context=ssl._create_unverified_context() self.client=xmlrpc.client.ServerProxy("https://localhost:9779",allow_none=True,context=context) self.user=os.environ["USER"] ...
985,090
28cdfe398d791ea3ff28cf70ff7fd4f815457e8c
cube=[value**3 for value in range(1,11)] print(cube) for value in cube: print(value)
985,091
8efa6e07e52d7743d05b83be79a6bde554a884e8
import fastapi import pytest import pytest_check as check import requests requests.Response.json() router = fastapi.APIRouter( prefix="/nodes", tags=["nodes"] ) def test_query_nodes(client): resp = client.get("/nodes/") check.is_true(200 <= resp.status_code < 300) res = resp.json() check.is_...
985,092
46b1476607bc1a4fc026874738a754bc538212dc
"""Pipeline functions for channel invitations""" from django.db import transaction from channels.api import get_admin_api from channels.models import ChannelInvitation def resolve_outstanding_channel_invites( strategy, backend, *args, user=None, is_new=False, **kwargs ): # pylint: disable=unused-argument ""...
985,093
a421f790ffc4376e8bb1e2cd58c4488bbe770f53
''' 2 types 1. Returning a fucntion from a fucntion. But the retured fuction is somewhere else or a different fun no part of the current 2. When the returing function is a innner function of the function we called. This hlep to develop a concept called lazy initialization ''' @track def square(x): return x*x d...
985,094
9a24c8253a38ae57647f4b29a0870ab209349714
import torch import numpy as np from models.modules.loss import GANLoss,FilterLoss from skimage.color import rgb2hsv,hsv2rgb from scipy.signal import convolve2d import time from scipy.ndimage.morphology import binary_opening from sklearn.feature_extraction.image import extract_patches_2d from utils.util import Indexing...
985,095
ceaaa7b40c44f8e02989e326cd016013226ab725
from django.urls import path from .import views urlpatterns = [ path('forum/', views.lista_topicos, name ='topicos'), path('forum/new', views.new_topico, name='new_topico'), path('forum/<int:pk>/', views.post, name='post'), path('forum/newpost', views.new_post, name = 'new_post'), path('forum/newcomen...
985,096
33c8c8d97ba02d03e98d3b8f524812346bc0fd89
#!/usr/bin/python # -*- coding: UTF-8 -*- from gentpl import operation_tpl operation_tpl.gen_tpl()
985,097
8ced086640afce35406d4dd86199241239c5230e
import logging from datetime import datetime, timedelta, timezone from sqlalchemy import Boolean, Column, DateTime, Integer, String, create_engine, desc from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool from .text_utils import date_str...
985,098
6037ea78400fc50d81dd711c70247da0912182b1
import requests from bs4 import BeautifulSoup from selenium import webdriver def start(): #browser = webdriver.PhantomJS('phantomjs.exe') browser = webdriver.Chrome('chromedriver.exe') url = 'http://www.footballsquads.co.uk/ger/2017-2018/' tag = 'gerbun.htm' browser.get(url+tag) html ...
985,099
13a1ff81189a5333693f88b82d5dccda99296cf3
from __future__ import division, print_function import numpy as np import control.matlab as cm import control as cp import matplotlib.pyplot as plt from IPython.display import Image def control(s, Y, D): end = 10 G = 1/(3*s*(s + 1)) F = (3*s*(s + 1)) KP, KD, KI = 16, 7, 4 H_pd = (KP + KD * s) ...