text stringlengths 38 1.54M |
|---|
import logging
from database import db_session
from models import Hack, Submission, HackCorpus
from ngrams import build_bad_advice
from datetime import datetime
from flask import jsonify
def give_bad_advice(category='lifehacks'):
return {'hack':build_bad_advice(db_session)}
def submit_hack(tweet_id=None, user=Non... |
import turtle
import random
food_list = ['icecream.gif','orange.gif', 'cupcake.gif','pepper.gif']
foodii = turtle.clone()
foodi = random.randint (0, 3)
turtle.register_shape(foodi)
this_food = food_list[foodi]
foodii_stamp = foodii.stamp()
turtle.mainloop()
|
from django.contrib import admin
from .models import Task, Subtask, Skill, UserSkill, SubtaskSkill
# Register your models here.
admin.site.register(Task)
admin.site.register(Subtask)
admin.site.register(Skill)
admin.site.register(UserSkill)
admin.site.register(SubtaskSkill)
|
#######
## Modulos
#######
#import fibonacci
#print("desde modulos: ",fibonacci.fib(4))
#print()
from fibonacci import fib,fibomath
print(dir())
print(fib(3)) |
from PyQt5.QtWidgets import QMessageBox, QAction, QFileDialog
from PyQt5.QtGui import QIcon
from simucaller.gui.dialog import HeatmapLoadingDialog
from simucaller.helpers import get_logger
log = get_logger(__name__)
class Menu(object):
"""
Abstract class for create menu.
Menu
* File
- Load ... |
""" Script base for orlov anat package. """
import logging
import pytest
# pylint: disable=E0401
from anat.script.kancolle.testcase_kancolle import KancolleNormal
logger = logging.getLogger(__name__)
@pytest.mark.usefixtures('conftests_fixture', 'orlov_fixture', 'anat_fixture')
# pylint: disable=E1101, C... |
# -*- coding: utf-8 -*-
'''
Created on 30 mars 2017
@author: heifara
'''
from odoo import models, fields, api
from odoo.tools.translate import _
class HolidaysType(models.Model):
_inherit = "hr.holidays.status"
count = fields.Boolean('Active le comptage des jours de congés malgré le dépassement de limite a... |
from pygsvn import git,svn
def execute(path='.'):
''' resolve SVN and git conflicts '''
if svn.has_conflicts(path):
from pygsvn.cmd import tsvn
tsvn.execute('resolve')
if git.has_conflicts(path):
from pygsvn.cmd import tgit
tgit.execute('resolve')
|
import requests
import random
from PIL import Image
from collections import Counter
from names import NameJoiner
from bs4 import BeautifulSoup
import os
import shutil
import cairosvg
import sqlite3
import itertools
import math
class CountryMixer:
def rgb2hex(self, color):
r, g, b = color
code = "#... |
# -*- coding: utf-8 -*-
"""
The goal of this file is to design a class for Neural Networks
@author: Sharjeel Abid Butt
@References
1. http://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/
2. https://github.com/NeoBoy/STSP_IIUI-Spring2016/tree/master/Task2
"""
import copy
import numpy as np
#impo... |
import socket
import struct
from tkinter import Tk, Button, INSERT, END, Label, Text
from tkinter import scrolledtext
# ---- Global Variables ----
gWindow = Tk()
gTxtIP = Text(gWindow, height=1, width=40)
gTxtFeedback = scrolledtext.ScrolledText(gWindow)
def TextBoxInput(e):
# We arrived here via an e... |
# Crie um programa que leia o nome completo de uma pessoa e mostre:
# O nome com todas as letras maiúsculas e minúsculas.
# Quantas letras ao todo (sem considerar espaços).
# Quantas letras tem o primeiro nome.
nome = input('Nome completo: ').strip()
print(nome.upper())
print(nome.lower())
print(len(nome) - nome.co... |
from typing import Dict
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from transformers import BertModel, AdamW, AutoModel, RobertaModel
from src.enums import BaseModelType
class BiEncoder(pl.LightningModule):
def __init__(self, base_model_type: str):
... |
from claseCola import Cola
import random
cola = Cola()
for i in range(4):
cola.encolar(random.randint(1,10))
cola.imprimirCola()
cola.encolar(6)
cola.imprimirCola()
d = cola.desencolar()
print(f"El dato {d} sale de la cola.")
d = cola.desencolar()
print(f"El dato {d} sale de la cola.")
sig = cola.siguiente()... |
# -*- encoding: UTF-8
import z3
import libirpy.util as util
import datatypes as dt
import label as l
def current_eq(s1, s2):
conj = []
idx = util.FreshBitVec('tlsidx', dt.size_t)
conj.append(s1.current == s2.current)
conj.append(z3.ForAll([idx], z3.Implies(
z3.ULT(idx, dt.TLS_NR_SLOTS),
... |
# Test for vacuum's reduced processing of heap pages (used for any heap page
# where a cleanup lock isn't immediately available)
#
# Debugging tip: Change VACUUM to VACUUM VERBOSE to get feedback on what's
# really going on
# Use name type here to avoid TOAST table:
setup
{
CREATE TABLE smalltbl AS SELECT i AS id, '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import re
import argparse
PATTERN = re.compile("([^\s]+)\s+\((.+)\)\s+type: (.+)\s+default: (.+)")
BOOL_CHOICES = ["y", "n", "1", "0", "true", "false"]
def ParseFlag(flag):
flag = flag.replace("\n", " ").strip()
m = PATTERN.search(flag)
return {k... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#Hash map
#Time: O(n)
#Space: O(n)
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if not head:
return None
hash_map = {}
... |
#Contains the artist name and list of albums for which they possess
class artist (object):
def __init__(self, artistName, aliasList, albumList, albumIdList, area):
self.artistName = artistName
self.area = area
self.albumList = albumList
self.albumIdList = albumIdList
self.aliasList = aliasList
def getA... |
from multiprocessing import Pool
from timer import Timer
import time
import os
from subprocess import call
def do_something(input):
time.sleep(input)
print(input, os.getpid(), os.getppid(), call([]))
if __name__ == '__main__':
arr = [1,2,1,2,1,2,1,2,1,2]
with Timer() as t:
with Pool(5) as p:
... |
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
# trata os erros de digitacao do ano de conclusao e calcula o GAP
# GAP: Diferença entre o ano de conclusao e o ano de ingresso na ufjf
def calculaGAP(df):
# trata erros de digitacção
df['anoconc2g'] = df['anoconc2g'].replace('____', None)
... |
#Jakub Janicki
# korzystajac z log obliczam x
# robie bucket sort wkładajac do bucketów korzystajac z równomiernego rozłozenia x
# sortuje wewnatrz bucketów insert sortem
# złozonosc czasowa O(n) poniewaz rozłozenie x jest równomierne wiec bucket sort jest linionwy
# poniewaz insert sort jest liniowy dla małych rozmiar... |
# https://programmers.co.kr/learn/courses/30/lessons/42626
# 나의 풀이
import heapq
def solution(scoville, K):
answer = 0
scoville.sort()
while True:
if scoville[0] >= K:
break
min1 = heapq.heappop(scoville)
min2 = heapq.heappop(scoville)
mixed_food = min1 + min2 *... |
from board import Board
def h(map):
queens = []
for i in range(len(map)):
for j in range(len(map)):
if map[i][j] == 1:
queens.append((i, j))
pairs = set()
for idx in range(len(queens)):
for idx2 in range(idx, len(queens)):
pairs.add((idx, idx2))... |
"""Unit tests for PyTorch Lidar sub-module."""
from pathlib import Path
from typing import Final
import numpy as np
import pandas as pd
import torch
from torch.testing._comparison import assert_close
from av2.torch import LIDAR_COLUMNS
from av2.torch.structures.lidar import Lidar
TEST_DATA_DIR: Final = Path(__file_... |
import os
import torch
# Verifies two checkpoints, taken before and after training from scratch,
# and determines which parameters values are unchanged after training
before_checkpoint_filename = "mae_e7d2_128_fromscratch_0.pth"
after_checkpoint_filename = "mae_e7d2_128_fromscratch.pth"
os.chdir("../checkpoints")
b... |
from django.contrib import admin
from .models import Diccionario, Publicacion
# Register your models here.
admin.site.register(Diccionario)
admin.site.register(Publicacion)
|
# Standard library imports
import unittest
# Third party imports
import numpy as np
import tensorflow as tf
import torch
# Local imports
class Test_Binary_Class(unittest.TestCase):
def test_nullify(self):
input_numpy = np.array([[1.,0.,0.,1.,0.,1.,1.,0.]])
self.assertEqual(nullify_all(... |
class Solution:
def isInterleave(self, s1, s2, s3):
return self.f(s1, s2, s3)
from functools import lru_cache
@lru_cache(maxsize=None)
def f(self, s1, s2, s3):
if (s1 == '' and s2 == '') or s3 == '':
return s1 == s2 == s3 == ''
return (self.f(s1[1:], s2, s3[1:]) if s... |
'''
Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
'''
'''
Single Number II
Given an array of integers, every element appears three times exc... |
""" Client App """
from flask import Blueprint, render_template, send_file
from os import path
from . import Config
client_bp = Blueprint('client_app', __name__,
url_prefix='',
static_url_path='',
static_folder='./dist/static/',
t... |
# Ternary operators
order_total = 247
# If/else form
if order_total > 100:
discount = 25
else:
discount = 0
print(order_total, discount)
# Ternary form
discount = 25 if order_total > 100 else 0
print(order_total, discount)
|
from datetime import datetime, timedelta
from typing import Any, Union
from auth.core.config import settings
from jose import jwt
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
ALGORITHM = "HS256"
def create_access_token(
subject: Union[str, Any],
... |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
from random import *
def getLatLong(line):
splitLine = line.split(",")
return "" + str(splitLine[21]) + "," + str(splitLine[20]) + ",0"
sourceFile = open("data/parking.csv", "r")
targetFile = open("data/parking.kml", "w")
targetFile.write('<?xml version="1.0" encoding="UTF-8"?>')
targetFile.write('<kml xmlns="http... |
import os, tempfile
from seamless.highlevel import Context, Cell
ctx = Context()
ctx.a = 10
ctx.a.celltype = "json"
ctx.b = 30
ctx.b.celltype = "json"
def build_transformer():
ctx.transform = lambda a,b: a + b
ctx.transform.example.a = 0
ctx.transform.example.b = 0
ctx.result = ctx.transform
ctx... |
# python3
# This is for annotation convert.
# It can convert VOC xml format to YOLO txt format.
# YOLO txt format can be trained in YOLOv4(darknet exe file).
#
# The experiment dir is VOC2007.
import sys
import os
from absl import app, flags
from absl.flags import FLAGS
from lxml import etree
flags.DEFINE_string(
... |
import os
from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from .forms import UploadFileForm
from .file_handling import read_csv, make_csv
from .models import create_tokens
# Workflow
# Gleaners end
# This will be through a su... |
from setuptools import find_packages, setup
setup(
name="spellingbee",
version="1.0",
packages=find_packages(),
license="Private",
description="Spelling bee for Kids on Mac",
author="sukhbinder",
author_email="sukh2010@yahoo.com",
entry_points={
'console_scripts': [' ... |
def has_negatives(a):
negatives_map = {(-n): None for n in a if n < 0}
positives_map = {(+n): None for n in a if n > 0}
matches = [n for n in positives_map if n in negatives_map]
return matches
if __name__ == "__main__":
print(has_negatives([-1, -2, 1, 2, 3, 4, -4]))
|
#!/usr/bin/env python
import socket
import argparse
parser = argparse.ArgumentParser(description='RCE in Nostromo web server through 1.9.6 due to path traversal.')
parser.add_argument('host',help='domain/IP of the Nostromo web server')
parser.add_argument('port',help='port number',type=int)
parser.add_argumen... |
"""CoinGecko model"""
__docformat__ = "numpy"
# pylint:disable=unsupported-assignment-operation
import logging
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
import regex as re
from pycoingecko import CoinGeckoAPI
from openbb_terminal.cryptocurrency.dataframe_helper... |
import pandas as pd
import os
import re
import shutil
class Allocator:
directory = "/home/zeski/Documents/PythonLessons/MachineLearning/Projects/DiabeticRetinopathy"
def __init__(self, file):
self.file = file
def file_locator(self):
"""
This method will walk through the project Fo... |
import tensorflow as tf
from google.protobuf.json_format import MessageToJson
file = '/home/derin/datasets/WIDER/WIDER_train/tfrecord'
fileNum = 1
for example in tf.python_io.tf_record_iterator(file):
jsonMessage = MessageToJson(tf.train.Example.FromString(example))
with open("RESULTS/image_{}".format(fileNum)... |
from abc import ABCMeta,abstractmethod
import numpy as np
import math
from sklearn.ensemble import RandomForestClassifier as RFClassifier
from sklearn import svm
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier as DTClassifier
from sklearn.linear_model impor... |
"""
\file Karma.py
\brief This file contains a plugin that provides a karma system for anything
"""
from PluginInterface import *
import MySQLdb
class Karma(PluginInterface):
"""
\brief An universal karma class
This class provides karma to any class of objects that is indexed
via integers. Users... |
"""
indexer exposes a function inex_docs which if given a data file,
processes every line of that file, builds an inverted index from unigrams to a list of Document objects.
"""
from collections import Counter
from typing import List, Dict, Tuple
from nltk.corpus import stopwords
from nltk.tokenize import word_token... |
#!/usr/bin/env python
"""
Created by howie.hu at 2021-04-08.
Description:模型训练库
Changelog: all notable changes to this file will be documented
"""
from .cosine_similarity import CosineSimilarity
|
# LookupTables
## This class is deprecated. It has been replaced by the table lpts_script_codes
class LookupTables:
def scriptCode(script):
scriptDic = {
"Amharic":"Ethi",
"Arabic":"Arab",
"Armenian":"Armn",
"Bengali":"Beng",
"Bengali Script":"Beng",
"Berber":"Tfng",
"Burmese":"Mymr",
... |
#!/usr/bin/env python
from pymongo import Connection
import gridfs
import mimetypes
import json
import datetime,time
import hashlib,uuid,base64
from bson.objectid import ObjectId
class snapshotNode(object):
"""
Class snapBuffer maintain the frames of snapshot pngs to the test case
"""
def __init__(sel... |
from pymongo import MongoClient
import re
'''DB Insert requests'''
#add new artists to our DB
def add_artists(artists):
for artist in artists:
entry = {
'id' : int(artists[artist]['id']),
'name' : artists[artist]['name'],
'url' : artists[artist]['url'],
}
... |
#!/usr/bin/python
import sys, os
import string, re
import numpy as np
import math
import matplotlib.pylab as plt
from sortedcontainers import SortedDict
from collections import defaultdict
from plsa_sparse import PLSA
# Vocabulary filepath
voc_fname = os.path.join('voc.txt')
# Documents filepath
#docs_fpath = os.pat... |
import sqlite3
class Introduction:
def __init__(self):
self.con = sqlite3.connect("user_information.db", check_same_thread=False)
self.cur = self.con.cursor()
self.cur.execute("""CREATE TABLE IF NOT EXISTS introductions (
user text not null,
content text not... |
import random
class Bird:
def __init__(self, row, col, type_of):
self.row = row
self.col = col
self.type_of = type_of
self.picture_taken = False
def picture(self):
self.picture_taken = True
class Coordinates:
def __init__(self, height, width, num_of_bi... |
import io, math, struct
from collections import OrderedDict
from struct import Struct
from Catalog.Identifiers import PageId, FileId, TupleId
from Catalog.Schema import DBSchema
import Storage.FileManager
class BufferPool:
"""
A buffer pool implementation.
Since the buffer pool is a cache, we do no... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.IndexBigbuyItem import IndexBigbuyItem
from alipay.aop.api.domain.IndexBlockBanner import IndexBlockBanner
class KoubeiMemberDataItemBigbuyQueryResponse... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 12:56:19 2018
comp_syntax
"""
from random import choice
from collections import defaultdict
class State(object):
def __init__(self, POS, output, transitions):
self.POS = POS
self.output = output
self.transitions = transitions... |
# Generated by Django 3.2 on 2021-05-30 09:10
from decimal import Decimal
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0006_auto_20210530_1154'),
]
operations = [
migrations.AlterFi... |
from invoke import task
@task
def view(c):
"""View the resume."""
c.run("xdg-open resume.pdf")
@task
def work(c):
"""Build the resume on change."""
c.run("watchmedo tricks tricks.yaml")
|
import base64
import configparser
import io
import urllib
from requests import Session
from .certs import install_intel_certs
class GLSession(Session):
"""a Session wrapper for gitlab api"""
def __init__(self, url, token):
install_intel_certs()
self._project_ids = {}
url = url.rstrip... |
from dialog_api import messaging_pb2
from dialog_bot_sdk.entities.Avatar import Avatar
class ServiceExt:
def __init__(self, changed_about: str, changed_avatar: Avatar, changed_title: str,
changed_topic: str, user_invited: int, user_kicked: int) -> None:
self.changed_about = changed_about... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 14:28:09 2020
@author: MarcoAmicabile
@description:
The script call the Keyforge API Decks to retrieve decks and cards data.
The API Call is parametric on results pagesize
The results are formatted and consolidated into SQL Server DB
PY Script API ... |
from django.contrib import admin
from django import forms
from .models import Building, Suite
admin.site.register(Building)
admin.site.register(Suite)
|
import pandas
df2=pandas.read_csv("C:\Lokesh\Repositories\pandas\pandasExercises\supermarkets.csv")
print(df2)
print(".......................................................................")
#setting index ID
df3=df2.set_index("ID")
print(df3)
print("....................................................................... |
# pode-se utilizar a função continue para saltar durante o while
# e break para parar o código
# ex:
x = 0
while x < 10:
if x == 5:
x = x + 1 # é necessário colocar novamente o contador se não bugga
continue
print(x)
x = x + 1
# no código acima imprimiu de 0 a 9 saltando o 5 pois eu inform... |
#!/usr/bin/env python3
import argparse
import logging
import json
import os
import sys
import traceback
import time
import Constants
import FoscamImager
import Mailer
import NetHelpers
# import TFOneShot ## Imported on demand
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = "ML detector for ... |
from local_mode import file_exists, request
def files_exist(opt_ml, files):
for f in files:
assert file_exists(opt_ml, f), 'file {} was not created'.format(f)
def predict_and_assert_response_length(data, content_type):
predict_response = request(data, request_type=content_type)
assert len(predic... |
def list_sort(L):
for x in range(len(L) - 1):
for y in range(x + 1,len(L)):
if L[x] > L[y]:
L[x],L[y] = L[y],L[x]
L = [2,5,9,1,11,18,21,4]
list_sort(L)
print(L) |
from math import factorial
fact = factorial(100)
sum = 0
for c in str(fact):
sum += int(c)
print (sum)
print(1/997) |
import os
import tempfile
from collections import OrderedDict
from zipfile import ZipFile
import dateutil.parser
from django import forms
from django.db.models import Exists, OuterRef, Q
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _
from pretix.base.models import OrderPay... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 10 16:53:24 2015
@author: Lothas
"""
import vrep
import math
def vec_length(vec):
length = 0
for i in vec:
length += i*i
length = math.sqrt(length)
return length
class Pioneer3D:
def __init__(self, clientID, name):
self.clientI... |
from sys import stdin
# 이분 탐색으로 풀기
N = int(stdin.readline())
num_list = sorted(list(map(int, stdin.readline().split())))
M = int(stdin.readline())
M_list = list(map(int, stdin.readline().split()))
def binary_search(my_list, key):
left, right = 0, N-1
while left <= right:
mid = (left + right)//2
... |
for _ in range(int(input())):
sound = input().split()
animal = []
s = input()
while s != 'what does the fox say?':
animal.append(s.split()[2])
s = input()
for x in sound:
if x not in animal:
print(x, end=' ') |
from . import branch, lambda_, sequential
__all__ = sum(
[m.__all__ for m in [
branch, lambda_, sequential,
]],
[]
)
from .branch import *
from .lambda_ import *
from .sequential import *
|
import numpy as np
import cv2
from matplotlib import pyplot as plt
import random
def augment(xys):
axy = np.ones( (len(xys), 1, 3) )
axy[:, :, :-1] = xys
return axy
def estimate(pairs, print_=False):
A = np.zeros((1,6))
b = np.zeros((1,1))
for i in range(len(pairs)):
# print pairs[i][0... |
import os
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
class MyUserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('Email must be set')
email = se... |
#
# Copyright 2021 The University of Queensland
# Author: Alex Wilson <alex@uq.edu.au>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, ... |
# Write a program that accepts a sentence and replace each occurrence of ‘python’ with ‘pythons’ without using regex
string_a = input("Enter the string to be replaced: ") # Accept the string from user
string_b = string_a.replace("python", "pythons") # replace the python word with pythons
print("Origin... |
from baselines.hdbscan import HDBSCAN
from baselines.meanshift_wrapper import MeanShiftWrapper
from baselines.completelinkage import CompleteLinkage
from baselines.singlelinkage import SingleLinkage
from mod_shift.ModShiftWrapper import ModShiftWrapper
def get_clusterer(method, config, target_dir, dataset=None):
... |
"""
Name: Dhruvin Modi
E-Mail: dhruvinmodi2015@gmail.com
"""
import random
import numpy as np
import matplotlib.pyplot as plt
class network(object):
def __init__(self,sizes):
self.sizes = sizes
self.weights = [np.random.randn(y,x) for x,y in zip(sizes[:-1],sizes[1:])]
self.biases = [np.random.randn(x,1) for x in... |
import tensorflow as tf
import numpy as np
from functools import reduce
import sys
sys.path.insert(0, '/home/nagy729krisztina/M4_treedom')
import config as cfg
class Vgg19:
######################################################
# Load variables form npy to build the VGG
# Args:
# vgg19_npy_pat... |
import re, requests, json
from config import setting
from encoder import UniversalEncoder
encoder = UniversalEncoder(setting.use_host,setting.use_port)
def pare(data:str):
data.replace("&","and")
data = data.lower()
data = re.sub(r"[^a-zA-Z0-9]+"," ",data)
data = data.strip()
data = re.sub(r"\s+",... |
import hashlib
import random
from datetime import datetime
'''
This module contains all methods needed to create and validate the proof of work
needed by our nse algorithm.
A PoW is a hash with n leading 0 from the round-time and a random number.
'''
# Function to create the PoW from the round-time and a ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A python 3.6+ script to send a batch of transactions from a CSV file.
Note that this script must be in the same directory as the CLI binary.
Due to a possible Nonce mismatch, it is recommended to NOT have 1 'from' address/wallet
appear in multiple CSV files that are ... |
"""
Script that takes a file list from the config directory (typically files.txt)
and then creates files with selections of training files and testing files.
Usage:
python split-file-list FILELIST TRAINING_BASE TESTING_BASE TRAINING_SIZE TESTING_SIZE
FILELIST - list with all the files in the corpus, w... |
# def get_endpoints_current_user(raise_unauthorized=True):
# """Returns a current user and (optionally) causes an HTTP 401 if no user.
#
# Args:
# raise_unauthorized: Boolean; defaults to True. If True, this method
# raises an exception which causes an HTTP 401 Unauthorized to be
# ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
#https://www.hackerrank.com/challenges/swap-case
ans=""
for s in raw_input():
value=ord(s)
if value>64 and value<91:
value=value+32
elif value>96 and value<123:
value=value-32
ans=ans+chr(value)
print ans
|
import cv2
#importing the cascade from the xml file
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')
#detection functions
def detect(gray, frame):
#x and y coordinate... |
#!/bin/python3
import yfinance as yf
import matplotlib.pyplot as plt
import datetime
import sys
import os
if not sys.argv[1:]:
print("Add stock names to generate graphs for")
exit(1)
stocks = [ x.upper() for x in sys.argv[1:] ]
savePath = "./stocks/"
if not os.path.exists(savePath):
os.makedirs(sav... |
import numpy as np
import pandas as pd
from pymer4.models import Lmer
import matplotlib.pyplot as plt
from matplotlib import cm
import statsmodels.api as sm
import statsmodels.formula.api as smf
# Create Pseudodata
def generate_pseudodata(n_mice, n_sessions, n_trials, fixed_effect, mouse_effect, mouse_in... |
#"""Analyse frequency distribution of words"""
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
sw = stopwords.words("english")
sw = set(sw)
print(f"{len(sw)} stopwords used: {sorted(sw)}")
path = "data/csv/vocab.csv"
#path = "data/txt/1980.txt"
limit = 10**8
with open(path) as f:
text =... |
"""
Aprimore o desafio anterior, mostrando no final:
A) A soma de todos os valores pares digitados.
B) A soma dos valores da terceira coluna.
C) O maior valor da segunda linha.
"""
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
somaPares = 0
somaColTres = 0
maiorValor = 0
for l in range(0,3):
for c in range(0,3):
... |
# coding: utf-8
from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.adaptive_quant_mode import AdaptiveQuantMode
from bitmovin_api_sdk.models.auto_level_setup import AutoLevelSetup
from bitmovin_api_sdk.models.b_adapt im... |
""" Customfield.
Do not edit this file by hand.
This is generated by parsing api.html service doc.
"""
from ambra_sdk.exceptions.service import AccountNotFound
from ambra_sdk.exceptions.service import AlreadyExists
from ambra_sdk.exceptions.service import FilterNotFound
from ambra_sdk.exceptions.service import Invalid... |
from django.conf.urls import url
from django.urls import path, include
from blogapp import admin, views
app_name = 'blogapp'
urlpatterns = [
# url(r'^index/$',views.index,name='index'),
url(r'^$', views.index, name='index'),
url(r'^detail/(\d+)/$', views.detail, name='detail'),
url(r'^contact/$', view... |
from django.contrib import admin
from .models import PhoneDevice
class PhoneDeviceAdmin(admin.ModelAdmin):
"""
:class:`~django.contrib.admin.ModelAdmin` for
:class:`~two_factor.plugins.phonenumber.models.PhoneDevice`.
"""
raw_id_fields = ('user',)
admin.site.register(PhoneDevice, PhoneDeviceAdm... |
# ./picdef.py
# -*- coding: utf-8 -*-
# PyXB bindings for NM:e879668f01fce2c06e252084699d6bc0827cd581
# Generated 2017-09-27 17:50:38.342662 by PyXB version 1.2.6 using Python 3.5.2.final.0
# Namespace sptdf
from __future__ import unicode_literals
import pyxb
import pyxb.binding
import pyxb.binding.saxer
import io
imp... |
#!/usr/bin/env python
import sys
import os
import hifive
import numpy
# open(sys.argv[1])
# hic = hifive.HiC('week13.hcp')
#
# data = hic.cis_heatmap(chrom='chr17', start=15000000, stop=17500000, binsize=10000, datatype='fend', arraytype='full')
# print(data)
list_of_midpoints = []
for line in open(sys.argv[1]):
... |
# Generated by Django 2.1.2 on 2019-01-31 11:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mrp_system', '0082_purchaseorderparts_total'),
]
operations = [
migrations.AlterField(
model_na... |
from collections import defaultdict
with open('input.txt', 'r') as input_file:
lines = input_file.readlines()
parse_ticket_info = True
parse_my_ticket = False
parse_other_tickets = False
my_ticket = []
tickets = []
valid_tickets = []
keys = []
field_limits = {}
for line in lines:
if line == '\n':
par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.