text stringlengths 38 1.54M |
|---|
# Run command file for percol
##########################################c
percol.import_keymap({
"C-g" : lambda percol: percol.cancel(),
"C-j" : lambda percol: percol.command.select_next(),
"C-k" : lambda percol: percol.command.select_previous(),
"C-n" : lambda percol: percol.command.select_next(),
... |
from django.urls import path
import recibos.views as recibos_views
urlpatterns = [
path('',recibos_views.RecibosList.as_view(),name="recibos"),
path('<int:pk>',recibos_views.RecibosDetail.as_view(),name="recibo"),
path('<int:pk>/file',recibos_views.RecibosByteDetail.as_view(),name="recibo_file")
]
|
import pytest
from takler.core import Limit, Task, SerializationType
from takler.core.limit import InLimit, InLimitManager
def test_limit_to_dict():
limit = Limit("upload_limit", 10)
assert limit.to_dict() == dict(
name="upload_limit",
limit=10,
value=0,
node_paths=list(),
... |
import xlrd
excelFile1 = 'excel1.xlsx'
excelFile2 = 'excel2.xlsx'
book1 = xlrd.open_workbook(excelFile1)
book2 = xlrd.open_workbook(excelFile2)
first_sheet = book1.sheet_by_index(0)
second_sheet = book2.sheet_by_index(0) |
#!/usr/local/bin/python3.5
import os,time,sys,time
import oss2
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from lib import innodb_backup as lib_innodb_backup
def upload(host,user,password,port,my_conf):
abc=lib_innodb_backup.backup(host,user,password,port,my_conf)
auth = oss... |
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select One Please:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. divide")
choice = input("Please Select One Now:")
num1 = int(inp... |
from splinter import Browser
from bs4 import BeautifulSoup
from webdriver_manager.chrome import ChromeDriverManager
import requests
import pandas as pd
import time
import os
def init_browser():
# NOTE: Replace the path with your actual path to the chromedriver
executable_path = {'executable_path': ChromeDrive... |
# this section of the code does not process or analyze anything. This simply exists to call on other modules to collect, store and use
# their outputs. This file requires all the imports just as all the imports mentioned here cannot run without this file. This code exists
# purely for organizational purposes and shou... |
import copy
import logging
from topicnet.cooking_machine.models import (
BaseScore as BaseTopicNetScore,
TopicModel
)
from .base_score import BaseScore
_logger = logging.getLogger()
# TODO: kostyl
global __NO_LOADING_DATASET__
__NO_LOADING_DATASET__ = [False]
class BaseCustomScore(BaseScore):
def __i... |
from django.db import models
# Create your models here.
class Adminmodel(models.Model):
User_Name=models.CharField(max_length=30)
Password=models.CharField(max_length=8)
def __str__(self):
return self.User_Name
class StateModel(models.Model):
State_no=models.AutoField(primary_key=True)
St... |
import pyforms, numpy as np, traceback, math
from pyforms.basewidget import BaseWidget
from pyforms.controls import ControlLabel
from pyforms.controls import ControlText
from pyforms.controls import ControlButton
from pyforms.controls import ControlCombo
from pyforms.controls import ControlCheckBox
from pyforms.... |
#!/usr/bin/env python3
"""Test out the sandbox helper class."""
import sys, os, re
import unittest
import logging
import time
from datetime import datetime
from sandbox import TestSandbox
DATA_DIR = os.path.abspath(os.path.dirname(__file__) + '/asandbox')
VERBOSE = os.environ.get('VERBOSE', '0') != '0'
class T(un... |
import pytest
from src.controllers.base_controller import BaseController
from src.controllers.bet_controller import BetController
from src.models.bet import Bet
@pytest.fixture
def create_instance():
bet = BetController()
return bet
def test_bet_controller_instance(create_instance):
assert isinstance(c... |
# 496. Next Greater Element I
# Runtime: 44 ms, faster than 88.07% of Python3 online submissions for Next Greater Element I.
# Memory Usage: 14.5 MB, less than 43.69% of Python3 online submissions for Next Greater Element I.
class Solution:
# Stack
def nextGreaterElement(self, nums1: list[int], nums2: list[... |
from ut import runcleos
import json
def _push_transaction(d):
cmd = [
"cleos",
"-u",
"https://api.eosbeijing.one",
"push",
"transaction",
json.dumps(d),
]
return runcleos(cmd)
def getaction(contract, action, data, f, p=False):
"""
contract :要玩的合约地址... |
from libs import pygame_textinput
import pygame
import time
from random import randrange
from objects.foca import Foca
from objects.alga import Alga
from objects.tubarao import Tubarao
from objects.peixe import Peixe
import random
from objects.tela import Tela
from objects.utils import utils
pygame.init()
pygame.displ... |
# -*- coding: utf-8 -*-
'''
* Copyright (C) 2015 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of pypYIN
*
* pypYIN is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF... |
import altair as alt
import pandas as pd
from .visitor import visit
from .aggregate import AGG_REPLACEMENTS
@visit.register(alt.JoinAggregateTransform)
def visit_joinaggregate(
transform: alt.JoinAggregateTransform, df: pd.DataFrame
) -> pd.DataFrame:
transform = transform.to_dict()
groupby = transform.ge... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from xml.dom import minidom
import os
pathTransDir = '/Users/renyushuang/custom/projectDo/DuScreenRecorder/RecordMaster/src/main/res'
pathTransFile = 'strings.xml'
pathAndroidDir = '/Users/renyushuang/custom/projectDo/VideoDownloader/app/src/main/res'
pathAndroidFile = 'str... |
from typing import List, Tuple
import numpy as np
import pandas as pd
import sklearn
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
class IsolationForestDetector(object):
def __init__(self):
self._scaler = StandardScaler()
# type: sklearn.preprocessi... |
from collections import defaultdict
from itertools import groupby
import sys
from q40 import Morph, arg_int
class Chunk:
"""cabocha lattice formatファイルから文節を読み込む"""
__slots__ = ('idx', 'dst', 'morphs', 'srcs')
# * 0 2D 0/0 -0.764522
def __init__(self, line):
info = line.rstrip().split()
... |
import babelfish
# Local directory settings.
TV_PATH = '/home/siorai/Downloads/Transmission/Organized/TV'
MOVIE_PATH = '/home/siorai/Downloads/Transmission/Organized/Movies'
APP_PATH = '/home/siorai/Downloads/Transmission/Organized/Programs'
MUSIC_PATH = '/home/siorai/Downloads/Transmission/Organized/Music'
OTHER_PATH... |
"""empty message
Revision ID: 06e2c7d46e81
Revises:
Create Date: 2021-08-29 11:52:21.775818
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '06e2c7d46e81'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
import os
# Cleaning up data files
if os.path.isfile('data1.txt'):
os.remove("data1.txt")
if os.path.isfile('data2.txt'):
os.remove("data2.txt")
if os.path.isfile('data3.txt'):
os.remove("data3.txt")
# finding all the available hosts
cmd = os.popen('bash checkhosts.sh')
print(cmd.read())
cmd.close()
# dat... |
import time
print('''
-----------------------------------------------------------------------
Project available in the cesarzxk/svg-react-native-converter repository
-----------------------------------------------------------------------
''')
looping = True
while(looping):
name = input('Entre com o nome do arqui... |
'''
1) Copy this file to config.py.
2) Set Wunderground API key here. https://www.wunderground.com/weather/api
'''
WUAPI = '12345abc'
|
from webob import Request, Response, exc
from webob.dec import wsgify
import re
class DictObj:
def __init__(self, d:dict):
if not isinstance(d, dict):
self.__dict__['_dict'] = {}
else:
self.__dict__['_dict'] = d
def __getattr__(self, item):
try:
retu... |
import random
class Board(object):
""" Returns a new partially-empty board for 2048.
Contains number 2 generated at random place in the board
"""
__row = 4
__column = 4
def __init__(self):
self.__board = None
def get_new_board(self):
self.__board = [[0 for _ in range(Boa... |
# Generated by Django 3.1.2 on 2020-10-19 22:41
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Startdir',
fields=[
... |
#!/usr/bin/env python3
#
# fusée gelée
#
# Launcher for the {re}switched coldboot/bootrom hacks--
# launches payloads above the Horizon
#
# discovery and implementation by @ktemkin
# likely independently discovered by lots of others <3
#
# this code is political -- it stands with those who fight for LGBT rights
# don't... |
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from . import app
from datetime import datetime
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -
#
# This file is part of restkit released under the MIT license.
# See the NOTICE for more information.
from setuptools import setup, find_packages
import glob
from imp import load_source
import os
import sys
if not hasattr(sys, 'version_info') or sys.version_info < (2, 6... |
# Bulls and Cows
'''
You are playing the following Bulls and Cows game with your friend:
You write down a number and ask your friend to guess what the number is.
Each time your friend makes a guess, you provide a hint that indicates
how many digits in said guess match your secret number exactly in both
digit ... |
from scrapy.item import Field
from scrapy.item import Item
from scrapy.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from scrapy.loader.processors import MapCompose
from scrapy.linkextractors import LinkExtractor
from scrapy.loader import ItemLoader
class Propiedad(Item):
informacion = Field()... |
import os
import csv
from statistics import mean
csvpath = os.path.join('Resources', 'election_data.csv')
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
csv_header = next(csvreader)
row_count = 0
candidates_with_votes = []
votes = {}
for row in csvreader:
... |
# -*- coding: utf-8 -*-
'''
Created on Dec 6th, 2017
@author: Varela
motivation: module provides clustering from distance and transforming (from structs)
'''
#Regex
import glob # Unix style GLOB performs pattern matching on files
import re
#Datascience stuff
import pandas as pd
import numpy as np
#Nice co... |
first_name = "PP"
last_name = "Singh"
output = "Hello, {} {}".format(first_name,last_name)
# output = f"Hello{first_name}"
print(output) |
import itertools
import sys
'''
To run:
python palindrome.py <string>
The time complexity is O(N) because we iterate through the string and
try to find a palindrome configuration. The worst case is where we:
a) obtain a palindrome by iterating through half the string, or
b) discover there are two singular letter... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
#... |
# fields CFHTLenS W1-4
# subfields: 171 1deg^2 throughout W1-4
# cells: 4x4arcmin covering each subfield, in a grid
# usage: use one of the following arguments: lens name, followed by orig or samp, followed by number of bins, followed by radius (45,60,90 or 120) and by maglimit
import numpy as np
import sys
import os
... |
"""
Class of strategies that are agnostic and have a joint GP.
"""
from argparse import Namespace
import numpy as np
from scipy.stats import norm as normal_distro
from strategies.joint_opt import JointOpt
from util.misc_util import sample_grid, build_gp_posterior, ei_acq, \
expected_improv... |
from time import sleep
def naC(temp):
return (5/9) * (temp-32)
def naF(temp):
return (9/5) * temp + 32
while(True):
opcja = input("1.Zamiana [°C] na [°F]\n2.Zamiana [°F] na [°C]\nWpisz cokolwiek innego by zakończyć program:\n")
if opcja == '1':
temp = int(input("Podaj temp w [°C]: "))
print(tem... |
# 机试题
# 1.lis = [['哇',['how',{'good':['am',100,'99']},'太白金星'],'I']] (2分)
# lis = [['哇', ['how', {'good': ['am', 100, '99']}, '太白金星'], 'I']]
# o列表lis中的'am'变成大写。(1分)
# lis[0][1][1]['good'][0] = lis[0][1][1]['good'][0].upper()
# print(lis)
# o列表中的100通过数字相加在转换成字符串的方式变成'10010'。(1分)
# lis[0][1][1]['good'][1] = str(lis[0][1][... |
import acqua.aqueduct as aq
import acqua.label as al
import acqua.labelCollection as coll
gestore = "ACAMLaSpezia"
aq.setEnv('Liguria//'+gestore)
dataReportCollectionFile = 'Metadata/DataReportCollection.csv'
geoReferencedLocationsListFile = 'Metadata/GeoReferencedLocationsList.csv'
fc = al.createJSONLabels(gestore,dat... |
# /usr/bin/python
# -*- encoding:utf-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.rnn import BasicLSTMCell
from tensorflow.contrib.rnn import MultiRNNCell
from tensorflow.contrib.rnn import static_bidirectional_rnn
from tensorflow.contrib.layers impor... |
# CarControl.py
#
from serial import Serial
from threading import Timer
class CarControl:
def __init__(self, comport):
self.comport = comport
self.cars = {
1: {'x-servo':1, 'y-servo':2},
2: {'x-servo':3, 'y-servo':4},
3: {'x-servo':5, 'y-se... |
#!/usr/bin/python
import pprint, sys, time
import dbus, flimflam
if (len(sys.argv) < 2):
print "Usage: %s <service_name>" % (sys.argv[0])
sys.exit(1)
flim = flimflam.FlimFlam(dbus.SystemBus())
timeout = time.time() + 30
while time.time() < timeout:
service = flim.FindElementByPropertySubstring('Service'... |
# Løsning basert på gradient decent
from numpy import *
def f(k, n):
f = e**(k/n) - 1
return f
def E(X, n):
return abs(f(X[0], n) + f(X[1], n) + f(X[2], n) + f(X[3], n) - pi)
'''
def E_grad(X, n):
s = sign(f(X[0], n) + f(X[1], n) + f(X[2], n) + f(X[3], n) - pi)
pDE_a = (s*e**(X[0... |
from services.detection.tf_pose.networks import get_graph_path, model_wh
from services.detection.tf_pose.estimator import TfPoseEstimator
from services.detection.fsanet_pytorch.utils import draw_axis
from services.detection.fsanet_pytorch.face_detector import FaceDetector
import onnxruntime
import torch
import tensorfl... |
#QUESTAO3
print("Funções recursivas são funções que chamam a si mesma de forma que, para resolver um problema maior, utiliza a recursão para chegar as unidades básicas do problema em questão e então calcular o resultado final.\n Exemplo:")
def fatorial(n):
if (n==1):
return (n)
return fatorial(n-1)*n... |
# construct a relative transformation
from importlib import resources
import numpy as np
from timemachine.fe.rbfe import setup_initial_states
from timemachine.fe.single_topology import SingleTopology
from timemachine.fe.utils import get_romol_conf, read_sdf
from timemachine.ff import Forcefield
def get_hif2a_ligan... |
template = """<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script>var token = "{{ token }}";</script>
<script src="//api.bitrix24.com/api/v1/"></script>
<script>
function runApplication (currentValues) {
currentValues = currentValues || {}
var form = do... |
"""
Graph State
===========
"""
from collections import defaultdict
import numpy as np
class _GraphState:
"""
The topology graph of a molecule under construction.
"""
__slots__ = [
"_vertex_building_blocks",
"_vertices",
"_edges",
"_lattice_constants",
"_ve... |
from django.shortcuts import render
from .serializers import RegisterSerializer, LoginSerializer, UserSerializer
from rest_framework.generics import GenericAPIView
from rest_framework import status, permissions
from rest_framework.response import Response
from knox.models import AuthToken
from django.contrib.auth impor... |
from base.element_field import ElementField
from dataclasses import dataclass
@dataclass
class Water(ElementField):
img = 'C:/Users/Данагуль/Desktop/текущее/ООЯ и С/game/image/water1.png'
|
# Copyright (c) 2020 by BionicDL Lab. All Rights Reserved.
# !/usr/bin/python
# -*- coding:utf-8 -*-
from setuptools import setup, find_packages
setup(
name='DeepClaw',
version='1.0.3',
description=(
'a reconfigurable benchmark of robotic hardware and task hierarchy for robot learning'
),
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import scipy.optimize
df = pd.read_csv('data/bcd_gradient.csv', comment='#')
df = df.rename(columns={'fractional distance from anterior': 'x',
'[bcd] (a.u.)': 'I_bcd'})
plt.plot(df['x'], df['I_bcd'], ... |
# 静态方法,类方法
class TestClass:
@classmethod
def clssMethod(cls):
print('class name is {},full name is {}'.format(cls.__name__, cls.__qualname__))
@staticmethod
def staticMethod():
print('this is static method')
def main():
TestClass.clssMethod()
TestClass.staticMethod()
a = ... |
# 给出一个完全二叉树,求出该树的节点个数。
#
# 说明:
#
# 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
#
# 示例:
#
# 输入:
# 1
# / \
# 2 3
# / \ /
# 4 5 6
#
# 输出: 6
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/count-complete-tree-nodes
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转... |
from file_utils import file_contents
from pytokens import PYKEYWORDS
from type_simulation import TYPES
from nlparser import QueryParser
from type_simulation import guess_types, get_referencables
from canon_utils import fetch_queries_codes, parsable_code, reproducable_code, give_me_5
import ast
# import codeg... |
from datetime import datetime, timedelta
from faker import Faker
from flask_wtf import FlaskForm
from flask import session
import wtforms as forms
from db import mongo
from schemas import UserSchema
class EmailForm(FlaskForm):
email = forms.StringField('Email Address')
def validate_email(form, field):
... |
# Generated by Django 3.2.5 on 2021-07-18 22:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('events', '0005_alter_presence_unique_together'),
]
operations = [
migrations.RenameField(
model_name='presence',
old_name='i... |
from flask import session
import requests
BASE_PARAMS = {'per_page': '50'}
CANVAS_DOMAIN = "usu.instructure.com"
def courses(token, id='15', more_pages_URI=None, term=None, deleted=None):
# parameters should be entered as type str
rh = {"Authorization": "Bearer %s" % token}
BASE_PARAMS = {'per_page': '50'... |
import requests
r = requests.post("http://0.0.0.0:5000/", json={'ID':'10200','FPS':'2','duration':'40','lang':'hindi'})
print(r.status_code, r.reason)
print(r.text)
# from urllib.parse import urlencode
# from urllib.request import Request, urlopen
# url = 'http://0.0.0.0:5000/' # Set destination URL here
# post_fi... |
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse,JsonResponse, HttpResponse
from django.views.decorators.http import require_GET,require_POST,require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate,login as... |
import turtle as t
t.shape("turtle")
t.penup()
t.pendown()
t.forward(100)
t.left(60)
t.forward(100)
t.left(60)
t.forward(100)
t.left(60)
t.forward(100)
t.left(60)
t.forward(100)
t.left(60)
t.forward(100)
t.left(60)
t.done()
|
import os
def hello_world():
print("-------> CLAYTHON SAYS ------ HELLO")
pass
if __name__ == "__main__":
hello_world()
|
'''korean_dict_parser_type_1.py
Korean dictionary parser for type 1 text files
'''
import json
from word_functions import (
strip_and_sub_using_regex,
generate_korean_dictionary_type_1,
)
INPUT_FILE = "../txt/6000_p1.txt"
OUTPUT_FILE = "../json/korean_dict_6000_part_1.json"
def main():
# Read korean w... |
# Generated by Django 2.2 on 2019-10-28 01:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera... |
#map- Function
def triple(x):
return 3*x
def triplesuffle(y):
nl = map(triple,y)
return list(nl)
v = [1,2,3]
z = triplesuffle(v)
print(z)
#map- Lambda
def five(value):
new_list = map(lambda u:5*u, value)
return list(new_list)
b = [8,9,10]
n = five(b)
print(n)
... |
"""
Solve the sudoko which is a 3*3 matrix, the sum of each row and each column and diagonal
of the matrix is 15. Function sudoko2 seems better for it only caculate the rows once.
"""
from itertools import permutations
def sudoko():
numbers = [1,2,3,4,5,6,7,8,9]
pmNumbers = permutations(numbers)
results... |
# Generated by Django 3.1.7 on 2021-03-28 07:31
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('home', '0004_auto_20210328_1256'),
]
operations = [
migrations.AlterField(
... |
# -*- coding: utf-8 -*-
# @Author :AI悦创
# @DateTime :2019/9/15 11:31
# @FileName :判断是否为整数插件.PY
# @Function :功能
# Development_tool :PyCharm
# <-------import data-------------->
# def isinstance_int(start_pn_num, end_pn_sum):
def isinstance_int(target):
# target = end_pn_sum/start_pn_num
if isin... |
# Copyright 2020 The KNIX Authors
#
# 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 or agree... |
# -*- coding: utf-8 -*-
# @Time : 5/24/18 10:54 AM
# @Author : yunfan
# @File : voc_eval.py
import numpy as np
import json
import cPickle
from DetmAPinVOC import DetmAPinVOC
from gluoncv.data.pascal_voc.detection import VOCDetection
DEBUG = False
VOC_2007_JSON_PATH = './VOC2007-SSD-512.json'
def res_to_allbb... |
from flask import Flask, session, request, jsonify, render_template
from flask.ext.cache import Cache
import os
import json
# SETUP ======================================================================================
app = Flask(__name__) #APPLICATION
app.config.from_object(__name__)
app.jinja_env.autoescape = F... |
while(True):
n = int(input())
if n==0: break
arr = list(map(int,input().split()))
r=d=0
chk=0
ans=0
now=arr[0]
if arr[2]-arr[1] == arr[1]-arr[0]:
d=arr[2]-arr[1]
chk=1
else:
r = arr[2]//arr[1]
chk=2
if chk==1:
for i in range(0,n):
... |
__author__ = "Ankur Prakash Singh"
# Date format "%m-%d-%Y"
__date__ = '02-20-2020'
"""Max Profit With Transactions"""
|
from datetime import timedelta
from sqlalchemy import func
"""
https://github.com/apache/airflow/blob/16d93c9e45e14179c7822fed248743f0c3fd935c/airflow/www_rbac/views.py#L153
Script that can be used to check if scheduler running correctly as it can sometimes gets stuck
unable to schedule new tasks despite the proces... |
from pwn import *
context(arch='amd64',os='linux',log_level='debug')
sl = lambda x:io.sendline(x)
s = lambda x:io.send(x)
rn = lambda x:io.recv(x)
ru = lambda x:io.recvuntil(x, drop=True)
r = lambda :io.recv()
it = lambda: io.interactive()
success = lambda x:log.success(x)
binary = './task_magic'
io = process(binary)... |
import cv2 as cv
import numpy as np
if __name__ == '__main__':
img = cv.imread('imagem.png')
imgGray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
retval, imgOTSU = cv.threshold(imgGray,0,255,cv.THRESH_OTSU)
kernel = cv.getStructuringElement(cv.MORPH_RECT,(1,3))
for i in range(5):
i... |
from dataclasses import dataclass
import dataclasses
from functools import reduce
from gclang.gen.GuardedVisitor import GuardedVisitor
import sympy as sp
from gclang.guarded_exception import GuardedException
from ..gen.GuardedParser import GuardedParser
def compose(*fns):
return reduce(lambda f, g: lambda x: f... |
import datetime
import tushare as ts
from app_registry import appRegistry as ar
from model.m_area import MArea
from model.m_industry import MIndustry
from model.m_stock import MStock
from model.m_user_stock import MUserStock
from model.m_stock_daily import MStockDaily
from util.app_util import AppUtil
'''
获取沪深两市所有挂牌股票... |
import random
def make_lst():
count = int(input("How many numbers do you need? "))
lowest = int(input("What's the lowest number? "))
upper = int(input("What's the highest number? ")) + 1
lst=[]
for i in range (0,count):
lst.append(random.randrange(lowest,upper))
return lst
print(m... |
#!/usr/bin/python
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
This tool creates a tarball with all the sources, but without .svn directories.
It can also remove files which are not strictly re... |
#!/usr/bin/python
from sys import *
def generic_istream(filename):
#print >> stderr,"opening ",filename
if filename=="-":
return sys.stdin
else:
return open(filename)
def printUsageAndExit(programName):
print >> stderr,programName,"fastafile > outfile"
exit()
def softMaskToHardMaskSeq(seq):
nseq=""
for... |
from typing import List
from sql_types import SqlType, SqlColumn
from function import FunctionTemplate, MacroDefinition
class Prop:
def __init__(self, name: str, proptype: SqlColumn):
self.name = name
self.proptype = proptype
class Struct:
def __init__(self, name: str, columns: List[SqlColumn]):
# assert c... |
import FWCore.ParameterSet.Config as cms
def customise(process):
# fragment allowing to simulate neutron background in muon system
# using HP neutron package and thermal neutron scattering
from SimG4Core.Application.NeutronBGforMuons_cff import neutronBG
process = neutronBG(process)
if hasattr(process,'g... |
"""The smart list name."""
from jupiter.core.domain.entity_name import EntityName
class SmartListName(EntityName):
"""The smart list name."""
|
from nltk.corpus import brown
from multiprocessing import Pool
import string
import nltk
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
import re
# Get brown data
rawData = brown.tagged_sents()
# Lower case, stopword removal, trim sentences
def preprocess(rawSentence):
sentence = [] ... |
# 5. Assert a test case true if the input falls under the range[-5,5]
def assert_test(num):
assert -5 <= num <= 5
#test
assert_test(4)
assert_test(6) |
import os
from google.cloud import storage
from django.test import TestCase
from django.conf import settings
from .storage_service import FileStorageService
class FileStorageTests(TestCase):
@classmethod
def setUpTestData(cls):
storage_client = storage.Client()
cls.bucket = storage_client.get... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 17 14:55:53 2017
@author: Administrator
"""
from gensim import corpora, models, similarities
import matplotlib.pyplot as plt
import numpy as np
import os
filelist=os.listdir('C:\\Users\\Administrator\\Desktop\\original_lda\\rawdata');
for item in filel... |
from crawler import download_all, download_srt_file, download_improve
url = 'http://www.xuetangx.com/courses/course-v1:TsinghuaX+20220332X+2018_T2/courseware/a1039c2138944208a18a83d3c14dd799/f33a4efe2738403ba73cccd510fafb38/'
if __name__ == '__main__':
download_improve(url)
# download_srt_file(url)
|
from django.shortcuts import render
from rest_framework.decorators import api_view
from .serializer import MovieSerializer
from .models import Movie
from rest_framework.response import Response
# Create your views here.
@api_view(['GET'])
def apiOverview(request):
api_urls = {
'List':'/get-movie/',
'Create':'/pos... |
import os, time, datetime
from preprocess import PreprocessingPipeline
from random import shuffle
sampling_rate = 125
n_velocity_bins = 32
seq_length = 1024
n_tokens = 256 + sampling_rate + n_velocity_bins
def main():
pipeline = PreprocessingPipeline(input_dir="data", stretch_factors=[0.975, 1, 1.025],
... |
########################
# Constants declaration
########################
# YOU SHOULD MODIFY THIS FILE
# USE 'constants_perso' to declare your modifications
# the tag for replacement
tag = '€'
# 1. list of LaTeX environnment whose content will be discard
# Ex. \begin{equation} ... \end{equation} will be replace b... |
import pandas as pd
def planning(df):
df['loadDate'] = df['loadDate'].str[:10]
df['dayofweek'] = list(df['loadDate'].map(str) + " "
+ pd.to_datetime(df['loadDate'], format='%Y-%m-%d').dt.day_name())
new = list(df['loadlocation'].map(str) + " " + df['loadingReference'].map(str) ... |
# Generated by Django 4.0.1 on 2022-03-02 08:20
from django.db import migrations
def UpdateJobStatus(apps, schema_editor):
"""A bug resulted in the human readable choices values for Job.status being saved in the
database. This migration updates all existing job records to ensure that the correct
values a... |
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from pathlib import Path
import json
from request_appi import AppiResponseMonitor
class MonitorVentas(PatternMatchingEventHandler, Observer):
def __init__(self, path='.', patterns='*', logfunc=print):
PatternMatc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.