blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2
values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220
values | src_encoding stringclasses 30
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 2 10.3M | extension stringclasses 257
values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3b1911ff0bdb6665e42f5d841028643cca5a8f38 | 7cf87ceef67fd8b7c33174ddf3fb289756200e48 | /lists/views.py | 66576dff17a81b7dc415bef96e22d200fc1bc8ce | [] | no_license | codekaizen/tdd-with-python | cb4e98cec2cb1e3e88f92337d607ecd6c2aad55e | ba1b962a086f1801cba94dd190a71bb3c3bbacde | refs/heads/master | 2021-01-24T01:22:17.727821 | 2015-08-07T21:49:22 | 2015-08-07T21:49:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 350 | py | from django.http import HttpResponse
from django.shortcuts import redirect, render
from lists.models import Item
def home_page(request):
if request.method == 'POST':
Item.objects.create(text=request.POST['item_text'])
return redirect('/')
items = Item.objects.all()
return render(request, 'home.html', {'items': items}) | [
"mesbah.amin@gmail.com"
] | mesbah.amin@gmail.com |
272b439af84b2a99cb3216d93d524eb6ea6978b4 | 103f75613a84afab0a5cdba5e2b844ebdb84612b | /speech2ipa/outputs.py | 327fa1d2ff9d107e1874fb0218e8390b07eb4bac | [] | no_license | n8marti/speech2ipa | 00fb986cad39715438b07e94d0562ba5b575a19c | 0ea45de6bcf9388709a0c140bc63f0092bbe4fd5 | refs/heads/master | 2023-04-13T16:11:03.508893 | 2021-04-26T12:55:20 | 2021-04-26T12:55:20 | 347,347,758 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,285 | py | """Functions used to generate various outputs from the given WAV file."""
import numpy as np
import matplotlib.ticker as ticker
import wave
from matplotlib import pyplot
from scipy.fft import irfft, rfft, rfftfreq
from speech2ipa import utils
def save_wave_as(np_frames, frame_rate, output_file):
"""Write out the wave data to a WAV file."""
byte_frames = np_frames.tobytes()
with wave.open(str(output_file), 'wb') as wav:
#wav.setparams(file_info)
wav.setframerate(frame_rate)
wav.setnchannels(1)
wav.setsampwidth(2)
wav.writeframes(byte_frames)
def plot_spectrogram(frame_rate, np_frames, input_file, output_file):
"""Plot spectrogram to new window and to PNG file."""
plt_specgram = pyplot
# Set format details for plot.
fig = plt_specgram.figure(num=None, figsize=(12, 7.5), dpi=300)
ax = fig.add_subplot(111)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(2000))
ax.yaxis.set_minor_locator(ticker.MultipleLocator(500))
ax.tick_params(axis='both', direction='inout')
plt_specgram.title(f"Spectrogram of:\n{input_file}")
plt_specgram.xlabel('Time (seconds)')
plt_specgram.ylabel('Frequency (Hz)')
"""
### This doesn't result in a "narrow" enough bandwidth; i.e. the frequencies
# Set NFFT so that there are ~100 columns per second of audio.
# have too much resolution and each formant is split into multiple
# bands.
columns_per_sec = 100 # desired horizontal resolution
noverlap = 500 # default: 128; correlates with vertical resolution
# matplotlib says that an NFFT that is a power of 2 is most efficient,
# but how would I round the calculation to the nearest power of 2?
NFFT = int(frame_rate / columns_per_sec + noverlap) # NFFT = 941
"""
# If NFFT is too high, then there the horizontal (frequency) resolution is
# too fine, and there are multiple bands for each formant. However, if
# NFFT is too low, then the whole image is rather blurry and even the
# formants are not well differentiated (i.e. at the fault vaules for NFFT
# and noverlap). noverlap that is half of NFFT seems to minimize background
# noise, as well.
noverlap = 256 # default: 128
NFFT = 512 # default: 256
# Create the plot.
spectrum, frequencies, times, img = plt_specgram.specgram(
np_frames,
Fs=frame_rate,
cmap='gnuplot',
noverlap=noverlap,
NFFT=NFFT,
)
ax.set_ylim(None, 8000)
cbar = plt_specgram.colorbar()
cbar.ax.set_ylabel('dB')
# Save the plot to file & show.
plt_specgram.savefig(output_file)
#plt_specgram.show()
#print(len(np_frames))
#print(len(spectrum.flat))
#print(len(spectrum), len(spectrum[0]))
return spectrum, frequencies, times, img
def plot_waveform(frame_rate, np_frames, output_file):
"""Plot raw frame data values to new window and to PNG file."""
plt_waveform = pyplot
x, y = [], []
for i, f in enumerate(np_frames):
x.append((i + 1) / frame_rate)
y.append(f)
# Create the plot.
fig = plt_waveform.figure(num=None, figsize=(12, 7.5), dpi=100)
#plt_waveform.scatter(x, y, marker='.', s=0.1)
plt_waveform.plot(x, y, marker=',', ms=1)
# Save the plot to file & show.
plt_waveform.savefig(output_file)
#plt_waveform.show()
def plot_fourier(frame_rate, np_frames, output_file):
"""Plot Fourier Transformation of audio sample."""
plt_fourier = pyplot
n = len(np_frames)
#norm_frames = np.int16((byte_frames / byte_frames.max()) * 32767)
yf = rfft(np_frames)
xf = rfftfreq(n, 1 / frame_rate)
fig = plt_fourier.figure(num=None, figsize=(12, 7.5), dpi=100)
plt_fourier.plot(xf, np.abs(yf))
plt_fourier.savefig(output_file)
#plt_fourier.show()
def generate_plots(input_file, np_frames, frame_rate):
# Generate spectrogram.
output_file = input_file.with_suffix(".specgram.png")
np_spectrum, np_freqs, np_times, img_spec = plot_spectrogram(
frame_rate,
np_frames,
input_file,
output_file,
)
# Generate waveform plot.
output_file = input_file.with_suffix(".waveform.png")
plot_waveform(
frame_rate,
np_frames,
output_file,
)
# Generate plot of Fourier Transformation.
output_file = input_file.with_suffix(".fourier.png")
plot_fourier(
frame_rate,
np_frames,
output_file,
)
return np_spectrum, np_freqs, np_times
def print_spectrum_properties(np_spectrum, np_freqs, np_times):
"""Print out insightful properties of the normalized spectrum data."""
# Duration (s)
# Frequency range (max 8 kHz)
duration = round(np_times[-1], 2)
max_amp_raw = max(np_spectrum.flat)
min_amp_raw = min(np_spectrum.flat)
print(f"Duration: {duration} s")
def print_sample_properties(properties_dict):
for prop, data in properties_dict.items():
print(f"{prop}: {data['value']} {data.get('unit')}")
def print_frame_data(time_frames):
print(f"Index\tTime\tSilence\tVocal.\tTurb.\tFormants")
for t, data in time_frames.items():
print(f"{data['index']}\t{round(t, 3)}\t{data['silence']}\t{data['vocalization']}\t{data['turbulence']}\t{data['formants']}")
def print_amplitudes(time_frames):
for t, data in time_frames.items():
print(f"{round(t, 3)}\n{[round(a) for a in data['amplitudes']]}\n")
def print_frequencies(np_freqs):
print(np_freqs)
def print_terminal_spectrogram(np_spectrum, np_freqs, np_times, time_frames=False):
"""Print out a basic spectrogram in the terminal for debugging."""
for ri, r in enumerate(np_spectrum[::-1]):
# Print frequency scale item.
freq = np_freqs[len(np_freqs) - ri - 1]
if ri % 2 == 0:
print(f"{int(freq / 1000)}K ", end='')
else:
print(' ', end='')
# Print frequency rows.
for a in r:
#min_amp = utils.get_min_amp(freq)
min_amp = 10
if a < min_amp:
print(' ', end='')
elif a < 100 * min_amp:
print('- ', end='')
elif a < 10000 * min_amp:
print('* ', end='')
else:
print('# ', end='')
print()
# Print time scale.
dec_places = 1
shift = 5 / 10 ** ( dec_places + 1 )
print(' ', end='')
for i, t in enumerate(np_times):
if i % 2 == 0:
if t < shift:
shift = 0
print(f"{round(t - shift, dec_places)} ", end='')
print()
if time_frames:
# Print evaluated properties.
print()
# - silence
print('S: ', end='')
for time_frame in time_frames.values():
if time_frame['silence'] == True:
print('T ', end='')
else:
print('F ', end='')
print()
# - vocalization
print('V: ', end='')
for time_frame in time_frames.values():
if time_frame['vocalization'] == True:
print('T ', end='')
else:
print('F ', end='')
print()
# - turbulence
print('T: ', end='')
for time_frame in time_frames.values():
if time_frame['turbulence'] == True:
print('T ', end='')
else:
print('F ', end='')
print('\n')
def print_wav_frames(wavinfo, wavframes, startsec, endsec):
"""Print one frame per line from the given time range."""
# column1 = relative frequency?
# column2 = relative amplitude?
print(wavinfo)
bitrate = 16 # assumed, for now. Found at bytes 35-36 (10 00 = 16).
len_frame = wavinfo.nchannels * wavinfo.sampwidth
framerate = wavinfo.framerate
startfr = int(startsec * framerate)
endfr = int(endsec * framerate)
for i, frame in enumerate(wavframes[startfr:endfr]):
if i % len_frame < len_frame - 1:
print(f"{frame}\t", end='')
else:
print(frame)
print()
| [
"nate_marti@sil.org"
] | nate_marti@sil.org |
91ff4557889267cdc86ec60b66665b358bc9d290 | f5a080763fdee42f266a2d391d4f2ad728d7fa1d | /docs/rst2latex-pygments | f5d3cfa0485e574319d21374d79fd37229a1e2bf | [] | no_license | SQLab/CRAX | e4ee124d534a67276be0a4c484db5120971166b9 | 57916623c347dd03f1a0d952accc2130ab053b1e | refs/heads/master | 2020-04-09T02:56:31.425639 | 2015-08-19T16:15:52 | 2015-08-19T16:15:52 | 12,452,558 | 44 | 11 | null | 2014-07-15T02:29:51 | 2013-08-29T05:50:26 | C | UTF-8 | Python | false | false | 2,085 | #!/usr/bin/env python
# Author: David Goodger, the Pygments team, Günter Milde
# Date: $Date: $
# Copyright: This module has been placed in the public domain.
# This is a merge of the docutils_ `rst2latex` front end with an extension
# suggestion taken from the pygments_ documentation.
"""
A front end to docutils, producing LaTeX with syntax colouring using pygments
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
description = ('Generates LaTeX documents from standalone reStructuredText '
'sources. Uses `pygments` to colorize the content of'
'"code-block" directives. Needs an adapted stylesheet'
+ default_description)
# Define a new directive `code-block` that uses the `pygments` source
# highlighter to render code in color.
#
# Code from the `pygments`_ documentation for `Using Pygments in ReST
# documents`_.
from docutils import nodes
from docutils.parsers.rst import directives
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import LatexFormatter
pygments_formatter = LatexFormatter()
def pygments_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
try:
lexer = get_lexer_by_name(arguments[0])
except ValueError:
# no lexer found - use the text one instead of an exception
lexer = get_lexer_by_name('text')
parsed = highlight(u'\n'.join(content), lexer, pygments_formatter)
return [nodes.raw('', parsed, format='latex')]
pygments_directive.arguments = (1, 0, 1)
pygments_directive.content = 1
directives.register_directive('code-block', pygments_directive)
# Call the docutils publisher to render the input as latex::
publish_cmdline(writer_name='latex', description=description)
# .. _doctutile: http://docutils.sf.net/
# .. _pygments: http://pygments.org/
# .. _Using Pygments in ReST documents: http://pygments.org/docs/rstdirective/
| [
"vova.kuznetsov@epfl.ch"
] | vova.kuznetsov@epfl.ch | |
d5a7228eb423cd746537fad129b68f8f1b788af3 | c963b8e79864bbb8b49d1aeca4dee6ea81d14032 | /OutputView/OnePage/OutputViewText.py | 54b442d51f95cd6115aace0b346d681dc9036dc1 | [] | no_license | ShmilyC/search | 8a232742de9a6cbf18fe612bf2cba6ddcdf0c275 | 9bed028fe16c9403278045f00eb7e28bdee1c395 | refs/heads/master | 2021-01-21T23:53:27.029649 | 2017-09-02T08:29:16 | 2017-09-02T08:29:16 | 102,182,937 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 439 | py | import tkinter
import OutputView.OnePage.OutputViewBase
class OutputViewText(OutputView.OnePage.OutputViewBase.BaseWindowShow):
def __init__(self):
super().__init__()
self.text = tkinter.Text(self.win,width = 800,height = 700)
self.text.pack()
def adddata(self,data):
self.text.insert(tkinter.INSERT,data+'\r\n')
# b= OutputViewText()
# b.adddata('a')
# b.adddata('b')
# b.adddata('c')
# b.show() | [
"shmilybell@hotmail.com"
] | shmilybell@hotmail.com |
c11116d9e8790b12a12d5976fdbb216b0825b54c | 3beb429e5f8816e2215b6b666dc760c0dd5849dd | /datastore/shared/di/exceptions.py | 797fad95376f48ca47db4c4ef37519563ca8d1af | [
"MIT"
] | permissive | OpenSlides/openslides-datastore-service | 329fdf66aebc5001b1e645ff70627dac70a37d26 | c8de45413c3f56c3b53c327e5669950202e38ac9 | refs/heads/main | 2023-09-04T17:01:23.363886 | 2023-08-31T17:34:18 | 2023-08-31T17:34:18 | 231,762,719 | 3 | 12 | MIT | 2023-08-03T12:40:23 | 2020-01-04T12:53:24 | Python | UTF-8 | Python | false | false | 173 | py | class DependencyInjectionError(Exception):
pass
class DependencyNotFound(DependencyInjectionError):
def __init__(self, protocol):
self.protocol = protocol
| [
"finn.stutzenstein@hotmail.de"
] | finn.stutzenstein@hotmail.de |
758ae7878b713d970fe3b7ab18a2b639634f9bab | 78670cd636007d3917cafa66e0cd19ac91bc26c7 | /Python_stack/django/django_intro/form_test/form_test/urls.py | 06383fae192594ca9485cb8ea65deb71e0cf7a61 | [] | no_license | Blackwell805/CodingDojo | 9c06d663815bee26ec4854a55ba82b0cdddbd0f5 | 9069a137e564824d9dd5ccc14b24abbb4a4cebb1 | refs/heads/main | 2023-05-01T22:57:10.408319 | 2021-05-23T19:43:14 | 2021-05-23T19:43:14 | 345,438,240 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 730 | py | """form_test URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import path, include
urlpatterns = [
path('', include('form_app.urls')),
]
| [
"austinbobs@gmail.com"
] | austinbobs@gmail.com |
1d4ebcce0118f05541c3c6d3e01ae58b51dcc55a | 9df2fb0bc59ab44f026b0a2f5ef50c72b2fb2ceb | /sdk/paloaltonetworks/azure-mgmt-paloaltonetworksngfw/generated_samples/certificate_object_global_rulestack_delete_maximum_set_gen.py | 1f902b1ba35bfded952bc53f1fceaa215a018896 | [
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-generic-cla"
] | permissive | openapi-env-test/azure-sdk-for-python | b334a2b65eeabcf9b7673879a621abb9be43b0f6 | f61090e96094cfd4f43650be1a53425736bd8985 | refs/heads/main | 2023-08-30T14:22:14.300080 | 2023-06-08T02:53:04 | 2023-06-08T02:53:04 | 222,384,897 | 1 | 0 | MIT | 2023-09-08T08:38:48 | 2019-11-18T07:09:24 | Python | UTF-8 | Python | false | false | 1,697 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.identity import DefaultAzureCredential
from azure.mgmt.paloaltonetworksngfw import PaloAltoNetworksNgfwMgmtClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-paloaltonetworksngfw
# USAGE
python certificate_object_global_rulestack_delete_maximum_set_gen.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = PaloAltoNetworksNgfwMgmtClient(
credential=DefaultAzureCredential(),
subscription_id="SUBSCRIPTION_ID",
)
response = client.certificate_object_global_rulestack.begin_delete(
global_rulestack_name="praval",
name="armid1",
).result()
print(response)
# x-ms-original-file: specification/paloaltonetworks/resource-manager/PaloAltoNetworks.Cloudngfw/preview/2022-08-29-preview/examples/CertificateObjectGlobalRulestack_Delete_MaximumSet_Gen.json
if __name__ == "__main__":
main()
| [
"noreply@github.com"
] | openapi-env-test.noreply@github.com |
24683605599a74d701fac1f237e88cce740f5240 | 2c162270be724f2aacf530985d401200f70c3660 | /personal_profolio/settings.py | cdddf9befabafc65f5cc2992f13508ab300c0f9e | [] | no_license | colodaddy/django3-personal-portfolio | 5dadaf3b35c027e43815cf9aef7c6b48d7e067f4 | 4ada03a6e33046e8681b031e2174d8a06a7cc52f | refs/heads/master | 2022-04-27T01:23:59.058324 | 2020-04-29T17:20:54 | 2020-04-29T17:20:54 | 259,992,526 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,216 | py | """
Django settings for personal_profolio project.
Generated by 'django-admin startproject' using Django 3.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '8!cxgs*l)@zfzlmh&katwxlxk9gpzj3ugme(s+4%@9%!*fw-^x'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'portfolio'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'personal_profolio.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'personal_profolio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
| [
"colodaddy@gmail.com"
] | colodaddy@gmail.com |
8bb7c4cc5ced138d96e58cdc82079ed850851be7 | cbd8f38b5ec1ca5aa2a7d5cdd10ad4621ec2dab8 | /conversions/flask/Quotes/flask-qoutes-v1.0-challenge8-with-backend/src/app.py | 367674f263e56842a0e70683d1251ad6d065fd48 | [] | no_license | codingdojo88oliver/training | 712b53e6d154b8fba9ac8d7bc62c53b9d92935ab | d1f2ae75adb04c4227596ae3f6fb1f8fd9e09b39 | refs/heads/master | 2022-12-22T03:27:04.966619 | 2020-01-10T08:47:24 | 2020-01-10T08:47:24 | 220,404,969 | 0 | 0 | null | 2022-12-07T18:12:56 | 2019-11-08T06:51:29 | null | UTF-8 | Python | false | false | 7,243 | py | from flask import Flask, render_template,request, redirect, session, flash
from mysqlconnection import connectToMySQL
app = Flask(__name__)
app.secret_key = 'keep it secret, keep it safe'
@app.route("/")
def index():
return render_template("index.html")
@app.route("/register", methods=["POST"])
def register():
errors = {}
if request.method == "POST":
try:
if len(request.form['name']) < 5:
flash("Name should be at least 5 characters")
if len(request.form['username']) < 5:
flash("Username should be at least 5 characters")
if len(request.form['password']) < 8:
flash("Password should be at least 8 characters")
if request.form['password'] != request.form['c_password']:
flash("Passwords do not match")
except Exception as e:
flash("Unknown error")
if '_flashes' in session.keys():
return redirect('/')
else:
mysql = connectToMySQL()
query = "INSERT INTO users (name, username, password,created_at) VALUES (%(name)s, %(username)s, %(password)s,NOW());"
data = {
"name": request.form['name'],
"username": request.form['username'],
"password": request.form['password'],
}
user = mysql.query_db(query, data)
flash( "User " + request.form['name'] + " with username " + request.form['username'] + " successfully registered!")
return redirect("/dashboard")
@app.route('/login', methods=['post'])
def login():
try:
mysql = connectToMySQL()
query = "SELECT * FROM users WHERE username = %(username)s and password = %(password)s;"
data = {
"username": request.form['username'],
"password": request.form['password'],
}
user = mysql.query_db(query, data)
session['is_logged_in'] = True
session['name'] = user[0]['name']
session['user_id'] = user[0]['id']
return redirect("/dashboard")
except Exception as e:
flash("Invalid username and password combination")
return redirect("/")
@app.route("/dashboard", methods = ["GET"])
def dashboard():
if 'is_logged_in' in session:
if session['is_logged_in'] == True:
try:
mysql = connectToMySQL()
query = "SELECT * FROM users WHERE id = %(id)s LIMIT 1;"
data = {
"id": session['user_id']
}
user = mysql.query_db(query, data)
except Exception as e:
flash("Invalid session")
return redirect("/")
mysql = connectToMySQL()
query = "SELECT favorites.id as favorites_id, users.name, quotes.quoted_by, quotes.quote, favorites.user_id, favorites.quote_id as quote_id FROM users left join quotes on quotes.user_id = users.id left join favorites on favorites.quote_id = quotes.id WHERE favorites.user_id = %(id)s ;"
favorite_quotes = mysql.query_db(query,data)
# get all quotes except favorites
except_quote_ids = []
if favorite_quotes:
for favorite_quote in favorite_quotes:
except_quote_ids.append(favorite_quote['quote_id'])
mysql = connectToMySQL()
query = "SELECT quotes.quoted_by, quotes.quote, quotes.user_id, users.name, quotes.id FROM quotes left join users on users.id = quotes.user_id WHERE quotes.id NOT IN %(except_quote_ids)s;"
data = {
"except_quote_ids": except_quote_ids,
}
quotes = mysql.query_db(query, data)
return render_template("dashboard.html", user = user, quotes = quotes, favorite_quotes = favorite_quotes)
else:
mysql = connectToMySQL()
query = "SELECT * FROM quotes left join users on users.id = quotes.user_id;"
quotes = mysql.query_db(query)
return render_template("dashboard.html", user = user, user_id = session['user_id'], quotes = quotes, favorite_quotes = favorite_quotes)
else:
flash("User is not logged in")
return redirect("/")
else:
flash("User is not logged in")
return redirect("/")
@app.route('/create-quote', methods=['POST'])
def createQuote():
errors = {}
if request.method == "POST":
try:
if len(request.form['quoted_by']) < 5:
flash("Qouted By should be at least 5 characters")
if len(request.form['quote']) < 10:
flash("Qoute should be at least 10 characters")
except Exception as e:
flash("Unknown error")
if '_flashes' in session.keys():
return redirect('/dashboard')
else:
try:
mysql = connectToMySQL()
query = "SELECT * FROM users WHERE id = %(id)s;"
data = {
"id": session['user_id']
}
user = mysql.query_db(query, data)
except Exception as e:
flash("User is not logged in")
return redirect("/")
mysql = connectToMySQL()
query = "INSERT INTO quotes (user_id, quoted_by, quote,created_at) VALUES (%(user_id)s, %(quoted_by)s, %(quote)s,NOW());"
data = {
"user_id": user[0]['id'],
"quoted_by": request.form['quoted_by'],
"quote": request.form['quote'],
}
quote = mysql.query_db(query, data)
flash("You just shared a new quote!")
return redirect('/dashboard')
@app.route('/move-to-favorites', methods=['post'])
def moveToFavorites():
try:
mysql = connectToMySQL()
query = "SELECT * FROM users WHERE id = %(id)s;"
data = {
"id": session['user_id']
}
user = mysql.query_db(query, data)
except Exception as e:
flash("User is not logged in")
return redirect("/")
mysql = connectToMySQL()
query = "SELECT * FROM quotes WHERE id = %(quote_id)s;"
data = {
"quote_id": request.form['quote_id'],
}
quote = mysql.query_db(query, data)
mysql = connectToMySQL()
query = "INSERT INTO favorites (user_id, quote_id, created_at) VALUES (%(user_id)s, %(quote_id)s,NOW());"
data = {
"quote_id": request.form['quote_id'],
"user_id": session['user_id'],
}
favorites = mysql.query_db(query, data)
flash("You just favorited a quote!")
return redirect('/dashboard')
@app.route('/remove-from-favorites', methods=['POST'])
def removeFromFavorites():
try:
mysql = connectToMySQL()
query = "SELECT * FROM users WHERE id = %(id)s;"
data = {
"id": session['user_id']
}
user = mysql.query_db(query, data)
except Exception as e:
flash("User is not logged in")
return redirect("/")
mysql = connectToMySQL()
query = "DELETE FROM favorites WHERE id = %(favorite_id)s;"
data = {
"favorite_id": request.form['favorite_id']
}
favorite = mysql.query_db(query, data)
flash("You just removed a quote from favorites!")
return redirect('/dashboard')
@app.route('/delete-quote', methods=['POST'])
def deleteQuote():
try:
mysql = connectToMySQL()
query = "SELECT * FROM users WHERE id = %(id)s;"
data = {
"id": session['user_id']
}
user = mysql.query_db(query, data)
except Exception as e:
flash("User is not logged in")
return redirect("/")
mysql = connectToMySQL()
query = "DELETE FROM quotes WHERE id = %(quote_id)s;"
data = {
"quote_id": request.form['quote_id']
}
quote = mysql.query_db(query, data)
flash("You just deleted a quote!")
return redirect('/dashboard')
@app.route('/logout', methods=['GET'])
def logout():
session.clear()
return redirect("/")
@app.route('/reset', methods=['GET'])
def reset():
mysql = connectToMySQL()
mysql.query_db("SET FOREIGN_KEY_CHECKS = 0;")
mysql.query_db("DELETE FROM users WHERE username in('mally5@yahoo.com', 'brian@gmail.com', 'james@gmail.com');")
mysql.query_db("SET FOREIGN_KEY_CHECKS = 1;")
return redirect('/')
if __name__ == "__main__":
app.run(port=8000, debug=True)
| [
"jaymarbajala110@gmail.com"
] | jaymarbajala110@gmail.com |
7d4ef385bc8e2f16164e4764430ca8e399270673 | 7847c2967ccd69303e77240a28b7bb081e66a826 | /bullet.py | 3481dacba3c0515af26fd0943499d3b58ddae405 | [] | no_license | Miczu3000/Inwazja | 6c751334adab6ef2d85a6cd710e84516d9058180 | 385ba02bbfc8f53852f6822e423c95c30522ecc3 | refs/heads/main | 2023-04-06T08:01:51.607729 | 2021-04-08T19:06:15 | 2021-04-08T19:06:15 | 349,696,479 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 630 | py | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self, ai_game):
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.color = self.settings.bullet_color
self.rect = pygame.Rect(0, 0, self.settings.bullet_width, self.settings.bullet_height)
self.rect.midtop = ai_game.ship.rect.midtop
self.y = float(self.rect.y)
def update(self):
self.y -= self.settings.bullet_speed
self.rect.y = self.y
def draw_bullet(self):
pygame.draw.rect(self.screen, self.color, self.rect)
| [
"d.krakus@gmail.com"
] | d.krakus@gmail.com |
c9f3049c1eef8bf880fda6b0c40fca0c650b1f96 | 1905c38ac140a444c583c64ee263a0a5fcec16a6 | /sem-3/7.JULY/23_loops.py | 46fc43a49c038412491347ccc1bf53ce24fe3231 | [] | no_license | B-Tech-AI-Python/Class-assignments | a5bfe96118e6867d3e2dbe73ce6abf26a7330f1b | 892d9c25b9712bf3bbfd7f29529eca8b47fb8039 | refs/heads/master | 2023-04-29T14:19:43.053931 | 2021-05-20T12:35:53 | 2021-05-20T12:35:53 | 283,107,191 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,292 | py | # %%
# Average of n natural numbers
import calendar
n = int(input("Enter range: "))
sum = 0
for n in range(n+1):
sum = sum+n
avg = sum/n
print("Average is:", avg)
# %%
# Factorial of a number
n = int(input("Enter a number: "))
fact = 1
if n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, n + 1):
fact = fact*i
print("The factorial is:", fact)
# %%
# Check if number is prime or not
n = int(input("Enter a number: "))
if n > 1:
for i in range(2, n):
if (n % i == 0):
print(n, "is composite")
break
else:
print(n, "is prime")
elif n == 0 or 1:
print("Invalid input")
else:
pass
# %%
# Calculate sum of series
n = int(input("Enter a number: "))
sum = 0
for i in range(1, n+1):
sum = (1/i)+sum
print("The sum of the series is:", sum)
# %%
# Generate calendar
yyyy = int(input("Enter year in yyyy format: "))
mm = int(input("Enter month in mm format: "))
print()
print(calendar.month(yyyy, mm))
# %%
# Generate pyramid sequence
n = int(input("Enter rows: "))
for i in range(n+1):
for j in range(1, i+1):
print(j, end="")
print()
# %%
# Multiplication table till 10
for i in range(1, 11):
for j in range(1, 11):
print(i, 'x', j, '=', (i*j))
print("")
| [
"ishani@kathuria.net"
] | ishani@kathuria.net |
987439b42c00b0d2b88c3321cf1b9710546aedfc | dd1922e5970fb259fb1c6d1ce523a61c0c0aac94 | /PlotScript.py | 4d114c9f60a6dcd5fef18d570f92ca681904ec68 | [] | no_license | aniliitb10/Graph_plotting | 4d07a9847fbe8af27a4d3f73716752922425a0fb | 54d56b5d20548ed7c12bde4fa6548e15c128862a | refs/heads/master | 2021-01-02T23:36:01.297414 | 2017-08-09T16:36:30 | 2017-08-09T16:36:30 | 99,502,828 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,287 | py | import matplotlib.pyplot as plt
import numpy as np
import math
margin_x = 0.0
margin_y = 1.0
numOfTicksOnYAxis = 11
numOfTicksOnXAxis = 11
font_size = 20
markers = ['s', 'o', 'p', '*', '8'] # ref:http://matplotlib.org/api/markers_api.html
colors = ['b', 'g', 'r', 'k', 'm'] # ref:http://matplotlib.org/api/colors_api.html
line_styles = ['-', '--', '-.', ':'] # ref:http://matplotlib.org/api/lines_api.html
counter = [0]
def plot(x, y, label=""):
counter[0] += 1
plt.plot(x, y)
plt.plot(x, y,
color=colors[counter[0] % len(colors)],
marker=markers[counter[0] % len(markers)],
linestyle=line_styles[counter[0] % len(line_styles)],
markersize=8,
label=label) # for the legend
def main():
x_axis = np.linspace(0, 2*np.pi, 100) # start, stop, number of divisions
y_axis_sin = [math.sin(x) for x in x_axis]
y_axis_cos = [math.cos(x) for x in x_axis]
y_axis_cos2x = [math.cos(2*x) for x in x_axis]
plot(x_axis, y_axis_sin, "sin(x)")
plot(x_axis, y_axis_cos, "cos(x)")
plot(x_axis, y_axis_cos2x, "cos(2x)")
min_x, max_x = min(x_axis), max(x_axis)
min_y, max_y = min(min(y_axis_sin), min(y_axis_cos)), max(max(y_axis_sin), max(y_axis_cos))
# draw y = 0
plt.plot([min_x - margin_x, max_x + margin_x], [0, 0], color='k')
# draw x = 0 line
# plt.plot([0, 0], [min_y - margin_y, max_y + margin_y], color='k')
# Fixing the length of axes
plt.xlim(min_x - margin_x, max_x + margin_x) # touple of min, max
plt.ylim(min_y - margin_y, max_y + margin_y) # touple of min, max
# Marking ticks on axes
plt.yticks(np.linspace(min_y - margin_y, max_y + margin_y, numOfTicksOnYAxis))
# plt.xticks: if an array of strings is provided as 2nd argument, it links with corresponding entry of 1st array
# x_ticks_array = ["0", "pi/2", "pi", "1.5*pi", "2* pi"]
# plt.xticks(np.linspace(0, 2*np.pi, len(x_ticks_array)), x_ticks_array),
plt.xticks(np.linspace(0, 2*np.pi, numOfTicksOnXAxis))
plt.xlabel("x-values (in radian)", fontsize=font_size)
plt.ylabel("Values", fontsize=font_size)
plt.title("sin(x), cos(x) and cos(2x)", fontsize=font_size)
plt.grid()
plt.legend()
plt.show()
plt.close()
main()
| [
"aniliitb10@gmail.com"
] | aniliitb10@gmail.com |
6b3f498770a1dfc3845ef9db19d864e6ef3dbe55 | f98a2875e0cdc84341fe8e37b11336368a257fe7 | /agents/product.py | a86acbd28d5e0c5f8555128eb791223b5eb52c56 | [
"MIT"
] | permissive | anhnguyendepocen/PolicySpace2 | eaa83533b7ad599af677ce69353841e665b447d0 | d9a450e47651885ed103d3217dbedec484456d07 | refs/heads/master | 2023-08-28T04:55:40.834445 | 2021-10-21T18:50:03 | 2021-10-21T18:50:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 298 | py |
class Product:
def __init__(self, product_id, quantity, price):
self.product_id = product_id
self.quantity = quantity
self.price = price
def __repr__(self):
return 'Product ID: %d, Quantity: %d, Price: %.1f' % (self.product_id, self.quantity, self.price)
| [
"furtadobb@gmail.com"
] | furtadobb@gmail.com |
9ef5d57d536f5c88f705b1032cc0936e2d4cd565 | f91a7469c9ae7727fe5abdbf54e9abd3f10ee737 | /testShapes.py | 7f69042c3b3ce4c2ce64e65f148f4eff0e411d60 | [] | no_license | dj03vand/Graphics | 5d6ea838d0c0550dce4c774f7bd0c510881b6579 | ad12dbb53d5d1ad64816ebd61eb0b626d8b15461 | refs/heads/master | 2020-04-19T05:31:36.131074 | 2019-01-28T15:54:59 | 2019-01-28T15:54:59 | 167,990,340 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 272 | py | from Shapes import *
c1 = Circle(5)
r1 = Rectangle(3,2)
c2 = Circle(3)
c3 = Circle(1)
r2 = Rectangle(1,1)
listShapes = [c1,r1,c2,c3,r2]
for item in listShapes:
print(item.toString())
print("Area: " + str(item.area()))
print("Perimeter: " + str(item.perimeter()))
| [
"dj03vand@siena.edu"
] | dj03vand@siena.edu |
f20ae13300ca5b6b6d5bf9cfb4ff8ce538a2144d | d65b8402277baf563d632f63a0dd097aaabc58c8 | /ecosmart/settings.py | 792cf4d6b6dda6821ad093ff63d08d4bc1fd2aa2 | [] | no_license | AjitJ01/echosmart | 546fcb126eaced53d3ff9e79e6e44d75d3936174 | 4c9abacd1455ceb957d461f3f3ed1e7a9c918095 | refs/heads/master | 2022-12-11T04:52:04.023802 | 2020-09-13T10:14:43 | 2020-09-13T10:14:43 | 292,631,857 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,759 | py | """
Django settings for ecosmart project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'is560k70n#cb^@xbvh56gxh(kp9)gc@cze-1!)@&t0cc&qgi5v'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
CORS_ORIGIN_WHITELIST = [
'http://127.0.0.1:4200',
'http://localhost:4200',
]
# Application definition
CORS_ORIGIN_ALLOW_ALL=True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'product',
'member_profile',
'user',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
ROOT_URLCONF = 'ecosmart.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ecosmart.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ecosmart',
'USER': 'root',
'PASSWORD': 'root',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'files')
MEDIA_URL = '/files/'
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
| [
"ajitj@druva.local"
] | ajitj@druva.local |
e06eb333e9351905b9f17d48acd4264dccb24973 | af30344da5c82ce3b5c65b962f0fdc0e6a70ba75 | /pythonIJ/function.py | e0e1d4c8d52486cf82f249d1ca4b417b4af685c0 | [] | no_license | udayabhishek/python | 6490b27db29d55e0705d83fe0b50cc510019a26e | 8e7cac66766b0c547dac2941e4d68f86170c71b3 | refs/heads/master | 2022-11-10T15:15:48.052511 | 2020-06-23T15:04:25 | 2020-06-23T15:04:25 | 272,762,381 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 340 | py | def user(name, *info):
print(name,info)
for item in info:
print(item)
user('ram', 1,2,3,4,"hi")
def userInfo(fname, lname, **userInfo):
userInfo['first_name'] = fname
userInfo['last_name'] = lname
return userInfo
userProfile = userInfo('ram', 'shayam', location='ayodhya', field = 'dharma')
print(userProfile) | [
"UD341583@wipro.com"
] | UD341583@wipro.com |
934c1811d723d3bdea5bbf35168370e4e8d8215e | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03145/s047914434.py | 5d829eaafb0ffcbf83b9454c4e85b5e4fd118c6a | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 82 | py | a,b,c=map(int,input().split())
aa=min(a,b)
bb=min(c,max(a,b))
print((aa*bb)//2)
| [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
94dc79bd4a390fef2cf961e89133f97b671c6bea | 549f20eca9a7ef50ee68680269cd2b071fde7e9e | /EPQ/EPQ/img_proc_func.py | 0dc24436726dab1c45e53ff1e039224114ce160c | [] | no_license | monkey-sheng/EPQ | 815d500cb2f84fa63f2a811aab179fc3623b270b | 03768cd5254a119756e8ebb6e187177f91b855b7 | refs/heads/master | 2020-04-17T03:06:42.348282 | 2019-04-04T03:01:51 | 2019-04-04T03:01:51 | 166,166,942 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,284 | py | from django.http import HttpResponse
from django.shortcuts import render
from PIL import Image
img_dict = {}
def img_proc(request,img,size):
session_key=request.session.session_key
img_dict[session_key]=[] # create a list to store the img for this session
size=int(size)
img=Image.open(img)
length = size
width = size
img1=img.resize((width,length))
img_dict[session_key].append(img1)
img2=img.resize((2*width,2*length))
img_dict[session_key].append(img2)
def img_return(request,img_id): #except is to handle the case of direct access
try:
session_key=request.session.session_key
if session_key is None:
raise ValueError # in case session_key is messed up and img results cannot be fetched using it
img_list=img_dict[session_key] # get the list of img from the dict for this session
img_id=int(img_id)
response=HttpResponse(content_type='img/png')
img_list[img_id-1].save(response,'png') # img_id starts from 1 for better url understanding
return response
except IndexError:
return render(request,'testproject/error_page.html')
except ValueError:
return HttpResponse("Session error: no active session")
| [
"noreply@github.com"
] | monkey-sheng.noreply@github.com |
29686d96ab46a59858ee3223ce247073765aac09 | 955920ccccee07f48486a02d94ed6808e17328fd | /parse_wiki.py | 40fe4a1ed85e61b926c80e19bcb6b9911c38575a | [] | no_license | GeorginaWilcox/govhack | 959db14895e0f11d62528afb17d8ca3cb39f98d7 | 8750fb6c6eb7478c3b55c8430d0600610b49ca36 | refs/heads/master | 2016-09-05T09:48:53.639876 | 2013-06-07T07:15:27 | 2013-06-07T07:15:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 270 | py | #!/usr/bin/python3
import xml.etree.ElementTree as etree
tree = etree.parse('wiki.xml')
root = tree.getroot()
for child in root:
if child.tag == "tr":
country = child[0]
for t in country:
if t.tag == "a":
print(t.text)
| [
"georginawilcox@gmail.com"
] | georginawilcox@gmail.com |
f372b031a486f46d98659827a1702cd2214b8922 | 4b272964c4d47ad1fdefd105f2c76e9c70b34570 | /adoptapetapp/migrations/0006_pet_description.py | cb947402d943488ab2fefe199288f4713b31af42 | [] | no_license | ozgemeva/adoptAPet | 0b9ef314ac82e3bedc15335df724a69f69b9d952 | 58b70c75d78f116fb25367bd6dfacd750540d91f | refs/heads/master | 2021-01-23T03:47:46.030438 | 2017-03-25T00:41:48 | 2017-03-25T00:41:48 | 86,121,361 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 483 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-02 19:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('adoptApetApp', '0005_auto_20170102_1850'),
]
operations = [
migrations.AddField(
model_name='pet',
name='description',
field=models.CharField(default='No Description', max_length=550),
),
]
| [
"ozgemeva@hotmail.com"
] | ozgemeva@hotmail.com |
f88ab3831636a1bcaddfb7640f4a637ef8ed63a0 | ae88172e4ab99bb879851f7c4304330028bf90d9 | /mito/occurence.py | a55830c84dfa22b1150c10c4fb1f1c4566720f2e | [] | no_license | ju-lab/cjy_projects | 1510cc91e86a648df91573bbb392e496b80c9299 | 6f746a9cd66818813661c5c33acc8cba8f67e29e | refs/heads/master | 2020-03-08T03:34:46.678373 | 2018-08-22T01:31:31 | 2018-08-22T01:31:31 | 127,895,333 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 987 | py | import pysam
import re
mt = pysam.FastaFile('./rCRS/chrMT.fa')
acccc_pos = []
for i in re.finditer(string=mt.fetch('MT'), pattern=r'ACCCC'):
acccc_pos.append(i.start() + 1)
tcccc_pos = []
for j in re.finditer(string=mt.fetch('MT'), pattern=r'TCCCC'):
tcccc_pos.append(j.start()+1)
# 10x greater vat rate in these positions=
high_vaf_pos = [72,152,204,248,263,302,310,316,515,567,750,1438,2487,3109,3492,6419,7028,10277,10306,12684,12705,12825,13062,13095,13105,13650,15326,16129,16183,16189,16218,16230,16249,16259,16263,16264,16274,16278,16284,16288,16293,16301,16311,16355,16356,16368,16390,16399,16427,16444,16496,16519,16527]
set(high_vaf_pos) & set(tcccc_pos)
set(high_vaf_pos) & set(acccc_pos)
"""
In [29]: len(acccc_pos)
Out[29]: 79
In [30]: len(tcccc_pos)
Out[30]: 50
In [31]: len(high_vaf_pos)
Out[31]: 53
In [42]: set(high_vaf_pos) & set(acccc_pos)
Out[42]: {302, 567, 2487, 6419, 10277, 16183}
In [43]: set(high_vaf_pos) & set(tcccc_pos)
Out[43]: {310, 16189}
"""
| [
"cjyoon@kaist.ac.kr"
] | cjyoon@kaist.ac.kr |
ff076d62b1e3ee0c2bcdbbb036e2b67089f77584 | bf1220aa8244280a4192647ebb202ba65eaa768c | /schema.py | 1e104b03d2fb224c2a525d03044bdba24fe1c7b7 | [] | no_license | dbritto-dev/django-graphql-domain-app-template | 2e47324b3e2567084d29e521e7af7bdc6e4a758f | 9a82e2a6680275fd61acd21ad41ba23f42a66f42 | refs/heads/master | 2023-01-04T09:09:20.623800 | 2020-10-30T01:41:58 | 2020-10-30T01:41:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,706 | py | # Built-in package
# Third-party packages
import graphene as gql
from django.db.transaction import atomic
# Local packages
from . import models, types, filters, crud
class Create{{ camel_case_app_name }}(types.{{ camel_case_app_name }}OutputMutation, gql.Mutation):
class Arguments:
data = types.{{ camel_case_app_name }}CreateInput(required=True)
@atomic
def mutate(
_root: models.{{ camel_case_app_name }}, _info: gql.ResolveInfo, data: types.{{ camel_case_app_name }}CreateInput,
) -> models.{{ camel_case_app_name }}:
return crud.create_{{ app_name }}(data)
class Update{{ camel_case_app_name }}(types.{{ camel_case_app_name }}OutputMutation, gql.Mutation):
class Arguments:
where = types.{{ camel_case_app_name }}WhereUniqueInput(required=True)
data = types.{{ camel_case_app_name }}UpdateInput(required=True)
@atomic
def mutate(
_root: models.{{ camel_case_app_name }}, _info: gql.ResolveInfo, where: types.{{ camel_case_app_name }}WhereUniqueInput, data: types.{{ camel_case_app_name }}UpdateInput,
) -> models.{{ camel_case_app_name }}:
return crud.update_{{ app_name }}(where, data)
class Delete{{ camel_case_app_name }}(types.{{ camel_case_app_name }}OutputMutation, gql.Mutation):
class Arguments:
where = types.{{ camel_case_app_name }}WhereUniqueInput(required=True)
@atomic
def mutate(
_root: models.{{ camel_case_app_name }}, _info: gql.ResolveInfo, where: types.{{ camel_case_app_name }}WhereUniqueInput,
) -> models.{{ camel_case_app_name }}:
return crud.delete_{{ app_name }}(where)
class Query(gql.ObjectType):
{{ app_name }} = gql.Field(types.{{ camel_case_app_name }}, where=types.{{ camel_case_app_name }}WhereUniqueInput(required=True))
{{ app_name }}s = gql.Field(gql.List(gql.NonNull(types.{{ camel_case_app_name }})), where=types.{{ camel_case_app_name }}WhereInput())
def resolve_{{ app_name }}(
_root: models.{{ camel_case_app_name }}, _info: gql.ResolveInfo, where: types.{{ camel_case_app_name }}WhereUniqueInput,
) -> models.{{ camel_case_app_name }}:
return crud.get_{{ app_name }}(where)
def resolve_{{ app_name }}s(
_root: models.{{ camel_case_app_name }}, _info: gql.ResolveInfo, where: types.{{ camel_case_app_name }}WhereInput = None,
) -> list[models.{{ camel_case_app_name }}]:
return crud.get_{{ app_name }}s(where)
class Mutation(gql.ObjectType):
create_{{ app_name }} = Create{{ camel_case_app_name }}.Field(required=True)
update_{{ app_name }} = Update{{ camel_case_app_name }}.Field()
delete_{{ app_name }} = Delete{{ camel_case_app_name }}.Field()
| [
"ddbn.c2@gmail.com"
] | ddbn.c2@gmail.com |
1e81b86a98a53879c756e4b7882215cd0a801927 | f326241710ec648c51ec1a87d6ccfc86cf96a828 | /smartsheet_share.py | e73e1891965260fa804d8ff75ff16821529dc066 | [] | no_license | wkliu/smartsheet | 7aef8c2140a3af30de92f449959e8c09000b84be | d5f3cd9166915bec7ad528cdb2cf17d0c558f6dd | refs/heads/master | 2020-03-29T13:28:27.504689 | 2019-05-06T10:07:34 | 2019-05-06T10:07:34 | 149,962,819 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,581 | py | import smartsheet
from myconfig import *
proxies = {'http': 'http://proxy.esl.cisco.com:80/', 'https':'http://proxy.esl.cisco.com:80/'}
#ss = smartsheet.Smartsheet(access_token=access_token, proxies=proxies)
ss = smartsheet.Smartsheet(access_token)
SEs=[davidtai, andrewyang, stanhuang, jimcheng, karlhsieh, vincenthsu, angelalin, barryhuang, vanhsieh, rickywang, tonyhsieh, willyhuang, jerrylin, allentseng, vinceliu]
DCSEs=[angelalin, allentseng, barryhuang, jimcheng, vinceliu]
ENSEs=[rickywang, karlhsieh, jerrylin, tonyhsieh]
SECSEs=[willyhuang, stanhuang, vincenthsu]
SPSEs=[davidtai, andrewyang, stanhuang]
COLSEs=[vanhsieh]
Share_Sheets = [destination_sheetIds["SP_SEVT_PL"]]
#COM_share = [destination_sheetIds["TOP5_COM"], destination_sheetIds["STA_COM"]]
#Share_Sheets = [destination_sheetIds["POST_SALE"]]
for se in SPSEs:
for item in Share_Sheets:
#print(se[item], se["email"])
newShareObj = ss.models.Share()
newShareObj.email = se["email"]
newShareObj.access_level = "EDITOR"
'''
if se in COLSEs:
newShareObj.access_level = "EDITOR"
else:
newShareObj.access_level = "VIEWER"
'''
print(newShareObj, item)
sheet = ss.Sheets.get_sheet(item)
sheet.share(newShareObj, send_email=False)
#sight = ss.Sights.share_sight(item, newShareObj, False)
#print(item)
#newShareObj = ss.models.Share()
#newShareObj.email = "angelin@cisco.com"
#newShareObj.access_level = "EDITOR"
#sheet = ss.Sheets.get_sheet(angelalin["KSO"])
#sheet.share(newShareObj)
| [
"wkliu228@gmail.com"
] | wkliu228@gmail.com |
466a55216de630473204039871d54f7d84b08ea2 | 8e2b6d920d60df64f589299156242d7bbc31106b | /apps/unit_conv_app/migrations/0002_subscriber.py | 601b37d866bdffd3f6d0ca824f9cb453740964b4 | [] | no_license | kurtw29/UnitConv | ba7d6c4ef72ba55ca893f461501192dff9a4751a | 779e94c2fe7e715bd9b920bfcea7fcbd5e2cb9c1 | refs/heads/master | 2020-03-27T00:04:10.826372 | 2018-11-14T15:21:42 | 2018-11-14T15:23:26 | 145,590,881 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 723 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-08-19 23:54
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('unit_conv_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Subscriber',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sub_email', models.CharField(max_length=255)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
]
| [
"ckurt37@gmail.com"
] | ckurt37@gmail.com |
423fa1cb328815906bfb72c7365fb8b0e574231d | 373e777a87ce94fee570579e7f4864ff69cccc98 | /posts/views.py | 810988d746aca8007822abdb2b61cfe21af63908 | [] | no_license | Vdkrt/technotrack-web1-spring-2017 | 9b0858c6ba6f4844fd889bddd8ab22c924cfff5d | 3ad5b4c2604726a5cb1caa5f44b42414cf314dee | refs/heads/master | 2021-01-17T05:56:59.178137 | 2017-04-03T20:59:55 | 2017-04-03T20:59:55 | 83,698,889 | 0 | 0 | null | 2017-03-02T16:21:10 | 2017-03-02T16:21:10 | null | UTF-8 | Python | false | false | 5,494 | py | # -*- coding: utf-8 -*-
from django.contrib.auth import get_user_model
from django.http import request
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView, UpdateView, CreateView
from comments.models import Comment
from .models import Blog, Post
from django import forms
from django.shortcuts import resolve_url
# Create your views here.
class SortBlogFrom(forms.Form):
sort = forms.ChoiceField(
choices=(
('title', u'Заголовок'),
('rate', u'Рейтинг'),
('description', u'Описание'),
('create_date', u'Дате публикации'),
),
required=False
)
search = forms.CharField(required=False)
class SortPostFrom(forms.Form):
sort = forms.ChoiceField(
choices=(
('title', u'Заголовок'),
('create_date', u'Дате публикации'),
),
required=False
)
search = forms.CharField(required=False)
class BlogsList(ListView):
queryset = Blog.objects.all()
template_name = 'posts/blogs.html'
def dispatch(self, request, *args, **kwargs):
self.sortform = SortBlogFrom(request.GET)
return super(BlogsList, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
queryset = super(BlogsList, self).get_queryset()
if self.sortform.is_valid():
if self.sortform.cleaned_data['sort']:
queryset = queryset.order_by(self.sortform.cleaned_data['sort'])
if self.sortform.cleaned_data['search']:
queryset = queryset.filter(title=self.sortform.cleaned_data['search'])
return queryset
def get_context_data(self, **kwargs):
context = super(BlogsList, self).get_context_data(**kwargs)
context['sortform'] = self.sortform
return context
class BlogView(ListView):
queryset = Post.objects.all()
template_name = 'posts/blog.html'
def dispatch(self, request, *args, **kwargs):
self.sortform = SortPostFrom(request.GET)
return super(BlogView, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
queryset = super(BlogView, self).get_queryset()
if self.sortform.is_valid():
if self.sortform.cleaned_data['sort']:
queryset = queryset.order_by(self.sortform.cleaned_data['sort'])
if self.sortform.cleaned_data['search']:
queryset = queryset.filter(title=self.sortform.cleaned_data['search'])
return queryset.filter(blog=self.kwargs['pk'])
def get_context_data(self, **kwargs):
context = super(BlogView, self).get_context_data(**kwargs)
context['sortform'] = self.sortform
context['blog'] = get_object_or_404(Blog, id=self.kwargs['pk'])
return context
class PostView(DetailView):
queryset = Post.objects.all()
template_name = 'posts/post.html'
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = ('title', 'description')
class UpdateBlog(UpdateView):
template_name = 'posts/editblog.html'
model = Blog
fields = ('title', 'description', 'category')
def get_queryset(self):
return Blog.objects.filter(author=self.request.user)
def get_success_url(self):
return resolve_url('blogs:oneblog', pk=self.object.id)
def form_valid(self, form):
form.instance.author = self.request.user
return super(UpdateBlog, self).form_valid(form)
class CreateBlog(CreateView):
template_name = 'posts/createblog.html'
model = Blog
fields = ('title', 'description', 'category')
def get_success_url(self):
return resolve_url('blogs:oneblog', pk=self.object.id)
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.rate = 0
return super(CreateBlog, self).form_valid(form)
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text')
class UpdatePost(UpdateView):
template_name = 'posts/editpost.html'
model = Post
fields = ('title', 'text')
def get_queryset(self):
return Post.objects.filter(author=self.request.user)
def get_success_url(self):
return resolve_url('blogs:onepost', pk=self.object.id)
def form_valid(self, form):
form.instance.author = self.request.user
return super(UpdatePost, self).form_valid(form)
class CreatePost(CreateView):
template_name = 'posts/createpost.html'
model = Post
fields = ('title', 'text', 'blog')
def get_form(self, **kwargs):
form = super(CreatePost, self).get_form()
form.fields['blog'].queryset = Blog.objects.all().filter(author = self.request.user)
return form
def get_success_url(self):
return resolve_url('blogs:onepost', pk=self.object.id)
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.rate = 0
#form.instance.blog = get_object_or_404(Blog, id=self.kwargs['pk'])
return super(CreatePost, self).form_valid(form)
def dispatch(self, request, *args, **kwargs):
blog = get_object_or_404(Blog, id=self.kwargs['pk'])
if blog.author == self.request.user:
return super(CreatePost, self).dispatch(request, *args, **kwargs)
else:
return redirect('error')
| [
"dnzl@bk.ru"
] | dnzl@bk.ru |
d8b55cb94184067e2e3d57f95ab20936d5d86e5e | c200119f4180ddc17dcaeb87d8bad6399442a529 | /tests/src/miniblog/settings.py | 4a49139d88b610ef74757746972a748e912302d5 | [] | no_license | marekmalek/django-observer | 3f4ae6ba1482f649d4495a95b95d4ec74f8222f2 | 3b9e4aeaaa9cd4cc4af7a245a185fb18e89e181a | refs/heads/master | 2021-01-18T06:59:34.588359 | 2012-08-31T16:31:25 | 2012-08-31T16:31:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,009 | py | # Django settings for weblog project.
import os
import sys
ROOT=os.path.join(os.path.dirname(__file__), '../../')
app_path=os.path.realpath(os.path.join(ROOT, '../'))
if app_path not in sys.path:
sys.path.insert(0, app_path)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT, 'database.db'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(ROOT, 'static'),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '4et6(22#@lgie4wogk)6um6^jklpkk0!z-l%uj&kvs*u2xrvfj%'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'miniblog.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(ROOT, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'miniblog.autocmd',
'miniblog.blogs',
)
FIXTURE_DIRS = (
os.path.join(ROOT, 'fixtures'),
)
LOGIN_REDIRECT_URL = '/'
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| [
"lambdalisue@hashnote.net"
] | lambdalisue@hashnote.net |
24c57c5a3592b7294a4d9838d10ad1930ad82c8b | 717cc419ab568e65ad15a28deb8238551f0291f8 | /sistemaEmpresa.py | d3ad84b96b48a78e83fc3c068ea25bab2717c5b8 | [] | no_license | danielfitipaldi/ExercicioHackaton | 4393b7211c3ab7213cef94f6085d83ee7214010b | 1198764f3753e65f0bab78c1f4d9ced59342f22f | refs/heads/master | 2022-11-26T07:12:35.651092 | 2020-07-15T04:33:07 | 2020-07-15T04:33:07 | 279,762,604 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,949 | py | # Bem vindo
print('-' * 30)
print('BEM VINDO AO SISTEMA DA SUA EMPRESA'.center(30))
print('-' * 30)
# Menu
funcionario = {}
quadroDeFucionarios = []
faturamentoEmpresa = metaEmpresa = partLucro = opcao = 0
while True:
try:
opcao = int(input('[ 1 ] Cadastrar Funcionário \n'
'[ 2 ] Alterar tempo de empresa \n'
'[ 3 ] Cadastrar valor da meta da empresa \n'
'[ 4 ] Cadastrar faturamento da empresa \n'
'[ 5 ] Exibir listagem de funcionários \n'
'[ 6 ] Sair \n'
'Escolha sua opção para prosseguir: '))
except (ValueError, TypeError, ZeroDivisionError):
print('Opção inválida.')
if opcao not in range(1, 7):
try:
opcao = int(input('Escolha uma das opções válidas para prosseguir: '))
except (ValueError, TypeError, ZeroDivisionError):
print('Opção inválida. ')
if opcao == 1:
funcionario.clear()
print('-' * 30)
print('CADASTRAR FUNCIONÁRIO'.center(30))
print('-' * 30)
funcionario['Nome'] = str(input('Nome: '))
funcionario['Idade'] = int(input('Idade: '))
funcionario['Tempo de empresa'] = int(input('Tempo de empresa (anos): '))
funcionario['Salario Mensal'] = float(input('Salário: '))
quadroDeFucionarios.append(funcionario.copy())
if opcao == 2:
print('-' * 30)
print('ALTERAR TEMPO DE EMPRESA'.center(30))
print('-' * 30)
nomeAlterado = str(input('Digite o nome do funcionário: '))
for c in range(len(quadroDeFucionarios)):
if quadroDeFucionarios[c]['Nome'].lower() == nomeAlterado.lower():
quadroDeFucionarios[c]['Tempo de empresa'] = int(input(f'Você deseja alterar o tempo de empresa '
f'de {quadroDeFucionarios[c]["Nome"]}. '
f'Qual o novo valor? '))
if opcao == 3:
print('-' * 30)
print('CADASTRAR VALOR DA META DA EMPRESA')
metaEmpresa = float(input('Meta da empresa em R$: '))
print('-' * 30)
if opcao == 4:
print('-' * 30)
print('CADASTRAR FATURAMENTO DA EMPRESA')
faturamentoEmpresa = float(input('Faturamento da empresa em R$: '))
print('-' * 30)
if opcao == 5:
print('-' * 30)
print('EXIBIR LISTAGEM DE FUNCIONÁRIOS')
# Participação no Lucro = (faturamento - meta da empresa) / total de funcionários
partLucro = (faturamentoEmpresa - metaEmpresa) / len(quadroDeFucionarios)
if faturamentoEmpresa > metaEmpresa:
for c in range(len(quadroDeFucionarios)):
if quadroDeFucionarios[c]['Tempo de empresa'] >= 10:
quadroDeFucionarios[c]['Salário Final'] = quadroDeFucionarios[c]['Salario Mensal'] + \
(quadroDeFucionarios[c]['Salario Mensal'] * 2 / 100) \
+ partLucro
else:
quadroDeFucionarios[c]['Salário Final'] = quadroDeFucionarios[c]['Salario Mensal'] + partLucro
else:
for c in range(len(quadroDeFucionarios)):
quadroDeFucionarios[c]['Salário Final'] = quadroDeFucionarios[c]['Salario Mensal']
for cadaFunc in quadroDeFucionarios:
print(f'Nome: {cadaFunc["Nome"]} Idade: {cadaFunc["Idade"]} Tempo de Empresa: {cadaFunc["Tempo de empresa"]} '
f'ano(s) Salário Mensal: {cadaFunc["Salario Mensal"]} Salário Final: {cadaFunc["Salário Final"]}')
print('-' * 30)
if opcao == 6:
break
print('-' * 30)
print('OBRIGADO E VOLTE SEMPRE!'.center(30))
print('-' * 30)
| [
"danielfitipaldi@iMac-de-Daniel.local"
] | danielfitipaldi@iMac-de-Daniel.local |
fd1a4d1c83ffe83564c83dbfa41797456e4e9e88 | 0425e745abf1a87624b55f1636aa3961806babcd | /phonebook/migrations/0001_initial.py | b78a10dd685699543e9bacea40c8be0e7b9ad20a | [
"MIT"
] | permissive | caiomartins1/phonebook | a802aee8ea74c9ff570466da32d86de7a653f5c7 | 2b694ed65964bdc3ee4c883c1a0f29a9cbf3a3e3 | refs/heads/main | 2023-01-01T11:14:39.857557 | 2020-10-19T18:09:28 | 2020-10-19T18:09:28 | 304,315,204 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 937 | py | # Generated by Django 3.1.2 on 2020-10-19 02:27
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),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=50)),
('second_name', models.CharField(max_length=50)),
('email', models.CharField(max_length=50)),
('phone_number', models.CharField(max_length=30)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"dev.caiomartins@gmail.com"
] | dev.caiomartins@gmail.com |
cb0fbdb98f51edb323e77ac971a051e4e5dbf795 | 3cda2dc11e1b7b96641f61a77b3afde4b93ac43f | /test/training_service/config/metrics_test/trial.py | 43e3ac1b4d66f7bd96f307c7314cbfb226ab1cdc | [
"MIT"
] | permissive | Eurus-Holmes/nni | 6da51c352e721f0241c7fd26fa70a8d7c99ef537 | b84d25bec15ece54bf1703b1acb15d9f8919f656 | refs/heads/master | 2023-08-23T10:45:54.879054 | 2023-08-07T02:39:54 | 2023-08-07T02:39:54 | 163,079,164 | 3 | 2 | MIT | 2023-08-07T12:35:54 | 2018-12-25T12:04:16 | Python | UTF-8 | Python | false | false | 818 | py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import time
import json
import argparse
import nni
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--dict_metrics", action='store_true')
args = parser.parse_args()
if args.dict_metrics:
result_file = 'expected_metrics_dict.json'
else:
result_file = 'expected_metrics.json'
nni.get_next_parameter()
with open(result_file, 'r') as f:
m = json.load(f)
time.sleep(5)
for v in m['intermediate_result']:
time.sleep(1)
print('report_intermediate_result:', v)
nni.report_intermediate_result(v)
time.sleep(1)
print('report_final_result:', m['final_result'])
nni.report_final_result(m['final_result'])
print('done')
| [
"noreply@github.com"
] | Eurus-Holmes.noreply@github.com |
f79e68250b1e1aee7f9af399d1bde8aad4a258fc | 6606a424c898116efdb7d2b940285559fd452eb3 | /morvanzhou/Q_learning/sarsa/sarsa_maze/maze_env.py | 387fafc12a91ced1980e90cb5272cd39068ef6d8 | [] | no_license | rain150403/RL_learning | 9d8e1629d5af2ad353f3deabd8fb7f43d82e8d77 | 9e0955f133887ef1ee39b17da06b7013cdad47d5 | refs/heads/master | 2021-09-12T14:19:59.171816 | 2018-04-17T14:23:23 | 2018-04-17T14:23:23 | 107,094,213 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,951 | py | """
Reinforcement learning maze example.
Red rectangle: explorer.
Black rectangles: hells [reward = -1].
Yellow bin circle: paradise [reward = +1].
All other states: ground [reward = 0].
This script is the environment part of this example.
The RL is in RL_brain.py.
View more on my tutorial page: https://morvanzhou.github.io/tutorials/
"""
import numpy as np
import time
import sys
if sys.version_info.major == 2:
import Tkinter as tk
else:
import tkinter as tk
UNIT = 40 # pixels
MAZE_H = 4 # grid height
MAZE_W = 4 # grid width
class Maze(tk.Tk, object):
def __init__(self):
super(Maze, self).__init__()
self.action_space = ['u', 'd', 'l', 'r']
self.n_actions = len(self.action_space)
self.title('maze')
self.geometry('{0}x{1}'.format(MAZE_H * UNIT, MAZE_H * UNIT))
self._build_maze()
def _build_maze(self):
self.canvas = tk.Canvas(self, bg='white',
height=MAZE_H * UNIT,
width=MAZE_W * UNIT)
# create grids
for c in range(0, MAZE_W * UNIT, UNIT):
x0, y0, x1, y1 = c, 0, c, MAZE_H * UNIT
self.canvas.create_line(x0, y0, x1, y1)
for r in range(0, MAZE_H * UNIT, UNIT):
x0, y0, x1, y1 = 0, r, MAZE_H * UNIT, r
self.canvas.create_line(x0, y0, x1, y1)
# create origin
origin = np.array([20, 20])
# hell
hell1_center = origin + np.array([UNIT * 2, UNIT])
self.hell1 = self.canvas.create_rectangle(
hell1_center[0] - 15, hell1_center[1] - 15,
hell1_center[0] + 15, hell1_center[1] + 15,
fill='black')
# hell
hell2_center = origin + np.array([UNIT, UNIT * 2])
self.hell2 = self.canvas.create_rectangle(
hell2_center[0] - 15, hell2_center[1] - 15,
hell2_center[0] + 15, hell2_center[1] + 15,
fill='black')
# create oval
oval_center = origin + UNIT * 2
self.oval = self.canvas.create_oval(
oval_center[0] - 15, oval_center[1] - 15,
oval_center[0] + 15, oval_center[1] + 15,
fill='yellow')
# create red rect
self.rect = self.canvas.create_rectangle(
origin[0] - 15, origin[1] - 15,
origin[0] + 15, origin[1] + 15,
fill='red')
# pack all
self.canvas.pack()
def reset(self):
self.update()
time.sleep(0.5)
self.canvas.delete(self.rect)
origin = np.array([20, 20])
self.rect = self.canvas.create_rectangle(
origin[0] - 15, origin[1] - 15,
origin[0] + 15, origin[1] + 15,
fill='red')
# return observation
return self.canvas.coords(self.rect)
def step(self, action):
s = self.canvas.coords(self.rect)
base_action = np.array([0, 0])
if action == 0: # up
if s[1] > UNIT:
base_action[1] -= UNIT
elif action == 1: # down
if s[1] < (MAZE_H - 1) * UNIT:
base_action[1] += UNIT
elif action == 2: # right
if s[0] < (MAZE_W - 1) * UNIT:
base_action[0] += UNIT
elif action == 3: # left
if s[0] > UNIT:
base_action[0] -= UNIT
self.canvas.move(self.rect, base_action[0], base_action[1]) # move agent
s_ = self.canvas.coords(self.rect) # next state
# reward function
if s_ == self.canvas.coords(self.oval):
reward = 1
done = True
elif s_ in [self.canvas.coords(self.hell1), self.canvas.coords(self.hell2)]:
reward = -1
done = True
else:
reward = 0
done = False
return s_, reward, done
def render(self):
time.sleep(0.1)
self.update()
| [
"noreply@github.com"
] | rain150403.noreply@github.com |
bd82b1c953e59a07098e957afa6fad1cf2bb16b3 | 5066bcb9b98b67be4297d77184a34520c5853f18 | /manage.py | a6f43a28825ef9a8c7b1d3da15876dadfad8f5e7 | [] | no_license | ndongamadu/mvaccination | 281fb2b6d8421588ba6136835203247d764a2fbe | f8fc5876508b84d25f914dc6d68ca9923f85e229 | refs/heads/master | 2020-03-24T18:24:46.288567 | 2018-09-13T11:49:42 | 2018-09-13T11:49:42 | 142,891,024 | 0 | 0 | null | 2018-09-13T11:49:43 | 2018-07-30T15:00:20 | Python | UTF-8 | Python | false | false | 544 | py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mvaccination.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| [
"ndongamadou@gmail.com"
] | ndongamadou@gmail.com |
ff73736dc6dfa421b3b2cd1e78d46948bf4ca591 | e3afba20e6f175fc91f1ee4c02ae7f18a45662ac | /move.py | a7cddc1e0878adbfb828e776ceb8614ed6223541 | [] | no_license | keselasela/find_rect | 18f588999e8e6c726b6eeead88c19d8c75d75a06 | 05e318b0342ebb17ed327c7c21bda911ab64160f | refs/heads/master | 2020-06-04T20:40:20.004680 | 2019-06-16T12:09:51 | 2019-06-16T12:09:51 | 192,184,458 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,319 | py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import pigpio
import time
import cv2
import numpy as np
import threading
pi = pigpio.pi()
X_MAX = 1700 #→
X_MIN = 900 #←
X_HOME = 1300
Y_MAX = 1500#下
Y_MIN = 800#上
Y_HOME = 900
#capture = cv2.VideoCapture(0)
#capture.set(3, 360)
#capture.set(4, 240)
#width = capture.get(3)
#height = capture.get(4)
# 左 ← 0 → 右
# 上 ← 0 → 下
#def move(degree_x, degree_y):
# duty_x = int(-degree_x + X_HOME)
# duty_y = int(degree_y + Y_HOME)
# pi.set_servo_pulsewidth(4, duty_x)
# pi.set_servo_pulsewidth(17, duty_y)
def move(degree_x, degree_y):
pi.set_servo_pulsewidth(4, degree_x)
pi.set_servo_pulsewidth(17, degree_y)
def main():
now_degree_x, now_degree_y, move_degree_x, move_degree_y = X_HOME,Y_HOME,0,0
move(X_HOME,Y_HOME)
th = threading.Thread(target=track)
th.setDaemon(True)
th.start()
while True:
ret, frame = capture.read()
cv2.imshow('Capture',frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
capture.release()
cv2.destroyAllWindows()
def track():
print(111)
while():
left,right = input().split(" ")
print(left,right)
move(left,right)
if __name__ == '__main__':
main() | [
"1230zakiyama@gmail.com"
] | 1230zakiyama@gmail.com |
78d183326b0a879a088d597454e4f919a84c51c4 | 8505b6fb190bee37ad38df73fed554b0f8d7b89c | /coaudicle-server.py | 4920b9e39e54166c113e9c1e7ef68f40056a07ec | [] | no_license | spencersalazar/coAudicle-server | e4fac50dc137f72c758a514389ba1fdcfc61febd | 107d7ca52c41c874ec08bfb6739087288bfa4f38 | refs/heads/master | 2020-05-15T09:08:57.821154 | 2014-09-05T16:48:56 | 2014-09-05T16:48:56 | 22,117,075 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,055 | py |
from twisted.web import server, resource
from twisted.internet import reactor, defer, task
from twisted.python import log
import types, uuid, json, cgi
from datetime import datetime, timedelta
import ago # pip install ago
DEFERRED_TIMEOUT=30.0 # seconds
class Site(server.Site):
def getResourceFor(self, request):
request.setHeader('Content-Type', 'application/json')
return server.Site.getResourceFor(self, request)
# shorthand convenience method
bind = types.MethodType
def bindPOST(parent, path):
def doit(f):
r = resource.Resource()
r.render_POST = bind(f, parent)
parent.putChild(path, r)
return doit
def bindGET(parent, path):
def doit(f):
r = resource.Resource()
r.render_GET = bind(f, parent)
parent.putChild(path, r)
return doit
def validateAction(action):
return True
def sanitizeAction(action):
return action
class Room(resource.Resource):
isLeaf = False
def __init__(self, name, uuid=None):
resource.Resource.__init__(self)
self._start = datetime.today()
self._members = []
self._name = name
if uuid == None:
uuid = uuid.uuid4().hex
self._uuid = uuid
self._actions = []
self._defers = []
self._cleanupTask = task.LoopingCall(self.cleanup)
self._cleanupTask.start(1)
# join action
@bindPOST(self, 'join')
def join_POST(self, request):
user_id = request.args['user_id'][0]
name = request.args['user_name'][0]
if not self.isMember(user_id):
self._members.append({ 'user_name': name, 'user_id': user_id })
self.postAction({ 'user_id': user_id, 'type': 'join', 'user_name': name })
return json.dumps({'status': 200, 'msg': 'OK'})
# leave action
@bindPOST(self, 'leave')
def leave_POST(self, request):
user_id = request.args['user_id'][0]
for member in self._members:
if member['user_id'] == user_id:
self._members.remove(member)
self.postAction({ 'user_id': user_id, 'type': 'leave' })
return json.dumps({'status': 200, 'msg': 'OK'})
# submit action
@bindPOST(self, 'submit')
def submit_POST(self, request):
user_id = request.args['user_id'][0]
action = json.loads(request.args['action'][0])
if not self.isMember(user_id):
request.setResponseCode(401)
return json.dumps({'status': 401, 'msg': 'Unauthorized'})
if not validateAction(action):
request.setResponseCode(400)
return json.dumps({'status': 400, 'msg': 'Bad request'})
action = sanitizeAction(action)
action['user_id'] = user_id
self.postAction(action)
return json.dumps({'status': 200, 'msg': 'OK'})
# retrieve action(s)
@bindGET(self, 'actions')
def actions_GET(self, request):
if 'after' in request.args:
after = int(request.args['after'][0])
if after+1 < len(self._actions):
return self.renderActions(request, after)
else:
d = defer.Deferred()
d.request = request
d.timestamp = datetime.today()
d.addCallback(self.renderActions, after, True)
self._defers.append(d)
return server.NOT_DONE_YET
else:
return self.renderActions(request)
def render_GET(self, request):
# just list room members
arr = []
for member in self._members:
arr.append({ 'user_name': member['user_name'] })
return json.dumps(arr)
def renderActions(self, request, after=None, async=False):
if after is not None:
data = json.dumps(self._actions[after+1:])
else:
data = json.dumps(self._actions)
if async:
request.write(data)
request.finish()
else:
return data
def postAction(self, action):
action['aid'] = len(self._actions)
self._actions.append(action)
for defer in self._defers:
defer.callback(defer.request)
del self._defers[:]
def cleanup(self):
# cleanup defers that have timeed out for > 10 seconds
defers = []
for defer in self._defers:
if (datetime.today() - defer.timestamp) > timedelta(seconds=DEFERRED_TIMEOUT):
defer.callback(defer.request)
else:
defers.append(defer)
self._defers = defers
def isMember(self, user_id):
for member in self._members:
if member['user_id'] == user_id:
return True
return False
def __str__(self):
return '%d %s - active %s' % (len(self._members), "member" if len(self._members) == 1 else "members", ago.human(datetime.today() - self._start, 1, past_tense = '{0}',))
class Rooms(resource.Resource):
isLeaf = False
def __init__(self):
resource.Resource.__init__(self)
self._rooms = []
def addRoom(self, name, uuid=None):
room = Room(name, uuid)
self._rooms.append(room)
self.putChild(room._uuid, room)
def render_GET(self, request):
arr = []
for room in self._rooms:
arr.append({ 'name': room._name, 'uuid': room._uuid, 'info': str(room) })
return json.dumps(arr)
root = resource.Resource()
rooms = Rooms()
rooms.addRoom('global', 'global')
root.putChild('rooms', rooms)
site = Site(root)
reactor.listenTCP(8080, site)
reactor.run()
| [
"spencer.salazar@gmail.com"
] | spencer.salazar@gmail.com |
b0504f6fbbe712366d92f283d5cbb43334f0bf11 | e4cbd82358ba5e8b4d4bacefa054e4ecda2d1517 | /config/settings_base.py | 622ff272b323de19ec535a9f28658818391172f6 | [] | no_license | mziegler/UssdDjangoDemo | a69ca95010443e5925fdf181904da05e9938bcc3 | 9b29eb562a7832aa6a033daf1bee8d99746ee93b | refs/heads/master | 2020-07-21T18:16:40.325034 | 2017-07-01T00:42:40 | 2017-07-01T00:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,480 | py | """
Django settings for djangoUSSD project.
Generated by 'django-admin startproject' using Django 1.9.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(PROJECT_DIR, ...)
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_DIR = os.path.join(PROJECT_DIR,'config')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'q@^7+k@94i7&x58y(czx*&zw7g+x2i!7%hwmj^fr$qey(a^%e9'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Site Apps
'UssdHttp',
'UssdDemo',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['UssdHttp/simulator/static'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(CONFIG_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Session Settings
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR,'UssdHttp/simulator/static'),
)
| [
"t.perrier@gmail.com"
] | t.perrier@gmail.com |
2d507377a10d3350cc729739daf540151c9c4dc8 | 2e4169290bf115e62cebe1a51ce1dc1528bc2cd2 | /trunk/vlist/vlist.py | 703c11e359dcaf87b186f2001be0c4794c72d3e8 | [] | no_license | BGCX067/ezwidgets-svn-to-git | 6c96bb408369316d395f6c8836b8e7be063ae0d8 | 2864f45bc3e9d87b940b34d0fa6ce64e712c2df8 | refs/heads/master | 2021-01-13T09:49:25.511902 | 2015-12-28T14:19:53 | 2015-12-28T14:19:53 | 48,833,330 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,324 | py | #----------------------------------------------------------------------------
# Name: vlist.py
# Purpose: virtual list with mix-in ColumnSorter class
#
# Author: Egor Zindy
#
# Created: 26-June-2005
# Licence: public domain
#----------------------------------------------------------------------------
import wx
import wx.lib.mixins.listctrl as listmix
class VirtualList(wx.ListCtrl, listmix.ColumnSorterMixin):
def __init__(self, parent,columns,style=0):
wx.ListCtrl.__init__( self, parent, -1,
style=wx.LC_REPORT|wx.LC_VIRTUAL|style)
listmix.ColumnSorterMixin.__init__(self, len(columns))
self.itemDataMap={}
self.il = wx.ImageList(16, 16)
self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
self.il_symbols={}
#adding some art (sm_up and sm_dn are used by ColumnSorterMixin
#symbols can be added to self.il using SetSymbols
symbols={"sm_up":wx.ART_GO_UP,"sm_dn":wx.ART_GO_DOWN}
self.SetSymbols(symbols)
#building the columns
self.SetColumns(columns)
#---------------------------------------------------
# These methods are callbacks for implementing the
# "virtualness" of the list...
def OnGetItemText(self, item, col):
index=self.itemIndexMap[item]
s = self.itemDataMap[index][col]
return s
def OnGetItemImage(self, item):
return -1
def OnGetItemAttr(self, item):
return None
#---------------------------------------------------
# These methods are Used by the ColumnSorterMixin,
# see wx/lib/mixins/listctrl.py
def GetListCtrl(self):
return self
def GetSortImages(self):
return self.il_symbols["sm_dn"],self.il_symbols["sm_up"]
def SortItems(self,sorter=None):
r"""\brief a SortItem which works with virtual lists
The sorter is not actually used (should it?)
"""
#These are actually defined in ColumnSorterMixin
#col is the column which was clicked on and
#the sort flag is False for descending (Z->A)
#and True for ascending (A->Z).
col=self._col
#creating pairs [column item defined by col, key]
items=[]
for k,v in self.itemDataMap.items():
items.append([v[col],k])
#sort the pairs by value (first element), then by key (second element).
#Multiple same values are okay, because the keys are unique.
items.sort()
#getting the keys associated with each sorted item in a list
k=[key for value, key in items]
#False is descending (starting from last)
if self._colSortFlag[col]==False:
k.reverse()
#storing the keys as self.itemIndexMap (is used in OnGetItemText,Image,ItemAttr).
self.itemIndexMap=k
#redrawing the list
self.Refresh()
#---------------------------------------------------
# These methods should be used to interact with the
# controler
def SetItemMap(self,itemMap):
r"""\brief sets the items to be displayed in the control
\param itemMap a dictionary {id1:("item1","item2",...), id2:("item1","item2",...), ...} and ids are unique
"""
l=len(itemMap)
self.itemDataMap=itemMap
self.SetItemCount(l)
#This regenerates self.itemIndexMap and redraws the ListCtrl
self.SortItems()
def SetColumns(self,columns):
r"""\brief adds columns to the control
\param columns a list of columns (("name1",width1),("name2",width2),...)
"""
i=0
for name,s in columns:
self.InsertColumn(i, name)
self.SetColumnWidth(i, s)
i+=1
def SetSymbols(self,symbols,provider=wx.ART_TOOLBAR):
r"""\brief adds symbols to self.ImageList
Symbols are provided by the ArtProvider
\param symbols a dictionary {"name1":wx.ART_ADD_BOOKMARK,"name2":wx.ART_DEL_BOOKMARK,...}
\param provider an optional provider
"""
for k,v in symbols.items():
self.il_symbols[k]=self.il.Add(wx.ArtProvider_GetBitmap(v,provider,(16,16)))
| [
"you@example.com"
] | you@example.com |
b8757c2faa9762ba75335651117bff56af634c5e | ccdf76ab5339a7447ebedb4852fc2c101d194694 | /Docs/source/conf.py | ac209ed211c04bf844287ac157e576938ab26296 | [
"Apache-2.0"
] | permissive | haliembabiker/syndrome_decoding_estimator | 06da1aa9351f4a031951beccadb99b550b260772 | c7d9aaeed83708dbf5db3c45a007c0010a1225c8 | refs/heads/master | 2023-08-14T06:44:34.534062 | 2021-09-20T12:10:06 | 2021-09-20T12:10:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,972 | py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------
project = 'Syndrome Decoding Estimator'
copyright = '2021, Esser, Andre and Bellini, Emanuele'
author = 'Esser, Andre and Bellini, Emanuele'
# The full version, including alpha/beta/rc tags
release = '1.0'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
| [
"andre.esser@tii.ae"
] | andre.esser@tii.ae |
bfeaaddab99e19c986bbf1ccfbc6810fe93b3b11 | f36d296f90ad941d55b7f4345564a2c6de96fcb3 | /src/ShapeOpMeshIndexer.py | a78b7a329e5b6e5c4579df2e4657a710452e65a2 | [] | no_license | AndersDeleuran/ShapeOpGHPython | d40a278b60fbf01b84070e3ab32e86410c222539 | c4f6b747983dfd9acbd510e1c8fff231c86e8322 | refs/heads/master | 2021-06-04T08:08:21.549078 | 2020-05-21T07:58:32 | 2020-05-21T07:58:32 | 24,236,891 | 44 | 8 | null | null | null | null | UTF-8 | Python | false | false | 6,849 | py | """
Extract vertex indices from a mesh using various patterns.
-
Authors: Anders Holden Deleuran (CITA/KADK), Mario Deuss (LGG/EPFL)
Github: github.com/AndersDeleuran/ShapeOpGHPython
Updated: 150401
Args:
Pattern:
The vertex indices pattern to extract from the mesh:
-
faceVertices = vertex indices for each face.
vertexNeighbours = neighbour vertex indices for each vertex.
edgeVertices = vertex indices for each edge.
verticesAll = vertex indices for each vertex (flat list).
verticesEach = vertex indices for each vertex (datatree).
edgeFaceVertices = neighbour face-vertex indices for each edge.
faceAngleVertices = neighbour vertices for each vertex corner for each face.
nakedVertices = vertices on the perimeter of the mesh, sorted by closed loops.
Mesh: The mesh to extract vertex indices from.
Returns:
PointIndices: The vertex indices pattern.
"""
import Grasshopper as gh
# Set component name
ghenv.Component.Name = "ShapeOpMeshIndexer"
ghenv.Component.NickName = "SOMI"
def getFaceVertices(mesh):
""" Get datatree with the face vertex indices for each face in a mesh """
faceVertices = gh.DataTree[int]()
for i in range(Mesh.Faces.Count):
fl = Mesh.Faces.Item[i]
if fl.IsQuad:
fIDs = (fl.A,fl.B,fl.C,fl.D)
else:
fIDs = (fl.A,fl.B,fl.C)
faceVertices.AddRange(fIDs,gh.Kernel.Data.GH_Path(i))
return faceVertices
def getVertexNeighbours(mesh):
""" Get datatree with the vertex plus vertex neighbour indices
for each vertex in a mesh """
vertexNeighbours = gh.DataTree[int]()
for i in range(Mesh.Vertices.Count):
vnIDs = [i] + list(Mesh.Vertices.GetConnectedVertices(i))
vertexNeighbours.AddRange(vnIDs,gh.Kernel.Data.GH_Path(i))
return vertexNeighbours
def getEdgeVertices(mesh):
""" Get datatree with the edge vertex indices for each edge in mesh """
# Get edge vertices
edges = []
for i in range(Mesh.Vertices.Count):
neighbours = Mesh.Vertices.GetConnectedVertices(i)
for n in neighbours:
if n > i:
edges.append((i,n))
# Make datatree
edgeVertices = gh.DataTree[int]()
for i,e in enumerate(edges):
edgeVertices.AddRange(e,gh.Kernel.Data.GH_Path(i))
return edgeVertices
def getVerticesEach(mesh):
""" Get datatree with the index of each vertex in a mesh """
verticesEach = gh.DataTree[int]()
for i in range(Mesh.Vertices.Count):
verticesEach.AddRange([i],gh.Kernel.Data.GH_Path(i))
return verticesEach
def getVerticesAll(mesh):
""" Get a list with all the vertex indices of a mesh """
verticesAll = range(mesh.Vertices.Count)
return verticesAll
def getEdgeFaceVertices(mesh):
""" Get datatree with the four/six face vertex indices for each mesh edge,
which is used to construct the shapeop bending constraint signature """
# Make GH datatree
edgeFaceVerticesPtIDs = gh.DataTree[int]()
for i in range(mesh.TopologyEdges.Count):
p = gh.Kernel.Data.GH_Path(i)
if len(mesh.TopologyEdges.GetConnectedFaces(i)) == 2:
# Get edge vertex indices
tVts = mesh.TopologyEdges.GetTopologyVertices(i)
eVtA = mesh.TopologyVertices.MeshVertexIndices(tVts.I)[0]
eVtB = mesh.TopologyVertices.MeshVertexIndices(tVts.J)[0]
eVts = set((eVtA,eVtB))
# Get edge face vertex index
fA,fB = mesh.TopologyEdges.GetConnectedFaces(i)
fVtsA = mesh.Faces.GetTopologicalVertices(fA)
fVtsB = mesh.Faces.GetTopologicalVertices(fB)
fVtsA = [mesh.TopologyVertices.MeshVertexIndices(i)[0] for i in fVtsA]
fVtsB = [mesh.TopologyVertices.MeshVertexIndices(i)[0] for i in fVtsB]
fVts = set(fVtsA + fVtsB)
# Get the face indices which are not part of the edge
fVts = list(fVts - eVts)
# Make the bending constraint point indices list
eFVIDs = list(eVts) + fVts
edgeFaceVerticesPtIDs.AddRange(eFVIDs,p)
return edgeFaceVerticesPtIDs
def getFaceAngleVertices(mesh):
""" Get datatree with the face angle vertex indices for each face in a mesh """
faceVertices = gh.DataTree[int]()
n = 0
for i in range(Mesh.Faces.Count):
fl = Mesh.Faces.Item[i]
if fl.IsQuad:
faceVertices.AddRange((fl.A,fl.B,fl.D),gh.Kernel.Data.GH_Path(n+0))
faceVertices.AddRange((fl.B,fl.C,fl.A),gh.Kernel.Data.GH_Path(n+1))
faceVertices.AddRange((fl.C,fl.D,fl.B),gh.Kernel.Data.GH_Path(n+2))
faceVertices.AddRange((fl.D,fl.A,fl.C),gh.Kernel.Data.GH_Path(n+3))
n += 4
else:
faceVertices.AddRange((fl.A,fl.B,fl.C),gh.Kernel.Data.GH_Path(n+0))
faceVertices.AddRange((fl.B,fl.C,fl.A),gh.Kernel.Data.GH_Path(n+1))
faceVertices.AddRange((fl.C,fl.A,fl.B),gh.Kernel.Data.GH_Path(n+2))
n += 3
return faceVertices
def getNakedVertices(mesh):
""" Get datatree with indices of naked vertices, sorted by closed loops """
# Get naked edges as polylines and naked edge status
npl = list(mesh.GetNakedEdges())
nvts = mesh.GetNakedEdgePointStatus()
# Sort the naked vertices by which polyline they belong to
nakedVertices = gh.DataTree[int]()
for i,v in enumerate(nvts):
if v:
for j,pl in enumerate(npl):
p = gh.Kernel.Data.GH_Path(j)
if pl.Contains(mesh.Vertices.Item[i]):
nakedVertices.Add(i,p)
return nakedVertices
if Mesh and Pattern:
if Pattern == "faceVertices":
PointIndices = getFaceVertices(Mesh)
elif Pattern == "edgeVertices":
PointIndices = getEdgeVertices(Mesh)
elif Pattern == "vertexNeighbours":
PointIndices = getVertexNeighbours(Mesh)
elif Pattern == "verticesEach":
PointIndices = getVerticesEach(Mesh)
elif Pattern == "verticesAll":
PointIndices = getVerticesAll(Mesh)
elif Pattern == "edgeFaceVertices":
PointIndices = getEdgeFaceVertices(Mesh)
elif Pattern == "faceAngleVertices":
PointIndices = getFaceAngleVertices(Mesh)
elif Pattern == "nakedVertices":
PointIndices = getNakedVertices(Mesh)
else:
PointIndices = [] | [
"andersdeleuran@outlook.com"
] | andersdeleuran@outlook.com |
5c9f18e7a55cc50e630488c58245d016ff55cd15 | 1838a2f3660c654147dcf55507472b6746506302 | /examples/zeus_malware.py | 5ae4a0f78d0df2d29ed21d7e5dc434f299767f48 | [] | no_license | EdwardOwusuAdjei/AIengine-xtra | 5eaa1f44f0b318462c07913b49bcec68bff35638 | d4cc87068a1683786c6eb33faf84f11a6d46030e | refs/heads/master | 2021-01-10T17:10:34.989045 | 2016-02-17T19:38:59 | 2016-02-17T19:38:59 | 51,943,608 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,735 | py | #!/usr/bin/env python
""" Example for analyse URIs and Host for detect Zeus Malware """
__author__ = "Luis Campo Giralte"
__copyright__ = "Copyright (C) 2013-2016 by Luis Campo Giralte"
__revision__ = "$Id$"
__version__ = "0.1"
import sys
import os
import base64
import glob
sys.path.append("../src/")
import pyaiengine
def callback_uri(flow):
print("Zeus activity detected on flow",str(flow))
def callback_host(flow):
h = flow.http_info
if (h):
host = str(h.host_name)
if (host):
print("Suspicious activity detected on flow",str(flow),host)
if __name__ == '__main__':
st = pyaiengine.StackLan()
data = dict()
# Load the hosts and Urls on memory
# The list have been download from https://zeustracker.abuse.ch/blocklist.php?download=compromised
h_mng = pyaiengine.DomainNameManager()
with open("zeus.dat") as f:
for line in f.readlines():
l = line.strip()
b = l.find("/")
r_host = l[:b]
r_uri = l[b:]
if (not data.has_key(r_host)):
h = pyaiengine.DomainName(r_host,r_host)
s = pyaiengine.HTTPUriSet("Set for %s" % r_host)
h.callback = callback_host
h_mng.add_domain_name(h)
h.http_uri_set(s)
s.callback = callback_uri
data[r_host] = (h,s)
data[r_host][1].addURI(r_uri)
""" Plug the DomainNameManager on the HTTPProtocol """
st.setDomainNameManager(h_mng,"HTTPProtocol")
st.tcp_flows = 500000
st.udp_flows = 163840
with pyaiengine.PacketDispatcher("eth0") as pd:
pd.stack = st
pd.run()
print h_mng
sys.exit(0)
| [
"luis@localhost.localdomain"
] | luis@localhost.localdomain |
2af8ec4894b212eef1676f0c2641ff8cfdc7bb64 | bb23a193f3da6695ba2e5946cd0ceb4073426f4e | /pixel/pixel.py | e4620db75353f69e482bd27a87869d2a58582a3a | [] | no_license | PixelTool/pixelpy | a1d25fb7538b6f67890e4f8887ffa0900e2c7bbf | c3c37a3b7d9422ddf26d6f8f1d3a48fc9d045857 | refs/heads/master | 2021-01-10T15:57:13.589070 | 2015-09-02T11:56:45 | 2015-09-02T11:56:45 | 36,861,161 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,020 | py | # coding=utf-8
import logging
from .filters import Filter
logging.basicConfig(
format="%(levelname) -10s %(asctime)s %(module)s:%(lineno)s %(funcName)s %(message)s",
level=logging.CRITICAL
)
def parse(selector, rule, ps=None):
if not rule:
return None
rst = {}
r_name = rule.get('name')
r_type = rule.get('type')
r_def = rule.get('def')
r_source = rule.get('source')
r_selector = None
if r_source:
r_selector = r_source.get('selector')
if r_name == u'[root]':
if r_type == u'{}':
rst = result_for_rule_type_dict(selector, r_selector, r_def)
elif r_type == u'[]':
rst = result_for_rule_type_array(selector, r_selector, r_def)
else:
rst['name'] = r_name
if r_type == u'string':
if r_source:
r = result_for_rule_type_string(selector, r_source, ps)
rst['value'] = r
if isinstance(r, list):
rst['len'] = len(r)
else:
rst['value'] = None
elif r_type == u'{}':
r = result_for_rule_type_dict(selector, r_selector, r_def)
rst['value'] = r
elif r_type == u'[]':
r = result_for_rule_type_array(selector, r_selector, r_def)
rst['value'] = r
logging.debug('>>> %s %s %s', r_name, r_selector, rst)
return rst if rst and len(rst) > 0 else None
def result_for_rule_type_dict(selector, r_selector, r_def):
result = {}
for i in r_def:
r = None
if r_selector:
try:
s_selector = i['source']['selector']
result = parent_and_child(r_selector, s_selector)
i['source']['selector'] = result['sub']
r = parse(selector, i, result['ps'])
except Exception, e:
print e
else:
r = parse(selector, i)
try:
if r and r['name'] and r['value']:
result[r['name']] = r['value']
except Exception, e:
pass
return result
def result_for_rule_type_array(selector, r_selector, r_def):
result = []
if r_selector:
parent = None
for i in r_def:
try:
s_selector = i['source']['selector']
ret = parent_and_child(r_selector, s_selector)
parent = ret['ps']
if parent:
i['source']['selector'] = ret['sub']
except Exception, e:
pass
if parent:
items = selector.css(parent)
for item in items:
tempValue = {}
for i in r_def:
r = parse(item, i)
try:
if r and r['name'] and r['value']:
tempValue[r['name']] = r['value']
except Exception, e:
raise e
if tempValue and len(tempValue):
result.append(tempValue)
else:
result = result_for_array_without_parent_selector(selector, r_def)
else:
result = result_for_array_without_parent_selector(selector, r_def)
return result
def result_for_array_without_parent_selector(selector, r_def):
result = []
temp_rst = []
logging.debug('>>> %s', r_def)
for i in r_def:
r = parse(selector, i, '[]')
logging.debug(r)
try:
if r and r['name'] and r['value']:
temp_rst.append(r)
except Exception, e:
pass
maxLen = 0
for i in temp_rst:
try:
length = i['len']
maxLen = length if length > maxLen else maxLen
except Exception, e:
pass
for i in xrange(0, maxLen):
r = {}
for j in temp_rst:
try:
item = j['value']
val = item[i]
if val:
r[j['name']] = val
except Exception, e:
pass
if len(r):
result.append(r)
return result
def result_for_rule_type_string(selector, source, ps=None):
if not source:
return None
result = None
method = source.get('method')
r_selector = source.get('selector')
r_filter = source.get('filter')
if not ps:
result = ''.join(result_with_method(selector, r_selector, method))
if r_filter:
filt = Filter(result, r_filter)
result = filt.result().strip()
elif ps == '[]':
"""
|ref| result_for_array_without_parent_selector
"""
result = result_with_method(selector, r_selector, method)
if r_filter:
filt = Filter(None, r_filter)
temp = []
for i in result:
filt.value = i
r = filt.result()
logging.info(']]] %s', r)
if r and r.strip():
temp.append(r.strip())
result = temp
else:
temp = selector.css(ps)
if len(temp) > 0:
selector = temp[0]
result = ''.join(result_with_method(selector, r_selector, method))
if r_filter:
filt = Filter(result, r_filter)
result = filt.result().strip()
return result
def result_with_method(selector, r_selector, method):
result = None
if method == u'text':
result = selector.css(r_selector + '::text').extract()
elif method == u'html':
result = selector.css(r_selector).extract()
elif method.find(u'[') != -1:
attr = method.lstrip('[').rstrip(']')
result = selector.css(r_selector + '::attr(' + attr + ')').extract()
return result
def parent_and_child(parent, child):
arrp = parent.split('>')
p_length = len(arrp)
arrc = child.split('>')
ps = '>'.join(arrp).strip()
sub = '>'.join(arrc[p_length:]).strip()
return {'ps': ps, 'sub': sub}
| [
"docdedi@gmail.com"
] | docdedi@gmail.com |
5f7b5a15c9442a8a6d69e574837dd9b9db1641db | 329bf886f90cdcc5b083d2ab47c529f5df95767b | /survey/views.py | 7a2375bebe6f6c999d7383dd539267dda614e1e5 | [] | no_license | leliel12/otree_saral | f4a16073479836df36789a58a311a8dc0e2fd7f5 | d4c91e1b9451460a656f270fe9f540bf811a9a32 | refs/heads/master | 2021-01-10T08:39:39.278589 | 2015-10-26T00:53:29 | 2015-10-26T00:53:29 | 43,258,370 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 697 | py | # -*- coding: utf-8 -*-
from __future__ import division
from . import models
from ._builtin import Page, WaitPage
from otree.common import Currency as c, currency_range
from .models import Constants
class Question(Page):
form_model = models.Player
form_fields = ["name", "age", "email", "gender", "major",
"location_of_your_partners_influence_your_decisions",
"working_in_a_location_of_their_choice_more_less_to_the_team",
"partners_in_location_their_choice_worked_harder_than_the_lab",
"I_work_best_in", "risks_in_everyday_life", "risks_in_financial_decision"]
page_sequence = [Question]
| [
"jbc.develop@gmail.com"
] | jbc.develop@gmail.com |
8f3a6baafb25b129e6233a39d872b7165f14a823 | 9e2df3fb58cf5eac085cc88432a89b044c1bca33 | /blog/migrations/0003_post_tags.py | 9249b54f14da287648ba0f5125392cdf4aabe66d | [
"MIT"
] | permissive | jedrek1993/django_blog | b78eea253eddf9ad5ca5aebdb9232b1b311206ea | 9141b33be862cb4c59e9b0459852310bbf6d5f36 | refs/heads/master | 2020-08-02T11:05:54.328401 | 2019-11-14T09:00:18 | 2019-11-14T09:00:18 | 211,329,284 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 549 | py | # Generated by Django 2.2.5 on 2019-09-29 10:14
from django.db import migrations
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('blog', '0002_comment'),
]
operations = [
migrations.AddField(
model_name='post',
name='tags',
field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
),
]
| [
"jedrek1993@gmail.com"
] | jedrek1993@gmail.com |
584b006defbe2d0cd59210e2e3608c5a4121c9b2 | ce02d4b31a041ea8e92a9542e2e315cdc69e843f | /comments/models.py | da10c5e8954c8d9caed765062b0e19bd18534fa7 | [] | no_license | qwiukj/blog | 63ab37cde8e365624311deb8f36da5b8b1e4dbb6 | 93950c18777cb17330e677e5e4c0fc3680787ebf | refs/heads/master | 2021-04-05T23:39:41.551209 | 2018-03-10T07:50:23 | 2018-03-10T07:50:23 | 124,496,337 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 519 | py | from django.db import models
from django.utils.six import python_2_unicode_compatible
# python_2_unicode_compatible 装饰器用于兼容 Python2
@python_2_unicode_compatible
class Comment(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=255)
url = models.URLField(blank=True)
text = models.TextField()
created_time = models.DateTimeField(auto_now_add=True)
post = models.ForeignKey('blogs.Post')
def __str__(self):
return self.text[:20] | [
"1454124891@qq.com"
] | 1454124891@qq.com |
cddc5a4cc036862742efa3f7d3499f4c6a1f3fac | 6c60b64944447c0578b6ab11fb33078d61c54df2 | /ErrorPlot.py | 6b1961b3448aba2c839eaaf2d286617497f86716 | [] | no_license | BDEvan5/Motion-Capture-System | 3add73f9cf9e50469a6aa9a5e7facac9fbe02c44 | 8041911fbf2dfa34afee7d77dbd775e3f55f333e | refs/heads/master | 2022-12-13T17:51:55.965391 | 2020-09-10T17:01:00 | 2020-09-10T17:01:00 | 294,402,913 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,315 | py |
from matplotlib import pyplot as plt
import scipy.io as sio
import numpy as np
class ErrorPlot:
def __init__(self, session=1, stream_nums=[1, 2, 3], indep=[1, 2, 3]):
self.session = session
self.stream = stream_nums
self.ses_length = len(self.stream)
self.analysis_list = []
self.indep = indep
for i in range(self.ses_length):
obj = AnalysisData()
obj.set_path(self.session, self.stream[i])
self.analysis_list.append(obj)
self.error_list = []
self.std_list = []
def calculate_errors(self):
for obj, i in zip(self.analysis_list, range(len(self.analysis_list))):
print("Stream: " + str(self.stream[i]) + " --> Independent variable: " + str(self.indep[i]))
err, std = obj.run_error_analysis()
self.error_list.append(err)
self.std_list.append(err)
def plot_graph(self, indep_name):
plt.figure(1)
plt.plot(self.indep, self.error_list, 'x', markersize=12, color='red')
# plt.plot(self.indep, self.std_list)
plt.ylabel('Average Error (cm)')
# self.error_list[:] = self.error_list[:,0]
diction = {'x':self.indep, 'y':self.error_list}
sio.savemat('Experimental.mat', diction)
plt.xlabel(indep_name)
plt.title('Average Error vs ' + indep_name)
plt.show()
def plot_errors(self):
plt.figure(2)
fig, axes = plt.subplots(self.ses_length+1, 1)
for (obj, i) in zip(self.analysis_list, range(self.ses_length)):
axes[i].plot(obj.t, obj.error)
plt.title('Error in experiments')
for obj in self.analysis_list:
axes[self.ses_length].plot(obj.t, obj.error)
plt.show()
class AnalysisData:
def __init__(self):
self.d = []
self.t = []
self.targetX = []
self.targetY = []
self.error = []
self.path = ""
def set_path(self, session, stream):
session_dp = "StaticServerSession%d/" % session
stream_dp = session_dp + "StreamData%d/" % stream
self.path = stream_dp + "Analysis%d/" % stream
self.load_analysis_data()
def load_analysis_data(self):
path = self.path
self.d = np.load(path + 'data_d.npy', allow_pickle=True)
self.t = np.load(path + 'data_t.npy', allow_pickle=True)
self.targetX = np.load(path + 'target_t.npy', allow_pickle=True)
try:
self.targetY = np.load(path + 'target d.npy', allow_pickle=True)
except:
self.targetY = np.load(path + 'target_d.npy', allow_pickle=True)
self.error = np.load(path + 'error_e.npy', allow_pickle=True)
def run_error_analysis(self):
start_point = 10
error = self.error[start_point:]
# print(error)
avg_error = np.average(error)
std_dev = np.std(error)
print("Average error: %f" % avg_error)
print("Standard Deviation: %f" % std_dev)
return avg_error, std_dev
def plot_histogram(self):
# avg_error, std_dev = self.run_error_analysis()
# possibly remove zeros first
error = np.copy(self.error)
error = [e for e in error if (e != 0 and e < 10)]
# print(error)
avg_error = np.average(error)
std_dev = np.std(error)
median = np.median(error)
n, bins, patches = plt.hist(x=error, bins=30, color='#0504aa', alpha=0.7, rwidth=0.85, label='Frequency of Error')
plt.axvline(x=avg_error, color='red', label='Average Error')
plt.axvline(x=(avg_error+std_dev), linestyle='--', color='green', label='1 Standard Deviation')
plt.axvline(x=(avg_error - std_dev), linestyle='--', color='green')
plt.axvline(x=median, linestyle=':', color='blue', label='Median')
plt.grid(axis='y', alpha=0.75)
plt.xlabel('Error (cm)')
plt.ylabel('Frequency')
plt.title('Distribution of Error')
plt.legend()
maxfreq = n.max()
# Set a clean upper y-axis limit.
plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)
plt.show()
| [
"benjaminevans316@gmail.com"
] | benjaminevans316@gmail.com |
a9a761d195dc8f846420561f8a25a3db6b48ed86 | 2339f3e554c2bff0143ed44d5172a071687a3a3d | /docset/predicate.py | 9cbbd5ee952ace63ff8e3f38790d696337a9d5d5 | [
"MIT"
] | permissive | vhbit/rust-docset | 9a04248b348bcb9a3135e233d3e7545ae688b0e5 | 58b416e949a9c02e2118bcc0ce0260b864f61b58 | refs/heads/master | 2021-01-15T15:25:55.059535 | 2016-08-22T11:51:18 | 2016-08-22T11:51:18 | 20,811,120 | 12 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,010 | py | import logging as log
import re
import os
def predicate_fn(pair):
key, value = pair
if key == "matches":
r = re.compile(value)
return lambda x: (r.search(x) != None)
elif key == "startswith":
return lambda x: x.startswith(value)
elif key == "dirname":
return lambda x: (os.path.dirname(x) == value)
log.warn("Unknown predicate: %s", key)
return None
def construct_predicate(**kwargs):
fn_list = filter(lambda x: x != None, map(predicate_fn, kwargs.items()))
if len(fn_list) == 0:
print "Invalid predicate"
log.warn("Check rules, one of predicates has no arguments, will always fail")
def closure(data):
for fn in fn_list:
if not fn(data):
break
else:
return True
return False
return closure
def rel_path(**kwargs):
f = construct_predicate(**kwargs)
def closure(ctx):
data = ctx['rel_path']
return f(data)
return closure
| [
"valerii.hiora@gmail.com"
] | valerii.hiora@gmail.com |
063b792d94acf75bce2c6fe1ed6610d4ffbaf195 | a3628ec03d75b01f8a44ff3d9d14883b200c7925 | /190104_crawling_auction_save_into_DB.py | 5999f6b92c5e48af7caccaacf018e721ab6ef8dd | [] | no_license | SeokHyeon-Hwang/with_python | a36315c479976a049c3ac2ee60cee45ea828663e | 9f47a4cdc57a9bd0c4b145171f8881264614119d | refs/heads/master | 2020-03-26T04:04:22.002415 | 2019-06-19T11:16:40 | 2019-06-19T11:16:40 | 144,484,444 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,037 | py | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 6 12:18:56 2018
@author: ktm
"""
#%%
# library 불러오기
from bs4 import BeautifulSoup
import requests as rq
import lxml
#%%
url = "http://browse.auction.co.kr/search?keyword={}&itemno=&nickname=&frm=hometab&dom=auction&isSuggestion=No&retry=&Fwk={}&acode=SRP_SU_0100&arraycategory=&encKeyword={}".format('여성의류', '여성의류', '여성의류')
res=rq.get(url)
html = res.content
soup=BeautifulSoup(html, 'lxml')
#%%
soup_item = soup.find_all('div', class_='section--itemcard')
num = len(soup_item)
num
title=[]
Dprice = []
for i in range(0,num):
# 상품명
soup_title = soup_item[i].find('span', class_='text--title')
print(soup_title)
if soup_title is not None:
title_text = soup_title.text
title.append(title_text)
else:
title.append('')
# 할인가
soup_Dprice = soup_item[i].find('strong', class_='text--price_seller')
if soup_Dprice is not None:
Dprice_text = soup_Dprice.text
Dprice.append(Dprice_text)
else:
Dprice.append('')
#%%
# mysql 실행
import mysql.connector
mydb = mysql.connector.connect(
host = 'localhost',
user = 'root',
passwd = 'qwer1234',
database = 'mydatabase')
mycursor = mydb.cursor()
#%%
# create TABLE
sql = 'CREATE TABLE auction (id INT AUTO_INCREMENT PRIMARY KEY , title VARCHAR(255), Dprice VARCHAR(255))'
mycursor.execute(sql)
#%%
# 만들어진 Table 확인
sql = 'SHOW TABLES'
mycursor.execute(sql)
for x in mycursor:
print(x)
#%%
# auction2 테이블에 데이터 저장하기
num = len(soup_item)
for i in range(0,num):
sql = 'INSERT INTO auction (title, Dprice) VALUE (%s, %s)'
val = (title[i], Dprice[i])
mycursor.execute(sql, val)
mydb.commit()
#%%
## 저장한 데이터 확인
sql = 'SELECT * FROM auction'
mycursor.execute(sql)
for x in mycursor:
print(x)
| [
"noreply@github.com"
] | SeokHyeon-Hwang.noreply@github.com |
a315342b69afb0c56f94ac2d281879dc9989b81e | e350435f946b069a6d73236f3d35622bfe78a489 | /mlp.py | efc81d747db18e44035f046e6d7532ef91594c67 | [] | no_license | jonathanalmd/mlpplanner | d9d7866c8d3e322477089b21467da09c072e6755 | d758e22e873bb5bccbcc456fadc5a8e0d7bf8f90 | refs/heads/master | 2021-03-19T18:53:32.451505 | 2018-03-02T01:25:58 | 2018-03-02T01:25:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,862 | py | import sys
import plex
import multipparser
import mlpplanner
import re
import time
def parse(pinput):
planning = multipparser.mlpParser()
if len(pinput) > 1:
run_parser = True
in_type = pinput[0].split(".")
if in_type[-1] not in ["pddl","PDDL"]:
print("Invalid input for PDDL DOMAIN formalization")
print("Correct use: python mlpparser.py input.{strips,adl} or python mlpparser.py domain.pddl problem.pddl")
run_parser = False
in_type = pinput[1].split(".")
if in_type[-1] not in ["pddl","PDDL"]:
print("Invalid input for PDDL PROBLEM formalization")
print("Correct use: python mlpparser.py input.{strips,adl} or python mlpparser.py domain.pddl problem.pddl")
run_parser = False
if run_parser:
pmode = "pddl"
domain, problem = multipparser.parse(pmode,[pinput[0], pinput[1]])
# print(domain)
# print(problem)
planning.setPDDL(domain, problem)
else:
sys.exit()
else: # strips ou adl
in_type = inputlist[0].split(".")
pmode = in_type[-1]
if pmode not in ["adl","strips","ADL","STRIPS"]:
print(">Invalid input file:",inputlist[0])
print("Correct use: python mlpparser.py input.{strips,adl} or python mlpparser.py domain.pddl problem.pddl")
sys.exit()
else:
strips_adl = multipparser.parse(pmode, [inputlist[0]])
if strips_adl:
# print(strips_adl)
in_type = inputlist[0].split(".")
if in_type[-1] in ["strips","STRIPS"]:
planning.setSTRIPS(strips_adl)
else: # adl
planning.setADL(strips_adl)
return planning
def runMlp(inputlist):
planning = multipparser.mlpParser()
if len(inputlist) > 1:
run_parser = True
in_type = inputlist[0].split(".")
if in_type[-1] not in ["pddl","PDDL"]:
print("Invalid input for PDDL DOMAIN formalization")
print("Correct use: python mlpparser.py input.{strips,adl} or python mlpparser.py domain.pddl problem.pddl")
run_parser = False
in_type = inputlist[1].split(".")
if in_type[-1] not in ["pddl","PDDL"]:
print("Invalid input for PDDL PROBLEM formalization")
print("Correct use: python mlpparser.py input.{strips,adl} or python mlpparser.py domain.pddl problem.pddl")
run_parser = False
if run_parser:
pmode = "pddl"
domain, problem = multipparser.parse(pmode,[inputlist[0], inputlist[1]])
# print(domain)
# print(problem)
planning.setPDDL(domain, problem)
rmode = "pddl"
else:
sys.exit()
elif len(inputlist) == 1:
in_type = inputlist[0].split(".")
pmode = in_type[-1]
if pmode not in ["adl","strips","ADL","STRIPS"]:
print(">Invalid input file:",inputlist[0])
print("Correct use: python mlpparser.py input.{strips,adl} or python mlpparser.py domain.pddl problem.pddl")
sys.exit()
else:
strips_adl = multipparser.parse(pmode, [inputlist[0]])
if strips_adl:
# print(strips_adl)
in_type = inputlist[0].split(".")
if in_type[-1] in ["strips","STRIPS"]:
planning.setSTRIPS(strips_adl)
rmode = "strips"
else: # adl
planning.setADL(strips_adl)
rmode = "adl"
return planning,rmode
# @profile
def mlPlanner(inputlist):
planner_time = 0
parse_time = 0
start_time = time.time()
parsed_data, rmode = runMlp(inputlist)
print(parsed_data)
planner = mlpplanner.BFSPlanner(rmode)
parse_time = (time.time() - start_time)
# run planner
start_time = time.time()
plan = planner.solve(parsed_data)
planner_time = (time.time() - start_time)
if plan:
print("Plan:")
for act in plan:
print(act)
print("Plan length: %d"%(len(plan)))
else:
print("No plan was found")
# print(planning.getPDDLDomainPredicates())
print("Parse: %s seconds" % (parse_time))
print("Planner: %s seconds" % (planner_time))
print("Total: %s seconds" % (planner_time + parse_time))
def mlParse(inputlist):
parse_time = 0
planner_time = 0
input_parser = inputlist
# print (input_parser)
start_time = time.time()
parsed_data = parse(input_parser)
parse_time = (time.time() - start_time)
# print(parsed_data)
# print("Parse: %s seconds" % (parse_time))
return parsed_data, parse_time
| [
"jalmeida@polaris.local"
] | jalmeida@polaris.local |
953f12c8e1f2fbede5df6eff0a9e8c77a8f891b3 | b11d5c511cfdcd4e7aaed53cc290e454876ae42f | /deploy/appDeploy.py | 7d2e354a6a61df93221ca550144eea78bd3b287f | [] | no_license | theITHollow/hollowapp | c2fde90ef2c0c95c4f25eacee9574c220d3de464 | b943c8e8dc2d0d0e7bf2fbf06729a59bc8265fe4 | refs/heads/master | 2022-12-17T05:32:07.740055 | 2018-03-01T21:43:29 | 2018-03-01T21:43:29 | 117,169,136 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,761 | py | #!/usr/bin/python
import boto3
import time
import json
import sys, os, subprocess
profile = 'sandbox'
session = boto3.Session(profile_name=profile)
client = session.client('cloudformation')
ec2client = session.client('ec2')
rdsclient = session.client('rds')
#Read the Variables File Output by the InfraDeploy Stage
json_data=open('variables.json').read()
data = json.loads(json_data)
#print(data)
#Print the results of the variables file
#print(data['EC2'])
#print(data['RDS'])
#Wanted to use this for the StackNames but this doesn't allow an expression
EC2stack = data['EC2']
RDSstack = data['RDS']
RDSresponse = client.describe_stack_resources(
StackName="HollowApp-RDS",
LogicalResourceId="MyDB"
)
#Get the PhysicalResourceId of the RDS datbase from the Cloudformation StackId
RDSID = RDSresponse['StackResources'][0]['PhysicalResourceId']
database = rdsclient.describe_db_instances(
DBInstanceIdentifier=RDSID
)
#Get the RDS Instance Endpoint from the CloudFormation StackName
RDSendpoint = database['DBInstances'][0]['Endpoint']['Address']
response1 = client.describe_stack_resources(
StackName='HollowApp-EC2-LB',
LogicalResourceId = "HollowApp1EC2"
)
#print(response1)
response2 = client.describe_stack_resources(
StackName=EC2stack,
LogicalResourceId = "HollowApp2EC2"
)
#print(response2)
#Get the PhysicalResourceId from the CloudFormation Stack
EC2ID1 = response1['StackResources'][0]['PhysicalResourceId']
EC2ID2 = response2['StackResources'][0]['PhysicalResourceId']
ec2instance1 = ec2client.describe_instances(
InstanceIds = [EC2ID1]
)
ec2instance2 = ec2client.describe_instances(
InstanceIds = [EC2ID2]
)
EC2IP1 = ec2instance1['Reservations'][0]['Instances'][0]['PublicIpAddress']
EC2IP2 = ec2instance2['Reservations'][0]['Instances'][0]['PublicIpAddress']
#execute a bash script to SSH to the EC2 hosts
os.chmod('deploy/connect.sh', 0o777)
if profile == 'sandbox':
pass_arg=[]
pass_arg.append("deploy/connect.sh")
pass_arg.append("SBX-ed2-keypair.pem")
pass_arg.append(EC2IP1)
pass_arg.append(EC2IP2)
pass_arg.append(RDSendpoint)
subprocess.call(pass_arg)
if profile == 'sharedservices':
subprocess.call(["deploy/connect.sh", "shs-ec2-keypair.pem", str(EC2IP1), str(RDSendpoint)])
subprocess.call(["deploy/connect.sh", "shs-ec2-keypair.pem EC2IP2 RDSendpoint"])
if profile == 'nonprod':
subprocess.call(["deploy/connect.sh", "npd-ec2-keypair.pem EC2IP1 RDSendpoint"])
subprocess.call(["deploy/connect.sh", "npd-ec2-keypair.pem EC2IP2 RDSendpoint"])
if profile == 'production':
subprocess.call(["deploy/connect.sh", "ppd-ec2-keypair.pem EC2IP1 RDSendpoint"])
subprocess.call(["deploy/connect.sh", "ppd-ec2-keypair.pem EC2IP2 RDSendpoint"])
| [
"noreply@github.com"
] | theITHollow.noreply@github.com |
a580d64f8cdaba61f0e8bd0451ba0ed2c3264e8c | 96db8aa8991b239578cd949069a35c80771054b6 | /Generation/LHE-signal/patchMEInt.py | b13cb0c0ac4b6bcf897536ad8116cdf9c4ea159b | [] | no_license | andrey-popov/pheno-htt | 37435675a82cea6da9b405339a52ec7444dd30f7 | e6ef12cec5606cbf3e5c8a1224d4170d2ccdbf3b | refs/heads/master | 2021-05-12T00:33:27.694980 | 2019-04-25T12:53:01 | 2019-04-25T12:53:01 | 117,536,495 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,992 | py | #!/usr/bin/env python
"""Patches computation of squared ME to keep interference terms only.
This script patches Fortran code generated for each subprocess. When
summing over helicities, it computes the squared matrix element as is,
then inverts the sign of the given coupling, recomputes the squared
matrix element, and finally returns the half-difference of the two. This
way only terms with odd degrees in the coupling are kept.
Definitions of couplings can be found in file couplings.py in the
directory with the model.
This trick was proposed by Sebastien Wertz.
"""
from __future__ import print_function
import argparse
import os
import re
import shutil
import tempfile
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(epilog=__doc__)
arg_parser.add_argument('dir', help='Directory generated by MadGraph for a given process')
arg_parser.add_argument(
'coupling', type=int,
help='Index of the coupling whose sign will be inversed'
)
args = arg_parser.parse_args()
coupling_name = 'GC_{}'.format(args.coupling)
sub_proc_dir = os.path.join(args.dir, 'SubProcesses')
if not os.path.exists(sub_proc_dir):
raise RuntimeError(
'Directory "{}" does not contain required subdirectory "SubProcesses".'.format(
args.dir
)
)
regex_include = re.compile(r'(\s*)INCLUDE\s+\'maxamps\.inc\'\s*')
regex_me = re.compile(r'(\s*)T=(MATRIX1\(.+\))\s*')
# Loop over all subprocesses
for entry in os.listdir(sub_proc_dir):
if not os.path.isdir(os.path.join(sub_proc_dir, entry)):
continue
src_file_name = os.path.join(sub_proc_dir, entry, 'matrix1.f')
print('Patching file "{}".'.format(src_file_name))
src_file = open(src_file_name)
out_file = tempfile.NamedTemporaryFile(mode='w', delete=False)
out_file_name = out_file.name
# Copy content of the source file with up to the end of the
# include block. Add inclusion of file with couplings.
while True:
line = src_file.readline()
if not line:
raise RuntimeError(
'Failed to locate the end of the include block in file "{}".'.format(
src_file_name
)
)
out_file.write(line)
match = regex_include.match(line)
if match:
out_file.write(match.group(1) + 'INCLUDE \'coupl.inc\'\n')
break
# Copy the remaining content of the source file. When the
# computation of the squared ME is encountered, apply the trick
# with flipping of the sign of selected coupling.
num_me_patches = 0
while True:
line = src_file.readline()
if not line:
break
out_file.write(line)
match = regex_me.match(line)
if match:
spacing = match.group(1)
me_call = match.group(2)
out_file.write('{s}{c}=-{c}\n'.format(s=spacing, c=coupling_name))
out_file.write('{}T=5D-1*(T-{})\n'.format(spacing, me_call))
out_file.write('{s}{c}=-{c}\n'.format(s=spacing, c=coupling_name))
num_me_patches += 1
if num_me_patches != 2:
raise RuntimeError(
'In file "{}" found {} places in which the squared matrix element is evaluated '
'while 2 places expected.'.format(src_file_name, num_me_patches)
)
src_file.close()
out_file.close()
shutil.move(src_file_name, src_file_name + '.orig')
shutil.move(out_file_name, src_file_name)
| [
"rainfinder@gmail.com"
] | rainfinder@gmail.com |
b131350cfdf498bbe64bf2d776c1ebcf201c2e8e | dae71a7159f119fa86ac79ce16558d263ec4f756 | /src/mydetic/s3_datastore.py | 1d72246c13e3a636e01dd75ca737e44b66674036 | [
"Apache-2.0"
] | permissive | nMustaki/mydetic | f3c37b3d6a6c4fb04df460e0127e37ec87c5f28f | b1ba73c7af14a4e1b84ea81796c13f11c62a6c14 | refs/heads/master | 2021-01-16T20:39:32.900466 | 2015-02-21T05:25:04 | 2015-02-21T05:25:04 | 31,198,743 | 0 | 0 | null | 2015-02-23T08:02:17 | 2015-02-23T08:02:17 | null | UTF-8 | Python | false | false | 7,069 | py | """
DataStore implementation that stores data in an S3 Bucket.
"""
import datetime
import boto
from boto.s3.key import Key
from boto.s3.connection import Location
from datastore import DataStore
from mydeticexceptions import MyDeticMemoryAlreadyExists, MyDeticNoMemoryFound
from memorydata import MemoryData
import re
class S3DataStore(DataStore):
"""
S3 implementation of DataStore.
This class doesn't catch boto.exception - you should handle it upstream.
"""
def __init__(self, s3_config=None):
"""
Constructor
:param s3_config: Dictionary containing S3 connection details.
"""
DataStore.__init__(self)
if s3_config is not None:
self.validate_s3_params(s3_config)
self._s3_config = s3_config
if len(self._s3_config['region']) > 0:
self._connection = boto.s3.connect_to_region(self._s3_config['region'],
aws_access_key_id=self._s3_config['aws_access_key_id'],
aws_secret_access_key=self._s3_config['aws_secret_access_key'])
else:
self._connection = boto.connect_s3()
self._bucket = None
def create_bucket_if_required(self):
if self._bucket is None:
self._bucket = self._connection.lookup(self._s3_config['bucket'])
if self._bucket is None:
self._bucket = self._connection.create_bucket(self._s3_config['bucket'],
location=self._s3_config['region'])
return self._bucket
@staticmethod
def validate_s3_params(s3_config):
"""
Check that everything is tickety-boo with the s3 params. Just
check that they're all there, not that they're right.
:param s3_config: Dictionary containing S3 connection details.
:raises: ValueError
"""
missing_params = []
for required_param in ['region', 'aws_access_key_id', 'aws_secret_access_key', 'bucket', 'region']:
if required_param not in s3_config:
missing_params.append(required_param)
if len(missing_params) > 0:
raise ValueError("s3 config is missing [%s]" % ','.join(missing_params))
@staticmethod
def generate_memory_key_name(user_id, memory_date):
"""
:param user_id: user id string
:param memory_date: a datetime.date
:return: a key name for the memory ("user_id/YYYYMMDD.json")
"""
user_id_str = user_id
if type(user_id) is unicode:
user_id_str = user_id.encode('utf-8')
return "%s/%s.json" % (user_id_str, memory_date.strftime("%Y%m%d"))
@staticmethod
def date_from_keyname(key_name):
"""
Parse out the date from the memory key name
:param key_name: string of key name
:return: datetime.date
:raise: ValueError if key name is wrong format
"""
m = re.match('^.+/(\d+)\.json', key_name)
if m:
return datetime.datetime.strptime(m.group(1), "%Y%m%d").date()
else:
raise ValueError("Invalid format for key name [%s]" % key_name)
def get_memory(self, user_id, memory_date):
"""
:param user_id: str the User ID
:type user_id: str or unicode
:param memory_date:
:type memory_date: datetime.date
:return: The memory
:raises MyDeticNoMemoryFound if there isn't a memory on this day
"""
self.create_bucket_if_required()
k = self._bucket.get_key(self.generate_memory_key_name(user_id, memory_date))
if k is None:
raise MyDeticNoMemoryFound(user_id, memory_date)
return MemoryData.from_json_str(k.get_contents_as_string())
def has_memory(self, user_id, memory_date):
"""
Return whether a memory exists for a user at a date.
:param user_id:
:type user_id: str or unicode
:param memory_date:
:type memory_date: datetime.date
:return: True if a memory exists, false otherwise.
"""
self.create_bucket_if_required()
k = self._bucket.get_key(self.generate_memory_key_name(user_id, memory_date))
return k is not None
def update_memory(self, memory):
"""
:param memory: updated MemoryData object. NOTE: only text is changed.
:return: No return value
:raises: MyDeticMemoryNotFoundError is memory doesn't already exist
"""
self.create_bucket_if_required()
k = self._bucket.get_key(self.generate_memory_key_name(memory.user_id, memory.memory_date))
if k is None:
raise MyDeticNoMemoryFound(memory.user_id, memory.memory_date)
old_memory = self.get_memory(memory.user_id, memory.memory_date)
old_memory.memory_text = memory.memory_text
old_memory.touch()
k.set_contents_from_string(old_memory.as_json_str())
def add_memory(self, memory):
"""
:param memory:
:raises MyDeticMemoryAlreadyExists
:return:
"""
self.create_bucket_if_required()
if self.has_memory(memory.user_id, memory.memory_date):
raise MyDeticMemoryAlreadyExists(memory.user_id, memory.memory_date)
bucket = self._bucket
k = Key(bucket)
k.key = self.generate_memory_key_name(memory.user_id, memory.memory_date)
k.set_contents_from_string(memory.as_json_str(), headers={'Content-Type': 'application/json'})
def list_memories(self, user_id, start_date=None, end_date=None):
"""
get memories for a user_id, optionally restricted by date range
:param user_id:
:param start_date:
:param end_date:
:return: an ordered list of dates that contain memories
"""
self.create_bucket_if_required()
retval = []
keys = self._bucket.list(user_id)
for k in keys:
try:
mem_date = self.date_from_keyname(k.name)
except ValueError:
# skip keys with invalid names
continue
# TODO: replace these range checks with something more efficient. At one memory
# TODO: per day we're not going to have more than a couple thousand entries for a while.
if start_date is not None:
if mem_date < start_date:
continue
if end_date is not None:
if mem_date > end_date:
continue
retval.append(mem_date)
return sorted(retval)
def delete_memory(self, user_id, memory_date):
"""
:param user_id:
:param memory_date:
:return: the deleted memory
:raises: MyDeticNoMemoryFound
"""
mem_to_delete = self.get_memory(user_id, memory_date)
self._bucket.delete_key(self.generate_memory_key_name(user_id, memory_date))
return mem_to_delete | [
"andrew.k.reid@gmail.com"
] | andrew.k.reid@gmail.com |
879d3e52d3b63ee8f078a3a5f876d4b96ca5aba3 | 3dc60bbcb27600ffe7baa4e6187fe2c71bb7b5ab | /Python/to-lower-case.py | ca69091671f3380ba24c1920aca7d39718fe6f48 | [
"MIT"
] | permissive | phucle2411/LeetCode | 33f3cc69fada711545af4c7366eda5d250625120 | ba84c192fb9995dd48ddc6d81c3153488dd3c698 | refs/heads/master | 2022-01-14T16:49:50.116398 | 2019-06-12T23:41:29 | 2019-06-12T23:41:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 203 | py | # https://leetcode.com/problems/to-lower-case/submissions/
class Solution:
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
return str.lower()
| [
"JaredLGillespie@hotmail.com"
] | JaredLGillespie@hotmail.com |
bacdf81a75c15e912b8ee6eff3ab32540cb35e47 | 792520d7a730010cb04975007495acf4ff4995a1 | /wesnoth/wmldata.py | a3b10eedd9aa3d29ec219634ae250e60520c659b | [] | no_license | Yossarian/WesnothAddonServer | cc48bad65117686f372fbd3c0a4b4b74f7f3c0f5 | 408ca395b839ab629b21c90ad4909ef73b0e7980 | refs/heads/master | 2021-01-10T21:16:49.363090 | 2010-05-17T22:24:06 | 2010-05-17T22:24:06 | 542,581 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 20,115 | py | #!/usr/bin/env python
# encoding: utf8
"""
This module represents the internal appearance of WML.
Note: We cannot store textdomain information, due to how the parser work.
For example:
name = _"x" + {foor} + {bar}
That string may actually be composed from three different textdomains. The
textdomain stuff in here is therefore only useful to CampGen, as that does
not allow composed strings like above.
"""
import re, sys
import wmlparser
import codecs
class Data:
"""Common subclass."""
def __init__(self, name):
self.name = name
self.file = "(None)"
self.line = -1
def __str__( self ):
return self.debug(show_contents = True, write = False)
def debug(self, show_contents = False, use_color = False, indent=0, write=True):
if use_color:
magenta = "\x1b[35;1m"
off = "\x1b[0m"
else:
magenta = off = ""
pos = indent * " "
result = pos + "\ " + magenta + self.name + off + " (" + self.__class__.__name__ + ")"
if show_contents:
result += "'" + self.get_value() + "'"
if write:
# The input usually is utf8, but it also may be not - for example
# if a .png image is transmitted over WML. As this is only for
# display purposes, we ask Python to replace any garbage - and then
# re-encode as utf8 for console output.
text = result.decode("utf8", "replace")
text = text.encode("utf8", "replace")
sys.stdout.write(text)
sys.stdout.write("\n")
else: return result
def copy(self):
c = self.__class__(self.name, self.data) # this makes a new instance or so I was told
return c
def compare(self, other):
return self.name == other.name and self.data == other.data
def get_value(self):
return ""
def get_type(self):
return self.__class__.__name__
def set_meta(self, file, line):
self.file = file
self.line = line
def get_meta(self):
return (self.file, self.line,)
class DataText(Data):
"""Represents any text strings."""
def __init__(self, name, text, translatable = False):
Data.__init__(self, name)
self.data = text
self.translatable = translatable
def copy(self):
return DataText(self.name, self.data, self.translatable)
def get_value(self):
return self.data
def set_value(self, data):
self.data = data
class DataBinary(Data):
"""A binary chunk of WML."""
def __init__(self, name, binary):
Data.__init__(self, name)
self.data = binary
def get_value(self):
return self.data
def set_value(self, data):
self.data = data
class DataMacro(Data):
"""A macro."""
def __init__(self, name, macro):
Data.__init__(self, name)
self.data = macro
def get_value(self):
return self.data
def set_value(self, data):
self.data = data
class DataDefine(Data):
"""A definition."""
def __init__(self, name, params, define):
Data.__init__(self, name)
self.params = params
self.data = define
def copy(self):
return DataDefine(self.name, self.params, self.data)
def get_value(self):
return self.data
def set_value(self, data):
self.data = data
class DataComment(Data):
"""A comment (normally discarded)."""
def __init__(self, name, comment):
Data.__init__(self, name)
self.data = comment
def get_value(self):
return self.data
def set_value(self, data):
self.data = data
class DataClosingTag(Data):
"""Yes, those are kept."""
def __init__(self, name):
Data.__init__(self, name)
self.data = None
class WMLException(Exception):
def __init__(self, text):
super( WMLException, self ).__init__()
self.text = text
print text
def __str__(self):
return self.text
class DataSub(Data):
def __init__(self, name, sub = [], textdomain=None):
"""The sub parameter is a list of sub-elements."""
Data.__init__(self, name)
self.data = []
self.dict = {}
self.textdomain = textdomain
for element in sub:
self.insert(element)
def clean_empty_ifdefs(self):
rem = []
for item in self.data:
if isinstance(item, DataIfDef):
if item.data == []:
rem.append(item)
if isinstance(item, DataSub):
item.clean_empty_ifdefs()
while rem:
item = rem.pop()
print "Removing empty #ifdef %s" % item.name
self.remove(item)
def write_file(self, f, indent=0, textdomain=""):
f.write(self.make_string( indent, textdomain))
def make_string(self, indent = 0, textdomain = ""):
"""Write the data object to the given file object."""
ifdef = 0
result = []
self.clean_empty_ifdefs()
for item in self.data:
if ifdef:
if not isinstance(item, DataIfDef) or not item.type == "else":
result.append("#endif\n")
ifdef = 0
if isinstance(item, DataIfDef):
if item.type == "else":
result.append("#else\n")
else:
result.append("#ifdef %s\n" % item.name)
result.append( item.make_string(indent + 4, textdomain) )
ifdef = 1
elif isinstance(item, DataSub):
result.append(" " * indent)
result.append("[%s]\n" % item.name)
result.append(item.make_string(indent + 4, textdomain))
result.append(" " * indent)
close = item.name
if close[0] == "+": close = close[1:]
result.append("[/%s]\n" % close)
elif isinstance(item, DataText):
result.append(" " * indent)
text = item.data.replace('"', r'""')
# We always enclosed in quotes
# In theory, the parser will just remove then on reading in, so
# the actual value is 1:1 preserved
# TODO: is there no catch?
if textdomain and item.textdomain == "wesnoth":
result.append("#textdomain wesnoth\n")
result.append(" " * indent)
# FIXME: don't compile regex's if they are one shots
if item.translatable:
if "=" in text:
text = re.compile("=(.*?)(?=[=;]|$)"
).sub("=\" + _\"\\1\" + \"", text)
text = '"' + text + '"'
text = re.compile(r'\+ _""').sub("", text)
result.append('%s=%s\n' % (item.name, text))
else:
result.append('%s=_"%s"\n' % (item.name, text))
else:
result.append('%s="%s"\n' % (item.name, text))
if textdomain and item.textdomain == "wesnoth":
result.append(" " * indent)
result.append("#textdomain %s\n" % textdomain)
elif isinstance(item, DataMacro):
result.append(" " * indent)
result.append("%s\n" % item.data)
elif isinstance(item, DataComment):
result.append("%s\n" % item.data)
elif isinstance(item, DataDefine):
result.append("#define %s %s\n%s#enddef\n" % (item.name, item.params,
item.data))
elif isinstance(item, DataClosingTag):
result.append("[/%s]\n" % item.name)
elif isinstance(item, DataBinary):
data = item.data.replace('"', r'""')
result.append("%s=\"%s\"\n" % (
item.name, data))
else:
raise WMLException("Unknown item: %s" % item.__class__.__name__)
if ifdef:
result.append("#endif\n")
bytes = ""
for r in result:
if r != None:
# For networking, we need actual bytesteam here, not unicode.
bytes += str(r)
return bytes
def is_empty(self):
return len(self.data) == 0
def children(self):
return self.data
def place_dict(self, data):
if data.name in self.dict:
self.dict[data.name] += [data]
else:
self.dict[data.name] = [data]
def append(self, other):
"""Append all elements of other."""
for item in other.data:
self.insert(item)
def insert(self, data):
"""Inserts a sub-element."""
self.data += [data]
self.place_dict(data)
def insert_first(self, data):
self.data = [data] + self.data
if data.name in self.dict:
self.dict[data.name] = [data] + self.dict[data.name]
else:
self.dict[data.name] = [data]
def insert_after(self, previous, data):
"""Insert after given node, or else insert as first."""
if not previous in self.data: return self.insert_first(data)
# completely rebuild list and dict
new_childs = []
self.dict = {}
for child in self.data:
new_childs += [child]
self.place_dict(child)
if child == previous:
new_childs += [data]
self.place_dict(data)
self.data = new_childs
def insert_at(self, pos, data):
"""Insert at given index (or as last)."""
if pos >= len(self.data): return self.insert(data)
# completely rebuild list and dict
new_childs = []
self.dict = {}
i = 0
for child in self.data:
if i == pos:
new_childs += [data]
self.place_dict(data)
new_childs += [child]
self.place_dict(child)
i += 1
self.data = new_childs
def insert_as_nth(self, pos, data):
"""Insert as nth child of same name."""
if pos == 0: return self.insert_first(data)
already = self.get_all(data.name)
before = already[pos - 1]
self.insert_after(before, data)
def remove(self, child):
"""Removes a sub-element."""
self.data.remove(child)
self.dict[child.name].remove(child)
def clear(self):
"""Remove everything."""
self.data = []
self.dict = {}
def copy(self):
"""Return a recursive copy of the element."""
copy = DataSub(self.name)
for item in self.data:
subcopy = item.copy()
copy.insert(subcopy)
return copy
def compare(self, other):
if len(self.data) != len(other.data): return False
for i in range(self.data):
if not self.data[i].compare(other.data[i]): return False
return True
def rename_child(self, child, name):
self.dict[child.name].remove(child)
child.name = name
# rebuild complete mapping for this name
if name in self.dict: del self.dict[name]
for item in self.data:
if item.name == name:
if name in self.dict:
self.dict[name] += [item]
else:
self.dict[name] = [item]
def insert_text(self, name, data, translatable = False,
textdomain = ""):
data = DataText(name, data, translatable = translatable)
data.textdomain = textdomain
self.insert(data)
def insert_macro(self, name, args = None):
macrodata = "{" + name
if args: macrodata += " " + str(args)
macrodata += "}"
data = DataMacro(name, macrodata)
self.insert(data)
def get_first(self, name, default = None):
"""Return first of given tag, or default"""
if not name in self.dict or not self.dict[name]: return default
return self.dict[name][0]
def get_all_with_attributes(self, attr_name, **kw):
"""Like get_or_create_sub_with_attributes."""
ret = []
for data in self.get_all(attr_name):
if isinstance(data, DataSub):
for key in kw:
if data.get_text_val(key) != kw[key]:
break
else:
ret += [data]
return ret
def get_or_create_sub(self, name):
for data in self.get_all(name):
if isinstance(data, DataSub): return data
sub = DataSub(name, [])
self.insert(sub)
return sub
def create_sub(self, name):
sub = DataSub(name, [])
self.insert(sub)
return sub
def get_or_create_sub_with_attributes(self, name, **kw):
"""For the uber lazy. Example:
event = scenario.get_or_create_sub_with_attribute("event", name = "prestart")
That should find the first prestart event and return it, or else
create and insert a new prestart event and return it.
"""
for data in self.get_all(name):
if isinstance(data, DataSub):
for key in kw:
if data.get_text_val(key) != kw[key]:
break
else:
return data
sub = DataSub(name, [])
for key in kw:
sub.set_text_val(key, kw[key])
self.insert(sub)
return sub
def get_or_create_ifdef(self, name):
for data in self.get_all(name):
if isinstance(data, DataIfDef): return data
ifdef = DataIfDef(name, [], "then")
self.insert(ifdef)
return ifdef
def delete_all(self, name):
while 1:
data = self.get_first(name)
if not data: break
self.remove(data)
def remove_all(self, name):
self.delete_all(name)
def find_all(self, *args):
"""Return list of multiple tags"""
return [item for item in self.data if item.name in args]
def get_all(self, name):
"""Return a list of all sub-items matching the given name."""
if not name in self.dict: return []
return self.dict[name]
def get_text(self, name):
"""Return a text element"""
for data in self.get_all(name):
if isinstance(data, DataText): return data
return None
def get_texts(self, name):
"""Gets all text elements matching the name"""
return [text for text in self.get_all(name)
if isinstance(text, DataText)]
def get_all_text(self):
"""Gets all text elements"""
return [text for text in self.data
if isinstance(text, DataText)]
def get_binary(self, name):
"""Return a binary element"""
for data in self.get_all(name):
if isinstance(data, DataBinary): return data
return None
def remove_text(self, name):
text = self.get_text(name)
if text: self.remove(text)
def get_macros(self, name):
"""Gets all macros matching the name"""
return [macro for macro in self.get_all(name)
if isinstance(macro, DataMacro)]
def get_all_macros(self):
"""Gets all macros"""
return [macro for macro in self.data
if isinstance(macro, DataMacro)]
def get_ifdefs(self, name):
"""Gets all ifdefs matching the name"""
return [ifdef for ifdef in self.get_all(name)
if isinstance(ifdef, DataIfDef)]
def get_subs(self, name):
"""Gets all elements matching the name"""
return [sub for sub in self.get_all(name)
if isinstance(sub, DataSub)]
def get_all_subs(self):
"""Gets all elements"""
return [sub for sub in self.data
if isinstance(sub, DataSub)]
def remove_macros(self, name):
for macro in self.get_macros(name):
self.remove(macro)
def get_binary_val(self, name, default = None):
"""For the lazy."""
binary = self.get_binary(name)
if binary: return binary.data
return default
def get_text_val(self, name, default = None):
"""For the lazy."""
text = self.get_text(name)
if text: return text.data
return default
def set_text_val(self, name, value, delete_if = None, translatable = False,
textdomain = ""):
"""For the lazy."""
text = self.get_text(name)
if text:
if value == delete_if:
self.remove(text)
else:
text.data = value
text.textdomain = textdomain
text.translatable = translatable
else:
if value != delete_if:
self.insert_text(name, value, translatable = translatable,
textdomain = textdomain)
def get_comment(self, start):
for item in self.get_all("comment"):
if isinstance(item, DataComment):
if item.data.startswith(start): return item
return None
def set_comment_first(self, comment):
"""For the lazy."""
for item in self.get_all("comment"):
if isinstance(item, DataComment):
if item.data == comment: return
self.insert_first(DataComment("comment", comment))
def get_quantity(self, tag, difficulty, default = None):
"""For the even lazier, looks for a value inside a difficulty ifdef.
"""
v = self.get_text_val(tag)
if v != None: return v
for ifdef in self.get_ifdefs(["EASY", "NORMAL", "HARD"][difficulty]):
v = ifdef.get_text_val(tag)
if v != None: return v
return default
def set_quantity(self, name, difficulty, value):
"""Sets one of 3 values of a quantity. If it doesn't exist yet, also the
other difficulties get the same value.
"""
value = str(value)
# read existing values
q = []
for d in range(3):
q += [self.get_quantity(name, d, value)]
q[difficulty] = value
# remove current tags
self.remove_text(name)
for ifdef in self.get_ifdefs("EASY") + self.get_ifdefs("NORMAL") + self.get_ifdefs("HARD"):
ifdef.remove_text(name)
# insert updated item
if q[0] == q[1] == q[2]:
self.set_text_val(name, value)
else:
for d in range(3):
ifdef = self.get_or_create_ifdef(["EASY", "NORMAL", "HARD"][d])
ifdef.set_text_val(name, q[d])
def debug(self, show_contents = False, use_color = False, indent=0, write=True):
if use_color:
red = "\x1b[31;1m"
off = "\x1b[0m"
else:
red = off = ""
pos = indent * " "
result = pos + "\ " + red + self.name + off + " (" + self.__class__.__name__ + ")\n"
if write:
sys.stdout.write( result )
indent += 1
for child in self.data:
cresult = child.debug(show_contents, use_color, indent, write=write)
if not write:
result += "\n" + cresult
indent -= 1
if not write:
return result
class DataIfDef(DataSub):
"""
An #ifdef section in WML.
"""
def __init__(self, name, sub, type):
DataSub.__init__(self, name, sub)
self.type = type
def copy(self):
copy = DataSub.copy(self)
copy.type = self.type
return copy
def read_file(filename, root_name = "WML"):
"""
Read in a file from disk and return a WML data object, with the WML in the
file placed under an entry with the name root_name.
"""
parser = wmlparser.Parser(None)
parser.parse_file(filename)
data = DataSub(root_name)
parser.parse_top(data)
return data
| [
"157482@student.pwr.wroc.pl"
] | 157482@student.pwr.wroc.pl |
0e7e09672ebeada1189387da00af53196a910a78 | 8154ce402e2316b27dd4936411fb7b580fc64072 | /Python/zelle/ch3/ch3.py | 38a48273d1a7d7d9879ff0046d68330cba427a12 | [] | no_license | dmsenter89/learningProgramming | 9a961522dd046ec7b3eaf9baea351844568afaca | b984c1d5ad54a0d2927eaea265ddce4af2eaeaaf | refs/heads/master | 2020-12-10T11:16:16.348651 | 2017-06-29T02:36:48 | 2017-06-29T02:36:48 | 21,745,701 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 923 | py | import math
# exercise 1
# calculate volume and surface of sphere from input
print('--------------------------------------------')
print('Exercise 1 - Calculate vol.and surf. of sphere from Input.')
radius = float(input("Enter radius: "))
V = 4.0/3.0*math.pi*radius**3
A = 4.0*math.pi*radius**2
print("Volume={0}, Surface={1}.".format(V,A))
print('End exercise 1.')
# exercise 2
print('--------------------------------------------')
print('Exercise 2 - Cost/sq inch of Pizza.')
diam = int(input("Diameter of Pizz (int): "))
cost = float(input('Cost: '))
A = math.pi*(diam/2.0)**2
cpi = cost/A
print('Cost: ${0}/sqr inch.'.format(round(cpi,2)))
print('End exercise 2.')
# exercise 3
print('--------------------------------------------')
print('Exercise 3 - Epact of Gregorian year.')
year = int(input('Enter 4 digit year: '))
C = year//100
epact = (8+(C//4)-C+((8*C+13)//25)+11*(year%19))%30
print('Epact =', epact, '.')
| [
"dmsenter89@gmail.com"
] | dmsenter89@gmail.com |
879c8c51f5208dd40ed3791d0ab2a887735fcf85 | 155497bf1cad4dd8ea3db387323df6cf938c6b19 | /02/string_bits.py | 62d61efb868baf4b48f029b92272b4541b358cde | [] | no_license | gp70/homework | 45a9fb22eb67958173a20fa30c73f1305c8bffc4 | 404b3444573998eac5042fbfe60cdd33b384420a | refs/heads/master | 2021-01-23T21:22:52.596980 | 2017-12-06T18:41:21 | 2017-12-06T18:41:21 | 102,896,521 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 125 | py | def string_bits(str):
n = 0
nstr = ''
while n in range(len(str)):
nstr = nstr + str[n]
n = n + 2
return nstr
| [
"gareth.petterson70@myhunter.cuny.edu"
] | gareth.petterson70@myhunter.cuny.edu |
8a88fd90ab4a7c81cf59aadf58ee93a232cb79b1 | c1cbf7c837b0d46ae82de24f3bc98f77b8ce243b | /ne583/Test/test02/Problem 3.py | b9d789bb505d992d43464cbf3150b3027d91293a | [] | no_license | piovere/nucnotes | 4d199aff580bebf1598be15b4854dc08cff7d7a5 | 1285087d9ca2505b59bbf3bc643969c2341dc553 | refs/heads/master | 2020-09-15T07:56:39.429161 | 2019-04-01T17:16:16 | 2019-04-01T17:16:16 | 65,939,252 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,884 | py |
# coding: utf-8
# # Problem 3
# In[1]:
from scipy.integrate import trapz
from scipy.special import legendre
from scipy.optimize.zeros import newton
from numpy.polynomial.legendre import leggauss
import numpy as np
import matplotlib.pyplot as plt
# Plot the 14th Legendre polynomial to eyeball
# the starting guesses for the zeros
# In[2]:
x = np.linspace(-1, 1, 10000)
# In[3]:
l = legendre(14)
# In[4]:
plt.plot(x, l(x))
plt.xlim(0, 1)
plt.axhline(y=0, alpha=0.3, color='black')
# This has seven positive and seven negative zeros
# In[5]:
guesses = [
0.1,
0.33,
0.52,
0.7,
0.8,
0.9,
1.0
]
# `newton` uses the Newton-Raphson method to find zeros of a function
# In[6]:
zeros = np.array([newton(l, g) for g in guesses])
print(zeros)
# Now I can construct the matrix of integrals for $x^n$
# Calculate the numerical integral of $x^n$ for even $n$'s
# In[7]:
integrals = np.array([0.5*trapz(x**n, x) for n in range(15)[::2]])
print(integrals)
# Create a matrix where each column $j$ and row $i$ is $\mu_j^{2i}$
# In[8]:
functions = np.array([zeros**n for n in range(15)[::2]])
# In[9]:
np.set_printoptions(precision=1)
print(functions)
# In[10]:
np.set_printoptions(precision=8)
# Get the official values to compare with
# In[11]:
mus, wts = leggauss(14)
# Compare the official $\mu$ values (stored in the variable `mus`) to my
# calculated values (stored in `zeros`)
# In[12]:
mus[7:]
# In[13]:
zeros
# Compare the official weights (stored in `wts`) to my calculated values
# (stored in `weights`)
# In[14]:
wts[7:]
# In[15]:
weights = np.linalg.inv(functions.T @ functions) @ functions.T @ integrals
weights
# Calculate the fractional error between my calculated weights and the
# official ones
# In[16]:
np.abs(weights - wts[7:]) / wts[7:]
# Pretty close! Within ~$10^{-4}$%
| [
"jpowersl@vols.utk.edu"
] | jpowersl@vols.utk.edu |
8b87ebf8bdf80001ed86b8d96849e17563c659cc | 7f047264b412f204afe64ecd68e4c621535f464d | /maoyan_top100/maoyantop100.py | a6392c6b519346994795e4763b10ecb148270772 | [] | no_license | lybtt/spider_learning | 7d67a64f55b2259bc7ea4eadc930065e5bcca41b | c14d42568de2606036600236ac24f821478831e0 | refs/heads/master | 2020-03-25T10:42:42.014422 | 2018-08-18T12:49:50 | 2018-08-18T12:49:50 | 143,671,859 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,883 | py | #coding:utf-8
#author:lyb
#Date: 2018/7/28 21:35
import pymongo
import requests
from requests.exceptions import RequestException
import re
import json
import time
from concurrent.futures import ThreadPoolExecutor, as_completed, ProcessPoolExecutor
from maoyan_top100.config import *
headers = {"User-Agent": USER_AGENT}
def get_proxy():
try:
response = requests.get(PROXY_POOL_URL)
if response.status_code == 200:
return response.text
return None
except ConnectionError:
return None
def get_one_page(url, headers):
try:
global PROXY
PROXY = get_proxy()
proxies = {
'http': 'http://' + PROXY
}
if PROXY:
res = requests.get(url, headers=headers, proxies=proxies)
if res.status_code == 200:
return res.text
return None
else:
return get_one_page(url, headers)
except RequestException:
return get_one_page(url, headers)
def parse_one_page(html):
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a.*?>(.*?)</a>.*?star">(.*?)</p>'
'.*?releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
items = re.findall(pattern, html)
for item in items:
yield {
'index': item[0],
'image': item[1],
'title': item[2],
'actor': item[3].strip()[3:],
'time': item[4].strip()[5:],
'score': item[5]+item[6]
}
def write_to_file(content):
with open('result.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')
def save_to_mongo(content):
client = pymongo.MongoClient(MONGO_URI)
db = client[MONGO_DB]
db[MONGO_TABLE].update({'title': content['title']}, {'$set': content}, True)
print('存储成功 :{}'.format(content['title']))
def main(offset):
url = "http://maoyan.com/board/4?offset=" + str(offset)
html = get_one_page(url, headers)
for item in parse_one_page(html):
# write_to_file(item)
save_to_mongo(item)
if __name__ == "__main__":
# 多线程
start_time = time.time()
with ThreadPoolExecutor(5) as executor:
all_task = [executor.submit(main, (num * 10)) for num in range(10)]
for future in as_completed(all_task):
data = future.result()
print('done, takes {} s'.format(time.time() - start_time))
"""
# 多进程
start_time = time.time()
with ProcessPoolExecutor(8) as executor:
all_task = [executor.submit(main, (num * 10)) for num in range(10)]
for future in as_completed(all_task):
data = future.result()
# for i in range(10):
# main(i*10)
print('done, takes {} s'.format(time.time() - start_time))
"""
| [
"812569791@qq.com"
] | 812569791@qq.com |
61b3812c3519c25bd5a6a83bf20d8cac617d01fd | e5a8fae911cb1d7dabb76b8d3e8f37fca85ff1ae | /Guess the word!.py | e260791dc23cd31efbbd98f63d7a42b6dd1068a6 | [] | no_license | moomill46/MyFirstRepo | 3372bad4571ee584874adedf6202e325a91928dd | 7d1b42bf668728ef8e3373f0756cb6ba8e301eb9 | refs/heads/master | 2021-09-14T15:19:47.706851 | 2018-05-15T14:44:59 | 2018-05-15T14:44:59 | 106,409,343 | 0 | 1 | null | 2017-11-16T14:33:16 | 2017-10-10T11:40:18 | Python | UTF-8 | Python | false | false | 1,028 | py | import random
number = random.randint(0,3)
words = ["Ice Cream", "Dog", "Grass", "Pencil"]
hint1 = ["Melting", "Bone", "Green", "Case"]
hint2 = ["Summer", "Woof", "Lawn", "Sharpen"]
guess = ""
counter = 1
secretword = words[number]
while True:
print("Guess the word!")
print("Please write the first letter with a capital letter. Type 'hint1', 'hint2', 'first letter', 'last letter', or 'give up' for help.")
guess = input()
if guess == secretword:
print("That is correct! You win!")
print("It took you " + str(counter) + " guesses.")
break
elif guess == "hint1":
print(hint1[number])
elif guess == "hint2":
print(hint2[number])
elif guess == "first letter":
print(secretword[0])
elif guess == "last letter":
print(secretword[-1])
elif guess == "give up":
print("The word was " + secretword + ".")
break
else:
print("Try again.")
counter += 1
| [
"noreply@github.com"
] | moomill46.noreply@github.com |
7d6a28c779181b9c628e22f4fb0d8db1ed01cf27 | dad31a33a6d438571959d115dea6598fb0256217 | /Env/utils/collision_detect.py | d21069affd97c2e7e1b23f173824a308ea8eaf26 | [] | no_license | ShawnLue/Dynamic-VIN-in-Gridworld | 3f4956c18608ba1da449e816d0f4e61f0f281223 | 4f5e332568e4764f51043ab63766af989aa5ae21 | refs/heads/master | 2021-07-13T11:50:02.531060 | 2017-11-20T09:29:25 | 2017-11-20T09:29:25 | 96,508,502 | 10 | 2 | null | null | null | null | UTF-8 | Python | false | false | 554 | py | # ----------------------------------------------------
# Second edition of HAADS(used for RL simulation)
# Author: Xiangyu Liu
# Date: 2016.11.26
# Filename: collision_detect.py
# ----------------------------------------------------
import pygame as pg
def collide_other(one, two):
"""
Callback function for use with pg.sprite.collidesprite methods.
It simply allows a sprite to test collision against its own group,
without returning false positives with itself.
"""
return one is not two and pg.sprite.collide_rect(one, two)
| [
"xiangyu.liu@hobot.cc"
] | xiangyu.liu@hobot.cc |
8693570b0b6900f711f8707fabbe6b35c3c43152 | 0915497f64bc5f5e93fef02ef01f6e98c46c73d0 | /geekshop/urls.py | 572f4429dd1f1a8d2a3d41274c55f91f7cf9f1b4 | [] | no_license | sinitsa2001/dj_git1 | 3d8e2820fb46a9e926120eb419ae89a54dfdb66b | 5362af7eb86129d13d61ffd7b1d5b37bb4e70e02 | refs/heads/master | 2023-02-26T00:42:26.737369 | 2021-01-07T15:58:08 | 2021-01-07T15:58:08 | 318,589,611 | 0 | 0 | null | 2021-02-02T06:12:59 | 2020-12-04T17:32:37 | CSS | UTF-8 | Python | false | false | 1,417 | py | """geekshop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from mainapp import views as mainapp_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', mainapp_views.index,name ='main'),
path('products/', include('mainapp.urls', namespace = 'products')),
# path('products/', mainapp_views.products, name ='products'),
# path('test_context/',mainapp_views.test_context),
path('auth/', include('authapp.urls')),
path('baskets/', include('basketapp.urls', namespace='baskets')),
path('admin-staff/', include('adminapp.urls', namespace='admin_staff')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
| [
"sinitsa2001@mail.ru"
] | sinitsa2001@mail.ru |
ef8bc9236fe9d8d6145fa6dcda21ac53ac36bd2e | 6b76c6a27a1cd5d32ca233ba83b730dc5f68fae3 | /week-03/5-kata/practice/24_solution.py | 8b751957703c840af92a5c4533a269f004b2098e | [] | no_license | TesztLokhajtasosmokus/velox-syllabus | 79fae3e6ac1a61d9fda4a2d66ddfd14f647cacfd | eeac5910636963691257024a077bcaed653fcbd2 | refs/heads/master | 2020-03-28T06:28:44.916564 | 2017-11-17T08:48:54 | 2017-11-17T08:48:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 352 | py | x = 8
time = 120
out = ''
# if x is dividable by 4
# and time is not more than 200
# set out to 'check'
# if time is more than 200
# set out to 'Time out'
# otherwise set out to 'Run Forest Run!'
maxtime = 200
if x % 4 == 0 and time < maxtime:
out = 'check'
elif time >= maxtime:
out = 'Time out'
else:
out = 'Fussa tee fussa'
print(out)
| [
"adam.gyulavari@lab.coop"
] | adam.gyulavari@lab.coop |
6be19881776e1f1c4e819d364e189061a9b189a8 | 9e703cadf5eef0b5a7a7d928db12c304fdaf7c8b | /Chapter_6/HighLowMedium.py | 997d2bb4596f185e3583b50f9b099424b48c81ad | [] | no_license | MikaylaRobinson/Python-For-Biologists | 0f5224780971598b812202641050bc7600f64687 | 9987f29606f31629cf86c6b082fb43ba8b4533a9 | refs/heads/master | 2020-03-28T16:12:18.489971 | 2018-09-26T04:07:55 | 2018-09-26T04:07:55 | 148,669,676 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 771 | py | """
Print out each gene name and a message labeling the AT content as high, medium, or low
"""
def finding_at_content(dna_sequence):
a_content = dna_sequence.upper().count("A")
t_content = dna_sequence.upper().count("T")
at_content = (a_content + t_content) / len(dna_sequence)
return at_content
gene_data = open("data.csv")
for gene in gene_data:
fields = gene.rstrip("\n").split(",")
species_name = fields[0]
sequence = fields[1]
gene_name = fields[2]
expression_level = fields[3]
if finding_at_content(sequence) > 0.65:
print(gene_name + " has high AT content")
elif finding_at_content(sequence) < 0.45:
print(gene_name + " has low AT content")
else:
print(gene_name + " has medium AT content") | [
"mikayla22robinson@gmail.com"
] | mikayla22robinson@gmail.com |
4fa3bc4a8f2a3c3bb5dc20efad9e51101ac63264 | 9dd90f5248ce83397f26f2e443344693527dff9a | /myproject/news/migrations/0006_news_tag.py | 14341d18780227800a4c5ba4ee2d98bd6afd8226 | [] | no_license | dyappscrip/myproject | 4cdbc35708a032653a048c1de66b281589eb3c17 | faf2954ebe44e9d630ab3b3a74a79ad55a8f45a3 | refs/heads/master | 2023-01-28T18:55:58.320265 | 2020-12-12T12:29:49 | 2020-12-12T12:29:49 | 320,553,385 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 366 | py | # Generated by Django 3.1.3 on 2020-12-09 06:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('news', '0005_news_ocatid'),
]
operations = [
migrations.AddField(
model_name='news',
name='tag',
field=models.TextField(default=''),
),
]
| [
"dhanraj@mobifyi.com"
] | dhanraj@mobifyi.com |
db1015691e7686409ba8a0670aaf42ca71b50462 | a45a7c23c7b8c33e6ad016487bff47f3cd4f3429 | /ejercicios-clase-07-01bim-GeraldJT/EjemploFor/Ejemplo01.py | 3b1ec411002f5caab7c03b9362f7ac388ae63e10 | [] | no_license | IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-GeraldJT | 87ca88e52b45886fa7124fff1155e9b53578c4ec | 6999ef41af2e5a0e42454605371e63bbe758320d | refs/heads/main | 2023-01-23T03:45:02.706359 | 2020-12-06T22:08:22 | 2020-12-06T22:08:22 | 318,824,586 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 133 | py | for i in range(0,10):
#
for i in range(10,1,-1):
#
for i in range(0,10,5):
#
for i in range(0,10,3):
#
for i in range(0,10, -11):
| [
"geraldjt.gmail.com"
] | geraldjt.gmail.com |
bc0b0d54a1088c43f86ec3954ea51b361c26df54 | b3f663328175f6dc8a654c8e683445b9072c25ff | /demo33_reduce5.py | 267d5d5df55d2b1d0ea3d89b3ebd47fa769bc921 | [] | no_license | viviyin/bdpy | be776118a041f140ac1a73ac089c6b77f033bcb6 | 98b219c37fec53a127856d6b13ef78b56685240d | refs/heads/master | 2022-11-30T02:12:10.464888 | 2020-07-17T09:03:52 | 2020-07-17T09:03:52 | 279,491,646 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 808 | py | import collections
from functools import reduce
from pprint import pprint
course = collections.namedtuple('course', ['name', 'field', 'attendee', 'remote'])
poop = course(name='poop', field='python', attendee=10, remote=False)
bdpy = course(name='bdpy', field='python', attendee=15, remote=True)
pykt = course(name='pykt', field='python', attendee=12, remote=True)
andbiz = course(name='andbiz', field='android', attendee=5, remote=True)
aiocv = course(name='aiocv', field='python', attendee=20, remote=False)
courses = (poop, bdpy, pykt, andbiz, aiocv)
pprint(courses)
courseByCategory = reduce(lambda acc, val: {**acc, **{val.field: acc[val.field] + [val.name]}}, courses,
{'python': [], 'android': []})
pprint(courseByCategory)
print({'a': 0, 'b': 1, 'a': 0 + 1, 'b': 1 + 1})
| [
"vivian82627@gmail.com"
] | vivian82627@gmail.com |
d0cfe89b6ef336648599b637bbfbfa48e759b3f5 | 19cec240505e27546cb9b10104ecb16cc2454702 | /linux/test/python/stat.py | 92948f7462ef0f06b81fcd9bffeaa35ac9a7e81c | [] | no_license | imosts/flume | 1a9b746c5f080c826c1f316a8008d8ea1b145a89 | a17b987c5adaa13befb0fd74ac400c8edbe62ef5 | refs/heads/master | 2021-01-10T09:43:03.931167 | 2016-03-09T12:09:53 | 2016-03-09T12:09:53 | 53,101,798 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 124 | py |
import flume.flmos as flmo
import sys
for f in sys.argv[1:] :
ls = flmo.stat_file (f)
print "%s => %s" % (f, ls)
| [
"imosts"
] | imosts |
6e1b6ebe2a2c4908be086912a1e365735cda1e4b | 227e26af048fd2ba5aa3bb06410a1ac801048152 | /tcpClient.py | ce3cd30a5ed54d8fc0f26a00b468037ebe8063a0 | [] | no_license | ahhswangkai/pylearn | 9122519fa6f3e868d6ecf210b39387b348ed4972 | 71477b0b8db10d4b5b6c203aa747b86611ecabfa | refs/heads/master | 2021-01-01T19:02:08.568412 | 2017-02-20T10:22:30 | 2017-02-20T10:22:30 | 30,176,686 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 207 | py | import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
print s.recv(1024)
for data in ['wk','sss','sskk']:
s.send(data)
print s.recv(1024)
s.send('exit')
s.close() | [
"ahhswangkai@163.com"
] | ahhswangkai@163.com |
00d1c33e3fb56e293769a2b22a45d9ee11e61274 | d73581e419cec58f7d7b58a22c2bd5a78959847d | /dummyrdm/RDM/checksums.py | 4cdcd229cc1f02a9a02bca694ab6b6abd4f8838b | [
"MIT"
] | permissive | dfivesystems/dummyRDM | e3953675f0834ef1236274835a8f75266931118a | 3d329b1538a62288bc42999b4dc0451583e64172 | refs/heads/master | 2023-08-17T19:06:34.214850 | 2020-01-19T19:56:54 | 2020-01-19T19:56:54 | 229,488,666 | 2 | 2 | MIT | 2023-08-14T22:08:10 | 2019-12-21T22:07:17 | Python | UTF-8 | Python | false | false | 150 | py | def rdmCheckSum(checksumbytes):
checksum = sum(checksumbytes)
checksumbytes.extend((checksum // 256, checksum % 256))
return checksumbytes | [
"dave@d5systems.co.uk"
] | dave@d5systems.co.uk |
8b6b1b686c656f460928930a4a0b4fa4374f8ad9 | 18e48f22f88fe80ce54d12fdbf9d05a7ca5bd65a | /0x11-python-network_1/7-error_code.py | ad1698d9aff563aff2ccaec553148dfecf84b193 | [] | no_license | SantiagoHerreG/holbertonschool-higher_level_programming | 426c4bc9bc080a81b72d2f740c8ed2eb365023eb | ca2612ef3be92a60764d584cf39de3a2ba310f84 | refs/heads/master | 2020-07-22T19:33:48.507287 | 2020-02-14T04:34:00 | 2020-02-14T04:34:00 | 207,305,022 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 342 | py | #!/usr/bin/python3
"""takes in a URL, sends a request to the URL and displays the body of
the response"""
import requests
import sys
if __name__ == "__main__":
url = sys.argv[1]
res = requests.get(url)
if res.status_code == requests.codes.ok:
print(res.text)
else:
print("Error code:", res.status_code)
| [
"888@holbertonschool.com"
] | 888@holbertonschool.com |
3a44f3a601e85bd1eb025f738bccf66cc41902b1 | 6d568abb860ee46a12a694e819f4a5aac2e0f136 | /raspberry-pi/raspi/lib/python2.7/sre_compile.py | 51d0a578072feb072adb44b9af784d9315720be1 | [] | no_license | jkubicek/home-automation | cab3df4ed634d33cd4d235872007a8b1c2e9d908 | 91c2c96ee5d5af82ae5fccf2a893e20f99dae72a | refs/heads/master | 2020-05-30T15:52:42.271713 | 2014-06-01T04:20:10 | 2014-06-01T04:20:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 102 | py | /opt/twitter/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.py | [
"jkubicek@twitter.com"
] | jkubicek@twitter.com |
a800f9d568a1d7598f3cae018badde0c06ea9409 | 8578ae5be776b49559fa95ce30f6b45b6a82b73a | /test/functional/p2p_fingerprint.py | 0a572d97cfb88494d434474850b03427f50dd5ed | [
"MIT"
] | permissive | devcoin/core | 3f9f177bd9d5d2cc54ff95a981cfe88671206ae2 | f67e8b058b4316dd491615dc3f8799a45f396f4a | refs/heads/master | 2023-05-25T03:42:03.998451 | 2023-05-24T07:59:22 | 2023-05-24T08:02:14 | 21,529,485 | 16 | 13 | MIT | 2022-01-07T17:04:18 | 2014-07-05T22:42:13 | C | UTF-8 | Python | false | false | 5,061 | py | #!/usr/bin/env python3
# Copyright (c) 2017-2020 The Bitcoin Core and Devcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test various fingerprinting protections.
If a stale block more than a month old or its header are requested by a peer,
the node should pretend that it does not have it to avoid fingerprinting.
"""
import time
from test_framework.blocktools import (create_block, create_coinbase)
from test_framework.messages import CInv, MSG_BLOCK
from test_framework.p2p import (
P2PInterface,
msg_headers,
msg_block,
msg_getdata,
msg_getheaders,
p2p_lock,
)
from test_framework.test_framework import DevcoinTestFramework
from test_framework.util import (
assert_equal,
)
class P2PFingerprintTest(DevcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
# Build a chain of blocks on top of given one
def build_chain(self, nblocks, prev_hash, prev_height, prev_median_time):
blocks = []
for _ in range(nblocks):
coinbase = create_coinbase(prev_height + 1)
block_time = prev_median_time + 1
block = create_block(int(prev_hash, 16), coinbase, block_time)
block.solve()
blocks.append(block)
prev_hash = block.hash
prev_height += 1
prev_median_time = block_time
return blocks
# Send a getdata request for a given block hash
def send_block_request(self, block_hash, node):
msg = msg_getdata()
msg.inv.append(CInv(MSG_BLOCK, block_hash))
node.send_message(msg)
# Send a getheaders request for a given single block hash
def send_header_request(self, block_hash, node):
msg = msg_getheaders()
msg.hashstop = block_hash
node.send_message(msg)
# Checks that stale blocks timestamped more than a month ago are not served
# by the node while recent stale blocks and old active chain blocks are.
# This does not currently test that stale blocks timestamped within the
# last month but that have over a month's worth of work are also withheld.
def run_test(self):
node0 = self.nodes[0].add_p2p_connection(P2PInterface())
# Set node time to 60 days ago
self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60)
# Generating a chain of 10 blocks
block_hashes = self.nodes[0].generatetoaddress(10, self.nodes[0].get_deterministic_priv_key().address)
# Create longer chain starting 2 blocks before current tip
height = len(block_hashes) - 2
block_hash = block_hashes[height - 1]
block_time = self.nodes[0].getblockheader(block_hash)["mediantime"] + 1
new_blocks = self.build_chain(5, block_hash, height, block_time)
# Force reorg to a longer chain
node0.send_message(msg_headers(new_blocks))
node0.wait_for_getdata([x.sha256 for x in new_blocks])
for block in new_blocks:
node0.send_and_ping(msg_block(block))
# Check that reorg succeeded
assert_equal(self.nodes[0].getblockcount(), 13)
stale_hash = int(block_hashes[-1], 16)
# Check that getdata request for stale block succeeds
self.send_block_request(stale_hash, node0)
node0.wait_for_block(stale_hash, timeout=3)
# Check that getheader request for stale block header succeeds
self.send_header_request(stale_hash, node0)
node0.wait_for_header(hex(stale_hash), timeout=3)
# Longest chain is extended so stale is much older than chain tip
self.nodes[0].setmocktime(0)
block_hash = int(self.nodes[0].generatetoaddress(1, self.nodes[0].get_deterministic_priv_key().address)[-1], 16)
assert_equal(self.nodes[0].getblockcount(), 14)
node0.wait_for_block(block_hash, timeout=3)
# Request for very old stale block should now fail
with p2p_lock:
node0.last_message.pop("block", None)
self.send_block_request(stale_hash, node0)
node0.sync_with_ping()
assert "block" not in node0.last_message
# Request for very old stale block header should now fail
with p2p_lock:
node0.last_message.pop("headers", None)
self.send_header_request(stale_hash, node0)
node0.sync_with_ping()
assert "headers" not in node0.last_message
# Verify we can fetch very old blocks and headers on the active chain
block_hash = int(block_hashes[2], 16)
self.send_block_request(block_hash, node0)
self.send_header_request(block_hash, node0)
node0.sync_with_ping()
self.send_block_request(block_hash, node0)
node0.wait_for_block(block_hash, timeout=3)
self.send_header_request(block_hash, node0)
node0.wait_for_header(hex(block_hash), timeout=3)
if __name__ == '__main__':
P2PFingerprintTest().main()
| [
"fernando@develcuy.com"
] | fernando@develcuy.com |
da901c8774512e8c8f761264d8e4305fe2a8ef57 | 1d9f59a23aec8cfda4b51a95db134fde270214c3 | /Part1/ann.py | 721985d5fae8a68737705e55f2da10cfa22605ab | [] | no_license | goffle/Python | 511e3f17c2b52e4169f0da2d40b8d3a28599f8ab | 2bc9dd1dfca8ccb03941e3821a4a5bccd22bfc47 | refs/heads/master | 2021-01-22T23:10:27.896259 | 2017-05-31T02:46:04 | 2017-05-31T02:46:04 | 92,802,541 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,559 | py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed May 31 07:20:01 2017
@author: seb
"""
# Artificial Neural Network
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# pip install tensorflow
# Installing Keras
# pip install --upgrade keras
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Part 2 - Now let's make the ANN!
# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense
# Initialising the ANN
classifier = Sequential()
# Adding the input layer and the first hidden layer
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
# Adding the second hidden layer
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
# Adding the output layer
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
# Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Fitting the ANN to the Training set
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)
# Part 3 - Making predictions and evaluating the model
# Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
# Home Work
dataset2 = pd.DataFrame([[0,0,600,1,40,3,60000,2,1,1,50000]]);
X_test2 = sc.transform(dataset2)
y_pred2 = classifier.predict(X_test2) | [
"se.legoff@gmail.com"
] | se.legoff@gmail.com |
1c1dcd8bc185c5981370cc6412b274be30918a26 | d2c4934325f5ddd567963e7bd2bdc0673f92bc40 | /tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_PolyTrend_Seasonal_Minute_MLP.py | 613e814baf612b7e6b06d1d12091e2333056e4bd | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jmabry/pyaf | 797acdd585842474ff4ae1d9db5606877252d9b8 | afbc15a851a2445a7824bf255af612dc429265af | refs/heads/master | 2020-03-20T02:14:12.597970 | 2018-12-17T22:08:11 | 2018-12-17T22:08:11 | 137,104,552 | 0 | 0 | BSD-3-Clause | 2018-12-17T22:08:12 | 2018-06-12T17:15:43 | Python | UTF-8 | Python | false | false | 172 | py | import pyaf.tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['RelativeDifference'] , ['PolyTrend'] , ['Seasonal_Minute'] , ['MLP'] ); | [
"antoine.carme@laposte.net"
] | antoine.carme@laposte.net |
8591bcf58366b8ff94295a55f3ab3600d0536bef | a85273a1bd2dfb3d0cf53fdf106ddb790ff7c0a3 | /Lab4/movies/permissions.py | e4fd781c6a0f1dafe17d17039b84ea86cd658ae6 | [] | no_license | jagodalewandowska/aplikacje-internetowe-lewandowska-185ic | f6e924bc5813174df54897881d1a7fa8105bb687 | 317b0ed88ea27683a7f318604437f5ba20ef1903 | refs/heads/main | 2023-02-21T10:25:42.296994 | 2021-01-27T17:26:14 | 2021-01-27T17:26:14 | 310,323,306 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 645 | py | # import zezwoleń z django rest
from rest_framework import permissions
# overriding metodę hasobjectpermission tak,
# aby pozwolić temu samemu użytkownikowi na edytowanie
# lub usuwanie jeśli jest właścicielem posta
# utworzenie własnej klasy, która rozszerza basepermission
class IsAuthorOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
# zezwolenie tylko do odczytu na zapytanie
if request.method in permissions.SAFE_METHODS:
return True
# zezwolenie na edytcję i usuwanie tylko dla właściciela posta
return obj.author == request.user | [
"jadlewandowska@gmail.com"
] | jadlewandowska@gmail.com |
100baaea21f962521c1a74299239dd8bde40a450 | 4c095c835cd391e4563a87d5f0652c8863a58ab1 | /textrank_model.py | 4c84b2144a15582cd97eb690e6c92d237d5c1839 | [] | no_license | wanglke/kewwords | 1bab62a6a246bedaee9d2947a562148081203d9d | 10ee5f451491769032046f945b2725e019759f93 | refs/heads/main | 2023-05-02T00:21:51.582848 | 2021-05-18T02:26:35 | 2021-05-18T02:26:35 | 345,949,680 | 5 | 1 | null | null | null | null | UTF-8 | Python | false | false | 934 | py | # coding=utf-8
import pandas as pd
import numpy as np
from utils import get_corpus
import jieba.analyse
class Textrank(object):
def __init__(self,data):
self.data = data
def get_keywords(self, stopkey, topk=5):
"""
get the top k keywords
:param topk:
:return:
"""
if isinstance(self.data, list):
key_list = []
for text in self.data:
jieba.analyse.set_stop_words("data/stopWord.txt")
keywords = jieba.analyse.textrank(text, topK=topk, allowPOS=('n', 'nz', 'v', 'vd', 'vn', 'l', 'a', 'd'))
key_list.append(keywords)
return key_list
if isinstance(self.data, str):
jieba.analyse.set_stop_words("data/stopWord.txt")
keywords = jieba.analyse.textrank(self.data , topK=topk, allowPOS=('n', 'nz', 'v', 'vd', 'vn', 'l', 'a', 'd'))
return keywords | [
"noreply@github.com"
] | wanglke.noreply@github.com |
e65a947a803a00f34dcaf38fb3e04939f3024575 | 1e3988a37cb7f36fefd898ab5b50f2c5ebc00708 | /manage.py | fb4edebf62b382108fc514fc30dc54130f1a0053 | [] | no_license | zawadzkm/www_zad2 | f5a8bd196bdd8650fd04766ed0bb8b423f08ca4f | 02f90dd58cf67477941f73203bd1684c5662c398 | refs/heads/master | 2021-01-23T08:04:26.531581 | 2017-04-18T12:39:42 | 2017-04-18T12:39:42 | 86,474,909 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 806 | py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "www_zad2.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
| [
"mariusz.zawadzki@roche.com"
] | mariusz.zawadzki@roche.com |
59378ed1c249261ad53db470074838f10644f261 | 3381d3d1b70bd88374e75d90197d0202945bbade | /authentication/views.py | 1ea82fb55ee882e019ac000c9ca14bf94b9c33ca | [] | no_license | PHONGLEX/djangorestframework_quizapi | 30d5011b67a484a525c94071672f29ed2b0cb700 | c9f7b4ebdc00188533a0a5f44c13594011729fa4 | refs/heads/master | 2023-08-02T00:58:35.647091 | 2021-10-01T09:17:05 | 2021-10-01T09:17:05 | 412,402,225 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,554 | py | import jsonpickle
import jwt
from rest_framework import generics, status
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.contrib import auth
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import smart_str, force_bytes, DjangoUnicodeDecodeError
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.contrib.sites.shortcuts import get_current_site
from django.conf import settings
from django.urls import reverse
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from .models import User
from .serializers import *
from .tasks import send_email_task
class RegisterView(generics.GenericAPIView):
serializer_class = RegisterSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user = User.objects.get(email=user_data['email'])
token = RefreshToken.for_user(user)
site = get_current_site(request).domain
url = reverse('email-verify')
link = 'http://' + site + url + "?token=" + str(token)
body = "Hi" + user.email + "\n Please use the link below to verify your account " + link
data = {
'subject': "Verify your account",
"body": body,
"to": user.email
}
send_email_task.delay(data)
return Response({'message': "We've sent you an email to verify your account"}, status=status.HTTP_201_CREATED)
class EmailVerificationView(generics.GenericAPIView):
serializer_class = EmailVerificationSerializer
token_param = openapi.Parameter('token', openapi.IN_QUERY, description="token param", type=openapi.TYPE_STRING)
@swagger_auto_schema(manual_parameters=[token_param])
def get(self, request):
token = request.GET.get('token')
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms="HS256")
user = User.objects.get(id=payload['user_id'])
if not user.is_verified:
user.is_verified = True
user.save()
return Response({"message":"Successfully activate"}, status=status.HTTP_200_OK)
except jwt.exceptions.DecodeError as e:
return Response({"error": "Invalid token, please request a new one"}, status=status.HTTP_400_BAD_REQUEST)
except jwt.exceptions.ExpiredSignatureError as e:
return Response({"error": "Token is expired, please request a new one"}, status=status.HTTP_400_BAD_REQUEST)
class LoginView(generics.GenericAPIView):
serializer_class = LoginSerializer
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.data, status=status.HTTP_200_OK)
class ResetPasswordView(generics.GenericAPIView):
serializer_class = ResetPasswordSerializer
def post(self, request):
email = request.data.get('email')
user = User.objects.filter(email=email)
if user.exists():
user = user[0]
uidb64 = urlsafe_base64_encode(force_bytes(jsonpickle.encode(user)))
token = PasswordResetTokenGenerator().make_token(user)
url = reverse('reset-password-confirm', kwargs={
'uidb64': uidb64,
'token': token
})
site = get_current_site(request).domain
link = 'http://' + site + url
body = "Hi " + user.email + "\n Please use the link below to reset your password " + link
data = {
'subject': "Reset your password",
"body": body,
"to": user.email
}
send_email_task.delay(data)
return Response({'message': "We've sent you an email to reset your password"}, status=status.HTTP_200_OK)
class CheckPasswordResetTokenView(APIView):
def post(self, request, uidb64, token):
try:
obj = smart_str(urlsafe_base64_decode(uidb64))
user = jsonpickle.decode(obj)
if not PasswordResetTokenGenerator().check_token(user, token):
return Response({'error': "Invalid token, please request a new one"}, status=status.HTTP_400_BAD_REQUEST)
return Response({'success': True, 'uidb64': uidb64, 'token': token}, status=status.HTTP_200_OK)
except Exception as e:
return Response({'error': "Invalid token, please request a new one"}, status=status.HTTP_200_OK)
class SetNewPasswordView(generics.GenericAPIView):
serializer_class = SetNewPasswordSerializer
def patch(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
return Response({"message": "Changed password successfully"}, status=status.HTTP_200_OK)
class LogoutView(generics.GenericAPIView):
serializer_class = LogoutSerializer
permission_classes = (IsAuthenticated,)
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(status=status.HTTP_204_NO_CONTENT)
| [
"fonglex@gmail.com"
] | fonglex@gmail.com |
13e62f614a85f55ddb49bff1ab3f18529c63c670 | 90d82883200bdd942f06e91a5ebb54aa2b3ecba4 | /apps/dishes/migrations/0005_auto_20200910_0414.py | 2e65418d58ac3e72dcb414cb5aaa0b3477344ef3 | [] | no_license | dmitry-morgachev/ration-app | 394db69bb22df44888847007c5521c25c0524238 | ffc8188a320a4fe3ae99aeb80f79c1f05b3f47ab | refs/heads/master | 2022-12-15T10:41:46.629431 | 2020-09-10T10:20:54 | 2020-09-10T10:20:54 | 294,157,566 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,486 | py | # Generated by Django 2.2.16 on 2020-09-10 04:14
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('dishes', '0004_auto_20200910_0348'),
]
operations = [
migrations.RenameModel(
old_name='DishRation',
new_name='RationDish',
),
migrations.CreateModel(
name='UserRation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('eaten_in', models.DateTimeField(default=datetime.datetime(2020, 9, 10, 4, 14, 15, 950389, tzinfo=utc), verbose_name='Когда съедено')),
('ration_dishes', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='ration_dishes', to='dishes.RationDish', verbose_name='Блюдо')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ration', to=settings.AUTH_USER_MODEL, verbose_name='Пользователь')),
],
options={
'verbose_name': ('Рацион пользователя',),
'verbose_name_plural': 'Рационы пользователей',
},
),
]
| [
"powerpowerov@gmail.com"
] | powerpowerov@gmail.com |
30d040917850dbfe213295e61066ca08ae2f4ddd | 509fc176af52f46ce62f54a6f63c7c27b1bd0c2c | /djangofiltertest/djangofiltertest/apps/posts_areas/api_v1/views.py | d95acb524992ab1ca2a3395a52d48a793ab3f132 | [
"MIT"
] | permissive | gonzaloamadio/django-filter-test | 8b16fdb989a8141ba5852cd4804148cb6b153e86 | 7b9dbc36ca248e2113deaac03e824b123a31a4ba | refs/heads/master | 2022-12-10T11:35:07.684916 | 2019-01-24T09:19:21 | 2019-01-24T09:19:21 | 167,159,577 | 0 | 0 | MIT | 2022-12-08T01:33:33 | 2019-01-23T09:54:40 | Python | UTF-8 | Python | false | false | 270 | py | from posts_areas.api_v1.serializers import PostAreaSerializer
from posts_areas.models import PostArea
from djangofiltertest.libs.views import APIViewSet
class PostAreaViewSet(APIViewSet):
queryset = PostArea.objects.all()
serializer_class = PostAreaSerializer
| [
"gonzaloamadio@gmail.com"
] | gonzaloamadio@gmail.com |
927bf4049811ef0b096b9d2becfbb569c35c1b1c | bc9d3ac7a99f40fc85a927ef96491871d4f76ea1 | /apps/users/views.py | 404adb6209e78609d5605773fe78bb344c932b9c | [] | no_license | 0Monster0/MxOnline | 572ad427d018a4dec111060171fc2162344ea720 | 19c5d3588ecbde1a0289b65f62bd7f224b489ce1 | refs/heads/master | 2020-03-08T02:05:35.738890 | 2018-05-10T09:44:16 | 2018-05-10T09:44:16 | 127,849,542 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,809 | py | # -*- coding:utf-8 -*-
import json
from django.shortcuts import render
# Django自带的用户验证,login
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.views.generic import View
# 并集运算
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.hashers import make_password
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from .forms import LoginForm, RegisterForm, ForgetForm, ModifyPwdForm, UploadImageForm, UserInfoForm
from .models import UserProfile, EmailVerifyRecord, Banner
from courses.models import Course
from utils.email_send import send_register_email
from operation.models import UserMessage, UserCourse, UserFavorite
from organization.models import CourseOrg
from utils.mixin_utils import LoginRequiredMixin
class CustomBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
try:
user = UserProfile.objects.get(Q(username=username) | Q(email=username))
if user.check_password(password):
return user
except Exception as e:
return None
# 用户注册
class RegisterView(View):
def get(self, request):
# get 请求的时候,把验证码组件一系列的 HTML render 到 register.html 里
register_form = RegisterForm()
return render(request, 'register.html', {'register_form': register_form})
def post(self, request):
register_form = RegisterForm(request.POST)
if register_form.is_valid():
email = request.POST.get('email', '')
if UserProfile.objects.filter(email=email):
return render(request, 'register.html', {'register_form': register_form, 'msg': '用户已经存在!'})
password = request.POST.get('password', '')
user_profile = UserProfile()
user_profile.username = email
user_profile.email = email
user_profile.password = make_password(password)
user_profile.is_active = False
user_profile.save()
# 注册时发送一条消息
user_message = UserMessage()
user_message.user = user_profile.id
user_message.message = '欢迎注册慕学在线网!'
user_message.save()
send_register_email(email, 'register')
return render(request, 'send_success.html')
else:
return render(request, 'register.html', {'register_form': register_form})
class ActiveUserView(View):
def get(self, request, active_code):
all_records = EmailVerifyRecord.objects.filter(code=active_code)
if all_records:
for record in all_records:
email = record.email
user = UserProfile.objects.get(email=email)
user.is_active = True
user.save()
return HttpResponseRedirect(reverse('login'))
else:
return render(request, 'active_fail.html')
class LogoutView(View):
def get(self, request):
logout(request)
return HttpResponseRedirect(reverse('index'))
class LoginView(View):
def get(self, request):
return render(request, 'login.html', {})
def post(self, request):
login_form = LoginForm(request.POST)
if login_form.is_valid():
user_name = request.POST.get('username', '')
pass_word = request.POST.get('password', '')
user = authenticate(username=user_name, password=pass_word)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('index'))
else:
return render(request, 'login.html', {'msg': '用户未激活!'})
else:
return render(request, 'login.html', {'msg': '用户名或密码错误!'})
else:
return render(request, 'login.html', {'login_form': login_form})
class ForgetPwdView(View):
def get(self, request):
forget_form = ForgetForm()
return render(request, 'forgetpwd.html', {'forget_form': forget_form})
def post(self, request):
forget_form = ForgetForm(request.POST)
if forget_form.is_valid():
email = request.POST.get('email', '')
send_register_email(email, 'forget')
# 发送完毕返回登录页面并显示发送邮件成功。
return render(request, "login.html", {"msg": "重置密码邮件已发送,请注意查收"})
else:
return render(request, 'forgetpwd.html', {'forget_form': forget_form})
class ResetView(View):
def get(self, request, active_code):
all_records = EmailVerifyRecord.objects.filter(code=active_code)
if all_records:
for record in all_records:
email = record.email
return render(request, 'password_reset.html', {'email': email})
else:
return render(request, 'active_fail.html')
return render(request, 'login.html')
class ModifyPwdView(View):
'''
用户修改密码
'''
def post(self, request):
modify_form = ModifyPwdForm(request.POST)
if modify_form.is_valid():
pwd1 = request.POST.get('password1', '')
pwd2 = request.POST.get('password2', '')
email = request.POST.get('email', '')
if pwd1 != pwd2:
return render(request, 'password_reset.html', {'email': email, 'msg': '两次密码不一致,请重新输入!'})
user = UserProfile.objects.get(email=email)
user.password = make_password(pwd2)
user.save()
return render(request, 'login.html')
else:
email = request.POST.get('email', '')
return render(request, 'password_reset.html', {'email': email, 'modify_form': modify_form})
class UserInfoView(LoginRequiredMixin, View):
'''
用户个人信息
'''
def get(self, request):
return render(request, 'usercenter-info.html', {})
def post(self, request):
user_info_form = UserInfoForm(request.POST, instance=request.user)
if user_info_form.is_valid():
user_info_form.save()
return HttpResponse('{"status":"success"}', content_type='application/json')
else:
return HttpResponse(json.dumps(user_info_form.errors), content_type='application/json')
class UploadImageView(View):
'''
用户头像上传
'''
def post(self, request):
image_form = UploadImageForm(request.POST, request.FILES, instance=request.user)
if image_form.is_valid():
image = image_form.cleaned_data['image']
image_form.save()
return HttpResponse('{"status":"success"}', content_type='application/json')
else:
return HttpResponse('{"status":"fail"}', content_type='application/json')
class UpdatePwdView(LoginRequiredMixin, View):
'''
个人中心修改密码
'''
def post(self, request):
modify_form = ModifyPwdForm(request.POST)
if modify_form.is_valid():
pwd1 = request.POST.get('password1', '')
pwd2 = request.POST.get('password2', '')
if pwd1 != pwd2:
return HttpResponse('{"status":"fail","msg":"两次密码不一致"}', content_type='application/json')
user = request.user
user.password = make_password(pwd2)
user.save()
return HttpResponse('{"status":"success"}', content_type='application/json')
else:
return HttpResponse(json.dumps(modify_form.errors), content_type='application/json')
class SendEmailCodeView(LoginRequiredMixin, View):
'''
发送邮箱验证码
'''
def get(self, request):
email = request.GET.get('email', '')
if UserProfile.objects.filter(email=email):
return HttpResponse('{"email":"该邮箱已注册"}', content_type='application/json')
send_register_email(email, 'update_email')
return HttpResponse('{"status":"success", "msg":"发送验证码成功"}', content_type='application/json')
class UpdateEmailView(LoginRequiredMixin, View):
'''
个人中心修改邮箱
'''
def post(self, request):
email = request.POST.get('email', '')
code = request.POST.get('code', '')
existed_records = EmailVerifyRecord.objects.filter(email=email, code=code, send_type='update_email')
if existed_records:
user = request.user
user.email = email
user.save()
return HttpResponse('{"status":"success"}', content_type='application/json')
else:
return HttpResponse('{"status":"fail","msg":"验证码出错!"}', content_type='application/json')
class MyCourseView(LoginRequiredMixin, View):
'''
我的课程
'''
def get(self, request):
user_courses = UserCourse.objects.filter(user=request.user)
return render(request, 'usercenter-mycourse.html', {
'user_courses': user_courses
})
class MyFavOrgView(LoginRequiredMixin, View):
'''
我收藏的机构
'''
def get(self, request):
org_list = []
fav_orgs = UserFavorite.objects.filter(user=request.user, fav_type=2)
for fav_org in fav_orgs:
org_id = fav_org.fav_id
org = CourseOrg.objects.get(id=int(org_id))
org_list.append(org)
return render(request, 'usercenter-fav-org.html', {
'org_list': org_list
})
class MyFavTeacherView(LoginRequiredMixin, View):
'''
我收藏的老师
'''
def get(self, request):
teacher_list = []
fav_teachers = UserFavorite.objects.filter(user=request.user, fav_type=3)
for fav_teacher in fav_teachers:
teacher_id = fav_teacher.fav_id
teacher = CourseOrg.objects.get(id=int(teacher_id))
teacher_list.append(teacher)
return render(request, 'usercenter-fav-teacher.html', {
'teacher_list': teacher_list
})
class MyFavCourseView(LoginRequiredMixin, View):
'''
我收藏的课程
'''
def get(self, request):
course_list = []
fav_courses = UserFavorite.objects.filter(user=request.user, fav_type=1)
for fav_course in fav_courses:
course_id = fav_course.fav_id
course = CourseOrg.objects.get(id=int(course_id))
course_list.append(course)
return render(request, 'usercenter-fav-course.html', {
'course_list': course_list
})
class MyMessageView(LoginRequiredMixin, View):
'''
我的消息
'''
def get(self, request):
all_messages = UserMessage.objects.filter(user=request.user.id)
# 用户进入个人消息后清空未读消息的记录
all_unread_messages = UserMessage.objects.filter(user=request.user.id, has_read=False)
for unread_message in all_unread_messages:
unread_message.has_read = True
unread_message.save()
# 对我的消息进行分页
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
p = Paginator(all_messages, 5, request=request)
messages = p.page(page)
return render(request, 'usercenter-message.html', {
'messages': messages
})
class IndexView(View):
'''
慕学在线网首页
'''
def get(self, request):
# 取出轮播图
all_banners = Banner.objects.all().order_by('index')[:4]
courses = Course.objects.filter(is_banner=False)[:6]
banner_courses = Course.objects.filter(is_banner=True)[:3]
course_orgs = CourseOrg.objects.all()[:15]
return render(request, 'index.html', {
'all_banners': all_banners,
'courses': courses,
'banner_courses': banner_courses,
'course_orgs': course_orgs
})
def page_forbidden(request):
# 全局403处理函数
response = render_to_response('403.html', {})
response.status_code = 403
return response
def page_not_found(request):
# 全局404处理函数
response = render_to_response('404.html', {})
response.status_code = 404
return response
def page_error(request):
# 全局500处理函数
response = render_to_response('500.html', {})
response.status_code = 500
return response
| [
"630550245@qq.com"
] | 630550245@qq.com |
dc90c334f8f9314e070b2c504c81d5c4b72155a3 | bc9f66258575dd5c8f36f5ad3d9dfdcb3670897d | /lib/googlecloudsdk/core/util/tokenizer.py | 1a403b82516d25b5b6213598941a3ba5f7672ed2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | google-cloud-sdk-unofficial/google-cloud-sdk | 05fbb473d629195f25887fc5bfaa712f2cbc0a24 | 392abf004b16203030e6efd2f0af24db7c8d669e | refs/heads/master | 2023-08-31T05:40:41.317697 | 2023-08-23T18:23:16 | 2023-08-23T18:23:16 | 335,182,594 | 9 | 2 | NOASSERTION | 2022-10-29T20:49:13 | 2021-02-02T05:47:30 | Python | UTF-8 | Python | false | false | 2,291 | py | # -*- coding: utf-8 -*- #
# Copyright 2013 Google LLC. 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A utility for tokenizing strings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import io
__all__ = ['Literal', 'Separator', 'Tokenize']
_ESCAPE_CHAR = '\\'
class Literal(str):
pass
class Separator(str):
pass
def Tokenize(string, separators):
"""Tokenizes the given string based on a list of separator strings.
This is similar to splitting the string based on separators, except
that this function retains the separators. The separators are
wrapped in Separator objects and everything else is wrapped in
Literal objects.
For example, Tokenize('a:b,c:d', [':', ',']) returns [Literal('a'),
Separator(':'), Literal('b'), Separator(','), Literal('c'),
Separator(':'), Literal('d')].
Args:
string: str, The string to partition.
separators: [str], A list of strings on which to partition.
Raises:
ValueError: If an unterminated escape sequence is at the
end of the input.
Returns:
[tuple], A list of strings which can be of types Literal or
Separator.
"""
tokens = []
curr = io.StringIO()
buf = io.StringIO(string)
while True:
c = buf.read(1)
if not c:
break
elif c == _ESCAPE_CHAR:
c = buf.read(1)
if c:
curr.write(c)
continue
else:
raise ValueError('illegal escape sequence at index {0}: {1}'.format(
buf.tell() - 1, string))
elif c in separators:
tokens.append(Literal(curr.getvalue()))
tokens.append(Separator(c))
curr = io.StringIO()
else:
curr.write(c)
tokens.append(Literal(curr.getvalue()))
return tokens
| [
"cloudsdk.mirror@gmail.com"
] | cloudsdk.mirror@gmail.com |
14a58747c877c3be919ecea261d0a16b85adec91 | 8e713563751dc0f3fe6df60b5745999ceda15be2 | /cgi-bin/editurl.py | 00e6f4f01a49c726c71f15b4240d63a67dbf6113 | [] | no_license | siguremon/pyweb | 5cbeeb0008651e24d2fc46b052ea1290cb1fab31 | a2599526146b9f2415cba19d835f8e472d3c2eb1 | refs/heads/master | 2020-05-20T05:52:36.551142 | 2012-07-14T03:14:26 | 2012-07-14T03:14:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,335 | py | #!/usr/bin/env python
# coding: utf-8
from simpletemplate import SimpleTemplate
from rssurl import Rssurl
from os import path
from httphandler import Request, Response
import cgitb; cgitb.enable()
errors = {}
value_dic = {'errors':errors, 'title':'', 'url':'', 'item_id':''}
req = Request()
f = req.form
p = path.join(path.dirname(__file__), 'editform.html')
if not f.getvalue('posted'):
id = f.getvalue('id')
rss = Rssurl(id = int(id))
value_dic.update({'title':rss.title, 'url':rss.url, 'item_id':id})
else:
id = f.getvalue('id')
title = unicode(f.getvalue('title', ''), 'utf-8', 'ignore')
url = unicode(f.getvalue('url', ''), 'utf-8', 'ignore')
value_dic.update({'title':title, 'url':url, 'item_id':id})
if not title:
errors['title'] = u'タイトルを入力してください'
if not url.startswith('http://'):
errors['url'] = u'正しいURLを入力してください'
if not errors:
rss = Rssurl(id = int(f.getvalue('id')))
rss.title = f.getvalue('title')
rss.url = f.getvalue('url')
rss.update()
p = path.join(path.dirname(__file__), 'posted.html')
value_dic['message'] = u'RSS取得URLを編集しました'
t = SimpleTemplate(file_path = p)
res = Response()
body = t.render(value_dic)
res.set_body(body)
print res
| [
"siguremon@gmail.com"
] | siguremon@gmail.com |
4477871af63bc3553fb411a4fa66d4399b71b95d | 79db8b1a642b69180f6b38f89ecb6907f5850a6b | /build/ikiwi_abila_teleop_joy/catkin_generated/pkg.develspace.context.pc.py | d5c75afee19cdc60b406250ebec5436fb486ea13 | [] | no_license | zrjnz/ikiwi-abila | c85e92b03c811bdef8d91ee9ef2f66658c530932 | 41654c866df030bc94acfce8627be5188b3c88ea | refs/heads/master | 2023-04-20T23:08:02.036745 | 2021-05-05T08:31:13 | 2021-05-05T08:31:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 389 | py | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "ikiwi_abila_teleop_joy"
PROJECT_SPACE_DIR = "/home/ikiwi/ikiwi_abila_new/devel"
PROJECT_VERSION = "0.0.0"
| [
"jose.nunez@ub.edu"
] | jose.nunez@ub.edu |
ea11bf784f41f2baf536fbb111241ab1f1165160 | 66c7b0da6ee27ddce0943945503cdecf199f77a2 | /rllib/util/parameter_decay.py | 2df23cd677dcb3091464bf29c075df7a3d8bd9ee | [
"MIT"
] | permissive | tzahishimkin/extended-hucrl | 07609f9e9f9436121bcc64ff3190c966183a2cd9 | c144aeecba5f35ccfb4ec943d29d7092c0fa20e3 | refs/heads/master | 2023-07-09T22:57:28.682494 | 2021-08-24T08:50:16 | 2021-08-24T08:50:16 | 383,819,908 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,056 | py | """Implementation of a Parameter decay class."""
from abc import ABCMeta
import torch.jit
import torch.nn as nn
from rllib.util.neural_networks.utilities import inverse_softplus
class ParameterDecay(nn.Module, metaclass=ABCMeta):
"""Abstract class that implements the decay of a parameter."""
def __init__(self, start, end=None, decay=None):
super().__init__()
if not isinstance(start, torch.Tensor):
start = torch.tensor(start)
self.start = nn.Parameter(start, requires_grad=False)
if end is None:
end = start
if not isinstance(end, torch.Tensor):
end = torch.tensor(end)
self.end = nn.Parameter(end, requires_grad=False)
if decay is None:
decay = 1.0
if not isinstance(decay, torch.Tensor):
decay = torch.tensor(decay)
self.decay = nn.Parameter(decay, requires_grad=False)
self.step = 0
@torch.jit.export
def update(self):
"""Update parameter."""
self.step += 1
class Constant(ParameterDecay):
"""Constant parameter."""
def forward(self):
"""See `ParameterDecay.__call__'."""
return self.start
class Learnable(ParameterDecay):
"""Learnable parameter."""
positive: bool
def __init__(self, val, positive: bool = False):
self.positive = positive
if self.positive:
val = inverse_softplus(val).item()
super().__init__(val)
self.start.requires_grad = True
self.positive = positive
def forward(self):
"""See `ParameterDecay.__call__'."""
if self.positive:
return torch.nn.functional.softplus(self.start) + 1e-4
else:
return self.start
class ExponentialDecay(ParameterDecay):
"""Exponential decay of parameter."""
def forward(self):
"""See `ParameterDecay.__call__'."""
decay = torch.exp(-torch.tensor(1.0 * self.step) / self.decay)
return self.end + (self.start - self.end) * decay
class PolynomialDecay(ParameterDecay):
"""Polynomial Decay of a parameter.
It returns the minimum between start and end / step ** decay.
"""
def forward(self):
"""See `ParameterDecay.__call__'."""
return min(self.start, self.end / torch.tensor(self.step + 1.0) ** self.decay)
class LinearDecay(ParameterDecay):
"""Linear decay of parameter."""
def forward(self):
"""See `ParameterDecay.__call__'."""
return max(self.end, self.start - self.decay * self.step)
class LinearGrowth(ParameterDecay):
"""Linear decay of parameter."""
def forward(self):
"""See `ParameterDecay.__call__'."""
return min(self.end, self.start + self.decay * self.step)
class OUNoise(ParameterDecay):
"""Ornstein-Uhlenbeck Noise process.
Parameters
----------
mean: Tensor
Mean of OU process.
std_deviation: Tensor
Standard Deviation of OU Process.
theta: float
Parameter of OU Process.
dt: float
Time discretization.
dim: Tuple
Dimensions of noise.
References
----------
https://www.wikipedia.org/wiki/Ornstein-Uhlenbeck_process.
"""
def __init__(self, mean=0, std_deviation=0.2, theta=0.15, dt=1e-2, dim=(1,)):
if not isinstance(mean, torch.Tensor):
mean = mean * torch.ones(dim)
self.mean = mean
if not isinstance(std_deviation, torch.Tensor):
std_deviation = std_deviation * torch.ones(dim)
self.std_dev = std_deviation
self.theta = theta
self.dt = dt
super().__init__(start=torch.zeros_like(mean))
def forward(self):
"""Compute Ornstein-Uhlenbeck sample."""
x_prev = self.start.data
x = (
x_prev
+ self.theta * (self.mean - x_prev) * self.dt
+ self.std_dev
* torch.sqrt(torch.tensor(self.dt))
* torch.randn(self.mean.shape)
)
self.start.data = x
return x
| [
"shi.tzahi@gmail.com"
] | shi.tzahi@gmail.com |
8e1f9eeaa8eb59e4b8fd5822047b9e320adc32db | e2c120b55ab149557679e554c1b0c55126e70593 | /python/imagej/tests/test_ImgLib2_ImgFactory.py | 6b95c5b2582e670492dc615ed54d7090c3ee9152 | [] | no_license | acardona/scripts | 30e4ca2ac87b9463e594beaecd6da74a791f2c22 | 72a18b70f9a25619b2dbf33699a7dc1421ad22c6 | refs/heads/master | 2023-07-27T14:07:37.457914 | 2023-07-07T23:13:40 | 2023-07-07T23:14:00 | 120,363,431 | 4 | 5 | null | 2023-05-02T11:20:49 | 2018-02-05T21:21:13 | Python | UTF-8 | Python | false | false | 859 | py | from net.imglib2.img.array import ArrayImgFactory
from net.imglib2.type.numeric.integer import UnsignedByteType, UnsignedShortType
from net.imglib2.util import Intervals
# An 8-bit 256x256x256 volume
img = ArrayImgFactory(UnsignedByteType()).create([256, 256, 256])
# Another image of the same type and dimensions, but empty
img2 = img.factory().create([img.dimension(d) for d in xrange(img.numDimensions())])
# Same, but easier reading of the image dimensions
img3 = img.factory().create(Intervals.dimensionsAsLongArray(img))
# Same, but use an existing img as an Interval from which to read out the dimensions
img4 = img.factory().create(img)
# Now we change the type: same kind of image and same dimensions,
# but crucially a different pixel type (16-bit) via a new ImgFactory
imgShorts = img.factory().imgFactory(UnsignedShortType()).create(img)
| [
"sapristi@gmail.com"
] | sapristi@gmail.com |
f857a30e34a36932d528eae3936d5d238e918cb7 | 609e9edc94eb26d4c88debaca9d003709f46a1b8 | /make_model_dataset_statistics.py | c7c2f5e31ee0eef76e3002243c15afd144849b29 | [] | no_license | tanya525625/CollaborativeFiltering | bb05a16c934f09b512b47a7587dda464129a5960 | 302696b06a7dcb958c7a22dc9a228bbfe7e46d25 | refs/heads/master | 2022-12-18T07:45:36.746484 | 2020-09-25T06:51:02 | 2020-09-25T06:51:02 | 283,509,838 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,325 | py | import os
import json
from collections import OrderedDict
import numpy as np
import pandas as pd
def write_dict(data, filepath):
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
def sort_dict(data):
stats = OrderedDict(sorted(data.items(), key=lambda x: x[1]['count'], reverse=True))
for position in data.keys():
stats[position]["skills_stats"] = OrderedDict(sorted(data[position]["skills_stats"].items(),
key=lambda x: x[1], reverse=True))
return stats
def make_statistics(items):
unique_items = set(items)
items_count = [items.count(item) for item in unique_items]
statistics = dict(zip(unique_items, items_count))
sorted_statistics = dict(sorted(statistics.items(), reverse=True, key=lambda kv: kv[1]))
sorted_statistics.update({"unique_items_count": len(unique_items)})
sorted_statistics.update({"all_count": sum(items_count)})
return sorted_statistics
def save_files(df_seria, filepath):
res = []
res.clear()
for lst in df_seria:
lst = lst.replace('[', '').replace(']', '').replace('\'', '').split(',')
for i, el in enumerate(lst):
if el:
if el[0] == ' ':
lst[i] = el[1:]
res.extend(lst)
np.save(filepath, res)
def main():
data_dir = "data"
st_path = os.path.join(data_dir, "model_dataset_statistics")
is_save = False
input_path = os.path.join(data_dir, "filtered_dataset.csv")
if is_save:
df = pd.read_csv(input_path)
save_files(df['Position'].tolist(), os.path.join(data_dir, "all_labels.npy"))
save_files(df['Skills'].tolist(), os.path.join(data_dir, "all_items.npy"))
else:
labels = np.load(os.path.join(data_dir, "all_labels.npy"), allow_pickle=True).tolist()
items = np.load(os.path.join(data_dir, "all_items.npy"), allow_pickle=True).tolist()
if '' in labels:
labels.remove('')
items_st = make_statistics(items)
write_dict(items_st, os.path.join(st_path, "skills_statistics.json"))
labels_st = make_statistics(labels)
write_dict(labels_st, os.path.join(st_path, "labels_statistics.json"))
if __name__ == "__main__":
main() | [
"33422677+tanya525625@users.noreply.github.com"
] | 33422677+tanya525625@users.noreply.github.com |
85cdcc5d57482e29a337ba0119ef69327966665e | 985e54f1ecfd6d24a526be94969ff1cf27866d9b | /Util/srt_sanitizer.py | 795999adf439fc039b8264aaa1457a7275180c58 | [] | no_license | nehemiah-io/MS-Twitter-Bot | c3ee79cc362b6e72e73d3217f24f5922207899d4 | c2e2ce2c07d5428711f9996bfce8a4f848458bde | refs/heads/master | 2021-01-12T08:12:51.253101 | 2016-12-12T23:42:10 | 2016-12-12T23:42:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 836 | py | # -*- coding: utf-8 -*-
import pysrt
import re
def open_doc(source_text):
try:
subs = pysrt.open(source_text)
return subs
except UnicodeDecodeError:
subs = pysrt.open(source_text, encoding='iso-8859-1')
return subs
def sanitize(subs):
sanitized = ""
for sub in subs:
sanitized += sub.text + "\n"
return sanitized
def concatinate_string_to_file(str, file):
corpus = open(file, "a")
corpus.write(str)
def tokenize_and_clean_subs(sanitized_subs):
p = "(?:'([\wÀ-ÿ]+[\'\-]?[\wÀ-ÿ]*)'|((?:[\wÀ-ÿ]+[\'\-]?[\wÀ-ÿ]*[\'\-]?"\
")+)|((?:'?[\wÀ-ÿ]+[\'\-]?[\wÀ-ÿ]*)+))"
pattern = re.compile(p)
return pattern.findall(sanitized_subs)
subs = open_doc("Reservoir Dogs.srt")
sanitized_subs = sanitize(subs)
print(clean_subs(sanitized_subs))
| [
"fabiobean2@gmail.com"
] | fabiobean2@gmail.com |
93dba4d2be7a704301cbec05785594d801b8cd1a | ed74b7cd3572d759c6430ea55f008e91abe57f2d | /MagAOX/webapp/FilterCurves/filter_curves.py | af6916783375e081a884ff3ff4be337c724ca0a2 | [] | no_license | adelfranco/Follette-group | 8704e1b528d1c4d7110c0382472bd061ce565bf4 | a69858ddac398686e85f7869cdd8f2cc25c50b66 | refs/heads/master | 2023-08-04T09:57:14.279721 | 2021-06-19T01:37:51 | 2021-06-19T01:37:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,538 | py | import numpy as np, pandas as pd, matplotlib.pyplot as plt
plt.rcdefaults()
iprime = pd.read_fwf('VisAO_ip_filter_curve.dat', sep=" ", skiprows = 4)
zprime = pd.read_fwf('VisAO_zp_filter_curve.dat', sep=" ", skiprows = 4)
Ys = pd.read_fwf('VisAO_Ys_filter_curve.dat', sep=" ", skiprows = 4)
curves = [iprime,zprime,Ys]
for x in curves:
temporary_split = x['RSR RSR+atm'].str.split(expand=True,)
x['RSR'] = temporary_split[0]
x['RSR+atm'] = temporary_split[1]
#iprime = iprime.drop(['#'], axis=1)
#iprime = pd.to_numeric(iprime)
x['RSR'] = pd.to_numeric(x['RSR'])
#plt.plot(iprime['lambda'], iprime['RSR+atm'])
plt.plot(iprime['lambda'], iprime['trans'], label='i\' trans')
plt.plot(iprime['lambda'], iprime['RSR'], label='i\' RSR')
#plt.plot(iprime['lambda'], iprime['RSR+atm'], label='i\' RSR+atm')
plt.plot(zprime['lambda'], zprime['trans'], label='z\' trans')
plt.plot(zprime['lambda'], zprime['RSR'], label='z\' RSR')
#plt.plot(zprime['lambda'], zprime['RSR+atm'], label='z\' RSR+atm')
plt.plot(Ys['lambda'], Ys['trans'], label='YS trans')
plt.plot(Ys['lambda'], Ys['trans'], label='YS RSR')
#plt.plot(Ys['lambda'], Ys['trans'], label='YS RSR+atm')
plt.legend()
plt.show()
#x = np.fromfile("VisAO_ip_filter_curve.dat",dtype=dt)
#x = iprime = pd.read_fwf(‘VisAO_ip_filter_curve.dat’, sep=“\s+“, skiprows = 4)
#temporary_split = iprime['RSR RSR+atm'].str.split(expand=True,)
#iprime['RSR'] = temporary_split[0]
#iprime['RSR+atm'] = temporary_split[1]
#iprime['RSR'] = pd.to_numeric(iprime['RSR'])
| [
"noreply@github.com"
] | adelfranco.noreply@github.com |
1c418dc838580160d0af1fed8bba5b0a0e48b79c | e0ab376b815785ed83dcf696b2fb28c742f546ba | /reversestr.py | 95a87c14a0283cee90060daa1cb01c5eb188da42 | [] | no_license | jackyk/andelabs-bootcamp | 7838d26b08e31064521ec11044bbfc551ae5479d | b2e0405e20e4369683b456c7c39e162a9aec8283 | refs/heads/master | 2016-09-13T23:18:47.276439 | 2016-04-29T13:21:25 | 2016-04-29T13:21:25 | 57,385,181 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 227 | py | def reverse_string(string):
if string == '':
return "None"
else:
return string[::-1]
if string == string[::-1]:
return True
else:
return string[::-1]
print reverse_string("ee")
| [
"jackykimani13@gmail.com"
] | jackykimani13@gmail.com |
d0d3f0a3b66c4166ee6189c92371574c40ff103d | f3c0fb0ed19f652cf09e8814cc61051176197bd6 | /mysite/settings.py | 6223da14695ba868185223610217eec5fc5d0b36 | [] | no_license | fanssite/Learning-Djangoweb-Note | a81ec9c3a108f069fab1ca7f49a8d190051f380b | a591cba6f54846c0e4f2913bebae0ca7b3b57b83 | refs/heads/master | 2020-03-17T05:56:12.986883 | 2018-06-01T10:16:06 | 2018-06-01T10:16:06 | 133,334,208 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,468 | py | """
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'q^q%+qad1cf3&3f!vrg*be@a96kes0q^)5ol7edips(!8$#6%+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'account',
'article'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates'),],#[],#
'APP_DIRS': False,#False, 表示不允许按Django按默认方式寻找模板
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'zh-hans'#'en-us'
TIME_ZONE = 'Asia/Shanghai'#'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'#该配置使得浏览器可以直接通过port:/static/xx.jpg来访问xx图片
#制定静态文件目录
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
LOGIN_REDIRECT_URL= '/home/'
| [
"fkg8761060@qq.com"
] | fkg8761060@qq.com |
1154f213a7433278bb5b4257ace83fb3c330bdab | 22a4f85f17242e4b17f4fedd56bc5da97c823d48 | /s1617wechat/s1617wechat/urls.py | 8321a4fcaaacbd7afb562ae51bdf0f0e87810297 | [] | no_license | Three-Ratel/pro17_ | 11d6cfc134f255ba64ff39d212f18d867d893f4b | 6598bddc76268b6dd4d972af6184655c764dd812 | refs/heads/master | 2022-09-13T15:19:17.701443 | 2017-11-17T02:48:44 | 2017-11-17T02:48:44 | 268,671,924 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 878 | py | """s1617wechat URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/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 views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^login.html$', views.login),
url(r'^check_login.html$', views.login),
]
| [
"wuxp@imsa.org.cn"
] | wuxp@imsa.org.cn |
89e2d90ba4eedda9c8b3ce40056dde57e0048c0c | e60487a8f5aad5aab16e671dcd00f0e64379961b | /python_stack/Algos/leetcode_30days/max_subarray.py | 05464124d8c978cb2d1c61f8ef20653a3b199cf1 | [] | no_license | reenadangi/python | 4fde31737e5745bc5650d015e3fa4354ce9e87a9 | 568221ba417dda3be7f2ef1d2f393a7dea6ccb74 | refs/heads/master | 2021-08-18T08:25:40.774877 | 2021-03-27T22:20:17 | 2021-03-27T22:20:17 | 247,536,946 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,473 | py | # Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
# Example:
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
def findMaxIndex(nums):
maxIndex=0
for i in range(1,len(nums)):
if nums[maxIndex] < nums[i]:
maxIndex=i
return maxIndex
def maxCrossingSum(nums, l, m, h) :
# Include elements on left of mid.
sm = 0; left_sum = -10000
for i in range(m, l-1, -1) :
sm = sm + nums[i]
if (sm > left_sum) :
left_sum = sm
# Include elements on right of mid
sm = 0; right_sum = -1000
for i in range(m + 1, h + 1) :
sm = sm + nums[i]
if (sm > right_sum) :
right_sum = sm
# Return sum of elements on left and right of mid
return left_sum + right_sum;
def max_subArray_divide(nums,lowest,highest):
if lowest==highest:
return nums[lowest]
# Find Middle point
mid=(lowest+highest)//2
print(mid)
left_sum= max_subArray_divide(nums,lowest,mid)
right_sum= max_subArray_divide(nums,mid+1,highest)
cross_sum=maxCrossingSum(nums, lowest, mid, highest)
print(left_sum,right_sum,cross_sum)
return max(left_sum,right_sum,cross_sum)
def max_subArray(nums):
# divide and conqure
return max_subArray_divide(nums,0,len(nums)-1)
print(max_subArray([-2,1,-3,4,-1,2,1,-5,4])) | [
"reena.dangi@gmail.com"
] | reena.dangi@gmail.com |
b2a7b8d0a433202a5473dd0f9b466bce8de76849 | 9e2b2834e60fa24a424443129c63f1c81c01292f | /naive_bayes/nb_author_id.py | 74224d5044ea2ae7f3592e624cf5f32b851a92c9 | [] | no_license | sourabhgupta385/udacity-machine-learning | 26e8690a6ff70b566f2d666fbc5e8af40518dbe3 | 4f74f318afc31d3e0b959e376a1e827c36861302 | refs/heads/master | 2020-04-25T10:45:51.051573 | 2019-05-17T14:05:48 | 2019-05-17T14:05:48 | 172,720,734 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,119 | py | #!/usr/bin/python
"""
This is the code to accompany the Lesson 1 (Naive Bayes) mini-project.
Use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
#########################################################
### your code goes here ###
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
clf = GaussianNB()
t0 = time()
clf.fit(features_train, labels_train)
print "Training time: ", round(time()-t0, 3), "s"
t0 = time()
pred = clf.predict(features_test)
print "Prediction time: ", round(time()-t0, 3), "s"
print "Accuracy Score: ", accuracy_score(labels_test, pred)
#########################################################
| [
"root@bastion.121c.example.opentlc.com"
] | root@bastion.121c.example.opentlc.com |
9005824b15f37cce95df1b5a713379a40a63d616 | 1abb17c54ecea9cac1f23e7a8131315bf872a46d | /online_exam/online_test/classroom/migrations/0007_auto_20200929_2210.py | a4b52caec9319628c8ecc7b804799039b3ee40b0 | [] | no_license | papry/online_exam_plateform | 1a66cd7619ef4b126118d46e6a3661d25f341a8e | 919b70bf65e3a3bdd6ae47f5c79cf82f3ff118bc | refs/heads/master | 2022-12-29T06:29:37.897730 | 2020-10-18T15:12:03 | 2020-10-18T15:12:03 | 287,947,503 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 912 | py | # Generated by Django 2.0 on 2020-09-29 16:10
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('classroom', '0006_auto_20200909_2309'),
]
operations = [
migrations.CreateModel(
name='See',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('score', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='classroom.TakenQuiz')),
('subject', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='classroom.Subject')),
],
),
migrations.AlterField(
model_name='user',
name='first_name',
field=models.CharField(blank=True, max_length=30, verbose_name='first name'),
),
]
| [
"papry261@gmail.com"
] | papry261@gmail.com |
49cc71107ea54658f08a3dcfd3bad371b83f047a | 19d1cc838f86fa428a3c29293a7631cd99513578 | /venv/bin/easy_install | b8cdb524a293d778423a07e6c1ee15fd4071ab32 | [] | no_license | tidjumaev/python-pi-example | 2bc3d27480ba897f0f41ba2cca60107a555325b7 | 0704e21c4719ebdafa3fbd77506bf613b13d254d | refs/heads/master | 2021-03-24T08:42:45.067399 | 2020-04-04T16:35:07 | 2020-04-04T16:35:07 | 247,535,046 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 434 | #!/home/timur/PycharmProjects/pi/venv/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install')()
)
| [
"ti.djumaev@gmail.com"
] | ti.djumaev@gmail.com | |
aeaaaacc2ff4c496bb86857ae6184a615cc011f0 | 75a227e47124f76278f9e045353385edfc83de33 | /238.py | 040a26a190a0bed82e298e2a7c5710a558fb0acb | [] | no_license | ahujasushant/leetcode_problems | bbfae8757d8762dee5a889609bd9cd232455e659 | 9fc7ddcb59ee8be524fbc253bc973cf6f1eafe0f | refs/heads/master | 2023-03-28T16:49:20.097943 | 2021-04-03T17:41:54 | 2021-04-03T17:41:54 | 219,437,109 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 500 | py | class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
prod_right = [1] * len(nums)
prod_left = [1] * len(nums)
product_nums = []
for i in range(len(nums) - 1):
prod_left[i + 1] *= prod_left[i] * nums[i]
for i in range(len(nums) - 1, 0, -1):
prod_right[i - 1] *= prod_right[i] * nums[i]
for i in range(len(nums)):
product_nums.append(prod_left[i] * prod_right[i])
return product_nums | [
"sushantahuja35@gmail.com"
] | sushantahuja35@gmail.com |
8c4d47286298016368282b45a4cb4e2dc67954f7 | f27c49458bde84048e6008da8c52ca0f1ae711ce | /code/07-data-structures/simple_dict/playground.py | b8e36ebaf6c98c36c3e8c2912fe99193322d5f38 | [
"MIT"
] | permissive | talkpython/python-for-absolute-beginners-course | 54b0f48b5edbf7755de6ca688a8e737ba16dc2fc | 1930dab0a91526863dc92c3e05fe3c7ec63480e1 | refs/heads/master | 2022-11-24T03:02:32.759177 | 2022-11-08T14:30:08 | 2022-11-08T14:30:08 | 225,979,578 | 2,287 | 1,059 | MIT | 2022-11-07T19:45:15 | 2019-12-05T00:02:31 | Python | UTF-8 | Python | false | false | 547 | py | # Data structures
# 1. Dictionaries
# 2. Lists / arrays [1,1,7,11]
# 3. Sets
# Lists
lst = [1, 1, 11, 7]
print(lst)
lst.append(2)
print(lst)
lst.remove(11)
print(lst)
lst.sort()
print(lst)
# Sets:
st = {1, 1, 11, 7}
st.add(1)
st.add(1)
st.add(11)
print(st)
# Dictionaries
d = {
'bob': 0,
'sarah': 0,
'defeated_by': {'paper', 'wolf'},
'defeats': {'scissors', 'sponge'}
}
print(d['bob'])
d['bob'] += 1
print(d['bob'])
print(d)
d['michael'] = 7
print(d)
print(f"You are defeated by {d['defeated_by']}")
print(d.get('other', 42))
| [
"mikeckennedy@gmail.com"
] | mikeckennedy@gmail.com |
8dc61e64bb66988a363127243cb1b02813e86140 | a6a78f59f442c18449befc89be2b193e37b695d6 | /ivi/rigol/rigolDP800.py | fd988186043295e67c8db82281a56f6215da0aef | [
"MIT"
] | permissive | hohe/python-ivi | fa0b4b1232f4fca92bd046d2ae322e49959f8a83 | 0fe6d7d5aaf9ebc97085f73e25b0f3051ba996b6 | refs/heads/master | 2021-01-21T08:55:35.470107 | 2013-12-23T09:27:02 | 2013-12-23T09:27:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,380 | py | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from .. import ivi
from .. import dcpwr
from .. import scpi
TrackingType = set(['floating'])
TriggerSourceMapping = {
'immediate': 'imm',
'bus': 'bus'}
class rigolDP800(scpi.dcpwr.Base, scpi.dcpwr.Trigger, scpi.dcpwr.SoftwareTrigger,
scpi.dcpwr.Measurement):
"Rigol DP800 series IVI DC power supply driver"
def __init__(self, *args, **kwargs):
super(rigolDP800, self).__init__(*args, **kwargs)
self._instrument_id = 'Rigol Technologies,DP800'
self._output_count = 3
self._output_range = [[(8.0, 5.0)], [(30.0, 2.0)], [(-30.0, 2.0)]]
self._output_range_name = [['P8V'], ['P30V'], ['N30V']]
self._output_ovp_max = [8.8, 33.0, -33.0]
self._output_ocp_max = [5.5, 2.2, 2.2]
self._output_voltage_max = [8.0, 30.0, -30.0]
self._output_current_max = [5.0, 2.0, 2.0]
self._memory_size = 10
self._identity_description = "Rigol DP800 series DC power supply driver"
self._identity_identifier = ""
self._identity_revision = ""
self._identity_vendor = ""
self._identity_instrument_manufacturer = "Rigol Technologies"
self._identity_instrument_model = ""
self._identity_instrument_firmware_revision = ""
self._identity_specification_major_version = 3
self._identity_specification_minor_version = 0
self._identity_supported_instrument_models = ['DP831A', 'DP832', 'DP832A']
ivi.add_method(self, 'memory.save',
self._memory_save)
ivi.add_method(self, 'memory.recall',
self._memory_recall)
self._init_outputs()
def _memory_save(self, index):
index = int(index)
if index < 1 or index > self._memory_size:
raise OutOfRangeException()
if not self._driver_operation_simulate:
self._write("*sav %d" % index)
def _memory_recall(self, index):
index = int(index)
if index < 1 or index > self._memory_size:
raise OutOfRangeException()
if not self._driver_operation_simulate:
self._write("*rcl %d" % index)
| [
"alex@alexforencich.com"
] | alex@alexforencich.com |
ae27891e13ca1eaadd6120af23e1c56283342d8a | 6faadbb3dd4caed5dce833547758c9ba458de59f | /to_do/to_do/urls.py | 6bfd3fd0d3561a1eac3d9447ff4a11c8f1e6e930 | [] | no_license | rayhanhossen/To-Do-App | 403644831f498ea1b9d6a7c67969cea517b49daf | 4173f3576bc343eba534f67d02eb6fa0bf2d23fb | refs/heads/master | 2023-05-31T11:55:20.517277 | 2021-06-30T12:00:43 | 2021-06-30T12:00:43 | 256,956,750 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 792 | py | """to_do URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('tasks.urls'))
]
| [
"rayhanhossen.cse@gmail.com"
] | rayhanhossen.cse@gmail.com |
9035282cddc1d2da4f1b4762c92128446c2cb8ad | 7ba0fca9f0da684795db54661ca6f296c60a9c56 | /my_blog/settings.py | eef72df56ea0c21ba665bce4c8c613642237b5c9 | [] | no_license | nafei/my-pydjango-blog | f3547323ef561fdb26837886b0e952439c45733e | 3f1eec9866933289deb0aeb2e0b55b3a1d24349c | refs/heads/master | 2021-01-14T10:58:43.282099 | 2015-06-29T09:46:04 | 2015-06-29T09:46:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,464 | py | """
Django settings for my_blog project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'f#lawqt8m4@u@yv4ukve18y4d76rmt@58=v-jzn=gu3no(lv^3'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
'article',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'my_blog.urls'
WSGI_APPLICATION = 'my_blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = (
os.path.join(BASE_DIR, 'article/static/')
)
CKEDITOR_CONFIGS = {
'default': {
'toolbar': (
['div','Source','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print','SpellChecker','Scayt'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
['Form','Checkbox','Radio','TextField','Textarea','Select','Button', 'ImageButton','HiddenField'],
['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
['Link','Unlink','Anchor'],
['Image','Flash','CodeSnippet','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
['Styles','Format','Font','FontSize'],
['TextColor','BGColor'],
['Maximize','ShowBlocks','-','About', 'pbckcode'],
),
"extraPlugins": "codesnippet",
"codeSnippet_languages": {
"c":"c",
"cpp":"cpp",
"bash":"bash",
"python": "python"
},
"codeSnippet_theme": "monokai_sublime",
}
}
CKEDITOR_UPLOAD_PATH = "article/static/uploads/"
CKEDITOR_IMAGE_BACKEND = "pillow"
PRE_PAGE_NUM = 5
| [
"553069938@qq.com"
] | 553069938@qq.com |
7c405d090f0ab23b553f950534fcd3435141562f | c320550947a5fa77da721abda5d948f2ec408de9 | /shs_work_lang.py | d3063fdeda0fc5412b67697681dd35a9acb969aa | [] | no_license | weisslj/musicbrainz-bot | e8abf2f69aba2519693ee7f725b1d4800a0dd891 | b49c6beab9796785e7fe0faed9fa58612ce87e73 | refs/heads/master | 2021-01-20T21:45:08.798347 | 2014-05-06T21:25:51 | 2014-05-06T21:25:51 | 2,906,055 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,030 | py | #!/usr/bin/python
import re
import sqlalchemy
import solr
from editing import MusicBrainzClient
from mbbot.source.secondhandsongs import SHSWebService
import pprint
import urllib
import time
from utils import mangle_name, join_names, out, colored_out, bcolors
import config as cfg
engine = sqlalchemy.create_engine(cfg.MB_DB)
db = engine.connect()
db.execute("SET search_path TO musicbrainz, %s" % cfg.BOT_SCHEMA_DB)
mb = MusicBrainzClient(cfg.MB_USERNAME, cfg.MB_PASSWORD, cfg.MB_SITE)
shs = SHSWebService()
"""
CREATE TABLE bot_shs_work_lang (
work uuid NOT NULL,
processed timestamp with time zone DEFAULT now(),
CONSTRAINT bot_shs_work_lang_pkey PRIMARY KEY (work)
);
"""
query = """
WITH
works_wo_lang AS (
SELECT w.id AS work_id, u.url AS shs_url
FROM work w
JOIN l_url_work l ON l.entity1 = w.id AND l.link IN (SELECT id FROM link WHERE link_type = 280)
JOIN url u ON u.id = l.entity0
WHERE language IS NULL AND url NOT LIKE '%%/performance/%%'
/* Work should have a lyricist relation to be sure it's not an instrumental */
AND EXISTS (SELECT 1 FROM l_artist_work WHERE l_artist_work.entity1 = w.id AND l_artist_work.link IN (SELECT id FROM link WHERE link_type = 165))
/* SHS link should only be linked to this work */
AND NOT EXISTS (SELECT 1 FROM l_url_work WHERE l_url_work.entity0 = u.id AND l_url_work.entity1 <> w.id)
/* this work should not have another SHS link attached */
AND NOT EXISTS (SELECT 1 FROM l_url_work WHERE l_url_work.entity1 = w.id AND l_url_work.entity0 <> u.id
AND l_url_work.link IN (SELECT id FROM link WHERE link_type = 280))
AND l.edits_pending = 0
)
SELECT w.id, w.gid, w.name, w.language, wwol.shs_url, b.processed
FROM works_wo_lang wwol
JOIN work w ON wwol.work_id = w.id
LEFT JOIN bot_shs_work_lang b ON w.gid = b.work
ORDER BY b.processed NULLS FIRST, w.id
LIMIT 500
"""
iswcs_query = """
SELECT iswc from iswc
WHERE work = %s
ORDER BY iswc
"""
# select '"'||name ||'": ' || id || ',' from language where frequency = 2 order by id;
SHS_MB_LANG_MAPPING = {
"Arabic": 18,
"Chinese": 76,
"Czech": 98,
"Danish": 100,
"Dutch": 113,
"English": 120,
"Finnish": 131,
"French": 134,
"German": 145,
"Greek": 159,
"Italian": 195,
"Japanese": 198,
"[Multiple languages]": 284,
"Norwegian": 309,
"Polish": 338,
"Portuguese": 340,
"Russian": 353,
"Spanish": 393,
"Swedish": 403,
"Turkish": 433,
}
for work in db.execute(query):
colored_out(bcolors.OKBLUE, 'Looking up work "%s" http://musicbrainz.org/work/%s' % (work['name'], work['gid']))
m = re.match(r'http://www.secondhandsongs.com/work/([0-9]+)', work['shs_url'])
if m:
shs_work = shs.lookup_work(int(m.group(1)))
else:
continue
if 'language' in shs_work:
work = dict(work)
shs_lang = shs_work['language']
if shs_lang not in SHS_MB_LANG_MAPPING:
colored_out(bcolors.FAIL, ' * No mapping defined for language ''%s' % shs_lang)
else:
work['iswcs'] = []
for (iswc,) in db.execute(iswcs_query, work['id']):
work['iswcs'].append(iswc)
work['language'] = SHS_MB_LANG_MAPPING[shs_lang]
update = ('language',)
colored_out(bcolors.HEADER, ' * using %s, found language: %s' % (work['shs_url'], shs_lang))
edit_note = 'Setting work language from attached SecondHandSongs link (%s)' % work['shs_url']
out(' * edit note: %s' % (edit_note,))
mb.edit_work(work, update, edit_note)
else:
colored_out(bcolors.NONE, ' * using %s, no language has been found' % (work['shs_url'],))
if work['processed'] is None:
db.execute("INSERT INTO bot_shs_work_lang (work) VALUES (%s)", (work['gid'],))
else:
db.execute("UPDATE bot_shs_work_lang SET processed = now() WHERE work = %s", (work['gid'],))
| [
"aurelien.mino@gmail.com"
] | aurelien.mino@gmail.com |
5029921c8820ea49c76db8a0445082a1dfa941e2 | 5e3e2a7e66d0698d52960dfcb4fef903d2468af1 | /WebModule/homeworkweb6/river/mlab2.py | b7eb70bb138bbcac2da03a66c4f644c71299f66e | [] | no_license | FriendlyVietnamese/PhoHoangVietLinh-Fundamental-C4E19 | c91b48bd35b7bdd239d44cbfee47ea12710a62b5 | e65f96cfc3c8925c4a02a9a197751441940fe2fc | refs/heads/master | 2020-03-21T20:45:57.454468 | 2018-08-24T15:48:03 | 2018-08-24T15:48:03 | 139,026,714 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 435 | py | import mongoengine
# mongodb://admin:admin@ds021182.mlab.com:/
host = "ds021182.mlab.com"
port = 21182
db_name = "c4e"
user_name = "admin"
password = "admin"
def connect():
mongoengine.connect(db_name, host=host, port=port, username=user_name, password=password)
def list2json(l):
import json
return [json.loads(item.to_json()) for item in l]
def item2json(item):
import json
return json.loads(item.to_json()) | [
"Viet Linh"
] | Viet Linh |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.