blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
a6e3f9ad5215ff8793eca41e06d25c666424ff69
18567c0f5d32d220939bf249c53d046b43aa5acb
/crypto_test/check_user_password.py
21de9f1f3435dce019b373e2e6f94f311f0eda74
[]
no_license
MARConthemove/covid-test-web-site
aaf618227da0ffc920ee57ccd42f3c6d1cc63589
e926368a3563d8b43fb8a3a207770d0e8e0e6dab
refs/heads/master
2022-12-29T10:14:51.574318
2020-10-05T18:10:53
2020-10-05T18:10:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,016
py
#!/usr/bin/python3 # Let's assume a user has entered this data on the result query web form form_data = { "barcode": "ABCDEF", "password": "ErikasPW" } # Here is how to check whether the password is valid import binascii, hashlib hashes_found = set() with open( "test.csv" ) as f: for line in f: barcode, timestamp, password_hash, remainder = line.split( ",", 3 ) if barcode == form_data["barcode"].upper(): hashes_found.add( password_hash ) if len( hashes_found ) == 0: print( "Barcode not found.") elif len( hashes_found ) > 1: print( "Barcode has been found several times, with different passwords. Please contact the admins." ) else: assert len( hashes_found ) == 1 sha_instance = hashlib.sha3_384() sha_instance.update( form_data["password"].encode( "utf-8" ) ) encoded_hash_from_form = binascii.b2a_base64( sha_instance.digest(), newline=False ) if encoded_hash_from_form == list(hashes_found)[0].encode( "ascii" ): print( "Password correct." ) else: print( "Password wrong." )
[ "sanders@fs.tum.de" ]
sanders@fs.tum.de
d04d6b9893f5f78f3475521db16a4084f2eb7651
1ddacfc9d8e1096799d3e29d03f48a11b0d9b1cc
/compare_directories.py
806bfc49e967309193ef0b0e4eed850e9903c354
[]
no_license
fladd/CompareDirectories
275dece69ce8e1063bf49d9f77629ec5dda6af2e
f65a4f2b25de11135e358b098703c41e5cd1b22c
refs/heads/master
2021-01-01T03:59:29.730206
2016-05-04T12:41:31
2016-05-04T12:41:31
57,979,582
0
0
null
null
null
null
UTF-8
Python
false
false
7,754
py
""" Compare Directories. This tool will binary compare all files of a directory recursively to all files of a reference directory. Erroneous (not readable), differing, missing, new and identical files are reported. """ __author__ = "Florian Krause <fladd@fladd.de>" __version__ = "0.1.0" import sys import os import filecmp if sys.version[0] == '3': from tkinter import * from tkinter import ttk from tkinter import scrolledtext from tkinter import filedialog else: from Tkinter import * import ttk import ScrolledText as scrolledtext import tkFileDialog as filedialog class App: def __init__(self): self.reference_dir = "" self.test_dir = "" self.missing = [] self.new = [] self.common = [] self.match = [] self.mismatch = [] self.error = [] def get_files(self, d): all_files = [] for path, subdirs, files in os.walk(d): for name in files: all_files.append(os.path.join(path, name).replace(d, '')) return all_files def compare(self): if not self.reference_dir.endswith(os.path.sep): self.reference_dir += os.path.sep if not self.test_dir.endswith(os.path.sep): self.test_dir += os.path.sep self.reference_files = self.get_files(self.reference_dir) self.test_files = self.get_files(self.test_dir) self.missing = list(set(self.reference_files).difference( set(self.test_files))) self.new = list(set(self.test_files).difference( set(self.reference_files))) self.common = list(set(self.reference_files).intersection( set(self.test_files))) self.match = [] self.mismatch = [] self.error = [] try: self._progress["maximum"] = len(self.common) except: pass for c, f in enumerate(self.common): try: if filecmp.cmp(self.reference_dir + f, self.test_dir + f, shallow=False): self.match.append(f) else: self.mismatch.append(f) except: self.error.append(f) try: self._progress["value"] = c + 1 self._status.set(f) self._root.update() except: pass try: self._status.set("Done") self._show_report() self._reset_gui() except: pass def get_report(self): rtn = "" rtn += "Reference: {0}\nComparing: {1}\n\n".format(self.reference_dir, self.test_dir) for x in self.error: rnt += "[ERROR] {0}\n".format(x) for x in self.mismatch: rtn += "[DIFFERENT] {0}\n".format(x) for x in self.missing: rtn += "[MISSING] {0}\n".format(x) for x in self.new: rtn += "[NEW] {0}\n".format(x) if not self.error == [] and self.mismatch == [] and \ self.missing == [] and self.new == []: rtn += "" for x in self.match: rtn += "[SAME] {0}\n".format(x) return rtn def add_reference(self): self.reference_dir = filedialog.askdirectory(parent=self._root) try: self._reference.set(self.reference_dir) if self._test.get() != "": self._status.set("Ready") self._go.state(["!disabled"]) except: pass def add_test(self): self.test_dir = filedialog.askdirectory(parent=self._root) try: self._test.set(self.test_dir) if self._reference.get() != "": self._status.set("Ready") self._go.state(["!disabled"]) except: pass def _show_gui(self): self._root = Tk() self._root.title("Compare Directories") self._root.resizable(0, 0) if sys.platform.startswith("linux"): s = ttk.Style() s.theme_use("clam") self._reference = StringVar() self._test = StringVar() self._status = StringVar("") self._topframe = ttk.Frame(self._root, padding="5 5 5 5") self._topframe.grid(column=0, row=0, sticky=(N, W, E, S)) self._topframe.columnconfigure(0, weight=1) self._topframe.rowconfigure(0, weight=1) self._bottomframe = ttk.Frame(self._root, padding="5 5 5 5") self._bottomframe.grid(column=0, row=1, sticky=(N, W, E, S)) self._bottomframe.columnconfigure(0, weight=1) self._bottomframe.rowconfigure(0, weight=1) ttk.Label(self._topframe, text="Reference:").grid(column=0, row=0, sticky=(S, W)) self._reference_entry = ttk.Entry(self._topframe, width=50, textvariable=self._reference, state="readonly") self._reference_entry.grid(column=0, row=1, sticky=(N, S, E, W)) ttk.Button(self._topframe, text="Open", command=self.add_reference).grid(column=1, row=1, sticky=(N, S, E, W)) ttk.Label(self._topframe, text="Comparing:").grid(column=0, row=2, sticky=(S, W)) self._test_entry = ttk.Entry(self._topframe, width=50, textvariable=self._test, state="readonly") self._test_entry.grid(column=0, row=3, sticky=(N, S, E, W)) ttk.Button(self._topframe, text="Open", command=self.add_test).grid( column=1, row=3, sticky=(N, S, E, W)) self._go = ttk.Button(self._bottomframe, text="Go", state="disabled", command=self.compare) self._go.grid(column=0, row=0, sticky=(N, S)) self._progress = ttk.Progressbar(self._bottomframe) self._progress.grid(column=0, row=1, sticky=(N, S, E, W)) ttk.Label(self._bottomframe, textvariable=self._status, foreground="darkgrey", width=50, anchor=W).grid(column=0, row=2, sticky=(N, S, E, W)) for child in self._topframe.winfo_children(): child.grid_configure(padx=5, pady=5) for child in self._bottomframe.winfo_children(): child.grid_configure(padx=5, pady=5) self._reset_gui() self._root.mainloop() def _reset_gui(self): self._status.set("Set directories") self._progress["value"] = 0 self._go.state(["disabled"]) self._reference.set("") self._test.set("") def _show_report(self): report = ReportDialogue(self._root, self.get_report()) report.show() class ReportDialogue: def __init__(self, master, message): self.master = master top = self.top = Toplevel(master) top.title("Report") top.transient(master) top.grab_set() top.focus_set() self.text = scrolledtext.ScrolledText(top, width=77) self.text.pack(fill=BOTH, expand=YES) self.text.insert(END, message) self.text["state"] = "disabled" self.text.bind("<1>", lambda event: self.text.focus_set()) b = ttk.Button(top, text="Close", command=self.close) b.pack(pady=10) def show(self): self.master.wait_window(self.top) def close(self): self.top.destroy() if __name__ == "__main__": app = App() app._show_gui()
[ "fladd@web.de" ]
fladd@web.de
ff3754cab9ef652c3ac4d38fae0ec01e44e120e9
c7c7faf8e30e45cd9c74e86f467eff5bc6aab34d
/mulgen.py
2cd03430b30da1f339034fdc5a0981d481e8ff4c
[]
no_license
linaaan/Graduation-design
0cc9329916ad723965511b50689b2805d2e01bfc
0180cc013c38da40ccccac74e4922c0d17192547
refs/heads/main
2023-04-12T04:00:47.917844
2021-05-11T11:53:01
2021-05-11T11:53:01
366,047,406
0
0
null
null
null
null
UTF-8
Python
false
false
419
py
import RandomInitialPoint as RI import GenerationNode as GN import numpy as np def multgr(n, v): # n 是圈数 v是速度 i = 0 x = [] y = [] for i in range(n): x1, y1 = RI.InitialPoint(v) x1, y1 = GN.Generation(x1, y1, v) x = np.append(x, x1) y = np.append(y, y1) return(x, y) # xx, yy = multgr(3, 20) # print(xx) # car = multgr(1, 20) # print('car:', car)
[ "807605729@qq.com" ]
807605729@qq.com
171918eacf53dc68cdf837f4e9b33d81ba426350
a533010ba7e74422c5c7c0193ea2d880e427cb9d
/Python_auto_operation/bin/mlogvis
69b36f81947475e66d1dde10eb0cb5c3e1d112c6
[]
no_license
gateray/learning_python
727b3effe4875f27c86c3e5e66655905f3d5d681
bc08a58f3a5c1f1db884398efa9d27834514199f
refs/heads/master
2021-01-19T06:31:01.616421
2016-06-30T07:39:23
2016-06-30T07:39:23
62,290,273
0
0
null
null
null
null
UTF-8
Python
false
false
345
#!/home/gateray/PycharmProjects/Python_auto_operation/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'mtools==1.1.9','console_scripts','mlogvis' __requires__ = 'mtools==1.1.9' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('mtools==1.1.9', 'console_scripts', 'mlogvis')() )
[ "gateray.example.com" ]
gateray.example.com
8166e51901c32ec077752710fc5398034116a218
8665fe18231acd4dd591391a10215616f861a307
/backend/todo/forms.py
9c425349de6409986124a82b6b101c088bfea330
[]
no_license
MrZhengXin/database_td_lte
40bf74a4714ce16a1d177b870c770f3b72ceb5fb
7c41e4f713fd8347b3b5a72eecb71ab7ada772d9
refs/heads/master
2022-12-12T01:45:52.318358
2020-08-10T08:43:24
2020-08-10T08:43:24
282,181,665
0
1
null
null
null
null
UTF-8
Python
false
false
147
py
from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['file']
[ "510546841@qq.com" ]
510546841@qq.com
61f6dfee794cce2f3c3049caa511c66cc76090fd
6119f01302e1412bb6987266bf49b037d5560d30
/up_load/migrations/0001_initial.py
39feac41ed81c4509a2636739088af12ed6b7016
[]
no_license
wangdiaodiao520/Marketing-data-management
ce3a92b7531f823633a74e95542cc30d694c2619
e1864423229bbe26d1a661ef3db2e6f779a00fb7
refs/heads/master
2023-02-01T10:09:00.158293
2020-12-17T09:26:54
2020-12-17T09:26:54
310,980,322
0
0
null
null
null
null
UTF-8
Python
false
false
1,516
py
# Generated by Django 2.0 on 2020-11-03 17:49 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Channel', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=25)), ('channel_main', models.IntegerField()), ], options={ 'db_table': 'ygj_channel', }, ), migrations.CreateModel( name='Form', fields=[ ('id', models.AutoField(primary_key=True, serialize=False)), ('name', models.CharField(blank=True, max_length=50, null=True)), ('phone', models.BigIntegerField()), ('channel', models.IntegerField()), ('title', models.IntegerField()), ('mark', models.CharField(max_length=100)), ('promoter', models.IntegerField()), ('consult', models.IntegerField(blank=True, null=True)), ('active', models.IntegerField(blank=True, null=True)), ('submit_time', models.DateField()), ('up_time', models.DateField()), ('distribute_time', models.DateField(blank=True, null=True)), ], options={ 'db_table': 'ygj_form', }, ), ]
[ "15075747143@163.com" ]
15075747143@163.com
90fd031fae54e494378fc6f6718d5c9db90f9693
254a8334ec71770310173137e5b57b7daf9e8294
/launchlist/urls.py
9d37ad64892fc68cb6ed9d96c05df81baf841222
[ "MIT" ]
permissive
Mabvuto/LaunchList
15931793d10120c53865fd5e0653013f5677fd62
7018c139e029f87db11e32a2397b186a82950487
refs/heads/master
2021-01-12T22:14:38.023734
2015-04-13T05:02:52
2015-04-13T05:02:52
64,088,903
1
0
null
2016-07-24T22:44:03
2016-07-24T22:44:03
null
UTF-8
Python
false
false
723
py
from django.conf.urls import patterns, include, url from django.contrib import admin from launchlist.views import * urlpatterns = patterns('', # Examples: # url(r'^$', 'launchlist.views.home', name='home'), # url(r'^blog/', include('blog.urls')), # URLs for testing # url(r'^admin/', include(admin.site.urls)), # url(r'^testTemplate/$', view_testTemplate), # URLs for the actual user-facing site url(r'^$', view_intro), url(r'^intro/$', view_intro), url(r'^mission/$', view_mission), url(r'^spacecraft/$', view_spacecraft), url(r'^vehicle/$', view_launchVehicle), url(r'^summary/$', view_summary), url(r'^record/$', recordInput), url(r'^test/$', view_test), )
[ "tachk@rocketeeringetc.net" ]
tachk@rocketeeringetc.net
d0caa854e9e28624cdfc1352f608b8d07a7986a3
6267694634f09f7bb4372e3c335bc805fa1bde6c
/fig_3/prej_prej_8.py
268d0540319d020e5ccb5a0bb016c443ec82ce07
[]
no_license
deep-inder/prejudice_model
3707a9814bbe0fff7b9b885281aaefe3f0778b4a
6a1cd4df38b297d7bd39cfbd760a8f50dccc0e1f
refs/heads/master
2023-06-07T00:00:28.668466
2021-06-27T19:08:53
2021-06-27T19:08:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,388
py
import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) from twoGroups.baseClass import * from twoGroups.biasedAgent import * from twoGroups.unbiasedAgent import * from twoGroups.tftAgent import * from twoGroups.faction import * from twoGroups.antiAgent import * import statistics as s import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt import pickle class CPDModel(): def __init__(self, num_agents, num_factions, broadcasts=False, broadcast_percent=None): self.num_agents = num_agents self.agent_list = [] self.broadcast = broadcasts self.broadcast_percentage = broadcast_percent if broadcast_percent is not None else random.random() self.group_list = [[], []] self.payoff_list = [[], []] self.bias_list = [[],[]] self.faction_list = [] self.facalign_list = [[],[]] self.initial_bias_list = np.random.normal(0.5, 0.2, 1000).tolist() # self.national_median = 117 self.upper_class_track = [] self.anti_agents = [] # Keeping a track of payoff difference self.payoff_diff = [] for i in range(len(self.initial_bias_list)): if (self.initial_bias_list[i] >= 1): self.initial_bias_list[i] = 1 elif (self.initial_bias_list[i] <= 0): self.initial_bias_list[i] = 0 fac_agent_lists = [] for i in range(num_factions): fac_agent_lists.append([]) # Create agents and divide them in factions (Biased, S-TFT) for i in range(0, 800): grp_id = 0 fac_id = int(i / 20) a = BiasedAgent(i, grp_id, self) fac_agent_lists[fac_id].append(a) self.group_list[grp_id].append(a) self.agent_list.append(a) for i in range(800, 1000): grp_id = 1 fac_id = int(i / 20) a = BiasedAgent(i, grp_id, self) fac_agent_lists[fac_id].append(a) self.group_list[grp_id].append(a) self.agent_list.append(a) # Create Factions for i in range(num_factions): f = Faction(i, fac_agent_lists[i]) self.faction_list.append(f) def step(self, step_number): '''Advance the model by one step.''' logging_granularity = 100 # Select two agents from the agent list at random if (self.broadcast): rand = random.random() if (rand>0.60 and rand<0.61): # Perform broadcast Interaction # possible_broadcasting_agents = [] # for a in self.agent_list: # if(a.getSocialStatus() == 3): # possible_broadcasting_agents.append(a) # if(len(possible_broadcasting_agents) == 0): # for a in self.agent_list: # if(a.getSocialStatus() == 2): # possible_broadcasting_agents.append(a) [broadcasting_agent] = random.sample(self.group_list[0], 1) group_id = broadcasting_agent.getGroupId() size = len(self.group_list[group_id]) size = int(size * self.broadcast_percentage) broadcast_group = random.sample(self.group_list[group_id], size) bias = broadcasting_agent.getBias() for i in broadcast_group: i.recieveBroadcast(bias) #Perform normal interaction A, B = random.sample(self.agent_list, 2) coopA = A.getCoop(B) coopB = B.getCoop(A) payoffA = payoffCalc(coopA, coopB) payoffB = payoffCalc(coopB, coopA) self.payoff_diff.append(abs(payoffA - payoffB)) A.update(B, coopB, payoffA, payoffB) B.update(A, coopA, payoffB, payoffA) # Update national median after each interaction # median_update_lst = [] self.upper_class_track = [] for a in self.agent_list: # median_update_lst.append(a.getWealth()) if(a.getSocialStatus() == 3): self.upper_class_track.append(a) # median_index = int(self.num_agents/2) # self.national_median = median_update_lst[median_index] # if (step_number % logging_granularity == 0): # self.payoff_list[0].append(getAveragePayoff(self.group_list[0])) # self.payoff_list[1].append(getAveragePayoff(self.group_list[1])) # self.bias_list[0].append(getAverageBias(self.group_list[0])) # self.bias_list[1].append(getAverageBias(self.group_list[1])) # self.facalign_list[0].append(getAverageAlign(self.group_list[0])) # self.facalign_list[1].append(getAverageAlign(self.group_list[1])) print("Running model for both prejudiced groups in ratio 800:200") model_list = [] for r in range(10): model = CPDModel(1000, 50) for i in tqdm(range(1, 100000)): model.step(i) model_list.append(model) with open('1c/models/prej_prej/800-200.pkl', 'wb') as output: pickle.dump(model_list, output, pickle.HIGHEST_PROTOCOL) print("Model saved as 1c/models/prej_prej/800-200.pkl") print()
[ "mohan.deepinder@qgmail.com" ]
mohan.deepinder@qgmail.com
4661588400a58471995f03dc263819540a3d00a2
fcd6647e9e8861bf05aa678faba4b913074edf3e
/mbed-os/tools/build_travis.py
13a3d6f0c81cae1ba74a0d81b80d6ad54240383b
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ashok-rao/BLEClient_mbedDevConn_Watson
a23386def82d0da5fc8bbbe3fc79cbeb93a37e92
f162ec8a99ab3b21cee28aaed65da60cf5dd6618
refs/heads/master
2020-06-23T07:50:16.852047
2017-07-14T09:10:05
2017-07-14T09:10:05
74,658,976
1
3
NOASSERTION
2020-03-06T23:26:39
2016-11-24T09:40:20
C
UTF-8
Python
false
false
12,313
py
#!/usr/bin/env python2 """ Travis-CI build script mbed SDK Copyright (c) 2011-2013 ARM Limited 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 ################################################################################ # Configure builds here # "libs" can contain "dsp", "rtos", "eth", "usb_host", "usb", "ublox", "fat" build_list = ( { "target": "LPC1768", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "eth", "usb_host", "usb", "ublox", "fat"] }, { "target": "LPC2368", "toolchains": "GCC_ARM", "libs": ["fat"] }, { "target": "LPC2460", "toolchains": "GCC_ARM", "libs": ["rtos", "usb_host", "usb", "fat"] }, { "target": "LPC11U24", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "OC_MBUINO", "toolchains": "GCC_ARM", "libs": ["fat"] }, { "target": "LPC11U24_301", "toolchains": "GCC_ARM", "libs": ["fat"] }, { "target": "B96B_F446VE", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_L053R8", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_L152RE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F030R8", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_F031K6", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_F042K6", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_F070RB", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_F072RB", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F091RC", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F103RB", "toolchains": "GCC_ARM", "libs": ["rtos", "fat"] }, { "target": "NUCLEO_F207ZG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F302R8", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F303K8", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F303RE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F303ZE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F334R8", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F401RE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F410RB", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F411RE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_L432KC", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_L476RG", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_L011K4", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "NUCLEO_L031K6", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "NUCLEO_L073RZ", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_F429ZI", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F446RE", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_F446ZE", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NUCLEO_F746ZG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NUCLEO_F767ZI", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "MOTE_L152RC", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "ELMO_F411RE", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "MTS_MDOT_F405RG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "MTS_MDOT_F411RE", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "MTS_DRAGONFLY_F411RE", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "ARCH_MAX", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "DISCO_F051R8", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "DISCO_F334C8", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "DISCO_F401VC", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "DISCO_F407VG", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "DISCO_F429ZI", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "DISCO_F469NI", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "DISCO_F746NG", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "DISCO_F769NI", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "LPC1114", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "LPC11U35_401", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "UBLOX_C027", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "LPC11U35_501", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "LPC11U68", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "LPC11U37H_401", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "KL05Z", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "KL25Z", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb", "fat"] }, { "target": "KL27Z", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb", "fat"] }, { "target": "KL43Z", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb", "fat"] }, { "target": "KL46Z", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb", "fat"] }, { "target": "K20D50M", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "TEENSY3_1", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "K64F", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb", "fat"] }, { "target": "K22F", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb", "fat"] }, { "target": "LPC4088", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb", "fat"] }, { "target": "ARCH_PRO", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "LPC1549", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NRF51822", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "DELTA_DFCM_NNN40", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "NRF51_DK", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "NRF51_MICROBIT", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "fat"] }, { "target": "EFM32ZG_STK3200", "toolchains": "GCC_ARM", "libs": ["dsp"] }, { "target": "EFM32HG_STK3400", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, { "target": "EFM32LG_STK3600", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, { "target": "EFM32GG_STK3700", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, { "target": "EFM32WG_STK3800", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos", "usb"] }, { "target": "EFM32PG_STK3401", "toolchains": "GCC_ARM", "libs": ["dsp", "rtos"] }, { "target": "MAXWSNENV", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "MAX32600MBED", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "MAX32620HSP", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "RZ_A1H", "toolchains": "GCC_ARM", "libs": ["fat"] }, { "target": "SAMR21G18A", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "SAMD21J18A", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "SAMD21G18A", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, { "target": "SAML21J18A", "toolchains": "GCC_ARM", "libs": ["dsp", "fat"] }, ) ################################################################################ # Configure example test building (linking against external mbed SDK libraries liek fat or rtos) linking_list = [ {"target": "LPC1768", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_15", "MBED_16", "MBED_17"], "eth" : ["NET_1", "NET_2", "NET_3", "NET_4"], "fat" : ["MBED_A12", "MBED_19", "PERF_1", "PERF_2", "PERF_3"], "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } }, {"target": "K64F", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], "fat" : ["MBED_A12", "PERF_1", "PERF_2", "PERF_3"], "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } }, {"target": "K22F", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], "fat" : ["MBED_A12", "PERF_1", "PERF_2", "PERF_3"], "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } }, {"target": "KL43Z", "toolchains": "GCC_ARM", "tests": {"" : ["MBED_2", "MBED_10", "MBED_11", "MBED_16"], "fat" : ["MBED_A12", "PERF_1", "PERF_2", "PERF_3"], "rtos" : ["RTOS_1", "RTOS_2", "RTOS_3"], "usb" : ["USB_1", "USB_2" ,"USB_3"], } } ] ################################################################################ # Driver def run_builds(dry_run): for build in build_list: toolchain_list = build["toolchains"] if type(toolchain_list) != type([]): toolchain_list = [toolchain_list] for toolchain in toolchain_list: cmdline = "python tools/build.py -m %s -t %s -j 4 -c --silent "% (build["target"], toolchain) libs = build.get("libs", []) if libs: cmdline = cmdline + " ".join(["--" + l for l in libs]) print "Executing: " + cmdline if not dry_run: if os.system(cmdline) != 0: sys.exit(1) def run_test_linking(dry_run): """ Function run make.py commands to build and link simple mbed SDK tests against few libraries to make sure there are no simple linking errors. """ for link in linking_list: toolchain_list = link["toolchains"] if type(toolchain_list) != type([]): toolchain_list = [toolchain_list] for toolchain in toolchain_list: tests = link["tests"] # Call make.py for each test group for particular library for test_lib in tests: test_names = tests[test_lib] test_lib_switch = "--" + test_lib if test_lib else "" cmdline = "python tools/make.py -m %s -t %s -c --silent %s -n %s " % (link["target"], toolchain, test_lib_switch, ",".join(test_names)) print "Executing: " + cmdline if not dry_run: if os.system(cmdline) != 0: sys.exit(1) def run_test_testsuite(dry_run): cmdline = "python tools/singletest.py --version" print "Executing: " + cmdline if not dry_run: if os.system(cmdline) != 0: sys.exit(1) if __name__ == "__main__": run_builds("-s" in sys.argv) run_test_linking("-s" in sys.argv) run_test_testsuite("-s" in sys.argv)
[ "Ashok.Rao@arm.com" ]
Ashok.Rao@arm.com
77825d5d7d96d2954670502979e01b35cbeae203
3cb4f8e967cd21bad7c0f026c9799d901bc1fb73
/gutter/artist.py
d36f6223c3628f0bc120ba575bbfbbf60eb18838
[]
no_license
OEP/gutter
ffbba9c69ac92cbc2c3dae31ad62f8a9b24fd1fd
747092561359f4c9da59c7609232dd8abbc1c7b6
refs/heads/master
2021-01-16T18:07:49.844498
2013-07-16T12:53:40
2013-07-16T12:53:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,924
py
import album import song class RainwaveArtist(object): '''A :class:`RainwaveArtist` object represents one artist. .. note:: You should not instantiate an object of this class directly, but rather obtain one from :attr:`RainwaveChannel.artists` or :attr:`RainwaveSong.artists`. ''' def __init__(self, channel, raw_info): self._channel = channel self._raw_info = raw_info def __repr__(self): return '<RainwaveArtist [{}]>'.format(self) def __str__(self): return self.name.encode(u'utf-8') @property def id(self): '''The ID of the artist.''' return self._raw_info[u'artist_id'] @property def name(self): '''The name of the artist.''' return self._raw_info[u'artist_name'] @property def numsongs(self): '''The number of songs attributed to the artist.''' if u'artist_numsongs' not in self._raw_info: more_info = self._channel._get_artist_raw_info(self.id) self._raw_info = dict(self._raw_info.items() + more_info.items()) return self._raw_info[u'artist_numsongs'] @property def songs(self): '''A list of :class:`RainwaveSong` objects attributed to the artist.''' if u'songs' not in self._raw_info: more_info = self._channel._get_artist_raw_info(self.id) self._raw_info = dict(self._raw_info.items() + more_info.items()) if not hasattr(self, u'_songs'): self._songs = [] for raw_song in self._raw_info[u'songs']: album_id = raw_song[u'album_id'] new_raw_album = self._channel._get_album_raw_info(album_id) new_album = album.RainwaveAlbum(self._channel, new_raw_album) new_song = song.RainwaveSong(new_album, raw_song) self._songs.append(new_song) return self._songs
[ "william@subtlecoolness.com" ]
william@subtlecoolness.com
0abd1c788cd3722d148b30f9bf0fad0685983d00
42e3621158be2fead9fe4af2e351a34dca1fac53
/jobs/app.py
0d765039d72c7cff5a4410977dfab438ee0e23e5
[]
no_license
Manofdesign/PythonFlask-JobBoard
24aabbbec933b2bf4a1898c6b1106d1259422756
6399aaf147471cef93c424a1bb6005b31bc5c908
refs/heads/master
2023-01-01T16:41:36.403832
2020-10-28T22:17:13
2020-10-28T22:17:13
298,415,492
0
0
null
2020-09-24T23:09:30
2020-09-24T23:09:29
null
UTF-8
Python
false
false
2,927
py
import sqlite3 from flask import Flask, g, request, redirect, url_for from flask import render_template import datetime PATH = "db/jobs.sqlite" app = Flask(__name__) def open_connection(): connection = getattr(g,'_connection', None) if connection == None: connection = sqlite3.connect(PATH) g._connection = sqlite3.connect(PATH) connection.row_factory = sqlite3.Row return connection def execute_sql(sql, values=(), commit=False, single=False): connection = open_connection() cursor = connection.execute(sql, values) if commit == True: results = connection.commit() else: results = cursor.fetchone() if single else cursor.fetchall() cursor.close() return results @app.route('/job/<job_id>') def job(job_id): job = execute_sql( 'SELECT job.id, job.title, job.description, job.salary, employer.id as employer_id, employer.name as employer_name FROM job JOIN employer ON employer.id = job.employer_id WHERE job.id = ?', [job_id], single=True) return render_template('job.html', job=job) @app.teardown_appcontext def close_connection(exception): connection = getattr(g, '_connection', None) if connection != None: connection.close() return @app.route('/') @app.route('/jobs') def jobs(): jobs = execute_sql('SELECT job.id, job.title, job.description, job.salary, employer.id as employer_id, employer.name as employer_name FROM job JOIN employer ON employer.id = job.employer_id') return render_template('index.html', jobs=jobs) @app.route('/employer/<employer_id>') def employer(employer_id): employer = execute_sql( 'SELECT * FROM employer WHERE id=?', [employer_id], single=True) jobs = execute_sql( 'SELECT job.id, job.title, job.description, job.salary FROM job JOIN employer ON employer.id = job.employer_id WHERE employer.id = ?', [employer_id]) reviews = execute_sql( 'SELECT review, rating, title, date, status FROM review JOIN employer ON employer.id = review.employer_id WHERE employer.id = ?', [employer_id]) return render_template('employer.html', employer=employer, jobs=jobs, reviews=reviews) @app.route('/employer/<employer_id>/review', methods=('GET', 'POST')) def review(employer_id): if request.method == 'POST': review = request.form['review'] rating = request.form['rating'] title = request.form['title'] status = request.form['status'] date = datetime.datetime.now().strftime("%m/%d/%Y") execute_sql( 'INSERT INTO review (review, rating, title, date, status, employer_id) VALUES (?, ?, ?, ?, ?, ?)', (review, rating, title, date, status, employer_id), commit=True) return redirect(url_for('employer',employer_id=employer_id)) return render_template('review.html', employer_id=employer_id)
[ "43456962+Manofdesign@users.noreply.github.com" ]
43456962+Manofdesign@users.noreply.github.com
889ae073854d8de68add087030c54420209502d8
89a1e4e9d928ee3b0f962fa7f8e20ffbbc34c941
/quest_extension/migrations/0035_correctlyansweredquestion_time_modified.py
72f45bde31c766673acacda3121bb720bc81e344
[]
no_license
tdesai2017/Akamai_Quest_Extension_Training_Application
ff24b161cf7d0ca831dad56a010aa203e2c50ee7
97b8501a49e4c316c7859e3679f46d344db971cd
refs/heads/master
2022-12-12T17:09:34.295929
2019-11-04T19:42:38
2019-11-04T19:42:38
182,309,352
0
0
null
2022-12-08T05:14:45
2019-04-19T18:33:44
Python
UTF-8
Python
false
false
423
py
# Generated by Django 2.0.13 on 2019-06-19 13:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quest_extension', '0034_auto_20190613_1447'), ] operations = [ migrations.AddField( model_name='correctlyansweredquestion', name='time_modified', field=models.DateTimeField(auto_now=True), ), ]
[ "tdesai@prod-gtm-app10.bos01.corp.akamai.com" ]
tdesai@prod-gtm-app10.bos01.corp.akamai.com
1c165f1ccad36c215f56ef5613cea7ee2101c812
1facfd9d94b0f08ddde2834c717bda55359c2e35
/Python programming for the absolute beginner - Michael Dawson/Chapter 8 - OOP beginning/8.3.py
58bad4a7400168c26ceaa2894583a1b3bd76ba4e
[]
no_license
echpochmak/ppftab
9160383c1d34a559b039af5cd1451a18f2584549
f5747d87051d837eca431f782491ec9ba3b44626
refs/heads/master
2021-09-15T07:23:06.581750
2018-05-28T14:33:13
2018-05-28T14:33:13
261,880,781
1
0
null
2020-05-06T21:18:13
2020-05-06T21:18:13
null
UTF-8
Python
false
false
3,000
py
# The material form the book in polish # Opiekun zwierzaka # Wirtualny pupil, którym należy się opiekować class Critter(object): """Wirtualny pupil""" def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom def __str__(self): rep = "The valuse of your pet:\n" rep += "The hunger = " + str(self.hunger) rep += "\nThe boredom = " + str(self.boredom) return rep def __pass_time(self): self.hunger += 1 self.boredom += 1 @property def mood(self): unhappiness = self.hunger + self.boredom if unhappiness < 5: m = "szczęśliwy" elif 5 <= unhappiness <= 10: m = "zadowolony" elif 11 <= unhappiness <= 15: m = "podenerwowany" else: m = "wściekły" return m def talk(self): print("Nazywam się", self.name, "i jestem", self.mood, "teraz.\n") self.__pass_time() def eat(self, food = 4): print(""" How much food would you like to serve to you pet? \n 1. Type 1 for one snack. \n 2. Type 2 for 2 snacks. \n 3. Type 3 for 3 snacks. \n 4. Type 4 for 4 snacks. \n 5. Type 5 for 5 snacks. """, end = " ") food = int(input("Wybierasz: ")) print("Mniam, mniam. Dziękuję.") self.hunger -= food if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self, fun = 4): print(""" How log would you like to play with your pet? \n 1. Type 1 for one minute. \n 2. Type 2 for 2 minutes. \n 3. Type 3 for 3 minutes. \n 4. Type 4 for 4 minutes. \n 5. Type 5 for 5 minutes. """, end = " ") fun = int(input("Wybierasz: ")) print("Hura!") self.boredom -= fun if self.boredom < 0: self.boredom = 0 self.__pass_time() def main(): crit_name = input("Jak chcesz nazwać swojego zwierzaka?: ") crit = Critter(crit_name) choice = None while choice != "0": print \ (""" Opiekun zwierzaka 0 - zakończ 1 - słuchaj swojego zwierzaka 2 - nakarm swojego zwierzaka 3 - pobaw się ze swoim zwierzakiem 4 - show the values of your pet """) choice = input("Wybierasz: ") print() # wyjdź z pętli if choice == "0": print("Do widzenia.") # słuchaj swojego zwierzaka elif choice == "1": crit.talk() # nakarm swojego zwierzaka elif choice == "2": crit.eat() # pobaw się ze swoim zwierzakiem elif choice == "3": crit.play() elif choice == "4": print(crit) # nieznany wybór else: print("\nNiestety,", choice, "nie jest prawidłowym wyborem.") main() input("\n\nAby zakończyć program, naciśnij klawisz Enter.")
[ "mateuszszpakowski@wp.pl" ]
mateuszszpakowski@wp.pl
6fdd24a3d6b6ce8ba8f54ce5147babfcf93ea7c7
6d44e17911050ff2516c2c025b852ffe1b864a59
/superlists/urls.py
4b8a451669ee5a9f577b3105f7a4f9bfff21077d
[]
no_license
coa1esce/clash
e0086e9dd93eced80333ad95a46548618a54eedb
b3ef85733f762d6724783257cf816506214a1906
refs/heads/master
2021-01-10T13:08:49.868155
2016-04-07T22:45:21
2016-04-07T22:45:21
55,635,947
0
0
null
null
null
null
UTF-8
Python
false
false
812
py
"""superlists URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from lists import views urlpatterns = [ url(r'^$', views.home_page, name="home"), # url(r'^admin/', admin.site.urls), ]
[ "william.deguire@gmail.com" ]
william.deguire@gmail.com
d3001ec4f08bd4736214ae79c2c8e5734486bf4c
a4266b32b04df49a7d6251b5e125ef92369cbea8
/projects/01_fyyur/starter_code/migrations/versions/8d395419b3cd_.py
da0bc42269b7c95e489d73d4441a617333480d18
[]
no_license
Crazychukz/udacity-fyyur
9fed779f82bf406ea80d9c79710318cc4b95f708
7cda6fe4bf7490cfe00707c1e06dd43f2959bc49
refs/heads/main
2023-02-20T17:13:39.050992
2021-01-22T05:20:22
2021-01-22T05:20:22
329,382,955
0
0
null
null
null
null
UTF-8
Python
false
false
656
py
"""empty message Revision ID: 8d395419b3cd Revises: 4192c431ec89 Create Date: 2021-01-19 13:00:11.229361 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '8d395419b3cd' down_revision = '4192c431ec89' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('shows', sa.Column('start_date', sa.Date(), nullable=False)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('shows', 'start_date') # ### end Alembic commands ###
[ "chukwuemekacharles88@gmail.com" ]
chukwuemekacharles88@gmail.com
5ee18fe1c627d044dd94b31a4ae22fcca29f5c5f
f228c0aedc6d66676d52a87a4780cad43ca1af68
/manage.py
f92873d395d95c58e73995b20873d7ef0d4177f0
[]
no_license
MdShohoan/Django-Curd-operation
2e749c86d97b685e19a245c9063771376452b7d3
d62470a26b72368b9759a494ed881531e7b2beb0
refs/heads/main
2023-01-25T03:07:27.141933
2020-12-07T05:52:51
2020-12-07T05:52:51
319,217,445
0
0
null
null
null
null
UTF-8
Python
false
false
632
py
#!/usr/bin/env python3 """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Django_rest.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
[ "shohoankhan@gmail.com" ]
shohoankhan@gmail.com
32f6b9fff9acce58bdc331e9f0ec63770932d681
0a639bda0058ac76cca97d6123f6c39229f202f1
/companies/models.py
9092279495371d6cf60c4e5d5b187922621a9bb7
[]
no_license
sanchitbareja/occuhunt-web
bb86e630c2caff5815b164435464424b5cf83375
fab152e2ebae3f4dd5c8357696893065bdd30504
refs/heads/master
2020-05-21T01:15:48.973953
2015-01-13T04:03:18
2015-01-13T04:03:18
12,552,735
0
0
null
null
null
null
UTF-8
Python
false
false
3,089
py
from django.db import models import datetime # Create your models here. class CompanyType(models.Model): type = models.CharField(max_length = 256) def __unicode__(self): return self.type ORGANIZATION_TYPES_LIST = ( ('Accounting Services', 'Accounting Services'), ('Aerospace/Defense', 'Aerospace/Defense'), ('Agriculture', 'Agriculture'), ('Architecture/Planning', 'Architecture/Planning'), ('Arts and Entertainment', 'Arts and Entertainment'), ('Automotive/Transportation Manufacturing', 'Automotive/Transportation Manufacturing'), ('Biotech/Pharmaceuticals','Biotech/Pharmaceuticals'), ('Chemicals','Chemicals'), ('Computer Hardware','Computer Hardware'), ('Computer Software', 'Computer Software'), ('Consumer Products', 'Consumer Products'), ('Diversified Services', 'Diversified Services'), ('Education/Higher Education', 'Education/Higher Education'), ('Electronics and Misc. Tech', 'Electronics and Misc. Tech'), ('Energy', 'Energy'), ('Engineering', 'Engineering'), ('Financial Services', 'Financial Services'), ('Food, Beverage and Tobacco', 'Food, Beverage and Tobacco'), ('Government', 'Government'), ('Health Products and Services', 'Health Products and Services'), ('Hospital/Healthcare', 'Hospital/Healthcare'), ('Insurance', 'Insurance'), ('Law/Law Related', 'Law/Law Related'), ('Leisure and Travel', 'Leisure and Travel'), ('Materials and Construction', 'Materials and Construction'), ('Media', 'Media'), ('Metals and Mining', 'Metals and Mining'), ('Non-Profit and Social Services', 'Non-Profit and Social Services'), ('Other Manufacturing', 'Other Manufacturing'), ('Professional, Technical, and Administrative Services', 'Professional, Technical, and Administrative Services'), ('Real Estate', 'Real Estate'), ('Retail and Wholesale Trade', 'Retail and Wholesale Trade'), ('Telecommunications', 'Telecommunications'), ('Transportation Services', 'Transportation Services'), ('Utilities', 'Utilities'), ('Other', 'Other'), ) class Company(models.Model): name = models.CharField(max_length=512) founded = models.CharField(max_length=64, null=True, blank=True) funding = models.CharField(max_length=64, null=True, blank=True) website = models.URLField(max_length=512, null=True, blank=True) careers_website = models.URLField(max_length=512, null=True, blank=True) logo = models.URLField(max_length=512, null=True, blank=True) banner_image = models.URLField(max_length=512, null=True, blank=True) number_employees = models.CharField(max_length=48, null=True, blank=True) organization_type = models.CharField(max_length=512, null=True, blank=True, choices=ORGANIZATION_TYPES_LIST) company_description = models.TextField(null=True, blank=True) competitors = models.CharField(max_length=512, null=True, blank=True) avg_salary = models.CharField(max_length=64, null=True, blank=True) location = models.CharField(max_length=512, null=True, blank=True) intro_video = models.TextField(null=True, blank=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.name
[ "sanchitbareja@gmail.com" ]
sanchitbareja@gmail.com
1f284369bfbe954056b67fc0947ca8007b2caf08
beab30a1bb6ea08abc6bb63e6f22b1ed36c28af3
/pommerman/fight.py
978069671958a5f911bfa025bd3758221cdb3652
[ "Apache-2.0" ]
permissive
davnn/deep_pommerman
e350f2e6d657c5240000357494ed46f100273d75
98375ffbd076ade584309b9feef248e30de77120
refs/heads/master
2023-05-29T17:30:58.582056
2021-06-18T19:22:48
2021-06-18T19:22:48
375,286,652
0
0
null
null
null
null
UTF-8
Python
false
false
6,080
py
"""Run a battle among agents. Call this with a config, a game, and a list of agents. The script will start separate threads to operate the agents and then report back the result. An example with all four test agents running ffa: python run_battle.py --agents=test::agents.SimpleAgent,test::agents.SimpleAgent,test::agents.SimpleAgent,test::agents.SimpleAgent --config=PommeFFACompetition-v0 An example with one player, two random agents, and one test agent: python run_battle.py --agents=player::arrows,test::agents.SimpleAgent,random::null,random::null --config=PommeFFACompetition-v0 An example with a docker agent: python run_battle.py --agents=player::arrows,docker::pommerman/test-agent,random::null,random::null --config=PommeFFACompetition-v0 """ import atexit from datetime import datetime import os import random import sys import time import sys import argparse import numpy as np from pommerman import helpers from pommerman import make from pommerman import utility def run(config, agents_list, record_pngs_dir = None, record_json_dir = None, agent_env_vars = "", game_state_file = None, render_mode = 'human', do_sleep = True, render = False, num_episodes=1, seed=None): '''Wrapper to help start the game''' agents = [ helpers.make_agent_from_string(agent_string, agent_id) for agent_id, agent_string in enumerate(agents_list.split(',')) ] env = make(config, agents, game_state_file, render_mode=render_mode) def _run(record_pngs_dir=None, record_json_dir=None): '''Runs a game''' print("Starting the Game.") if record_pngs_dir and not os.path.isdir(record_pngs_dir): os.makedirs(record_pngs_dir) if record_json_dir and not os.path.isdir(record_json_dir): os.makedirs(record_json_dir) obs = env.reset() done = False while not done: if render: env.render( record_pngs_dir=record_pngs_dir, record_json_dir=record_json_dir, do_sleep=do_sleep) if render is False and record_json_dir: env.save_json(record_json_dir) time.sleep(1.0 / env._render_fps) actions = env.act(obs) obs, reward, done, info = env.step(actions) print("Final Result: ", info) if render: env.render( record_pngs_dir=record_pngs_dir, record_json_dir=record_json_dir, do_sleep=do_sleep) if do_sleep: time.sleep(5) env.render(close=True) if render is False and record_json_dir: env.save_json(record_json_dir) time.sleep(1.0 / env._render_fps) if record_json_dir: finished_at = datetime.now().isoformat() _agents = agents_list.split(',') utility.join_json_state(record_json_dir, _agents, finished_at, config, info) return info if seed is None: # Pick a random seed between 0 and 2^31 - 1 seed = random.randint(0, np.iinfo(np.int32).max) np.random.seed(seed) random.seed(seed) env.seed(seed) infos = [] times = [] for i in range(num_episodes): start = time.time() record_pngs_dir_ = record_pngs_dir + '/%d' % (i+1) \ if record_pngs_dir else None record_json_dir_ = record_json_dir + '/%d' % (i+1) \ if record_json_dir else None infos.append(_run(record_pngs_dir_, record_json_dir_)) times.append(time.time() - start) print("Game Time: ", times[-1]) atexit.register(env.close) return infos # def main(): # '''CLI entry pointed used to bootstrap a battle''' # simple_agent = 'test::agents.SimpleAgent' # player_agent = 'player::arrows' # docker_agent = 'docker::pommerman/simple-agent' # # parser = argparse.ArgumentParser(description='Playground Flags.') # parser.add_argument( # '--config', # default='PommeFFACompetition-v0', # help='Configuration to execute. See env_ids in ' # 'configs.py for options.') # parser.add_argument( # '--agents', # default=','.join([simple_agent] * 4), # # default=','.join([player_agent] + [simple_agent]*3]), # # default=','.join([docker_agent] + [simple_agent]*3]), # help='Comma delineated list of agent types and docker ' # 'locations to run the agents.') # parser.add_argument( # '--agent_env_vars', # help='Comma delineated list of agent environment vars ' # 'to pass to Docker. This is only for the Docker Agent.' # " An example is '0:foo=bar:baz=lar,3:foo=lam', which " # 'would send two arguments to Docker Agent 0 and one ' # 'to Docker Agent 3.', # default="") # parser.add_argument( # '--record_pngs_dir', # default=None, # help='Directory to record the PNGs of the game. ' # "Doesn't record if None.") # parser.add_argument( # '--record_json_dir', # default=None, # help='Directory to record the JSON representations of ' # "the game. Doesn't record if None.") # parser.add_argument( # "--render", # default=False, # action='store_true', # help="Whether to render or not. Defaults to False.") # parser.add_argument( # '--render_mode', # default='human', # help="What mode to render. Options are human, rgb_pixel, and rgb_array") # parser.add_argument( # '--game_state_file', # default=None, # help="File from which to load game state.") # parser.add_argument( # '--do_sleep', # default=True, # help="Whether we sleep after each rendering.") # args = parser.parse_args() # run(args) # # # if __name__ == "__main__": # main()
[ "muhrdavid@gmail.com" ]
muhrdavid@gmail.com
5be6010f3a856a416a0282d5b935f9e45d4e5abb
03f5ab2084198aa585be4a305c60d70cb16a93ee
/ex19.py
19cecb1d9194f814e48327fd85bf9a98b2545582
[]
no_license
Izaya-Shizuo/lpthw_solutions
b156c0f2f80ad002464e62783c65f36ace2b54db
b2be3c4d849265f952652c2680028fd582c3a67a
refs/heads/master
2021-01-10T16:26:53.208425
2015-12-24T07:51:37
2015-12-24T07:51:37
48,531,955
0
0
null
null
null
null
UTF-8
Python
false
false
1,114
py
# Defining the function here with two arguments. The function prints the values of the arguments def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" %cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket .\n" print "We can just give the function numbers directly:" # Directly give the values to the arguments of the functions cheese_and_crackers(20, 30) print "OR, we can use variables from our script:" # Giving the variables their values and defining them as the arguments of the functions amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheese, amount_of_crackers) print "We can even do math inside too:" # Performing the addition and assigning those values to the arguments of the function cheese_and_crackers(10+20, 5+6) print "And we can combine the two, variables and math:" # Same thing here we just add a constant with variable and assigning their sum to the arguments of the function cheese_and_crackers(amount_of_cheese+100, amount_of_crackers+1000)
[ "izayaikebukro@gmail.com" ]
izayaikebukro@gmail.com
db19624cb6bca80ea8e281560b363a90983a931b
ab13fe1bd925fc20f60b8bdfb44d8ed9ca437462
/Python/tempCodeRunnerFile.py
626dbfa1170c4ccf7320fbcf717fbffa8d7b21ef
[]
no_license
chaitanyakette/TechFiles
a5fc9b2f1f81cef3e3aaa47e08ace3a1f5ffb3cc
cfe66811439cdfe98ce965df1428887818ccc4b0
refs/heads/master
2023-07-13T23:57:12.714638
2021-08-23T17:28:53
2021-08-23T17:28:53
399,188,962
0
0
null
null
null
null
UTF-8
Python
false
false
14
py
c=c+1
[ "chaitmoun@gmail.com" ]
chaitmoun@gmail.com
af363d021e5648986bed5c80abd2f2829a4eac67
7024f5e954fa46dc266eedcde54b5bd32e5cd8c0
/users/views.py
1a6e718191a843d270f45fe705f9c5fd16e18b0b
[]
no_license
rahulg510/blogger
25e9a6105dd37ef3102386e6d2b8924cdfa0b0d1
8bb62d16908a5bb61e8d3e1b8b8057092d73cdfd
refs/heads/master
2022-04-27T03:13:43.511502
2020-04-18T07:02:05
2020-04-18T07:02:05
255,612,691
0
0
null
null
null
null
UTF-8
Python
false
false
666
py
from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from .forms import RegistrationForm def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid: form.save() username = request.POST['username'] password = request.POST['password1'] user = authenticate(request, username=username, password=password) login(request,user) return redirect('blog-home') else: form = RegistrationForm() context = {'form':form} return render(request, 'users/register.html', context)
[ "rahulg510@live.com" ]
rahulg510@live.com
55ffff92327e8de2093937623f78cd5e42b87c18
38f4a7ab5d174baab0fe7c0e45b7bd0b23fa9b91
/Python/Exe04.py
14952f564b92c2cdf562dc9a24f731824d9e05a3
[]
no_license
ranjiewwen/Everyday_Practice
764b7d89d6aecea3423980d30acc1985a40e7715
b12855d0414d7d64571093ec0b69ba775eda2068
refs/heads/master
2020-04-15T14:30:23.139626
2018-12-28T05:14:27
2018-12-28T05:14:27
54,867,492
8
1
null
null
null
null
UTF-8
Python
false
false
1,577
py
# coding: utf-8 var1 = 1 var2 = 10 del var1 #var3=ceil(4.3) var3='hello world!' var4='Python Rundo!' print 'var1[0]:',var3[0] print 'var2[1:5]:',var4[1:5] var5='hello world!' print '更新字符串:-',var5[:6]+'Runoob' a='hello' b='python' print a+b print 'H' in a print 'M' not in a print r'\n' print 'my name is %s and weight is %d kg!' % ('derrick',52) ''' python 三引号 triple quotes ''' print u'hello world!' list1 = ['physics','chemistry',1997,2000] print 'list1[1:5]',list1[1:3] list1[2]=2001 print list1 print len(list1) print min(list1) #python 元组 tup1=('physics','chemistry','1997','2001') tup2=(1,2,3,4,5,6,7) print "tup1[0]:",tup1[0] print "tup2[1:3]:",tup1[1:3] print tup1+tup2 print tup1; del tup1 print "after deleting tup1:" #print tup1 tup3=tuple(list1) print tup3 #python 字典 dict = {'Alice':'2341','beth':'9102','ceil':'3258'} ## -*- coding: utf-8 -*- dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} dict = {'name':'zara','age':7,'class':'First'} print 'dict[name]:',dict['name'] #print dict['Alice'] dict['age']=10 dict['School']='DSP school' print dict print len(dict) print str(dict) print type(dict) import time; #引入time模块 ticks=time.time() print '当前时间戳为:',ticks localtime=time.localtime(time.time()) print '本地时间为:',localtime localtime1=time.asctime(time.localtime(time.time())) print '本地时间为:',localtime1 #格式为时间 print time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) import calendar cal=calendar.month(2016,1) print "2016年1月的日历:\n",cal
[ "532685734@qq.com" ]
532685734@qq.com
28eb7a405c2e0bd1f3d508e0392db692e874d22d
0db39ede175595a1cbe397fe76266e41841a072f
/mysite/settings.py
b0e51e58323834d417a941f9f1e1eb8441f53050
[]
no_license
vandlaw7/my-first-blog
a3b382b5bc0ee79d29d2962a60a02a24c1c7817b
cb8b9ce64ea1958b77ef100d140d82c9c2c99ff8
refs/heads/master
2020-12-12T04:38:51.774083
2020-01-15T12:04:15
2020-01-15T12:04:15
234,043,972
0
0
null
null
null
null
UTF-8
Python
false
false
3,187
py
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.2.9. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'fgung_7362xm_!if1%d_f#+j5*(id%+_v2tzeqv46jq3ln7i9o' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Seoul' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')
[ "vandlaw@naver.com" ]
vandlaw@naver.com
286c2725fa2a7c64423fb359d8742ff3a8f7170a
3f7bd5c0db79b7fbf24b99d93f9a7bb285513fe6
/tools.py
620b108fe0598eaba2693dc7b9cd63b1686e0422
[]
no_license
mfldavidson/dfs_nsc_import_prep
f550d393a66f64329c6671dfac1b74344be9dc79
579b7aa0446070f9f372d5dc4346d6be5284b5bb
refs/heads/master
2022-12-20T21:16:29.971461
2020-11-02T15:59:55
2020-11-02T15:59:55
250,892,888
0
0
null
2022-12-08T10:21:23
2020-03-28T21:02:36
Jupyter Notebook
UTF-8
Python
false
false
2,680
py
from collections import OrderedDict import pandas as pd import numpy as np def extract_record(d): ''' Given an OrderedDict, extract the records and return a list of attributes and a list of columns. ''' record = [] cols = [] for var in d: if var not in ['attributes', 'url']: # Skip the unnecessary attributes and url data subitem = d.get(var) if type(subitem) == OrderedDict: for subvar in subitem: if subvar not in ['attributes', 'url']: record.append(subitem.get(subvar)) cols.append(f'{var} {subvar}') else: record.append((d.get(var))) cols.append(var) return record, cols def salesforce_to_dataframe(response): ''' Given an ordered dict returned from the Salesforce API, return a pandas data frame with the data. ''' arr = [] for item in response.get('records'): # Build a list containing the data for this individual record record, cols = extract_record(item) arr.append(record) # Append the list to the arr list # vars = response.get('records')[0].keys() # Get the keys for column names # vars = list(vars) # vars.remove('attributes') df = pd.DataFrame.from_records(arr, columns=cols) return df def year_to_period(date): ''' Given a date, return Fall, Winter, Summer, or NaN based on the month. Used to determine term/period of enrollment based on Enrollment Begin. NaN will be true for any rows that denote an earned degree. ''' if date.month < 4: return 'Winter' elif date.month < 8: return 'Summer' elif date.month <= 12: return 'Fall' else: return np.nan def degree_type(degree_title): ''' Given a degree title (such as "Certificate of Completion" or "Bachelor of Applied Science"), return the type of degree from the list Certificate, Associate, Bachelor, Master, PhD, JD, MD. ''' degrees = ['Certificate', 'Associate', 'Bachelor', 'Master', 'PhD', 'JD', 'MD'] for degree in degrees: upper = degree.upper() if upper in degree_title: return degree elif upper + 'S' in degree_title: return degree else: if 'DOCTORATE' in degree_title: return 'PhD' elif 'PHILOSOPHY' in degree_title: return 'PhD' elif 'JURIS' in degree_title: return 'JD' elif 'MEDICAL' in degree_title: return 'MD' elif 'MEDICINE' in degree_title: return 'MD'
[ "jmagdavidson@gmail.com" ]
jmagdavidson@gmail.com
c5cf8aee1be268414aa93dbc592e7fed079198c0
d84ac0465808797072ee6da70a42113b938777c1
/distance/traj_dist/lcss.py
504292478e3672893ea2963457dacedb65b72ad7
[]
no_license
mattkennedy416/Big-Time-Series-Analysis
d0c4520d7db27c2d805c5353a3e9e813dd9b1995
ae60833095fe99ee2dd2a85c1f69cf8748d95883
refs/heads/master
2020-04-16T08:30:20.064962
2019-02-21T04:58:39
2019-02-21T04:58:39
165,427,239
0
0
null
null
null
null
UTF-8
Python
false
false
1,916
py
from distance.traj_dist.basic_euclidean import eucl_dist from distance.traj_dist.basic_spherical import great_circle_distance ###################### # Euclidean Geometry # ###################### def e_lcss(t0, t1, eps): """ Usage ----- The Longuest-Common-Subsequence distance between trajectory t0 and t1. Parameters ---------- param t0 : len(t0)x2 numpy_array param t1 : len(t1)x2 numpy_array eps : float Returns ------- lcss : float The Longuest-Common-Subsequence distance between trajectory t0 and t1 """ n0 = len(t0) n1 = len(t1) # An (m+1) times (n+1) matrix C = [[0] * (n1 + 1) for _ in range(n0 + 1)] for i in range(1, n0 + 1): for j in range(1, n1 + 1): if eucl_dist(t0[i - 1], t1[j - 1]) < eps: C[i][j] = C[i - 1][j - 1] + 1 else: C[i][j] = max(C[i][j - 1], C[i - 1][j]) lcss = 1 - float(C[n0][n1]) / min([n0, n1]) return lcss ###################### # Spherical Geometry # ###################### def s_lcss(t0, t1, eps): """ Usage ----- The Longuest-Common-Subsequence distance between trajectory t0 and t1. Parameters ---------- param t0 : len(t0)x2 numpy_array param t1 : len(t1)x2 numpy_array eps : float Returns ------- lcss : float The Longuest-Common-Subsequence distance between trajectory t0 and t1 """ n0 = len(t0) n1 = len(t1) # An (m+1) times (n+1) matrix C = [[0] * (n1 + 1) for _ in range(n0 + 1)] for i in range(1, n0 + 1): for j in range(1, n1 + 1): if great_circle_distance(t0[i - 1, 0], t0[i - 1, 1], t1[j - 1, 0], t1[j - 1, 1]) < eps: C[i][j] = C[i - 1][j - 1] + 1 else: C[i][j] = max(C[i][j - 1], C[i - 1][j]) lcss = 1 - float(C[n0][n1]) / min([n0, n1]) return lcss
[ "mattkennedy416@gmail.com" ]
mattkennedy416@gmail.com
78374d045b6f66c2b39d4930157a45720df92186
2474ddeb131e641f097ed137d0f25b378c4b1a30
/migrations/versions/4b754e76ffe5_.py
51a9200cf0185a7eb77729acee7ca9ee8a853a42
[]
no_license
fatetwist/blog
7f44c6546b818c2bc2d66697ee78b1c1bcc27008
68ff35c6f71813c70df7427820683c39d84298e4
refs/heads/master
2021-08-28T04:49:58.051933
2017-12-11T08:02:13
2017-12-11T08:02:13
112,607,498
0
0
null
null
null
null
UTF-8
Python
false
false
804
py
"""empty message Revision ID: 4b754e76ffe5 Revises: 77f969a8abc1 Create Date: 2017-11-30 20:01:27.313714 """ # revision identifiers, used by Alembic. revision = '4b754e76ffe5' down_revision = '77f969a8abc1' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.alter_column('comments', 'user_id', existing_type=mysql.INTEGER(display_width=11), nullable=True) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.alter_column('comments', 'user_id', existing_type=mysql.INTEGER(display_width=11), nullable=False) # ### end Alembic commands ###
[ "591210216@qq.com" ]
591210216@qq.com
2014ec8e685ef502f09049145c975e7d7d1c2fc0
97b6d53ed1306db1c284ad9df7034ef035523ad1
/Headline/GetHeadlineCookie.py
b5ecb4d85fb6113ccbf2e20ac2600f5d126b2a2d
[]
no_license
molefuckgo/Spiders
cd7174e65650d10397e4f3f194b58add9fc6c5cc
6c8ba40b1f5258783c1842e5945eed8da6fa0079
refs/heads/master
2022-12-13T23:50:57.498843
2020-01-09T20:06:16
2020-01-09T20:06:16
232,619,276
0
0
null
null
null
null
UTF-8
Python
false
false
1,166
py
# !/usr/bin/env python # coding=utf-8 """ @File: GetHeadlineCookie.py @Time: 2020-01-09 16:04 @Desc: """ from selenium import webdriver import time window=webdriver.Chrome() window.get("https://www.toutiao.com/") c1={u"name":u"uid_tt",u"value": u"1f46d8d4bfcbefe9bc65e11e68f7d548",u"domain":u".toutiao.com"} c2={u"name":u"ccid",u"value": u"66c7871a52ca20abc48d678a36a501f2",u"domain":u".toutiao.com"} c3={u"name":u"ckmts",u"value": u"PUJw85AQ,qrJw85AQ,L6Cw85AQ",u"domain":u".toutiao.com"} c4={u"name":u"sid_tt",u"value":u"f89559a8c6f4507d2797ab84faedb6f3",u"domain":u".toutiao.com"} window.add_cookie(c1) window.add_cookie(c2) window.add_cookie(c3) window.add_cookie(c4) window.get("https://www.toutiao.com/") time.sleep(3) # window.refresh() word=window.find_element_by_xpath('//*[@id="rightModule"]/div[1]/div/div/div/input') word.send_keys("soho") time.sleep(2) window.find_element_by_xpath('//*[@id="rightModule"]/div[1]/div/div/div/div/button/span').click() time.sleep(5) window.quit() # html=window.page_source # print(html) # # window.get_screenshot_as_file("a.png") # page=window.page_source # print(page) cookies = window.get_cookies() # print(cookies)
[ "17647361832@163.com" ]
17647361832@163.com
fd494bed9ae526726c9566484dca2746fcf315b4
a024eb30d51fd73d1366def184b91f2b4159f3d1
/python/專案3LBOT/抓天氣.py
18c5bd47caa4184adb51426a0a234af274aa1bd9
[]
no_license
ooxx2500/python-sql-for-test
e4e084719374157cc8bd87e0f62fb2f5d71eb397
66f6ce9f500d2a5eeac162bfc5de321b305c0114
refs/heads/master
2023-02-19T08:19:10.541402
2021-01-18T17:04:16
2021-01-18T17:04:16
266,665,158
0
1
null
null
null
null
UTF-8
Python
false
false
3,207
py
# -*- coding: utf-8 -*- """ Created on Sat Jul 25 01:25:37 2020 @author: 莫再提 """ import requests from bs4 import BeautifulSoup def check_weather(city): citynumber=[20070335, 20070568, 20070569, 20070570, 20070572, 22695855, 22695856, 2295794, 2296315, 2296872, 2297839, 2301128, 2303611, 2304594, 2347336, 2306179, 2306180, 2306181, 2306182, 2306183, 2306184, 2306185, 2306186, 2306187, 2306188, 2306189, 2306190, 2306193, 2306194, 2306195, 2306198, 2306199, 2306200, 2306201, 2306202, 2306203, 2306204, 2306206, 2306207, 2306208, 2306209, 2306210, 2306211, 2306212, 2306213, 2306214, 2306217, 2306218, 2306223, 2306224, 2306226, 2306227, 2306228, 2306229, 2306231, 2306232, 2306243, 2306250, 2306251, 2306254, 2306255, 2347334, 2347335, 2347336, 2347338, 2347339, 2347340, 2347344, 2347345, 2347346, 12703515, 12703525, 12703534, 12703539, 12703543, 12703556, 12703563, 23424971, 28751581, 28751582, 28751583, 28751584, 28752011, 28752322, 28752396, 28752472, 28760734, 28760735, 55863654, 7153409] cityname=['台灣', '台北', '新北市', '高雄', '彰化', '基隆', '澎湖', '旗山', '嘉義', '竹東', '恆春', '苗栗', '豐原', '大武', '宜蘭', '台北', '高雄', '台中', '台南', '彰化', '中壢', '新竹', '新店', '花蓮', '基隆', '屏東', '台東', '佳里', '清水', '二林', '宜蘭', '岡山', '觀音', '鹿港', '龍潭', '麻豆', '南投', '布袋', '石岡', '蘇澳', '大園', '大甲', '淡水', '斗南', '東港', '鶯歌', '新化', '新社', '金山', '枋山', '和平', '關山', '三芝', '三灣', '萬里', '玉井', '南澳', '虎尾', '雙溪', '桃園國際機場', '高雄國際機場', '新竹', '花蓮', '宜蘭', '苗栗', '南投', '屏東', '台東', '桃園', '雲林', '台北', '台北', '新竹', '台中', '彰化', '高雄', '屏東', '台灣', '台南', '新竹', '嘉義', '台中', '南區', '淡水', '花蓮', '桃園', '連江', '金門', '太魯閣國家公園', '嘉義'] city="台北" a=cityname.index(city) number=citynumber[a] number=str(number) url="https://tw.news.yahoo.com/weather/%E8%87%BA%E7%81%A3/%E8%87%BA%E5%8C%97%E5%B8%82/%E8%87%BA%E5%8C%97%E5%B8%82-"+number retext='' page=requests.get(url) data=BeautifulSoup(page.content,"lxml") class_="city Fz(2em)--sm Fz(3.7em)--lg Fz(3.3em) Fw(n) M(0) Trsdu(.3s) desktop_Lh(1) smartphone_Lh(1)" city_name=data.findAll('h1',{'class':class_})[0] retext+="縣市:"+city_name.text+'\n' temp = data.findAll('span',{'class':'Va(t)'})[0] retext+="溫度:"+temp.text+'\n' body_temp = data.findAll('div',{'class':'Fl(end)'})[1].text #體感溫度 humidity = data.findAll('div',{'class':'Fl(end)'})[2].text #濕度 Ultraviolet_rays = data.findAll('div',{'class':'Fl(end)'})[4].text #紫外線 moon = data.findAll('div',{'class':'Fl(end)'})[5].text #月亮 rain = data.find_all('span',{'class':'D(ib) W(3.6em) Fz(1.2em) Ta(c)'})[0].text retext+="體感溫度:"+body_temp+'\n' retext+="濕度:"+humidity+'\n' retext+="紫外線:"+Ultraviolet_rays+'\n' retext+="降雨機率:"+rain+'\n' #print("月亮:",moon) return retext print(check_weather('台北市'))
[ "ooxx2500@gmail.com" ]
ooxx2500@gmail.com
26aa690ec62cb1867208234cd0c19ab8f7a9663a
3d19e1a316de4d6d96471c64332fff7acfaf1308
/Users/S/stefanw/kommunalverwaltung_nrw.py
aef5bdefc3a1b54035f7bc556bd8da592cd801c6
[]
no_license
BerilBBJ/scraperwiki-scraper-vault
4e98837ac3b1cc3a3edb01b8954ed00f341c8fcc
65ea6a943cc348a9caf3782b900b36446f7e137d
refs/heads/master
2021-12-02T23:55:58.481210
2013-09-30T17:02:59
2013-09-30T17:02:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,508
py
import scraperwiki import lxml.html as lh from lxml import etree LIST_URL = 'http://www3.chamaeleon.de/komnav/kundensuchergebnis.php?Ort=&PLZ=%s&OBGM=&Bundesland=Nordrhein-Westfalen&anfrage=imnrw' DETAIL_URL = 'http://www3.chamaeleon.de/komnav/kundensuchedetail.php?schluessel=%s&anfrage=imnrw&PLZ=%s&Ort=&Bundesland=Nordrhein-Westfalen&OBGM=&single_search=' def plz_generator(): for i in (3,4,5): for j in range(10): yield "%s%s" % (i, j) kommune = [] for plz in plz_generator(): print plz content = scraperwiki.scrape(LIST_URL % plz) content = content.decode('latin1') if 'Leider keinen Datensatz gefunden' in content: continue doc = lh.fromstring(content) for row in doc.cssselect('tr'): td = row.cssselect('td') if not td: continue kommune.append({ 'name': td[0].text_content().strip(), 'plz': td[1].text_content().strip(), 'head': td[3].text_content().strip(), 'key': td[4].cssselect('a')[0].attrib['href'].split('schluessel=')[1].split('&anfrage=')[0], 'source': td[4].cssselect('a')[0].attrib['href'] }) wanted = { u'': None, u'Stadt-/Gemeinde-/Kreisname': None, u'PLZ': None, u'Bundesland': None, u'Bev\xf6lkerungsdichte Einwohner pro km\xb2': None, u'(Ober-)b\xfcrgermeisterin/Landr\xe4tin/Oberkreisdirektorinbzw.(Ober-)b\xfcrgermeister/Landrat/Oberkreisdirektor': None, u'EMail': 'email', u'Postanschrift': 'address', u'Regierungsbezirk': 'gov_area', u'Fax': 'fax', u'Telefonzentrale': 'phone', u'Hausanschrift (Verwaltungssitz)': 'address2', u'PLZ-Hausanschrift': 'plz2', u'Ausl\xe4nderanteil (in %)': 'immigrant_percentage', u'EinwohnerInnen': 'population', u'davon weiblich/m\xe4nnlich (in %)': 'female_male_percentage', u'Fl\xe4che (in km\xb2)': 'area', u'Anzahl Besch\xe4ftigte': 'employees', u'Homepage der Kommune': 'url' } print repr(wanted.keys()) for kom in kommune: for v in wanted.values(): if v is not None: kom[v] = None content = scraperwiki.scrape(DETAIL_URL % (kom['key'], kom['plz'])) content = content.decode('latin1') doc = lh.fromstring(content) for row in doc.cssselect('tr'): td = row.cssselect('td') if not td: continue key = td[0].text_content().split(':')[0].strip() if wanted.get(key, None) is not None: kom[wanted[key]] = td[1].text_content().strip() elif key not in wanted: print repr(key) print repr(kom) scraperwiki.sqlite.save(['key'], kom, table_name='nrw_kommune')import scraperwiki import lxml.html as lh from lxml import etree LIST_URL = 'http://www3.chamaeleon.de/komnav/kundensuchergebnis.php?Ort=&PLZ=%s&OBGM=&Bundesland=Nordrhein-Westfalen&anfrage=imnrw' DETAIL_URL = 'http://www3.chamaeleon.de/komnav/kundensuchedetail.php?schluessel=%s&anfrage=imnrw&PLZ=%s&Ort=&Bundesland=Nordrhein-Westfalen&OBGM=&single_search=' def plz_generator(): for i in (3,4,5): for j in range(10): yield "%s%s" % (i, j) kommune = [] for plz in plz_generator(): print plz content = scraperwiki.scrape(LIST_URL % plz) content = content.decode('latin1') if 'Leider keinen Datensatz gefunden' in content: continue doc = lh.fromstring(content) for row in doc.cssselect('tr'): td = row.cssselect('td') if not td: continue kommune.append({ 'name': td[0].text_content().strip(), 'plz': td[1].text_content().strip(), 'head': td[3].text_content().strip(), 'key': td[4].cssselect('a')[0].attrib['href'].split('schluessel=')[1].split('&anfrage=')[0], 'source': td[4].cssselect('a')[0].attrib['href'] }) wanted = { u'': None, u'Stadt-/Gemeinde-/Kreisname': None, u'PLZ': None, u'Bundesland': None, u'Bev\xf6lkerungsdichte Einwohner pro km\xb2': None, u'(Ober-)b\xfcrgermeisterin/Landr\xe4tin/Oberkreisdirektorinbzw.(Ober-)b\xfcrgermeister/Landrat/Oberkreisdirektor': None, u'EMail': 'email', u'Postanschrift': 'address', u'Regierungsbezirk': 'gov_area', u'Fax': 'fax', u'Telefonzentrale': 'phone', u'Hausanschrift (Verwaltungssitz)': 'address2', u'PLZ-Hausanschrift': 'plz2', u'Ausl\xe4nderanteil (in %)': 'immigrant_percentage', u'EinwohnerInnen': 'population', u'davon weiblich/m\xe4nnlich (in %)': 'female_male_percentage', u'Fl\xe4che (in km\xb2)': 'area', u'Anzahl Besch\xe4ftigte': 'employees', u'Homepage der Kommune': 'url' } print repr(wanted.keys()) for kom in kommune: for v in wanted.values(): if v is not None: kom[v] = None content = scraperwiki.scrape(DETAIL_URL % (kom['key'], kom['plz'])) content = content.decode('latin1') doc = lh.fromstring(content) for row in doc.cssselect('tr'): td = row.cssselect('td') if not td: continue key = td[0].text_content().split(':')[0].strip() if wanted.get(key, None) is not None: kom[wanted[key]] = td[1].text_content().strip() elif key not in wanted: print repr(key) print repr(kom) scraperwiki.sqlite.save(['key'], kom, table_name='nrw_kommune')
[ "pallih@kaninka.net" ]
pallih@kaninka.net
b33fb5e2e744096ee753cca7e42a61f4e3f7efdd
a7092612d3b9f53d8e9585006a0f69fe8de10c55
/blog/blog_api.py
26446cb07e8f52ac2f6ccddac3addceaf99d2949
[]
no_license
Surfingbird/PythonTPRep
bc2fc80869a85d30c178325bc5221c23fb1a6a56
dc94822e966fa6b7af1630be13bc44a97716b062
refs/heads/master
2020-03-30T04:47:15.722204
2018-12-10T21:11:50
2018-12-10T21:11:50
150,761,775
0
0
null
null
null
null
UTF-8
Python
false
false
9,322
py
import pymysql.cursors from hashlib import md5 import configparser class BlogAPI: def __init__(self, path_to_config=None): path_to_config = path_to_config or 'settings.config' config = configparser.ConfigParser() config.read(path_to_config) host = config.get('Settings', 'host') user = config.get('Settings', 'user') password = config.get('Settings', 'password') database = config.get('Settings', 'database') port = config.get('Settings', 'port') self.conn = pymysql.connect(host=host, port=int(port), database=database, user=user, password=password) self.cursor = self.conn.cursor() self.auth_users = [] def create_user(self, login, password): """ Creates users. Has to be committed after creation. """ if not (login and password): raise ValueError('Blank user or password') hashed_pwd = md5(password.encode()).hexdigest() self.cursor.execute(f""" INSERT INTO Users (Login, Password) VALUES ({login}, {hashed_pwd}); """) def auth(self, login, password): """ Authorises user. If user exists, adds him to self.auth_users """ if not (login and password): raise ValueError('Login or password is blank') hashed_pwd = md5(password.encode()).hexdigest() self.cursor.execute(f""" SELECT UserID FROM Users WHERE Login = '{login}' AND Password = '{hashed_pwd}'; """) result = self.cursor.fetchone() if result: user_id, = result self.auth_users.append(user_id) def get_users(self): """ Return all registered users """ self.cursor.execute(""" SELECT Login FROM Users; """) user = self.cursor.fetchone() all_users = [] while user: username, = user all_users.append(username) user = self.cursor.fetchone() return all_users def create_blog(self, name, author_id=None): """ Creates blog. Has to be committed after creation. """ if not name: raise ValueError('Blank blog name.') author_id = author_id or 'NULL' self.cursor.execute(f""" INSERT INTO Blogs (Name, AuthorID) VALUES ('{name}', {author_id}); """) def edit_blog(self, blog_id, name): """ Edits blog name. Has to be committed after editing. """ if not name: raise ValueError('Blank blog name.') self.cursor.execute(f""" UPDATE Blogs SET Name = '{name}' WHERE BlogID = {blog_id}; """) def delete_blog(self, blog_id): """ Deletes blog. Has to be committed after deletion. """ if not blog_id: raise ValueError('Blank blog_id') self.cursor.execute(f""" DELETE FROM Blogs WHERE BlogID = {blog_id}; """) def get_blogs_all(self): """ Returns names of all blogs """ self.cursor.execute(""" SELECT Name FROM Blogs; """) result = self.cursor.fetchall() return [b[0] for b in result] def get_blogs_auth(self): """ Returns names of all blogs created by authorised users """ self.cursor.execute(""" SELECT Name FROM Blogs WHERE AuthorID IS NOT NULL; """) result = self.cursor.fetchall() return [b[0] for b in result] def create_post(self, blog_ids, author_id, header, content): """ Creates post in given blogs. Has to be committed after creation. """ if not any([blog_ids, author_id, header, content]): raise ValueError('Blank blog_ids, author_id, header or content.') for blog_id in blog_ids: self.cursor.execute(f""" INSERT INTO Posts (BlogID, AuthorID, Header, Content) VALUES ({blog_id}, {author_id}, '{header}', '{content}'); """) def edit_post(self, post_id, header, content): """ Edits header and content in post by its ID. Has to be committed after edition. """ if not any([post_id, header, content]): raise ValueError('Blank post_id, header or content.') self.cursor.execute(f""" UPDATE Posts SET Header = '{header}', Content = '{content}' WHERE PostID = {post_id}; """) def delete_post(self, post_id): """ Deletes post by its ID. Has to be committed after deletion. """ if not post_id: raise ValueError('Blank post_id.') self.cursor.execute(f""" DELETE FROM Posts WHERE PostID = {post_id}; """) def add_comment(self, post_id, author_id, content, parent_id=None): """ Creates comment if user is authorised and returns its comment_id. Has to be committed after creation. """ if author_id not in self.auth_users: raise Exception(f'User is not authorised. (UserID = {author_id})') if not any([post_id, author_id, content]): raise ValueError('Blank post_id, author_id or content.') parent_id = parent_id or 'NULL' self.cursor.execute(f""" INSERT INTO Comments (PostID, AuthorID, ParentID, Content) VALUES ({post_id}, {author_id}, {parent_id}, '{content}'); """) self.cursor.execute('SELECT LAST_INSERT_ID();') comment_id, = self.cursor.fetchone() return comment_id def get_comments_by_user_from_post(self, post_id, author_id): """ Returns comments made by user from specified post """ if not any([post_id, author_id]): raise ValueError('Blank post_id or author_id.') self.cursor.execute(f""" SELECT Content FROM Comments WHERE PostID = {post_id} AND AuthorID = {author_id}; """) return self.cursor.fetchall() @staticmethod def _get_elements_by_condition(arr, condition): elements = [] for el in arr: if condition(el): elements.append(el) return elements def get_comment_thread(self, comment_id): """ Returns comment thread starting with specified comment_id. Uses breadth-first search. """ if not comment_id: raise ValueError('Blank comment_id.') self.cursor.execute(f"""SELECT CommentID, PostID, AuthorID, ParentID, Content FROM Comments WHERE PostID = ( SELECT PostID FROM Comments WHERE CommentID = {comment_id} ) """) comments_info = list(self.cursor.fetchall()) stack = [] queue = [] starter_comment = self._get_elements_by_condition(arr=comments_info, condition=lambda el: el[0] == comment_id)[0] queue.insert(0, starter_comment) while queue: comment_info = queue.pop() stack.append(comment_info) comment_id = comment_info[0] comments = self._get_elements_by_condition(arr=comments_info, condition=lambda el: el[3] == comment_id) for comment_info in comments: queue.insert(0, comment_info) return stack def get_comments_by_users_from_blog(self, user_ids, blog_id): """ Returns comments made by several users from specified blog. """ if not any([user_ids, blog_id]): raise ValueError('Blank user_ids or blog_id.') user_ids_str = str(tuple(user_ids)) self.cursor.execute(f""" SELECT c.CommentID, c.PostID, c.AuthorID, c.ParentID, c.Content FROM Comments AS c LEFT JOIN Posts AS p ON c.PostID = p.PostID WHERE p.BlogID = {blog_id} AND c.AuthorID IN {user_ids_str} """) return self.cursor.fetchall() def commit(self): self.conn.commit()
[ "a.baronskiy@mail.ru" ]
a.baronskiy@mail.ru
323a4c7eddab68f041ff6fe4f9828b26f769b0ca
525c6a69bcf924f0309b69f1d3aff341b06feb8e
/sunyata/backend/chainer/core/map/power.py
f883795e8d4b0bb7d086f28a97f498406b350ed9
[]
no_license
knighton/sunyata_2017
ba3af4f17184d92f6277d428a81802ac12ef50a4
4e9d8e7d5666d02f9bb0aa9dfbd16b7a8e97c1c8
refs/heads/master
2021-09-06T13:19:06.341771
2018-02-07T00:28:07
2018-02-07T00:28:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
406
py
from chainer import functions as F from ....base.core.map.power import BasePowerAPI class ChainerPowerAPI(BasePowerAPI): def __init__(self): BasePowerAPI.__init__(self) def pow(self, x, a): return F.math.basic_math.pow(x, a) def rsqrt(self, x): return F.rsqrt(x) def sqrt(self, x): return F.sqrt(x) def square(self, x): return F.square(x)
[ "iamknighton@gmail.com" ]
iamknighton@gmail.com
d9bec0f6c57a3c8732298f0a3c6a95177cd043cd
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/synthetic/tree-big-6378.py
52a0e4f72cbae1d4e1737577e4ff7f5cd9ab764f
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
23,288
py
# Binary-search trees class TreeNode(object): value:int = 0 left:"TreeNode" = None right:"TreeNode" = None def insert(self:"TreeNode", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode(x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode(x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode2(object): value:int = 0 value2:int = 0 left:"TreeNode2" = None left2:"TreeNode2" = None right:"TreeNode2" = None right2:"TreeNode2" = None def insert(self:"TreeNode2", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode2(x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode2(x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode2", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode2(x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode2(x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode2", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode2", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode3(object): value:int = 0 value2:int = 0 value3:int = 0 left:"TreeNode3" = None left2:"TreeNode3" = None left3:"TreeNode3" = None right:"TreeNode3" = None right2:"TreeNode3" = None right3:"TreeNode3" = None def insert(self:"TreeNode3", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode3", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode3", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode3", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode4(object): value:int = 0 value2:int = 0 value3:int = 0 value4:int = 0 left:"TreeNode4" = None left2:"TreeNode4" = None left3:"TreeNode4" = None left4:"TreeNode4" = None right:"TreeNode4" = None right2:"TreeNode4" = None right3:"TreeNode4" = None right4:"TreeNode4" = None def insert(self:"TreeNode4", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode4", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode4", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode4", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode5(object): value:int = 0 value2:int = 0 value3:int = 0 value4:int = 0 value5:int = 0 left:"TreeNode5" = None left2:"TreeNode5" = None left3:"TreeNode5" = None left4:"TreeNode5" = None left5:"TreeNode5" = None right:"TreeNode5" = None right2:"TreeNode5" = None right3:"TreeNode5" = None right4:"TreeNode5" = None right5:"TreeNode5" = None def insert(self:"TreeNode5", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode5", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode5", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode5", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class Tree(object): root:TreeNode = None size:int = 0 def insert(self:"Tree", x:int) -> object: if self.root is None: self.root = makeNode(x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree2(object): root:TreeNode2 = None root2:TreeNode2 = None size:int = 0 size2:int = 0 def insert(self:"Tree2", x:int) -> object: if self.root is None: self.root = makeNode2(x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree2", x:int, x2:int) -> object: if self.root is None: self.root = makeNode2(x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree2", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree2", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree3(object): root:TreeNode3 = None root2:TreeNode3 = None root3:TreeNode3 = None size:int = 0 size2:int = 0 size3:int = 0 def insert(self:"Tree3", x:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree3", x:int, x2:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree3", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree3", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree3", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree3", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree4(object): root:TreeNode4 = None root2:TreeNode4 = None root3:TreeNode4 = None root4:TreeNode4 = None size:int = 0 size2:int = 0 size3:int = 0 size4:int = 0 def insert(self:"Tree4", x:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree4", x:int, x2:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree4", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert4(self:"Tree4", x:int, x2:int, x3:int, x4:int) $RetType: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree4", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree4", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree4", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree5(object): root:TreeNode5 = None root2:TreeNode5 = None root3:TreeNode5 = None root4:TreeNode5 = None root5:TreeNode5 = None size:int = 0 size2:int = 0 size3:int = 0 size4:int = 0 size5:int = 0 def insert(self:"Tree5", x:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree5", x:int, x2:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree5", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree5", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree5", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree5", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def makeNode(x: int) -> TreeNode: b:TreeNode = None b = TreeNode() b.value = x return b def makeNode2(x: int, x2: int) -> TreeNode2: b:TreeNode2 = None b2:TreeNode2 = None b = TreeNode2() b.value = x return b def makeNode3(x: int, x2: int, x3: int) -> TreeNode3: b:TreeNode3 = None b2:TreeNode3 = None b3:TreeNode3 = None b = TreeNode3() b.value = x return b def makeNode4(x: int, x2: int, x3: int, x4: int) -> TreeNode4: b:TreeNode4 = None b2:TreeNode4 = None b3:TreeNode4 = None b4:TreeNode4 = None b = TreeNode4() b.value = x return b def makeNode5(x: int, x2: int, x3: int, x4: int, x5: int) -> TreeNode5: b:TreeNode5 = None b2:TreeNode5 = None b3:TreeNode5 = None b4:TreeNode5 = None b5:TreeNode5 = None b = TreeNode5() b.value = x return b # Input parameters n:int = 100 n2:int = 100 n3:int = 100 n4:int = 100 n5:int = 100 c:int = 4 c2:int = 4 c3:int = 4 c4:int = 4 c5:int = 4 # Data t:Tree = None t2:Tree = None t3:Tree = None t4:Tree = None t5:Tree = None i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 i5:int = 0 k:int = 37813 k2:int = 37813 k3:int = 37813 k4:int = 37813 k5:int = 37813 # Crunch t = Tree() while i < n: t.insert(k) k = (k * 37813) % 37831 if i % c != 0: t.insert(i) i = i + 1 print(t.size) for i in [4, 8, 15, 16, 23, 42]: if t.contains(i): print(i)
[ "647530+Virtlink@users.noreply.github.com" ]
647530+Virtlink@users.noreply.github.com
7a47ac5c645e3e4674a4ab2a914c4082fd04d90d
5b6663056169ca85db13993adba9fe5a7a9bd164
/art_gallery_app/urls.py
897bde8e3fc4dee43a7ea1dc394595a5a21eadb2
[]
no_license
parthbhope/art_gallery_git
4302f78178a67cde5903d9daeef7207f2217de04
4dff6864d8df0eafeeba432b8115536c61861673
refs/heads/master
2022-12-07T06:10:24.876989
2020-09-07T18:10:14
2020-09-07T18:10:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
151
py
from django.urls import path from . import views app_name = 'art_gallery_app' urlpatterns = [ path('', views.HomeView.as_view(), name='home'), ]
[ "nikhil.sangwan95@gmail.com" ]
nikhil.sangwan95@gmail.com
c5f52c7666b606152434f9ac8390f8a97c2b6e24
611f6102af951691aa3108bcf16b0f13da0ce734
/tests/test_example_dags_system.py
cbf549d8edf21129a85952f566c8d1833597a6c3
[ "Apache-2.0", "BSD-3-Clause", "MIT", "Python-2.0" ]
permissive
marwan116/airflow
6b74dcdd1c7e1819a0160a634a355f90a89983da
e7b8eb7f3189fa587c49a2856dfd570f7625ca78
refs/heads/master
2021-02-07T09:16:40.246909
2020-02-29T17:05:56
2020-02-29T17:05:56
244,007,975
2
0
Apache-2.0
2020-02-29T17:06:22
2020-02-29T17:06:21
null
UTF-8
Python
false
false
1,108
py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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 parameterized import parameterized from tests.test_utils.system_tests_class import SystemTest class TestExampleDagsSystem(SystemTest): @parameterized.expand([ "example_bash_operator", "example_branch_operator" ]) def test_dag_example(self, dag_id): self.run_dag(dag_id=dag_id)
[ "jarek.potiuk@polidea.com" ]
jarek.potiuk@polidea.com
5f578f05e9eeca2e7a85d76fb6cb42a0d606f54b
8ec910de801b424540abb4e6e955838a287663b6
/Bucles/ManoMoneda.py
7ea1f29e4f99d1de6ef426446f1d5ad4a59e551a
[]
no_license
hector81/Aprendiendo_Python
f4f211ace32d334fb6b495b1b8b449d83a7f0bf8
9c73f32b0c82f08e964472af1923f66c0fbb4c22
refs/heads/master
2022-12-28T03:41:20.378415
2020-09-28T09:15:03
2020-09-28T09:15:03
265,689,885
0
0
null
null
null
null
UTF-8
Python
false
false
1,520
py
# El programa simulará el juego de adivinar en qué mano está la moneda. # Le preguntará a la persona el nombre y cuantas partidas quiere jugar, # luego calculará el ganador. import random def introducirNumero(): while True: try: numeroVecesPartida = int(input("Por favor ingrese un número : ")) if numeroVecesPartida > 0: return numeroVecesPartida break except ValueError: print("Oops! No era válido. Intente nuevamente...") print("Por favor ingrese un número de partidas: ") numeroVecesPartida = introducirNumero() while numeroVecesPartida > 0: print('¿En que mano tengo la moneda? Si crees que en la derecha pulsa 1 y si es en la izquierda pulsa 2') numeroEleccion = int(input("Escoge la mano : ")) if numeroEleccion > 2 or numeroEleccion < 1: print('Tienes que poner 1:derecha o 2:izquierda. No valen otros numeros') else: numeroAleatorio = random.randint(1, 2) if numeroAleatorio == numeroEleccion: print('Has acertado') numeroVecesPartida = 0 else: if (numeroVecesPartida - 1) == 0: print('No has acertado y ya no quedan intentos') numeroVecesPartida = 0 else: print('No has acertado. Vuelve a intertarlo. Te quedan ' + str(numeroVecesPartida - 1) + ' intentos') numeroVecesPartida = numeroVecesPartida - 1
[ "noreply@github.com" ]
noreply@github.com
8e4b245285f07713e1c4369fdee8f87e0bfeb513
6bee67a6684bb47d45b476b3b3db44608cd6b89f
/main/admin.py
64f7e6e656ea93017b7832dcc31f5e3635b815a7
[]
no_license
crutchweb/mrgsh
729032cf7728fe8311ae4ceab9489cf3781b4716
541bee0a46f07e74429a6256e6d18d5684bfe981
refs/heads/master
2020-06-27T01:11:26.861729
2019-07-31T08:17:45
2019-07-31T08:17:45
199,807,120
0
0
null
null
null
null
UTF-8
Python
false
false
1,757
py
from django.contrib import admin from django_mptt_admin.admin import DjangoMpttAdmin from main.models import * from django.utils.html import format_html def get_picture_preview(obj): if obj.pk: return format_html('<img src="{}" style="max-width: 200px; max-height: 200px;" />'.format(obj.image.url)) return "(Выберите изображение и сохраните, чтобы увидеть превью)" get_picture_preview.allow_tags = True class CategoryAdmin(DjangoMpttAdmin): def image_img(self, obj): return format_html('<img src="{}" width="50px"/>'.format(obj.image.url)) list_display = ('name_ru',) fields = [get_picture_preview, 'image', 'name_ru', 'description_ru', 'name_en', 'description_en', 'parent', 'slug'] readonly_fields = [get_picture_preview] list_per_page = 10 class ProductAdmin(admin.ModelAdmin): def image_img(self, obj): return format_html('<img src="{}" width="50px"/>'.format(obj.image.url)) list_display = ('name_ru',) fields = [get_picture_preview, 'image', 'category', 'name_ru', 'description_ru', 'name_en', 'description_en', 'slug'] readonly_fields = [get_picture_preview] list_per_page = 10 class NewsAdmin(admin.ModelAdmin): def image_img(self, obj): return format_html('<img src="{}" width="50px"/>'.format(obj.image.url)) list_display = ('name', 'slug', 'created', 'published',) fields = [get_picture_preview, 'image', 'name', 'slug', 'description', 'created', 'published', 'seo_keywords', 'seo_description'] readonly_fields = [get_picture_preview] list_per_page = 10 admin.site.register(Category, CategoryAdmin) admin.site.register(Product, ProductAdmin) admin.site.register(News, NewsAdmin)
[ "ilya@MacBook-Pro-Ilya.local" ]
ilya@MacBook-Pro-Ilya.local
29da5c21f55c6f0560b8849c7880343c04b3024c
ab4d24f955b179190966e1bb90ea71f45c420b38
/scripts/pre-processing/gen_star_results.py
9291da14679e41e9a0f567223aa0ca572760fed4
[]
no_license
ludmercentre/rna-seq_workflow
b59cf88699bf328d0f9f441c15ae3dd5e9773887
df2e1aae95d84bcb491297b1e910871ed203d5a9
refs/heads/master
2023-05-08T03:33:51.385617
2021-05-26T21:00:07
2021-05-26T21:00:07
277,873,548
0
0
null
null
null
null
UTF-8
Python
false
false
1,380
py
import os import sys import numpy as np import pandas as pd input_folder = sys.argv[1] output_file = sys.argv[2] # Import all STAR output files and append them in results_l list: results_l = list() for file in os.listdir("../{}/".format(input_folder)): if file.endswith("ReadsPerGene.out.tab"): results_l.append(pd.read_csv( "../{}/".format(input_folder)+file, sep="\t", # tab as separater skiprows=4, # Skip first 4 rows names = ['gene_id', file.split("_ReadsPerGene")[0]], # name columns "gene_ID" and sample name usecols = [0,1])) # Only use first two columns of STAR output. (Second column is gene counts) # Set "gene_id" column as index for all dataframes in list (this is required for concatenating) results_l = [df.set_index("gene_id") for df in results_l] # Concatenate all results together in a single dataframe: results_df = pd.concat(results_l, axis=1) # Rename columns of results_df to match sample_id names in MIA_rnaseq_samples_meta_df: results_df.columns = [x.split(".")[-1] for x in results_df.columns] # Important dataframe by sample IDs: results_df = results_df.sort_index(axis=1) # Save dataframe to file to be used in edgeR pipeline # reset index to get gene ids: results_df.reset_index().to_csv("../{}.csv".format(output_file), index=False)
[ "pedrobordignon@hotmail.com" ]
pedrobordignon@hotmail.com
5f0c9801ddd45972b8b510d2b70081f2894354c1
b21967593e233242681d5a1879acad00ee2d52c7
/dongtai/apps.py
a939561a0601142fde86b2bb1713361a58d7d96f
[ "Apache-2.0" ]
permissive
Darius-1024/dongtai-core
0796498fee39e14306579ac00a51cfaab10101e7
f98ba3b36897c30f6fd7139de36fae38e607e8c1
refs/heads/main
2023-07-18T11:21:49.166162
2021-08-31T15:44:37
2021-08-31T15:44:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
89
py
from django.apps import AppConfig class DongTaiConfig(AppConfig): name = 'dongtai'
[ "dongzhiyong@secnium.cn" ]
dongzhiyong@secnium.cn
7a7e1ce328c51f102ed2cf7acf2c61434b1b49d9
93f73e263f1cb286376da9ea8b23a654a3060f58
/setup.py
ad37fa00f376050751cf92a428b36f9c01dc375f
[]
no_license
chriscz/capstone_wrapper
d71f07157c1819857c9a13767de3935e43246616
26ca3d92d8f67ab295baf85727cabdc24b819f67
refs/heads/master
2021-01-20T03:01:26.466335
2017-02-24T20:07:13
2017-02-24T20:07:13
82,589,737
1
0
null
null
null
null
UTF-8
Python
false
false
446
py
from setuptools import setup __version__ = '0.2.2' setup( name='capstone_wrapper', version=__version__, description='A functional wrapper for capstone Python', url='', author='Chris Coetzee', author_email='chriscz93@gmail.com', license='Mozilla Public License 2.0 (MPL 2.0)', packages=['capstone_wrapper'], # install_requires=['capstone >= 3.0.3'], zip_safe=False )
[ "chriscz93@gmail.com" ]
chriscz93@gmail.com
6b57aa51eb80cb2ba879e3fe19dc47e190d2b60e
65cefe621c2444d9b793d7969d2e2c3ff54373d1
/analyze/api.py
c831cbc8c9d0c07781dd86cede87b9b4f346509d
[ "Apache-2.0" ]
permissive
leekangsan/HanziSRS
01585e694fbf81428085b8a162acf101f7f5bec1
50f84a9171b61df3305e8922b645b553e895a509
refs/heads/master
2020-03-29T05:19:19.583429
2018-04-28T04:37:35
2018-04-28T04:37:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
486
py
import requests from bs4 import BeautifulSoup def jukuu(word): params = { 'q': word } res = requests.get('http://www.jukuu.com/search.php', params=params) soup = BeautifulSoup(res.text, 'html.parser') for c, e in zip(soup.find_all('tr', {'class':'c'}), soup.find_all('tr', {'class':'e'})): yield { 'Chinese': c.text.strip(), 'English': e.text.strip() } if __name__ == '__main__': print(list(jukuu('寒假')))
[ "patarapolw@gmail.com" ]
patarapolw@gmail.com
f721fab446ec3c64e7791814788840c03215dd1d
1979325574fdff56026cac0b654dadfd41574ae1
/src/expts/allinPHS.py
39377f0c20a70cc3dcdc02f18cf0e53a15e76221
[ "Apache-2.0" ]
permissive
daStrauss/subsurface
5e45bac80d64a543c7f02fae83266109698b071f
0277c57aa777196d8e6b7d0a3b3f58c2fd39bab8
refs/heads/master
2021-01-23T12:11:39.043513
2013-07-09T06:21:03
2013-07-09T06:21:03
10,812,381
1
1
null
2016-02-23T09:39:29
2013-06-20T04:44:39
Python
UTF-8
Python
false
false
1,284
py
''' Created on Jan 9, 2013 Copyright © 2013 The Board of Trustees of The Leland Stanford Junior University. 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. @author: dstrauss ''' import numpy as np D = {'solverType':'phaseSplit', 'flavor':'TE', 'numRuns':100, 'expt':'goBig', 'numProcs':16} def getMyVars(parseNumber, D): '''routine to return the parameters to test at the current iteration.''' # noFreqs,noPhis,bkg = np.meshgrid(range(1,7), range(1,7), range(100)) D['freqs'] = np.round(np.logspace(np.log10(1000), np.log10(50000), 100)) D['inc'] = [75.0*np.pi/180.0] # one freq. D['numSensors'] = 20 D['bkgNo'] = parseNumber+100; D['numProcs'] = 100 D['rho'] = 1e-3 D['xi'] = 1e-12 return D
[ "dstrauss85@gmail.com" ]
dstrauss85@gmail.com
44c6d72d5f21383b6d928195d79e3ad79f27b826
5a208abf60e7ca0f7076426e3ec8f37b71883665
/system/storage.py
f9717c7d158eb7e861a5e9c4b61c3cd23c766233
[]
no_license
heynick/weChatIT
c076fd3c05e82c4b09c548b226484768bff9d77c
73911da2d9847b8e759a5ab8cf6d5e4cb54d10aa
refs/heads/master
2021-10-23T08:01:24.326967
2019-03-15T08:39:16
2019-03-15T08:39:16
175,779,792
0
0
null
null
null
null
UTF-8
Python
false
false
877
py
# -*- coding: UTF-8 -*- from django.core.files.storage import FileSystemStorage class ImageStorage(FileSystemStorage): from django.conf import settings def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL): # 初始化 super(ImageStorage, self).__init__(location, base_url) # 重写 _save方法 def _save(self, name, content): import os, time, random # 文件扩展名 ext = os.path.splitext(name)[1] # 文件目录 d = os.path.dirname(name) # 定义文件名,年月日时分秒随机数 fn = time.strftime('%Y%m%d%H%M%S') fn = fn + '_%d' % random.randint(0, 100) # 重写合成文件名 name = os.path.join(d, fn + ext) # 调用父类方法 return super(ImageStorage, self)._save(name, content)
[ "hey.nick@outlook.com" ]
hey.nick@outlook.com
a9824d0d81388e7a1c86015a10f71b7baff98af1
1ab8048dee0b503c9371c7ec47979f6135964262
/src/DenseNet/Model.py
c8e0fc8f4252bf97d15086412dc5b12589890cfa
[]
no_license
MoZhouting/ADDetect
7e60e8970dbf04341a19393740213bd469f3604f
881e49b4e73f0470401f16bd637bc35ebe4db4b1
refs/heads/master
2020-04-26T16:27:41.331473
2018-06-19T05:42:57
2018-06-19T05:42:57
137,845,119
0
1
null
null
null
null
UTF-8
Python
false
false
4,035
py
# coding = 'utf-8' import tensorflow as tf import numpy as np from tensorpack.graph_builder.model_desc import ModelDesc, InputDesc from tensorpack.models.conv2d import Conv2D from tensorpack.models.batch_norm import BatchNorm from tensorpack.models.pool import AvgPooling, GlobalAvgPooling from tensorpack.models.fc import FullyConnected from tensorpack.models.regularize import regularize_cost from tensorpack.tfutils.summary import add_moving_summary, add_param_summary from tensorpack.tfutils.symbolic_functions import prediction_incorrect # 分类数量,训练时酌情修改 _SUBJECT_NUM = 1000 class Model(ModelDesc): def __init__(self, depth): super(Model, self).__init__() self.N = int((depth - 4) / 3) self.growthRate =12 def _get_inputs(self): return [InputDesc(tf.float32, (None, 64, 64, 3), 'input'), InputDesc(tf.int32, (None,), 'label')] def _build_graph(self, input_vars): image, label = input_vars image = image / 128.0 - 1 def conv(name, l, channel, stride): return Conv2D(name, l, channel, 3, stride=stride,nl=tf.identity, use_bias=False, W_init=tf.random_normal_initializer(stddev=np.sqrt(2.0/9/channel))) def add_layer(name, l): shape = l.get_shape().as_list() in_channel = shape[3] with tf.variable_scope(name) as scope: c = BatchNorm('bn1', l) c = tf.nn.relu(c) c = conv('conv1', c, self.growthRate, 1) l = tf.concat([c, l], 3) return l def add_transition(name, l): shape = l.get_shape().as_list() in_channel = shape[3] with tf.variable_scope(name) as scope: l = BatchNorm('bn1', l) l = tf.nn.relu(l) l = Conv2D('conv1', l, in_channel, 1, stride=1, use_bias=False, nl=tf.nn.relu) l = AvgPooling('pool', l, 2) return l def dense_net(name): l = conv('conv0', image, 16, 1) with tf.variable_scope('block1') as scope: for i in range(self.N): l = add_layer('dense_layer.{}'.format(i), l) l = add_transition('transition1', l) with tf.variable_scope('block2') as scope: for i in range(self.N): l = add_layer('dense_layer.{}'.format(i), l) l = add_transition('transition2', l) with tf.variable_scope('block3') as scope: for i in range(self.N): l = add_layer('dense_layer.{}'.format(i), l) l = BatchNorm('bnlast', l) l = tf.nn.relu(l) l = GlobalAvgPooling('gap', l) l = FullyConnected('feature', l, out_dim=2048, nl=tf.identity) logits = FullyConnected('linear', l, out_dim=_SUBJECT_NUM, nl=tf.identity) return logits logits = dense_net("dense_net") prob = tf.nn.softmax(logits, name='output') cost = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label) cost = tf.reduce_mean(cost, name='cross_entropy_loss') wrong = prediction_incorrect(logits, label) # monitor training error add_moving_summary(tf.reduce_mean(wrong, name='train_error')) # weight decay on all W wd_cost = tf.multiply(1e-4, regularize_cost('.*/W', tf.nn.l2_loss), name='wd_cost') add_moving_summary(cost, wd_cost) add_param_summary(('.*/W', ['histogram'])) # monitor W self.cost = tf.add_n([cost, wd_cost], name='cost') def _get_optimizer(self): lr = tf.get_variable('learning_rate', initializer=0.1, trainable=False) tf.summary.scalar('learning_rate', lr) return tf.train.MomentumOptimizer(lr, 0.9, use_nesterov=True) if __name__ == '__main__': pass
[ "1090898535@qq.com" ]
1090898535@qq.com
0698c99303800807bd68f06413f3d56b2238d786
ba2fa46d365a8aaf4db689dbcece501eceb4021d
/DSA/array/REVERSE ARRAY/bySlice.py
2a6d03393db81d44e871baa51a0830a0c3358719
[]
no_license
itzsoumyadip/DSA
81283fb6197d49c242784711d4768230f9ada24d
97188f11b88ed6097679f7ab0682dc3c1c7424f0
refs/heads/main
2022-12-29T23:40:47.051109
2020-10-23T10:17:07
2020-10-23T10:17:07
306,034,999
1
0
null
null
null
null
UTF-8
Python
false
false
194
py
#Using Python List slicing def reverseList(A): print( A[::-1]) # Driver function to test above function A = [1, 2, 3, 4, 5, 6] print(A) print("Reversed list is") reverseList(A)
[ "noreply@github.com" ]
noreply@github.com
296283618e61a02a6f6c8c8516a5ae54f984803f
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02766/s873846892.py
1b5165713fefb3469a152f09d2a75411c31b81ee
[]
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
241
py
def main(): N, K = map(int, input().split()) ans = base10to(N, K) print(len(ans)) def base10to(n, b): if (int(n/b)): return base10to(int(n/b), b) + str(n%b) return str(n%b) if __name__ == '__main__': main()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
b9b94499cb2c65d677f9882700d36123591c641a
1888c630bed201cf97e4f047c7392270dfba749f
/scripts/utils.py
7e50f55f1375ab308e989d7fd7b94ff40562385e
[]
no_license
matchVote/matchvote_ops
ba4ca38df087db61adeb8cadf5b6ed2fc4100e3d
20f00763f43f99ad00ad8e294ec3a15701cf922b
refs/heads/master
2023-03-31T15:18:55.159226
2019-12-23T16:13:55
2019-12-23T16:13:55
103,915,269
0
0
null
2021-03-25T21:42:29
2017-09-18T08:49:41
Python
UTF-8
Python
false
false
163
py
from contextlib import contextmanager import sys @contextmanager def log(message): print(message, end='') sys.stdout.flush() yield print('Done')
[ "jimbonkgit@gmail.com" ]
jimbonkgit@gmail.com
feb03a00a8935db7f4557b8168f6365946ed2470
7479c35c5e3290a24892237871b9ff0c67554892
/mycoffee/admin.py
f8482772d211e93c9a2fcd9b28a0f6a11df8d8ca
[]
no_license
waed123/PrimeRose-Coffee
974e1267f67300b8daccb6ec0ac91a5beccc7ae2
7b8cb9b37177bba0da45a9c8c254c1425d03a3a3
refs/heads/master
2021-08-28T15:02:15.015045
2017-12-12T14:31:34
2017-12-12T14:31:34
113,331,896
0
0
null
null
null
null
UTF-8
Python
false
false
227
py
from django.contrib import admin from .models import Bean, Roast, Syrup, Powder, Coffee admin.site.register(Bean) admin.site.register(Roast) admin.site.register(Syrup) admin.site.register(Powder) admin.site.register(Coffee)
[ "waed@AUBs-MacBook-Pro.local" ]
waed@AUBs-MacBook-Pro.local
c35530d38480de046393b7f5b8eeaa544d902652
34bec6ee7a2e5c6ae90e8b646b34cfaa58bf65bb
/network/embedding.py
b8074b3f7088af7ab2eafb1a9c8058e887e2e744
[]
no_license
ninjatrick/Factored-Neural-Network
b5d68ad6e40bf17397268f76f4abd84f9257bfd1
d7139b78c47019107314174aa10bc9a778198c6f
refs/heads/master
2020-03-26T00:38:45.730539
2018-08-24T06:24:27
2018-08-24T06:24:27
144,329,793
0
0
null
null
null
null
UTF-8
Python
false
false
3,608
py
import tensorflow as tf import numpy as np FLAGS = tf.app.flags.FLAGS class Embedding(object): def __init__(self, is_training, word_vec,pos_vec, word, pos1, pos2,pos3): temp_word_embedding = tf.get_variable(initializer=word_vec, name = 'temp_word_embedding', dtype=tf.float32) unk_word_embedding = tf.get_variable('unk_embedding', [FLAGS.word_size], dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer()) self.word_vec = tf.concat([temp_word_embedding, tf.reshape(unk_word_embedding, [1, FLAGS.word_size]), tf.reshape(tf.constant(np.zeros([FLAGS.word_size], dtype=np.float32)), [1, FLAGS.word_size])], 0) temp_pos_embedding = tf.get_variable(initializer=pos_vec, name = 'temp_pos_embedding', dtype=tf.float32) unk_pos_embedding = tf.get_variable('UNK_embedding', [FLAGS.word_size], dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer()) self.pos_vec = tf.concat([temp_pos_embedding, tf.reshape(unk_pos_embedding, [1, FLAGS.word_size]), tf.reshape(tf.constant(np.zeros([FLAGS.word_size], dtype=np.float32)), [1, FLAGS.word_size])], 0) self.word = word self.pos1 = pos1 self.pos2 = pos2 self.pos3 = pos3 self.is_training = is_training def word_embedding(self, var_scope = None, reuse = False): with tf.variable_scope(var_scope or 'word_embedding', reuse = reuse): x = tf.nn.embedding_lookup(self.word_vec, self.word) return x def tag_embedding(self, var_scope = None, reuse = False): with tf.variable_scope(var_scope or 'tag_embedding', reuse = reuse): x = tf.nn.embedding_lookup(self.pos_vec, self.word) return x def pos_embedding(self, simple_pos=False): with tf.name_scope("pos_embedding"): if simple_pos: temp_pos_array = np.zeros((FLAGS.pos_num + 1, FLAGS.pos_size), dtype=np.float32) temp_pos_array[(FLAGS.pos_num - 1) / 2] = np.ones(FLAGS.pos_size, dtype=np.float32) pos1_embedding = tf.constant(temp_pos_array) pos2_embedding = tf.constant(temp_pos_array) else: temp_pos1_embedding = tf.get_variable('temp_pos1_embedding', [FLAGS.pos_num, FLAGS.pos_size], dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer()) pos1_embedding = tf.concat([temp_pos1_embedding, tf.reshape(tf.constant(np.zeros(FLAGS.pos_size, dtype=np.float32)), [1, FLAGS.pos_size])], 0) temp_pos2_embedding = tf.get_variable('temp_pos2_embedding', [FLAGS.pos_num, FLAGS.pos_size], dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer()) pos2_embedding = tf.concat([temp_pos2_embedding, tf.reshape(tf.constant(np.zeros(FLAGS.pos_size, dtype=np.float32)), [1, FLAGS.pos_size])], 0) input_pos1 = tf.nn.embedding_lookup(pos1_embedding, self.pos1) input_pos2 = tf.nn.embedding_lookup(pos2_embedding, self.pos2) x = tf.concat(values = [input_pos1, input_pos2], axis = 2) return x def concat_embedding(self, word_embedding, pos_embedding, tag_embedding): if pos_embedding is None: x = tf.concat(values = [tag_embedding,word_embedding], axis = 2) return x else: x = tf.concat(values = [tag_embedding,word_embedding], axis = 2) return tf.concat(values = [x, pos_embedding], axis = 2)
[ "noreply@github.com" ]
noreply@github.com
f472b761fec7406623071220b5224871d1110572
1cce4bbf7e6719661e63a05a10e6ca1022f2fc28
/briana_bennett/django_FS/courses/courses_app/urls.py
225ab6d618c92aa38a55cf90c8f9e73b697a0cdd
[]
no_license
mthwtkr/python_april_2017
f85ff49ff27e5ccf677da9a9dadce0b26af66b79
974d2e78ecb0fb9f03cbd4af3f935ed55e2c7545
refs/heads/master
2021-06-18T01:05:40.783921
2017-06-17T17:17:29
2017-06-17T17:17:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
263
py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^create$', views.create), url(r'^courses/(?P<id>\d+)/delete$', views.delete_page), url(r'^courses/(?P<id>\d+)/destroy$', views.destroy_or_not), ]
[ "bri.bennett89@gmail.com" ]
bri.bennett89@gmail.com
068d8dce5daa9ac6705c8b77bd447240a513c227
a38bf459ae380f67e0de22f7106a8df4385a7076
/tests/integration/goldens/logging/samples/generated_samples/logging_v2_generated_config_service_v2_list_views_sync.py
b273c465d3ec976b018c54a7b83e2a4218b81327
[ "Apache-2.0" ]
permissive
googleapis/gapic-generator-python
73ce9d52f6f5bb2652d49b237b24263d6637b1da
4eee26181e8db9fb5144eef5a76f178c1594e48a
refs/heads/main
2023-09-04T11:12:14.728757
2023-09-02T10:34:44
2023-09-02T10:34:44
129,809,857
116
65
Apache-2.0
2023-09-12T18:57:01
2018-04-16T21:47:04
Python
UTF-8
Python
false
false
1,852
py
# -*- coding: utf-8 -*- # Copyright 2023 Google LLC # # 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. # # Generated code. DO NOT EDIT! # # Snippet for ListViews # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-logging # [START logging_v2_generated_ConfigServiceV2_ListViews_sync] # This snippet has been automatically generated and should be regarded as a # code template only. # It will require modifications to work: # - It may require correct/in-range values for request initialization. # - It may require specifying regional endpoints when creating the service # client as shown in: # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import logging_v2 def sample_list_views(): # Create a client client = logging_v2.ConfigServiceV2Client() # Initialize request argument(s) request = logging_v2.ListViewsRequest( parent="parent_value", ) # Make the request page_result = client.list_views(request=request) # Handle the response for response in page_result: print(response) # [END logging_v2_generated_ConfigServiceV2_ListViews_sync]
[ "noreply@github.com" ]
noreply@github.com
bfac869f0436a17893a452f29634f8a5de14a7c7
3c2dcf75aab54af8e621d53b2c66dbca6bbc70de
/Lc_solution_in_python/0966.py
80de192dcd34cad900a2a150f72ad4c3ccf7948b
[]
no_license
Chenlei-Fu/Interview-Preperation
2169cbd4409dff78590d0ce1d842f1840abea9f3
5dc755560b453d852cc56855515f03a2c69e921a
refs/heads/master
2023-07-08T11:03:39.069933
2021-08-24T02:56:29
2021-08-24T02:56:29
366,813,424
2
0
null
null
null
null
UTF-8
Python
false
false
904
py
class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: """ the trick is vowel part since the vowels ('a', 'e', 'i', 'o', 'u') can be replaced they can be translated into * """ def translate(word): return ''.join('*' if c in 'aeiou' else c for c in word.lower()) def check(word): if word in wordSet: return word word_lower = word.lower() word_vowel = translate(word) if word_lower in capi: return capi[word_lower] if word_vowel in vowel: return vowel[word_vowel] return '' wordSet = set(wordlist) capi = {w.lower() :w for w in wordlist[::-1]} vowel = {translate(w): w for w in wordlist[::-1]} return [check(w) for w in queries]
[ "chenlei.fu@outlook.com" ]
chenlei.fu@outlook.com
b6e77859e8bbd31e695a444d619c0d2c0cdd7b2b
2965ef9b397ff45748d9dbdb4aa7aada275c52c7
/airflow_blog_dag.py
9ec6e4040c7e4cf394f6fde9afd5901a8f19cb35
[]
no_license
caglarkeskin/airflow_blog_example
a2dc95bf2a8068140db4de3e710f56b377384484
72dae7f9fa2ae16211d9293603313a5fbc753337
refs/heads/main
2023-04-06T18:02:31.205534
2021-04-11T19:11:03
2021-04-11T19:11:03
356,876,498
0
0
null
null
null
null
UTF-8
Python
false
false
1,738
py
from airflow.example_dags.spider import Cls from datetime import timedelta from airflow import DAG from airflow.operators.bash import BashOperator from airflow.operators.python import PythonOperator from airflow.utils.dates import days_ago spider = Cls.spider read_db = Cls.read_db db_to_s3 = Cls.db_to_s3 report = Cls.db_to_s3 default_args = { 'owner': 'airflow', 'depends_on_past': False, 'email': ['airflow@example.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=5), # 'queue': 'bash_queue', # 'pool': 'backfill', # 'priority_weight': 10, # 'end_date': datetime(2016, 1, 1), # 'wait_for_downstream': False, # 'dag': dag, # 'sla': timedelta(hours=2), # 'execution_timeout': timedelta(seconds=300), # 'on_failure_callback': some_function, # 'on_success_callback': some_other_function, # 'on_retry_callback': another_function, # 'sla_miss_callback': yet_another_function, # 'trigger_rule': 'all_success' } dag = DAG( 'blog_example', default_args=default_args, description='Example dag for airflow blog', schedule_interval="0 10 * * *", start_date=days_ago(2), tags=['example'], ) p1 = PythonOperator( task_id='spider', python_callable=spider, dag=dag, ) p2 = PythonOperator( task_id='read_db', python_callable=read_db, dag=dag, ) p3 = PythonOperator( task_id='db_to_s3', python_callable=db_to_s3, dag=dag, ) p4 = PythonOperator( task_id='report', python_callable=report, dag=dag, ) b1 = BashOperator( task_id='log', bash_command='echo "DAG basarili" > logfile.txt', dag=dag, ) p1 >> p2 >> p3 >> p4 >> b1
[ "caglar.keskin@zingat.com" ]
caglar.keskin@zingat.com
fdacb5b821ae1e0631dd4fb0cba3ca063ba60457
74264a37ad1b8e4bbdc1069edf7301b7f88dfecf
/eigen_pair.py
37e9b7263d68e74f4ddda50c698342b85b39c637
[]
no_license
JakeStubbs4/MTHE-493
89aceb507bcad52f52e199672af0f0c3de043409
5228ea157f94eb9ce0daff9866cd9a0a390ba8a4
refs/heads/master
2020-08-30T10:50:57.178588
2020-04-02T05:48:54
2020-04-02T05:48:54
218,356,612
1
0
null
2020-01-21T15:14:35
2019-10-29T18:32:37
Python
UTF-8
Python
false
false
259
py
class EigenPair: eigen_value = None magnitude = None eigen_vector = None def __init__(self, eigen_value, eigen_vector): self.eigen_value = eigen_value self.magnitude = abs(eigen_value) self.eigen_vector = eigen_vector
[ "jmichaelt98@gmail.com" ]
jmichaelt98@gmail.com
f230add663cb646c6a58b790057e3589310fff4a
d2a128ac5e73affa7baed75f8a76b3f9f30bea30
/spiders.py
1d596a902f100c54920345d2136dcb849d68dda9
[]
no_license
EEEEEEEEEEEEEEEEEEEIEEEEEEEEEEEEEEEEEE/Free_proxy_pool
11049451f2123bf12af2e50cc83cc888a7948ca7
1eb2318262a59830be46ac07e7766e29bfe76b2d
refs/heads/master
2021-07-16T22:38:44.724117
2017-10-23T03:50:08
2017-10-23T03:50:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,996
py
# -*- coding: utf-8 -*- ''' @author: yaleimeng@sina.com (C) Copyright 2017. @desc: 爬虫类。为代理池提供抓取代理IP功能。 @DateTime: Created on 2017/10/16,at 8:47 ''' import chardet, re, time import requests as rq from bs4 import BeautifulSoup as bs class Proxy_Spider(object): proxies_got = set() def request_page(cls, page, proxy=None, wait=2): head = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,' ' like Gecko) Chrome/55.0.2883.75 Safari/537.36'} try: r = rq.get(page, headers=head, proxies=proxy, timeout=wait) r.encoding = chardet.detect(r.content)['encoding'] return bs(r.text, 'lxml') except Exception: print('……无法获取网页。', end='\t') return None def crawl(self): self.__get_seo_FangFa() # 总量380左右。每分钟更新。 self.__get_code_busy() # 总量550上下。15到20分钟更新一次。 self.__get_Ai_Jia() # 6篇文章总量500多。每小时更新1篇文章。 # self.__get_All66() # 数量自定义。抓取到的代理越多,验证用时越长。 # self.__get_All89() # 考虑验证耗时因素,后面几个可以选择性启用。 # self.__get_kai_xin() # 每小时更新一篇文章,100个代理。 return self.proxies_got def crawl_for_init(self): self.__get_code_busy() # 更新很频繁,适合初次启动时更新一下。 self.__get_qq_room() # 该站每天更新一次,只适合在第一次启动时更新。不需要反复运行 return self.proxies_got def __rows_from(self, url, exp=None): # 从网页表格中提取,seo方法、codeBusy采用了这种方式。 express = 'table tbody tr' if exp is None else exp soup = self.request_page(url, wait=3) return None if soup is None else soup.select(express) def __get_seo_FangFa(self): for info in self.__rows_from('http://ip.seofangfa.com/'): item = info.select('td') address = item[0].text + ':' + item[1].text if address not in self.proxies_got: self.proxies_got.add(address) print('已采集seoFF,代理池IP总数:', len(self.proxies_got)) def __get_code_busy(self): urls = ['https://proxy.coderbusy.com/zh-cn/classical/anonymous-type/highanonymous/' 'p{}.aspx'.format(str(i)) for i in range(1, 12)] for url in urls: for info in self.__rows_from(url): item = info.select('td') address = item[0].text.strip() + ':' + item[1].text[16:-3] if address not in self.proxies_got: self.proxies_got.add(address) time.sleep(0.8) print('已采集code_busy,代理池IP总数:', len(self.proxies_got)) def __parse_by_re(self, url, reg_exp=re.compile('\w+\.\w+\.\w+\.\w+:\w+')): # 正则提取, 66ip、89ip、QQ_room、开心代理采用了这种解析方式 article = None if self.request_page(url) is None else self.request_page(url).__unicode__() return reg_exp.findall(article) def __get_All66(self): urls = ['http://www.66ip.cn/nmtq.php?getnum=300&isp=0&anonymoustype={}&start=&ports=&export=&ipaddress=' '&area=1&proxytype=0&api=66ip '.format(str(i)) for i in range(3, 5)] # 采集国内的,高匿、超匿2种HTTP代理。如果想采集国外的,area改为2。【如果要采集HTPPS,proxytpye = 1 】 for url in urls: self.proxies_got.update(self.__parse_by_re(url)) # 把找到的代理IP添加到集合里面 print('已采集66ip.cn,代理池IP总数:', len(self.proxies_got)) time.sleep(1.1) def __get_All89(self): url = 'http://www.89ip.cn/tiqv.php?sxb=&tqsl=400&ports=&ktip=&xl=on&submit=%CC%E1++%C8%A1' find_out = self.__parse_by_re(url) self.proxies_got.update(find_out) print('已采集89ip.cn,代理池IP总数:', len(self.proxies_got)) def __get_qq_room(self): page_list, output = [], set() host = 'http://ip.qqroom.cn/' news = self.request_page(host).select('section.article-list h2 a') # 标题必须包含‘代理ip’ for info in news: if info.text.__contains__('代理ip'): page_list.append(host + info.get('href')) ip_exp = re.compile('\d+\.\d+\.\d+\.\d+:\d+') # 文字描述太多。不能使用\w代替。 for page in page_list[:2]: # 只收集包含"代理ip"的前2篇文章 self.proxies_got.update(self.__parse_by_re(page, ip_exp)) print('已采集QQ_room,代理池IP总数:', len(self.proxies_got)) time.sleep(0.8) def __get_kai_xin(self): page_list = [] soup = self.request_page('http://www.kxdaili.com/daili.html') news = soup.select('div.clear_div > div.ui a')[:9:2] # 获取最新的5篇文章。 for info in news: link = 'http://www.kxdaili.com' + info.get('href') page_list.append(link) for page in page_list: self.proxies_got.update(self.__parse_by_re(page)) print('已采集开心代理,代理池IP总数:', len(self.proxies_got)) time.sleep(0.8) def __get_Ai_Jia(self): # 爱家网,每小时更新国内国外代理IP。可用率不成。 page_list = [] soup = self.request_page('http://www.ajshw.net/news/?list_9.html') for info in soup.select('dd.listBox5')[0].select('a')[:6]: # 国内代理最新的6篇文章。 link = 'http://www.ajshw.net' + info.get('href')[2:] # href开头有两个点..,要去掉。 page_list.append(link) def get_txt(cipher): # 邮箱混淆解密函数。 begin, out = cipher[:2], '' for n in range(4, len(cipher) + 1, 2): r = int(begin, 16) ^ int(cipher[n - 2:n], 16) if 57 < r: break # 这样后面第一次遇到@时就结束循环,返回结果。 out += chr(r) return out ip_exp = re.compile('\d+\.\w+\.\w+\.\w+:') for page in page_list: soup, ports = self.request_page(page), [] address = soup.select('div#newsContent p')[0] ips = ip_exp.findall(address.text) for pot in self.__rows_from(page, 'div#newsContent p a'): ports.append(get_txt(pot['data-cfemail'])) proxies = [a + b for a, b in zip(ips, ports)] # 要确保ip与端口一一对应。 self.proxies_got.update(proxies) print('已采集ajshw,代理池IP总数:', len(self.proxies_got)) time.sleep(0.8)
[ "noreply@github.com" ]
noreply@github.com
b6d2755a36f48a61ed029eb35bd4add95a9a0fc2
c343eb7934cb5e4aa7de1bf7fcbb914546b31f96
/glusterfsrest/fs/lock.py
fbef2691b50e6555101f104eed6f76299d593a87
[]
no_license
farfou/glusterfs-rest
1fa96ce0edcdf150cf79a02435044a44979eb586
2b9c299737c11eb483a1e8e78ebb1ebdc28c8823
refs/heads/master
2021-01-18T01:26:04.352485
2016-03-05T22:35:02
2016-03-06T11:46:39
53,226,576
0
0
null
2016-03-05T22:33:15
2016-03-05T22:33:15
null
UTF-8
Python
false
false
823
py
from threading import Lock as threading_Lock storlever_lock_factory = threading_Lock # default is threading.Lock def set_lock_factory(lock_factory): """set lock factory for storlever This lock should has a context interface(support "with") """ global storlever_lock_factory storlever_lock_factory = lock_factory def set_lock_factory_from_name(module_path_name, factory_func_name): """another version of set_lock_factory use the module name the function name instead of the function object """ global storlever_lock_factory storlever_lock_factory = \ getattr(__import__(module_path_name, fromlist=[factory_func_name]), factory_func_name) def lock(): """return a lock object support context for storlever""" return storlever_lock_factory()
[ "fabien.alin@gmail.com" ]
fabien.alin@gmail.com
22b0d7305194d18157b442fd91971e5029a6d26e
3587a975786bb743c13603f4ad28ed2bac2c18d5
/Python/Exercise/ex28.py
1565a2a852a20e598b627ce630b103f67d9883af
[]
no_license
Joycici/Coding
378ee84b8a172e0bf23cb2fbd61a61b4e2312927
c3975017c3aeaa54e94fea3a19befbfc352e2e20
refs/heads/master
2021-04-29T07:36:21.359565
2017-02-21T15:23:43
2017-02-21T15:23:43
77,978,547
0
0
null
null
null
null
UTF-8
Python
false
false
2,786
py
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' Exercise 28: Boolean Practice This practice should be running on python shell, so there is no coding on this Or, we can use print to show results. ''' """ __author='Joycici' __version__='1.0' """ print "The result should be True, isn't it? Type the result: %r" % (True and True) print "The result should be False, isn't it? Type the result: %r" % (False and True) print "The result should be False, isn't it? Type the result: %r" % (1 == 1 and 2 == 1) print "The result should be True, isn't it? Type the result: %r" % ("test" == "test") print "The result should be True, isn't it? Type the result: %r" % (1 == 1 and 2 != 1) print "The result should be True, isn't it? Type the result: %r" % (True and 1 == 1) print "The result should be False, isn't it? Type the result: %r" % (False and 0 != 0) print "The result should be True, isn't it? Type the result: %r" % (True or 1 == 1) print "The result should be False, isn't it? Type the result: %r" % ("test" == "testing") print "The result should be False, isn't it? Type the result: %r" % (1 != 0 and 2 == 1) print "The result should be True, isn't it? Type the result: %r" % ("test" != "testing") print "The result should be False, isn't it? Type the result: %r" % ("test" == 1) print "The result should be True, isn't it? Type the result: %r" % (not (True and False)) print "The result should be False, isn't it? Type the result: %r" % (not (1 == 1 and 0 != 1)) print "The result should be False, isn't it? Type the result: %r" % (not (10 == 1 or 1000 == 1000)) print "The result should be True, isn't it? Type the result: %r" % (not ("testing" == "testing" and "Zed" == "Cool Guy")) print "The result should be True, isn't it? Type the result: %r" % (1 == 1 and (not ("testing" == 1 or 1 == 0))) print "The result should be False, isn't it? Type the result: %r" % ("chunky" == "bacon" and (not (3 == 4 or 3 == 3))) print "The result should be False, isn't it? Type the result: %r" % (3 == 3 and (not ("testing" == "testing" or "Python" == "Fun"))) # 附加题 ''' == 等于!= 不等于>= 大于等于 <= 小于等于 ''' ''' python和很多语言可以返回布尔表达式中的一个操作数,而不仅仅是真或假。 这意味着如果你计算False and 1 你会得到表达式的第一个操作数 (False) , 但是如果你计算True and 1的时候,你得到它的第二个操作数(1)。试一试吧。 ''' print "test" and "test" #返回test print "test" and 1 #返回1 print 1 and "test" #返回test print True and 1 # 1 print 1 and True # true print False and 1 # false print 1 and False # false print 0 and True # 0 print True and 0 #0 print 0 and False #0 print False and 0 #false ???为什么不是0? print 1 or False # 返回1 print 0 or False # false
[ "xuci123@qq.com" ]
xuci123@qq.com
6cbec5e2430ea9ccfe0c2fe991f77e6418b25aff
fb942ec75797204fbe4a5b0e292797d5c76e4272
/yatube_api/settings.py
ecf707054678490423a6403c9ab64e13c61870cc
[]
no_license
hexhowk/api_final_yatube
682f64367a0437a245a5da4f4923e78b649764bd
57f0d6dd857ff808089a866f796171dab46c6eb1
refs/heads/master
2022-05-20T07:09:32.376754
2020-04-29T00:56:53
2020-04-29T00:56:53
259,788,547
0
0
null
null
null
null
UTF-8
Python
false
false
2,293
py
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'hhz7l-ltdismtf@bzyz+rple7*s*w$jak%whj@(@u0eok^f9k4' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', ] 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 = 'yatube_api.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'yatube_api.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } 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', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static/'),) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], }
[ "57973073+Rimmini@users.noreply.github.com" ]
57973073+Rimmini@users.noreply.github.com
8043bf4f0fcdecc59ee5421189b23a4884fc8599
ac5e52a3fc52dde58d208746cddabef2e378119e
/exps-sblp/sblp_ut=3.5_rd=0.65_rw=0.04_rn=4_u=0.075-0.325_p=harmonic-2/sched=RUN_trial=30/params.py
d0a52d0abffd2812cb65883935448f5d49c0ec13
[]
no_license
ricardobtxr/experiment-scripts
1e2abfcd94fb0ef5a56c5d7dffddfe814752eef1
7bcebff7ac2f2822423f211f1162cd017a18babb
refs/heads/master
2023-04-09T02:37:41.466794
2021-04-25T03:27:16
2021-04-25T03:27:16
358,926,457
0
0
null
null
null
null
UTF-8
Python
false
false
251
py
{'cpus': 4, 'duration': 30, 'final_util': '3.528333', 'max_util': '3.5', 'periods': 'harmonic-2', 'release_master': False, 'res_distr': '0.65', 'res_nmb': '4', 'res_weight': '0.04', 'scheduler': 'RUN', 'trial': 30, 'utils': 'uni-medium-3'}
[ "ricardo.btxr@gmail.com" ]
ricardo.btxr@gmail.com
12b340cd3ef8ebe5393bbdda0a5384ff90b2db85
07af7ff63c39f07441f0aeee401b6adb2a964b2d
/Model/XGBoost/lightgbm_model.py
0e7c2ce4e4b1ed5970f5e4dc0e2ffeb85daa0748
[]
no_license
LuckyTiger123/TimeSeries
aa4b5de5dfc9e871f1f3dbc4c3e32b9b633c196e
350515a1f6912dac196eb76ec697cbd17fae5b98
refs/heads/main
2023-02-19T13:31:25.894511
2021-01-10T08:07:25
2021-01-10T08:07:25
313,842,543
0
0
null
null
null
null
UTF-8
Python
false
false
4,357
py
import os import time import lightgbm as lgb import pandas as pd import numpy as np train_data = pd.DataFrame() train_label = pd.DataFrame() test_data = pd.DataFrame() test_label = pd.DataFrame() # define sample proportion proportion = 4 g = os.walk('/data/luckytiger/shengliOilWell/train_data') for _, _, file_list in g: for file in file_list: item = pd.read_excel('/data/luckytiger/shengliOilWell/train_data/{}'.format(file)) t_level_item = item[item['level'] != 60] t_no_level_item = item[item['level'] == 60].sample(int(t_level_item.shape[0] * proportion), replace=True) item = pd.concat([t_level_item, t_no_level_item], ignore_index=True) # t_input = item[['DEPTH', 'Por', 'Perm', 'AC', 'SP', 'COND', 'ML1', 'ML2']] # t_input = item[['Por', 'Perm', 'AC', 'SP', 'COND', 'ML1', 'ML2']] t_input = item[['DEPTH', 'AC', 'SP', 'COND', 'ML1', 'ML2']] # t_input['ML2'] = t_input['ML2'] / t_input['ML2'].mean() t_input['Well'] = file[:2] t_output = item['level'] t_output.loc[t_output != 60] = 61 # change to 2 class t_output = t_output - 60 train_data = pd.concat([train_data, t_input], ignore_index=True) train_label = pd.concat([train_label, t_output], ignore_index=True) print('read in train file {}'.format(file)) t = os.walk('/data/luckytiger/shengliOilWell/test_data') for _, _, file_list in t: for file in file_list: item = pd.read_excel('/data/luckytiger/shengliOilWell/test_data/{}'.format(file)) # t_input = item[['DEPTH', 'Por', 'Perm', 'AC', 'SP', 'COND', 'ML1', 'ML2']] # t_input = item[['Por', 'Perm', 'AC', 'SP', 'COND', 'ML1', 'ML2']] t_input = item[['DEPTH', 'AC', 'SP', 'COND', 'ML1', 'ML2']] # t_input = t_input / t_input.mean() t_input['Well'] = file[:2] t_output = item['level'] t_output.loc[t_output != 60] = 61 # change to 2 class t_output = t_output - 60 test_data = pd.concat([test_data, t_input], ignore_index=True) test_label = pd.concat([test_label, t_output], ignore_index=True) print('read in test file {}'.format(file)) np_train_input = np.array(train_data) np_train_output = np.array(train_label) np_train_output = np_train_output.flatten() np_test_input = np.array(test_data) np_test_output = np.array(test_label) np_test_output = np_test_output.flatten() params = { 'objective': 'multiclass', 'num_class': 2, 'max_depth': 6, 'num_threads': 4, # 'device_type': 'gpu', 'seed': 0, 'min_split_gain': 0.1, 'bagging_fraction': 0.7, 'feature_fraction': 0.7, 'lambda_l2': 2 } dtrain = lgb.Dataset(np_train_input, label=np_train_output) num_round = 50 bst = lgb.train(params, dtrain, num_round) file_flag = str(time.time()).replace('.', "_") bst.save_model('/data/luckytiger/shengliOilWell/train_result/model/xgboost/{}.model'.format(file_flag)) ans = bst.predict(np_test_input) ans = np.argmax(ans, axis=1) level_count = 0 no_level_count = 0 total_count = 0 level_correct_count = 0 no_level_correct_count = 0 total_correct_count = 0 for i in range(len(np_test_output)): if np_test_output[i] == 1: level_count += 1 if np_test_output[i] == ans[i]: level_correct_count += 1 total_correct_count += 1 elif np_test_output[i] == 0: no_level_count += 1 if np_test_output[i] == ans[i]: no_level_correct_count += 1 total_correct_count += 1 total_count += 1 level_acc = level_correct_count / level_count no_level_acc = no_level_correct_count / no_level_count total_acc = total_correct_count / total_count print('Model name:{}.model'.format(file_flag)) print('level acc:{} . no level acc:{} . total acc:{} .'.format(level_acc, no_level_acc, total_acc)) # total TP = FN = FP = TN = 0 for i in range(len(np_test_output)): if np_test_output[i] == 1 and ans[i] == 1: TP += 1 elif np_test_output[i] == 1 and ans[i] == 0: FN += 1 elif np_test_output[i] == 0 and ans[i] == 1: FP += 1 elif np_test_output[i] == 0 and ans[i] == 0: TN += 1 precision = TP / (TP + FP) recall = TP / (TP + FN) print('precision:{} . recall:{} .'.format(precision, recall)) print('f1:{} .'.format(2 * precision * recall / (precision + recall)))
[ "747837496@qq.com" ]
747837496@qq.com
86235f3224799eb00ea074017b73aa199c9f3ccc
86510b47b768d80127adcbd53b06fdff58fd95a4
/python/problem_010.py
c20fb3db3973ee559120b86ea5f3fdacea78b2cd
[]
no_license
Kimbsy/project-euler
d018ad759ae599147e11431f818c9bfd3fc82f73
e1eda2779b6499a6d33a848eacc5e1c15405bf70
refs/heads/master
2021-08-27T16:22:19.167892
2021-08-16T17:09:08
2021-08-16T17:09:08
50,948,043
0
0
null
null
null
null
UTF-8
Python
false
false
379
py
import math """The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ def is_prime(num): for i in range(2, int(math.sqrt(num)) + 1): if num % i is 0: return False return True target = 2000000 total = 2 for i in range(3, target, 2): if is_prime(i): total = total + i print(total)
[ "lordkimber@gmail.com" ]
lordkimber@gmail.com
9fded41e53994926b9987688f2a0c3d676ccb209
869447f4d4ab7620dc71c01d97f4a45b67ef7080
/custom_py/validate_rate.py
91f61320f63d8e7a42818e49e58dbdd418659ed0
[]
no_license
gsnbng/gsn_erpnext_fixtures
1daf08d81489a22a7c8d6471be2c07175474ebbd
3f84b25979208485f7c40e95cd711a97e4b2fce5
refs/heads/master
2020-04-17T11:05:55.090160
2016-12-12T15:04:52
2016-12-12T15:04:52
66,152,624
0
0
null
null
null
null
UTF-8
Python
false
false
1,926
py
from __future__ import unicode_literals import frappe from frappe.utils import cint, formatdate, flt, getdate from frappe import _, throw from erpnext.setup.utils import get_company_currency import frappe.defaults import ast import logging import string import datetime import re import json from frappe.utils import getdate, flt,validate_email_add,cint from frappe.model.naming import make_autoname from frappe.model.document import Document from frappe.model.mapper import get_mapped_doc from erpnext.controllers.status_updater import StatusUpdater class CustomError(Exception): pass @frappe.whitelist() def call_me(kwargs): if isinstance(kwargs, basestring): doc = frappe.get_doc(json.loads(kwargs)) frappe.msgprint(doc.doctype) #frappe.throw(_("xyz")) @frappe.whitelist() def validate_rate_with_reference_doc(kwargs): ref_details=[["Purchase Order", "purchase_order", "po_detail"],["Purchase Receipt", "purchase_receipt","pr_detail"]] if isinstance(kwargs, basestring): doc = frappe.get_doc(json.loads(kwargs)) for ref_dt, ref_dn_field, ref_link_field in ref_details: for d in doc.get("items"): if d.get(ref_link_field): ref_rate = frappe.db.get_value(ref_dt + " Item", d.get(ref_link_field), "rate") if (flt(d.rate - ref_rate)) > 0: #frappe.throw(_("{0}").format(ref_rate)) #frappe.throw(_("Row #{0}: Rate is more than {1}: {2} rate ({3} / {4}) ") # .format(d.idx, ref_dt, d.get(ref_dn_field), d.rate, ref_rate)) doc_rt=d.rate itemx=d.idx chk=1 return (itemx,ref_dt, doc_rt,ref_rate,chk)
[ "sheshanarayanag@gmail.com" ]
sheshanarayanag@gmail.com
7e3a97d42210041be00fe78eac7fdc797d8027a2
e74e89592d8a3b1a0b465a7b1595708b224362d2
/pset_pandas1_wine_reviews/data_cleaning/solutions/p8.py
3d5b21f733b7e5400eea8fc4cc02f3214b41120a
[ "MIT" ]
permissive
mottaquikarim/pydev-psets
016f60f1e9d9a534bd9a66ecde8eb412beee37d1
9749e0d216ee0a5c586d0d3013ef481cc21dee27
refs/heads/master
2023-01-10T11:15:57.041287
2021-06-07T23:38:34
2021-06-07T23:38:34
178,547,933
5
2
MIT
2023-01-03T22:28:27
2019-03-30T11:09:08
Jupyter Notebook
UTF-8
Python
false
false
564
py
""" Cleaning Data VIII - Find Null Values """ import numpy as np import pandas as pd wine_reviews = pd.read_csv('../../winemag-data-130k.csv') wine_reviews.rename(columns={'points': 'rating'}, inplace=True) # Use the below df for these problems: wine_ratings = wine_reviews[['title', 'country', 'rating', 'price']] # Return a count of the null values in wine_ratings. print(wine_ratings.isnull().sum()) """ title 0 country 63 rating 0 price 8996 """ # Print out the number of rows in wine_ratings. print(len(wine_ratings)) # 129971
[ "jgarreffa112@gmail.com" ]
jgarreffa112@gmail.com
330aee838bcfa337faecb71ec4cf47d8f2d01a0b
98c95fde2fadb00764769b8ef3c07d50e6e21778
/petsie/migrations/0001_initial.py
a5eb7a7f63d15e2739776b68bef75486e30b7e54
[]
no_license
golrizr/pets
a08c06719b78717297f25f88b78f2c3c13dd8970
67692074a0c33a457755cc10a0ec15482a6cdd6f
refs/heads/master
2021-01-13T01:54:19.907503
2014-08-22T18:00:54
2014-08-22T18:00:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
350
py
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): pass def backwards(self, orm): pass models = { } complete_apps = ['petsie']
[ "golriz25@hotmail.com" ]
golriz25@hotmail.com
4cb7933f1486a3aa55f92c6eca146b5e08994939
4fc5c590e90e973da8602c032eb9bc19c0d45dda
/super-hero-level/beautifulsoup2.py
cb4894529425fc3869cca8e4a3c1151b42a84e42
[]
no_license
shazam2064/python-excercises
6b27e39df30ec48a3aafa71253e911b2a09b3590
df7632150d4e64bfb5579996737dd4036ad91c7b
refs/heads/main
2023-03-30T20:13:49.910990
2021-03-31T12:27:22
2021-03-31T12:27:22
334,925,542
0
0
null
null
null
null
UTF-8
Python
false
false
2,260
py
# Extracting webpage elements by tag # Extracting the head - creates a Tag object # Will return only the first tag by that name from unittest import result head = result.head type(head) # Extracting h2 heading - creates a Tag object # Will return only the first tag by that name h2 = result.h2 type(h2) # Extracting the title - creates a Tag object # Will return only the first tag by that name title = result.title type(title) # Accessing the name of a tag head.name h2.name title.name # Setting a new name for a tag title.name = "mytitle" title # This change is reflected in the BeautifulSoup object itself # A tag may have any number of attributes. Example: # <header role="banner" class="navbar navbar-fixed-top navbar-static" # The header tag has two attributes: # attribute: role, value: "banner" # attribute: class, value: "navbar navbar-fixed-top navbar-static" # Using the attrs object attribute you can view the tag's own attributes # as a dictionary with the attribute name as the key and attribute value(s) as the value # Here, the 'role' attribute is a single-valued attribute # and the 'class' attribute is a multi-valued attribute # Note: for multi-valued attributes you get a list of the attribute's values as the dictionary value header = result.header print(header.prettify()) # pretty printing HTML code header.attrs # Accessing the value of a tag's attribute (as with any other dictionary) header['role'] header['class'] # or, using the get() method: header.get('role') header.get('class') # Modifying a tag's attribute value header['role'] = "something" header.attrs # Adding a new tag attribute header['new'] = "python" header.attrs # Removing a tag attribute del header['new'] header.attrs # Extracting the string from a tag h2 = result.h2 h2 h2.string 'Top items being scraped right now' type(h2.string) # this is called a NavigableString # https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring # Zooming in to a certain area of the HTML tree # Using a tag name as an attribute will give you only the first tag by that name # More info: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigating-the-tree # result.header.div # result.header.div.div.a # result.header.div.div.a.button
[ "gabriel.salomon.2007@gmail.com" ]
gabriel.salomon.2007@gmail.com
e1deceb39a471d45d08bfbacced76cdca43b001a
ccdc81165a6bfb65fd4d7956ed223dec94b3057d
/src/services/LogService.py
93a883d9145e9ba623769550a4e1f9d240283b3c
[]
no_license
asimyildiz/webservice-for-xibo1.7-python
1a1f76e161526061094b012f6446b83115fa21a9
d6e27825a627d0f8b7f514c93c5f636a338b0b06
refs/heads/master
2020-10-01T17:42:35.248951
2019-12-13T05:27:03
2019-12-13T05:27:03
227,589,335
0
0
null
null
null
null
UTF-8
Python
false
false
903
py
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. __author__ = "asim" __date__ = "$03.Kas.2015 16:18:39$" import logging class LogService(object): DEBUG = "debug" WARNING = "warning" ERROR = "error" CRITICAL = "critical" INFO = "info" @staticmethod def logMessage(message, logType): logging.basicConfig(filename='DigitalSignage.log',level=logging.INFO) if logType == LogService.DEBUG: logging.debug(message); elif logType == LogService.WARNING: logging.warning(message); elif logType == LogService.ERROR: logging.error(message); elif logType == LogService.CRITICAL: logging.critical(message); else : logging.info(message);
[ "asimyildiz@istanbulmd.com" ]
asimyildiz@istanbulmd.com
5ed1168c6daa809a0d2e8373f1dab54ae662f419
495ba1416e1aec34be69ded0b34eeb728896f25e
/tests/test_math.py
be32bcb4880ae7f021fb05dfcb8e5693b2f0b55e
[]
no_license
Brunorodrigoss/pytest_structure
a8ebdebc7380e8768a54f4c7b343f11ad70fec30
cf3bec49800c3caa06e7b6812c3016f9bd65fe1a
refs/heads/main
2023-01-19T07:58:16.854743
2020-11-21T20:24:42
2020-11-21T20:24:42
314,825,331
0
0
null
null
null
null
UTF-8
Python
false
false
2,107
py
import pytest """ This module contains basic unit tests for math operations. Their purpose is to show how to use the pytest framework by example. """ # ------------------------------------------------------------------------ # A most basic test funcion # ------------------------------------------------------------------------ @pytest.mark.math def test_one_plus_one(): assert 1 + 1 == 2 # ------------------------------------------------------------------------ # A test function to show assertion instrospection # ------------------------------------------------------------------------ @pytest.mark.math def test_one_plus_two(): a = 1 b = 2 c = 3 assert a + b == c # ------------------------------------------------------------------------ # A test function that verifies an exception # ------------------------------------------------------------------------ @pytest.mark.math def test_divide_by_zero(): with pytest.raises(ZeroDivisionError) as e: num = 1 / 0 assert 'division by zero' in str(e.value) # ------------------------------------------------------------------------ # Parametrized Tests Cases # Multiplication test ideas # - two positive integers # - indentity: multiplying any number by 1 # - zero: multiplying any number by 0 # - positive by a negative # - negative by a negative # - multiplying floats @pytest.mark.math def test_multiply_two_positive_ints(): assert 2 * 3 == 6 @pytest.mark.math def test_multiply_identity(): assert 1 * 99 == 99 @pytest.mark.math def test_multiply_zero(): assert 0 * 100 == 0 # DRY Principle: Don't repeat Yoursealf! # ------------------------------------------------------------------------ products = [ (2, 3, 6), # positive numbers (1, 99, 99), # identity (0, 99, 0), # zero (3, -4, -12), # positive by negative (-5, -5, 25), # negative by negative (2.5, 6.7, 16.75), # floats ] @pytest.mark.math @pytest.mark.parametrize('a, b, product', products) def test_multiplication(a, b, product): assert a * b == product
[ "bruno.rodrigo@farfetch.com" ]
bruno.rodrigo@farfetch.com
e07cea74af325bc2f4c384e1e7cf10621696e0c4
5419846a9e7010847fdbd232aa031fbd3e53e2bd
/Flask/ElasticBeanstalk/Request_Beanstalk.py
54e8f27c0df3f9a3c33df245136e699cc3db59ec
[]
no_license
RubensZimbres/Repo-2018
432d492df83bb6cf9268131d34b03241e0a2cbf5
4880ff9f85e5a190f6515d16a810b1cda9288c68
refs/heads/master
2021-12-14T08:25:45.171826
2021-12-06T22:14:48
2021-12-06T22:14:48
114,630,397
180
88
null
null
null
null
UTF-8
Python
false
false
673
py
import requests import boto3 from io import BytesIO import matplotlib.image as mpimg client = boto3.client('s3') resource = boto3.resource('s3') my_bucket = resource.Bucket('bucket-vecto') image_object = my_bucket.Object('dog.jpg') image = mpimg.imread(BytesIO(image_object.get()['Body'].read()), 'jpg') KERAS_REST_API_URL = "http://localhost:5000/predict" payload = {"image": image} r = requests.post(KERAS_REST_API_URL, files=payload) #.json() print(r.content) if r["success"]: for (i, result) in enumerate(r["predictions"]): print("{}. {}: {:.4f}".format(i + 1, result["label"], result["probability"])) else: print("Request failed")
[ "noreply@github.com" ]
noreply@github.com
47157eb7e1d8d2f5101413c4a384d3e2cb7d69b6
ace88a8f0a8644a8bf816d659f663c315eddfa64
/dnd/map_utils/dedge.py
de770f5b5bf6494a8b0d75772146aa0d2249c947
[]
no_license
ekrakar/Pathfinder-Toolkit
70808a8ef4f0e9c6a28a71e66c4b7410b41a22fa
2fc66a1d2de8fee36fb5589570a9cfbc9d8a5385
refs/heads/master
2020-03-26T17:04:21.857032
2018-08-17T16:10:36
2018-08-17T16:10:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
210
py
from dnd.map_utils import * class dedge(object): def __init__(self, point1, point2, number): self.number = number self.point1 = point1 self.point2 = point2 self.river = 0
[ "41119473+zefenzile@users.noreply.github.com" ]
41119473+zefenzile@users.noreply.github.com
73f8dacb0a6fd98a99721e8a113c12641950a990
175522feb262e7311fde714de45006609f7e5a07
/code/nprd/visualize_PTB.py
aab1cc504cd8b84b3cb1e24016f16bf6ca0b9dde
[]
no_license
m-hahn/predictive-rate-distortion
a048927dbc692000211df09da09ad1ed702525df
1ff573500a2313e0a79d68399cbd83970bf05e4d
refs/heads/master
2020-04-17T13:49:36.961798
2019-06-20T12:37:28
2019-06-20T12:37:28
166,631,865
0
0
null
null
null
null
UTF-8
Python
false
false
3,051
py
# Was called runMemoryManyConfigs_NeuralFlow_Words_English.py from matplotlib.ticker import MaxNLocator import math import subprocess import random import os from paths import LOG_PATH_WORDS import numpy as np ids = [x.split("_")[-1][:-4] for x in os.listdir("/home/user/CS_SCR/CODEBOOKS/") if "nprd" in x] print(ids) language = "PTB" model = "REAL" ress = [] times = [] epochs_nums = [] for idn in ids: with open("/home/user/CS_SCR/CODE/predictive-rate-distortion/results/outputs-nprd-words/test-estimates-"+language+"_"+"nprd_words_PTB_saveCodebook.py"+"_model_"+idn+"_"+model+".txt", "r") as inFile: args = next(inFile).strip().split(" ") epochs = len(next(inFile).strip().split(" ")) epochs_nums.append(epochs) next(inFile) next(inFile) next(inFile) time = float(next(inFile).strip()) times.append(time) print(args) beta = args[-3] beta = -math.log(float(beta)) if abs(beta - round(beta)) > 0.001: continue if round(beta) not in [1.0, 3.0, 5.0]: continue dat = [] with open("/home/user/CS_SCR/CODE/predictive-rate-distortion/results/nprd-samples/samples_"+idn+".txt", "r") as inFile: data = [x.split("\t") for x in inFile.read().strip().split("\n")] for i in range(0, len(data), 30): dat.append(data[i:i+30]) assert data[i][0] == '0', data[i] # print(len(dat)) ress.append((idn, round(beta), dat)) print(epochs_nums) print(times) #quit() ress = sorted(ress, key=lambda x:x[1]) #print(ress) import matplotlib import matplotlib.pyplot as plt numsOfTexts = [len(x[2]) for x in ress] print(numsOfTexts) variations = [] for j in range(min(numsOfTexts)): #len(ress[0][2])): data = ress[0][2][j] print(data) pos = np.asarray([int(x[0]) for x in data]) char = [x[1] for x in data] ys = [] for i in range(len(ress)): ys.append([float(x[2]) for x in ress[i][2][j]]) ys[-1] = np.asarray(ys[-1]) print(ys[-1]) print(ys[0]) fig, ax = plt.subplots() for y, color, style in zip(ys, ["red", "green", "blue"], ["dotted", "dashdot", "solid"]): ax.plot(pos[16:], y[16:], color=color, linestyle=style) variation = [y[16] for y in ys] variation = max(variation) - min(variation) variations.append((j, variation)) plt.subplots_adjust(left=0.03, right=0.99, top=0.99, bottom=0.17) fig.set_size_inches(9, 1.7) #ax.grid(False) plt.xticks(pos[16:], [x.decode("utf-8") for x in char][16:]) # plt.axvline(x=15.5, color="green") ax.grid(False) ax.set_ylabel("Cross-Entropy", fontsize=12) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # figure(figsize=(25,10)) fileName = "sample_"+str(j) fig.savefig("figures/"+fileName+".png", bbox_inches='tight') # plt.show() plt.gcf().clear() print("figures/"+fileName+".png") with open("figures/"+fileName+".txt", "w") as outFile: print >> outFile, (" ".join(char[:16])) print(sorted(variations, key=lambda x:x[1]))
[ "mhahn29@gmail.com" ]
mhahn29@gmail.com
79ec1a1ca8c7622eb1730afafe9b0ba4277f92e5
61fa6dd1672bcef50c0acde02cd0ec7d689254d0
/pyats/csr1kv/bin/yamllint
6709d236df4be9d1f69cf40d4a2557acd6475f1c
[]
no_license
jholsteyn/devnet-src
46364d993d83f24eede40f88c83c05044f2ad286
615893b7af0b08684af161fa99316d06703fcbbc
refs/heads/master
2023-05-12T08:49:42.488958
2021-06-08T16:50:10
2021-06-08T16:50:10
354,581,999
0
0
null
null
null
null
UTF-8
Python
false
false
427
#!/home/devasc/labs/devnet-src/pyats/csr1kv/bin/python3 # EASY-INSTALL-ENTRY-SCRIPT: 'yamllint==1.26.1','console_scripts','yamllint' __requires__ = 'yamllint==1.26.1' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('yamllint==1.26.1', 'console_scripts', 'yamllint')() )
[ "holsteynjohan@hotmail.com" ]
holsteynjohan@hotmail.com
5b421ca138ad52f140295d34f8ee1fdfc8559474
bc01e1d158e7d8f28451a7e108afb8ec4cb7d5d4
/sage/src/sage/modular/cusps_nf.py
ea7befba4c0d9a2601835cf1167a18323322bd32
[]
no_license
bopopescu/geosci
28792bda1ec1f06e23ba8dcb313769b98f793dad
0d9eacbf74e2acffefde93e39f8bcbec745cdaba
refs/heads/master
2021-09-22T17:47:20.194233
2018-09-12T22:19:36
2018-09-12T22:19:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
42,980
py
r""" The set `\mathbb{P}^1(K)` of cusps of a number field K AUTHORS: - Maite Aranes (2009): Initial version EXAMPLES: The space of cusps over a number field k: :: sage: k.<a> = NumberField(x^2 + 5) sage: kCusps = NFCusps(k); kCusps Set of all cusps of Number Field in a with defining polynomial x^2 + 5 sage: kCusps is NFCusps(k) True Define a cusp over a number field: :: sage: NFCusp(k, a, 2/(a+1)) Cusp [a - 5: 2] of Number Field in a with defining polynomial x^2 + 5 sage: kCusps((a,2)) Cusp [a: 2] of Number Field in a with defining polynomial x^2 + 5 sage: NFCusp(k,oo) Cusp Infinity of Number Field in a with defining polynomial x^2 + 5 Different operations with cusps over a number field: :: sage: alpha = NFCusp(k, 3, 1/a + 2); alpha Cusp [a + 10: 7] of Number Field in a with defining polynomial x^2 + 5 sage: alpha.numerator() a + 10 sage: alpha.denominator() 7 sage: alpha.ideal() Fractional ideal (7, a + 3) sage: alpha.ABmatrix() [a + 10, -3*a + 1, 7, -2*a] sage: alpha.apply([0, 1, -1,0]) Cusp [7: -a - 10] of Number Field in a with defining polynomial x^2 + 5 Check Gamma0(N)-equivalence of cusps: :: sage: N = k.ideal(3) sage: alpha = NFCusp(k, 3, a + 1) sage: beta = kCusps((2, a - 3)) sage: alpha.is_Gamma0_equivalent(beta, N) True Obtain transformation matrix for equivalent cusps: :: sage: t, M = alpha.is_Gamma0_equivalent(beta, N, Transformation=True) sage: M[2] in N True sage: M[0]*M[3] - M[1]*M[2] == 1 True sage: alpha.apply(M) == beta True List representatives for Gamma_0(N) - equivalence classes of cusps: :: sage: Gamma0_NFCusps(N) [Cusp [0: 1] of Number Field in a with defining polynomial x^2 + 5, Cusp [1: 3] of Number Field in a with defining polynomial x^2 + 5, ...] """ #***************************************************************************** # Copyright (C) 2009, Maite Aranes <M.T.Aranes@warwick.ac.uk> # # Distributed under the terms of the GNU General Public License (GPL) # http://www.gnu.org/licenses/ #***************************************************************************** from sage.structure.parent_base import ParentWithBase from sage.structure.element import Element, is_InfinityElement from sage.misc.cachefunc import cached_method from sage.misc.superseded import deprecated_function_alias _nfcusps_cache = {} _list_reprs_cache = {} def NFCusps_clear_list_reprs_cache(): """ Clear the global cache of lists of representatives for ideal classes. EXAMPLES:: sage: sage.modular.cusps_nf.NFCusps_clear_list_reprs_cache() sage: k.<a> = NumberField(x^3 + 11) sage: N = k.ideal(a+1) sage: sage.modular.cusps_nf.list_of_representatives(N) (Fractional ideal (1), Fractional ideal (17, a - 5)) sage: sage.modular.cusps_nf._list_reprs_cache.keys() [Fractional ideal (a + 1)] sage: sage.modular.cusps_nf.NFCusps_clear_list_reprs_cache() sage: sage.modular.cusps_nf._list_reprs_cache.keys() [] """ global _list_reprs_cache _list_reprs_cache = {} def list_of_representatives(N): """ Returns a list of ideals, coprime to the ideal ``N``, representatives of the ideal classes of the corresponding number field. Note: This list, used every time we check `\\Gamma_0(N)` - equivalence of cusps, is cached. INPUT: - ``N`` -- an ideal of a number field. OUTPUT: A list of ideals coprime to the ideal ``N``, such that they are representatives of all the ideal classes of the number field. EXAMPLES:: sage: sage.modular.cusps_nf.NFCusps_clear_list_reprs_cache() sage: sage.modular.cusps_nf._list_reprs_cache.keys() [] :: sage: from sage.modular.cusps_nf import list_of_representatives sage: k.<a> = NumberField(x^4 + 13*x^3 - 11) sage: N = k.ideal(713, a + 208) sage: L = list_of_representatives(N); L (Fractional ideal (1), Fractional ideal (37, a + 12), Fractional ideal (47, a - 9)) The output of ``list_of_representatives`` has been cached: :: sage: sage.modular.cusps_nf._list_reprs_cache.keys() [Fractional ideal (713, a + 208)] sage: sage.modular.cusps_nf._list_reprs_cache[N] (Fractional ideal (1), Fractional ideal (37, a + 12), Fractional ideal (47, a - 9)) """ if N in _list_reprs_cache: lreps = _list_reprs_cache[N] if not (lreps is None): return lreps lreps = NFCusps_ideal_reps_for_levelN(N)[0] _list_reprs_cache[N] = lreps return lreps def NFCusps_clear_cache(): """ Clear the global cache of sets of cusps over number fields. EXAMPLES:: sage: sage.modular.cusps_nf.NFCusps_clear_cache() sage: k.<a> = NumberField(x^3 + 51) sage: kCusps = NFCusps(k); kCusps Set of all cusps of Number Field in a with defining polynomial x^3 + 51 sage: sage.modular.cusps_nf._nfcusps_cache.keys() [Number Field in a with defining polynomial x^3 + 51] sage: NFCusps_clear_cache() sage: sage.modular.cusps_nf._nfcusps_cache.keys() [] """ global _nfcusps_cache _nfcusps_cache = {} def NFCusps(number_field, use_cache=True): r""" The set of cusps of a number field `K`, i.e. `\mathbb{P}^1(K)`. INPUT: - ``number_field`` -- a number field - ``use_cache`` -- bool (default=True) - to set a cache of number fields and their associated sets of cusps OUTPUT: The set of cusps over the given number field. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 5) sage: kCusps = NFCusps(k); kCusps Set of all cusps of Number Field in a with defining polynomial x^2 + 5 sage: kCusps is NFCusps(k) True Saving and loading works: :: sage: loads(kCusps.dumps()) == kCusps True We test use_cache: :: sage: NFCusps_clear_cache() sage: k.<a> = NumberField(x^2 + 11) sage: kCusps = NFCusps(k, use_cache=False) sage: sage.modular.cusps_nf._nfcusps_cache {} sage: kCusps = NFCusps(k, use_cache=True) sage: sage.modular.cusps_nf._nfcusps_cache {Number Field in a with defining polynomial x^2 + 11: ...} sage: kCusps is NFCusps(k, use_cache=False) False sage: kCusps is NFCusps(k, use_cache=True) True """ if use_cache: key = number_field if key in _nfcusps_cache: C = _nfcusps_cache[key] if not (C is None): return C C = NFCuspsSpace(number_field) if use_cache: _nfcusps_cache[key] = C return C #************************************************************************** #* NFCuspsSpace class * #************************************************************************** class NFCuspsSpace(ParentWithBase): """ The set of cusps of a number field. See ``NFCusps`` for full documentation. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 5) sage: kCusps = NFCusps(k); kCusps Set of all cusps of Number Field in a with defining polynomial x^2 + 5 """ def __init__(self, number_field): """ See ``NFCusps`` for full documentation. EXAMPLES:: sage: k.<a> = NumberField(x^3 + x^2 + 13) sage: kCusps = NFCusps(k); kCusps Set of all cusps of Number Field in a with defining polynomial x^3 + x^2 + 13 """ self.__number_field = number_field ParentWithBase.__init__(self, self) def __cmp__(self, right): """ Return equality only if right is the set of cusps for the same field. Comparing sets of cusps for two different fields gives the same result as comparing the two fields. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 5) sage: L.<a> = NumberField(x^2 + 23) sage: kCusps = NFCusps(k); kCusps Set of all cusps of Number Field in a with defining polynomial x^2 + 5 sage: LCusps = NFCusps(L); LCusps Set of all cusps of Number Field in a with defining polynomial x^2 + 23 sage: kCusps == NFCusps(k) True sage: LCusps == NFCusps(L) True sage: LCusps == kCusps False """ t = cmp(type(self), type(right)) if t: return t else: return cmp(self.number_field(), right.number_field()) def _repr_(self): """ String representation of the set of cusps of a number field. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 2) sage: kCusps = NFCusps(k) sage: kCusps Set of all cusps of Number Field in a with defining polynomial x^2 + 2 sage: kCusps._repr_() 'Set of all cusps of Number Field in a with defining polynomial x^2 + 2' sage: kCusps.rename('Number Field Cusps'); kCusps Number Field Cusps sage: kCusps.rename(); kCusps Set of all cusps of Number Field in a with defining polynomial x^2 + 2 """ return "Set of all cusps of %s" %(self.number_field()) def _latex_(self): """ Return latex representation of self. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 5) sage: kCusps = NFCusps(k) sage: latex(kCusps) # indirect doctest \mathbf{P}^1(\Bold{Q}[a]/(a^{2} + 5)) """ return "\\mathbf{P}^1(%s)" %(self.number_field()._latex_()) def __call__(self, x): """ Convert x into the set of cusps of a number field. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 5) sage: kCusps = NFCusps(k) sage: c = kCusps(a,2) Traceback (most recent call last): ... TypeError: __call__() takes exactly 2 arguments (3 given) :: sage: c = kCusps((a,2)); c Cusp [a: 2] of Number Field in a with defining polynomial x^2 + 5 sage: kCusps(2/a) Cusp [-2*a: 5] of Number Field in a with defining polynomial x^2 + 5 sage: kCusps(oo) Cusp Infinity of Number Field in a with defining polynomial x^2 + 5 """ return NFCusp(self.number_field(), x, parent=self) @cached_method def zero(self): """ Return the zero cusp. NOTE: This method just exists to make some general algorithms work. It is not intended that the returned cusp is an additive neutral element. EXAMPLE:: sage: k.<a> = NumberField(x^2 + 5) sage: kCusps = NFCusps(k) sage: kCusps.zero() Cusp [0: 1] of Number Field in a with defining polynomial x^2 + 5 """ return self(0) zero_element = deprecated_function_alias(17694, zero) def number_field(self): """ Return the number field that this set of cusps is attached to. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 1) sage: kCusps = NFCusps(k) sage: kCusps.number_field() Number Field in a with defining polynomial x^2 + 1 """ return self.__number_field #************************************************************************** #* NFCusp class * #************************************************************************** class NFCusp(Element): r""" Creates a number field cusp, i.e., an element of `\mathbb{P}^1(k)`. A cusp on a number field is either an element of the field or infinity, i.e., an element of the projective line over the number field. It is stored as a pair (a,b), where a, b are integral elements of the number field. INPUT: - ``number_field`` -- the number field over which the cusp is defined. - ``a`` -- it can be a number field element (integral or not), or a number field cusp. - ``b`` -- (optional) when present, it must be either Infinity or coercible to an element of the number field. - ``lreps`` -- (optional) a list of chosen representatives for all the ideal classes of the field. When given, the representative of the cusp will be changed so its associated ideal is one of the ideals in the list. OUTPUT: ``[a: b]`` -- a number field cusp. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 5) sage: NFCusp(k, a, 2) Cusp [a: 2] of Number Field in a with defining polynomial x^2 + 5 sage: NFCusp(k, (a,2)) Cusp [a: 2] of Number Field in a with defining polynomial x^2 + 5 sage: NFCusp(k, a, 2/(a+1)) Cusp [a - 5: 2] of Number Field in a with defining polynomial x^2 + 5 Cusp Infinity: :: sage: NFCusp(k, 0) Cusp [0: 1] of Number Field in a with defining polynomial x^2 + 5 sage: NFCusp(k, oo) Cusp Infinity of Number Field in a with defining polynomial x^2 + 5 sage: NFCusp(k, 3*a, oo) Cusp [0: 1] of Number Field in a with defining polynomial x^2 + 5 sage: NFCusp(k, a + 5, 0) Cusp Infinity of Number Field in a with defining polynomial x^2 + 5 Saving and loading works: :: sage: alpha = NFCusp(k, a, 2/(a+1)) sage: loads(dumps(alpha))==alpha True Some tests: :: sage: I*I -1 sage: NFCusp(k, I) Traceback (most recent call last): ... TypeError: unable to convert I to a cusp of the number field :: sage: NFCusp(k, oo, oo) Traceback (most recent call last): ... TypeError: unable to convert (+Infinity, +Infinity) to a cusp of the number field :: sage: NFCusp(k, 0, 0) Traceback (most recent call last): ... TypeError: unable to convert (0, 0) to a cusp of the number field :: sage: NFCusp(k, "a + 2", a) Cusp [-2*a + 5: 5] of Number Field in a with defining polynomial x^2 + 5 :: sage: NFCusp(k, NFCusp(k, oo)) Cusp Infinity of Number Field in a with defining polynomial x^2 + 5 sage: c = NFCusp(k, 3, 2*a) sage: NFCusp(k, c, a + 1) Cusp [-a - 5: 20] of Number Field in a with defining polynomial x^2 + 5 sage: L.<b> = NumberField(x^2 + 2) sage: NFCusp(L, c) Traceback (most recent call last): ... ValueError: Cannot coerce cusps from one field to another """ def __init__(self, number_field, a, b=None, parent=None, lreps=None): """ Constructor of number field cusps. See ``NFCusp`` for full documentation. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 1) sage: c = NFCusp(k, 3, a+1); c Cusp [3: a + 1] of Number Field in a with defining polynomial x^2 + 1 sage: c.parent() Set of all cusps of Number Field in a with defining polynomial x^2 + 1 sage: kCusps = NFCusps(k) sage: c.parent() is kCusps True """ if parent is None: parent = NFCusps(number_field) Element.__init__(self, parent) R = number_field.maximal_order() if b is None: if not a:#that is cusp "0" self.__a = R(0) self.__b = R(1) return if isinstance(a, NFCusp): if a.parent() == parent: self.__a = R(a.__a) self.__b = R(a.__b) else: raise ValueError("Cannot coerce cusps from one field to another") elif a in R: self.__a = R(a) self.__b = R(1) elif a in number_field: self.__b = R(a.denominator()) self.__a = R(a * self.__b) elif is_InfinityElement(a): self.__a = R(1) self.__b = R(0) elif isinstance(a, (int, long)): self.__a = R(a) self.__b = R(1) elif isinstance(a, (tuple, list)): if len(a) != 2: raise TypeError("unable to convert %r to a cusp \ of the number field"%a) if a[1].is_zero(): self.__a = R(1) self.__b = R(0) elif a[0] in R and a[1] in R: self.__a = R(a[0]) self.__b = R(a[1]) elif isinstance(a[0], NFCusp):#we know that a[1] is not zero if a[1] == 1: self.__a = a[0].__a self.__b = a[0].__b else: r = a[0].__a / (a[0].__b * a[1]) self.__b = R(r.denominator()) self.__a = R(r*self.__b) else: try: r = number_field(a[0]/a[1]) self.__b = R(r.denominator()) self.__a = R(r * self.__b) except (ValueError, TypeError): raise TypeError("unable to convert %r to a cusp \ of the number field"%a) else: try: r = number_field(a) self.__b = R(r.denominator()) self.__a = R(r * self.__b) except (ValueError, TypeError): raise TypeError("unable to convert %r to a cusp \ of the number field"%a) else:#'b' is given if is_InfinityElement(b): if is_InfinityElement(a) or (isinstance(a, NFCusp) and a.is_infinity()): raise TypeError("unable to convert (%r, %r) \ to a cusp of the number field"%(a, b)) self.__a = R(0) self.__b = R(1) return elif not b: if not a: raise TypeError("unable to convert (%r, %r) \ to a cusp of the number field"%(a, b)) self.__a = R(1) self.__b = R(0) return if not a: self.__a = R(0) self.__b = R(1) return if (b in R or isinstance(b, (int, long))) and (a in R or isinstance(a, (int, long))): self.__a = R(a) self.__b = R(b) else: if a in R or a in number_field: r = a / b elif is_InfinityElement(a): self.__a = R(1) self.__b = R(0) return elif isinstance(a, NFCusp): if a.is_infinity(): self.__a = R(1) self.__b = R(0) return r = a.__a / (a.__b * b) elif isinstance(a, (int, long)): r = R(a) / b elif isinstance(a, (tuple, list)): if len(a) != 2: raise TypeError("unable to convert (%r, %r) \ to a cusp of the number field"%(a, b)) r = R(a[0]) / (R(a[1]) * b) else: try: r = number_field(a) / b except (ValueError, TypeError): raise TypeError("unable to convert (%r, %r) \ to a cusp of the number field"%(a, b)) self.__b = R(r.denominator()) self.__a = R(r * self.__b) if not lreps is None: # Changes the representative of the cusp so the ideal associated # to the cusp is one of the ideals of the given list lreps. # Note: the trivial class is always represented by (1). I = self.ideal() for J in lreps: if (J/I).is_principal(): newI = J l = (newI/I).gens_reduced()[0] self.__a = R(l * self.__a) self.__b = R(l * self.__b) def _repr_(self): """ String representation of this cusp. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 1) sage: c = NFCusp(k, a, 2); c Cusp [a: 2] of Number Field in a with defining polynomial x^2 + 1 sage: c._repr_() 'Cusp [a: 2] of Number Field in a with defining polynomial x^2 + 1' sage: c.rename('[a:2](cusp of a number field)');c [a:2](cusp of a number field) sage: c.rename();c Cusp [a: 2] of Number Field in a with defining polynomial x^2 + 1 """ if self.__b.is_zero(): return "Cusp Infinity of %s"%self.parent().number_field() else: return "Cusp [%s: %s] of %s"%(self.__a, self.__b, \ self.parent().number_field()) def number_field(self): """ Returns the number field of definition of the cusp ``self`` EXAMPLES:: sage: k.<a> = NumberField(x^2 + 2) sage: alpha = NFCusp(k, 1, a + 1) sage: alpha.number_field() Number Field in a with defining polynomial x^2 + 2 """ return self.parent().number_field() def is_infinity(self): """ Returns ``True`` if this is the cusp infinity. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 1) sage: NFCusp(k, a, 2).is_infinity() False sage: NFCusp(k, 2, 0).is_infinity() True sage: NFCusp(k, oo).is_infinity() True """ return self.__b == 0 def numerator(self): """ Return the numerator of the cusp ``self``. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 1) sage: c = NFCusp(k, a, 2) sage: c.numerator() a sage: d = NFCusp(k, 1, a) sage: d.numerator() 1 sage: NFCusp(k, oo).numerator() 1 """ return self.__a def denominator(self): """ Return the denominator of the cusp ``self``. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 1) sage: c = NFCusp(k, a, 2) sage: c.denominator() 2 sage: d = NFCusp(k, 1, a + 1);d Cusp [1: a + 1] of Number Field in a with defining polynomial x^2 + 1 sage: d.denominator() a + 1 sage: NFCusp(k, oo).denominator() 0 """ return self.__b def _number_field_element_(self): """ Coerce to an element of the number field. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 2) sage: NFCusp(k, a, 2)._number_field_element_() 1/2*a sage: NFCusp(k, 1, a + 1)._number_field_element_() -1/3*a + 1/3 """ if self.__b.is_zero(): raise TypeError("%s is not an element of %s"%(self, \ self.number_field())) k = self.number_field() return k(self.__a / self.__b) def _ring_of_integers_element_(self): """ Coerce to an element of the ring of integers of the number field. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 2) sage: NFCusp(k, a+1)._ring_of_integers_element_() a + 1 sage: NFCusp(k, 1, a + 1)._ring_of_integers_element_() Traceback (most recent call last): ... TypeError: Cusp [1: a + 1] of Number Field in a with defining polynomial x^2 + 2 is not an integral element """ if self.__b.is_one(): return self.__a if self.__b.is_zero(): raise TypeError("%s is not an element of %s"%(self, \ self.number_field.ring_of_integers())) R = self.number_field().ring_of_integers() try: return R(self.__a/self.__b) except (ValueError, TypeError): raise TypeError("%s is not an integral element"%self) def _latex_(self): r""" Latex representation of this cusp. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 11) sage: latex(NFCusp(k, 3*a, a + 1)) # indirect doctest \[3 a: a + 1\] sage: latex(NFCusp(k, 3*a, a + 1)) == NFCusp(k, 3*a, a + 1)._latex_() True sage: latex(NFCusp(k, oo)) \infty """ if self.__b.is_zero(): return "\\infty" else: return "\\[%s: %s\\]"%(self.__a._latex_(), \ self.__b._latex_()) def __cmp__(self, right): """ Compare the cusps self and right. Comparison is as for elements in the number field, except with the cusp oo which is greater than everything but itself. The ordering in comparison is only really meaningful for infinity. EXAMPLES:: sage: k.<a> = NumberField(x^3 + x + 1) sage: kCusps = NFCusps(k) Comparing with infinity:: sage: c = kCusps((a,2)) sage: d = kCusps(oo) sage: c < d True sage: kCusps(oo) < d False Comparison as elements of the number field:: sage: kCusps(2/3) < kCusps(5/2) False sage: k(2/3) < k(5/2) False """ if self.__b.is_zero(): # self is oo, which is bigger than everything but oo. if right.__b.is_zero(): return 0 else: return 1 elif right.__b.is_zero(): if self.__b.is_zero(): return 0 else: return -1 return cmp(self._number_field_element_(), right._number_field_element_()) def __neg__(self): """ The negative of this cusp. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 23) sage: c = NFCusp(k, a, a+1); c Cusp [a: a + 1] of Number Field in a with defining polynomial x^2 + 23 sage: -c Cusp [-a: a + 1] of Number Field in a with defining polynomial x^2 + 23 """ return NFCusp(self.parent().number_field(), -self.__a, self.__b) def apply(self, g): """ Return g(``self``), where ``g`` is a 2x2 matrix, which we view as a linear fractional transformation. INPUT: - ``g`` -- a list of integral elements [a, b, c, d] that are the entries of a 2x2 matrix. OUTPUT: A number field cusp, obtained by the action of ``g`` on the cusp ``self``. EXAMPLES: :: sage: k.<a> = NumberField(x^2 + 23) sage: beta = NFCusp(k, 0, 1) sage: beta.apply([0, -1, 1, 0]) Cusp Infinity of Number Field in a with defining polynomial x^2 + 23 sage: beta.apply([1, a, 0, 1]) Cusp [a: 1] of Number Field in a with defining polynomial x^2 + 23 """ k = self.number_field() return NFCusp(k, g[0]*self.__a + g[1]*self.__b, \ g[2]*self.__a + g[3]*self.__b) def ideal(self): """ Returns the ideal associated to the cusp ``self``. EXAMPLES:: sage: k.<a> = NumberField(x^2 + 23) sage: alpha = NFCusp(k, 3, a-1) sage: alpha.ideal() Fractional ideal (3, 1/2*a - 1/2) sage: NFCusp(k, oo).ideal() Fractional ideal (1) """ k = self.number_field() return k.ideal(self.__a, self.__b) def ABmatrix(self): """ Returns AB-matrix associated to the cusp ``self``. Given R a Dedekind domain and A, B ideals of R in inverse classes, an AB-matrix is a matrix realizing the isomorphism between R+R and A+B. An AB-matrix associated to a cusp [a1: a2] is an AB-matrix with A the ideal associated to the cusp (A=<a1, a2>) and first column given by the coefficients of the cusp. EXAMPLES: :: sage: k.<a> = NumberField(x^3 + 11) sage: alpha = NFCusp(k, oo) sage: alpha.ABmatrix() [1, 0, 0, 1] :: sage: alpha = NFCusp(k, 0) sage: alpha.ABmatrix() [0, -1, 1, 0] Note that the AB-matrix associated to a cusp is not unique, and the output of the ``ABmatrix`` function may change. :: sage: alpha = NFCusp(k, 3/2, a-1) sage: M = alpha.ABmatrix() sage: M # random [-a^2 - a - 1, -3*a - 7, 8, -2*a^2 - 3*a + 4] sage: M[0] == alpha.numerator() and M[2]==alpha.denominator() True An AB-matrix associated to a cusp alpha will send Infinity to alpha: :: sage: alpha = NFCusp(k, 3, a-1) sage: M = alpha.ABmatrix() sage: (k.ideal(M[1], M[3])*alpha.ideal()).is_principal() True sage: M[0] == alpha.numerator() and M[2]==alpha.denominator() True sage: NFCusp(k, oo).apply(M) == alpha True """ k = self.number_field() A = self.ideal() if self.is_infinity(): return [1, 0, 0, 1] if not self: return [0, -1, 1, 0] if A.is_principal(): B = k.ideal(1) else: B = k.ideal(A.gens_reduced()[1])/A assert (A*B).is_principal() a1 = self.__a a2 = self.__b g = (A*B).gens_reduced()[0] Ainv = A**(-1) A1 = a1*Ainv A2 = a2*Ainv r = A1.element_1_mod(A2) b1 = -(1-r)/a2*g b2 = (r/a1)*g ABM = [a1, b1, a2, b2] return ABM def is_Gamma0_equivalent(self, other, N, Transformation=False): r""" Checks if cusps ``self`` and ``other`` are `\Gamma_0(N)`- equivalent. INPUT: - ``other`` -- a number field cusp or a list of two number field elements which define a cusp. - ``N`` -- an ideal of the number field (level) OUTPUT: - bool -- ``True`` if the cusps are equivalent. - a transformation matrix -- (if ``Transformation=True``) a list of integral elements [a, b, c, d] which are the entries of a 2x2 matrix M in `\Gamma_0(N)` such that M * ``self`` = ``other`` if ``other`` and ``self`` are `\Gamma_0(N)`- equivalent. If ``self`` and ``other`` are not equivalent it returns zero. EXAMPLES: :: sage: K.<a> = NumberField(x^3-10) sage: N = K.ideal(a-1) sage: alpha = NFCusp(K, 0) sage: beta = NFCusp(K, oo) sage: alpha.is_Gamma0_equivalent(beta, N) False sage: alpha.is_Gamma0_equivalent(beta, K.ideal(1)) True sage: b, M = alpha.is_Gamma0_equivalent(beta, K.ideal(1),Transformation=True) sage: alpha.apply(M) Cusp Infinity of Number Field in a with defining polynomial x^3 - 10 :: sage: k.<a> = NumberField(x^2+23) sage: N = k.ideal(3) sage: alpha1 = NFCusp(k, a+1, 4) sage: alpha2 = NFCusp(k, a-8, 29) sage: alpha1.is_Gamma0_equivalent(alpha2, N) True sage: b, M = alpha1.is_Gamma0_equivalent(alpha2, N, Transformation=True) sage: alpha1.apply(M) == alpha2 True sage: M[2] in N True """ k = self.number_field() other = NFCusp(k, other) if not (self.ideal()/other.ideal()).is_principal(): if not Transformation: return False else: return False, 0 reps = list_of_representatives(N) alpha1 = NFCusp(k, self, lreps=reps) alpha2 = NFCusp(k, other, lreps=reps) delta = k.ideal(alpha1.__b) + N if (k.ideal(alpha2.__b) + N)!= delta: if not Transformation: return False else: return False, 0 M1 = alpha1.ABmatrix() M2 = alpha2.ABmatrix() A = alpha1.ideal() B = k.ideal(M1[1], M1[3]) ABdelta = A*B*delta*delta units = units_mod_ideal(ABdelta) for u in units: if (M2[2]*M1[3] - u*M1[2]*M2[3]) in ABdelta: if not Transformation: return True else: AuxCoeff = [1, 0, 0, 1] Aux = M2[2]*M1[3] - u*M1[2]*M2[3] if Aux in A*B*N: if not u==1: AuxCoeff[3] = u else: A1 = (A*B*N)/ABdelta A2 = B*k.ideal(M1[2]*M2[2])/(A*ABdelta) f = A1.element_1_mod(A2) w = ((1 - f)*Aux)/(M1[2]*M2[2]) AuxCoeff[3] = u AuxCoeff[1] = w from sage.matrix.all import Matrix Maux = Matrix(k, 2, AuxCoeff) M1inv = Matrix(k, 2, M1).inverse() Mtrans = Matrix(k, 2, M2)*Maux*M1inv assert Mtrans[1][0] in N return True, Mtrans.list() if not Transformation: return False else: return False, 0 #************************************************************************** # Global functions: # - Gamma0_NFCusps --compute list of inequivalent cusps # Internal use only: # - number_of_Gamma0_NFCusps -- useful to test Gamma0_NFCusps # - NFCusps_ideal_reps_for_levelN -- lists of reps for ideal classes # - units_mod_ideal -- needed to check Gamma0(N)-equiv of cusps #************************************************************************** def Gamma0_NFCusps(N): r""" Returns a list of inequivalent cusps for `\Gamma_0(N)`, i.e., a set of representatives for the orbits of ``self`` on `\mathbb{P}^1(k)`. INPUT: - ``N`` -- an integral ideal of the number field k (the level). OUTPUT: A list of inequivalent number field cusps. EXAMPLES: :: sage: k.<a> = NumberField(x^2 + 5) sage: N = k.ideal(3) sage: L = Gamma0_NFCusps(N) The cusps in the list are inequivalent: :: sage: all([not L[i].is_Gamma0_equivalent(L[j], N) for i, j in \ mrange([len(L), len(L)]) if i<j]) True We test that we obtain the right number of orbits: :: sage: from sage.modular.cusps_nf import number_of_Gamma0_NFCusps sage: len(L) == number_of_Gamma0_NFCusps(N) True Another example: :: sage: k.<a> = NumberField(x^4 - x^3 -21*x^2 + 17*x + 133) sage: N = k.ideal(5) sage: from sage.modular.cusps_nf import number_of_Gamma0_NFCusps sage: len(Gamma0_NFCusps(N)) == number_of_Gamma0_NFCusps(N) # long time (over 1 sec) True """ # We create L a list of three lists, which are different and each a list of # prime ideals, coprime to N, representing the ideal classes of k L = NFCusps_ideal_reps_for_levelN(N, nlists=3) Laux = L[1]+L[2] Lreps = list_of_representatives(N) Lcusps = [] k = N.number_field() for A in L[0]: #find B in inverse class: if A.is_trivial(): B = k.ideal(1) #B = k.unit_ideal() produces an error because we need fract ideal g = 1 else: Lbs = [P for P in Laux if (P*A).is_principal()] B = Lbs[0] g = (A*B).gens_reduced()[0] #for every divisor of N we have to find cusps from sage.arith.all import divisors for d in divisors(N): #find delta prime coprime to B in inverse class of d*A #by searching in our list of auxiliary prime ideals Lds = [P for P in Laux if (P*d*A).is_principal() and P.is_coprime(B)] deltap = Lds[0] a = (deltap*d*A).gens_reduced()[0] I = d + N/d #especial case: A=B=d=<1>: if a.is_one() and I.is_trivial(): Lcusps.append(NFCusp(k, 0, 1, lreps=Lreps)) else: u = k.unit_group().gens() for b in I.invertible_residues_mod(u): #Note: if I trivial, invertible_residues_mod returns [1] #lift b to (R/a)star #we need the part of d which is coprime to I, call it M M = d.prime_to_idealM_part(I) deltAM = deltap*A*M u = (B*deltAM).element_1_mod(I) v = (I*B).element_1_mod(deltAM) newb = u*b + v #build AB-matrix: #----> extended gcd for k.ideal(a), k.ideal(newb) Y = k.ideal(newb).element_1_mod(k.ideal(a)) # if xa + yb = 1, cusp = y*g /a Lcusps.append(NFCusp(k, Y*g, a, lreps=Lreps)) return Lcusps def number_of_Gamma0_NFCusps(N): """ Returns the total number of orbits of cusps under the action of the congruence subgroup `\\Gamma_0(N)`. INPUT: - ``N`` -- a number field ideal. OUTPUT: ingeter -- the number of orbits of cusps under Gamma0(N)-action. EXAMPLES:: sage: k.<a> = NumberField(x^3 + 11) sage: N = k.ideal(2, a+1) sage: from sage.modular.cusps_nf import number_of_Gamma0_NFCusps sage: number_of_Gamma0_NFCusps(N) 4 sage: L = Gamma0_NFCusps(N) sage: len(L) == number_of_Gamma0_NFCusps(N) True sage: k.<a> = NumberField(x^2 + 7) sage: N = k.ideal(9) sage: number_of_Gamma0_NFCusps(N) 6 sage: N = k.ideal(a*9 + 7) sage: number_of_Gamma0_NFCusps(N) 24 """ k = N.number_field() # The number of Gamma0(N)-sub-orbits for each Gamma-orbit: from sage.arith.all import divisors Ugens = [k(u) for u in k.unit_group().gens()] s = sum([len((d+N/d).invertible_residues_mod(Ugens)) for d in divisors(N)]) # There are h Gamma-orbits, with h class number of underlying number field. return s*k.class_number() def NFCusps_ideal_reps_for_levelN(N, nlists=1): """ Returns a list of lists (``nlists`` different lists) of prime ideals, coprime to ``N``, representing every ideal class of the number field. INPUT: - ``N`` -- number field ideal. - ``nlists`` -- optional (default 1). The number of lists of prime ideals we want. OUTPUT: A list of lists of ideals representatives of the ideal classes, all coprime to ``N``, representing every ideal. EXAMPLES:: sage: k.<a> = NumberField(x^3 + 11) sage: N = k.ideal(5, a + 1) sage: from sage.modular.cusps_nf import NFCusps_ideal_reps_for_levelN sage: NFCusps_ideal_reps_for_levelN(N) [(Fractional ideal (1), Fractional ideal (2, a + 1))] sage: L = NFCusps_ideal_reps_for_levelN(N, 3) sage: all([len(L[i])==k.class_number() for i in range(len(L))]) True :: sage: k.<a> = NumberField(x^4 - x^3 -21*x^2 + 17*x + 133) sage: N = k.ideal(6) sage: from sage.modular.cusps_nf import NFCusps_ideal_reps_for_levelN sage: NFCusps_ideal_reps_for_levelN(N) [(Fractional ideal (1), Fractional ideal (13, a - 2), Fractional ideal (43, a - 1), Fractional ideal (67, a + 17))] sage: L = NFCusps_ideal_reps_for_levelN(N, 5) sage: all([len(L[i])==k.class_number() for i in range(len(L))]) True """ k = N.number_field() G = k.class_group() L = [] for i in range(nlists): L.append([k.ideal(1)]) it = k.primes_of_degree_one_iter() for I in G.list(): check = 0 if not I.is_principal(): Iinv = (I.ideal())**(-1) while check<nlists: J = next(it) if (J*Iinv).is_principal() and J.is_coprime(N): L[check].append(J) check = check + 1 return [tuple(l) for l in L] def units_mod_ideal(I): """ Returns integral elements of the number field representing the images of the global units modulo the ideal ``I``. INPUT: - ``I`` -- number field ideal. OUTPUT: A list of integral elements of the number field representing the images of the global units modulo the ideal ``I``. Elements of the list might be equivalent to each other mod ``I``. EXAMPLES:: sage: from sage.modular.cusps_nf import units_mod_ideal sage: k.<a> = NumberField(x^2 + 1) sage: I = k.ideal(a + 1) sage: units_mod_ideal(I) [1] sage: I = k.ideal(3) sage: units_mod_ideal(I) [1, a, -1, -a] :: sage: from sage.modular.cusps_nf import units_mod_ideal sage: k.<a> = NumberField(x^3 + 11) sage: k.unit_group() Unit group with structure C2 x Z of Number Field in a with defining polynomial x^3 + 11 sage: I = k.ideal(5, a + 1) sage: units_mod_ideal(I) [1, 2*a^2 + 4*a - 1, ...] :: sage: from sage.modular.cusps_nf import units_mod_ideal sage: k.<a> = NumberField(x^4 - x^3 -21*x^2 + 17*x + 133) sage: k.unit_group() Unit group with structure C6 x Z of Number Field in a with defining polynomial x^4 - x^3 - 21*x^2 + 17*x + 133 sage: I = k.ideal(3) sage: U = units_mod_ideal(I) sage: all([U[j].is_unit() and not (U[j] in I) for j in range(len(U))]) True """ k = I.number_field() Uk = k.unit_group() Istar = I.idealstar(2) ulist = Uk.gens_values() elist = [Istar(I.ideallog(u)).order() for u in ulist] from sage.misc.mrange import xmrange from sage.misc.all import prod return [prod([u**e for u,e in zip(ulist,ei)],k(1)) for ei in xmrange(elist)]
[ "valber@HPC" ]
valber@HPC
334f2e09ecf33e29d0f56df23a63fab3582e9ffb
d09a1fae642abf1a68c4f0563a40045a688be20d
/Module-3/3-1-4-4-Lists-collections-of-data-Operations-on-lists-Removing-elements-from-a-list.py
30b89896d32dd466857cbc7342942e1d49d35e1b
[]
no_license
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
fdbf02b16f47c89d7d8c457159e8eb079ca8d307
7ae5e1e65bb1c9982b9789e382cf626c863ffcb3
refs/heads/master
2022-11-13T20:26:48.549176
2020-07-08T14:06:12
2020-07-08T14:06:12
267,685,762
0
0
null
null
null
null
UTF-8
Python
false
false
320
py
#!/usr/bin/python3 """ It may look strange, but negative indices are legal, and can be very useful. An element with an index equal to -1 is the last one in the list. Similarly, the element with an index equal to -2 is the one before last in the list. """ numbers = [111, 7, 2, 1] print(numbers[-1]) print(numbers[-2])
[ "rolandoquiroz@gmail.com" ]
rolandoquiroz@gmail.com
ef227b68a8ef96872a75eda2e6d46bd3f4e313fb
2d2268e2e1ab883c6532b86345e7f54a9769a29e
/grupos/migrations/0005_auto_20190218_1137.py
32fa0e257cbbb8244daba2001071261a91a5dde6
[]
no_license
thygolem/pyadminGrupos
3ddd2553aec5b2186f936f98012d16b28cafc0fe
d1a9479ec836365d50247ccdd8b9437fb382433d
refs/heads/master
2021-10-25T12:18:35.013425
2019-03-11T11:57:37
2019-03-11T11:57:37
179,463,429
0
0
null
null
null
null
UTF-8
Python
false
false
8,408
py
# Generated by Django 2.1.5 on 2019-02-18 10:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('grupos', '0004_auto_20190215_1043'), ] operations = [ migrations.RenameField( model_name='grupo', old_name='timestamp', new_name='ultima_revisión', ), migrations.RemoveField( model_name='grupo', name='alarma_general', ), migrations.RemoveField( model_name='grupo', name='bajo_nv_bateria', ), migrations.RemoveField( model_name='grupo', name='bajo_nv_gasoil', ), migrations.RemoveField( model_name='grupo', name='bajo_nv_refrigerante', ), migrations.RemoveField( model_name='grupo', name='carga_bateria', ), migrations.RemoveField( model_name='grupo', name='cp', ), migrations.RemoveField( model_name='grupo', name='fallo_arranque', ), migrations.RemoveField( model_name='grupo', name='fallo_caldeo', ), migrations.RemoveField( model_name='grupo', name='fallo_cargador', ), migrations.RemoveField( model_name='grupo', name='fallo_general', ), migrations.RemoveField( model_name='grupo', name='grupo_en_marcha', ), migrations.RemoveField( model_name='grupo', name='hz', ), migrations.RemoveField( model_name='grupo', name='kw', ), migrations.RemoveField( model_name='grupo', name='marca', ), migrations.RemoveField( model_name='grupo', name='min_frecuencia', ), migrations.RemoveField( model_name='grupo', name='modo_auto', ), migrations.RemoveField( model_name='grupo', name='modo_manual', ), migrations.RemoveField( model_name='grupo', name='modo_test', ), migrations.RemoveField( model_name='grupo', name='presion_aceite', ), migrations.RemoveField( model_name='grupo', name='propietario', ), migrations.RemoveField( model_name='grupo', name='sobre_frecuencia', ), migrations.RemoveField( model_name='grupo', name='sobrecarga', ), migrations.RemoveField( model_name='grupo', name='sobretension', ), migrations.RemoveField( model_name='grupo', name='stop', ), migrations.RemoveField( model_name='grupo', name='subtension', ), migrations.RemoveField( model_name='grupo', name='temp_agua', ), migrations.RemoveField( model_name='grupo', name='tension_bateria', ), migrations.AddField( model_name='grupo', name='alternador_modelo', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='alternador_n_serie', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='altitud', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='anomalias', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='equipo_control', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='filtros_aceite_cant', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='filtros_aceite_modelo', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='filtros_agua_cant', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='filtros_agua_modelo', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='filtros_aire_cant', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='filtros_aire_modelo', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='filtros_combustible_cant', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='filtros_combustible_modelo', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='frecuencia', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='horas_funcionamiento', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='litros_aceite', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='litros_deposito', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='litros_refrigerante', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='modelo_baterias', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='motor_modelo', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='motor_n_serie', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='n_serie', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='num_baterias', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='otros_respuestos', field=models.CharField(blank=True, max_length=800), ), migrations.AddField( model_name='grupo', name='potencia_kva', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='tensión', field=models.CharField(blank=True, max_length=200), ), migrations.AddField( model_name='grupo', name='tensión_cc', field=models.CharField(blank=True, max_length=200), ), migrations.AlterField( model_name='grupo', name='latitud', field=models.CharField(blank=True, max_length=200), ), migrations.AlterField( model_name='grupo', name='longitud', field=models.CharField(blank=True, max_length=200), ), migrations.AlterField( model_name='grupo', name='modelo', field=models.CharField(max_length=500), ), ]
[ "ivansimo@industria40.me" ]
ivansimo@industria40.me
5f3eb0adbedd522f2f753458e0903b5e7b4e8430
decce7f88ac26892896802fd8508342f58889219
/typeidea/comment/migrations/0001_initial.py
78ff329fc3ff4c21d3ead9245fcd7e40a7ed65a7
[]
no_license
woxidadiaosi/typeidea
2c59cce8aa6e6c59b28798fabd99943473a4b773
cfe3db444f1ba72f0076c121aee86f5cd4c88c34
refs/heads/master
2020-12-28T17:51:50.622748
2020-02-07T04:04:36
2020-02-07T04:04:36
238,428,970
0
0
null
null
null
null
UTF-8
Python
false
false
1,206
py
# Generated by Django 2.2 on 2020-02-07 03:46 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('target', models.CharField(max_length=255, verbose_name='评论目标')), ('content', models.CharField(max_length=2000, verbose_name='内容')), ('nickname', models.CharField(max_length=50, verbose_name='昵称')), ('website', models.URLField(verbose_name='网站')), ('email', models.EmailField(max_length=254, verbose_name='邮箱')), ('status', models.PositiveIntegerField(choices=[(1, '正常'), (0, '删除')], default=1, verbose_name='状态')), ('created_time', models.DateTimeField(auto_now_add=True, verbose_name='创建时间')), ], options={ 'verbose_name': '评论', 'verbose_name_plural': '评论', }, ), ]
[ "hty1194123800@163.com" ]
hty1194123800@163.com
1e1bed689d29fc1001498014cc02e0800969be85
a22c3c1d13fa01e1a61718393dbf89f4dc406bee
/week3/usepack.py
ae11d4ea6e720549f2c28ce8beb6c1d59554d325
[]
no_license
jumirang/python-test
f6a6c35059a8b62a6888a3bace0045b9a95f176f
5e12dbeea6ba3334ca0780fc42144efee646d1f0
refs/heads/master
2021-01-19T15:54:53.297888
2018-11-07T05:17:55
2018-11-07T05:17:55
88,233,883
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
# import game.sound.load as LOAD # 축약어 사용 # LOAD.load1() # LOAD.load2() from game.sound.load import * load1() load2()
[ "minseok.hwangbo@lge.com" ]
minseok.hwangbo@lge.com
f78847b795173c43b7152e277ae789321145022a
82bae57f5e5e591a645b7e81b445153c8fcc3c6d
/Glider/GliderFull.py
d8f479c573f8b7e0ad317b5ae6cf95795ae99ae9
[]
no_license
Aerothon-2020/Adv2019Aircraft
ed74ef5ffc65bb8044c36d974c2b9662a6e0459b
eb8cb724578628ff5bf9a9858817632b64a6fa3b
refs/heads/master
2020-08-04T01:30:57.995223
2019-09-30T20:48:05
2019-09-30T20:48:05
211,953,382
0
0
null
null
null
null
UTF-8
Python
false
false
10,734
py
from __future__ import division # let 5/2 = 2.5 rather than 2 #from os import environ as _environ; _environ["scalar_off"] = "off" from scalar.units import M, FT, IN, ARCDEG, RAD, LBF, SEC, KG, SLUG, OZF, gacc, GRAM, OZM from scalar.units import AsUnit from Aerothon.ACAircraft import ACTailAircraft from Aerothon.ACWingWeight import ACRibWing from Aerothon.DefaultMaterialsLibrary import Monokote, PinkFoam, Basswood, Steel, Balsa, Aluminum, Ultracote from Adv2019Aircraft.MonoWing.Fuselage import Fuselage from Reg2015Aircraft_AeroCats.Propulsion.Propulsion import Propulsion from Adv2019Aircraft.MonoWing.Glider import Wing import pylab as pyl import cmath as math # # Create the Aircraft from the ACTailAircraft class Aircraft = ACTailAircraft() Aircraft.name = 'AdvAeroCats_2019' # # Assign the already generated parts Aircraft.SetFuselage(Fuselage) Aircraft.SetPropulsion(Propulsion) Aircraft.SetWing(Wing) # # Position the wing on the top of the fuselage Aircraft.WingFuseFrac = 0.575 Aircraft.Wing.i = 1.0*ARCDEG # # Aircraft Properties # Total weight is going to change Aircraft.TotalWeight = 50*LBF # Engine align Aircraft.EngineAlign = 0.7 Aircraft.TippingAngle = 15*ARCDEG # Black line on AC plot Aircraft.RotationAngle = 12*ARCDEG # Red line on AC plot Aircraft.Alpha_Groundroll = 0*ARCDEG Aircraft.CMSlopeAt = (0 * ARCDEG, 10 * ARCDEG) Aircraft.CLSlopeAt = (0 * ARCDEG, 15 * ARCDEG) Aircraft.CLHTSlopeAt = (0 * ARCDEG, 15 * ARCDEG) Aircraft.DWSlopeAt = (0 * ARCDEG, 15 * ARCDEG) Aircraft.Alpha_Zero_CM = 3.0 * ARCDEG #for steady level flight Aircraft.StaticMargin = 0.06 # Location of Wing Aircraft.WingXMaxIt = 50 Aircraft.WingXOmega = 1 # # Maximum velocity for plotting purposes Aircraft.VmaxPlt = 75*FT/SEC # # Estimate for the time the aircraft rotates on the ground during takeoff Aircraft.RotationTime = 0.5 * SEC Aircraft.NoseGearOffset = 7.5*IN ############################################################################### # # Tail surfaces # ############################################################################### #============================================================================== # Horizontal tail #============================================================================== HTail = Aircraft.HTail HTail.Airfoil = 'NACA0012' #HTail.AR = 3 HTail.b = 42 *IN HTail.TR = 1.0 HTail.o_eff = 0.96 HTail.S = 480 *IN**2 HTail.L = 47.5 *IN #Length from X_CG to Tail AC #HTail.VC = 0.70 # 0.8 for S1223 airfoil HTail.FullWing = True HTail.DWF = 1 #Main wing Down wash factor (Typically between 1.0 (close to wing) and 2.0 (far away)) HTail.Inverted = False HTail.ClSlopeAt = (-5*ARCDEG, 10*ARCDEG) HTail.CmSlopeAt = (-4*ARCDEG, 5*ARCDEG) Aircraft.HTailPos = 0 #T-Tail =1 regular tail =0 # # Elevator properties # HTail.Elevator.Fc = 0.5 #Elevator % of Tail chord HTail.Elevator.Fb = 1.0 #Elevator 100% of rear tail span HTail.Elevator.Ft = 0.0 #0.25 HTail.Elevator.Weight = 0.1*LBF HTail.Elevator.WeightGroup = "HTail" HTail.Elevator.Servo.Fc = 0.3 HTail.Elevator.Servo.Fbc = 0.15 #Relocating the HTail Servo closer to the elevator HTail.Elevator.Servo.Weight = 0.3 * OZF HTail.Elevator.Servo.WeightGroup = "Controls" HTail.Elevator.Servo.Torque = 33.3*IN*OZM #Set the sweep about the elevator hinge HTail.SweepFc = 1.0 - HTail.Elevator.Fc #Makes Elevator LE straight # # Structural properties # Spar taken as 1/8 inch width and thickness of the max thickness at the root # Basswood = Basswood.copy() BWRibMat = Balsa.copy() BWRibMat.Thickness = 1/8 * IN HTail.SetWeightCalc(ACRibWing) HTail.WingWeight.RibMat = BWRibMat HTail.WingWeight.RibSpace = 6 * IN HTail.WingWeight.SkinMat = Ultracote.copy() HTail.WingWeight.WeightGroup = 'HTail' HTail.WingWeight.AddSpar("MainSpar", 1*IN, 1*IN, (0.25,0),1.0, False) HTail.WingWeight.MainSpar.SparMat.LinearForceDensity = .008*LBF/(1*IN) HTail.WingWeight.MainSpar.ScaleToWing = [False, False] HTail.WingWeight.MainSpar.WeightGroup = "HTail" HTail.WingWeight.AddSpar("LeadingEdge", 0.25*IN, 0.25*IN, (0.01,0),1.0, False) HTail.WingWeight.LeadingEdge.SparMat = Balsa.copy() #HTail.WingWeight.LeadingEdge.SparMat.LinearForceDensity = .008*LBF/(1*IN) HTail.WingWeight.LeadingEdge.ScaleToWing = [False, False] HTail.WingWeight.LeadingEdge.WeightGroup = "HTail" HTail.WingWeight.AddSpar("TrailingEdge", 0.5*IN, 0.25*IN, (0.975,0),1.0, False) HTail.WingWeight.TrailingEdge.SparMat = Balsa.copy() #HTail.WingWeight.TrailingEdge.SparMat.LinearForceDensity = .008*LBF/(1*IN) HTail.WingWeight.TrailingEdge.ScaleToWing = [False, False] HTail.WingWeight.TrailingEdge.WeightGroup = "HTail" #HTail.WingWeight.AddSpar("TrailingEdge2", 1/16*IN, 11/8*IN, (0.25,1),1.0, False) #HTail.WingWeight.TrailingEdge2.SparMat = Balsa.copy() #.LinearForceDensity = .008*LBF/(1*IN) #HTail.WingWeight.TrailingEdge2.Position = (0.45,0.55) #HTail.WingWeight.TrailingEdge2.ScaleToWing = [False, False] #HTail.WingWeight.TrailingEdge2.WeightGroup = "HTail" #============================================================================== # Vertical tail #============================================================================== VTail = Aircraft.VTail VTail.Airfoil = 'NACA0012' #VTail.VC = 0.09 #VTail.AR = 2 VTail.b = 20 *IN VTail.TR = 0.75 VTail.Axis = (0, 1) #(0,1) VTail.L = HTail.L #Setting Vtail at distance back From Wing VTail.o_eff = 0.96 VTail.S = 210 * IN**2 VTail.FullWing = False VTail.Symmetric = False Aircraft.VTailPos = 0 # # Rudder properties VTail.Rudder.Fc = 0.5 VTail.Rudder.Weight = 0.05*LBF VTail.Rudder.WeightGroup = "VTail" VTail.Rudder.SgnDup = -1.0 VTail.Rudder.Servo.Fc = 0.3 VTail.Rudder.Servo.Fbc = 0 #VTail.Rudder.Servo.Weight = 5*GRAM*gacc VTail.Rudder.Servo.Weight = 0.3 * OZF VTail.Rudder.Servo.WeightGroup = "Controls" VTail.Rudder.Servo.Torque = 33.3*IN*OZM #Set the sweep about the rudder hinge VTail.SweepFc = 1.0 #- VTail.Rudder.Fc # # Structural properties # Spar taken as 1/8 inch width and thickness of the max thickness at the root VTail.SetWeightCalc(ACRibWing) VTail.WingWeight.RibMat = BWRibMat VTail.WingWeight.RibSpace = 5 * IN VTail.WingWeight.SkinMat = Ultracote.copy() VTail.WingWeight.WeightGroup = 'VTail' VTail.WingWeight.AddSpar("MainSpar", 1*IN, 1*IN, (0.25,0),1.0, False) VTail.WingWeight.MainSpar.SparMat.LinearForceDensity = .008*LBF/(1*IN) #= Balsa.copy() VTail.WingWeight.MainSpar.ScaleToWing = [False, False] VTail.WingWeight.MainSpar.WeightGroup = "VTail" VTail.WingWeight.AddSpar("LeadingEdge", 1/8*IN, 1/8*IN, (0.008,0),1.0, False) VTail.WingWeight.LeadingEdge.SparMat = Balsa.copy() #VTail.WingWeight.LeadingEdge.LinearForceDensity = .008*LBF/(1*IN) VTail.WingWeight.LeadingEdge.ScaleToWing = [False, False] VTail.WingWeight.LeadingEdge.WeightGroup = "VTail" VTail.WingWeight.AddSpar("TrailingEdge", 1/16*IN, 1.75*IN, (0.915,0),1.0, False) VTail.WingWeight.TrailingEdge.SparMat = Balsa.copy() #VTail.WingWeight.TrailingEdge.LinearForceDensity = .008*LBF/(1*IN) VTail.WingWeight.TrailingEdge.ScaleToWing = [False, False] VTail.WingWeight.TrailingEdge.WeightGroup = "VTail" #VTail.WingWeight.AddSpar("TrailingEdge2", 1/16*IN, 1.75*IN, (0.25,1),1.0, False) #VTail.WingWeight.TrailingEdge2.SparMat = Balsa.copy() #.LinearForceDensity = .008*LBF/(1*IN) #VTail.WingWeight.TrailingEdge2.Position = (0.915,-0.2) #VTail.WingWeight.TrailingEdge2.ScaleToWing = [False, False] #VTail.WingWeight.TrailingEdge2.WeightGroup = "VTail" ############################################################################### # # Landing Gear # ############################################################################### Aluminum = Aluminum.copy() Steel = Steel.copy() MainGear = Aircraft.MainGear #MainGear.Theta = 60 * ARCDEG MainGear.GearHeight = 6 * IN #MainGear.StrutL = 0.2 * IN MainGear.StrutW = 0.25 * IN MainGear.StrutH = 0.25 * IN MainGear.WheelDiam = 5 * IN MainGear.X[1] = 6.0 * IN MainGear.Strut.Weight = 1.35* LBF MainGear.Strut.WeightGroup = "LandingGear" MainGear.Wheel.Weight = 0.2*LBF MainGear.Wheel.WeightGroup = "LandingGear" NoseGear = Aircraft.NoseGear NoseGear.StrutW = 0.1 * IN NoseGear.StrutH = 0.1 * IN NoseGear.WheelDiam = 5 * IN NoseGear.Strut.Weight = 1 * LBF NoseGear.Strut.WeightGroup = "LandingGear" NoseGear.Wheel.Weight = .2*LBF NoseGear.Wheel.WeightGroup = "LandingGear" Aircraft.EmptyWeight = Aircraft.EmptyWeight if __name__ == '__main__': print print 'Aircraft V_LO:', AsUnit( Aircraft.GetV_LO(), 'ft/s') print 'Wing V_LO:', AsUnit( Aircraft.Wing.GetV_LO(), 'ft/s') print print 'V max climb : ', AsUnit( Aircraft.V_max_climb(), 'ft/s') print 'V max : ', AsUnit( Aircraft.Vmax(), 'ft/s') print 'Ground Roll : ', AsUnit( Aircraft.Groundroll(), 'ft') print 'Total Weight : ', AsUnit( Aircraft.TotalWeight, 'lbf') #print 'Payload Weight : ', AsUnit( Aircraft.PayloadWeight(), 'lbf') print 'Wing Height : ', AsUnit( Aircraft.Wing.Upper(0*IN),'in') print 'Vertical Tail H: ', AsUnit( Aircraft.VTail.Tip()[2], 'in' ) print 'HTail Incidence: ', AsUnit( Aircraft.HTail.i, 'deg') print "Lift of AoA : ", AsUnit( Aircraft.GetAlphaFus_LO(),'deg') print "Zero CM AoA : ", AsUnit( Aircraft.Alpha_Zero_CM, 'deg') print 'HTail VC : ', AsUnit( Aircraft.HTail.VC) print 'VTail VC : ', AsUnit( Aircraft.VTail.VC) print 'VTail Area : ', AsUnit( Aircraft.VTail.S, 'in**2') print 'HTail Area : ', AsUnit( Aircraft.HTail.S, 'in**2') print 'HTail Length : ', AsUnit( Aircraft.HTail.L, 'in') #print 'Empty Weight : ', AsUnit( Aircraft.EmptyWeight, 'lbs') Aircraft.Draw() Aircraft.WriteAVLAircraft('AVLAircraft.avl') Wing.WingWeight.DrawDetail = True # VTail.WingWeight.DrawRibs = False # VTail.WingWeight.DrawDetail = False # VTail.WingWeight.Draw(fig = 2) # VTail.Draw(fig = 2) # # HTail.WingWeight.DrawRibs = False # HTail.WingWeight.DrawDetail = False # HTail.WingWeight.Draw(fig = 3) # HTail.Draw(fig = 3) # Aircraft.PlotPolarsSlopes(fig=3) #Aircraft.PlotCMPolars(4, (-10*ARCDEG, -5*ARCDEG, 0*ARCDEG, +5*ARCDEG, +10 * ARCDEG), XcgOffsets=(+0.05, -0.05)) ## CG LIMITS: AFT = +12%, FWD = -22% #HTail.Draw2DAirfoilPolars(fig=2) #Aircraft.PlotCLCMComponents(fig = 5, del_es = (-10*ARCDEG, -5*ARCDEG, 0*ARCDEG, +5*ARCDEG, +10 * ARCDEG)) #Aircraft.PlotPropulsionPerformance(fig=6) pyl.show()
[ "41376231+mwybo@users.noreply.github.com" ]
41376231+mwybo@users.noreply.github.com
89f84e5991577b3aaefe1cd98c93a8b80579f788
ae0434c20e5604a2beeb8183e577e8f1d91020f8
/Python/valid_parentheses.py
9008937d67f86b117651e8d7d11bf3bfe9bfc855
[]
no_license
savadev/leetcode-4
d0324078b9cdded4801888427ce1a13a83ef9e07
aec4b06b3bccc640ecfe5c349ccf9e71d5a33474
refs/heads/master
2020-12-31T20:04:22.904153
2016-05-07T20:46:43
2016-05-07T20:46:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
707
py
#!/usr/bin/env python # Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. # The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] p_dict = {')':'(', ']':'[', '}':'{'} for c in s: if c in p_dict.values(): stack.append(c) else: if stack and p_dict[c] == stack[-1]: stack.pop() else: return False return not stack
[ "rayzhang1011@gmail.com" ]
rayzhang1011@gmail.com
6d8979e0e0896e0486d44fe100a07499207bbae9
00ddd642a75e3c66321ac690ef4bffadfcf298c0
/framework/utils/rnn/rnn.py
109cafee737646a7207c86114cd7dd0aca677df5
[ "MIT" ]
permissive
Francesco-Sovrano/Combining--experience-replay--with--exploration-by-random-network-distillation-
51f444e58a53a051334a1152785c71f4007ec320
bf6f2b9a8703227dc40b06bbb170cbb89c04e76f
refs/heads/master
2020-05-01T11:42:24.393414
2020-01-03T21:09:58
2020-01-03T21:09:58
177,449,608
5
2
null
null
null
null
UTF-8
Python
false
false
9,126
py
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np from tensorflow.contrib.cudnn_rnn import CudnnLSTM, CudnnGRU from tensorflow.contrib.rnn import LSTMBlockCell, LSTMBlockFusedCell, GRUBlockCellV2 from utils.tensorflow_utils import gpu_count class RNN(object): def __init__(self, type, units, batch_size, direction=1, dtype='float32', stack_size=1, dropout=0., training=True): self.training = training self.stack_size = stack_size self.tf_dtype = eval('tf.{}'.format(dtype)) self.np_dtype = eval('np.{}'.format(dtype)) self.batch_size = batch_size self.units = units self.type = type self.use_gpu = gpu_count() > 0 # When you calculate the accuracy and validation, you need to manually set the keep_probability to 1 (or the dropout to 0) so that you don't actually drop any of your weight values when you are evaluating your network. If you don't do this, you'll essentially miscalculate the value you've trained your network to predict thus far. This could certainly negatively affect your acc/val scores. Especially with a 50% dropout_probability rate. self.dropout_probability = dropout if not self.training else 0. self.direction = direction self.rnn_layer = None if type == 'LSTM': self.cell = CudnnLSTM if self.use_gpu else LSTMBlockCell elif type == 'GRU': self.cell = CudnnGRU if self.use_gpu else GRUBlockCellV2 # State shape if self.use_gpu: # initial_state: a tuple of tensor(s) of shape [num_layers * num_dirs, batch_size, num_units] if self.type == 'LSTM': self.state_shape = [2, self.stack_size*self.direction, self.batch_size, self.units] elif type == 'GRU': self.state_shape = [1, self.stack_size*self.direction, self.batch_size, self.units] else: if self.type == 'LSTM': self.state_shape = [self.direction, self.stack_size, 2, self.batch_size, self.units] elif type == 'GRU': self.state_shape = [self.direction, self.stack_size, self.batch_size, self.units] def default_state(self): return np.zeros(self.state_shape, self.np_dtype) def state_placeholder(self, name=''): return tf.placeholder(shape=[None]+self.state_shape, name='{}_{}'.format(name,self.type), dtype=self.tf_dtype) def _process_single_batch(self, input, initial_state): # Build initial state if self.use_gpu: # initial_state: a tuple of tensor(s) of shape [num_layers * num_dirs, batch_size, num_units] initial_state = tuple(tf.unstack(initial_state)) else: state_list = [] if self.type == 'LSTM': for d in range(self.direction): state = initial_state[d] state_list.append([ tf.nn.rnn_cell.LSTMStateTuple(state[i][0],state[i][1]) for i in range(self.stack_size) ]) else: for d in range(self.direction): state_list.append(tf.unstack(initial_state[d])) initial_state = state_list output, final_state = self.rnn_layer(inputs=input, initial_state=initial_state) return output, final_state def process_batches(self, input, initial_states, sizes): # Add batch dimension, sequence length here is input batch size, while sequence batch size is batch_size if len(input.get_shape()) > 2: input = tf.layers.flatten(input) input_depth = input.get_shape().as_list()[-1] input = tf.reshape(input, [-1, self.batch_size, int(input_depth/self.batch_size)]) # Build RNN layer if self.rnn_layer is None: self.rnn_layer = self._build(input) # Get loop constants batch_limits = tf.concat([[0],tf.cumsum(sizes)], 0) batch_count = tf.shape(sizes)[0] output_shape = [self.batch_size, self.direction*self.units] # Build condition condition = lambda i, output, final_states: i < batch_count # Build body def body(i, output, final_states): start = batch_limits[i] end = batch_limits[i+1] ith_output, ith_final_state = self._process_single_batch(input=input[start:end], initial_state=initial_states[i]) output = tf.concat((output,ith_output), 0) final_states = tf.concat((final_states,[ith_final_state]), 0) return i+1, output, final_states # Build input i = 0 output = tf.zeros([1]+output_shape, self.tf_dtype) final_states = tf.zeros([1]+self.state_shape, self.tf_dtype) # Loop _, output, final_states = tf.while_loop( cond=condition, # A callable that represents the termination condition of the loop. body=body, # A callable that represents the loop body. loop_vars=[ i, # 1st variable # batch index output, # 2nd variable # RNN outputs final_states # 3rd variable # RNN final states ], shape_invariants=[ # The shape invariants for the loop variables. tf.TensorShape(()), # 1st variable tf.TensorShape([None]+output_shape), # 2nd variable tf.TensorShape([None]+self.state_shape) # 3rd variable ], swap_memory=True, # Whether GPU-CPU memory swap is enabled for this loop return_same_structure=True # If True, output has same structure as loop_vars. ) output = tf.layers.flatten(output) # Return result return output[1:], final_states[1:] # Remove first element we used to allow concatenations inside loop body def _build(self, inputs): if self.use_gpu: rnn = self.cell( num_layers=self.stack_size, num_units=self.units, direction='unidirectional' if self.direction == 1 else 'bidirectional', dropout=self.dropout_probability, # set to 0. for no dropout dtype=self.tf_dtype ) rnn.build(inputs.get_shape()) # Build now def rnn_layer(inputs, initial_state): # Do not build here, just call return rnn.call(inputs=inputs, initial_state=initial_state, training=self.training) return rnn_layer else: # Build RNN cells cell_list = [] for d in range(self.direction): cell_list.append([self.cell(num_units=self.units, name='{}_cell{}_{}'.format(self.type,d,i)) for i in range(self.stack_size)]) # Apply dropout_probability if self.dropout_probability > 0.: dropout = tf.nn.rnn_cell.DropoutWrapper for rnn_cells in cell_list: rnn_cells = [ dropout(cell=cell, output_keep_prob=1-self.dropout_probability) for cell in rnn_cells[:-1] ] + rnn_cells[-1:] # Do not apply dropout_probability to last layer, as in GPU counterpart implementation # Build stacked dynamic RNN <https://stackoverflow.com/questions/49242266/difference-between-multirnncell-and-stack-bidirectional-dynamic-rnn-in-tensorflo> # sequence_length = [tf.shape(inputs)[0]] if self.direction == 1: # Unidirectional def unidirectional_rnn_layer(inputs, initial_state): output = inputs final_state = [] for i,(cell,state) in enumerate(zip(cell_list[0],initial_state[0])): output, output_state = tf.nn.dynamic_rnn( cell = cell, inputs = output, initial_state = state, # sequence_length = sequence_length, time_major = True # The shape format of the inputs and outputs Tensors. If true, these Tensors must be shaped [max_time, batch_size, depth]. If false, these Tensors must be shaped [batch_size, max_time, depth]. Using time_major = True is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. ) final_state.append(output_state) final_state = tf.reshape([final_state], self.state_shape) return output, final_state return unidirectional_rnn_layer else: # Bidirectional def bidirectional_rnn_layer(inputs, initial_state): output, output_state_fw, output_state_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn( cells_fw = cell_list[0], # List of instances of RNNCell, one per layer, to be used for forward direction. cells_bw = cell_list[1], # List of instances of RNNCell, one per layer, to be used for backward direction. inputs = inputs, # The RNN inputs. this must be a tensor of shape: [batch_size, max_time, ...], or a nested tuple of such elements. initial_states_fw = initial_state[0], # (optional) A list of the initial states (one per layer) for the forward RNN. Each tensor must has an appropriate type and shape [batch_size, cell_fw.state_size]. initial_states_bw = initial_state[1], # (optional) Same as for initial_states_fw, but using the corresponding properties of cells_bw. # sequence_length = sequence_length, # (optional) An int32/int64 vector, size [batch_size], containing the actual lengths for each of the sequences. time_major = True # The shape format of the inputs and outputs Tensors. If true, these Tensors must be shaped [max_time, batch_size, depth]. If false, these Tensors must be shaped [batch_size, max_time, depth]. Using time_major = True is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. ) final_state = [output_state_fw, output_state_bw] final_state = tf.reshape(final_state, self.state_shape) return output, final_state return bidirectional_rnn_layer
[ "toor@MacBook-Pro-di-Toor.local" ]
toor@MacBook-Pro-di-Toor.local
0a94e8b28ffb9b780fef50e6b6ab2f2f57064e96
8842fdf7738b51469fda6803688d5e66ce7bdc20
/MD5.py
45326261e43b1d54f014ad1f23c3ff82ea90a5fe
[]
no_license
yadav-umesh/DATA
bf1c79b5db426e125774e5ed99dd243345cc76fa
d83ac5a4f789b36c828229703d0c67da697eac40
refs/heads/master
2020-09-21T07:24:41.874695
2019-11-29T06:14:06
2019-11-29T06:14:06
224,723,488
0
0
null
null
null
null
UTF-8
Python
false
false
2,596
py
import math rotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] constants = [int(abs(math.sin(i + 1)) * 2 ** 32) & 0xFFFFFFFF for i in range(64)] init_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] functions = 16 * [lambda b, c, d: (b & c) | (~b & d)] + \ 16 * [lambda b, c, d: (d & b) | (~d & c)] + \ 16 * [lambda b, c, d: b ^ c ^ d] + \ 16 * [lambda b, c, d: c ^ (b | ~d)] index_functions = 16 * [lambda i: i] + \ 16 * [lambda i: (5 * i + 1) % 16] + \ 16 * [lambda i: (3 * i + 5) % 16] + \ 16 * [lambda i: (7 * i) % 16] def left_rotate(x, amount): x &= 0xFFFFFFFF return ((x << amount) | (x >> (32 - amount))) & 0xFFFFFFFF def md5(message): message = bytearray(message) # copy our input into a mutable buffer orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff message.append(0x80) while len(message) % 64 != 56: message.append(0) message += orig_len_in_bits.to_bytes(8, byteorder='little') hash_pieces = init_values[:] for chunk_ofst in range(0, len(message), 64): a, b, c, d = hash_pieces chunk = message[chunk_ofst:chunk_ofst + 64] for i in range(64): f = functions[i](b, c, d) g = index_functions[i](i) to_rotate = a + f + constants[i] + int.from_bytes(chunk[4 * g:4 * g + 4], byteorder='little') new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF a, b, c, d = d, new_b, b, c for i, val in enumerate([a, b, c, d]): hash_pieces[i] += val hash_pieces[i] &= 0xFFFFFFFF return sum(x << (32 * i) for i, x in enumerate(hash_pieces)) def md5_to_hex(digest): raw = digest.to_bytes(16, byteorder='little') return '{:032x}'.format(int.from_bytes(raw, byteorder='big')) if __name__ == '__main__': demo = [b"", b"a", b"abc", b"message digest", b"abcdefghijklmnopqrstuvwxyz", b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"] for message in demo: print(md5_to_hex(md5(message)), ' <= "', message.decode('ascii'), '"', sep='')
[ "noreply@github.com" ]
noreply@github.com
d27a3896f5fa3feb5f17cd7861eb6378cabfc5d6
867846ed1df7f560ccc473413a70020155f66ad4
/writeImageToBinary.py
8ebf38106007bbfc86bd7004a67293c4219d32a9
[]
no_license
abhineet123/PTF
84297bf5aa95320dbc2d34f422f2dd563ff65a58
0c63f7f8251af0d70c329b2cef53694db76c1656
refs/heads/master
2023-08-18T18:34:40.513936
2023-08-09T17:28:51
2023-08-09T17:28:51
157,794,848
5
1
null
2021-05-16T18:48:32
2018-11-16T01:24:05
MATLAB
UTF-8
Python
false
false
4,088
py
# from DecompUtils import * # from distanceGrid import applyFilter # import time import os import cv2 import numpy as np # from Misc import getParamDict if __name__ == '__main__': db_root_dir = 'C:/Datasets' track_root_dir = '../Tracking Data' img_root_dir = '../Image Data' dist_root_dir = '../Distance Data' track_img_root_dir = '../Tracked Images' # params_dict = getParamDict() # param_ids = readDistGridParams() # # actors = params_dict['actors'] # sequences = params_dict['sequences'] # challenges = params_dict['challenges'] # filter_types = params_dict['filter_types'] # # actor_id = param_ids['actor_id'] # seq_id = param_ids['seq_id'] # challenge_id = param_ids['challenge_id'] # inc_id = param_ids['inc_id'] # start_id = param_ids['start_id'] # filter_id = param_ids['filter_id'] # kernel_size = param_ids['kernel_size'] # show_img = param_ids['show_img'] # # arg_id = 1 # if len(sys.argv) > arg_id: # actor_id = int(sys.argv[arg_id]) # arg_id += 1 # if len(sys.argv) > arg_id: # seq_id = int(sys.argv[arg_id]) # arg_id += 1 # if len(sys.argv) > arg_id: # challenge_id = int(sys.argv[arg_id]) # arg_id += 1 # if len(sys.argv) > arg_id: # filter_id = int(sys.argv[arg_id]) # arg_id += 1 # # if actor_id >= len(actors): # print 'Invalid actor_id: ', actor_id # sys.exit() # # actor = actors[actor_id] # sequences = sequences[actor] # # if seq_id >= len(sequences): # print 'Invalid dataset_id: ', seq_id # sys.exit() # if challenge_id >= len(challenges): # print 'Invalid challenge_id: ', challenge_id # sys.exit() # if filter_id >= len(filter_types): # print 'Invalid filter_id: ', filter_id # sys.exit() # # seq_name = sequences[seq_id] # filter_type = filter_types[filter_id] # challenge = challenges[challenge_id] # # if actor == 'METAIO': # seq_name = seq_name + '_' + challenge actor = 'GRAM' seq_name = 'idot_1_intersection_city_day_short' start_id = 0 filter_type = 'none' kernel_size = 3 show_img = 1 print 'actor: ', actor # print 'seq_id: ', seq_id print 'seq_name: ', seq_name # print 'filter_type: ', filter_type # print 'kernel_size: ', kernel_size src_dir = db_root_dir + '/' + actor + '/Images/' + seq_name if not os.path.exists(img_root_dir): os.makedirs(img_root_dir) if filter_type != 'none': img_fname = img_root_dir + '/' + seq_name + '_' + filter_type + str(kernel_size) + '.bin' else: img_fname = img_root_dir + '/' + seq_name + '.bin' print 'Reading images from: {:s}'.format(src_dir) print 'Writing image binary data to: {:s}'.format(img_fname) img_fid = open(img_fname, 'wb') file_list = os.listdir(src_dir) # print 'file_list: ', file_list no_of_frames = len(file_list) print 'no_of_frames: ', no_of_frames end_id = no_of_frames init_img = cv2.imread(src_dir + '/image{:06d}.jpg'.format(1)) img_height = init_img.shape[0] img_width = init_img.shape[1] # np.array([no_of_frames, ], dtype=np.uint32).tofile(img_fid) np.array([img_width, img_height], dtype=np.uint32).tofile(img_fid) win_name = 'Filtered Image' if show_img: cv2.namedWindow(win_name) for frame_id in xrange(start_id, end_id): # print 'frame_id: ', frame_id curr_img = cv2.imread(src_dir + '/image{:06d}.jpg'.format(frame_id + 1)) if len(curr_img.shape) == 3: curr_img_gs = cv2.cvtColor(curr_img, cv2.cv.CV_BGR2GRAY) else: curr_img_gs = curr_img # if filter_type != 'none': # curr_img_gs = applyFilter(curr_img_gs, filter_type, kernel_size) curr_img_gs.astype(np.uint8).tofile(img_fid) if show_img: cv2.imshow(win_name, curr_img_gs) if cv2.waitKey(1) == 27: break img_fid.close()
[ "asingh1@ualberta.ca" ]
asingh1@ualberta.ca
dc626b4ebb260142009e22ea191beae6612323fb
64f1558d2549c2f0b9d3a6fa3200eaf7cc3e486b
/openodia/_understandData.py
52ab2b14e9f0c776897248d7085a7c7388e828fc
[ "MIT" ]
permissive
JanviRaina/openodia
e38b02abd261fdb50f0a634b4279326d77802eff
f33d095afcb2e87108986ecf16a5ee0f59568502
refs/heads/main
2023-08-19T01:43:51.503249
2021-10-10T17:08:26
2021-10-10T17:08:26
411,574,369
0
0
MIT
2021-09-29T07:32:43
2021-09-29T07:32:42
null
UTF-8
Python
false
false
2,286
py
import re from typing import Any, Dict, List, Union from openodia.common.constants import STOPWORDS from openodia.common.utility import LOGGER class UnderstandData: """Tokenizer implementation""" @classmethod def word_tokenizer(cls, text): """Split the text into words""" # TODO: Do not remove the punctuation characters token_list = [ token for token in re.split( r"[!\"#$%&\'()*+,-./:;<=>?@[\\\]\^\_`{|}~୲—\s+]", text, flags=re.UNICODE ) if token ] return token_list @classmethod def sentence_tokenizer(cls, text): """Split the text into sentences""" sent_list = text.split(" ।") LOGGER.debug(f"{len(sent_list)} sentences have been formed using ' ।' splitter.") return sent_list @classmethod def remove_stopwords( cls, text: Union[str, List[str]], get_str: bool = False ) -> Union[List[str], str]: """Remove frequently used words from the text :param text: It can take both tokens and text string as input :param get_str: provide whether the output needed on str or list """ token_list: List[str] = cls.word_tokenizer(text) if isinstance(text, str) else text cleaned_tokens = [token for token in token_list if token not in STOPWORDS] return " ".join(cleaned_tokens) if get_str else cleaned_tokens @classmethod def detect_language(cls, text: str, threshold: float = 0.5) -> Dict[str, Any]: """Detect language if it is Odia or non-Odia :param text: text to detect language :param threshold: confidence score which if crossed will be determined as Odia """ if len(text) == 0: print("No text detected") return {} space_removed_text = text.replace(" ", "") odia_text = "".join( [letter for letter in space_removed_text if ord(letter) in range(2817, 2931)] ) score = len(odia_text) / len(space_removed_text) language = "odia" if score > threshold else "non-odia" confidence_score = score if language == "odia" else 1 - score return {"language": language, "confidence_score": round(confidence_score, 2)}
[ "soumendra.s@outlook.com" ]
soumendra.s@outlook.com
336b66817aeb69caf5a08e2b80c1beac92d48c6d
de01cb554c2292b0fbb79b4d5413a2f6414ea472
/algorithms/Easy/1275.find-winner-on-a-tic-tac-toe-game.py
b051c0e2d84dffb8192059fd3585ceb77ed909e8
[]
no_license
h4hany/yeet-the-leet
98292017eadd3dde98a079aafcd7648aa98701b4
563d779467ef5a7cc85cbe954eeaf3c1f5463313
refs/heads/master
2022-12-10T08:35:39.830260
2020-09-02T23:12:15
2020-09-02T23:12:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,576
py
# # @lc app=leetcode id=1275 lang=python3 # # [1275] Find Winner on a Tic Tac Toe Game # # https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/description/ # # algorithms # Easy (52.88%) # Total Accepted: 17K # Total Submissions: 32.2K # Testcase Example: '[[0,0],[2,0],[1,1],[2,1],[2,2]]' # # Tic-tac-toe is played by two players A and B on a 3 x 3 grid. # # Here are the rules of Tic-Tac-Toe: # # # Players take turns placing characters into empty squares (" "). # The first player A always places "X" characters, while the second player B # always places "O" characters. # "X" and "O" characters are always placed into empty squares, never on filled # ones. # The game ends when there are 3 of the same (non-empty) character filling any # row, column, or diagonal. # The game also ends if all squares are non-empty. # No more moves can be played if the game is over. # # # Given an array moves where each element is another array of size 2 # corresponding to the row and column of the grid where they mark their # respective character in the order in which A and B play. # # Return the winner of the game if it exists (A or B), in case the game ends in # a draw return "Draw", if there are still movements to play return "Pending". # # You can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the # grid is initially empty and A will play first. # # # Example 1: # # # Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]] # Output: "A" # Explanation: "A" wins, he always plays first. # "X " "X " "X " "X " "X " # " " -> " " -> " X " -> " X " -> " X " # " " "O " "O " "OO " "OOX" # # # Example 2: # # # Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]] # Output: "B" # Explanation: "B" wins. # "X " "X " "XX " "XXO" "XXO" "XXO" # " " -> " O " -> " O " -> " O " -> "XO " -> "XO " # " " " " " " " " " " "O " # # # Example 3: # # # Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]] # Output: "Draw" # Explanation: The game ends in a draw since there are no moves to make. # "XXO" # "OOX" # "XOX" # # # Example 4: # # # Input: moves = [[0,0],[1,1]] # Output: "Pending" # Explanation: The game has not finished yet. # "X " # " O " # " " # # # # Constraints: # # # 1 <= moves.length <= 9 # moves[i].length == 2 # 0 <= moves[i][j] <= 2 # There are no repeated elements on moves. # moves follow the rules of tic tac toe. # # class Solution: def tictactoe(self, moves: List[List[int]]) -> str:
[ "kevin.wkmiao@gmail.com" ]
kevin.wkmiao@gmail.com
e9f6eacfaf01a7fff4da4c15768700dfd006c709
423cc7775d1ab9874729ba304d7682a12b4a4d43
/plugins/analyzer/previewcomparer.py
6cc2539edc04ea1fb6f7350dfbf6e684d05043bc
[]
no_license
eyeyunianto/ghiro
7ec2dc5ae2b766883da6f26975fd41829336e8f8
24ce80244893fc94300e1c4f5e3305bd182d65a6
refs/heads/master
2020-04-06T04:33:07.155509
2015-06-21T21:30:27
2015-06-21T21:30:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,807
py
# Ghiro - Copyright (C) 2013-2015 Ghiro Developers. # This file is part of Ghiro. # See the file 'docs/LICENSE.txt' for license terms. import logging from itertools import izip from lib.analyzer.base import BaseAnalyzerModule from lib.utils import str2image from lib.db import get_file try: from PIL import Image IS_PIL = True except ImportError: IS_PIL = False logger = logging.getLogger(__name__) class ImageComparer(): """Image comparator.""" @staticmethod def calculate_difference(preview, original_image_id): """Calculate difference between two images. @param preview: preview dict @param original_image_id: original image ID @return: difference, difference percentage """ try: i1 = str2image(get_file(original_image_id).read()) except IOError as e: logger.warning("Comparer error reading image: {0}".format(e)) return # Check if thumb was resized. if "original_file" in preview: i2 = str2image(get_file(preview["original_file"]).read()) else: i2 = str2image(get_file(preview["file"]).read()) # Resize. width, height = i2.size try: i1 = i1.resize([width, height], Image.ANTIALIAS) except IOError as e: logger.warning("Comparer error reading image: {0}".format(e)) return # Checks. #assert i1.mode == i2.mode, "Different kinds of images." #assert i1.size == i2.size, "Different sizes." # Calculate difference. pairs = izip(i1.getdata(), i2.getdata()) if len(i1.getbands()) == 1: # for gray-scale jpegs dif = sum(abs(p1-p2) for p1,p2 in pairs) else: dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2)) ncomponents = i1.size[0] * i1.size[1] * 3 # Get diff percentage. diff_perc = int((dif / 255.0 * 100) / ncomponents) # Binary option. if diff_perc >= 15: diff = True else: diff = False return diff, diff_perc class PreviewComparerAnalyzer(BaseAnalyzerModule): """Compares previews extracted with the original image.""" order = 20 def check_deps(self): return IS_PIL def run(self, task): # Compare previews to catch differences. if "metadata" in self.results: if "preview" in self.results["metadata"]: for preview in self.results["metadata"]["preview"]: difference = ImageComparer.calculate_difference(preview, self.results["file_data"]) if difference: preview["diff"], preview["diff_percent"] = difference return self.results
[ "alessandro@tanasi.it" ]
alessandro@tanasi.it
56cc9c7aab8b053852097bf92de03832d5bbbbe3
3a6a9bd8cb6a977b77c9313282b769177bf1e0c6
/src/data_access/via_DMS/DMSDatabase.py
3fdc487f0c8cc8bfabf09c2f02b32b31692bdfb0
[]
no_license
PNNL-Comp-Mass-Spec/NMDC-Proteomics-Workflow
d34dd04ac1e32b7cfc77df3252ebec6a873f2ee2
1c8d04a6cdb497905a42e026663b39417ffdad02
refs/heads/master
2022-11-24T22:56:20.454860
2020-08-06T02:33:35
2020-08-06T02:33:35
266,201,144
0
0
null
null
null
null
UTF-8
Python
false
false
1,553
py
import pymssql import logging import sys class DMSDatabase: ''' Database connection class''' def __init__(self, config): ''' :param config: ''' self.SERVER = config.db_server self.USER = config.db_user self.PASSWORD = config.db_password self.DATABASE_NAME = config.db_name self.conn = None def open_connection(self): ''' Connection to DMS MS sqlserver i.e DMS5 or DMS_Data_Package ''' try: if self.conn is None: self.conn = pymssql.connect(server = self.SERVER, user = self.USER, password = self.PASSWORD, database= self.DATABASE_NAME) except pymssql.MySQLError as conn_err: logging.error(conn_err) sys.exit() finally: logging.info("Connection opened successfully") def run_query(self, query): '''Execute SQL query. ''' try: self.open_connection() # Create cursor cursor = self.conn.cursor(as_dict=True) cursor.execute(query) # generator object. return cursor except Exception as e: print(e) # FIXME: Close connection and test again! # finally: # if self.conn: # self.conn.close() # self.conn=None # logging.info("Database connection closed")
[ "anubhav@pnnl.gov" ]
anubhav@pnnl.gov
a13daec41fb007a716ec02000dd869e5b10ad0d7
65ff11d13d2f8e007d2224005329cce07ec8b84b
/mysite/polls/models.py
ce7d109d899c93e7c008d8ccf36190e3be3ee80f
[]
no_license
jpinfanti/MyProjects
19d9f1ed992dcd4d66d03eab46ae65e51f4c98c6
2199876d1c1d391998ac46a30b7626b1ca7befed
refs/heads/master
2020-05-25T09:21:00.079517
2019-06-01T11:13:52
2019-06-01T11:13:52
187,733,712
0
0
null
null
null
null
UTF-8
Python
false
false
871
py
import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text
[ "jpinfanti@gmail.com" ]
jpinfanti@gmail.com
bd8c5e0702e994db9f0374d5bbc3e2dbd3556e83
83dfcc05045a2dbe797bb7869932a03881d6f33a
/tools/preprocess_pascal_voc.py
6703656b4110e2f9a3cc5930ca20ea89d12d53e4
[]
no_license
deepaksinghdangi/Yolo-DNA
8de4bc488603ec178dcff38f168ab6c3ab3c7235
870424e67c02edc38489acdce98acec194342ff5
refs/heads/master
2021-04-28T13:51:11.982694
2018-04-01T13:49:07
2018-04-01T13:49:07
121,951,015
0
1
null
null
null
null
UTF-8
Python
false
false
2,323
py
"""preprocess pascal_voc data """ import os import xml.etree.ElementTree as ET import struct import numpy as np PASCAL_OP='data\\pascal_voc.txt' YOLO_ROOT_PATH='data\\VOCdevkit2007' classes_name = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train","tvmonitor"] classes_num = {'aeroplane': 0, 'bicycle': 1, 'bird': 2, 'boat': 3, 'bottle': 4, 'bus': 5, 'car': 6, 'cat': 7, 'chair': 8, 'cow': 9, 'diningtable': 10, 'dog': 11, 'horse': 12, 'motorbike': 13, 'person': 14, 'pottedplant': 15, 'sheep': 16, 'sofa': 17, 'train': 18, 'tvmonitor': 19} YOLO_ROOT = os.path.abspath('.') DATA_PATH = os.path.join(YOLO_ROOT, YOLO_ROOT_PATH) OUTPUT_PATH = os.path.join(YOLO_ROOT, PASCAL_OP) def parse_xml(xml_file): """parse xml_file Args: xml_file: the input xml file path Returns: image_path: string labels: list of [xmin, ymin, xmax, ymax, class] """ tree = ET.parse(xml_file) root = tree.getroot() image_path = '' labels = [] for item in root: if item.tag == 'filename': image_path = os.path.join(DATA_PATH, 'VOC2007\\JPEGImages', item.text) elif item.tag == 'object': obj_name = item[0].text obj_num = classes_num[obj_name] xmin = int(item[4][0].text) ymin = int(item[4][1].text) xmax = int(item[4][2].text) ymax = int(item[4][3].text) labels.append([xmin, ymin, xmax, ymax, obj_num]) return image_path, labels def convert_to_string(image_path, labels): """convert image_path, lables to string Returns: string """ out_string = '' out_string += image_path for label in labels: for i in label: out_string += ' ' + str(i) out_string += '\n' return out_string def main(): out_file = open(OUTPUT_PATH, 'w') xml_dir = DATA_PATH + "\\VOC2007\\Annotations\\" xml_list = os.listdir(xml_dir) print(xml_list[0]) xml_list = [xml_dir + temp for temp in xml_list] print("Helo from Anuj") print(xml_list[0]) for xml in xml_list: try: image_path, labels = parse_xml(xml) record = convert_to_string(image_path, labels) out_file.write(record) except Exception: pass out_file.close() if __name__ == '__main__': main()
[ "noreply@github.com" ]
noreply@github.com
3101fafbbcfc2cfaa0e6f7a1575e16028e6c40f7
e8d59cb03af8da46d8e0dafcc721dc4e7681f9ef
/ex005.py
ee00125552322f8e31b66bcd1f523f015eb3dee4
[ "MIT" ]
permissive
GuilhermeAntony14/Estudando-Python
51490ff7e37500bbfd936af0e1a616e2f960239d
b020f6d2625e7fcc42d30658bcbd881b093434dd
refs/heads/main
2023-04-14T01:26:38.004729
2021-04-26T01:17:42
2021-04-26T01:17:42
361,016,865
0
0
null
null
null
null
UTF-8
Python
false
false
187
py
v1 = int(input('adicione um numero: ')) print(f' \n Antecessor \033[34m{v1-1:>10}\033[m ' f'\n Valor original \033[34m{v1:>6}\033[m ' f'\n Sucessor \033[34m{v1+1:>12}\033[m')
[ "gdutramerlo@gmail.com" ]
gdutramerlo@gmail.com
70136f71853311d56750505b916562c57a3ecfe2
91d550f23c8716eb06171f41f2fd54d3e2d17a04
/TODO/TODOapp/migrations/0017_auto_20181117_0124.py
4feaeaaff74fa0b0a16b0a819a278b1664088d0d
[]
no_license
johannesWestenhoeferGit/scalors-assignment-backend-todo
b5c5470b6d9112452f1a82732ee946f1108e1df9
362d974430f85e52086d79fc4220290c751a1c08
refs/heads/master
2020-04-07T10:51:13.982057
2018-11-19T23:24:20
2018-11-19T23:24:20
158,300,412
0
0
null
null
null
null
UTF-8
Python
false
false
490
py
# Generated by Django 2.1.3 on 2018-11-17 00:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('TODOapp', '0016_auto_20181117_0115'), ] operations = [ migrations.AlterField( model_name='todo', name='board', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='TODOapp.Board'), ), ]
[ "45103219+johannesWestenhoeferGit@users.noreply.github.com" ]
45103219+johannesWestenhoeferGit@users.noreply.github.com
5159d1ced08d025941903ecb69f0c155b3a03343
20c1fbd31cdab2b198574fa13d36aa46f7ab093f
/Chapter3_2.py
27adf263d210068d0948ff92465d46738aa6f313
[]
no_license
EyeMyData/INFX501
093fd879a84673b61b54f7db18f305a3ca62b86d
2243e425725e3214f0d5d0c067bf125f0e64e237
refs/heads/master
2021-01-15T16:28:33.583772
2015-12-07T02:19:26
2015-12-07T02:19:26
44,037,011
0
0
null
null
null
null
UTF-8
Python
false
false
631
py
## Exercise 2: Rewrite your pay program using try and except so that your ## program handles non-numeric input gracefully by printing a message ## and exiting the program. The following shows the output from three ## executions of the program: hours = input('Enter Hours: ') rate = input('Enter Rate: ') try: hours = float(hours) rate = float(rate) if hours > 40: overtime = hours- 40 overtimepay = overtime*(1.5*rate) regularpay = 40*rate print('Pay:', regularpay+overtimepay) else : pay = hours*rate print('Pay:', pay) except: print('Please enter a number')
[ "rtbrush@yahoo.com" ]
rtbrush@yahoo.com
5280e76f15eda7f59c1e3df3589cfef7933ddb8c
b04e7039549ab26aee5b8f8e41d6508cc5a12815
/Logic/functionalitati.py
84742e194c6aa264ea41e9064166070ac96f94e6
[]
no_license
H0R4T1U/Asociatii
bb5da881178607ffdd8bbf20d0c1c8f53cb64b04
ce75b121803c86c19dcb9c1a151e77df927e75ca
refs/heads/main
2023-01-02T17:30:49.630560
2020-10-28T21:56:36
2020-10-28T21:56:36
308,148,343
0
0
null
null
null
null
UTF-8
Python
false
false
159
py
from Logic.crud import get_nr_apt def sterge_toate_cheltuielile(nr_apt,lista): [cheltuiala for cheltuiala in lista if get_nr_apt(cheltuiala) != nr_apt]
[ "horatiubanciu11@gmail.com" ]
horatiubanciu11@gmail.com
f7a2533e7ef495540bbd17beb264ad19363e9de1
2eb318ab2034256e68dc3c2d33abd203fbadcc45
/the actual siri.py
700a4970ef43ccd0a4e3c58888a8b554be4b70ac
[]
no_license
Gustavasa/PG_ENY
c779a1a2664af19f5417fc4482e7c4afc0ef0b1e
37481673785183a93b7847aedef4aadedb2fbd1d
refs/heads/master
2021-09-14T17:21:02.955190
2018-05-16T15:43:52
2018-05-16T15:43:52
116,997,453
0
0
null
null
null
null
UTF-8
Python
false
false
628
py
import win32com.client as wincl import speech_recognition as sr import webbrowser as wb speak = wincl.Dispatch("SAPI.SpVoice") r = sr.Recognizer() with sr.Microphone() as source: speak.Speak("Hello Erik how can I help you") print("listening...") audio = r.listen(source) print("thinking...") try: words = r.recognize_google(audio) speak.Speak("Lets go and look for" + r.recognize_google(audio)) wb.open("https://www.google.com/search?q=" + words) except sr.UnknownValueError: speak.Speak("what are you saying") except sr.RequestError as e: speak.Speak("nope")
[ "noreply@github.com" ]
noreply@github.com
f5654ebb548102ad5967c419da8d9acc2be6c724
84ce2afa75e1fede9ec5dad94381f8a406e8b44f
/hello-world/quotes.py
41bc03835b643b05fb88efd6d6599f923f1cd08a
[ "MIT" ]
permissive
selvendiranj-zz/python-tutorial
c920b0b3565a90792743414b1c357f77d04ce62f
e3fd0855fc06b1b3ec45079cd6bd055a439d2e84
refs/heads/master
2021-09-05T15:18:30.150647
2018-01-29T07:20:55
2018-01-29T07:20:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
369
py
""" Python accepts single ('), double () and triple (''' or ) quotes to denote string literals, as long as the same type of quote starts and ends the string. """ word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences.""" days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
[ "selvendiranj@gmail.com" ]
selvendiranj@gmail.com
04ddbac7ba10873f1683d524b740172d45be4312
f5cbcc5f356fbcb801545b358241e3a0e283a3a9
/setting.py
fe5c764f9cbbc02b1d935eed59a78b2b66af6b64
[]
no_license
hulinbig/flaskblog
6c1001decf4e1a5241d7153759f6599ea0767137
13def2b1a83b06792f646f4217fd78a6d30ecf39
refs/heads/master
2023-04-05T01:41:28.456457
2021-04-14T01:53:42
2021-04-14T01:53:42
317,810,762
0
0
null
null
null
null
UTF-8
Python
false
false
963
py
#!-*- coding:utf-8 -*- import os __author__ = 'ALX LIN' class Config: ENV = 'development' DEBUG = True #mysql + pymysql://user:password@host:port/databasename SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:123456@localhost:3306/blog" #这里只能用localhost,不能用本家地址127.0.0.1 SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_ECHO = True #secret_key SECRET_KEY = 'sdfdsfsdfsefsdf12fsdf' #项目路径 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) #静态文件夹的路径 STATIC_DIR = os.path.join(BASE_DIR, 'static') TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') #头像的上传目录 UPLOAD_ICON_DIR = os.path.join(STATIC_DIR, 'upload/icon') #相册的上传目录 UPLOAD_PHOTO_DIR = os.path.join(STATIC_DIR, 'upload/photo') class DevelopmentConfig(Config): ENV = 'development' class ProductionConfig(Config): ENV = 'production' DEBUG = False
[ "hulinbig" ]
hulinbig
72a2fc5198d4c85f8cce4bbdb3d5833ef90ac973
ccd0d58fc77536f289ef2da4b66406966b514162
/Cluster.py
26edfe154ce91a59662b957412429384949fa882
[]
no_license
hiafi/cs497_project
07d2ea2a6e492196aaed35edec0fa5bf0473959a
6acc554180e0bdef2c31eacd6d59ecc4dc843512
refs/heads/master
2016-09-08T05:06:06.424951
2013-06-03T19:07:44
2013-06-03T19:07:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,920
py
#!/usr/bin/python #-------------------------------------------------------------------------------- #Jonathan Roberts, Nathaniel Nguyen, and John Ho #Computer Science 497B #Spring Quarter 2013 #Network Intrusion Project #------------------------------------------------------------------------------ # Credits to pandoricweb.tumblr.com/post/8646701677/python-implementation-of # -k-means-clustering for source code #------------------------------------------------------------------------------- import Point #------------------------------------------------------------------------------- class Cluster: #--------------------------------------------------------------------------- def __init__(self, points): #Check if cluster is empty if ( len(points) == 0 ): raise Exception("ILLEGAL: empty cluster") #Check if all points in cluster are the same dimensions self.points = points self.n = points[0].n for p in points: if ( p.n != self.n): raise Exception("ILLEGAL: wrong dimensions") self.centroid = self.calculateCentroid() #--------------------------------------------------------------------------- def __repr__(self): return str(self.points) #--------------------------------------------------------------------------- def update(self, points, distanceFormula): old_centroid = self.centroid self.points = points self.centroid = self.calculateCentroid() return distanceFormula(old_centroid, self.centroid) #--------------------------------------------------------------------------- def calculateCentroid(self): reduce_coord = lambda i:reduce(lambda x,p : x + p.coords[i], self.points, 0.0) centroid_coords = [reduce_coord(i) / len(self.points) for i in range(self.n)] return Point.Point(centroid_coords)
[ "nnguyen939@gmail.com" ]
nnguyen939@gmail.com
791aa3c7a4424a4e38c935d847f9fa57c01e7616
780c28373887ae0ef1ced41732987ace7647384f
/vinmonopol/env/bin/pip2.7
948c3172dfc3d73761e1c3750d2fc4dd30a769f6
[]
no_license
Paalar/AlcoSearch
1803262018098f2a59fc4689e7ad4da629a68909
a3a7cece79e5efd132e4295c114544398aa43ee4
refs/heads/master
2021-03-30T17:57:03.354123
2018-05-31T08:37:02
2018-05-31T08:37:02
107,410,954
0
0
null
null
null
null
UTF-8
Python
false
false
272
7
#!/Users/GPD/Desktop/python-docs-samples/appengine/standard/django/env/bin/python2.7 # -*- coding: utf-8 -*- import re import sys from pip import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "paaledward@gmail.com" ]
paaledward@gmail.com
30d1666faf99c5f78e76ef60c5dcde682f89ddb2
b51d9f725c349c71d5ef6678d615d346b105272b
/src/captcha/conf/settings.py
41dee9bd23b62938b1c26d160bfe19defad909d3
[]
no_license
lpe234/dannysite.com
9557a5ed19da223057d6617153388526398618b1
2edae21fcfaec8625422007cc9ef4e1471a4ea54
refs/heads/master
2021-01-17T05:54:39.802076
2014-04-07T04:36:33
2014-04-07T04:36:33
22,376,149
1
0
null
2019-01-08T09:41:41
2014-07-29T10:24:22
null
UTF-8
Python
false
false
2,658
py
import os from django.conf import settings CAPTCHA_FONT_PATH = getattr(settings, 'CAPTCHA_FONT_PATH', os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'fonts/Vera.ttf'))) CAPTCHA_FONT_SIZE = getattr(settings, 'CAPTCHA_FONT_SIZE', 22) CAPTCHA_LETTER_ROTATION = getattr(settings, 'CAPTCHA_LETTER_ROTATION', (-35, 35)) CAPTCHA_BACKGROUND_COLOR = getattr(settings, 'CAPTCHA_BACKGROUND_COLOR', '#ffffff') CAPTCHA_FOREGROUND_COLOR = getattr(settings, 'CAPTCHA_FOREGROUND_COLOR', '#001100') CAPTCHA_CHALLENGE_FUNCT = getattr(settings, 'CAPTCHA_CHALLENGE_FUNCT', 'captcha.helpers.random_char_challenge') CAPTCHA_NOISE_FUNCTIONS = getattr(settings, 'CAPTCHA_NOISE_FUNCTIONS', ('captcha.helpers.noise_arcs', 'captcha.helpers.noise_dots',)) CAPTCHA_FILTER_FUNCTIONS = getattr(settings, 'CAPTCHA_FILTER_FUNCTIONS', ('captcha.helpers.post_smooth',)) CAPTCHA_WORDS_DICTIONARY = getattr(settings, 'CAPTCHA_WORDS_DICTIONARY', '/usr/share/dict/words') CAPTCHA_PUNCTUATION = getattr(settings, 'CAPTCHA_PUNCTUATION', '''_"',.;:-''') CAPTCHA_FLITE_PATH = getattr(settings, 'CAPTCHA_FLITE_PATH', None) CAPTCHA_TIMEOUT = getattr(settings, 'CAPTCHA_TIMEOUT', 5) # Minutes CAPTCHA_LENGTH = int(getattr(settings, 'CAPTCHA_LENGTH', 4)) # Chars CAPTCHA_IMAGE_BEFORE_FIELD = getattr(settings, 'CAPTCHA_IMAGE_BEFORE_FIELD', True) CAPTCHA_DICTIONARY_MIN_LENGTH = getattr(settings, 'CAPTCHA_DICTIONARY_MIN_LENGTH', 0) CAPTCHA_DICTIONARY_MAX_LENGTH = getattr(settings, 'CAPTCHA_DICTIONARY_MAX_LENGTH', 99) if CAPTCHA_IMAGE_BEFORE_FIELD: CAPTCHA_OUTPUT_FORMAT = getattr(settings, 'CAPTCHA_OUTPUT_FORMAT', u'%(image)s %(hidden_field)s %(text_field)s') else: CAPTCHA_OUTPUT_FORMAT = getattr(settings, 'CAPTCHA_OUTPUT_FORMAT', u'%(hidden_field)s %(text_field)s %(image)s') CATPCHA_TEST_MODE = getattr(settings, 'CAPTCHA_TEST_MODE', False) # Failsafe if CAPTCHA_DICTIONARY_MIN_LENGTH > CAPTCHA_DICTIONARY_MAX_LENGTH: CAPTCHA_DICTIONARY_MIN_LENGTH, CAPTCHA_DICTIONARY_MAX_LENGTH = CAPTCHA_DICTIONARY_MAX_LENGTH, CAPTCHA_DICTIONARY_MIN_LENGTH def _callable_from_string(string_or_callable): if callable(string_or_callable): return string_or_callable else: return getattr(__import__('.'.join(string_or_callable.split('.')[:-1]), {}, {}, ['']), string_or_callable.split('.')[-1]) def get_challenge(): return _callable_from_string(CAPTCHA_CHALLENGE_FUNCT) def noise_functions(): if CAPTCHA_NOISE_FUNCTIONS: return map(_callable_from_string, CAPTCHA_NOISE_FUNCTIONS) return [] def filter_functions(): if CAPTCHA_FILTER_FUNCTIONS: return map(_callable_from_string, CAPTCHA_FILTER_FUNCTIONS) return []
[ "manyunkai@hotmail.com" ]
manyunkai@hotmail.com
d710a089b2dc8dcb65b7b3f939796b6203abf478
74b7a3165c1ef143fc648e83c228795ee70c0e26
/cs253.py
5fae75f99073dd8fb38c3317de33dcf9deb9b433
[]
no_license
Nandan1996/Intro-To-Backend
98d90ada4bf6c89187a4f85c042746d33d0badf6
c8015ccd28a8186b122f32a3287580b982cba847
refs/heads/master
2021-01-13T14:13:19.693056
2016-11-04T10:23:39
2016-11-04T10:23:39
72,839,234
0
0
null
null
null
null
UTF-8
Python
false
false
7,473
py
import os import re from string import letters import random import hmac import hashlib import webapp2 import jinja2 from google.appengine.ext import db #setting up jinja environment template_dir = os.path.join(os.path.dirname('__file__'),'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),autoescape = True) secret = 'ps.abzk1~nsndxa>sqb&li$094=!' def hash_str(s): #return hashlib.md5(s).hexdigest() return hmac.new(secret,s).hexdigest() def make_secure_val(s): return "%s|%s" % (s, hash_str(s)) def check_secure_val(secure_val): val = secure_val.split('|')[0] if secure_val == make_secure_val(val): return val def render_str(template, **params): t = jinja_env.get_template(template) return t.render(params) class BlogHandler(webapp2.RequestHandler): def write(self,*a,**kw): self.response.out.write(*a,**kw) def render_str(self,template,**params): t = jinja_env.get_template(template) return t.render(params) def render(self,template,**kw): self.write(self.render_str(template,**kw)) def set_secure_cookie(self,name,val): cookie_val = make_secure_val(val) self.response.headers.add_header( 'Set-Cookie', "%s=%s; path=/" %(name,cookie_val)) def read_secure_cookie(self,name): cookie_val = self.request.cookies.get(name) return cookie_val and check_secure_val(cookie_val) def login(self,user): self.set_secure_cookie('user_id',str(user.key().id())) def logout(self): self.response.headers.add_header('Set-Cookie','user_id=; path=/') #it is called by gae at first step def initialize(self,*a,**kw): webapp2.RequestHandler.initialize(self,*a,**kw) uid = self.read_secure_cookie('user_id') #checking whether user is alredy logged in self.user = uid and User.by_id(int(uid)) class MainPage(BlogHandler): def get(self): self.write('hello, udacity!') #signup stuff's #for signup validation USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$") PWD_RE = re.compile(r"^.{3,20}$") EMAIl_RE = re.compile(r"^[\S]+@[\S]+.[\S]+$") def valid_username(username): if USER_RE.match(username): return True else: return False def valid_password(password): if PWD_RE.match(password): return True else: return False def valid_email(email): if EMAIl_RE.match(email): return True else: return False class Signup(BlogHandler): def get(self): self.render('signup.html') def post(self): self.username = self.request.get('username') self.password = self.request.get('password') verify = self.request.get('verify') self.email = self.request.get('email') params = dict(username=self.username,email = self.email) herror = False if not valid_username(self.username): params['uerror'] = "That wasn't a valid username." herror = True if not valid_password(self.password): params['perror'] = "That wasn't a valid password." herror = True if not self.password == verify: params['verror'] = "Your passwords didn't match." herror = True if not (self.email == "" or valid_email(self.email)): params['eerror'] = "That wasn't a valid email." herror = True if herror: self.render('signup.html',**params) else: self.done() def done(self,username): raise NotImplementedError class Unit2Signup(Signup): def done(self,username): self.redirect('/unit2/welcome?username='+self.username) class Unit2Welcome(BlogHandler): def get(self): username = self.request.get('username') self.render('welcome.html',username = username) #blog stuff's def blog_key(name = "default"): return db.Key.from_path('blogs',name) class Post(db.Model): subject = db.StringProperty(required = True) content = db.TextProperty(required = True) created = db.DateTimeProperty(auto_now_add = True) last_modified = db.DateTimeProperty(auto_now = True) def render(self): self._render_text = self.content.replace('\n','<br>') return render_str('post.html',p=self) class BlogFront(BlogHandler): def get(self): posts = db.GqlQuery("select * from Post order by created desc limit 10") self.render('front.html',posts = posts) class PostPage(BlogHandler): def get(self,post_id): key = db.Key.from_path('Post', int(post_id), parent=blog_key()) post = db.get(key) if not post: self.error('404') return else: self.render('permalink.html',post=post) class NewPost(BlogHandler): def get(self): self.render('newpost.html') def post(self): subject = self.request.get('subject') content = self.request.get('content') if subject and content: p = Post(parent = blog_key(),subject = subject, content = content) key = p.put() self.redirect('/blog/%s' %str(key.id())) else: error = 'subject and content, please!' self.render('newpost.html',subject = subject,content=content,error=error) #user's stuff def make_salt(length = 5): salt = ''.join(random.choice(letters) for x in xrange(length)) return salt def make_pw_hash(name,pw,salt = None): if not salt: salt = make_salt() h = hashlib.sha256(name+pw+salt).hexdigest() return '%s,%s' % (salt,h) def valid_pw(name, pw, h): salt = h.split(',')[0] new_hash = make_pw_hash(name,pw,salt) return new_hash == h def users_key(group = 'default'): key = db.Key.from_path('users',group) return key class User(db.Model): name = db.StringProperty(required = True) pwd_hash = db.StringProperty(required = True) email = db.StringProperty() @classmethod def by_id(cls,uid): return User.get_by_id(uid,parent = users_key()) @classmethod def by_name(cls,name): u = User.all().filter("name =", name).get() return u @classmethod def register(cls,name,password,email=None): pw_hash = make_pw_hash(name,password) return User(parent = users_key(), name = name, pwd_hash = pw_hash, email = email) class Register(Signup): def done(self): #Make sure user doesn't already exist u = User.by_name(self.username) if u: exists = "That user already exists." self.render("signup.html",exists = exists) else: user = User.register(name = self.username, password = self.password, email = self.email) user.put() self.login(user) self.redirect('/welcome') class Login(BlogHandler): def get(self): self.render('login.html') def post(self): username = self.request.get('username') user = User.by_name(username) password = self.request.get('password') if user and valid_pw(username,password,user.pwd_hash): self.login(user) self.redirect('/welcome') else: self.render('login.html',username = username,error = 'Invalid login.') class Logout(BlogHandler): def get(self): self.logout() self.redirect('/signup') class Welcome(BlogHandler): def get(self): if self.user: self.render("welcome.html",username = self.user.name) else: self.redirect('/signup') app = webapp2.WSGIApplication([('/',MainPage), ('/blog/?',BlogFront), ('/blog/([0-9]+)',PostPage), ('/blog/newpost',NewPost), ('/unit2/signup',Unit2Signup), ('/unit2/welcome',Unit2Welcome), ('/signup',Register), ('/welcome',Welcome), ('/login',Login), ('/logout',Logout) ],debug = True) #nothing
[ "choudharynandan260@gmail.com" ]
choudharynandan260@gmail.com
67f8dd978a2a2ff13f5ff70942fa69acd743fbf3
36dd43d5ad263902c6280e371063ad6e1d5ff1e6
/blog/models.py
c737b883f947523f8e0ec08abe73c80f1033b9f5
[]
no_license
monica-0218/Pazcal-Blog
1625a28d2fec3fc451578cd040bb0efe36340adc
de8bd3a1f1d55b11a03f0a179fe7e4df3de8b1f5
refs/heads/master
2022-12-31T14:14:48.563036
2020-10-26T14:04:36
2020-10-26T14:04:36
307,390,392
0
0
null
null
null
null
UTF-8
Python
false
false
2,690
py
from django.db import models from markdown import markdown from markdownx.models import MarkdownxField from taggit.managers import TaggableManager from django.conf import settings class Dungeon(models.Model): img = models.ImageField('サムネ', upload_to='images/') name = models.CharField('ダンジョン名', max_length=255) slug = models.SlugField('url名', unique=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'ダンジョン' verbose_name_plural = 'ダンジョン' def __str__(self): return self.name class Post(models.Model): dungeon = models.ForeignKey(Dungeon, on_delete=models.PROTECT, related_name='dungeon') tags = TaggableManager(blank=True) thumbnail = models.ImageField('サムネ', upload_to='images/') title = models.CharField('タイトル', max_length=30) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, blank=False) content = MarkdownxField('本文') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def get_markdown_text_as_html(self): """MarkDown記法で書かれたtextをHTML形式に変換して返す""" return markdown(self.content, extensions=['fenced_code', 'attr_list', 'nl2br', 'tables', 'sane_lists']) class Meta: ordering = ['-created_at'] verbose_name = '記事' verbose_name_plural = '投稿記事' def __str__(self): return self.title class Comment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, blank=False) content = MarkdownxField('本文') post = models.ForeignKey(to=Post, related_name='comments', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class Meta: ordering = ['created_at'] verbose_name = 'コメント' verbose_name_plural = 'コメントリスト' class CommentReply(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, blank=False) content = MarkdownxField('本文') reply = models.ForeignKey(to=Comment, related_name='replies', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class Meta: ordering = ['created_at'] verbose_name = '返信' verbose_name_plural = '返信リスト' class Favolate(models.Model): post = models.ForeignKey(to=Post, related_name='favolate', on_delete=models.CASCADE) is_favolate =
[ "sorakawa0218@gmail.com" ]
sorakawa0218@gmail.com
770326a7c554452415a3a4823c7975bc958ac5bb
45a2fef5a35090e2c3794824735dc137553c3d3b
/backup/fcards/utils.py
a968797ac2ea04b200ab1d427b0368cd1c17ba3c
[]
no_license
kris-brown/personal_website
9248ec23e2ebab8d820a0c6be70f6fb06a80144f
4dadfeba80eaf3f25f87b6f7bed48aa9db6ec8fc
refs/heads/master
2021-08-28T00:03:07.483092
2021-08-09T06:19:56
2021-08-09T06:19:56
190,462,717
1
0
null
null
null
null
UTF-8
Python
false
false
3,164
py
from typing import List as L, Tuple as T '''Misc helpful things''' def flatten(lol:L[list])->list: return [item for sublist in lol for item in sublist] ################################################################################ class Tree(object): ''' Parse a nested bullet structure where nesting is determined by whitespace, e.g. - A - A1 - A2 - A2i - B ''' def __init__(self, value : str, children : L['Tree']) -> None: self.value = value; self.children = children def __str__(self)->str: return self.print(0) def __len__(self)->int: return 1 + sum(map(len,self.children)) def showflat(self,_discard : bool = True)->str: '''Discard root and show flattened information (for Anki cards)''' if _discard: curr = '' else: if self.value and self.value[0]=='-': curr = '\n'+self.value[1:] else: curr = '\n'+self.value return curr + ''.join([c.showflat(_discard=False) for c in self.children]) def print(self, indent : int) -> str: '''Visualize as tree''' rest = ''.join([c.print(indent+1) for c in self.children]) return '\n' + '\t'*indent + self.value + rest @classmethod def from_str(cls, lines:L[str]) -> 'Tree': '''Takes the "content" of an orgmode node (list of strings) and makes a Tree''' pairs = [(cls.level(x),x) for x in filter(lambda x: not x.isspace(),lines)] try: root = Tree(value = 'root', children = cls.parse_children(pairs)) except ValueError as e: print(e) for k,v in pairs: print(k,v) import pdb;pdb.set_trace();assert False return root @classmethod def parse_children(cls, pairs : L[T[int,str]]) -> L['Tree']: '''Recursively parse a list of (indent-level, <content>) pairs''' if not pairs: return [] # Base case: no more children next_val = pairs[0][1].strip() # our first element is definitely a child. childlevel = pairs[0][0] # All children have this indentation level children = [] # The list that we will return next_pairs = [] # type: L[T[int,str]] ## the lines that are descendents of the child for i,x in pairs[1:]: if i < childlevel: raise ValueError('Indentation level incorrectly parsed: ',x) elif i > childlevel: next_pairs.append((i,x)) # something that belongs to next child at some depth else: # We've returned back to the child indentation level, so everything we've seen up to now gets added children.append(Tree(value = next_val, children = cls.parse_children(next_pairs))) next_val, next_pairs = x.strip(), [] # reset these variables # Add the last tree children.append(Tree(value=next_val,children = cls.parse_children(next_pairs))) return children @staticmethod def level(astr : str) -> int: '''Get indentation level assuming tab spacing = 8''' ws = astr[:len(astr) - len(astr.lstrip())] return ws.count(' ')+8*ws.count('\t')
[ "ksb@stanford.edu" ]
ksb@stanford.edu
bc538b379293fe63b0ba139868e58411d965d740
6b511b69062ad8cfee9dcc2b44cfe4fb2db5d229
/QuoraQuestionChallenge/preprocessing_util/parsetree_operations.py
cd8bab13651341c097bf342bb0d3685067738f07
[]
no_license
ahmorsi/QuoraQuestionChallenge
3b0421b92f2322767af7311d953674750614e78c
15bac05d258a5c147c731f59d31dd67b2c3f7174
refs/heads/master
2021-01-23T00:05:58.570102
2017-04-07T19:47:00
2017-04-07T19:47:00
85,693,384
0
0
null
null
null
null
UTF-8
Python
false
false
12,702
py
from pattern.text.en import parsetree, parse import pickle from question import Question import unicodedata from itertools import chain with open("./stored_data/lemmatized_questions_pairs.pickle", "rb") as loader: lemmatized_questions_pairs = pickle.load(loader) with open("./stored_data/clean_question_pairs.pickle", "rb") as loader: clean_question_pairs = pickle.load(loader) with open("./stored_data/stemmed_questions_pairs.pickle", "rb") as loader: stemmed_questions_pairs = pickle.load(loader) with open("./stored_data/tokenized_question_pairs.pickle", "rb") as loader: tokenized_question_pairs = pickle.load(loader) clean_question_pairs = map(lambda v: (v[0].encode('ascii', 'ignore'), v[1].encode('ascii', 'ignore')), clean_question_pairs) lemmatized_questions_pairs = map(lambda v: (map(lambda u: u.encode('ascii', 'ignore'), v[0]), map(lambda u: u.encode('ascii', 'ignore'), v[1])), lemmatized_questions_pairs) stemmed_questions_pairs = map(lambda v: (map(lambda u: u.encode('ascii', 'ignore'), v[0]), map(lambda u: u.encode('ascii', 'ignore'), v[1])), stemmed_questions_pairs) tokenized_question_pairs = map(lambda v: (map(lambda u: u.encode('ascii', 'ignore'), v[0]), map(lambda u: u.encode('ascii', 'ignore'), v[1])), tokenized_question_pairs) print(len(clean_question_pairs)) questions = [] def dic_to_string(param): string = "" for item in param.items(): string += str(item[0][0]) + " " + str(item[0][1]) + " " + str(item[1]) + " " return string.strip() for i in range(40000, 50000): print(i) question1_string = clean_question_pairs[i][0] question2_string = clean_question_pairs[i][1] question1 = Question(question1_string) question2 = Question(question2_string) tokenized_question1 = tokenized_question_pairs[i][0] tokenized_question2 = tokenized_question_pairs[i][1] lemmatized_question1 = lemmatized_questions_pairs[i][0] lemmatized_question2 = lemmatized_questions_pairs[i][1] stemmed_question1 = stemmed_questions_pairs[i][0] stemmed_question2 = stemmed_questions_pairs[i][1] question1.set_lemmatized_question_tokens(lemmatized_question1) question2.set_lemmatized_question_tokens(lemmatized_question2) question1.set_stemmed_question_tokens(stemmed_question1) question2.set_stemmed_question_tokens(stemmed_question2) question1.set_question_tokens(tokenized_question1) question2.set_question_tokens(tokenized_question2) question1_parsetree = parsetree(question1_string, relations=True) question2_parsetree = parsetree(question2_string, relations=True) if len(question1_parsetree) == 1: parse_string = str(parse(question1_string, relations=True)) question1.set_parse_tree_string(parse_string) tokens_tags, tokens_roles, tokens_chunks = {}, {}, {} for sentence in question1_parsetree: for chunk in sentence.chunks: for word in chunk.words: #print(chunk.role) tokens_tags[(int(word.index), str(word.string))] = word.tag tokens_chunks[(int(word.index), str(word.string))] = word.chunk tokens_roles[(int(word.index), str(word.string))] = chunk.role question1.set_tokens_tags(tokens_tags) question1.set_tokens_chunks(tokens_chunks) question1.set_tokens_roles(tokens_roles) else: parse_string = str(parse(question1_string, relations=True)) question1.set_parse_tree_string(parse_string) tokens_tags, tokens_roles, tokens_chunks = {}, {}, {} for sentence in question1_parsetree: for chunk in sentence.chunks: for word in chunk.words: tokens_tags[(int(word.index), str(word.string))] = word.tag tokens_chunks[(int(word.index), str(word.string))] = word.chunk tokens_roles[(int(word.index), str(word.string))] = chunk.role question1.set_tokens_tags(tokens_tags) question1.set_tokens_chunks(tokens_chunks) question1.set_tokens_roles(tokens_roles) partial_questions = [] for partial_question in question1_parsetree[1:]: partial_question_string = partial_question.string partial_question_object = Question(partial_question_string) parse_string = str(parse(partial_question_string, relations=True)) partial_question_parse_tree = parsetree(partial_question_string, relations=True) partial_question_object.set_parse_tree_string(parse_string) tokens_tags, tokens_roles, tokens_chunks = {}, {}, {} for sentence in partial_question_parse_tree: for chunk in sentence.chunks: for word in chunk.words: tokens_tags[(int(word.index), str(word.string))] = word.tag tokens_chunks[(int(word.index), str(word.string))] = word.chunk tokens_roles[(int(word.index), str(word.string))] = chunk.role partial_question_object.set_tokens_tags(tokens_tags) partial_question_object.set_tokens_chunks(tokens_chunks) partial_question_object.set_tokens_roles(tokens_roles) partial_questions.append(partial_question_object) question1.set_partial_questions(partial_questions) if len(question2_parsetree) == 1: parse_string = str(parse(question1_string, relations=True)) question2.set_parse_tree_string(parse_string) tokens_tags, tokens_roles, tokens_chunks = {}, {}, {} for sentence in question2_parsetree: for chunk in sentence.chunks: for word in chunk.words: tokens_tags[(int(word.index), str(word.string))] = word.tag tokens_chunks[(int(word.index), str(word.string))] = word.chunk tokens_roles[(int(word.index), str(word.string))] = chunk.role question2.set_tokens_tags(tokens_tags) question2.set_tokens_chunks(tokens_chunks) question2.set_tokens_roles(tokens_roles) else: parse_string = str(parse(question2_string, relations=True)) question2.set_parse_tree_string(parse_string) tokens_tags, tokens_roles, tokens_chunks = {}, {}, {} for sentence in question2_parsetree: for chunk in sentence.chunks: for word in chunk.words: tokens_tags[(int(word.index), str(word.string))] = word.tag tokens_chunks[(int(word.index), str(word.string))] = word.chunk tokens_roles[(int(word.index), str(word.string))] = chunk.role question2.set_tokens_tags(tokens_tags) question2.set_tokens_chunks(tokens_chunks) question2.set_tokens_roles(tokens_roles) partial_questions = [] for partial_question in question2_parsetree[1:]: partial_question_string = partial_question.string partial_question_object = Question(partial_question_string) parse_string = str(parse(partial_question_string, relations=True)) partial_question_parse_tree = parsetree(partial_question_string, relations=True) partial_question_object.set_parse_tree_string(parse_string) tokens_tags, tokens_roles, tokens_chunks = {}, {}, {} for sentence in partial_question_parse_tree: for chunk in sentence.chunks: for word in chunk.words: tokens_tags[(int(word.index), str(word.string))] = word.tag tokens_chunks[(int(word.index), str(word.string))] = word.chunk tokens_roles[(int(word.index), str(word.string))] = chunk.role partial_question_object.set_tokens_tags(tokens_tags) partial_question_object.set_tokens_chunks(tokens_chunks) partial_question_object.set_tokens_roles(tokens_roles) partial_questions.append(partial_question_object) question2.set_partial_questions(partial_questions) questions.append((question1, question2)) print("End Processing") q = questions[0][0] with open("./stored_data/data_preprocessing.txt", "a") as writer: for question_pair in questions: writer.write("#\n") first_question = question_pair[0] second_question = question_pair[1] writer.write(first_question.get_question() + "\n") writer.write(' '.join(first_question.get_question_tokens()) + "\n") writer.write(first_question.get_stemmed_question() + "\n") writer.write(' '.join(first_question.get_stemmed_tokens()) + "\n") writer.write(first_question.get_lemmatized_question() + "\n") writer.write(' '.join(first_question.get_lemmatized_tokens()) + "\n") writer.write(dic_to_string(first_question.get_tokens_tags()) + "\n") writer.write(dic_to_string(first_question.get_tokens_roles()) + "\n") writer.write(dic_to_string(first_question.get_tokens_chunks()) + "\n") partial_first_question = first_question.get_partial_questions() writer.write(str(len(partial_first_question)) + "\n") for i in range(0, len(partial_first_question)): current_question = partial_first_question[i] writer.write(current_question.get_question() + "\n") writer.write(' '.join(current_question.get_question_tokens()) + "\n") writer.write(current_question.get_stemmed_question() + "\n") writer.write(' '.join(current_question.get_stemmed_tokens()) + "\n") writer.write(current_question.get_lemmatized_question() + "\n") writer.write(' '.join(current_question.get_lemmatized_tokens()) + "\n") writer.write(dic_to_string(current_question.get_tokens_tags()) + "\n") writer.write(dic_to_string(current_question.get_tokens_roles()) + "\n") writer.write(dic_to_string(current_question.get_tokens_chunks()) + "\n") writer.write("--\n") writer.write(second_question.get_question() + "\n") writer.write(' '.join(second_question.get_question_tokens()) + "\n") writer.write(second_question.get_stemmed_question() + "\n") writer.write(' '.join(second_question.get_stemmed_tokens()) + "\n") writer.write(second_question.get_lemmatized_question() + "\n") writer.write(' '.join(second_question.get_lemmatized_tokens()) + "\n") writer.write(dic_to_string(second_question.get_tokens_tags()) + "\n") writer.write(dic_to_string(second_question.get_tokens_roles()) + "\n") writer.write(dic_to_string(second_question.get_tokens_chunks()) + "\n") partial_second_question = second_question.get_partial_questions() writer.write(str(len(partial_second_question)) + "\n") for i in range(0, len(partial_second_question)): current_question = partial_second_question[i] writer.write(current_question.get_question() + "\n") writer.write(' '.join(current_question.get_question_tokens()) + "\n") writer.write(current_question.get_stemmed_question() + "\n") writer.write(' '.join(current_question.get_stemmed_tokens()) + "\n") writer.write(current_question.get_lemmatized_question() + "\n") writer.write(' '.join(current_question.get_lemmatized_tokens()) + "\n") writer.write(dic_to_string(current_question.get_tokens_tags()) + "\n") writer.write(dic_to_string(current_question.get_tokens_roles()) + "\n") writer.write(dic_to_string(current_question.get_tokens_chunks()) + "\n") print("Question: " + str(q.get_question())) print("Tokens: " + str(q.get_question_tokens())) print("Stemmed Question: " + str(q.get_stemmed_question())) print("Stemmed Tokens: " + str(q.get_stemmed_tokens())) print("Lemmatized Question" + str(q.get_lemmatized_question())) print("Lemmatized Tokens" + str(q.get_lemmatized_tokens())) print("Partial Questions: " + str(q.get_partial_questions())) print("Parsetree String: " + str(q.get_parse_tree_string())) print("Tokens Tags: " + str(q.get_tokens_tags())) print("Tokens Roles: " + str(q.get_tokens_roles())) print("Tokens Chunks" + str(q.get_tokens_chunks())) """ with open('./stored_data/questions_objects_pairs.pickle', "wb") as saver: pickle.dump(questions, saver, protocol=2) s = 'What is the step by step guide to invest in share market in india?' s = parsetree(s, relations=True) for sentence in s: for chunk in sentence.chunks: for word in chunk.words: print(str(word.string) + " " + str(chunk.role)) """
[ "ahani.fcis@gmail.com" ]
ahani.fcis@gmail.com