text stringlengths 8 6.05M |
|---|
import importlib
import game.bitboard as bitop
import game.util as util
def run(module_name_1, module_name_2, N=1000):
m1 = importlib.import_module(module_name_1)
m2 = importlib.import_module(module_name_2)
modules = [m1, m2]
wins = [0, 0]
for i in range(N):
arr = util.initial_setup()
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from sklearn import naive_bayes
from models.binary_classifier import BinaryClassifier
class GaussianNB(BinaryClassifier, naive_bayes.GaussianNB)... |
#!/usr/bin/env python3
# Write a Shannon entropy calculator: H = -sum(pi * log(pi))
# Use fileinput to get the data from nucleotides.txt
# Make sure that the values are probabilities
# Make sure that the distribution sums to 1
# Report with 3 decimal figures
"""
python3 entropy.py nucleotides.txt
1.846
"""
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from pyspark import SparkContext, SparkConf
def create_mutual_friends(line):
person = line[0].strip()
friends = line[1]
if(person != ''):
person = int(person)
final_friend_values = []
for friend in frie... |
# Generated by Django 2.2.1 on 2019-05-07 17:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portalapp', '0007_loggedissue'),
]
operations = [
migrations.AddField(
model_name='loggedissue',
name='url',
... |
import base64
base64_message = input("Enter base64 String: ")
base64_bytes = base64_message.encode('ascii')
message_bytes = base64.b64decode(base64_bytes)
message = message_bytes.decode('ascii')
print("Decoded Message: " + message)
|
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class timeSheetEntry(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
start = models.DateTimeField()
end = models.DateTimeField()
time = models.IntegerField()
comm... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 19:24:29 2020
@author: user
"""
import torch.nn as nn
class Encoder(nn.Module):
def __init__(self, isize, nz, nc, ndf, ngpu, n_extra_layers=0, add_final_conv=True):
super(Encoder,self).__init__()
self.ngpu = ngpu
assert 16 %... |
#[LeetCode] 130. Surrounded Regions_Medium tag: DFS/BFS |
_ID_LIST = {'Server' :
(({'name':'Server', 'id':int()}), ({'name':'channel', 'id':int()})),
### ^ Dictionary is set up in this format, actual servers omitted for privacy purposes
}
_SERVER = 'Server'
default_guild = _ID_LIST[_SERVER][0]
default_channel = _ID_LIST[_SERVER][1]
limit =... |
# Generated by Django 3.0.7 on 2020-06-19 09:45
from django.db import migrations
def fill_new_admin_field(apps, schema_editor):
Restaurant = apps.get_model("foodcartapp", "Restaurant")
for restaurant in Restaurant.objects.all():
restaurant.new_admin = restaurant.admin.user
restaurant.save()
... |
import pdfx
import os
import sys
from os import walk
import csv
import git
# [filter(lambda item: "docker" in item or "github" in item or "pdf" in item, link_list) for link_list in l]
def main():
#path = "/mnt/c/Users/Fjona/Desktop/2018-2019/UROP/icse/2018/pdfs/ICSE2018-7hDWfdAOTaSxSTuYmZ7C9S/73vOGjBk... |
"""
Most codes from https://github.com/carpedm20/DCGAN-tensorflow
"""
from __future__ import division
import math
import random
import pprint
import scipy.misc
import numpy as np
from time import gmtime, strftime
from six.moves import xrange
import os, gzip
import csv
from PIL import Image
from random import randint
i... |
from __future__ import division
from __future__ import print_function
import sys
import os
import torch
from torch.autograd import Variable
from collections import OrderedDict
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import torch.optim as opti... |
# coding=UTF-8
import math
import operator
lista = [2, 6, 4, 7, -2]
if all(i % 2 == 0 for i in lista):
print("Todos são pares.")
else:
print("Tem algum impar.")
print("")
if not any(i <= 0 for i in lista ):
print("Todos são positivos.")
else:
print("Tem algum negativo.")
print("")
lista1 = [1, 4,... |
import cv2
import numpy as np
input = cv2.imread("./Desktop/OpenCV/Basics/hand.jpg")
# input.shape return tuples with three value. The first value represent height(x-coordinate), second value
# represent width(y-coordinate) and third value represent returns '3L' which are the RGB values of an Image
print input.shape
pr... |
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, HttpResponseRedirect, HttpResponse
from .models import UserProfile
from .forms import UserForm
from neighborhood.models import Neighborhood, House
from feed.forms i... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-04-05 06:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('water_watch_api', '0007_auto_20180404_1952'),
]
oper... |
# A~F 중 한 숫자 입력받기
num = input()
num = int(num, 16)
for i in range(1, 16):
print('%X' % num, '*%X' % i, '=%X' % (num * i), sep='') |
__author__ = 'YY20' |
# Bài 01: Viết chương trình tính tổng, tích của các phần tử trong một list.
my_list = [0, 1, 2, 3, 8, 5, 6, 7, 8, 9]
tong = 0
tich = 1
for i in range(len(my_list)) :
tong += my_list[i]
tich *=my_list[i]
print(tong)
print(tich)
|
def display(hash_table):
for i in range(len(hash_table)):
print(i, end = " ")
for j in hash_table[i]:
print("->", end = " ")
print(j, end = " ")
print()
def hash(key):
return key % len(hash_table)
def insert(hash_table, key, value):
hash_key = hash(key)
... |
# TODO: Autenticação com usuário e senha para acessar usa conta
# TODO: Manter o saldo atualizado em um arquivo JSON
# TODO: Manter um histórico de depósitos e saques e permitir gerar um extrato detalhado
def menu_deposito():
return float(input('Digite o valor para depósito: R$ '))
def menu_saque():
return... |
import jsonlines
import sys
import os
from shutil import copyfile
import argparse
import pdb
import pickle
import numpy as np
from nltk.tokenize import sent_tokenize
from tqdm import tqdm
sys.path.append('/data/rsg/nlp/darsh/aggregator/crawl_websites/NUT/')
from gather_annotations import _perform_tagging, _read_entity... |
# -*- coding: utf-8 -*-
import docutils.core
# All information about reStructeredText is here
# http://docutils.sourceforge.net/docs/user/rst/quickref.html
rest = '''
=======
Heading
=======
SubHeading
----------
This is just a simple
little subsection. Now,
we'll show a bulleted list:
- item one
- item two
- item ... |
from test.core.derivatives.implementation.base import DerivativesImplementation
import torch
from backpack.hessianfree.hvp import hessian_vector_product
from backpack.hessianfree.lop import transposed_jacobian_vector_product
from backpack.hessianfree.rop import jacobian_vector_product
class AutogradDerivatives(Deri... |
#!/usr/bin/env python
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""
Demo script showing detections in sample i... |
import enum
import itertools
import string
import typing
from .number_set import NumberSet
class AreaType(enum.Enum):
ROW = 0
COLUMN = 1
BLOCK = 2
def __init__(self, index):
self._index = index
@property
def index(self):
return self._index
def orthogonal_type(self) -> '... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" AvroSerializer class
Serialize / Deserialize record to avro schema
Note:
In schemas folder your avro file must have the *avsc.yaml* extension
Todo:
* Remove workaround in constructor (os.path ...)
"""
import json
import os
import re
from... |
#!/usr/bin/env python
# Level Script
# Use scene.when to schedule events.
# Yield when you want to wait until the next event.
# This is a generator. Using a busy loop will halt the game.
from math import tau, pi
from game.constants import GREEN
from game.scripts.level import Level
class Level2(Level):
number ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 该自定键值映射参照数据库设计文档
light_color = {
1 : 'white',
2 : 'blue',
3 : 'yellow',
}
class PolicyInstance:
"""
策略实例类型
"""
#: 实例号
instance_id = -1
#: 策略号
policy_id = -1
#: 植被号
plant_id = -1
#: 房间号
room_i... |
from django.contrib import admin
from .models import Bootcamp, User, Course, Review
# Register your models here.
admin.site.register(User)
admin.site.register(Bootcamp)
admin.site.register(Course)
admin.site.register(Review)
|
""" gps_util.py - parsing of GPS messages """
import datetime,traceback,logging,time,sys,math
from common import UTC,excTraceback,hexDump,parseTimeString
from tl_logger import TLLog,logOptions
log = TLLog.getLogger( 'gps' )
logGPSD = TLLog.getLogger( 'GPSD' )
logGpsData = TLLog.getLogger( 'gpsdata' )
class Satellite(... |
# -*- coding: utf-8 -*-
"""Utils."""
from zope.component import getUtility
from plone.behavior.interfaces import IBehavior
# from plone.memoize.ram import cache
from dexterity.localrolesfield.interfaces import IBaseLocalRoleField
def cache_key(fun, fti):
return fti
# @cache(cache_key) a test with profilehooks... |
from django.conf.urls import url, include
#from django.views.generic import TemplateView
from . import views
urlpatterns = [
# url(r'^shipping-address/$', TemplateView.as_view(
# template_name='users/user_shipping_address_view.html')),
url(r'^shipping-address/$',
views.ShippingAddressView.as_view... |
#!python
# Fetch one or more book's fpgen source from fadedpage,
# rerun fpgen, and send the resulting mobi
# output back to fadedpage.
#
# scp should be setup to work without a password
#
# Args is a list of fadedpage book ids
# Old .mobi file is left in 20######.save.mobi
# New .mobi file is left in 20######.mobi
i... |
import os.path as osp
import pandas as pd
from .manager import BaseManager
from utils import seed_everything, make_datapath_list
from dataset import TrainDataset, Anno_xml2list, DataTransform, od_collate_fn, get_dataloader
from models import ObjectDetectionModel
class Train(BaseManager):
def __call__(self):
... |
#!/usr/bin/env python3
import sys
def main(inputfile):
with open(inputfile, 'r') as rd:
print("Resulting frequency:", find_rep_freq(0, rd))
def find_rep_freq(start, rd):
current = start
counter = 0
mutations = [int(x.strip()) for x in rd.readlines()]
max_mut = len(mutations)
found_fr... |
#!/usr/bin/python
import requests,pprint,bs4
page=requests.get('https://dataquestio.github.io/web-scraping-pages/simple.html')
print(page)
print(page.status_code) #print status code
#print(page.content) #print the content of the page
#from bs4 import BeautifulSoup
#soup=BeautifulSoup(page.content,'html.parser')
#prin... |
#Worked
prefix = "ffmpeg -i gd691108d"
d_v = 1
t_v = 1
mids = ".shn gd69-11-08-"
nt_v = 1
file = open("slate2.txt", "w")
def tracks():
global t_v
global nt_v
file.write("\n" + prefix + str(d_v) + "t0" + str(t_v) + mids + "0" + str(nt_v)+".flac"+"\n")
t_v += 1
nt_v += 1
def trackx():
global t_v
global nt_v
... |
import json
import datetime
import h5py
import numpy as np
from pelops.datasets.chip import ChipDataset, Chip
class FeatureDataset(ChipDataset):
def __init__(self, filename):
super().__init__(filename)
self.chip_index_lookup, self.chips, self.feats = self.load(filename)
self.filename_lookup... |
import time
from inc import *
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def CheckTable(tablename):
conn, cursor = Mysql()
try:
cursor.execute("select count(1) from `%s` limit 1" %(tablename))
except:
print "%s not exist" % (tablename)
print "%s exist" % (tablen... |
import splitter
import unittest
class TestSplitFunction(unittest.TestCase):
"""docstring for TestSplitFunction"""
# def __init__(self, arg):
# super(TestSplitFunction, self).__init__()
# self.arg = arg
def setUp(self):
pass
def tearDown(self):
pass
def testSimpleString(self):
r = splitter.split('Goog 100 4... |
from rest_framework import permissions
from rest_framework.permissions import IsAdminUser
class IsOwner(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it or see it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are all... |
import torch
import transformers
import turbo_transformers
from turbo_transformers.layers.utils import convert2tt_tensor, try_convert, convert_returns_as_type, ReturnType
import time
model = transformers.BertModel.from_pretrained('bert-base-uncased')
model.eval()
torch.set_grad_enabled(False)
bertlayer = model.encode... |
from django.http import Http404, HttpResponse
from rest_framework import generics
from rest_framework.generics import get_object_or_404
from clasificador.models import ClassifierModel
from documentos.models import DocumentGroup
from gerente.datatxt_helpers import Datatxt
from pruebas.models import BaseTestResult, Docum... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def fetcher(obj, index):
"""该函数用于索引"""
return obj[index]
x = [1, 2]
try:
fetcher(x, 4)
except IndexError:
print('got exception!')
print('contining...')
|
from django.contrib import admin
from .models import StaffMember, Department
@admin.register(StaffMember)
class StaffMemberAdmin(admin.ModelAdmin):
list_display = (
'id',
'name',
'work_department',
'phone_num',
'grade',
'school_department',
... |
try:
from kfp.components import InputPath
from kfp.components import OutputPath
except ImportError:
def InputPath(c):
return c
def OutputPath(c):
return c
metrics = "Metrics"
def wikiqa_test(
dataset_path: InputPath(str),
wikiqa_path: InputPath(str),
prev_model_path: In... |
import glob
import os
import re
import cv2
import face_recognition as fr
# predictor_path = 'dlib_data/shape_predictor_5_face_landmarks.dat'
# face_rec_model_path = 'dlib_data/dlib_face_recognition_resnet_model_v1.dat'
known_people_folder = 'images'
cam = cv2.VideoCapture(0)
color_green = (0, 255, 0)
line_width = 2... |
import sys
if len(sys.argv) != 3:
print("Usage: python convert_shp_to_json.py SHAPE_FILE OUT_FILE")
exit(2)
print("Importing modules...")
import geopandas as gpd
print("Reading file...")
gdf = gpd.read_file(sys.argv[1])
print("Writing to file...")
jsonfile = gdf.to_json()
with open(sys.argv[2], "w+") as f:
... |
"""
This app creates an animated sidebar using the dbc.Nav component and some local
CSS. Each menu item has an icon, when the sidebar is collapsed the labels
disappear and only the icons remain. Visit www.fontawesome.com to find
alternative icons to suit your needs!
dcc.Location is used to track the current location, ... |
from hue import HueControlUtil as hue
from wemo import WemoControlUtil as wemo
from alexa import AlexaControlUtil as alexa
from googleApis.googleSheetController import GoogleSheetController
from googleApis.googleDriveController import GoogleDriveController
from googleApis.gmailController import GmailController
import t... |
# Generated by Django 2.2 on 2019-04-26 08:18
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='card',
name... |
from rest_framework import serializers
from watchlist_app.models import WatchList, StreamPlatform, Review
class ReviewSerializer(serializers.ModelSerializer):
review_user = serializers.StringRelatedField(read_only=True)
class Meta:
model = Review
exclude = ('watchlist',)
# fields = "_... |
# Service monitor - updates the service status every configured interval
# Service configruations refer
from pprint import pprint
import urllib2
import json
import base64
import time
import ConfigParser
import os
import sys
from monitors.baseMonitor import BaseMonitor
import ha_engine.ha_infra as infra
# ===========... |
from charm.adapters.ibenc_adapt_hybrid import HybridIBEnc
from charm.adapters.ibenc_adapt_identityhash import HashIDAdapter
from charm.schemes.ibenc.ibenc_bb03 import IBE_BB04
from charm.schemes.ibenc.ibenc_bf01 import IBE_BonehFranklin
from charm.schemes.ibenc.ibenc_ckrs09 import IBE_CKRS
from charm.schemes.ibenc.iben... |
from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title('Dropdown Meny')
root.iconbitmap('images/diablo.ico')
root.geometry("200x200")
def show():
lbl = Label(root, text=clicked.get()).pack()
options = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Sat... |
# Generated by Django 2.2.7 on 2020-01-15 09:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('statics', '0013_auto_20200114_2217'),
]
operations = [
migrations.AddField(
model_name='review',
name='index',
... |
import os
import time
source = ['/Users/YanYu/Desktop/']
target_dir = '/Users/YanYu/Desktop/'
target = target_dir+time.strftime('%Y%m%d%H%M%S')+'.zip'
zip_command = "zip -qr '%s' %s"%(target, ''.join(source))
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup failed' |
from collections import OrderedDict
favorite_languages=OrderedDict()
favorite_languages['a']='python'
favorite_languages['b']='c++'
favorite_languages['c']='c'
favorite_languages['d']='ruby'
for name,language in favorite_languages.items():
print(name.title()+" 's favorite_language is "+language.title()... |
import numpy as np
from qiskit import (
#IBMQ,
QuantumCircuit,
QuantumRegister,
ClassicalRegister,
execute,
Aer,
)
from math import pi
from qiskit.visualization import plot_histogram
from qiskit.tools.visualization import circuit_drawer
from rpy2 import robjects as robjects
def de... |
import random
import numpy as np
import matplotlib.pyplot as plt
def rand_seed(m, b, num=2):
# create empty list
x_coor = []
y_coor = []
label = []
# positive and negtive point number
pos_num = int(num / 2)
neg_num = num - pos_num
# random create point
for i in range(pos_num):
... |
"""
Edanur Demir
EENet models
"""
from torch import nn
from flops_counter import get_model_complexity_info
from resnet import ResNet, ResNet6n2
__all__ = ['EENet',
'eenet18', 'eenet34', 'eenet50', 'eenet101', 'eenet152',
'eenet20', 'eenet32', 'eenet44', 'eenet56', 'eenet110',]
def ... |
# Greg Elgin, Connor Hamilton
# CS 205: Warm up project
# Last Updated: 02/10/20
# Parsing system to take a string input and return token values
# Calls query function with tokens as parameters
import shlex
region_list = ["Great Lakes", "Harrisburg Scranton", "Hartford Springfield", "Houston", "Indianapolis", "Jackso... |
"""SCT URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... |
############################################################################
# LOGISTIC REGRESSION #
# Note: NJUST Machine Learning Assignment. #
# Task: Binary Classification, Multi-class Classification. #
# Optimi... |
#coding:utf8
#https://www.jianshu.com/p/c307d04eee56
#1。适合度分析(拟合性分析)
# 某科学家预言抛一个色子,各面向上的几率都相同。为了验证自己理论的正确性,该科学家抛了600次硬币,
# 结果为一点102次,二点102次,三点96次,四点105次,五点95次,六点100次。
# 显然这个结果和理论预期并不完全一样,那么,科学家的理论有错吗?我们就用Python来验证一下。
from scipy import stats
import numpy as np
from scipy import stats
obs = [102, 102, 96, 105, 95, 100]... |
from flask import render_template, redirect
import helper
def create_link():
return redirect('/')
def get_liks():
return render_template(
'index.html',
dar = helper.dar(),
user = 'teste'
)
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'winter2021_updated_nocheckboxes.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from P... |
import errno
import os
import pandas as pd
import math
import json
import time
from project_thesis.visualization.visualizer import (
visualize_solution,
visualize_test_instance,
)
class Instance:
def __init__(
self,
scooters: pd.DataFrame,
delivery_nodes: pd.DataFrame,
depo... |
import time
from django.core.exceptions import ValidationError
from rest_framework import serializers
def hh_mm_to_minutes(str_hh_mm):
"""Перевести строку формата 'HH:MM' во время."""
minutes = time.strptime(str_hh_mm, '%H:%M')
return minutes.tm_hour * 60 + minutes.tm_min
def interval_validator(value):... |
import urllib.request
from bs4 import BeautifulSoup
import csv
from time import sleep
import pandas as pd
import json
import urllib.request
import os
from PIL import Image
import yaml
import requests
import sys
import argparse
import Levenshtein
vol = 6
curation_uri = "https://raw.githubusercontent.com/nakamura196/ge... |
# https://wikidocs.net/42528
'''
Q1. 주어진 자연수가 홀수인지 짝수인지 판별해 주는 함수(is_odd)를 작성해 보자.
'''
def is_odd(num):
return '홀수' if num % 2 == 1 else '짝수'
print(is_odd(2))
'''
Q2. 입력으로 들어오는 모든 수의 평균 값을 계산해 주는 함수를 작성해 보자. (단 입력으로 들어오는 수의 개수는 정해져 있지 않다.)
'''
numbers = input('Input the numbers: ')
toString = filter(lambda x: x,... |
""" Script that streams the emotion detected in the camera feed to a local web-application.
Faces are detected in frames, then for each face detected in a frame, a rectangle is draw around the face. Once this is
done, the emotion displayed in the face is written to the rectangle.
There are a few errors in readings due ... |
from app import create_app
from config import Config
import os
import logging
import pytest
from pandas import DataFrame, read_csv
from flask_jwt_extended import create_access_token
TEST_ROOT: str = os.path.dirname(os.path.abspath(__file__))
TEST_USER: dict = {"id": 1, "username": "test", "password": "password"}
CSV... |
class Solution:
# @param A : string
# @param B : integer
# @return a list of integers
def findPerm(self, A, B):
"""
Just walk through an array of size B increasing or decreasing numbers as necessary,
keeping track of the current largest and smallest numbers, and then make a pass
... |
import socket
import sys
size = 1024
client= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('',8000)) #Leaving the host part blank means 'localhost'
print client.getsockname()
print '%'
name=''
while 1:
# read from keyboard
while not name:
name=raw_input("Name... |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
import time
class Team(models.Model):
"""
Team model class.
"""
scoreboard = models.ForeignKey('Scoreboard', related_name='teams', related_query_name='team')
... |
# a=[1,4,5,6,7,9,12,11]
# a.insertion_sort(a)
# print(a)
def insertionSort(arr):
i=1
while i>len(arr):
key = arr[i]
j = i+1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j += 1
arr[j+1] = key
arr = [12, 11, 13, 5, 6]
insertionSort(arr)... |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda interval: interval[1])
current_end, result = float("-inf"), 0
for interval in intervals:
if interval[0] >= current_end... |
print("LETTER K HAS BEEN SUCCESSFULLY EXECUTED") |
# -*- coding: utf-8 -*-
class Parser:
def __init__(self, tokens, tabelaDeSimbolos):
self.tokens = tokens # lista de todos os tokens lidos do arquivo
self.tokenAtual = "" # token sendo analisado no momento
self.posicaoAtual = 0 # posição do token atual na lista "tokens"
self.errosAtu... |
from operator import itemgetter
from collections import OrderedDict
from matplotlib import font_manager, rc, style
import requests, io, json
import matplotlib.pyplot as plt
import numpy as np
links = []
sourcePath = "/home/hanjung/intern/files/"
f = open("links_cpp.txt", "r")
#get the links which used on hashing.py
... |
# Generated by Django 2.2.4 on 2019-08-31 01:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20190831_0039'),
]
operations = [
migrations.AddField(
model_name='video',
name='filterpath',
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import time
from datetime import datetime
BITCOIN_PRICE_THRESHOLD = 10000
BITCOIN_API_URL = 'https://api.coinmarketcap.com/v1/ticker/bitcoin/'
IFTTT_WEBHOOKS_URL = 'https://maker.ifttt.com/trigger/{}/with/key/cMCIlvY3aJFHAY6C1bllqDBbPev0cIPfg5QXEWIuXr5'
def ... |
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.html import strip_tags
from tinymce import HTMLField
from filebrowser.fields import FileBrowseField
# Create your models here.
class Page(models.Model):
is_published = models.BooleanField(default=False, help_text='Check... |
### importing modules
####################################################################################
import sys
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.text import TextPath
from matplotlib.patches import PathPatch
from matplotlib.font_manager import FontProperties
##... |
#Map the column back to Gene
#Written by Ruiqi Zhong April 8, 2017
import pickle
import pandas
import glob
import csv
paths = glob.glob("KEGG_6k/*.pkl")
print paths
for path in paths:
gene_name = []
data = pickle.load(open(path,"rb"))
data = data[data.columns[[1]]]
for i in range(1,data.shape[0]):
... |
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import argparse
import os
from models import *
from utils import load_pretrained_net, fetch_target, fetch_nearest_poison_bases, fetch_poison_bases
from trainer import make_convex_polytope_poisons, train_network_with_poi... |
import os
import getopt
from dataclasses import dataclass
from config import Config
@dataclass
class Arguments():
verbose: bool = False
help: bool = False
target_dir: str = None
branch: str = None
commit_range: str = None
config: Config = None
@staticmethod
def helptext():
ret... |
n = int(input())
c, r, s = 0, 0, 0
for i in range(0, n):
q, e = input().split(' ')
if e == 'C':
c += int(q)
elif e == 'R':
r += int(q)
elif e == 'S':
s += int(q)
print('Total: {} cobaias'.format(c + r + s))
print('Total de coelhos: {}'.format(c))
print('Total de ratos: {}'... |
import numpy as np
import re
regex = 'position=<[ ]*(?P<x>\-*\d+),[ ]*(?P<y>\-*\d+)> velocity=<[ ]*(?P<vx>\-*\d+),[ ]*(?P<vy>\-*\d+)>'
p = re.compile(regex)
data = []
n_points = 0
with open('input.txt') as f:
for l in f:
match = p.match(l.strip()).groupdict()
data.append(
list(map(int, ... |
import collections
import itertools
import random
import sys
def frequentsets(k,prev,s,f):
if k==1:
dsingles={}
f=open("new_toivonen.txt")
for line in f:
line=line.rstrip()
items=line.split(',')
items.sort()
for item in it... |
# encoding: utf-8
'''
@Version: V1.0
@Author: JE2Se
@Contact: admin@je2se.com
@Website: https://www.je2se.com
@Github: https://github.com/JE2Se/
@Time: 2020/6/10 12:39
@File: StrutsScan.py
@Desc:
'''
from lib.ModelLoad import ONLoad
from lib import *
import os
import logging
dlist = []
#文件遍历
def StrutsSc... |
# 23415
# 13425 ++
# 12435 ++
# 12345 ++
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumSwaps function below.
def minimumSwaps(arr):
temp = [0] * (len(arr) + 1)
for pos, val in enumerate(arr):
temp[val] = pos
pos += 1
count = 0
for i in... |
import flask
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['GET'])
def home():
return "<iframe src='https://airtw.epa.gov.tw/AirQuality_APIs/WebWidget.aspx?site=18' width='320px' height='380px' scrolling='yes'></iframe><iframe src='https://airtw.epa.gov.tw/AirQuality_APIs/WebWi... |
import time
from selenium import webdriver
#브라우저 열기
browser = webdriver.Edge("./msedgedriver.exe")
#네이버로 이동
browser.get("http://naver.com")
#로그인 버튼 클릭
elem = browser.find_element_by_class_name("link_login")
elem.click()
time.sleep(3)
#로그인
browser.find_element_by_id("id").send_keys("naverID")
browser.find_element_... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
result = 0
l = 0
dict = set()
for r in range(len(s)):
if s[r] in dict:
while l < r:
if s[l] == s[r]:
l += 1
break
... |
from django import forms
class DateInput(forms.DateInput):
input_type = 'date'
class SearchForm(forms.Form):
start_date = forms.DateField(
label='Статистика с', widget=forms.widgets.DateInput(attrs={'type': 'date'}))
end_date = forms.DateField(
label='Статистика по', widget=forms.widgets... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.