text stringlengths 38 1.54M |
|---|
# coding:utf-8
'''
@Copyright:LintCode
@Author: ultimate010
@Problem: http://www.lintcode.com/problem/nth-to-last-node-in-list
@Language: Python
@Datetime: 16-06-18 11:23
'''
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = ... |
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
"""Test for Employee class"""
def setUp(self):
self.annual_salary = 22000
self.employee = Employee("Shafran", "Nawaz", self.annual_salary)
self.default_raise = 5000
self.custom_raise = 10000
... |
#encoding:utf-8
#主题与转换(Topics and Transformations)
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
#转换接口
from gensim import corpora, models, similarities
dictionary = corpora.Dictionary.load('./tmp/deerwester.dict')
corpus = corpora.MmCorpus('./tmp/deerw... |
#
# Create by Hua on 3/24/22.
#
"""
You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi.
You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to... |
"""
reate a program that will play the “cows and bulls” game with the user. The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, they have a “cow”.
For every digit the user guessed correctly in the wr... |
"""
Code by Zhujun and Zhijing, modified by Shinan
"""
import numpy as np
import sys
import os
import glob
import multiprocessing as mp
from keras.models import Sequential
from keras.layers import LSTM, Dense
from keras.callbacks import EarlyStopping
from keras.layers.core import Activation
from keras import backend a... |
import tkinter
#创建主窗口
win = tkinter.Tk()
#设置标题
win.title("Tracy")
#设置大小和位置
win.geometry("400x400+200+50") #长宽400 距离左侧200,上部50
#进入消息循环
'''
Label:标签控件,可以显示文本
'''
#win:父窗体
#text:显示文本内容
#bg:背景色
#fg:字体色
#wraplength:指定text文本中多宽后进行换行
#justify :设置换行后的对齐方式center lift right
#anchor:位置 n北,e东,s南,w西,ne东北,nw西北,se东南,sw西南,or center... |
#loops
carros=["HRV", "Golf", "Argo", "Focus"]
for x in carros: # inicializa sem parentes e ja criamos uma variavel dentro do for
print(x)
if(x=="Golf"):
print("VW")
#podemos ja usar
# for x ( ja cria a variavel)
# for x in (ja mostra qual array percorrer)
#python automaticamente pode criar a lis... |
import asyncio
"""
def afetch(stories):
full_text = []
async def fetch(url):
print("Task %s: Fetching..." % (url.text))
url.initialize()
await asyncio.sleep(.1)
full_text.append(url.text)
print("%s Complete." % (url.url))
... |
from SyncCourseData.models import Course
import json
import re
def load_class():
json_data = open('classes_up.json').read()
data = json.loads(json_data)
for token in data:
try:
name = token['class_name'][0]
num_pos = re.search('\d', name)
new_course = Course()
... |
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.minimal = []
self.data = []
self.length = 0
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.data.append(x)
sel... |
from typing import Dict, List, Optional
import logging
import traceback
import os
import time
from chat_thief.config.commands_config import OBS_COMMANDS
from chat_thief.audioworld.soundeffects_library import SoundeffectsLibrary
from chat_thief.chat_parsers.command_parser import CommandParser
from chat_thief.config.log... |
"""Script to download hub logs from S3 when they are ready."""
import os
import re
import sys
import boto3
from hublogs.wait import waitForFiles
def testValidHubId(hubid):
try:
pattern = b"[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}"
xre = re.compile(pattern)
... |
# coding:utf-8
import os
import re
import cv2
import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
root_dir = "./emotions_image/"
directory = os.listdir(root_dir)
categories = [f for f in directory if os.path.isdir(os.path.join(root_dir, f))]
num_classes = len(categories)... |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Faces of Madison</title>
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initia... |
import pydantic
from pydantic import BaseSettings
class Settings(BaseSettings):
"""Settings are loaded from .env."""
DATABASE_URL: pydantic.SecretStr
class Config:
"""Config options."""
frozen = True
env_file = ".env"
env_file_encoding = "utf-8"
settings = Settings()
|
# Generated by Django 3.1.3 on 2020-11-09 16:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('gallery', '0002_auto_20201109_1056'),
]
operations = [
migrations.AlterField(
model_name='image... |
import json
import wikipedia
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
class CountriesWiki:
def __init__(self, file_name):
self.counter = 0
self.file_name = file_name
self.file = open(self.file_name, encoding='utf8')
self.json_data = j... |
import numpy as np
import random
from keras.preprocessing.image import ImageDataGenerator
class Dataset:
def __init__(self, X, y, mean=None, std=None, normalize=True):
assert X.shape[0] == y.shape[0], 'Got different numbers of data and labels'
assert (mean is None) == (std is None), 'Must specify ... |
def entropyWeighted(X):
import numpy as np
row_sums = X.sum(axis=0)
P = X / row_sums[np.newaxis,:]
k = 1/np.log(X.shape[0])
E = np.multiply(P, np.log(P))
ev = -1 * k * E.sum(axis=0)
delv = 1.0 - ev
wv = delv/np.sum(delv)
Iv = np.dot(P, wv)
return(Iv)
if __name__ == '__... |
from django.contrib import admin
from myapp.models import Db_name,Db_instance
from django.contrib.auth.models import User
# Register your models here.
#通过 admin.site.register 注册模型类, 这样 admin 就可以管理数据库中这种类型的对象
# 实例列表
@admin.register(Db_instance)
class DbinstanceAdmin(admin.ModelAdmin):
# 设置显示的字段
list_display =... |
import math
import glob
from os.path import basename
import tensorflow as tf
from tensorflow import keras
import numpy as np
from scipy import misc
from ard_cnn import ARDCNN
import cv2
from sklearn import metrics
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '4'
from IPython import embed
#LEN = 2232
LEN = 5
BATCH... |
# encoding:utf-8
import functools
import hashlib
import random
import string
import uuid
try:
import simplejson as json
except ImportError:
import json
json_dumps = functools.partial(json.dumps, ensure_ascii=False)
unique_uuid = lambda: uuid.uuid4().hex
def md5_hex_digest(x):
return hashlib.md5(x.encod... |
#!/usr/bin/python
# coding=utf-8
from lxml import etree
#Carga del fichero XML
def carga_xml():
try:
xml_completo = etree.parse("musica_utf8.xml")
except:
return "error"
if carga_xml() == "error":
print "Debe existir el fichero musica_utf8.xml en el directorio"
else:
xml_completo = e... |
""" HTML formatter for responses
"""
import logging
import os
from database.dictionary import Dictionary
from database.user import User
from server.navigation import Navigation
def html_format_template(path, user=None, nav=None, variables=None):
with open(os.path.join(os.environ["WORKDIR"], "templates", path), ... |
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.middle = None
self.right = None
self.end = 0
def __str__(self):
return self.val
def set_left(self, node):
self.left = node
def set_middle(self,... |
'''
Created on Apr 30, 2015
@author: pekzeki
'''
from pymongo import MongoClient
import networkx as nx
from network_analysis import graph_analysis as GA
from random import randint
def random_attacked_graph(random_attack_list):
G = nx.Graph()
for user in user_collection.find():
G.add_node(user.get("... |
"""
A simple GUI calculator
"""
import tkinter as tk
import numexpr
# Create window and set title
ROOT = tk.Tk()
ROOT.title("Calculator")
def _clear_():
ENTER.delete(0, 100)
def calculate():
"""
calculate tkinter entry
"""
# get the entry
cal_this = ENTER.get()
# if entry is valid
tr... |
from datetime import date
from time import sleep
print('-=-' * 20)
print('CONFEDERAÇÃO DE NATAÇÃO PROFISSIONAL')
print('-=-' * 20)
anoNascimento = int(input('Digite o ANO de nascimento: '))
idade = (date.today().year - anoNascimento)
print()
print('PROCESSANDO...')
sleep(2)
print()
if idade <= 9:
print('Nadador... |
import copy
import ipcalc
import logging
from graphs import Graph
from database import get_mongodb
import services
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image
import time
class Neighbor:
def __init__(self, interface, neighbor_ip):
self.neigh... |
from django.urls import path,include
from . import views
urlpatterns = [
# path('handle-payment/', views.PaymentView.as_view(), name='handle_payment'),
path('lessons/', include('lessons.urls')),
path('checkout/', views.PaymentView.as_view(), name='checkout'),
path('profile/<int:pk>/', views.Profile... |
import re
room_intents = {
'1' : ['1', '(.*) 1 (.*)', '(.*) one', '(.*) one (.*)','(.*)first room', 'first room (.*)'],
'2' : ['2', '(.*) 2 (.*)', '(.*) two', '(.*) two (.*)',' (.*) second room',' second room (.*)'],
'3' : ['3', '(.*) 3 (.*)', '(.*) three', '(.*) three (.*)','(.*) third room',' third ... |
import ROOT
import collections
### variable list
variables = {
"pth":{"name":"pth","title":"p_{T}^{H} [GeV]","bin":50,"xmin":0,"xmax":1000},
"pthl":{"name":"pth","title":"p_{T}^{H} [GeV]","bin":50,"xmin":0,"xmax":5000},
"mll":{"name":"ll_m","title":"m_{ll} [GeV]","bin":50,"xmin":12,"xmax":200},
"mt":{"... |
###imported modules
import os
import subprocess
###functions
#function for listing files in any path
def ls(path):
files = os.listdir(path)
#remove .DS Store files in the list of files in the folder
if (files[0] == ".DS_Store"):
files = files[1:]
return files
# function for changing directories
def cd( cmd ):... |
import sys
import os
import numpy as np
import scipy.sparse as sps
from collections import Counter
"""
training_datafile = sys.argv[1]
testing_datafile = sys.argv[2]
validation_datafile = sys.argv[3]
topk_neg_to_use = int(sys.argv[4])
topk_pos_to_use = int(sys.argv[5])
"""
def data_write(path):
with open(file = pat... |
from rest_framework.pagination import PageNumberPagination
class StandardResultsSetPagination(PageNumberPagination):
page_size = 9
page_size_query_param = 'limit'
max_page_size = 1000
class Meta:
ordering = ['-id']
|
import json
from pydantic import BaseModel
from database.symphony_db import Symphony_Db, Serie
from service.database.database_service import DataBaseService
from constants.request_model import *
class SerieService:
entity = Serie
@staticmethod
@Symphony_Db.atomic()
def get(id: int):
entity = Se... |
# coding: utf-8
"""
\"Data Governance Center: REST API v2\"
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import ... |
n=float(input())
print('enter the feet:',n)
acres=n/43560
print('farmers field in acres is',acres)
|
#!/usr/bin/python3
# coding=utf-8
# -------------------------------------------------------------------------------
# This file is part of Phobos, a Blender Add-On to edit robot models.
# Copyright (C) 2020 University of Bremen & DFKI GmbH Robotics Innovation Center
#
# You should have received a copy of the 3-Clause ... |
#symulacja bramki - wrzucamy do niej monety
#klasa,ktora generuje pieniadze
#druga klasa, ktora generuje stan, np., zeby przejsc przez bramke musze miec 2 zl cnt musi podjac decyzje na podstawie czegosc
# musimy dac iles czasu na otwarcie bramki i znowu
import random
from time import sleep # importujemy, zeby r... |
from spider_man.crawler.base.spider import BaseSpider
from spider_man.database import MongoDB
from spider_man.spiders.jumei.good.extractor import GoodDynamicDetailPageExtractor
class GoodDynamicDetailSpider(BaseSpider):
# 爬虫名
name = 'goodDynamicDetail_spider'
default_seed_vals = []
default_origin_url... |
import random
import pandas as pd
import numpy as np
class SeqChunker:
def __init__(self, data, W_size=64, batch_size=64, shuffle=True, neg_frac=1,
data_encoders=None, label_encoders=None, data_cols=None, label_cols=None):
"""
Generates sequence chunks of fixed sized window with d... |
'''
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
'''
def singleNumber(nums):
"""
:type nums: List[int]
:rtype:... |
# 企业路由
from flask import Blueprint, render_template, flash, redirect, url_for
from flask_login import login_required, current_user
from jobplus.forms import CompanyProfileForm
from jobplus.decorators import company_required
company = Blueprint('company', __name__, url_prefix='/company')
@company.route('/profile', me... |
""" This file is used to test an LQR implementation """
import matplotlib as mpl
mpl.use('Qt4Agg')
import logging
import imp
import os
import os.path
import sys
import copy
import argparse
import threading
import time
# Add gps/python to path so that imports work.
sys.path.append('/'.join(str.split(__file__, '/')[:-... |
import os
pid=os.fork()
if pid<0:
pass
elif pid ==0:
print("Child pid:",os.getpid())
else:
while True:
pass
|
# uma função qualquer
import math
def f(x):
return x**3+x**2 + 0.001
# return math.log(x)+x**2
# método da bisseção
m=0
a, b = [-2, 4]
n = 10 # número de iterações
print("O número de iterações é", n)
for i in range(n):
m = (a + b) / 2
if f(m) == 0:
print('A raiz é:', m)
elif f(a) * f(... |
#!/usr/bin/env python3
from core.operation import Operation
from input_parser import add_operation
class Info(Operation):
def __init__(self, kind: str, **kwargs):
super().__init__(**kwargs)
self.kind = kind
def __call__(self):
if self.kind == "prefix":
self._set_build_pat... |
import psycopg2.extras
import arcpy
from time import time
from terreno import Terreno
from cronometro import Cronometro
arcpy.env.workspace = r"Database Connections\My Database Connection.sde"
data = "BD.DBO.TABLE"
print("Eliminando tabla ...")
conn = psycopg2.connect("dbname='xxxxxx' user='xxxxxx' host='xxx.xx.xx.x... |
__author__ = 'COX1KB'
# I observed as people came in late to a scientific talk, that manners prevented them from walking to the front row
# to free chairs, instead engaging in absurd behavior.
# Run the simulator.
# What insight did the mysterious stranger have into the data structure?
# Can you find the problem line ... |
"""Adds historical game power tracking
Revision ID: 60f9ffc05b0a
Revises: 95106b5a352d
Create Date: 2020-08-22 08:17:13.008010
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "60f9ffc05b0a"
down_revision = "95106b5a352d"
branch_labels = None
depends_on = None
... |
from main import handler
dummy_event = {'Lat': -6.329598542338873, 'Long': 106.72983194993282, 'DeviceId': 1, 'Humidity': 44.200001, 'Temp': 29.6, 'Fire': 1.695236}
if __name__ == "__main__":
handler(dummy_event, None)
|
# Create a list called instructors
instructors = []
# Add the following strings to the instructors list
# "Colt"
# "Blue"
# "Lisa"
instructors.append("Colt")
instructors.append("Blue")
instructors.append("Lisa")
# Run the tests to make sure you've done this correctly!
print(instructors)
|
from abaqusConstants import *
class DamageEvolution:
"""The DamageEvolution object specifies material properties to define the evolution of
damage.
Notes
-----
This object can be accessed by:
.. code-block:: python
import material
mdb.models[name].materials[name].ductileDama... |
# Generated by Django 3.1.2 on 2021-03-13 13:46
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('found', '0008_auto_20210313_1908'),
]
operations = [
migrations.AlterFie... |
#coding:utf-8
from __future__ import print_function
import time
from hashlib import md5
from bson import ObjectId
import tornado.web
from apps.api.common import BaseHandler
from lib.routes import route
from apps.api.utils import generate_access_token, generate_geohash
@route('/api/login')
class ApiLoginHandler(BaseH... |
#coding: utf-8
from __future__ import unicode_literals, absolute_import
from django.db import models
from fias.fields import UUIDField
class AddrObjIndex(models.Model):
class Meta:
app_label = 'fias'
aoguid = UUIDField()
aolevel = models.PositiveSmallIntegerField()
scname = models.TextFiel... |
# Copyright (C) 2020 Alisson Linhares, Rodolfo Azevedo.
# All rights reserved.
#
# This project is a free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any late... |
import sys
import csv
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
def main (mast_line, chr, start, end, l):
start = int(start)
l = int(l)
n = 0
c = 0
for m in mast_line.split("]_"):
try:
i, strand = m.split("_[")
i = int(i)
strand = strand[0]
n += i
correc... |
#! /usr/local/bin/pymol -qc
'''
[* 22] highlight the interfaces and look around
'''
# to tfm in pymol https://pymolwiki.org/index.php/Transform_selection
# to get the tfm needed: copy object by hand, than follow this to get the tfm
# see here https://pymolwiki.org/index.php/Get_object_matrix
# print(tfm) to have ti sp... |
import pandas as pd
import numpy as np
data = pd.read_csv('thanksgiving-2015-poll-data.csv', encoding="Latin-1")
intro_message = '''Using the data set described below the following
pieces of information willbe determined:
\t1* What is the top 3 desserts & pies people eat at thanksgiving
\t2* The most common... |
from gql import gql
from gql.client import Client
from gql.transport.requests import RequestsHTTPTransport
from gh_repos.settings.common import GH_API_TOKEN
GH_API_URL = 'https://api.github.com/graphql'
class GraphQLError(Exception):
"""GraphQLError Exception."""
def __init__(self, message):
"""Ini... |
from __future__ import print_function
from boto3.dynamodb.conditions import Key, Attr
import boto3
import json
import time
import logging
def lambda_handler(event, context):
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('order')
menuId = table.get_item(
Key ={
'OderId': e... |
import json
# helper word class
class Word:
def __init__(self, json: dict):
self.q_la = json["qLa"] # question text in latin
self.q_en = json["qEn"] # question text in english
self.a_la = json["aLa"] # answer text in latin
self.a_en = json["aEn"] # answer text in latin
... |
# Curbrock Summon 2
CURBROCK2 = 9400930 # MOD ID
CURBROCKS_ESCAPE_ROUTE_VER2 = 600050040 # MAP ID
CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050 # MAP ID 2
sm.spawnMob(CURBROCK2, 190, -208, False)
sm.createClock(1800)
sm.addEvent(sm.invokeAfterDelay(1800000, "warp", CURBROCKS_ESCAPE_ROUTE_VER3, 0))
sm.waitForMobDeath(CURBRO... |
# -*- coding: utf-8 -*-
import xlrd
from lib import legend
class raw_legend(object):
def __init__(self):
self.legends = {}
def get_name(self, table, row):
name = table.cell(row, 0).value
#print name
name = str(int(name))
return name
def get_hp(self, table, row):
hp = int(table.cell(ro... |
'''dataset_d1: generate dataset with 1 feature and 1 label'''
import numpy as np
import pdb
import unittest
import random_sample
def d1(fun, num_samples, x_low, x_high, error_mean, error_variance):
'''generate label := fun(x) + N(error_mean, error_variance)
ARGS
fun: function(number) -> number
num_... |
import spacy
nlp = spacy.load("en")
doc = nlp("The big grey dog ate all of the chocolate, but fortunately he wasn't sick!")
doc.text.split()
[token.orth_ for token in doc]
[(token, token.orth_, token.orth) for token in doc]
[token.orth_ for token in doc if not token.is_punct | token.is_space]
practice = "practice pract... |
from typing import Union
import numpy as np
import pandas as pd
from scipy.stats import beta
from scattertext import CorpusBasedTermScorer
"""
Note that the functions here are more or less a direct translation from the LRC implementation in R by Evert (2023).
Stephanie Evert. 2023. Measuring Keyness. https://osf.io... |
input = open("input.txt", "r")
entries = sorted([int(line.strip()) for line in input])
l = 0
r = len(entries)-1
while l < r:
left = entries[l]
right = entries[r]
total = left + right
if total > 2020:
r -= 1
elif total < 2020:
l += 1
elif total == 2020:
break
print(right *... |
from pytube import YouTube
import getpass
class downloader_class():
def __init__(self, url, save_path='C:\\Users\\' + getpass.getuser() +'\\Downloads\\Video'):
self.url = url
self.save_path = save_path
def download(self, quality, extension):
try:
yt = YouTube(self.url)
... |
"""
Main TensorFlow based Neural Network Model
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import tensorflow as tf
from dnn_data import *
import os
parser = argparse.ArgumentParser()
parser.add_argument('--batch-size', default=1... |
#coding=utf-8
'''
函数名:read_init.py
函数作用:读取配置文件代码封装,读取文件config路径下方的文件,可以在file_path修改读取文件
作者:曾志坤,时间:20180315
'''
import configparser
# read_ini = configparser.ConfigParser()
# data = read_ini.read('E:\AppiumProjectAndroid\config\LocalElement.ini')
# print(data)
# print(read_ini.get('login_element','username'))
class R... |
def displayrev(arr):
if(len(arr)==0):
print()
else:
print(arr[-1],end=",")
displayrev(arr[0:len(arr)-1])
arr = eval(input("Enter the elements enclosed within []:"))
print(type(arr))
displayrev(arr)
|
# -*- coding:utf-8 -*-
import setup_django_version
import os
import re
try:
import json
except ImportError:
import simplejson as json
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.db import djangoforms
from google.appengine.ext.webapp.template import _... |
import tensorflow as tf
import numpy as np
import os
import sys
import math
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
#tf.executing_eagerly()
def add_timing_signal_nd(x, min_timescale=1.0, max_timescale=1.0e4):
"""Adds a bunch of sinusoids of different frequencies to a Tensor.
Each channel of the input Tensor is ... |
from utilities import parse_arg
import os
import file_utils
import avro.schema
from avro.datafile import DataFileWriter
from avro.io import DatumWriter
schema = avro.schema.Parse(open("dataset.avsc").read())
data_dir = parse_arg("--data-base-dir", required=True)
collection_name = parse_arg("--database", required=Tru... |
import numpy as np
import matplotlib.pyplot as plt
import pickle
import sys
sys.path.append("../Analysis_Scripts/")
from data_functions import *
from aux_spectrum_functions import get_spectrum
from energy_functions import get_scaled_dunham
from constants import *
def load_dunham(filename = 'dunham_matrices_fit.pickl... |
#coding:utf-8
import subprocess,os
user='alvin'
maindir='/opt/'
project='SophirothPXE'
port=8001
logdir='/var/log/sophirothpxe/'
logfile=logdir+'sophiroth.log'
workdirk=maindir+project
os.chdir(workdirk)
if os.path.exists(logdir):
pass
else:
subprocess.call('sudo mkdir -p %s'%logdir, shell=True)
subproce... |
from java.util import HashMap
from java.util import HashSet
from java.util import Map
from java.util import Set
from java.util.Map import Entry
from java.util import ArrayList
from java.util import Hashtable
from java.lang import System
from java.io import FileInputStream
from weblogic.management.mbeanserver... |
koszyk=['pomidor','ogorek','ser','szynka','pomarancza']
ceny =[100,120,100,150,260]
suma = 0
suma = sum(ceny)
promocja_r1 = False
promocja_r2 = False
promocja_r3 = False
ilosc_produktow_promocja_r1 = 4
cena_produktow_promocja_r2 = 500
cena_produktow_promocja_r3 = 600
if len(koszyk)>ilosc_produktow_promocja_r1:
... |
def find_cal_summary(service, calendarname):
response = service.calendarList().list().execute()
calendarItems = response.get('items')
myCalendar = filter(lambda x: calendarname in x['summary'], calendarItems)
if myCalendar:
myCalendar = next(myCalendar)
return myCalendar
def update_calend... |
import scrapy
class JewelSpider(scrapy.Spider):
name = "jewelbot"
allowed_domain = ['https://www.houseofindya.com/zyra/cat?depth=1&label=Jewelry']
start_urls = ['https://www.houseofindya.com/zyra/cat?depth=1&label=Jewelry']
# location of csv file
custom_settings = {'FEED_URI': 'new1/csvF... |
from django.urls import path
from . import views
app_name = 'cart'
urlpatterns = [
path('', views.CartView.as_view(), name="cart_list"),
path('addcart/', views.AddCartView.as_view(), name='add_to_cart'),
path('update-quantity/', views.UpdateQuantityView.as_view(), name='update_quantity'),
path('delete-... |
import unicodedata
def to_halfwidth(text):
result = ''
for char in text:
name = unicodedata.name(char, None)
if name == 'IDEOGRAPHIC SPACE':
result += ' '
elif not name or name.find('FULLWIDTH') != 0:
result += char
else:
new_name = name.repl... |
import os
from utils import *
from flask import Flask, session, render_template, request, redirect, url_for
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.exc import IntegrityError
from passlib.hash import sha256_crypt
ap... |
#!/usr/bin/env python
"""polly - build a corpus from an IMAP folder and use it to generate passwords.
usage: %(PROG)s args ...
Config File Options
-------------------
The following options can be specified in the config file. Some can
also be given on the command line.
digits - when True, allow digits betw... |
#-*-coding:utf-8-*-
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import os
import sys
from flask import Flask, request, render_template, redirect, flash, url_for, g, session, abort, make_response, current_app
from flask.ext.mysqldb import MySQL
from functools import wraps
import datetime
imp... |
import unittest
import os
import logging
import subprocess
import time
from oeqa.selftest.base import oeSelfTest
from oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars
from oeqa.selftest.qemucommand import QemuCommand
class SotaToolsTests(oeSelfTest):
@classmethod
def setUpClass(cls):
... |
def solution(name):
answer = 0
min_move = len(name) - 1
nxt = 0
for i, char in enumerate(name):
answer += min(ord(char) - ord('A'), ord('Z') - ord(char) + 1)
nxt = i + 1
while nxt < len(name) and name[nxt] == 'A':
nxt += 1
min_move = min(min_move, i + i + l... |
import tweepy
import sys
import json
import time
import logging
from datetime import datetime as dt
class ReplyQuerier(tweepy.API):
"""
ReplyQuerier takes care of the application logic for conducting queries using
Twitter Search API, dependent on tweepy.
...
Attributes
----------
io : Io... |
#!/usr/bin/python2
import sys
import os
import ast
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
frame_size = (400, 440)
tile_size = 20
black = (0, 0, 0)
grey = (127, 127, 127)
yellow = (255, 215, 0)
font = ImageFont.truetype("/usr/share/fonts/TTF/OxygenMono-Regular.ttf", 15)
infile = sys... |
__author__ = 'Sam'
import BitcoinChartsAPI
import Database
import time
from operator import itemgetter
db = Database
api = BitcoinChartsAPI
SLEEP = 0 #seconds
class BitcoinCharts():
def BitcoinChartsData(self, thisExchange): #'thisExchange' is the 'exchangeCode' we've passed to this method... |
import os
from setuptools import setup, find_packages
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.... |
class Prototype(object):
value = 'default'
def clone(self, **attr):
obj = self.__class__()
obj.__dict__.update(attr)
return obj
class PrototypeDispatcher(object):
def __init__(self):
self._objects = {}
def getObject(self, obj_name):
print(f'Getting object {obj_name}')
return self._... |
# 문제5.
# 함수 sum 을 만드세요. 이 함수는 임의의 개수의 인수를 받아서 그 합을 계산합니다.
def sum(*nums):
s = 0
for n in nums:
s += n
return s
print(sum(1, 3, 5, 7, 9))
|
#List
print("Ini List :")
contoh_list =["Alvin",12,12.0,[1,2,3],{},{},True]
print(contoh_list[0])
print(contoh_list[-4])
contoh_list.append("David")
contoh_list.insert(3,"Dian")
print(contoh_list)
print("SortData : ")
list_angka = [1,4,7,9,8]
list_angka.sort() #besar ke kecil
print(list_angka)
list_angka.so... |
class Flight:
def __init__(self,
start_time,
end_time,
passengers,
max_passengers,
from_dest,
to_dest,
terminal,
declined):
self.start_time = start_time
self... |
import os, sys
import commands
fpath = sys.argv[1]
sitelist = [
'163.com',
'qq.com',
'sina.com.cn',
'xinhuanet.com',
'ifeng.com',
'hexun.com',
'jiemian.com',
'thepaper.com',
'yicai.com',
]
c = commands.getstatusoutput("ps aux | grep BGY_YQ_NEWS_META")
if 'scrapy' in c[1]:
exit()
for line in open(fpath,'r')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.