text
stringlengths
38
1.54M
def str_float(x): import re x0=x x=re.findall(r"\d+\.?\d*",x) if len(x)==0: x=np.nan elif len(x)==1: x=float(x[0]) else: print('x should one number',x) return x0 return x def num_format(x,n=9,k=4,f='f'): """ n is the total width of the field...
import json import time import logging import pickle from tqdm import tqdm from utils.squad_utils import SQuADExampleExtended from allennlp.predictors.predictor import Predictor from allennlp.data.tokenizers.sentence_splitter import SpacySentenceSplitter from allennlp.data.tokenizers import WordTokenizer from allennl...
"""`dataloader.py` defines: * a customized dataset object for lattices * a function to create dataloaders for train, val, test """ import logging import numpy as np import os from torch.utils.data import Dataset, DataLoader import utils, lattice class LatticeDataset(Dataset): """ Lattice dataset object. ...
import subprocess import sys def get_interface(): cmd = ['nmcli', 'c'] output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0].decode() for line in output.split('\n'): vals = line.split() if len(vals) < 4: continue if 'ethernet' in line: re...
# A sample distutils script to show to build your own # extension module which extends pywintypes or pythoncom. # # Use 'python setup.py build' to build this extension. import os from distutils.core import setup, Extension from distutils.sysconfig import get_python_lib sources = ["win32_extension.cpp"] # Sp...
import csv train_csv_path = './data/celeba_20k/train.csv' test_csv_path = './data/celeba_20k/test.csv' with open(train_csv_path, newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print(', '.join(row))
"""Object Relational Model for merge-queue database.""" import enum import json import sqlalchemy from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import String fr...
#---------------------------------------- # @author : Amjad Yousef Majid # @date : Jan. 24, 2019 #---------------------------------------- # ## This script goes through files in a given directory (folder) and replace a # phrase with a new one. import re import shutil import glob import sys import os #TODO handle...
import os, fnmatch import sys import pyinotify class EventProcessor(pyinotify.ProcessEvent): _methods = ["IN_CREATE", "IN_DELETE", "IN_DELETE_SELF", "IN_MODIFY", "IN_MOVED_TO"] def process_generator(cls, method): def _method_name(self, event): ...
# Unittests For Function calculate_second_max # To Run : python -m unittest parsing_script_test.py import unittest import pandas as pd class verifyOutputFile(unittest.TestCase): df = pd.read_csv('output_data.csv') def test_column_names(self): df = pd.read_csv('output_data.csv') sel...
from django.shortcuts import render # Create your views here. def home(request): return render(request,'home.html') def history(request): return render(request, 'history.html') def five(request): return render(request, 'five.html') def six(request): return render(request, 'six.html') def seven(requ...
class Fifty_fifty: # OUTCOME TYPES LOST = 1 SUCCESS_TO_OPOSITION = 2 SUCCESS_TO_TEAM = 3 WON = 4
from menu import Menu from statistics_reader import read, retrieve_statistics class TacklesSacksMenu(Menu): data = read("data_files/Tackles.txt") def option_1(self): print(retrieve_statistics(self.data, 4, "tackles")) self.process_menu_selections() def option_2(self): print(retrie...
# coding: utf-8 import random import re from django.template import Library register = Library() class ProfanitiesFilter(object): """ Filtre de grossièretés """ # Overrides def __init__(self, filterlist, ignore_case=True, replacements="-", complete=True, inside_words=False): """ Initialiser le ...
import pika queue_name = 'priority-queue' max_priority = 10 def get_channel(): # connect and get channel parameters = pika.ConnectionParameters('localhost') connection = pika.BlockingConnection(parameters) channel = connection.channel() # declare queue with max priority channel.queue_declare...
# # @lc app=leetcode.cn id=142 lang=python3 # # [142] 环形链表 II # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # hash法,访问的节点val设置为最大值,当遇到值为最大值的节点时就是循环指针的入口节点 # 64ms 68% 5% 16.9MB def d...
import pygame import torch from pong_game_objects import * if __name__ == '__main__': input(""" Pong main game script: Use: - Run script and follow input prompts to setup windowsize and players. Current Options: Human, Perfect, NN ...
from typing import Optional import discord from discord.ext import commands import sources.ids as IDS import sources.text as T class MiniEntry: def __init__(self, userID: int, targetUserID: int, count: int): self.userID = userID self.targetUserID = targetUserID self.count = count class Co...
import asyncio import base64 import json import keyword import textwrap from chromewhip.protocol import input class Splash: def __init__(self, request, response=None): self.response = response self.request = request self._selector_queue = [] async def initialize(self): driver...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from selenium import selenium sel = selenium("localhost", 4444, "*firefox", "http://www.baidu.com/") sel.start() sel.open("/") sel.type("id=kw", "selenium grid") sel.click("id=su") sel.wait_for_page_to_load("30000") sel.stop() # (C:\Users\Han\Anaconda3) C:\Users\Han\...
import numpy as np from cv2 import cv2 import matplotlib.pyplot as plt erosion_size = 0 max_elem = 2 max_kernel_size = 21 title_trackbar_element_type = 'Element:\n 0: Rect \n 1: Cross \n 2: Ellipse' title_trackbar_kernel_size = 'Kernel size:\n 2n +1' title_erosion_window = 'Erosion Demo' title_dilatation_window = 'Dil...
#-----Header-----# #This file finds the data points used in figure c1,c2 and c3 of Holstein et al. #The data points are found from calibration measurements, half of which use the calibration polarizer. #--/--Header--/--# #-----Imports-----# import numpy as np import matplotlib.pyplot as plt import astropy.i...
#!/usr/bin/python with open('./exp1.dat', 'r') as f: begin = 0 for line in f.readlines(): begin = begin + 1; channel = [] if begin > 14 :#valid data is after line 14 #electrode 0 is reference channel.append([float(line.split()[1]) - float(line.split()[0]), float(line.split()[2]) - float(line.split()[...
import requests import sys import cv2 import pydicom import pyodbc import numpy as np host = 'http://182.156.200.179:8042' link = 'http://182.156.200.179:8042/patients' f = requests.get(link) all_patient_id_index = f.json() # print(all_patient_id_index) patientNameOrID = input("Enter Patient Name or Id t...
#!/usr/bin/python import rospy from cs1567p1.srv import * from std_srvs.srv import * LEFT = 0 RIGHT = 1 UP = 2 DOWN = 3 CLOSED = 0 OPEN = 1 UNKNOWN = 2 class Cell(object): def __init__(self, left=UNKNOWN, right=UNKNOWN, up=UNKNOWN, down=UNKNOWN): self.walls = [left, right, up, down] def get_open_w...
class Solution: # @param {string} s # @return {integer} def titleToNumber(self, s): result = 0 base = ord('A') - 1 for c in s: result = result * 26 + ord(c)- base return result so = Solution() print so.titleToNumber('AA')
#!/bin/python3 import sys n,k = input().strip().split(' ') n,k = [int(n),int(k)] c = [int(c_temp) for c_temp in input().strip().split(' ')] Energy = 100 start = k start %= n while(start != 0): # print (start) if (c[start] == 1): Energy -= 2 Energy -= 1 start += k start %= n if (c[start] == 1): Energ...
import torch from models import SurfaceMapModel from models import InterMapModel from utils import show_mesh SURFACE_PATH_Q = '/SET/HERE/YOUR/PATH' SURFACE_PATH_F = '/SET/HERE/YOUR/PATH' SURFACE_PATH_G = '/SET/HERE/YOUR/PATH' CHECKPOINT_PATH = '/SET/HERE/YOUR/PATH' landmarks_g = [] landmarks_f = [] de...
import json import argparse from data_helpers.data_preprocessor import preprocess if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( '-c', '--config', default="./config/data_preprocessor_config.json", type=str, help='Data preprocessor config file path.' ) ...
# Generated by Django 3.2.5 on 2021-08-04 19:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('jobapp', '0023_remove_applicant_image'), ] operations = [ migrations.RemoveField( model_name='job', name='header_image', ...
import sys import pandas as pd from sqlalchemy import create_engine def transform_categories(categories_df): """ Makes transformations in the categories data. Arguments: categories_df: the categories dataframe Output: categories_df_trans: the transformed categories dataframe ""...
from bs4 import BeautifulSoup import requests import re import urllib import os import argparse import sys import json try: # For Python 3.0 and later from urllib.request import urlopen except ImportError: # Fall back to Python 2's urllib2 from urllib2 import urlopen # adapted from http://stackoverflo...
import smtplib from email.mime.text import MIMEText from utils import printerr def send_email_properly(contents, to_addr, from_addr, host, username, password): msg = MIMEText(contents, "plain") msg['Subject'] = "Dupin notification" msg['From'] = from_addr msg['To'] = to_addr s = smtplib.SMTP(hos...
import random #### # Each team's file must define four tokens: # team_name: a string # strategy_name: a string # strategy_description: a string # move: A function that returns 'c' or 'b' #### team_name = 'Exposed' # Only 10 chars displayed. strategy_name = 'If neccessary' strategy_descriptio...
import string import csv from we_module.we import We we = We(True) import re import pandas import datetime import time import numpy import os # analyzign a log file to produce only the errors from contracts sf comms, and filtering out the retries mylog = open('file.txt', 'r') unique_exceptions = [] all_exceptions = [...
# _*_ coding:UTF8 _*_ import socket port=8081 s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #从指定的端口,从任何发送者,接收UDP数据 s.bind(('',port)) print('正在等待接入...') while True: #接收一个数据 data,addr=s.recvfrom(1024) print 'Received:',data,'from',addr
from __future__ import unicode_literals from django.apps import AppConfig class UvsConfig(AppConfig): name = 'uvs'
import json from urllib.parse import urlencode from tornado.httpclient import AsyncHTTPClient from timesheet.dispatches.insert_log import insert_log from timesheet.integrations.zoho_projects.integration import ZohoProjectsIntegration from timesheet.integrations.zoho_projects.utils import BASE_URL from timesheet.utils...
from .workflow_factory import workflow_factory import noodles from math import log, floor from noodles.tutorial import add @noodles.schedule def mul(a, b): return a * b @noodles.schedule def factorial(n): if n == 0: return 1 else: return mul(n, factorial(n - 1)) @noodles.schedule def f...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Version.net_end' db.alter_column(u'windberg_register_version', 'net_end', self.gf('django...
# Generated by Django 3.2.4 on 2021-06-10 19:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogs', '0006_alter_post_category'), ] operations = [ migrations.AlterModelOptions( name='category', options={'verbo...
from flask import request, Blueprint, jsonify, render_template, make_response, json from .. import db from main.models import UserModel from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity, get_jwt # from main.mail.functions import send_mail # Blueprint to access auth methods auth = Bluep...
import pytest from puzzles.naming_a_company import distinct_names @pytest.mark.parametrize( "ideas, expected", [ (["coffee", "donuts", "time", "toffee"], 6), (["lack", "back"], 0), ], ) def test_distinct_names(ideas, expected): assert distinct_names(ideas) == expected
# -*- coding: utf-8 -*- import os import sys import random import pickle class Objet: nbreObjets = 0 def __init__ (self, num, longueur, largeur, hauteur, poids) : self._num = num self._longueur = longueur self._largeur = largeur self._hauteur = hauteur self._poids = poids O...
############################################## # The MIT License (MIT) # Copyright (c) 2016 Kevin Walchko # see LICENSE for full details ############################################## from ins_nav.wgs84 import RE, FLATTENING, E2 from math import sqrt, atan2, sin, cos import numpy as np # New -------------------------...
# Audio To Text # Transcribe Audio # You can transcribe an audio file automatically with Python. # If you have an audio file with spoken words, the program will output a transcription of that audio file completely automatically. # This example uses English as input language for the audio file, but technically any la...
import torch import torch.nn as nn import json import src.mpii_dataset as ds import src.arch.models as models import src.arch.loss as loss from torch.utils.data import DataLoader from tqdm import tqdm import os from datetime import datetime import math triangle(0, 0, math.cos(math.radians(omega1)), ...
# simple implementation of Node class. class Node: """Lightweight, non-public class for storing a singly linked list""" __slots__ = "_element", "_next" # streamline memory usage. def __init__(self,element,next): self._element = element # reference to user's element self....
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-06 02:08 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import documents.models class Migration(migrations.Migration): initial = True dependencies = [ ('homework', '0001_...
import pyautogui as pgui import time import tkinter as tk import sys import random import pyperclip as pp root = tk.Tk() root.title("RPAApp") root.geometry("500x200") titlename = ("RPA") label1 = tk.Label(root, text=titlename, font=("Ricty Diminished", 12)).pack() box1 = tk.Entry() box1.insert(tk.END,"") box1.pac...
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class IntegrationConfig(AppConfig): name = 'integration' verbose_name = _('integration')
from django.db import models tpodoc = (('E', 'Entrada'),('S', 'Salida'),) class chofer(models.Model): ci = models.IntegerField() nombre = models.CharField(max_length=100) placa_vehiculo = models.CharField(max_length=20) creado = models.DateTimeField(auto_now_add = True, editable=False, null = True, blank = True) ...
import keyboard import os while True: if keyboard.is_pressed("1"): print("1. Görev") os.system('..\\daire\\main.py') if keyboard.is_pressed("2"): os.system('..\\dikdörtgen\\main.py') if keyboard.is_pressed("3"): print("3. Görev")
from gesture import Gesture class Player: def __init__(self): self.win_counter = 0 self.choice ="" self.gesture = Gesture() def choose_name(self): self.name = input("Insert name: ") def choose_gesture(self): # how to return value to be manipulated validation = Fal...
''' Created on 2013-7-26 finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]): @author: Administrator ''' #encoding=utf-8 import re p = re.compile(r'\d+') for m in p.finditer('one1two2three3'): print m.group()
# # 트리의 부모 찾기 import sys from collections import deque if __name__ == "__main__": read = sys.stdin.readline n = int(read()) arr = [[]*(n+1) for _ in range(n+1)] chk = [0] * (n+1) parent = [0] * (n+1) for _ in range(n-1): a,b = map(int,read().split()) arr[a].append(b) a...
from datetime import datetime from flask_bcrypt import generate_password_hash, check_password_hash from app import db class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, nullable=False) username = db.Column(db.String(80), unique=True, nullable=False) email = db....
import tkinter from tkinter import messagebox A = 32 # ASCIIコードのA番以降を使う(delも除外) A=32で制御文字を除くすべてのASCII文字が使用可能 #10進数numをN進数に変換する関数 def dec_to_N(num,N): keta=0 for i in range(10**9): if num<N**i: keta+=i break ans=[0]*keta check=0 for i in range(1,keta+1): j=...
import os import matplotlib.pyplot as plt import numpy as np import pandas as pd from PyPDF2 import PdfFileMerger from lib.chronics import get_sorted_chronics from lib.constants import Constants as Const from lib.rl_utils import compute_returns from lib.visualizer import pprint from .experiment_base import Experiment...
# Generated by Django 3.1.7 on 2021-04-12 05:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('loginanddashboard', '0017_auto_20210412_0917'), ] operations = [ migrations.RemoveField( model_name='allowancesdeductions', ...
#!python import glob LICENSE='./LICENSE-MIT' PATTERN='./src/DocoptNet/*.cs' OUTPUT='Docopt.cs' def main(): usings = set(); codes = [] for srcfile in glob.glob(PATTERN): #print(srcfile) with open(srcfile, 'r', encoding='utf-8-sig') as fp: for line in fp: #prin...
# 3.1 变量 # (1) 命名 # 1) 只能包含字母、数字和下划线, 不能包含空格 ex: a, a1, is_true, est_vrai # 2) 不能以数字开头 ex: 正确 :b_5 错误: 5b,5_b # 3) 不要将关键字和函数名用作变量名 ex: print, range, False, class, is, return, if 都不可以 # (2) 注意事项 # 1) 见名知义 name, age, student_id # 2) 避免使用小写字母l,o # (3) 赋值 "=" ...
#!/usr/bin/python from scapy.all import * ip=IP(src="10.0.0.1", dst="10.0.0.2") SYN=TCP(sport=1500, dport=80, flags="S", seq=100) SYNACK=sr1(ip/SYN) my_ack = SYNACK.seq + 1 ACK=TCP(sport=1050, dport=80, flags="A", seq=101, ack=my_ack) send(ip/ACK) payload="clear" PUSH=TCP(sport=1050, dport=80, flags="PA", seq=11, ac...
import so def lambda_handler(evento, context): what_to_print = so.environ.get('what_to_print') how_many_times = int(os.environ.get('how_many_times')) if what_to_print and how_many_times > 0: for i in range(0, how_many_times): print(f"what_to_print: {what_to_print}") return what_...
""" This code reads from the Thingful node and gets a list of all Sensors. The code then reads through the list of sensors and counts the number with a location of zero (at the moment assumes if x=0 y=0). Then displays percentage that are zero locations. Documentation for the GROW node is available at: https://grow...
import uuid """ 'array_of_docs' : [ -1, { "sclr" : 11, "str" : "e", "arr" : [4,5,6,{"sclr" : 21, "str" : "f"}] }, { "sclr" : 12, "str" : "g", "arr" : [7,8,9,{"sclr" : 22, "str" : "h"}] }, -2 ] """ smallObj= { 'sclr' : 0, 'str' : "...
from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'apps.basic.views.index'), url(r'^basic/$', 'apps.basic.views.index'), url(r'^admin/', include(admin.site.urls)), )
#!/usr/bin/python import docker import json import socket from docker import Client import json import etcd import time from daemon import runner import sys import getopt def get_container_key(json): c = Client(base_url='unix://var/run/docker.sock') b=str(json['Names'][0]) container_name=b.lstrip('/') for k in js...
s = 'abcdefghijklmnopqrstuvwxyz' print(s[1:3] == 'bc') # a print(s[:14] == 'abcdefghijklmn') # b print(s[14:] == 'opqrstuvwxyz') # c print(s[1:-1] == 'bcdefghijklmnopqrstuvwxy') # d The slice of s excluding the first and last characters is 'bcdefghijklmnopqrstuvw'.
i = 0 # if i > 0: # print("I is greater than 0") # else: # print("I is less than 0") # while condition: # statement while (i < 10): print(i, "is less than 10") i += 1 if i == 10: print("I is", i) print("Loop ended")
import requests from bs4 import BeautifulSoup from bs4.element import Tag import pandas as pd from pandas import DataFrame, Series import os # 页面模板,{0}处填写的页面从1开始 urlTempPage = "https://cd.ke.com/ershoufang/pg{0}su1ie2sf1l2p5/" # 用户代理 ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Geck...
import numpy as np from my_pytools.my_numpy.integrate import simps_2d from my_pytools.my_numpy.interpolate import ndinterp from my_pytools.my_numpy.rotations import rotate_discrete_data # function def f(theta_val, phi_val): return np.sin(theta_val) + 1 # get discrete f at N^2 angular points N = 500 tau = np.linsp...
import operator from visits_detector.core.components.data_structures import EventType, Event, SubInteraction from visits_detector.core.components.event_type_determiner.event_type_determiner_base import EventTypeDeterminerBase class HeuristicsEventTypeDeterminer(EventTypeDeterminerBase): @staticmethod def _ch...
import numpy from sklearn import mixture training=numpy.loadtxt('training',delimiter=',',skiprows=1) validn=numpy.loadtxt('validn',delimiter=',',skiprows=1) testset=numpy.loadtxt('testset',delimiter=',',skiprows=1) training_d = training[:,0:20] training_c = training[:,21] testset_d = testset[:,0:20] testset_c = testse...
from leads.models import Message from rest_framework import viewsets from .serializers import MessageSerializer class PatchNoteViewSet(viewsets.ModelViewSet): serializer_class = MessageSerializer queryset = PatchNote.objects.all()
import json import yaml import sys from threading import Lock import prometheus_client import requests import urllib3 from flask import Response, Flask, request from prometheus_client import Gauge import logging from logging.handlers import RotatingFileHandler UNDERSCORE = "_" SLASH = "/" HYPHEN = "-" PLUS = "+" LOG...
#BLOG POSTS #AUTHORS class Author(object): def __init__(self, name, age, genre): self.name = name self.age = age self.genre = genre self.blogs = [] def __repr__(self): return "Author: {0}".format(self.name) #BLOG class Blog(object): def __init__(self, title, date, subject): self.title = title self....
# # Parametric gait controllers. # # @akshara # import numpy as np from .cpg_oscillator import CpgController class Robot: def __init__(self, n_legs, n_joint_per_leg): self.n_legs = n_legs self.n_joint_per_leg = n_joint_per_leg # As many oscillators as joints. Amplitude of knee set to 0 ...
# image handling API from PIL import Image from StringIO import StringIO import base64 from mimetypes import guess_type import sqlite3 as lite # images = {} # thumbs = {} DB_path = "imageapp.db" def create_thumbnail(data): #Resize same ratio img = Image.open(StringIO(data)) basewidth = 200 wpercent = ...
import clr, sys clr.AddReference('ZyGames.Framework.Common'); clr.AddReference('ZyGames.Framework'); clr.AddReference('ZyGames.Framework.Game'); clr.AddReference('ZyGames.Tianjiexing.Model'); clr.AddReference('ZyGames.Tianjiexing.BLL'); clr.AddReference('ZyGames.Tianjiexing.Lang'); from action import * from System im...
import numpy as np import sys, getopt found = np.empty(10) found.fill( False ) def check(n, count=1): global found if n==0: return -1 n_str=str(count*n) #print n_str for i in range(len(n_str)): found[n_str[i]]=True #print found if np.all(found): return count*n return check(n, count+1) ...
import uuid import requests import shortuuid from PIL import Image from django.contrib.auth import get_user_model from django.contrib.postgres.fields import ArrayField, JSONField from django.db import models from django.http import HttpRequest from django.template import Template, Context from django.template.loader i...
""" Student code for Word Wrangler game Can't use set, sorted, or sort Always return a new list (no working in place) """ import urllib2 import codeskulptor import poc_wrangler_provided as provided import math WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplica...
import utils, os import numpy as np from data import preprocess, visualization from config import args from keras.optimizers import Adam from models.simple_cnn import SimpleCNN from keras.callbacks import ModelCheckpoint, EarlyStopping from keras.losses import categorical_crossentropy # save configs utils.save_logs()...
import motor.motor_asyncio from decouple import config # name of the database MONGODB_DB = config('DB_NAME', default='news_api') # name of the collection MONGODB_COLLECTION = config('COLLECTION_NAME', default='news') # mongodb://<dbUser>:<dbUserPassword>@host:port MONGO_DETAILS = config('MONGO_DETAILS', default='mo...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2019-07-02 16:29 # @Author : hedengfeng # @Site : # @File : anima_test.py # @Software: learn_python # @description: import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation fig, ax = plt.s...
class LinkedList: def __init__(self): self.head = None self.tail = None self.length = 0 def append(self, value): node = Node(value) if not self.head: self.head = node self.tail = node else: self.tail.next = node ...
from math import factorial from itertools import accumulate from operator import mul def nCr(n, r): if r > n or r < 0: return 0 if r == n or r == 0: return 1 a, b = max(r, n - r), min(r, n - r) a = list(accumulate(range(a + 1, n + 1), mul))[-1] return a // factorial(b)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('Mecze', '0013_auto_20151202_0044'), ] operations = [ migrations.RemoveField( model_name='sklad_na_mecz', ...
import datetime from tkapi.util import queries from tkapi.zaak import Zaak, ZaakSoort from tkapi.dossier import Dossier, DossierWetsvoorstel from tkapi.document import Document from .core import TKApiTestCase class TestDossier(TKApiTestCase): def test_get_dossiers(self): dossiers = self.api.get_dossier...
#! /usr/bin/env python ########################################################################## # CAPSUL - Copyright (C) CEA, 2013 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html ...
from find_gaps import generate_gaps from seq_dataset import bed_seq_data, generate_train_dataset from process_hic_data import normalize_hic_map, get_norm_matrix_for_region import sys,os import numpy as np import logging from termcolor import colored, cprint logging.basicConfig(format='%(asctime)s %(name)s: %(message)s'...
from recursion_util import * import collections import fileinput import json import sys fields_string = sys.argv[1] field_parts = fields_string.split('+') lines = ''.join(sys.stdin.readlines()) data_rows = json.loads(lines) out_rows = [] seen_keys = set() for row in data_rows: key_parts = [] failed = False for fi...
# coding: utf-8 import socket, hashlib, time, threading, json, enum, os ''' Trabalho de Redes de Computadores Desenvolvedores: Daniel Soares Eva Costa de Melo version 0.1 ''' def main(): ''' Verifica se o diretório existe ''' verificaPath("logs"); verificaPath("backups"); ''' Obtém o conteudo do arq...
from jnpr.junos import Device from jnpr.junos.exception import ConnectError from objects.SM_Node import * ############# # Device ############# class Junos_Device(Node): def __init__(self, host_name, ip, username, password): Node.__init__(self, name=host_name, parent=None, node_type='Device') self...
import subprocess # set working directory to contain uber_buckets, yellow_buckets, green_buckets subprocess.call("Rscript parse.R", shell=True)
# Generated by Django 2.2.4 on 2020-03-10 09:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('portal_users', '0055_auto_20200225_1056'), ('organizations', '0111_erorotext'), ] operations = [ mig...
#!/usr/bin/env python # coding: utf-8 # In[4]: import pickle def load_obj(name): with open(name + '.pkl', 'rb') as f: return pickle.load(f, encoding='latin1') def save_obj(obj, name): with open(name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) ...
from django.contrib import admin from .models import * admin.site.register(User) admin.site.register(Course) admin.site.register(Lecture) admin.site.register(HomeWork) admin.site.register(Solution) admin.site.register(Mark) admin.site.register(Comment)
from functools import cache from sys import path import numpy as np from typing import List # from multi_distr import MultiDistr # 5* pity (pathological case) def pathological_e5s_pity(n): ret = np.array([0]) return int((n==1) | (n==2)) * 1/2 def pathological_solver(chain): # Make the chain drain out th...