index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
995,500
9e7a701b11f184cafaf0f80f7e256fb6bec33afe
months_map = {"Jan":1,"Feb":2,"Mar":3,"Apr":4,"May":5,"Jun":6,"Jul":7,"Aug":8,"Sep":9,"Oct":10,"Nov":11,"Dec":12} def compareDates(date1, date2): date1Arr = date1.split(' ') date2Arr = date2.split(' ') if int(date1Arr[-1])>int(date2Arr[-1]): return 1 elif int(date2Arr[-1])>int(date1Arr[-1]): return -1 elif months_map[date1Arr[1]] > months_map[date2Arr[1]]: return 1 elif months_map[date2Arr[1]] > months_map[date1Arr[1]]: return -1 elif date1Arr[0]>date2Arr[0]: return 1 elif date2Arr[0]>date1Arr[0]: return -1 return 0 def sortDates(dates): # Write your code here dates.sort(compareDates) return dates print (sortDates(["20 Oct 2052","06 Jun 1933","26 May 1960","20 Sep 1958","16 Mar 2068","25 May 1912","16 Dec 2018","26 Dec 2061","04 Nov 2030","28 Jul 1963"]))
995,501
ab62c4552c4864d594374bb7de7d69b2e8ac72d5
''' Copyright (C) 2015 Pistiwique, Pitiwazou Created by Pistiwique, Pitiwazou This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import bpy from . function_utils.get_path import get_library_path from os.path import join, isdir, isfile, basename from os import listdir from . icons.icons import load_icons from .function_utils.get_path import (get_directory, get_addon_path, get_library_path, get_addon_preferences, ) from .assets_scenes.assets_functions import (get_groups, get_scripts, ) from .materials.materials_functions import (get_custom_material_render_scene, get_valid_materials, ) from .operators import settings from .assets_scenes.assets_scene_op import * from .ibl.ibl_op import * from .materials.materials_op import * from .operators import * from .library.operators import * # ----------------------------------------------------------------------------- # POPUP MENU OPTIONS # ----------------------------------------------------------------------------- class PropertiesMenu(bpy.types.Operator): bl_idname = "view3d.properties_menu" bl_label = "Properties Menu" def execute(self, context): return {'FINISHED'} def check(self, context): return True def invoke(self, context, event): AM = context.window_manager.asset_m self.dpi_value = bpy.context.user_preferences.system.dpi return context.window_manager.invoke_props_dialog(self, width=self.dpi_value*5, height=100) def draw(self, context): layout = self.layout AM = context.window_manager.asset_m addon_prefs = get_addon_preferences() thumbnails_path = get_directory('icons') extentions = (".jpg", ".jpeg", ".png") thumbnail_list = [f.rsplit(".", 1)[0] for f in listdir(thumbnails_path) if f.endswith(extentions)] row = layout.row(align = True) row.prop(AM, "option_choise", expand = True) if AM.option_choise == 'tools': layout.separator() row = layout.row(align = True) row.prop(AM, "tools_options", expand = True) layout.separator() if AM.tools_options == 'assets': layout.label("RENAME ASSET") split = layout.split(percentage = 0.1) split.separator() row = split.row(align=True) row.prop(AM, "new_name", text="New name") #Check icon List if AM.new_name: if AM.new_name in thumbnail_list: split = layout.split(percentage = 0.1) split.separator() split.label("\" {} \" already exist".format(AM.new_name), icon='ERROR') else: row.operator("object.change_name_asset", text="", icon='FILE_TICK') layout.label("MOVE ASSET") split = layout.split(percentage = 0.1) split.separator() row = split.row() row.prop(AM, "new_lib", text = "Libraries") split = layout.split(percentage = 0.1) split.separator() row = split.row() row.prop(AM, "new_cat", text = "Categories") layout.separator() split = layout.split(percentage = 0.12) split.separator() row = split.row() row.operator("object.move_asset", text = "Move asset") layout.separator() else: layout.separator() layout.operator("object.debug_preview", text = "Debug") layout.separator() elif AM.option_choise == 'import': if AM.library_type == 'materials': if AM.libraries == "Render Scenes": layout.prop(AM, "active_layer", text="Use Active layer") layout.prop(AM, "existing_material", text="Use Existing Materials") else: layout.prop(AM, "active_layer", text="Use Active layer") layout.prop(AM, "existing_material", text="Use Existing Materials") layout.prop(AM, "existing_group", text="Use Existing Groups") if AM.import_choise == 'link': layout.prop(AM, "run_script", text="run script when imported") layout.prop(AM, "snap_enabled", text="Snap to faces") elif AM.option_choise == 'display': layout.prop(addon_prefs, "show_name_assets", text="Show Preview's names") layout.prop(addon_prefs, "show_labels", text="Show labels in the preview") # ----------------------------------------------------------------------------- # ASSETS ADDING OPTIONS PANEL # ----------------------------------------------------------------------------- def asset_adding_panel(self, context): """ Sub panel for the adding assets """ AM = context.window_manager.asset_m layout = self.layout box = layout.box() act_obj = context.active_object obj_list = [obj for obj in context.scene.objects if obj.select] thumbnails_path = get_directory('icons') is_subsurf = False view = context.space_data fx_settings = view.fx_settings ssao_settings = fx_settings.ssao extentions = (".jpg", ".jpeg", ".png") thumb_list = [thumb.rsplit(".", 1)[0] for thumb in listdir(thumbnails_path) if thumb.endswith(extentions)] if len(obj_list) >= 2: asset_name = AM.group_name else: asset_name = act_obj.name if act_obj.modifiers: for mod in act_obj.modifiers: if mod.type == 'SUBSURF': is_subsurf = True if asset_name not in thumb_list or asset_name in thumb_list and AM.replace_rename == 'replace': if asset_name in thumb_list and AM.replace_rename == 'replace': box.label("\" {} \" already exist".format(asset_name), icon='ERROR') box.separator() row = box.row(align=True) row.prop(AM, "replace_rename", text=" ", expand=True) if AM.replace_rename == 'rename': if multi_object: box.prop(AM, "group_name", text="") else: ob = context.object box.prop(ob, "name", text="") else: if len(obj_list) >= 2: row = box.row() box.label("Choose the asset name") box.prop(AM, "group_name", text = "") else: ob = context.object box.prop(ob, "name", text="Name") row = box.row(align = True) row.prop(AM, "render_type", text = " ", expand = True) row = box.row() row.label("Thumbnail extention:") row = box.row(align = True) row.prop(AM, "thumb_ext", expand = True) # ---------------------- # # RENNDER THUMBNAIL # # ---------------------- # if AM.render_type == 'render': if len(obj_list) == 1 and not is_subsurf: box.prop(AM, "add_subsurf", text = "Subsurf") box.prop(AM, "add_smooth", text = "Smooth") box.prop(AM, "material_render", text="Addon material") # --------------------- # # OPENGL THUMBNAIL # # --------------------- # elif AM.render_type == 'opengl': row = box.row(align=True) row.operator("object.setup_ogl_render", text="Setup OGL render" if not "AM_OGL_Camera" in [obj.name for obj in context.scene.objects] else "View camera", icon='ZOOMIN') row.operator("object.remove_ogl_render", text="", icon='ZOOMOUT') row = layout.column() row = box.row(align=True) row.label("Background:") row.prop(AM, "background_alpha", text="") row = box.row(align=True) row.prop(view, "show_only_render") row = box.row(align=True) row.prop(view, "use_matcap") if view.use_matcap : row.prop(AM, "matcap_options", text="", icon='TRIA_UP' if AM.matcap_options else 'TRIA_DOWN') if AM.matcap_options: row = box.row(align=True) row.template_icon_view(view, "matcap_icon") row = box.row(align=True) row.prop(fx_settings, "use_ssao", text="Ambient Occlusion") if fx_settings.use_ssao: row.prop(AM, "ao_options", text="", icon='TRIA_UP' if AM.ao_options else 'TRIA_DOWN') if AM.ao_options: subcol = box.column(align=True) subcol.prop(ssao_settings, "factor") subcol.prop(ssao_settings, "distance_max") subcol.prop(ssao_settings, "attenuation") subcol.prop(ssao_settings, "samples") subcol.prop(ssao_settings, "color") # -------------------- # # IMAGE THUMBNAIL # # -------------------- # elif AM.render_type == 'image': row = box.row(align=True) row.prop(AM, "image_type", text=" ", expand=True) if AM.image_type == 'disk': box.label("Choose your thumbnail") box.prop(AM, "custom_thumbnail_path", text="") else: box.prop_search(AM, "render_name", bpy.data, "images", text="") row = box.row(align=True) if len(obj_list) == 1: if (asset_name not in thumb_list or AM.replace_rename == 'replace') and (AM.render_type in ['opengl', 'render'] or AM.render_type == 'image' and (AM.image_type == 'disk' and AM.custom_thumbnail_path or AM.image_type == 'rendered' and AM.render_name)): row.operator("object.add_asset_in_library", text="OK", icon='FILE_TICK') else: if AM.group_name and (asset_name not in thumb_list or AM.replace_rename == 'replace') and (AM.render_type in ['opengl', 'render'] or AM.render_type == 'image' and (AM.image_type == 'disk' and AM.custom_thumbnail_path or AM.image_type == 'rendered' and AM.render_name)): row.operator("object.add_asset_in_library", text="OK", icon='FILE_TICK') row.operator("object.cancel_panel_choise", text="Cancel", icon='X') else: box.label("\" {} \" already exist".format(asset_name), icon='ERROR') box.separator() row = box.row(align=True) row.prop(AM, "replace_rename", text=" ", expand=True) if AM.replace_rename == 'rename': if len(obj_list) >= 2: box.prop(AM, "group_name", text="") else: ob = context.object box.prop(ob, "name", text="") row = box.row() row.operator("object.cancel_panel_choise", text="Cancel", icon='X') # ----------------------------------------------------------------------------- # MATERIALS ADDING OPTIONS PANEL # ----------------------------------------------------------------------------- def materials_adding_panel(self, context): """ Sub panel for the adding materials """ AM = context.window_manager.asset_m layout = self.layout box = layout.box() view = context.space_data thumbnails_path = get_directory('icons') library_path = get_library_path() extentions = (".jpg", ".jpeg", ".png") thumb = [thumb.rsplit(".", 1)[0] for thumb in listdir(thumbnails_path) if thumb.endswith(extentions)] if AM.as_mat_scene: thumb_list = thumb + ["AM_Cloth", "AM_Sphere"] else: thumb_list = thumb cam_is_valid = False obj_is_valid = False if not AM.as_mat_scene and not bpy.context.object: box.prop(AM, "as_mat_scene", text = "Save as material scene") box.label("No active_object in the scene", icon='ERROR') box.operator("object.cancel_panel_choise", text="Cancel", icon='X') elif not AM.as_mat_scene and not bpy.context.active_object.active_material: box.prop(AM, "as_mat_scene", text = "Save as material scene") box.label("The object have no material", icon='ERROR') box.operator("object.cancel_panel_choise", text="Cancel", icon='X') else: if AM.as_mat_scene and not isdir(join(library_path, 'materials', "Render Scenes")): box.operator("object.create_rder_scn_lib", text = "Create render scene library", icon = 'FILESEL') box.operator("object.cancel_panel_choise", text="Cancel", icon='X') else: if AM.as_mat_scene: asset_name = AM.scene_name else: active_mat = context.active_object.active_material asset_name = active_mat.name if len(bpy.context.active_object.material_slots) == 1: AM.multi_materials = False if AM.as_mat_scene and (not asset_name in thumb_list or asset_name in thumb_list and AM.replace_rename == 'replace') or\ not AM.as_mat_scene and (AM.multi_materials and get_valid_materials() or not AM.multi_materials and asset_name not in thumb_list or asset_name in thumb_list and AM.replace_rename == 'replace'): if not AM.multi_materials: if asset_name in thumb_list and AM.replace_rename == 'replace': box.label("\" {} \" already exist".format(asset_name), icon='ERROR') box.separator() if len(bpy.context.active_object.material_slots) >= 2 and AM.replace_rename == 'rename': box.prop(AM, "multi_materials", text = "All materials") row = box.row(align=True) row.prop(AM, "replace_rename", text=" ", expand=True) if AM.replace_rename == 'rename': if AM.as_mat_scene: box.prop(AM, "scene_name", text = "") else: box.prop(AM, "rename_mat", text="") box.prop(AM, "as_mat_scene", text = "Save as material scene") if not AM.as_mat_scene and len(bpy.context.active_object.material_slots) >= 2: if len(get_valid_materials()) != len(bpy.context.active_object.material_slots) and AM.multi_materials: box.label("Some materials wont be added", icon = 'ERROR') box.label(" because there already exist") row = box.row() row.prop(AM, "multi_materials", text = "All materials") if AM.as_mat_scene: row = box.row(align = True) row.label("Scene name:") row.prop(AM, "scene_name", text = "") row = box.row(align = True) row.prop(AM, "render_type", text = " ", expand = True) row = box.row() row.label("Thumbnail extention:") row = box.row(align = True) row.prop(AM, "thumb_ext", expand = True) if AM.as_mat_scene: for obj in context.scene.objects: if obj.type == 'CAMERA': cam_is_valid = True if len([obj for obj in context.selected_objects if obj.type != 'CAMERA' and bpy.context.active_object == obj]) == 1: obj_is_valid = True row = box.row() row.label("Selected object rendering", icon = 'FILE_TICK' if obj_is_valid else 'CANCEL') row = box.row() row.label("Camera in the scene", icon = 'FILE_TICK' if cam_is_valid else 'CANCEL') if not cam_is_valid: row = box.row() row.operator("object.camera_add", text = "Add camera", icon = 'OUTLINER_OB_CAMERA') if not AM.as_mat_scene: # --------------------- # # RENDER THUMBNAIL # # --------------------- # if AM.render_type == 'render': row = box.row(align = True) row.label("Thumbnail:") row.prop(AM, "mat_thumb_type", text = "") # --------------------- # # OPENGL THUMBNAIL # # --------------------- # if AM.render_type == 'opengl': row = box.row(align=True) row.operator("object.setup_ogl_render", text="Setup OGL render" if not "AM_OGL_Camera" in [obj.name for obj in context.scene.objects] else "View camera", icon='ZOOMIN') row.operator("object.remove_ogl_render", text="", icon='ZOOMOUT') row = layout.column() row = box.row(align=True) row.label("Background:") row.prop(AM, "background_alpha", text="") row = box.row(align=True) row.prop(view, "show_only_render") # -------------------- # # IMAGE THUMBNAIL # # -------------------- # elif AM.render_type == 'image': row = box.row(align=True) row.prop(AM, "image_type", text=" ", expand=True) if AM.image_type == 'disk': box.label("Choose your thumbnail") box.prop(AM, "custom_thumbnail_path", text="") else: box.prop_search(AM, "render_name", bpy.data, "images", text="") row = box.row(align=True) if (AM.as_mat_scene and AM.scene_name and cam_is_valid and obj_is_valid or not AM.as_mat_scene) and (AM.render_type == 'render' or (asset_name not in thumb_list or AM.replace_rename == 'replace') and AM.render_type == 'opengl' or AM.render_type == 'image' and (AM.image_type == 'disk' and AM.custom_thumbnail_path or AM.image_type == 'rendered' and AM.render_name)): if AM.as_mat_scene: row.operator("object.add_scene_in_library", text="OK", icon='FILE_TICK') else: row.operator("object.add_material_in_library", text="OK", icon='FILE_TICK') row.operator("object.cancel_panel_choise", text="Cancel", icon='X') else: if AM.multi_materials and not get_valid_materials(): box.label("All materials already exist".format(asset_name), icon='ERROR') box.separator() if len(bpy.context.active_object.material_slots) >= 2: box.prop(AM, "multi_materials", text = "All materials") else: box.label("\" {} \" already exist".format(asset_name), icon='ERROR') box.separator() if len(bpy.context.active_object.material_slots) >= 2: box.prop(AM, "multi_materials", text = "All materials") else: AM.multi_materials = False row = box.row(align=True) row.prop(AM, "replace_rename", text=" ", expand=True) if AM.replace_rename == 'rename': if AM.as_mat_scene: box.prop(AM, "scene_name", text = "") else: box.prop(AM, "rename_mat", text="") row = box.row() row.operator("object.cancel_panel_choise", text="Cancel", icon='X') # ----------------------------------------------------------------------------- # SCENES ADDING OPTIONS PANEL # ----------------------------------------------------------------------------- def scene_adding_panel(self, context): """ Sub panel for the adding scenes """ AM = context.window_manager.asset_m layout = self.layout box = layout.box() view = context.space_data fx_settings = view.fx_settings ssao_settings = fx_settings.ssao thumbnails_path = get_directory('icons') extentions = (".jpg", ".jpeg", ".png") thumb_list = [thumb.rsplit(".", 1)[0] for thumb in listdir(thumbnails_path) if thumb.endswith(extentions)] if AM.scene_name not in thumb_list or AM.scene_name in thumb_list and AM.replace_rename == 'replace': if AM.scene_name in thumb_list and AM.replace_rename == 'replace': box.label("\" {} \" already exist".format(AM.scene_name), icon='ERROR') box.separator() row = box.row(align=True) row.prop(AM, "replace_rename", text=" ", expand=True) if AM.replace_rename == 'rename': box.prop(AM, "scene_name", text="") row = box.row(align = True) row.label("Scene name:") row.prop(AM, "scene_name", text = "") row = box.row(align = True) row.prop(AM, "render_type", text = " ", expand = True) row = box.row() row.label("Thumbnail extention:") row = box.row(align = True) row.prop(AM, "thumb_ext", expand = True) # --------------------- # # OPENGL THUMBNAIL # # --------------------- # if AM.render_type == 'opengl': row = box.row(align=True) row.operator("object.setup_ogl_render", text="Setup OGL render" if not "AM_OGL_Camera" in [obj.name for obj in context.scene.objects] else "View camera", icon='ZOOMIN') row.operator("object.remove_ogl_render", text="", icon='ZOOMOUT') row = layout.column() row = box.row(align=True) row.label("Background:") row.prop(AM, "background_alpha", text="") row = box.row(align=True) row.prop(view, "show_only_render") row = box.row(align=True) row.prop(view, "use_matcap") if view.use_matcap : row.prop(AM, "matcap_options", text="", icon='TRIA_UP' if AM.matcap_options else 'TRIA_DOWN') if AM.matcap_options: row = box.row(align=True) row.template_icon_view(view, "matcap_icon") row = box.row(align=True) row.prop(fx_settings, "use_ssao", text="Ambient Occlusion") if fx_settings.use_ssao: row.prop(AM, "ao_options", text="", icon='TRIA_UP' if AM.ao_options else 'TRIA_DOWN') if AM.ao_options: subcol = box.column(align=True) subcol.prop(ssao_settings, "factor") subcol.prop(ssao_settings, "distance_max") subcol.prop(ssao_settings, "attenuation") subcol.prop(ssao_settings, "samples") subcol.prop(ssao_settings, "color") # -------------------- # # IMAGE THUMBNAIL # # -------------------- # elif AM.render_type == 'image': row = box.row(align=True) row.prop(AM, "image_type", text=" ", expand=True) if AM.image_type == 'disk': box.label("Choose your thumbnail") box.prop(AM, "custom_thumbnail_path", text="") else: box.prop_search(AM, "render_name", bpy.data, "images", text="") row = box.row(align=True) if AM.scene_name and ((AM.scene_name not in thumb_list or AM.replace_rename == 'replace') and AM.render_type == 'opengl' or AM.render_type == 'image' and (AM.image_type == 'disk' and AM.custom_thumbnail_path or AM.image_type == 'rendered' and AM.render_name)): row.operator("object.add_scene_in_library", text="OK", icon='FILE_TICK') row.operator("object.cancel_panel_choise", text="Cancel", icon='X') else: box.label("\" {} \" already exist".format(AM.scene_name), icon='ERROR') box.separator() row = box.row(align=True) row.prop(AM, "replace_rename", text=" ", expand=True) if AM.replace_rename == 'rename': box.prop(AM, "scene_name", text="") row = box.row() row.operator("object.cancel_panel_choise", text="Cancel", icon='X') # ----------------------------------------------------------------------------- # HDRI ADDING OPTIONS PANEL # ----------------------------------------------------------------------------- def hdri_adding_panel(self, context): """ Sub panel for the adding HDRI """ AM = context.window_manager.asset_m layout = self.layout box = layout.box() row = box.row() row.prop(AM, "existing_thumb", text = "Use existing Thumbnails") row = box.row() row.label("Thumbnail extention:") row = box.row(align = True) row.prop(AM, "thumb_ext", expand = True) row = box.row(align = True) row.operator("wm.ibl_importer", text="OK", icon='FILE_TICK') row.operator("object.cancel_panel_choise", text="Cancel", icon='X') # ----------------------------------------------------------------------------- # IBL OPTIONS PANEL # ----------------------------------------------------------------------------- def ibl_options_panel(self, context): """ Sub panel for the ibl options """ AM = context.window_manager.asset_m node_group = bpy.context.scene.world.node_tree.nodes layout = self.layout box = layout.box() row = box.row() row.alignment = 'CENTER' row.label("IMAGE") row = box.row(align = True) row.label("Rotation:") col = row.column() col.prop(node_group["Mapping"], "rotation", text = "") row = box.row(align = True) row.label("Projection:") row.prop(AM, "projection", text = "") row = box.row(align = True) row.label("Blur:") row.prop(node_group["ImageBlur"].inputs[1], "default_value", text = "") row = box.row(align = True) row.label("Visible:") row.prop(bpy.context.scene.world.cycles_visibility, "camera") row = box.row(align = True) row.label("Transparent:") row.prop(bpy.context.scene.cycles, "film_transparent") box = layout.box() row = box.row(align = True) row.label("Gamma:") row.prop(node_group["AM_IBL_Tool"].inputs[0], "default_value", text = "") box = layout.box() row = box.row() row.alignment = 'CENTER' row.label("LIGHT") row = box.row(align = True) row.label("Strength:") row.prop(node_group["AM_IBL_Tool"].inputs[2], "default_value", text = "") row = box.row(align = True) row.label("Saturation:") row.prop(node_group["AM_IBL_Tool"].inputs[3], "default_value", text = "") row = box.row(align = True) row.label("Hue:") row.prop(node_group["AM_IBL_Tool"].inputs[4], "default_value", text = "") row = box.row(align = True) row.label("Mix Hue:") row.prop(node_group["AM_IBL_Tool"].inputs[5], "default_value", text = "") box = layout.box() row = box.row() row.alignment = 'CENTER' row.label("GLOSSY") row = box.row(align = True) row.label("Strength:") row.prop(node_group["AM_IBL_Tool"].inputs[7], "default_value", text = "") row = box.row(align = True) row.label("Saturation:") row.prop(node_group["AM_IBL_Tool"].inputs[8], "default_value", text = "") row = box.row(align = True) row.label("Hue:") row.prop(node_group["AM_IBL_Tool"].inputs[9], "default_value", text = "") row = box.row(align = True) row.label("Mix Hue:") row.prop(node_group["AM_IBL_Tool"].inputs[10], "default_value", text = "") layout.operator("wm.save_ibl_settings", text = "Save settings", icon = 'FILE_TICK') # ----------------------------------------------------------------------------- # DRAW TOOLS PANEL # ----------------------------------------------------------------------------- class VIEW3D_PT_tools_AM_Tools(bpy.types.Panel): bl_label = "Asset Management" bl_space_type = 'VIEW_3D' bl_region_type = 'TOOLS' bl_category = "Tools" def draw(self, context): layout = self.layout wm = context.window_manager AM = wm.asset_m library_path = get_library_path() addon_prefs = get_addon_preferences() thumbnails_path = get_directory('icons') favourites_path = get_directory("Favorites") if library_path: icons = load_icons() rename = icons.get("rename_asset") no_rename = icons.get("no_rename_asset") favourites = icons.get("favorites_asset") no_favourites = icons.get("no_favorites_asset") h_ops = icons.get("hardops_asset") row = layout.row(align = True) row.prop(AM, "library_type", text=" ", expand = True) #layout.operator("my_operator.debug_operator", text = "debug") if not AM.library_type in listdir(library_path): layout.operator("object.create_lib_type_folder", text = "Create {} folder".format(AM.library_type)).lib_type = AM.library_type # ----------------------------------------------------------------------------- # LIBRARIES # ----------------------------------------------------------------------------- else: row = layout.row(align = True) row.prop(AM, "libraries") row.prop(AM, "show_prefs_lib", text = "", icon = 'TRIA_UP' if AM.show_prefs_lib else 'SCRIPTWIN') if AM.show_prefs_lib: box = layout.box() row = box.row(align = True) row.operator("object.add_asset_library", text = "Add") row.operator("object.remove_asset_m_library", text = "Remove") row.prop(AM, "rename_library", text = "", icon_value = rename.icon_id if AM.rename_library else no_rename.icon_id ) if AM.rename_library: row = box.row() if AM.libraries == "Render Scenes": row.label("This library don't", icon = 'CANCEL') row = box.row() row.label("have to change name") else: row.prop(AM, "change_library_name") if AM.change_library_name: if AM.change_library_name in [lib for lib in listdir(join(library_path, AM.library_type)) if isdir(join(library_path, AM.library_type))]: row = layout.row() row.label("\"{}\" already exist".format(AM.change_library_name), icon = 'ERROR') else: row.operator("object.asset_m_rename_library", text = "", icon = 'FILE_TICK') # ----------------------------------------------------------------------------- # CATEGORIES # ----------------------------------------------------------------------------- row = layout.row(align = True) row.prop(AM, "categories") row.prop(AM, "show_prefs_cat", text = "", icon = 'TRIA_UP' if AM.show_prefs_cat else 'SCRIPTWIN') if AM.show_prefs_cat: box = layout.box() row = box.row(align = True) row.operator("object.add_asset_category", text = "Add") row.operator("object.remove_asset_m_category", text = "Remove") row.prop(AM, "rename_category", text = "", icon_value = rename.icon_id if AM.rename_category else no_rename.icon_id ) if AM.rename_category: row = box.row() row.prop(AM, "change_category_name") if AM.change_category_name: if AM.change_category_name in [cat for cat in listdir(join(library_path, AM.library_type, AM.libraries)) if isdir(join(library_path, AM.library_type, AM.libraries))]: row = layout.row() row.label("\"{}\" already exist".format(AM.change_category_name), icon = 'ERROR') else: row.operator("object.asset_m_rename_category", text = "", icon = 'FILE_TICK') # ----------------------------------------------------------------------------- # ADDING MENU # ----------------------------------------------------------------------------- if AM.adding_options: if AM.library_type == 'assets': asset_adding_panel(self, context) elif AM.library_type == 'materials': materials_adding_panel(self, context) elif AM.library_type == 'scenes': scene_adding_panel(self, context) elif AM.library_type == 'hdri': hdri_adding_panel(self, context) # ----------------------------------------------------------------------------- # DRAW PANEL # ----------------------------------------------------------------------------- else: if AM.library_type in ["assets", "materials"]: row = layout.row(align = True) row.prop(AM, "import_choise", expand = True) row.operator("object.edit_asset", text = "", icon = 'LOAD_FACTORY') elif AM.library_type == "scenes": layout.operator("object.edit_asset", text = "Edit Scene", icon = 'LOAD_FACTORY') # Show only Favourites sheck box if len(listdir(favourites_path)): row = layout.row() row.prop(AM, "favourites_enabled", text = "Show Only Favourites") # Asset Preview row = layout.row(align = True) row.prop row = layout.row() col = row.column() col.scale_y = 1.17 col.template_icon_view(wm, "AssetM_previews", show_labels = True if addon_prefs.show_labels else False) col = row.column(align = True) # Add/Remove asset from the library if AM.library_type in ['scenes', 'hdri'] or AM.library_type in ['assets', 'materials'] and context.selected_objects and not AM.render_running: col.prop(AM, "adding_options", text = "", icon = 'ZOOMIN') col.operator("object.remove_asset_from_lib", text = "", icon = 'ZOOMOUT') # Favourites if len(listdir(favourites_path)): if isfile(join(favourites_path, wm.AssetM_previews)): col.operator("object.remove_from_favourites", text="", icon_value=favourites.icon_id) else: col.operator("object.add_to_favourites", text="", icon_value=no_favourites.icon_id) else: col.operator("object.add_to_favourites", text="", icon_value=no_favourites.icon_id) # Custom import if AM.library_type in ['assets', 'scenes']: col.prop(AM, "custom_data_import", icon = 'FILE_TEXT', icon_only=True) # Popup options col.operator("view3d.properties_menu", text="", icon='SCRIPTWIN') # Without import if AM.without_import: col.prop(AM, "without_import", icon='LOCKED', icon_only=True) else: col.prop(AM, "without_import", icon='UNLOCKED', icon_only=True) # Tool options if AM.library_type != 'scenes': col.prop(AM, "display_tools", text = "", icon = 'TRIA_UP' if AM.display_tools else 'MODIFIER') # Render Thumbnail if AM.asset_adding_enabled: layout.label("Adding asset...", icon='RENDER_STILL') layout.label("Please wait... ") layout.operator("wm.console_toggle", text="Check/Hide Console") elif AM.render_running: if AM.material_rendering: layout.label("Rendering: %s" % (AM.material_rendering[0]), icon='RENDER_STILL') else: layout.label("Thumbnail rendering", icon='RENDER_STILL') layout.label("Please wait... ") layout.operator("wm.console_toggle", text="Check/Hide Console") else: if settings["file_to_edit"] != "" and settings["file_to_edit"] == bpy.data.filepath: row = layout.row(align=True) row.operator("wm.back_to_original", text = "Save", icon = 'SAVE_COPY') row.operator("wm.cancel_changes", text = "Cancel", icon = 'X') if AM.display_tools: box = layout.box() if AM.library_type == 'assets': box.operator("object.rename_objects", text = "Correct Name", icon = 'SAVE_COPY') box.operator("material.link_to_base_names", text="Materials to base name", icon = 'MATERIAL') box.operator("object.clean_unused_data", text="Clean unused datas", icon = 'MESH_DATA') box.separator() box = layout.box() box.operator("object.asset_m_add_to_selection", text = "Asset to selection", icon = 'MOD_MULTIRES') row = box.row(align = True) row.operator("object.asset_m_link", text = "Link", icon = 'CONSTRAINT') row.operator("object.asset_m_unlink", text = "Unlink", icon = 'UNLINKED') row = box.row() row.alignment = 'CENTER' row.label("Prepare asset") row = box.row(align = True) row.operator("object.prepare_asset", text = "AM", icon = 'OBJECT_DATA').type = 'AM' row.operator("object.prepare_asset", text = "H_Ops", icon_value = h_ops.icon_id).type = 'H_Ops' elif AM.library_type == 'materials': box.operator("material.link_to_base_names", text="Materials to base name", icon = 'MATERIAL') box.operator("object.clean_unused_data", text="Clean unused datas", icon = 'MESH_DATA') else: # Asset name if addon_prefs.show_name_assets: row = layout.row(align = True) row.label("Name :") sub = row.row() sub.scale_x = 2.0 sub.label(context.window_manager.AssetM_previews.rsplit(".", 1)[0]) if AM.library_type in ['assets', 'scenes'] and AM.custom_data_import: layout.prop(AM, "datablock", text = "") # Replace if context.object is not None and context.object.mode == 'OBJECT' and AM.library_type == 'assets' and context.selected_objects: row = layout.row(align=True) row.prop(AM, "replace_asset", text="Replace Asset") if AM.replace_asset: row.prop(AM, "replace_multi", text="Multi") else: AM.replace_multi = False else: AM.replace_asset=False row = layout.row(align=True) row.scale_y = 1.1 row.scale_x = 1.5 row.operator("object.next_asset", text="", icon='TRIA_LEFT').selection = -1 row.scale_x = 1 if AM.library_type == 'scenes' and not AM.custom_data_import: row.operator("wm.open_active_preview", text = "Click to open") elif AM.library_type in ['assets', 'scenes'] and AM.custom_data_import: row.operator("wm.assetm_custom_browser", text = "Custom import") else: row.operator("object.import_active_preview", text="Replace Asset" if AM.replace_asset else "Click to import") row.scale_x = 1.5 row.operator("object.next_asset", text="", icon='TRIA_RIGHT').selection = 1 if AM.display_tools: box = layout.box() if AM.library_type == 'hdri': if "AM_IBL_WORLD" in bpy.data.worlds: ibl_options_panel(self, context) else: box.label("No setup IBL", icon = 'ERROR') elif AM.library_type == 'assets': box.operator("object.rename_objects", text = "Correct Name", icon = 'SAVE_COPY') box.operator("material.link_to_base_names", text="Materials to base name", icon = 'MATERIAL') box.operator("object.clean_unused_data", text="Clean unused datas", icon = 'MESH_DATA') box.separator() box = layout.box() box.operator("object.asset_m_add_to_selection", text = "Asset to selection", icon = 'MOD_MULTIRES') row = box.row(align = True) row.operator("object.asset_m_link", text = "Link", icon = 'CONSTRAINT') row.operator("object.asset_m_unlink", text = "Unlink", icon = 'UNLINKED') row = box.row() row.alignment = 'CENTER' row.label("Prepare asset") row = box.row(align = True) row.operator("object.prepare_asset", text = "AM", icon = 'OBJECT_DATA').type = 'AM' row.operator("object.prepare_asset", text = "H_Ops", icon_value = h_ops.icon_id).type = 'H_Ops' elif AM.library_type == 'materials': box.operator("material.link_to_base_names", text="Materials to base name", icon = 'MATERIAL') box.operator("object.clean_unused_data", text="Clean unused datas", icon = 'MESH_DATA') # Link if AM.library_type == 'assets' and AM.import_choise == 'link': groups = get_groups(context.window_manager.AssetM_previews.rsplit(".", 1)[0]) if groups[0] != "empty": box = layout.box() box.label("Group to link") for group in groups: box.operator("object.import_active_preview", text=group, icon='LINK_BLEND').group_name = group else: box = layout.box() box.label("Group to link") box.label("There's no group to link") box.label("Use custom import to link objects") #Script scripts = get_scripts(context.window_manager.AssetM_previews.rsplit(".", 1)[0]) if scripts[0] != "empty": box = layout.box() box.label("Script:") for txt in scripts: box.operator("text.import_script", text=txt).script = txt else: layout.label("Define the library path", icon='ERROR') layout.label("in the addon preferences please.") layout.operator("screen.userpref_show", icon='PREFERENCES') # ----------------------------------------------------------------------------- # DRAW UI PANEL # ----------------------------------------------------------------------------- class VIEW3D_PT_view_3d_AM_UI(bpy.types.Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_label = "Asset Management" def draw(self, context): layout = self.layout wm = context.window_manager AM = wm.asset_m library_path = get_library_path() addon_prefs = get_addon_preferences() thumbnails_path = get_directory('icons') favourites_path = get_directory("Favorites") if library_path: icons = load_icons() rename = icons.get("rename_asset") no_rename = icons.get("no_rename_asset") favourites = icons.get("favorites_asset") no_favourites = icons.get("no_favorites_asset") h_ops = icons.get("hardops_asset") row = layout.row(align = True) row.prop(AM, "library_type", text=" ", expand = True) #layout.operator("my_operator.debug_operator", text = "debug") if not AM.library_type in listdir(library_path): layout.operator("object.create_lib_type_folder", text = "Create {} folder".format(AM.library_type)).lib_type = AM.library_type # ----------------------------------------------------------------------------- # LIBRARIES # ----------------------------------------------------------------------------- else: row = layout.row(align = True) row.prop(AM, "libraries") row.prop(AM, "show_prefs_lib", text = "", icon = 'TRIA_UP' if AM.show_prefs_lib else 'SCRIPTWIN') if AM.show_prefs_lib: box = layout.box() row = box.row(align = True) row.operator("object.add_asset_library", text = "Add") row.operator("object.remove_asset_m_library", text = "Remove") row.prop(AM, "rename_library", text = "", icon_value = rename.icon_id if AM.rename_library else no_rename.icon_id ) if AM.rename_library: row = box.row() if AM.libraries == "Render Scenes": row.label("This library don't", icon = 'CANCEL') row = box.row() row.label("have to change name") else: row.prop(AM, "change_library_name") if AM.change_library_name: if AM.change_library_name in [lib for lib in listdir(join(library_path, AM.library_type)) if isdir(join(library_path, AM.library_type))]: row = layout.row() row.label("\"{}\" already exist".format(AM.change_library_name), icon = 'ERROR') else: row.operator("object.asset_m_rename_library", text = "", icon = 'FILE_TICK') # ----------------------------------------------------------------------------- # CATEGORIES # ----------------------------------------------------------------------------- row = layout.row(align = True) row.prop(AM, "categories") row.prop(AM, "show_prefs_cat", text = "", icon = 'TRIA_UP' if AM.show_prefs_cat else 'SCRIPTWIN') if AM.show_prefs_cat: box = layout.box() row = box.row(align = True) row.operator("object.add_asset_category", text = "Add") row.operator("object.remove_asset_m_category", text = "Remove") row.prop(AM, "rename_category", text = "", icon_value = rename.icon_id if AM.rename_category else no_rename.icon_id ) if AM.rename_category: row = box.row() row.prop(AM, "change_category_name") if AM.change_category_name: if AM.change_category_name in [cat for cat in listdir(join(library_path, AM.library_type, AM.libraries)) if isdir(join(library_path, AM.library_type, AM.libraries))]: row = layout.row() row.label("\"{}\" already exist".format(AM.change_category_name), icon = 'ERROR') else: row.operator("object.asset_m_rename_category", text = "", icon = 'FILE_TICK') # ----------------------------------------------------------------------------- # ADDING MENU # ----------------------------------------------------------------------------- if AM.adding_options: if AM.library_type == 'assets': asset_adding_panel(self, context) elif AM.library_type == 'materials': materials_adding_panel(self, context) elif AM.library_type == 'scenes': scene_adding_panel(self, context) elif AM.library_type == 'hdri': hdri_adding_panel(self, context) # ----------------------------------------------------------------------------- # DRAW PANEL # ----------------------------------------------------------------------------- else: if AM.library_type in ["assets", "materials"]: row = layout.row(align = True) row.prop(AM, "import_choise", expand = True) row.operator("object.edit_asset", text = "", icon = 'LOAD_FACTORY') elif AM.library_type == "scenes": layout.operator("object.edit_asset", text = "Edit Scene", icon = 'LOAD_FACTORY') # Show only Favourites sheck box if len(listdir(favourites_path)): row = layout.row() row.prop(AM, "favourites_enabled", text = "Show Only Favourites") # Asset Preview row = layout.row(align = True) row.prop row = layout.row() col = row.column() col.scale_y = 1.17 col.template_icon_view(wm, "AssetM_previews", show_labels = True if addon_prefs.show_labels else False) col = row.column(align = True) # Add/Remove asset from the library if AM.library_type in ['scenes', 'hdri'] or AM.library_type in ['assets', 'materials'] and context.selected_objects and not AM.render_running: col.prop(AM, "adding_options", text = "", icon = 'ZOOMIN') col.operator("object.remove_asset_from_lib", text = "", icon = 'ZOOMOUT') # Favourites if len(listdir(favourites_path)): if isfile(join(favourites_path, wm.AssetM_previews)): col.operator("object.remove_from_favourites", text="", icon_value=favourites.icon_id) else: col.operator("object.add_to_favourites", text="", icon_value=no_favourites.icon_id) else: col.operator("object.add_to_favourites", text="", icon_value=no_favourites.icon_id) # Custom import if AM.library_type in ['assets', 'scenes']: col.prop(AM, "custom_data_import", icon = 'FILE_TEXT', icon_only=True) # Popup options col.operator("view3d.properties_menu", text="", icon='SCRIPTWIN') # Without import if AM.without_import: col.prop(AM, "without_import", icon='LOCKED', icon_only=True) else: col.prop(AM, "without_import", icon='UNLOCKED', icon_only=True) # Tool options if AM.library_type != 'scenes': col.prop(AM, "display_tools", text = "", icon = 'TRIA_UP' if AM.display_tools else 'MODIFIER') # Render Thumbnail if AM.asset_adding_enabled: layout.label("Adding asset...", icon='RENDER_STILL') layout.label("Please wait... ") layout.operator("wm.console_toggle", text="Check/Hide Console") elif AM.render_running: if AM.material_rendering: layout.label("Rendering: %s" % (AM.material_rendering[0]), icon='RENDER_STILL') else: layout.label("Thumbnail rendering", icon='RENDER_STILL') layout.label("Please wait... ") layout.operator("wm.console_toggle", text="Check/Hide Console") else: if settings["file_to_edit"] != "" and settings["file_to_edit"] == bpy.data.filepath: row = layout.row(align=True) row.operator("wm.back_to_original", text = "Save", icon = 'SAVE_COPY') row.operator("wm.cancel_changes", text = "Cancel", icon = 'X') if AM.display_tools: box = layout.box() if AM.library_type == 'assets': box.operator("object.rename_objects", text = "Correct Name", icon = 'SAVE_COPY') box.operator("material.link_to_base_names", text="Materials to base name", icon = 'MATERIAL') box.operator("object.clean_unused_data", text="Clean unused datas", icon = 'MESH_DATA') box.separator() box = layout.box() box.operator("object.asset_m_add_to_selection", text = "Asset to selection", icon = 'MOD_MULTIRES') row = box.row(align = True) row.operator("object.asset_m_link", text = "Link", icon = 'CONSTRAINT') row.operator("object.asset_m_unlink", text = "Unlink", icon = 'UNLINKED') row = box.row() row.alignment = 'CENTER' row.label("Prepare asset") row = box.row(align = True) row.operator("object.prepare_asset", text = "AM", icon = 'OBJECT_DATA').type = 'AM' row.operator("object.prepare_asset", text = "H_Ops", icon_value = h_ops.icon_id).type = 'H_Ops' elif AM.library_type == 'materials': box.operator("material.link_to_base_names", text="Materials to base name", icon = 'MATERIAL') box.operator("object.clean_unused_data", text="Clean unused datas", icon = 'MESH_DATA') else: # Asset name if addon_prefs.show_name_assets: row = layout.row(align = True) row.label("Name :") sub = row.row() sub.scale_x = 2.0 sub.label(context.window_manager.AssetM_previews.rsplit(".", 1)[0]) if AM.library_type in ['assets', 'scenes'] and AM.custom_data_import: layout.prop(AM, "datablock", text = "") # Replace if context.object is not None and context.object.mode == 'OBJECT' and AM.library_type == 'assets' and context.selected_objects: row = layout.row(align=True) row.prop(AM, "replace_asset", text="Replace Asset") if AM.replace_asset: row.prop(AM, "replace_multi", text="Multi") else: AM.replace_multi = False else: AM.replace_asset=False row = layout.row(align=True) row.scale_y = 1.1 row.scale_x = 1.5 row.operator("object.next_asset", text="", icon='TRIA_LEFT').selection = -1 row.scale_x = 1 if AM.library_type == 'scenes' and not AM.custom_data_import: row.operator("wm.open_active_preview", text = "Click to open") elif AM.library_type in ['assets', 'scenes'] and AM.custom_data_import: row.operator("wm.assetm_custom_browser", text = "Custom import") else: row.operator("object.import_active_preview", text="Replace Asset" if AM.replace_asset else "Click to import") row.scale_x = 1.5 row.operator("object.next_asset", text="", icon='TRIA_RIGHT').selection = 1 if AM.display_tools: box = layout.box() if AM.library_type == 'hdri': if "AM_IBL_WORLD" in bpy.data.worlds: ibl_options_panel(self, context) else: box.label("No setup IBL", icon = 'ERROR') elif AM.library_type == 'assets': box.operator("object.rename_objects", text = "Correct Name", icon = 'SAVE_COPY') box.operator("material.link_to_base_names", text="Materials to base name", icon = 'MATERIAL') box.operator("object.clean_unused_data", text="Clean unused datas", icon = 'MESH_DATA') box.separator() box = layout.box() box.operator("object.asset_m_add_to_selection", text = "Asset to selection", icon = 'MOD_MULTIRES') row = box.row(align = True) row.operator("object.asset_m_link", text = "Link", icon = 'CONSTRAINT') row.operator("object.asset_m_unlink", text = "Unlink", icon = 'UNLINKED') row = box.row() row.alignment = 'CENTER' row.label("Prepare asset") row = box.row(align = True) row.operator("object.prepare_asset", text = "AM", icon = 'OBJECT_DATA').type = 'AM' row.operator("object.prepare_asset", text = "H_Ops", icon_value = h_ops.icon_id).type = 'H_Ops' elif AM.library_type == 'materials': box.operator("material.link_to_base_names", text="Materials to base name", icon = 'MATERIAL') box.operator("object.clean_unused_data", text="Clean unused datas", icon = 'MESH_DATA') # Link if AM.library_type == 'assets' and AM.import_choise == 'link': groups = get_groups(context.window_manager.AssetM_previews.rsplit(".", 1)[0]) if groups[0] != "empty": box = layout.box() box.label("Group to link") for group in groups: box.operator("object.import_active_preview", text=group, icon='LINK_BLEND').group_name = group else: box = layout.box() box.label("Group to link") box.label("There's no group to link") box.label("Use custom import to link objects") #Script scripts = get_scripts(context.window_manager.AssetM_previews.rsplit(".", 1)[0]) if scripts[0] != "empty": box = layout.box() box.label("Script:") for txt in scripts: box.operator("text.import_script", text=txt).script = txt else: layout.label("Define the library path", icon='ERROR') layout.label("in the addon preferences please.") layout.operator("screen.userpref_show", icon='PREFERENCES') # ----------------------------------------------------------------------------- # DRAW POPUP PANEL # ----------------------------------------------------------------------------- class WM_OT_am_popup(bpy.types.Operator): bl_idname = "view3d.asset_m_pop_up_preview" bl_label = "Asset preview" @classmethod def poll(cls, context): return bpy.context.mode in ['OBJECT', 'EDIT_MESH'] def execute(self, context): return {'FINISHED'} def check(self, context): return True def invoke(self, context, event): self.library_path = get_library_path() self.addon_prefs = get_addon_preferences() dpi_value = bpy.context.user_preferences.system.dpi return context.window_manager.invoke_props_dialog(self, width=dpi_value*2.5, height=100) def draw(self, context): WM = context.window_manager AM = WM.asset_m thumbnails_path = get_directory('icons') favourites_path = get_directory("Favorites") icons = load_icons() favourites = icons.get("favorites_asset") no_favourites = icons.get("no_favorites_asset") h_ops = icons.get("hardops_asset") layout = self.layout row = layout.row(align = True) row.prop(AM, "library_type", text=" ", expand = True) if not AM.library_type in listdir(self.library_path): layout.operator("object.create_lib_type_folder", text = "Create {} folder".format(AM.library_type)).lib_type = AM.library_type row = layout.row(align = True) row.prop(AM, "libraries") row = layout.row(align = True) row.prop(AM, "categories") # Show only Favourites sheck box if len(listdir(favourites_path)): row = layout.row() row.prop(AM, "favourites_enabled", text = "Show Only Favourites") # Asset Preview row = layout.row(align = True) row.prop row = layout.row() col = row.column() col.scale_y = 1.17 col.template_icon_view(WM, "AssetM_previews", show_labels = True if self.addon_prefs.show_labels else False) col = row.column(align = True) # Favourites if len(listdir(favourites_path)): if isfile(join(favourites_path, WM.AssetM_previews)): col.operator("object.remove_from_favourites", text="", icon_value=favourites.icon_id) else: col.operator("object.add_to_favourites", text="", icon_value=no_favourites.icon_id) else: col.operator("object.add_to_favourites", text="", icon_value=no_favourites.icon_id) # Popup options col.operator("view3d.properties_menu", text="", icon='SCRIPTWIN') # Without import if AM.without_import: col.prop(AM, "without_import", icon='LOCKED', icon_only=True) else: col.prop(AM, "without_import", icon='UNLOCKED', icon_only=True) # Asset name if self.addon_prefs.show_name_assets: row = layout.row(align = True) row.label("Name :") sub = row.row() sub.scale_x = 2.0 sub.label(WM.AssetM_previews.rsplit(".", 1)[0]) # Tool options if AM.library_type in ['assets', 'hdri']: col.prop(AM, "display_tools", text = "", icon = 'TRIA_UP' if AM.display_tools else 'MODIFIER') # Replace if context.object is not None and context.object.mode == 'OBJECT' and AM.library_type == 'assets': row = layout.row(align=True) row.prop(AM, "replace_asset", text="Replace Asset") if AM.replace_asset: row.prop(AM, "replace_multi", text="Multi") else: AM.replace_multi = False else: AM.replace_asset=False row = layout.row(align=True) row.scale_y = 1.1 row.scale_x = 1.5 row.operator("object.next_asset", text="", icon='TRIA_LEFT').selection = -1 row.scale_x = 1 if AM.library_type == 'scenes': row.operator("wm.open_active_preview", text = "Click to open") else: row.operator("object.append_active_preview", text="Replace Asset" if AM.replace_asset else "Click to import") row.scale_x = 1.5 row.operator("object.next_asset", text="", icon='TRIA_RIGHT').selection = 1 if AM.display_tools: box = layout.box() if AM.library_type == 'hdri': if "AM_IBL_WORLD" in bpy.data.worlds: ibl_options_panel(self, context) else: box.label("No setup IBL", icon = 'ERROR') elif AM.library_type == 'assets': box.operator("object.rename_objects", text = "Correct Name", icon = 'SAVE_COPY') box.operator("material.link_to_base_names", text="Materials to base name", icon = 'MATERIAL') box.operator("object.clean_unused_data", text="Clean unused datas", icon = 'MESH_DATA') box.separator() box = layout.box() box.operator("object.asset_m_add_to_selection", text = "Asset to selection", icon = 'MOD_MULTIRES') row = box.row(align = True) row.operator("object.asset_m_link", text = "Link", icon = 'CONSTRAINT') row.operator("object.asset_m_unlink", text = "Unlink", icon = 'UNLINKED') row = box.row() row.alignment = 'CENTER' row.label("Prepare asset") row = box.row(align = True) row.operator("object.prepare_asset", text = "AM", icon = 'OBJECT_DATA').type = 'AM' row.operator("object.prepare_asset", text = "H_Ops", icon_value = h_ops.icon_id).type = 'H_Ops' elif AM.library_type == 'materials': box.operator("material.link_to_base_names", text="Materials to base name", icon = 'MATERIAL') box.operator("object.clean_unused_data", text="Clean unused datas", icon = 'MESH_DATA')
995,502
0610ca8868793420e35a190ad63d1a5c5e7efddc
from django import forms class LoginForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label = 'Password', widget=forms.PasswordInput) class ProfileForm(forms.Form): profile_description = forms.CharField(widget=forms.Textarea(attrs={ 'class':"form-control", 'rows': 5, 'style': 'width:60%', 'placeholder': 'Write your profile description here!', }))
995,503
f3dc8509d5b68f26d401535acbf2431f2fbc0a22
import shutil import pandas as pd from tqdm import tqdm, trange def copyUniqueImages(coordinates_path, source_path, destination_path): image_file = pd.read_csv( coordinates_path, sep=',', header=None) image_names = image_file[3] for i in tqdm(range(1, len(image_names))): shutil.copy(source_path + image_names[i], destination_path + image_names[i])
995,504
1a42945f2a48e1d4281aac7baf7823a24e9c1e48
#classes and subclasses to import import cv2 import numpy as np import os ################################################################################################# # DO NOT EDIT!!! ################################################################################################# #subroutine to write rerults to a csv def writecsv(color,shape,size,count): #open csv file in append mode filep = open('results1B_eYRC#509.csv','a') # create string data to write per image datastr = "," + color + "-" + shape + "-" + size + "-" + count #write to csv filep.write(datastr) def colorOf(BGR = []): if ((BGR[0] <= 60 & BGR[0] >= 0) & (BGR[1] <= 60 & BGR[1] >= 0) & (BGR[2] <= 255 & BGR[2] >= 200)): return "red",1 elif ((BGR[0] <= 60 & BGR[0] >= 0) & (BGR[1] <= 255 & BGR[1] >= 200) & (BGR[2] <= 255 & BGR[2] >= 200)): return "yellow",2 elif (( BGR[0] >= 0 & BGR[0] <= 100) & (BGR[1] >= 120 & BGR[1] <= 180) & (BGR[2] == 255)): return "orange",3 elif ((BGR[0] <= 60 & BGR[0] >= 0) & (BGR[1] <= 255 & BGR[1] >= 200) & (BGR[2] <= 60 & BGR[2] >= 0)): return "green",4 elif((BGR[0] <= 255 & BGR[0] >= 200) & (BGR[1] <= 60 & BGR[1] >= 0) & (BGR[2] <= 60 & BGR[2] >= 0)): return "blue",5 def main(path): original=cv2.imread(path) file_list = os.listdir(os.getcwd()+"\Sample Images")#put in the sample file location area_list=[] for i in file_list : image=cv2.imread("Sample Images\\"+i) edged_image=cv2.Canny(image.copy(),150,150) _,contours_image,heirarchy = cv2.findContours(edged_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) area_list.append(cv2.contourArea(contours_image[0])) if "test" in path: square = cv2.imread('square.jpeg') gray_square = cv2.cvtColor(square, cv2.COLOR_BGR2GRAY) ret, thresh_square = cv2.threshold(gray_square,180,255,1) _,contours_sqr,heirarchy = cv2.findContours(thresh_square.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnt1 = contours_sqr[0] edged_image = cv2.Canny(original.copy(),150,150) _,contours,heirarchy = cv2.findContours(edged_image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) required_matrix=np.zeros((6,4,5)) #red-1,yellow-2,orange-3,green-4,blue-5 #small-1,large-2,medium-3 #triangle-1,rectangle-2,square-3,circle-4 font = cv2.FONT_HERSHEY_SIMPLEX countour_xy=[] for j in range (0,len(contours),2): i=contours[j] approx = cv2.approxPolyDP(i,0.01*cv2.arcLength(i,True),True) x = len(approx) M = cv2.moments(i) cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) size = "medium" x1=i[0][0][0]+1 y1=i[0][0][1]+1 color,d = colorOf(original[y1,x1])#d is the color index of the required matrix area = cv2.contourArea(i) if(cv2.contourArea(i)<3500): x=x-1 if x == 3: if (area >= area_list[6]): size = "large" required_matrix[d,3,1]+=1 elif (area <= area_list[7]): size = "small" required_matrix[d,1,1]+=1 else :required_matrix[d,2,1]+=1 cv2.putText(original,size+" "+str(color)+" triangle", (cx, cy), font, 0.4, (0, 0, 0), 1, 0) continue elif x == 4: ret = cv2.matchShapes(i,cnt1,1,0.0) if ret < 0.05: if (area >= area_list[4]): size = "large" required_matrix[d,3,3]+=1 elif (area <= area_list[5]): size = "small" required_matrix[d,1,3]+=1 else:required_matrix[d,2,3]+=1 cv2.putText(original, size+" "+str(color)+" square", (cx, cy), font, 0.4, (0, 0, 0), 1, 0) else: if (area >= area_list[2]): size = "large" required_matrix[d,3,2]+=1 elif (area <= area_list[3]): size = "small" required_matrix[d,1,2]+=1 else:required_matrix[d,2,2]+=1 cv2.putText(original, size+" "+str(color)+" rectangle", (cx, cy), font, 0.4, (0, 0, 0), 1, 0) continue elif x == 5: cv2.putText(original, size+" " +str(color)+" pentagon", (cx, cy), font, 0.4, (0, 0, 0), 1, 0) continue elif x >= 6: if (area >= area_list[0]): size = "large" required_matrix[d,3,4]+=1 elif (area <= area_list[1]): size = "small" required_matrix[d,1,4]+=1 else: required_matrix[d,2,4]+=1 cv2.putText(original, size+" "+str(color)+" circle", (cx, cy), font, 0.4, (0, 0, 0), 1, 0) continue shape_List=["","Triangle","Rectangle","Square","Circle"] size_List=["","Small","Medium","Large"] col_List=["","Red","Yellow","Orange","Green","Blue"] for colInd in xrange(1,6): for sizeInd in xrange(1,4): for shapeInd in xrange(1,5): if(required_matrix[colInd][sizeInd][shapeInd]>0): writecsv(col_List[colInd],shape_List[shapeInd],size_List[sizeInd],str(required_matrix[colInd][sizeInd][shapeInd])[:-2]) cv2.imwrite(os.getcwd()+"\output"+path[len(path)-5:],original) ################################################################################################# # DO NOT EDIT!!! ################################################################################################# #main where the path is set for the directory containing the test images if __name__ == "__main__": mypath = '.' #getting all files in the directory onlyfiles = ["\\".join([mypath, f]) for f in os.listdir(mypath) if f.endswith(".png")] #iterate over each file in the directory for fp in onlyfiles[:]: #Open the csv to write in append mode filep = open('results1B_eYRC#509.csv','a') #this csv will later be used to save processed data, thus write the file name of the image filep.write(fp[2:]) #close the file so that it can be reopened again later filep.close() #process the image main(fp) #open the csv filep = open('results1B_eYRC#509.csv','a') #make a newline entry so that the next image data is written on a newline filep.write('\n') #close the file filep.close()
995,505
28db7bbc4d2c1fc57f4977683f90cbf748d6238a
""" Marco Fernandez Pranno Ejercicio 1 """ def extendedGcd(a, b): """ Greatest common divisor d of a and b, and x and y integers satisfying ax + by = d """ if b == 0: return a, 1, 0 x1 = 0 x2 = 1 y1 = 1 y2 = 0 while b != 0: q = a // b r = a - q * b x = x2 - q * x1 y = y2 - q * y1 a = b b = r x2 = x1 x1 = x y2 = y1 y1 = y if a < 0: return -a, -x2, -y2 return a, x2, y2 def gcd(a, b): while b != 0: a, b = b, a % b return a
995,506
2ec655a9f8cb5777b47d9f0cd8802081fac07fd1
#n大于5时,将n分成3的倍数越多,乘积越大,如果最后剩余1,表示前一个分割为4,需要将4分为2个2,而不是1和3 class Solution: def cuttingRope(self, n: int) -> int: if n == 2: return 1 if n == 3: return 2 num3 = n // 3 res = n - num3 * 3 if res == 1: num3 -= 1 num2 = (n - num3 * 3) //2 return int(3 ** num3 * 2 ** num2)%1000000007
995,507
1ced1ef23ccef4eae6670fc5f0f1ae6935643559
conf={'19223239': '2018-06-21 16:01:30', '40892716': '2018-06-21 16:02:07', '70712': '2018-06-21 16:00:21', '40891010': '2018-06-21 16:02:05', '40979217': '2018-06-21 16:02:10', '40791012': '2018-06-21 16:02:03', '1838993': '2018-06-21 16:00:28', '18744865': '2018-06-21 16:01:14', '40247513': '2018-06-21 16:01:55', '40838631': '2018-06-21 16:02:05', '18783135': '2018-06-21 16:01:16', '501833': '2018-06-21 16:00:27', '19310489': '2018-06-21 16:01:48', '40547236': '2018-06-21 16:01:57', '9552697': '2018-06-21 16:00:35', '19274703': '2018-06-21 16:01:46', '40323833': '2018-06-21 16:01:55', '40977911': '2018-06-21 16:02:09', '40977650': '2018-06-21 16:02:08', '40554484': '2018-06-21 16:01:58', '40530117': '2018-06-21 16:01:56', '18016271': '2018-06-21 16:01:07', '18533472': '2018-06-21 16:01:08', '40957563': '2018-06-21 16:02:08', '15298400': '2018-06-21 16:00:41', '40555545': '2018-06-21 16:01:59', '19235176': '2018-06-21 16:01:32', '14550596': '2018-06-21 16:00:36', '40573759': '2018-06-21 16:02:00', '19379442': '2018-06-21 16:01:51', '40836383': '2018-06-21 16:02:04', '17234809': '2018-06-21 16:00:55', '19172085': '2018-06-21 16:01:24', '40011461': '2018-06-21 16:01:52', '40242643': '2018-06-21 16:01:54', '15454921': '2018-06-21 16:00:46', '4680362': '2018-06-21 16:00:30', '19355548': '2018-06-21 16:01:50', '16387': '2018-06-21 16:00:19', '18702921': '2018-06-21 16:01:13', '18007982': '2018-06-21 16:00:59', '18805071': '2018-06-21 16:01:17', '15131322': '2018-06-21 16:00:40', '19004616': '2018-06-21 16:01:23', '19259560': '2018-06-21 16:01:36', '40235340': '2018-06-21 16:01:53'}
995,508
205d688d187f92acb384a910798d37335b912eda
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'd:\pythoncode\6.ui_files\first_view.ui' # # Created by: PyQt5 UI code generator 5.13.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import * import sys class First_view(QMainWindow): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(910, 722) # 主窗口尺寸 self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.my_view = QtWidgets.QTableView(self.centralwidget) self.my_view.setGeometry(QtCore.QRect(225, 71, 681, 611)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.my_view.setFont(font) self.my_view.setShowGrid(True) self.my_view.setSortingEnabled(False) self.my_view.setObjectName("my_view") self.widget = QtWidgets.QWidget(self.centralwidget) self.widget.setGeometry(QtCore.QRect(80, 130, 111, 291)) self.widget.setObjectName("widget") self.verticalLayout = QtWidgets.QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(20) self.verticalLayout.setObjectName("verticalLayout") self.show_button = QtWidgets.QPushButton(self.widget) font = QtGui.QFont() font.setPointSize(12) self.show_button.setFont(font) self.show_button.setObjectName("show_button") self.verticalLayout.addWidget(self.show_button) self.add_button = QtWidgets.QPushButton(self.widget) font = QtGui.QFont() font.setPointSize(12) self.add_button.setFont(font) self.add_button.setObjectName("add_button") self.verticalLayout.addWidget(self.add_button) self.del_button = QtWidgets.QPushButton(self.widget) font = QtGui.QFont() font.setPointSize(12) self.del_button.setFont(font) self.del_button.setObjectName("del_button") self.verticalLayout.addWidget(self.del_button) self.modify_button = QtWidgets.QPushButton(self.widget) font = QtGui.QFont() font.setPointSize(12) self.modify_button.setFont(font) self.modify_button.setObjectName("modify_button") self.verticalLayout.addWidget(self.modify_button) self.query_button = QtWidgets.QPushButton(self.widget) font = QtGui.QFont() font.setPointSize(12) self.query_button.setFont(font) self.query_button.setObjectName("query_button") self.verticalLayout.addWidget(self.query_button) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 910, 23)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.show_button.setText(_translate("MainWindow", "显示所有员工")) self.add_button.setText(_translate("MainWindow", "添加员工信息")) self.del_button.setText(_translate("MainWindow", "删除员工信息")) self.modify_button.setText(_translate("MainWindow", "修改员工信息")) self.query_button.setText(_translate("MainWindow", "查询员工信息")) if __name__ == '__main__': app = QApplication(sys.argv) fv = First_view() fv.setupUi(fv) fv.show() sys.exit(app.exec_())
995,509
36af93032e30dab543159eee0f803421a9656217
# Copyright 2019 The TensorFlow Authors. 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. # ============================================================================== """Some gradient util functions to help users writing custom training loop.""" from __future__ import absolute_import from __future__ import division # from __future__ import google_type_annotations from __future__ import print_function from absl import logging import tensorflow.compat.v2 as tf def _filter_grads(grads_and_vars): """Filter out iterable with grad equal to None.""" grads_and_vars = tuple(grads_and_vars) if not grads_and_vars: return grads_and_vars filtered = [] vars_with_empty_grads = [] for grad, var in grads_and_vars: if grad is None: vars_with_empty_grads.append(var) else: filtered.append((grad, var)) filtered = tuple(filtered) if not filtered: raise ValueError("No gradients provided for any variable: %s." % ([v.name for _, v in grads_and_vars],)) if vars_with_empty_grads: logging.warning( ("Gradients do not exist for variables %s when minimizing the loss."), ([v.name for v in vars_with_empty_grads])) return filtered def _filter_and_allreduce_gradients(grads_and_vars, allreduce_precision="float32"): """Filter None grads and then allreduce gradients in specified precision. This utils function is used when users intent to explicitly allreduce gradients and customize gradients operations before and after allreduce. The allreduced gradients are then passed to optimizer.apply_gradients( experimental_aggregate_gradients=False). Arguments: grads_and_vars: gradients and variables pairs. allreduce_precision: Whether to allreduce gradients in float32 or float16. Returns: pairs of allreduced non-None gradients and variables. """ filtered_grads_and_vars = _filter_grads(grads_and_vars) (grads, variables) = zip(*filtered_grads_and_vars) if allreduce_precision == "float16": grads = [tf.cast(grad, "float16") for grad in grads] allreduced_grads = tf.distribute.get_replica_context().all_reduce( tf.distribute.ReduceOp.SUM, grads) if allreduce_precision == "float16": allreduced_grads = [tf.cast(grad, "float32") for grad in allreduced_grads] return allreduced_grads, variables def _run_callbacks(callbacks, grads_and_vars): for callback in callbacks: grads_and_vars = callback(grads_and_vars) return grads_and_vars def minimize_using_explicit_allreduce(tape, optimizer, loss, trainable_variables, pre_allreduce_callbacks=None, post_allreduce_callbacks=None): """Minimizes loss for one step by updating `trainable_variables`. Minimizes loss for one step by updating `trainable_variables`. This explicitly performs gradient allreduce, instead of relying on implicit allreduce in optimizer.apply_gradients(). If training using FP16 mixed precision, explicit allreduce will aggregate gradients in FP16 format. For TPU and GPU training using FP32, explicit allreduce will aggregate gradients in FP32 format. Arguments: tape: An instance of `tf.GradientTape`. optimizer: An instance of `tf.keras.optimizers.Optimizer`. loss: the loss tensor. trainable_variables: A list of model Variables. pre_allreduce_callbacks: A list of callback functions that takes gradients and model variables pairs as input, manipulate them, and returns a new gradients and model variables pairs. The callback functions will be invoked in the list order and before gradients are allreduced. With mixed precision training, the pre_allreduce_allbacks will be applied on scaled_gradients. Default is no callbacks. post_allreduce_callbacks: A list of callback functions that takes gradients and model variables pairs as input, manipulate them, and returns a new gradients and model variables paris. The callback functions will be invoked in the list order and right before gradients are applied to variables for updates. Default is no callbacks. """ if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer): # FP16 GPU code path with tape: scaled_loss = optimizer.get_scaled_loss(loss) scaled_grads = tape.gradient(scaled_loss, trainable_variables) grads_and_vars = zip(scaled_grads, trainable_variables) if pre_allreduce_callbacks: grads_and_vars = _run_callbacks(pre_allreduce_callbacks, grads_and_vars) (allreduced_scaled_grads, filtered_training_vars) = _filter_and_allreduce_gradients( grads_and_vars, allreduce_precision="float16") allreduced_unscaled_grads = optimizer.get_unscaled_gradients( allreduced_scaled_grads) grads_and_vars = zip(allreduced_unscaled_grads, filtered_training_vars) else: # TPU or FP32 GPU code path grads = tape.gradient(loss, trainable_variables) grads_and_vars = zip(grads, trainable_variables) if pre_allreduce_callbacks: grads_and_vars = _run_callbacks(pre_allreduce_callbacks, grads_and_vars) (allreduced_grads, filtered_training_vars) = _filter_and_allreduce_gradients( grads_and_vars, allreduce_precision="float32") grads_and_vars = zip(allreduced_grads, filtered_training_vars) if post_allreduce_callbacks: grads_and_vars = _run_callbacks(post_allreduce_callbacks, grads_and_vars) optimizer.apply_gradients( grads_and_vars, experimental_aggregate_gradients=False)
995,510
ccd2c932e2ab86ebde26af90fb930f7e2937ed44
import numpy as np from XFP import XFP, LeducRLEnv seed = 100 np.random.seed(seed) env = XFP() env.compute_p2_best_response() env.compute_p1_best_response() p1 = 0.0 p2 = 0.0 for i in range(100): cards = env.possible_cards_list[np.random.randint(24)] game_state = "" while True: if game_state in env.ending: v1, v2 = env.compute_payoff(cards, game_state) p1 += v1 p2 += v2 # print cards, game_state, v1, v2 break if game_state in env.round1_states_set: rd = 1 else: rd = 2 if game_state in env.player1_states_set: # action = env.choose_action_p1(game_state, cards, rd) if np.random.randint(0, 100) < 37: action = 'C' else: action = 'B' game_state = game_state + action else: action = env.choose_action_p2(game_state, cards, rd) # if np.random.randint(0, 100) < 37: # action = 'C' # else: # action = 'B' game_state = game_state + action print p1, p2 assert seed != 100 or p2 == 60 and seed == 100 # test realization policy_p1 = {} policy_p2 = {} for key, _ in env.q_value1_final.iteritems(): p = np.random.rand() policy_p1[key] = [p, 1.0 - p] for key, _ in env.q_value2_final.iteritems(): p = np.random.rand() policy_p2[key] = [p, 1.0 - p] realization = XFP.compute_realization(policy_p1, policy_p2) print XFP.tournament(seed, 10000, policy_p1, policy_p2) print XFP.compute_payoff_given_realization(realization) p1, p2 = XFP.compute_realization2policy(realization) for key in policy_p1: assert np.allclose(policy_p1[key], p1[key]) for key in policy_p2: assert np.allclose(policy_p2[key], p2[key]) # test mix policy env.finish() env.opponent_policy_p2 = policy_p2 env.opponent_policy_p1 = policy_p1 env.compute_p1_best_response() env.compute_p2_best_response() player1_best_response_policy = XFP.convert_q_s_a2greedy_policy(env.q_value1_final) player2_best_response_policy = XFP.convert_q_s_a2greedy_policy(env.q_value2_final) env.finish() # test best response with realization env.opponent_realization_p1 = realization env.opponent_realization_p2 = realization env.opponent_realization_enable = True env.compute_p1_best_response() env.compute_p2_best_response() player1_best_response_policy_given_realization = XFP.convert_q_s_a2greedy_policy(env.q_value1_final) player2_best_response_policy_given_realization = XFP.convert_q_s_a2greedy_policy(env.q_value2_final) for key, item in player1_best_response_policy.iteritems(): assert np.allclose(item, player1_best_response_policy_given_realization[key]) for key, item in player2_best_response_policy.iteritems(): assert np.allclose(item, player2_best_response_policy_given_realization[key]) env.finish() env.opponent_realization_enable = False print XFP.tournament(seed, 1000, player1_best_response_policy, policy_p2) print XFP.tournament(seed, 1000, policy_p1, player2_best_response_policy) realization_old = XFP.compute_realization(policy_p1, policy_p2) realization_br1 = XFP.compute_realization(player1_best_response_policy, policy_p2) realization_br2 = XFP.compute_realization(policy_p1, player2_best_response_policy) mix_realization_p1 = XFP.mix_realization(realization_br1, realization_old, 0.5) mix_realization_p2 = XFP.mix_realization(realization_br2, realization_old, 0.5) new_policy_p1, p2_extra = XFP.compute_realization2policy(mix_realization_p1) p1_extra, new_policy_p2 = XFP.compute_realization2policy(mix_realization_p2) for key in policy_p1: assert np.allclose(policy_p1[key], p1_extra[key]) for key in policy_p2: assert np.allclose(policy_p2[key], p2_extra[key]) print XFP.tournament(seed, 1000, new_policy_p1, policy_p2) print XFP.tournament(seed, 1000, policy_p1, new_policy_p2) # test LeducRLEnv leduc = LeducRLEnv(seed=seed) print leduc.reset() print leduc.act(1) print leduc.act(1) print leduc.act(1) print leduc.act(1)
995,511
bacd8fa09dfb5921ea12e316d59a5dd810fce58a
from chalicelib import recipients_service from chalicelib.donations.donation import Donation from chalicelib.donations.donations_repository import DonationsDynamoDBRepository DONATIONS = DonationsDynamoDBRepository.create() def send_donation(donation_request): donation = Donation.create_new_from(donation_request) if not donation.is_valid(): raise Exception('donation is not valid') recipient = recipients_service.find_recipient(donation.to_recipient) if not recipient: raise Exception('not a recipient') DONATIONS.put(donation) return { "donation": donation, "recipient": recipient } def find_from_citizen(citizen): return DONATIONS.find_by(citizen=citizen) def find_for_recipient(recipient): return DONATIONS.find_by(recipient=recipient) def find_donations(): return DONATIONS.get_all()
995,512
d1ea643ad4f6f094baffee5032b61b1d3c1828d3
from django import template from django.urls import reverse from django.apps import apps import random register = template.Library() @register.filter def to_class_name(value): return value.__class__.__name__ @register.inclusion_tag('GBEX_app/links.html') def links(selected_model): menus = {} selected_menu = "" for model in apps.get_app_config('GBEX_app').get_models(): if hasattr(model, "GBEX_Page"): if model.__name__ == selected_model: selected_menu = model.menu_label menus[model.menu_label] = reverse(f"list_{model.__name__}") return { "menus": menus, "selected_menu": selected_menu, } @register.simple_tag def random_int(a, b=None): if b is None: a, b = 0, a return random.randint(a, b)
995,513
20b61b31cd8f0e1d7c625874e90beb8fa1fa3ff6
from datetime import timedelta import time import paramiko from utils.helper_functions import do_ssh def take_snapshot(bot=None, msg=None, remote=None, ssh_user=None, ssh_password=None): chat_id = msg.message.chat.id user = msg.message.chat.first_name +" "+msg.message.chat.last_name ssh, established = do_ssh(bot, chat_id, remote, ssh_user, ssh_password) if established: try: bot.sendMessage(chat_id, "He enviado la orden...", parse_mode="Html") if user is None: user = "... no se pudo obtener el nombre" notify = "Se ha jecutado una captura de pantalla en "+ remote+" a peticion de " + str(user) broadcast_user_action(bot, chat_id, notify) ssh_stdin, stdout, stderr = ssh.exec_command("export DISPLAY=:0 \n /usr/bin/ksnapshot") #print stdout.channel.recv_exit_status() err = stderr.channel.recv_stderr(1024) if err: if err.startswith('kbuildsycoca running...'): pass else: bot.sendMessage(chat_id, " \xF0\x9F\x98\x94 \n %s" % err, parse_mode="Html") else: bot.sendMessage(chat_id, "\xF0\x9F\x98\x8E \n<b>Captura de pantalla finalizada en %s</b>" % remote, parse_mode="Html") except Exception, e: print(e.message) bot.sendMessage(chat_id, "\xF0\x9F\x92\xA5 \xF0\x9F\x98\xB5 <b>Ocurrio un inconveniente " "al solicitar la ejecucion de ksnapshot</b>", parse_mode="Html") ssh.close() else: bot.sendMessage(chat_id, " \xF0\x9F\x98\x94 \xF0\x9F\x92\x94 <i>Hijole!, no logre conectar con %s" % remote, parse_mode="Html" ) def reboot_host(bot=None, msg=None, remote=None, ssh_user=None, ssh_password=None): chat_id = msg.message.chat.id user = msg.message.chat.first_name +" "+msg.message.chat.last_name ssh, established = do_ssh(bot, chat_id, remote, ssh_user, ssh_password) if established: try: bot.sendMessage(chat_id, "He enviado la orden...", parse_mode="Html") if user is None: user = "... no se pudo obtener el nombre" notify = "Se ha mandado a reiniciar "+ remote+" a peticion de " + str(user) broadcast_user_action(bot, chat_id, notify) ssh_stdin, stdout, stderr = ssh.exec_command("init 6") #print stdout.channel.recv_exit_status() err = stderr.channel.recv_stderr(1024) if err: if err.startswith('kbuildsycoca running...'): pass else: bot.sendMessage(chat_id, " \xF0\x9F\x98\x94 \n %s" % err, parse_mode="Html") else: bot.sendMessage(chat_id, "\xF0\x9F\x98\x8E \n<b>%s se ha o se esta reiniciando</b>" % remote, parse_mode="Html") except Exception, e: print(e.message) bot.sendMessage(chat_id, "\xF0\x9F\x92\xA5 \xF0\x9F\x98\xB5 <b>Ocurrio un inconveniente " "al solicitar el reinicio</b>", parse_mode="Html") ssh.close() else: bot.sendMessage(chat_id, " \xF0\x9F\x98\x94 \xF0\x9F\x92\x94 <i>Hijole!, no logre conectar con %s" % remote, parse_mode="Html" ) def broadcast_user_action(bot=None, chat_id=None, info_msg=""): bot.sendMessage(chat_id, " \xF0\x9F\x91\xBC <b>Accion publicada en canal @stecnica</b>", parse_mode="Html") bot.sendMessage('@stecnica', "\xF0\x9F\x93\xA2 \xF0\x9F\x91\xBC <b> %s </b>" % info_msg, parse_mode="Html")
995,514
af3d7469541ce436c5716c4f39fa4ac21391238f
from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Activities(models.Model): """ Model represents various activities that user can add to his Travel Plan. """ WARSAW = 'WAR' KRAKOW = 'KRK' GDANSK = 'GDA' CITIES = [ (WARSAW, 'Warsaw'), (KRAKOW, 'Krakow'), (GDANSK, 'Gdansk'), ] CLASSIC = 'CLS' CRAZY = 'CRZ' TYPE = [ (CLASSIC, 'Classic'), (CRAZY, 'Crazy') ] name = models.CharField(max_length=256) description = models.TextField() duration = models.IntegerField() city = models.CharField(max_length=3, choices=CITIES) activity_type = models.CharField(max_length=3, choices=TYPE) image = models.ImageField() def __str__(self): return self.name class TravelPlan (models.Model): """ Model represents a Travel Plan that can be created by user. """ name = models.CharField(max_length=256) description = models.TextField() created = models.DateTimeField(auto_now_add=True) activities = models.ManyToManyField(Activities, through='TravelPlanActivities') user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class WeekDay(models.Model): """ Model represents a day in a week. User decides on which day he wants to add certain activity to his travel plan. """ MONDAY = 'Monday' TUESDAY = 'Tuesday' WEDNESDAY = 'Wednesday' THURSDAY = 'Thursday' FRIDAY = 'Friday' SATURDAY = 'Saturday' SUNDAY = 'Sunday' DAYS = [ (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), (SATURDAY, 'Saturday'), (SUNDAY, 'Sunday'), ] name = models.CharField(max_length=9, choices=DAYS) order = models.IntegerField(unique=True) def __str__(self): return self.get_name_display() class TravelPlanActivities(models.Model): """ Model represents which activity is to be added to which travel plan. Additionally, the hour of activity booking can be specified. """ HOURS = [ (1, '1:00 AM'), (2, '2:00 AM'), (3, '3:00 AM'), (4, '4:00 AM'), (5, '5:00 AM'), (6, '6:00 AM'), (7, '7:00 AM'), (8, '8:00 AM'), (9, '9:00 AM'), (10, '10:00 AM'), (11, '11:00 AM'), (12, '12:00 PM'), (13, '1:00 PM'), (14, '2:00 PM'), (15, '3:00 PM'), (16, '4:00 PM'), (17, '5:00 PM'), (18, '6:00 PM'), (19, '7:00 PM'), (20, '8:00 PM'), (21, '9:00 PM'), (22, '10:00 PM'), (23, '11:00 PM'), (24, '12:00 AM') ] travel_plan = models.ForeignKey(TravelPlan, on_delete=models.CASCADE, null=True) activities = models.ForeignKey(Activities, on_delete=models.CASCADE, null=True) week_day = models.ForeignKey(WeekDay, on_delete=models.CASCADE) time = models.IntegerField(choices=HOURS) user = models.ManyToManyField(User)
995,515
ca14e7c7c4a4e5d6514c5b664f918a110c8431a9
import pandas as pd @transform_pandas( Output(rid="ri.vector.main.execute.ac452cb8-5902-4044-a251-a10617f9ee6d"), s_interact_invars=Input(rid="ri.foundry.main.dataset.56725eae-2284-4cb3-a920-ac17601fcc18") ) def unnamed_4(s_interact_invars): @transform_pandas( Output(rid="ri.foundry.main.dataset.c58607a0-5f4b-4882-a060-ad93dc631a26"), s_interact_NOTinvars=Input(rid="ri.foundry.main.dataset.7dc6d77a-edbf-4c00-834d-ac149c707e21"), s_interact_invars=Input(rid="ri.foundry.main.dataset.56725eae-2284-4cb3-a920-ac17601fcc18") ) def unnamed_5(s_interact_invars, s_interact_NOTinvars): local_df1 = (s_interact_invars) local_df2 = s_interact_NOTinvars print(local_df1) return local_df1
995,516
0676e6b060472cc60002eeb0998717bd3bef9dcf
from d08lib import read_d08, State, run_until_loop def main(): orig_ops = tuple(read_d08()) *_, cand_ops = run_until_loop(State(opc=0, acc=0), orig_ops) for i in cand_ops: if orig_ops[i][0] == "acc": continue ops = list(orig_ops) ops[i] = ("jmp" if ops[i][0] == "nop" else "nop", ops[i][1]) state = State(opc=0, acc=0) final_state, finished, _ = run_until_loop(state, ops) if finished: print(i, final_state) break if __name__ == "__main__": main()
995,517
fc19ccef78b16da9a178f12942421d3bc3006d2a
""" Balanced strings are those who have equal quantity of 'L' and 'R' characters. Given a balanced string s split it in the maximum amount of balanced strings. Return the maximum amount of splitted balanced strings. Example 1: Input: s = "RLRRLLRLRL" Output: 4 Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. Example 2: Input: s = "RLLLLRRRLR" Output: 3 Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'. Example 3: Input: s = "LLLLRRRR" Output: 1 Explanation: s can be split into "LLLLRRRR". Example 4: Input: s = "RLRRRLLRLL" Output: 2 Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R' Constraints: 1 <= s.length <= 1000 s[i] = 'L' or 'R' """ class Solution(object): def balancedStringSplit(self, s): """ :type s: str :rtype: int """ flag, n = None, 0 res = 0 for c in s: if flag is None: flag = c n += 1 elif flag == c: n += 1 else: n -= 1 if n == 0: res += 1 flag, n = None, 0 return res examples = [ { "input": { "s": "RLRRLLRLRL", }, "output": 4 }, { "input": { "s": "RLLLLRRRLR", }, "output": 3 }, { "input": { "s": "LLLLRRRR", }, "output": 1 }, { "input": { "s": "RLRRRLLRLL", }, "output": 2 } ] import time if __name__ == '__main__': solution = Solution() for n in dir(solution): if not n.startswith('__'): func = getattr(solution, n) print(func) for example in examples: print '----------' start = time.time() v = func(**example['input']) end = time.time() print v, v == example['output'], end - start
995,518
e30a866ed33caaefd5bd07595248ebcfbcc6978e
# -*- coding: utf-8 -*- from . import LiuYue from ..util import LunarUtil class LiuNian: """ 流年 """ def __init__(self, da_yun, index): self.__daYun = da_yun self.__lunar = da_yun.getLunar() self.__index = index self.__year = da_yun.getStartYear() + index self.__age = da_yun.getStartAge() + index def getIndex(self): return self.__index def getYear(self): return self.__year def getAge(self): return self.__age def getGanZhi(self): """ 获取干支 :return: 干支 """ offset = LunarUtil.getJiaZiIndex(self.__lunar.getJieQiTable()["立春"].getLunar().getYearInGanZhiExact()) + self.__index if self.__daYun.getIndex() > 0: offset += self.__daYun.getStartAge() - 1 offset %= len(LunarUtil.JIA_ZI) return LunarUtil.JIA_ZI[offset] def getXun(self): """ 获取所在旬 :return: 旬 """ return LunarUtil.getXun(self.getGanZhi()) def getXunKong(self): """ 获取旬空(空亡) :return: 旬空(空亡) """ return LunarUtil.getXunKong(self.getGanZhi()) def getLiuYue(self): """ 获取流月 :return: 流月 """ n = 12 liu_yue = [] for i in range(0, n): liu_yue.append(LiuYue(self, i)) return liu_yue
995,519
77c95ab52dc0108c348d557cc756469de98a844c
# -*- coding: utf-8 -*- # @Time : 2021/5/25 16:57 # @Author : haojie zhang """ 516. 最长回文子序列 给定一个字符串 s ,找到其中最长的回文子序列,并返回该序列的长度。可以假设 s 的最大长度为 1000 。 示例 1: 输入: "bbbab" 输出: 4 一个可能的最长回文子序列为 "bbbb"。 """ class Solution: def longestPalindromeSubseq(self, s: str) -> int: n = len(s) dp = [[0] * n for _ in range(n)] for i in range(n-1, -1, -1): dp[i][i] = 1 for j in range(i+1, n): if s[i] == s[j] and (j - i == 1 or dp[i+1][j-1]): dp[i][j] = dp[i+1][j-1] + 2 else: dp[i][j] = max(dp[i+1][j], dp[i][j-1]) return dp[0][-1] s = "bbbab" obj = Solution() print(obj.longestPalindromeSubseq(s))
995,520
bde62132a0190f7a98d80784082a03f9213f74c6
import tensorflow as tf import keras from keras import layers, optimizers from keras.models import Model from keras.layers import Dense, Activation, Flatten, Conv2D, MaxPool2D, AveragePooling2D, BatchNormalization, \ ZeroPadding2D, Input, GlobalAveragePooling2D import numpy as np import cv2 import os x_train = []; y_train = [] for filename in os.listdir("datasets/train"): im = cv2.imread(os.path.join("datasets/train", filename), 1) im = cv2.resize(im, (224, 224)) x_train.append(im) if(filename[0] == '0'): y_train.append(0) elif(filename[0] == '1'): y_train.append(1) elif(filename[0] == '2'): y_train.append(2) elif(filename[0] == '4'): y_train.append(3) x_test = []; y_test = [] for filename in os.listdir("datasets/test"): im = cv2.imread(os.path.join("datasets/test", filename), 1) im = cv2.resize(im, (224, 224)) x_test.append(im) if(filename[0] == '0'): y_test.append(0) elif(filename[0] == '1'): y_test.append(1) elif(filename[0] == '2'): y_test.append(2) elif(filename[0] == '4'): y_test.append(3) x_train = np.array(x_train) y_train = np.array(y_train) x_test = np.array(x_test) y_test = np.array(y_test) # Scale images to the [0, 1] range x_train = x_train.astype("float32") / 255 x_test = x_test.astype("float32") / 255 print(x_train.shape) # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, 4) y_test = keras.utils.to_categorical(y_test, 4) print(y_train.shape) ################# base_model = keras.applications.MobileNetV2(weights='imagenet', include_top=False) x = base_model.output x = GlobalAveragePooling2D()(x) predictions = Dense(4, activation='softmax')(x) model = Model(inputs=base_model.input, outputs=predictions) model.summary() adam = optimizers.Adam(0.001) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=adam, metrics=['accuracy']) cb = keras.callbacks.ModelCheckpoint("./models/model.hdf5", monitor='loss', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1) callback = [cb] model.fit(x_train, y_train, batch_size=16, epochs=1500, verbose=1, validation_data=(x_test, y_test), callbacks=callback) # evaluating and printing results score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1])
995,521
13b633a1a7a0d1d6a69b9074f7c0118625dd3a12
from unittest import TestCase from ipynb.fs.full.index import * class TxTest(TestCase): def test_coinbase_height(self): raw_tx = bytes.fromhex('01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff5e03d71b07254d696e656420627920416e74506f6f6c20626a31312f4542312f4144362f43205914293101fabe6d6d678e2c8c34afc36896e7d9402824ed38e856676ee94bfdb0c6c4bcd8b2e5666a0400000000000000c7270000a5e00e00ffffffff01faf20b58000000001976a914338c84849423992471bffb1a54a8d9b1d69dc28a88ac00000000') stream = BytesIO(raw_tx) tx = Tx.parse(stream) self.assertEqual(tx.coinbase_height(), 465879) raw_tx = bytes.fromhex('0100000001813f79011acb80925dfe69b3def355fe914bd1d96a3f5f71bf8303c6a989c7d1000000006b483045022100ed81ff192e75a3fd2304004dcadb746fa5e24c5031ccfcf21320b0277457c98f02207a986d955c6e0cb35d446a89d3f56100f4d7f67801c31967743a9c8e10615bed01210349fc4e631e3624a545de3f89f5d8684c7b8138bd94bdd531d2e213bf016b278afeffffff02a135ef01000000001976a914bc3b654dca7e56b04dca18f2566cdaf02e8d9ada88ac99c39800000000001976a9141c4bc762dd5423e332166702cb75f40df79fea1288ac19430600') stream = BytesIO(raw_tx) tx = Tx.parse(stream) self.assertIsNone(tx.coinbase_height())
995,522
2f837ae3e3a8c08692e75453446316ebbe777ee6
from __future__ import division import argparse import pandas as pd import re # regular expression # useful stuff import numpy as np from scipy.special import expit from sklearn.preprocessing import normalize __authors__ = ['Antoine Guiot', 'Arthur Claude', 'Armand Margerin'] __emails__ = ['antoine.guiot@supelec.fr', 'arthur.claude@supelec.fr', 'armand.margerin@gmail.com'] import pickle from spacy.lang.en import English nlp = English() # to add a word as stop word nlp.vocab[word].is_stop = True def text2sentences(path): sentences = [] with open(path) as f: for l in f: # l = re.sub('[^a-zA-Z]', '', l) # regex = re.compile('[^a-zA-Z]') # First parameter is the replacement, second parameter is your input string sentences.append(re.sub('[^a-zA-Z]', ' ', l).lower().split()) # removing stopwords and punctuation for sentence in sentences: for word in sentence: lexeme = nlp.vocab[word] if lexeme.is_stop == True: sentence.remove(word) return sentences def loadPairs(path): data = pd.read_csv(path, delimiter='\t') pairs = zip(data['word1'], data['word2'], data['similarity']) return pairs class SkipGram: def __init__(self, sentences, nEmbed=100, negativeRate=5, winSize=5, minCount=5): self.minCount = minCount self.winSize = winSize # dictionnary containing the nb of occurrence of each word sentences_concat = np.concatenate(sentences) unique, frequency = np.unique(sentences_concat, return_counts=True) self.occ = dict(zip(unique, frequency)) self.vocab = {k: v for k, v in self.occ.items() if v > self.minCount} self.w2id = dict(zip(self.vocab.keys(), np.arange(0, len(self.vocab)))) self.trainset = sentences # set of sentences self.negativeRate = negativeRate self.nEmbed = nEmbed id = self.w2id.values() vect = np.random.random((self.nEmbed, len(self.w2id))) self.U = dict(zip(id, vect.T)) self.V = dict(zip(id, vect.T)) # self.U = np.random.random((self.nEmbed, len(self.w2id))) # self.V = np.random.random((self.nEmbed, len(self.w2id))) self.loss = [] self.trainWords = 0 self.accLoss = 0. self.q = {} s = 0 for w in self.w2id.keys(): f = self.occ[w] ** (3 / 4) s += f self.q[self.w2id[w]] = f self.q = {k: v / s for k, v in self.q.items()} # dictionary with keys = ids and values = prob q def sample(self, omit): """samples negative words, ommitting those in set omit""" w2id_list = list(self.w2id.values()) q_list = list(self.q.values()) negativeIds = np.random.choice(w2id_list, size=self.negativeRate, p=q_list) for i in range(len(negativeIds)): if negativeIds[i] in omit: while negativeIds[i] in omit: negativeIds[i] = np.random.choice(w2id_list, p=q_list) return negativeIds def train(self, nb_epochs=10): eta = 0.25 for epoch in range(nb_epochs): eta = 0.9 * eta for counter, sentence in enumerate(self.trainset): sentence = list(filter(lambda word: word in self.vocab, sentence)) for wpos, word in enumerate(sentence): wIdx = self.w2id[word] winsize = np.random.randint(self.winSize) + 1 start = max(0, wpos - winsize) end = min(wpos + winsize + 1, len(sentence)) for context_word in sentence[start:end]: ctxtId = self.w2id[context_word] if ctxtId == wIdx: continue negativeIds = self.sample({wIdx, ctxtId}) self.trainWord(wIdx, ctxtId, negativeIds, eta) self.trainWords += 1 self.accLoss += self.compute_loss(wIdx, ctxtId) if counter % 100 == 0: # print(' > training %d of %d' % (counter, len(self.trainset))) self.loss.append(self.accLoss / self.trainWords) self.trainWords = 0 self.accLoss = 0. def trainWord(self, wordId, contextId, negativeIds, eta): # compute gradients of l U1 = self.U[wordId] V2 = self.V[contextId] scalar = U1.dot(V2) gradl_word = 1 / (1 + np.exp(scalar)) * V2 gradl_context = 1 / (1 + np.exp(scalar)) * U1 # modifié le signe # update representations U1 += eta * gradl_word V2 += eta * gradl_context # update U and V self.U[wordId] = U1 self.V[contextId] = V2 for negativeId in negativeIds: # compute gradients of l U1 = self.U[wordId] V2 = self.V[negativeId] scalar = U1.dot(V2) gradl_word = -1 / (1 + np.exp(-scalar)) * V2 gradl_context = -1 / (1 + np.exp(-scalar)) * U1 # update representations U1 += eta * gradl_word V2 += eta * gradl_context # update U and V self.U[wordId] = U1 self.V[negativeId] = V2 def save(self, path): with open(path, 'wb') as f: pickle.dump([self.U, self.w2id, self.vocab], f) def compute_loss(self, id_word_1, id_word_2): w1 = self.U[id_word_1] w2 = self.U[id_word_2] scalair = w1.dot(w2) similarity = 1 / (1 + np.exp(-scalair)) return similarity def compute_score(self): true = pd.read_csv('simlex.csv', delimiter='\t') pairs = loadPairs('simlex.csv') similarity_prediction = [] for a, b, _ in pairs: # make sure this does not raise any exception, even if a or b are not in sg.vocab similarity_prediction.append((self.similarity(a, b))) similarity_prediction = pd.DataFrame(np.array(similarity_prediction), columns=['prediction']) merged_df = pd.concat([similarity_prediction, true], axis=1) merged_df = merged_df[merged_df['prediction'] < 1] return merged_df[['prediction', 'similarity']].corr().similarity[0] def similarity(self, word1, word2): """ computes similiarity between the two words. unknown words are mapped to one common vector :param word1: :param word2: :return: a float \in [0,1] indicating the similarity (the higher the more similar) """ common_vect = +np.ones(self.nEmbed) * 10000 if word1 not in self.vocab and word2 in self.vocab: id_word_2 = self.w2id[word2] w1 = common_vect w2 = self.U[id_word_2] elif word1 in self.vocab and word2 not in self.vocab: id_word_1 = self.w2id[word1] w1 = self.U[id_word_1] w2 = common_vect elif word1 not in self.vocab and word2 not in self.vocab: w1 = common_vect w2 = common_vect else: id_word_1 = self.w2id[word1] id_word_2 = self.w2id[word2] w1 = self.U[id_word_1] w2 = self.U[id_word_2] # scalair = w1.dot(w2)/np.linalg.norm(w1,w2) similarity = w1.dot(w2) / (np.linalg.norm(w1) * np.linalg.norm(w2)) # similarity = 1 / (1 + np.exp(-scalair)) # similarity = scalair / (np.linalg.norm(w1) * np.linalg.norm(w2)) return similarity @staticmethod def load(path): with open(path, 'rb') as f: U_l, w2id_l, vocab_l = pickle.load(f) sg = SkipGram([]) sg.U = U_l sg.w2id = w2id_l sg.vocab = vocab_l return sg if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--text', help='path containing training data', required=True) parser.add_argument('--model', help='path to store/read model (when training/testing)', required=True) parser.add_argument('--test', help='enters test mode', action='store_true') opts = parser.parse_args() if not opts.test: sentences = text2sentences(opts.text) sg = SkipGram(sentences) sg.train(1) sg.save(opts.model) else: pairs = loadPairs(opts.text) sg = SkipGram.load(opts.model) for a, b, _ in pairs: # make sure this does not raise any exception, even if a or b are not in sg.vocab print(sg.similarity(a, b))
995,523
ef66a8c7e9c68731b2840991cedfe0c44f48c4a9
#!/usr/bin/env python3 import sys from math import sqrt def overlap(x1=0, y1=0, r1=1, x2=0, y2=0, r2=1): return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) < r1 + r2
995,524
f817e9a2c1cf9e520a64b683ecee1250f7ea23dd
from PyQt4 import QtCore, QtGui from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * import sys import codecs import download import time import os class Downloader(QObject): # To be emitted when every items are downloaded done = pyqtSignal() def __init__(self, urlList, teams, out = None, parent = None): super(Downloader, self).__init__(parent) self.urlList = urlList self.teams = teams if out: sys.stdout = out # As you probably don't need to display the page # you can use QWebPage instead of QWebView self.page = QWebPage(self) self.page.loadFinished.connect(self.save) self.currentTeam() def currentTeam(self): try: self.use = self.urlList.pop() self.startNext() except IndexError: print("It looks like there's a problem!") self.done.emit() def startNext(self): self.page.mainFrame().load(QUrl(self.teams[self.use]['promo'])) def save(self, ok): if ok: data = self.page.mainFrame().toHtml() self.teams[self.use]['html'] = data results = download.download_promo(self.teams[self.use], self.use) print('Downloading promo for {0}: \t link: {1}'.format(self.use, self.teams[self.use]['promo'])) #else: # print("Error while downloading %s\nSkipping."%self.currentUrl()) if self.urlList: self.currentTeam() else: self.done.emit() app = QApplication(sys.argv) MainWindow = QtGui.QMainWindow() teams, overall, downloadedFiles = download.load_teams() for team in teams.keys(): teams[team]['html'] = '' date = time.strftime("_%m_%d_%Y") teams2 = dict(teams) for team in teams2.keys(): directory = os.path.join('Data', date, 'Promo', team+date+".csv") if os.path.exists(directory): del teams[team] print("Already got it team {0}: url - {1}".format(team, teams2[team]['promo'])) downloader = Downloader(sorted(list(teams.keys())), teams) downloader.done.connect(app.quit) web = QWebView() web.setPage(downloader.page) web.show() sys.exit(app.exec_())
995,525
caf312b4eaa016ad5a711921c87d669f0ae0982b
from flask import Flask, render_template import random #시작점인지 검증하기 위해 Flask에서 내부적으로 구현해놓은 부분 app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" @app.route("/ara") def ara(): return "This is Ara!!!!" #pass variable routing @app.route('/greeting/<string:name>') #<string:name> 이 부분 변화 가능 def greeting(name): return f'반갑습니다 {name}님! ' #주소 : http://127.0.0.1:5000/greeting/ara #결과 : 반갑습니다 ara님! @app.route('/cube/<int:num>') def cube(num): res = num ** 3 return f'{res}' # ==str(res) #<int:people> import random as rand @app.route('/lunch/<int:num>') def lunch(num): lunch = ['Salad', 'Pizza', 'SundaeGukbab', 'F20', 'Gimbab','Toast','Yogurt','Tomatilo'] res = random.sample(lunch, num) return str(res) @app.route('/html') def html(): html_string = """ <h1> This is H1 tag </h1> <h2> This is H2 tag </h2> <p> This is p tag </p> """ return html_string @app.route('/html_file') def html_file(): return render_template('index.html') @app.route('/hi/<string:name>') def hi(name): return render_template('hi.html', your_name=name) @app.route('/menulist') def menulist(): menulist = ['Salad', 'Pizza', 'SundaeGukbab', 'F20', 'Gimbab', 'Toast', 'Yogurt', 'Tomatilo'] return render_template('menulist.html', menu_list=menulist) if __name__ == '__main__': app.run(debug=True)
995,526
e71503cee57cd4545eac3b1a2c2f50f278cb5b92
'''Functions for validating and sprucing-up inputs.''' def validate_sidewalks(sidewalks): sidewalks_ls = sidewalks[sidewalks.type == 'LineString'] n = sidewalks_ls.shape[0] if n: if n < sidewalks.shape[0]: m = sidewalks.shape[0] - n print('Warning: Removed {} non-LineString sidewalks'.format(m)) return sidewalks_ls else: raise Exception('No LineStrings in sidewalks dataset: are they' + ' MultiLineStrings?') def validate_streets(streets): streets_ls = streets[streets.type == 'LineString'] n = streets_ls.shape[0] if n: if n < streets.shape[0]: m = streets.shape[0] - n print('Warning: Removed {} non-LineString streets'.format(m)) return streets_ls else: raise Exception('No LineStrings in streets dataset: are they' + ' MultiLineStrings?')
995,527
1dd9be0e09c74d5666015e33957d9a6d8793a332
import simple_dense X = np.array([[0, 0, 0], [1, 0, 1], [0, 1, 1], [1, 1, 0], [0, 1, 1]]) y = np.array([[0], [1], [1], [0], [1]]) print("Learning start") net = simple_dense.network(X, y, 10, 10) for j in range(100000): net.epoch() if j%1000 == 0: net.epoch(1) net.epoch(1) print("Learning end") X = np.array([[0, 0, 0], [1, 0, 1], [0, 1, 1], [1, 1, 0]]) net.predict(X)
995,528
f78a79c275e90a90394269b230cdef39dbc4d979
""" Python program to find the largest element and its location. """ def largest_element(a): """ Return the largest element of a sequence a. """ return None if __name__ == "__main__": a = [1,2,3,2,1] print("Largest element is {:}".format(largest_element(a)))
995,529
5d35c6ce0373b36c1d0cbfe85d9d89a39a41a77f
nota1 = float(input('Insira a primeira nota do aluno: ')) nota2 = float(input('Insira a segunda nota do aluno: ')) media = (nota1 + nota2) / 2 if media < 5: print('\033[41mREPROVADO\033[m') elif media >= 5 and media < 7: print('\033[43mRECUPERAÇÃO\033[m') else: print('\033[42mAPROVADO\033[m')
995,530
43e9948b96522ddae75a530d489e7ca16cfaf632
# mendefinisikan array dengan nilai awal import array A = array.array('i', [100,200,300,400,500]) print("Nilai awal sebelum diubah :", A) # mengubah nilai dari elemen tertentu A[1] = -700 # mengubah elemen kedua A[4] = 800 # mengubah elemen kelima print("Nila akhir setelah diubah :", A) #exercise9.10 # nilai awal (sebelum dibalik) print("Nilai Awal sebelum dibalik :", A) # membalik urutan elemen array print("Nilai Akhir setelah dibalik ", A.reverse())
995,531
11a5ab5775a3ff85db3b4f2a6a64c173f6670537
#!/usr/bin/env python import subprocess import Utils APPNAME = 'HDTraceWritingCLibrary' VERSION = '0svn20090617' srcdir = '.' blddir = 'build' def _getconf (key): # FIXME Maybe use os.confstr(). p = subprocess.Popen(['getconf', key], stdout=subprocess.PIPE, close_fds=True) v = p.communicate()[0].strip() if not v: return [] return Utils.to_list(v) def set_options (opt): opt.tool_options('compiler_cc') def configure (conf): conf.check_tool('compiler_cc') conf.env.CCFLAGS += ['-std=gnu99', '-ggdb', '-O2' ] conf.env.CCFLAGS += _getconf('LFS_CFLAGS') conf.env.LDFLAGS += _getconf('LFS_LDFLAGS') conf.env.LDFLAGS += _getconf('LFS_LIBS') conf.check_cc( header_name = 'dlfcn.h', lib = 'dl', uselib_store = 'DL' ) #conf.env.CCFLAGS += ['-Wextra', '-Wno-missing-field-initializers', '-Wno-unused-parameter', '-Wold-style-definition', '-Wdeclaration-after-statement', '-Wmissing-declarations', '-Wmissing-prototypes', '-Wredundant-decls', '-Wmissing-noreturn', '-Wshadow', '-Wpointer-arith', '-Wcast-align', '-Wwrite-strings', '-Winline', '-Wformat-nonliteral', '-Wformat-security', '-Wswitch-enum', '-Wswitch-default', '-Winit-self', '-Wmissing-include-dirs', '-Wundef', '-Waggregate-return', '-Wmissing-format-attribute', '-Wnested-externs', '-Wstrict-prototypes'] conf.sub_config('src') conf.sub_config('tests') conf.sub_config('tools') ''' -# Enable debugging flags when enabled -AC_ARG_ENABLE(debugging, - AC_HELP_STRING([--enable-debugging],[enable debugging flags and output (overrides CFLAGS argument)]), - [ - CFLAGS="-g -O0 -ggdb -DDEBUG" - ] - ) - -# Enable compiler warnings when enabled and using gcc -AC_ARG_ENABLE(warnings, - AC_HELP_STRING([--enable-warnings],[enable lots of compiler warnings (only with GCC)]), - [ - if test "$GCC" != "yes" - then - CFLAGS="${CFLAGS} -pedantic -Wall -Wextra -Waggregate-return -Wcast-align -Wcast-qual \ - -Wconversion -Wfloat-equal -Wformat=2 -Winit-self -Winline -Wmissing-declarations \ - -Wmissing-format-attribute -Wmissing-include-dirs -Wmissing-noreturn \ - -Wmissing-prototypes -Wnested-externs -Wold-style-definition -Wredundant-decls \ - -Wshadow -Wstrict-prototypes -Wswitch-default -Wswitch-enum -Wundef -Wwrite-strings" - else - AC_MSG_WARN(["--enable-warnings" only does something when using gcc]) - fi - ] - ) - -# Disable assert macro for faster code -AC_ARG_ENABLE(asserts, - AC_HELP_STRING([--disable-asserts],[disable assertion code (should produce faster code)]), - [ - if test "$enableval" == "no" - then - CPPFLAGS="${CPPFLAGS} -DNDEBUG" - fi - ] - ) ''' def build (bld): bld.add_subdirs('include') bld.add_subdirs('src') bld.add_subdirs('tests') bld.add_subdirs('tools') ''' -doxyINPUT = $(SRC_DIR) $(INC_DIR) $(top_srcdir)/include - -devdoc: force - OUTDIR=$(DOC_DIR) INPUT="$(doxyINPUT)" doxygen $(top_srcdir)/Doxyfile - -apidoc: force - mkdir -p $(DOC_DIR)/api - OUTDIR=$(DOC_DIR)/api INPUT="$(doxyINPUT)" doxygen $(top_srcdir)/Doxyfile.api_only '''
995,532
38c28cb45893172567e3db15e90677b35e6d5830
#!/usr/bin/python import sys import json import base64 import requests file_contents = open(sys.argv[1], 'rb').read() encoded_contents = base64.b64encode(file_contents) payload = {'app': encoded_contents} r = requests.post('https://192.168.38.110/rest/app', auth=('admin', sys.argv[2]), data=json.dumps(payload), verify=False) print r.status_code print r.text
995,533
71d0ccfb56369e20f58b1dc8333a88694380bae6
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-21 20:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('menus', '0002_auto_20170224_1508'), ] operations = [ migrations.RemoveField( model_name='menu', name='dishes', ), migrations.AddField( model_name='dish', name='menus', field=models.ManyToManyField(to='menus.Menu'), ), migrations.AddField( model_name='menu', name='meal_permissions', field=models.CharField(choices=[('NG', 'No Guests or Meal Exchanges'), ('NME', 'No Meal Exchanges'), ('SGO', 'Sophomore Guests Only'), ('NTO', 'No Boxes for Take-out'), ('ALL', 'Guests and Meal Exchanges Allowed')], default='ALL', max_length=10), ), ]
995,534
6f3a9e3e2bb0fb1cc7dea844dfdf3942f8b80039
# -*- coding: utf-8 -*- # Copyright (C) 2006-2008 Vodafone España, S.A. # Author: Pablo Martí # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Base Wrapper """ __version__ = "$Rev: 1203 $" from vmc.common.resource_manager import ResourceManager from vmc.common.exceptions import StateMachineNotReadyError class BaseWrapper(object): """ I wrap the access to resources in runtime I'm the entry point to interact with the bottom half of the app for third party developers """ BEHAVIOUR_KLASS = None def __init__(self, device, noti_callbacks, sm_callbacks, sm_errbacks): super(BaseWrapper, self).__init__() self.device = device self.noti_callbacks = noti_callbacks self.sm_callbacks = sm_callbacks self.sm_errbacks = sm_errbacks self.behaviour = None self.rmanager = ResourceManager() self.setup() def setup(self): if self.device: self.device = self.rmanager.setup_device(self.device) args = [self, self.device, self.noti_callbacks] self.rmanager.setup_notifications_and_daemons(*args) def start_behaviour(self, *args): """ Starts the Behaviour meta state machine. """ dialer = self.rmanager.get_dialer() self.behaviour = self.BEHAVIOUR_KLASS(self.device, dialer, self.sm_callbacks, self.sm_errbacks, *args) self.rmanager.notimanager.add_listener(self.behaviour) self.behaviour.notification_manager = self.rmanager.notimanager self.behaviour.start() def get_current_sm(self): """ Returns the current state machine in use @raise StateMachineNotReadyError: When the state machine is not ready. This is to prevent third-party plugin developers to perform operations when they shouldn't """ if self.behaviour.initting: raise StateMachineNotReadyError return self.behaviour.current_sm
995,535
b159f761180622de9e2d158350516e18690495b0
# This is a test service class TestService(object): pass def init(): return dict(service_class=TestService)
995,536
fec55e03bc70d1b4b7bd0c12ac9029c8f581e455
# Developed by Redjumpman for Redbot # Credit to jonnyli1125 for the original work on Discordant # Standard Library import aiohttp import re import urllib.parse # Red from redbot.core import commands # Discord import discord BaseCog = getattr(commands, "Cog", object) class Jisho(BaseCog): def __init__(self): self.connector = aiohttp.TCPConnector(force_close=True) self.session = aiohttp.ClientSession(connector=self.connector) def __unload(self): self.session.close() @commands.command() async def jisho(self, ctx, word: str): """Translates Japanese to English, and English to Japanese Works with Romaji, Hiragana, Kanji, and Katakana""" search_args = await self.dict_search_args_parse(ctx, word.lower()) if not search_args: return limit, query = search_args message = urllib.parse.quote(query, encoding='utf-8') url = "http://jisho.org/api/v1/search/words?keyword=" + message async with self.session.get(url) as response: data = await response.json() try: messages = [self.parse_data(result) for result in data["data"][:limit]] except KeyError: return await ctx.send("I was unable to retrieve any data") try: await ctx.send('\n'.join(messages)) except discord.HTTPException: await ctx.send("No data for that word.") def parse_data(self, result): japanese = result["japanese"] output = self.display_word(japanese[0], "**{reading}**", "**{word}** {reading}") + "\n" new_line = "" if result["is_common"]: new_line += "Common word. " if result["tags"]: new_line += "Wanikani level " + ", ".join( [tag[8:] for tag in result["tags"]]) + ". " if new_line: output += new_line + "\n" senses = result["senses"] for index, sense in enumerate(senses, 1): parts = [x for x in sense["parts_of_speech"] if x is not None] if parts == ["Wikipedia definition"]: continue if parts: output += "*{}*\n".format(", ".join(parts)) output += "{}. {}".format(index, "; ".join(sense["english_definitions"])) for attr in ["tags", "info"]: if sense[attr]: output += ". *{}*.".format("".join(sense[attr])) if sense["see_also"]: output += ". *See also: {}*".format(", ".join(sense["see_also"])) output += "\n" if len(japanese) > 1: output += "Other forms: {}\n".format(", ".join( [self.display_word(x, "{reading}", "{word} ({reading})") for x in japanese[1:]])) return output def display_word(self, obj, *formats): return formats[len(obj) - 1].format(**obj) async def dict_search_args_parse(self, ctx, message): if not message: return await ctx.send("Error in arg parse") limit = 1 query = message result = re.match(r"^([0-9]+)\s+(.*)$", message) if result: limit, query = [result.group(x) for x in (1, 2)] return int(limit), query
995,537
370b3f1150ec790a59b0bbcb39932375a60b30de
#user enters a number i_num1=int(input("please enter a number")) i_num2=int(input("please enter another number")) #code outputs greatest number if i_num1 > i_num2: print(i_num1) else: print(i_num2) ##ACS - end if (this should appear after each construct)
995,538
2f9c0c723041f0c4427c2201d526c9aefad71116
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ## Frank@Villaro-Dixon.eu - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE, etc. __version__ = "1.0" from .Elevation import Elevation # vim: set ts=4 sw=4 noet:
995,539
4084ecfa02b6492abeab8f02bb2e3794863d483b
# coding: utf-8 # Here goes the imports import csv import matplotlib.pyplot as plt # Let's read the data as a list print("Reading the document...") with open("chicago.csv", "r") as file_read: reader = csv.reader(file_read) data_list = list(reader) print("Ok!") # Let's check how many rows do we have print("Number of rows:") print(len(data_list)) # Printing the first row of data_list to check if it worked. print("Row 0: ") print(data_list[0]) # It's the data header, so we can identify the columns. # Printing the second row of data_list, it should contain some data print("Row 1: ") print(data_list[1]) input("Press Enter to continue...") # TASK 1 # TODO: Print the first 20 rows using a loop to identify the data. print("\n\nTASK 1: Printing the first 20 samples") for row in range(0,21): ''' A loop with range from 0 to 20 to obey the first Task ''' print(data_list[row]) # Let's change the data_list to remove the header from it. data_list = data_list[1:] # We can access the features through index # E.g. sample[6] to print gender or sample[-2] input("Press Enter to continue...") # TASK 2 # TODO: Print the `gender` of the first 20 rows print("\nTASK 2: Printing the genders of the first 20 samples") for row in range(0,21): ''' A loop with range from 0 to 20 to obey the second Task, choosing the 7th element(gender) of each row ''' print(data_list[row][6]) # Cool! We can get the rows(samples) iterating with a for and the columns(features) by index. # But it's still hard to get a column in a list. Example: List with all genders input("Press Enter to continue...") # TASK 3 # TODO: Create a function to add the columns(features) of a list in another list in the same order def column_to_list(data, index): ''' Function to select the same element of a list of lists. Arg: a : list of lists b : element that will be taken from the list into a new list returns a new list of parameter b. ''' column_list = [] for row in data: column_list.append(row[index]) # Tip: You can use a for to iterate over the samples, get the feature by index and append into a list return column_list # Let's check with the genders if it's working (only the first 20) print("\nTASK 3: Printing the list of genders of the first 20 samples") print(column_to_list(data_list, -2)[:20]) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(column_to_list(data_list, -2)) is list, "TASK 3: Wrong type returned. It should return a list." assert len(column_to_list(data_list, -2)) == 1551505, "TASK 3: Wrong lenght returned." assert column_to_list(data_list, -2)[0] == "" and column_to_list(data_list, -2)[1] == "Male", "TASK 3: The list doesn't match." # ----------------------------------------------------- input("Press Enter to continue...") # Now we know how to access the features, let's count how many Males and Females the dataset have # TASK 4 # TODO: Count each gender. You should not use a function to do that. male = 0 female = 0 for row in data_list: if row[6].lower() == 'male': male += 1 elif row[6].lower() == 'female': female += 1 # Checking the result print("\nTASK 4: Printing how many males and females we found") print("Male: ", male, "\nFemale: ", female) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert male == 935854 and female == 298784, "TASK 4: Count doesn't match." # ----------------------------------------------------- input("Press Enter to continue...") # Why don't we creeate a function to do that? # TASK 5 # TODO: Create a function to count the genders. Return a list # Should return a list with [count_male, counf_female] (e.g., [10, 15] means 10 Males, 15 Females) def count_gender(data_list): ''' Function to count each sex. Arg: a : list which contains the sexes returns a list that the first item is the sum of males and the second item is the sum of females ''' male = 0 female = 0 for row in data_list: if row[6].lower() == 'male': male += 1 elif row[6].lower() == 'female': female += 1 return [male, female] print("\nTASK 5: Printing result of count_gender") print(count_gender(data_list)) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(count_gender(data_list)) is list, "TASK 5: Wrong type returned. It should return a list." assert len(count_gender(data_list)) == 2, "TASK 5: Wrong lenght returned." assert count_gender(data_list)[0] == 935854 and count_gender(data_list)[1] == 298784, "TASK 5: Returning wrong result!" # ----------------------------------------------------- input("Press Enter to continue...") # Now we can count the users, which gender use it the most? # TASK 6 # TODO: Create a function to get the most popular gender and print the gender as string. # We expect to see "Male", "Female" or "Equal" as answer. def most_popular_gender(data_list): ''' Function to determine which sex is more popular. Arg: a : list which contains the sexes returns it will print the answer of which sex has appeared more in the data_list ''' answer = "" gender = count_gender(data_list) if gender[0] > gender [1]: answer = 'Male' elif gender[0] < gender [1]: answer = 'Female' else: answer = 'Equal' return answer print("\nTASK 6: Which one is the most popular gender?") print("Most popular gender is: ", most_popular_gender(data_list)) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(most_popular_gender(data_list)) is str, "TASK 6: Wrong type returned. It should return a string." assert most_popular_gender(data_list) == "Male", "TASK 6: Returning wrong result!" # ----------------------------------------------------- # If it's everything running as expected, check this graph! gender_list = column_to_list(data_list, -2) types = ["Male", "Female"] quantity = count_gender(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantity') plt.xlabel('Gender') plt.xticks(y_pos, types) plt.title('Quantity by Gender') plt.show(block=True) input("Press Enter to continue...") # TASK 7 # TODO: Plot a similar graph for user_types. Make sure the legend is correct. print("\nTASK 7: Check the chart!") def count_user_type(data_list): ''' Function to count each type of user Arg: a : list which contains the sexes returns a list that the first value is the user type Subscribed and the second type is Customer ''' subscriber = 0 customer = 0 for row in data_list: if row[-3].lower() == 'subscriber': subscriber += 1 elif row[-3].lower() == 'customer': customer += 1 return [subscriber, customer] user_types_list = column_to_list(data_list,-3) types = ['Subscriber', 'Customer'] quantity = count_user_type(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantity') plt.xlabel('User Type') plt.xticks(y_pos,types) plt.title('Quantity by User Type') plt.show(block=True) input("Press Enter to continue...") # TASK 8 # TODO: Answer the following question male, female = count_gender(data_list) print("\nTASK 8: Why the following condition is False?") print("male + female == len(data_list):", male + female == len(data_list)) answer = "Because not all users have specified their gender." print("Answer:", answer) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert answer != "Type your answer here.", "TASK 8: Write your own answer!" # ----------------------------------------------------- input("Press Enter to continue...") # Let's work with the trip_duration now. We cant get some values from it. # TASK 9 # TODO: Find the Minimum, Maximum, Mean and Median trip duration. # You should not use ready functions to do that, like max() or min(). trip_duration_list = column_to_list(data_list, 2) trip_duration_list = list(map(int, trip_duration_list)) def mean__trip(data): ''' Function to find the average trip duration. Arg: a : list which contains all trip duration returns returns the average of the trips in the argument A. ''' return sum(data)/len(data) def median__trip(data): ''' Function to find the median of trip duration Arg: a : list which contains all trip duration returns returns the median of the trips in the argument A ''' sorted(data) data_length = len(data) if data_length < 1: return None if data_length % 2 == 1: return sorted(data)[data_length // 2] else: return sum(sorted(data)[data_length // 2 - 1:data_length // 2 + 1]) / 2.0 min_trip = 600 max_trip = 0. mean_trip = mean__trip(trip_duration_list) median_trip = median__trip(trip_duration_list) for trip in trip_duration_list: if trip < min_trip: min_trip = trip if trip > max_trip: max_trip = trip print("\nTASK 9: Printing the min, max, mean and median") print("Min: ", min_trip, "Max: ", max_trip, "Mean: ", mean_trip, "Median: ", median_trip) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert round(min_trip) == 60, "TASK 9: min_trip with wrong result!" assert round(max_trip) == 86338, "TASK 9: max_trip with wrong result!" assert round(mean_trip) == 940, "TASK 9: mean_trip with wrong result!" assert round(median_trip) == 670, "TASK 9: median_trip with wrong result!" # ----------------------------------------------------- input("Press Enter to continue...") # TASK 10 # Gender is easy because usually only have a few options. How about start_stations? How many options does it have? # TODO: Check types how many start_stations do we have using set() user_types = set(column_to_list(data_list,3)) print("\nTASK 10: Printing start stations:") print(len(user_types)) print(user_types) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert len(user_types) == 582, "TASK 10: Wrong len of start stations." # ----------------------------------------------------- input("Press Enter to continue...") # TASK 11 # Go back and make sure you documented your functions. Explain the input, output and what it do. Example: # def new_function(param1: int, param2: str) -> list: """ Example function with annotations. Args: param1: The first parameter. param2: The second parameter. Returns: List of X values """ input("Press Enter to continue...") # TASK 12 - Challenge! (Optional) # TODO: Create a function to count user types without hardcoding the types # so we can use this function with a different kind of data. print("Will you face it?") answer = "yes" def count_items(column_list): ''' Function that counts how many valid and different items there are in a list :param column_list: :return: diferent item types, how many items there are in total ''' all_items = [] for column in column_list: if column != '': all_items.append(column) item_types = set(all_items) count_items = len(all_items) print('item_types', item_types) print('count', count_items) return item_types, count_items if answer == "yes": # ------------ DO NOT CHANGE ANY CODE HERE ------------ column_list = column_to_list(data_list, -2) types, counts = count_items(column_list) print("\nTASK 11: Printing results for count_items()") print("Types:", types, "Counts:", counts) print(types) assert len(types) == 3, "TASK 11: There are 3 types of gender!" assert sum(counts) == 1551505, "TASK 11: Returning wrong result!" # -----------------------------------------------------
995,540
466cf315c28ee71b1e3127eec4aa892e37065782
#!/usr/bin/python3 import argparse import toml import os import sys from getosmapsgpx import get_gpx curl_help_str="A good firefox curl command to get an OS maps GPX file\n\ Go to firefox, perform a legitimate GPX download with the network monitor open\n\ Then right click the event, copy curl, then paste into this file" parser = argparse.ArgumentParser(description="Look through TOML files of walks and cache all GPX", formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('out_dir', metavar='O', type=str, help='Director to put output in') parser.add_argument('curl_file', metavar='C', type=str, help=curl_help_str) parser.add_argument('files', metavar='F', type=str, nargs='+', help='TOML file(s) to process') args = parser.parse_args() for file in args.files: t = toml.load(file) if t["filetype"] == "walk": for walk in t["walks"]: if "osmapsroute" in walk: output_filename = args.out_dir+"/"+walk["name"]+".gpx" print(output_filename) if not (os.path.exists(output_filename)): gpx_str = get_gpx(args.curl_file, walk["osmapsroute"]) f = open(output_filename, "w") f.write(gpx_str)
995,541
d474678c63a51ce4794a5ab31794376ca546f42a
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jul 25 22:55:17 2021 @author: ayla """ import rospy from geometry_msgs.msg import Twist, Point from nav_msgs.msg import Odometry from tf.transformations import euler_from_quaternion from math import atan2 import numpy as np import random import operator koordinat = [] for i in range(0,5): x=int(random.random() * 5) y=int(random.random() * 5) koordinat.append((x,y)) print("Gidilecek koordinatlar:",koordinat) def baslangic_popülasyonu(boyut,koordinat_sayisi): popülasyon = [] for i in range(0,boyut): popülasyon.append(yeni_üye(koordinat_sayisi)) return popülasyon def pick_mate(N): i=random.randint(0,N) print(i) return i def distance(i,j): return np.sqrt((i[0]-j[0])**2 + (i[1]-j[1])**2) def popülasyon_skoru(popülasyon, koordinat_listesi): skorlar = [] for i in popülasyon: print(i) skorlar.append(uyumluluk(i, koordinat_listesi)) #print([uyumluluk(i, the_map)]) return skorlar def uyumluluk(rota,koordinat_listesi): skor=0 for i in range(1,len(rota)): k=int(rota[i-1]) l=int(rota[i]) skor = skor + distance(koordinat_listesi[k],koordinat_listesi[l]) return skor def yeni_üye(koordinat_sayisi): pop=set(np.arange(koordinat_sayisi,dtype=int)) rota=list(random.sample(pop,koordinat_sayisi)) return rota def crossover(a,b): cocuk=[] cocuk_A=[] cocuk_B=[] gen_A=int(random.random()* len(a)) gen_B=int(random.random()* len(a)) gen_baslangic=min(gen_A,gen_B) gen_son=max(gen_A,gen_B) for i in range(gen_baslangic,gen_son): cocuk_A.append(a[i]) cocuk_B=[item for item in a if item not in cocuk_A] cocuk=cocuk_A+cocuk_B return cocuk def mutasyon(rota,olasılık): rota=np.array(rota) for degisim_p in range(len(rota)): if(random.random() < olasılık): swapedWith = np.random.randint(0,len(rota)) temp1=rota[degisim_p] temp2=rota[swapedWith] rota[swapedWith]=temp1 rota[degisim_p]=temp2 return rota def secilim(popRanked, elitUye): secilimSonuc=[] sonuc=[] for i in popRanked: sonuc.append(i[0]) for i in range(0,elitUye): secilimSonuc.append(sonuc[i]) return secilimSonuc def oran(popülasyon,koordinat_listesi): uygunlukSonuc = {} for i in range(0,len(popülasyon)): uygunlukSonuc[i] = uyumluluk(popülasyon[i],koordinat_listesi) return sorted(uygunlukSonuc.items(), key = operator.itemgetter(1), reverse = False) def cins(havuz): cocuklar=[] for i in range(len(havuz)-1): cocuklar.append(crossover(havuz[i],havuz[i+1])) return cocuklar def mutasyonluPopülasyon(cocuklar,mutasyon_orani): yeni_jenerasyon=[] for i in cocuklar: mutasyonlu_cocuk=mutasyon(i,mutasyon_orani) yeni_jenerasyon.append(mutasyonlu_cocuk) return yeni_jenerasyon def çiftHavuz(popülasyon, secilimSonuc): çiftHavuz = [] for i in range(0, len(secilimSonuc)): index = secilimSonuc[i] çiftHavuz.append(popülasyon[index]) return çiftHavuz def yeni_jenerasyon(koordinat_listesi,akim_popülasyon,mutasyon_orani,elit_üye): popülasyon_orani=oran(akim_popülasyon,koordinat_listesi) secilim_sonuc=secilim(popülasyon_orani,elit_üye) havuz=çiftHavuz(akim_popülasyon,secilim_sonuc) cocuklar=cins(havuz) yeni_jenerasyon=mutasyonluPopülasyon(cocuklar,mutasyon_orani) return yeni_jenerasyon def genetik_algoritma(koordinat_listesi,popülasyon_boyut=1000,elit_uye=75,mutasyon_orani=0.01,jenerasyon=2000): pop=[] gelisim = [] koordinatSayisi=len(koordinat_listesi) popülasyon=baslangic_popülasyonu(popülasyon_boyut,koordinatSayisi) gelisim.append(oran(popülasyon,koordinat_listesi)[0][1]) print(f"ilk rota mesafesi{gelisim[0]}") print(f"ilk rota {popülasyon[0]}") for i in range(0,jenerasyon): pop = yeni_jenerasyon(koordinat_listesi, popülasyon, mutasyon_orani, elit_uye) gelisim.append(oran(pop,koordinat_listesi)[0][1]) rank_=oran(pop,koordinat_listesi)[0] print(f"En iyi rota :{pop[rank_[0]]} ") print(f"en iyi rota mesafesi {rank_[1]}") return rank_, pop rank_,pop=genetik_algoritma(koordinat_listesi=koordinat) #print(pop[rank_[0]]) array = [] array = pop[rank_[0]] #print(array[1]) #print(koordinat[array[0]][1]) #hedef.x = koordinat[array[0]][0] #hedef.y = koordinat[array[0]][1] """ class Tsp(): def __init__(self): rospy.init_node("TSP") pub = rospy.Publisher("/cmd_vel",Twist,queue_size=1) self.x = 0.0 self.y = 0.0 self.theta = 0.0 hedef = Point() hiz = Twist() rate = rospy.Rate(4) for i in range(len(koordinat)-1): hedef.y = koordinat[array[i]][0] hedef.x = koordinat[array[i]][1] print(hedef) while not (abs(hedef.x-x) < 0.01 and abs(hedef.y-y) < 0.01): rospy.Subscriber("/odom",Odometry,self.odomCallback) inc_x = hedef.x - self.x inc_y = hedef.y - self.y aci = atan2(inc_y,inc_x) if abs(aci - self.theta) > 0.1: hiz = Twist() hiz.linear.x = 0.0 hiz.angular.z = 0.3 pub.publish(hiz) else: hiz = Twist() hiz.linear.x = 0.1 hiz.angular.z = 0.0 pub.publish(hiz) rate.sleep() def odomCallback(self,mesaj): self.x = mesaj.pose.pose.position.x self.y = mesaj.pose.pose.position.y mesaj.pose.pose.position.z = 0 rot_q = mesaj.pose.pose.orientation (roll, pitch, self.theta) = euler_from_quaternion([rot_q.x, rot_q.y, rot_q.z, rot_q.w]) Tsp() """ rospy.init_node("TSP") pub = rospy.Publisher("cmd_vel",Twist,queue_size=1) hiz = Twist() hedef = Point() rate = rospy.Rate(4) def odomCallback(mesaj): global x global y global theta x = mesaj.pose.pose.position.x y = mesaj.pose.pose.position.y mesaj.pose.pose.position.z = 0 rot_q = mesaj.pose.pose.orientation (roll, pitch, theta) = euler_from_quaternion ([rot_q.x, rot_q.y, rot_q.z, rot_q.w]) x = 0.0 y = 0.0 theta = 0.0 for i in range(len(koordinat)-1): hedef = Point() hedef.x = koordinat[array[i]][0] hedef.y = koordinat[array[i]][1] print("Hedef konum:") print(hedef) while not (abs(hedef.x-x)<0.01 and abs(hedef.y-y)<0.01): rospy.Subscriber("/odom", Odometry, odomCallback) inc_x = hedef.x - x inc_y = hedef.y - y aci = atan2(inc_y, inc_x) if abs(aci - theta) > 0.1: hiz = Twist() hiz.linear.x = 0.0 hiz.angular.z = 0.3 pub.publish(hiz) else: hiz = Twist() hiz.linear.x = 0.1 hiz.angular.z = 0.0 pub.publish(hiz) rate.sleep() print("Hedefe ulaşıldı !!!") hedef.x = 0.0 hedef.y = 0.0 while not rospy.is_shutdown(): rospy.Subscriber("/odom", Odometry, odomCallback) inc_x = hedef.x - x inc_y = hedef.y - y aci = atan2(inc_y, inc_x) if abs(aci - theta) > 0.1: hiz = Twist() hiz.linear.x = 0.0 hiz.angular.z = 0.3 pub.publish(hiz) else: hiz = Twist() hiz.linear.x = 0.1 hiz.angular.z = 0.0 pub.publish(hiz) rate.sleep() print("Başlangıç noktasına dönüldü.")
995,542
fb4f92e9d94c51e9bdde05a4a0f76eb82819e39d
from socket import MsgFlag import pytest import numpy as np import CompOSE_to_SC.conversion as conversion import CompOSE_to_SC.download as dl import h5py import os import shutil h5_files = [] def look_for_test_file(): '''Looks for test files in the TestFiles directory. If no files are found, LS220 is downloaded from stellarcollapse.org, decompressed and moved into the TestFiles directory. Args: None Returns: None ''' for root, dir, files in os.walk('../PracticeFiles'): [h5_files.append(file) for file in files if file[-3:]=='.h5'] print(h5_files) try: assert len(h5_files)>0, 'No EOS h5 files found in TestFiles directory' except AssertionError as msg: print(msg) dl('https://stellarcollapse.org/EOS/LS220_234r_136t_50y_analmu_20091212_SVNr26.h5.bz2') [h5_files.append(files[0]) for root, dir, files in os.walk('.') if files[0][-3:]=='.h5'] shutil.move('./LS220_234r_136t_50y_analmu_20091212_SVNr26.h5', '../PracticeFiles/LS220_234r_136t_50y_analmu_20091212_SVNr26.h5') print(h5_files) def test_conv_h5(): ''' Makes sure the input file exists Makes sure the input and output files are in h5 format Makes sure the new file contains the right StellarCollapse list of keys Tests the conv_h5 function using the first h5 file in the TestFiles directoy Args: None Returns: None ''' filename='../PracticeFiles/' + h5_files[0] new_file=filename[:-3]+'_converted.h5' try: assert os.path.exists(filename), 'path for input file does not exist' assert filename[-3:]=='.h5', 'original file is not in h5 format' assert new_file[-3:]=='.h5', 'new file name chosen must have .h5 extension' print('files are h5 format') except AssertionError as msg: if str(msg) == 'original file is not in h5 format': try: assert 'tar' not in filename and 'zip' not in filename, 'original file is in a compressed format' except AssertionError as msg: print(msg) else: conversion.conv_h5(filename, new_file) try: assert os.path.exists(new_file), 'conv_h5 did not create a new file' except AssertionError as msg: print(msg) else: with h5py.File(new_file, 'r') as f: try: assert list(f.keys()) == ['Abar', 'Xa', 'Xh', 'Xn', 'Xp', 'Zbar', 'cs2', 'dedt', 'dpderho', 'dpdrhoe', 'energy_shift', 'entropy', 'gamma', 'logenergy', 'logpress', 'logrho', 'logtemp', 'mu_e', 'mu_n', 'mu_p', 'muhat', 'munu', 'pointsrho', 'pointstemp', 'pointsye', 'ye'], 'new file does not contain all necessary Stellar Collapse keys, or they are not in the right order' except AssertionError as msg: print(msg) else: print('Everything seems to be working!') os.remove(new_file) if __name__ == '__main__': look_for_test_file() test_conv_h5()
995,543
b99a19d0e43f3d95c92fe7cce5d8977b6c2c5be4
# -*- coding: utf-8 -*- __all__ = ["Base_cir", "Orig_cir", "Elev_cir", "Slope_cir", "Tpi_cir"] from .base_cir import Base_cir from .orig_cir import Orig_cir from .elev_cir import Elev_cir from .slope_cir import Slope_cir from .tpi_cir import Tpi_cir
995,544
18ed417c08c6dd597aa1be60bc95824fa44faf49
import FWCore.ParameterSet.Config as cms rootTupleTracks = cms.EDProducer("BristolNTuple_Tracks", Prefix = cms.string('Track.'), Suffix = cms.string(''), )
995,545
66027a655aab49f67ee891f399687e770757ae6b
import itertools from multiprocessing import Pool def genc(ab, p): a, b = ab c = p-a-b if c < 0: return None elif a**2 + b**2 == c**2: return (a, b, c) def lengths(p): ab = itertools.combinations(range(1, p+1), 2) coords = map(lambda x: genc(x, p), ab) coords = [x for x in coords if x is not None] return coords if __name__ == '__main__': p = Pool() solns = p.map(lengths, range(1, 1001)) r = map(len, solns) r = list(r) print(r.index(max(r))+1)
995,546
56924c634d810eba166c4290d335569c074e34a8
import turtle def main(): #put label on top of page turtle.title("Hello World") #set up screen size turtle.setup(500, 500, 0, 0) #move turtle to origin turtle.penup() turtle.goto(0,0) # set the color to navy turtle turtle.color("navy") # write the message turtle.write("Hello World", font = ("Times New Roman", 36, "bold")) # persist the drawing turtle.done() main()
995,547
978327732d78f6f9e8eabd507e35021ac44995de
from django.db import models class AudioBook(models.Model): file_field = models.FileField(upload_to='documents/')
995,548
614cd5d5a27acd607b46c4517c2b678e5a201979
import sys import math T = int(sys.stdin.readline().rstrip()) for i in range(T): x, y = map(int, sys.stdin.readline().rstrip().split()) dist = y - x p = int(math.sqrt(dist)) remain = math.ceil((dist - (p * p)) / p) print(p * 2 - 1 + remain)
995,549
119c51a43dc12b746b1e77b6a5038765f3377e03
from notification.webhook import Discord
995,550
ec902e2fcc06489abaa56839de28d22e55dd13b3
#FTP Client Side Code import socket s = socket.socket() #declare socket variable port = 8888 s.connect(('192.168.56.101', port)) #established connection to the server print("connected to server:") filename = input(str("Rename file as : ")) #enter what name file you want to save, you can rename it file = open(filename, 'wb') file_data = s.recv(1024) #will receive file file.write(file_data) #will write it on client storage file.close() #close file function print("File has been received successfully.") s.close() #close socket print('Server-Client Connection End')
995,551
218700713b29ab3e1cf0c211ebcb9eec19902634
from datetime import datetime, timedelta from jose import JWTError, jwt from schema import TokenData # for production is value has to be newly generated with: # opensl rand -hex 32 SECRET_KEY = "09d25e094faa6ca2556c818166b7a9569b93f7099f6f0f4caa6cf63b88e8d3e7" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 120 def create_token(data: dict): to_encode = data.copy() expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt def verify_token(token: str, credentials_exception): try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) except JWTError: raise credentials_exception return token_data
995,552
0cb71baceb4ef32b2e1ff80843c4ab42b6cade55
""" This file contains Belief classes, which store and update the belief distributions about the user whose reward function is being learned. :TODO: GaussianBelief class will be implemented so that the library will include the following work: E. Biyik, N. Huynh, M. J. Kochenderger, D. Sadigh; "Active Preference-Based Gaussian Process Regression for Reward Learning", RSS'20. """ from typing import Callable, Dict, List, Tuple, Union import numpy as np from aprel.learning import User, QueryWithResponse from aprel.utils import gaussian_proposal, uniform_logprior class Belief: """An abstract class for Belief distributions.""" def __init__(self): pass def update(self, data: Union[QueryWithResponse, List[QueryWithResponse]], **kwargs): """Updates the belief distribution with a given feedback or a list of feedbacks.""" raise NotImplementedError class LinearRewardBelief(Belief): """An abstract class for Belief distributions for the problems where reward function is assumed to be a linear function of the features.""" def __init__(self): pass @property def mean(self) -> Dict: """Returns the mean parameters with respect to the belief distribution.""" raise NotImplementedError class SamplingBasedBelief(LinearRewardBelief): """ A class for sampling based belief distributions. In this model, the entire dataset of user feedback is stored and used for calculating the true posterior value for any given set of parameters. A set of parameter samples are then sampled from this true posterior using Metropolis-Hastings algorithm. Parameters: logprior (Callable): The logarithm of the prior distribution over the user parameters. user_model (User): The user response model that will be assumed by this belief distribution. dataset (List[QueryWithResponse]): A list of user feeedbacks. initial_point (Dict): An initial set of user parameters for Metropolis-Hastings to start. logprior (Callable): The logarithm of the prior distribution over the user parameters. Defaults to a uniform distribution over the hyperball. num_samples (int): The number of parameter samples that will be sampled using Metropolis-Hastings. **kwargs: Hyperparameters for Metropolis-Hastings, which include: - `burnin` (int): The number of initial samples that will be discarded to remove the correlation with the initial parameter set. - `thin` (int): Once in every `thin` sample will be kept to reduce the autocorrelation between the samples. - `proposal_distribution` (Callable): The proposal distribution for the steps in Metropolis-Hastings. Attributes: user_model (User): The user response model that is assumed by the belief distribution. dataset (List[QueryWithResponse]): A list of user feeedbacks. num_samples (int): The number of parameter samples that will be sampled using Metropolis-Hastings. sampling_params (Dict): Hyperparameters for Metropolis-Hastings, which include: - `burnin` (int): The number of initial samples that will be discarded to remove the correlation with the initial parameter set. - `thin` (int): Once in every `thin` sample will be kept to reduce the autocorrelation between the samples. - `proposal_distribution` (Callable): The proposal distribution for the steps in Metropolis-Hastings. """ def __init__(self, user_model: User, dataset: List[QueryWithResponse], initial_point: Dict, logprior: Callable = uniform_logprior, num_samples: int = 100, **kwargs): super(SamplingBasedBelief, self).__init__() self.logprior = logprior self.user_model = user_model self.dataset = [] self.num_samples = num_samples kwargs.setdefault('burnin', 200) kwargs.setdefault('thin', 20) kwargs.setdefault('proposal_distribution', gaussian_proposal) self.sampling_params = kwargs self.update(dataset, initial_point) def update(self, data: Union[QueryWithResponse, List[QueryWithResponse]], initial_point: Dict = None): """ Updates the belief distribution based on the new feedback (query-response pairs), by adding these to the current dataset and then re-sampling with Metropolis-Hastings. Args: data (QueryWithResponse or List[QueryWithResponse]): one or more QueryWithResponse, which contains multiple trajectory options and the index of the one the user selected as most optimal initial_point (Dict): the initial point to start Metropolis-Hastings from, will be set to the mean from the previous distribution if None """ if isinstance(data, list): self.dataset.extend(data) else: self.dataset.append(data) if initial_point is None: initial_point = self.mean self.create_samples(initial_point) def create_samples(self, initial_point: Dict) -> Tuple[List[Dict], List[float]]: """Samples num_samples many user parameters from the posterior using Metropolis-Hastings. Args: initial_point (Dict): initial point to start the chain for Metropolis-Hastings. Returns: 2-tuple: - List[Dict]: dictionaries where each dictionary is a sample of user parameters. - List[float]: float values where each entry is the log-probability of the corresponding sample. """ burnin = self.sampling_params['burnin'] thin = self.sampling_params['thin'] proposal_distribution = self.sampling_params['proposal_distribution'] samples = [] logprobs = [] curr_point = initial_point.copy() sampling_user = self.user_model.copy() sampling_user.params = curr_point curr_logprob = self.logprior(curr_point) + sampling_user.loglikelihood_dataset(self.dataset) samples.append(curr_point) logprobs.append(curr_logprob) for _ in range(burnin + thin * self.num_samples - 1): next_point = proposal_distribution(curr_point) sampling_user.params = next_point next_logprob = self.logprior(next_point) + sampling_user.loglikelihood_dataset(self.dataset) if np.log(np.random.rand()) < next_logprob - curr_logprob: curr_point = next_point.copy() curr_logprob = next_logprob samples.append(curr_point) logprobs.append(curr_logprob) self.samples, self.logprobs = samples[burnin::thin], logprobs[burnin::thin] @property def mean(self) -> Dict: """Returns the mean of the belief distribution by taking the mean over the samples generated by Metropolis-Hastings.""" mean_params = {} for key in self.samples[0].keys(): mean_params[key] = np.mean([self.samples[i][key] for i in range(self.num_samples)], axis=0) if key == 'weights': mean_params[key] /= np.linalg.norm(mean_params[key]) return mean_params
995,553
607b7628467d5a2ff88103f315478393653fa5c5
# -*- coding: utf-8 -*- """ Das Modul pickle ist genau dafuer gedacht persistente Speicherung von Objekten & Lesen von Objekten Serialisierung & Deserialisierung Folgende Typen gehen: None, False, True numerische Typen(int, float, complex, bool) str, bytes sequentielle Typen (tuple, list) Mengen(set, frozenset) Dictionarys(solange die Daten darin serialisiert werden koennen) Hierbei wird alles mit Klassennamen gespeichert Der Code einer Funktion, die Definition und die Attribute einer Klasse aber nicht globale Funktionen Built-In Funktionen globale Klassen Klasseninstanzen, deren Attribute serialisiert werden koennen """ # pickle hat 3 verschiedene Formate zur Speicherung von Daten # 0 -> String besteht nur aus ASCII (a-kompatibel) # 1 -> Binaerstring, platzsparender als 0 (a-kompatibel) # 2 -> neues Binaerformat -> Klasseninstanz-optimiert # (ab Python 2.3 lesbar/nutzbar) # 3 -> neu seit Python3 -> erst ab 3.0 nutzbar # unterstuetzt den neuen bytes-Typ # Ist Standard und wird von pickle verwendet import pickle """ # pickle.dump(obj, file[, protocol]) # Speichert obj in das Dateiobjekt file (muss zum schreiben offen sein) # protocol kann angegeben werden (siehe oben) -> 3 ist standard # write binary f = open("pickle-test.dat", "bw") pickle.dump([1,2,3], f) # file kann jedes Dateiobjekt sein, dass write-Methode implementiert # z.B. StringIO-Instanzen # pickle.load(file) # Laedt die Datei ein und erkennt automatisch das Protocol # read binary f = open("pickle-test.dat", "rb") res = pickle.load(f) print(res) """ # pickle.dumps(obj[, protocol]) # serialisiert aus obj ein bytes-String #pickle.dumps([1,2,3]) #print(pickle.dumps([1,2,3])) #pickle.loads(string) # deserialisiert aus bytes-String #s = pickle.dumps([1,2,3,4,5]) #ds = pickle.loads(s) #print(ds)
995,554
47c2c7d568dd75b56d16e6892eacc6170b225b7d
def sayHi(): print('Hi, this is my module speaking. ') __version__ = "0.1" #end of module, will be used in mymodule_demo.py
995,555
d72eeb084e580d54f3830ddfb88bc90c7d5f7f83
# -*- coding: utf-8 -*- # @Time : 2018/01/11 1:33 # @Author : Yu Bowen # @Site : www.ybwsfl.xin # @File : OpenCV转换成PIL.Image格式.py # @Software: PyCharm # @Desc : # @license : Copyright(C), NJUST # @Contact : yubowen_njust@163.com # @Modified : import cv2 from PIL import Image import numpy img = cv2.imread("C:/Users/yubow/Documents/GitHub/tensorflow_from_my_notebook/10.network/2.AlexNET/images/llama.jpeg") # cv2.imshow("OpenCV", img) image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) image.show() cv2.waitKey()
995,556
9ce16fa272d7d99a749375f82a9ed49299c6dbde
from gPhoton.gMap import gMap def main(): gMap(band="NUV", skypos=[219.137042,1.636906], skyrange=[0.0333333333333,0.0333333333333], stepsz = 30., cntfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdBs/sdB_LBQS_1434+0151/sdB_LBQS_1434+0151_movie_count.fits", cntcoaddfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdB/sdB_LBQS_1434+0151/sdB_LBQS_1434+0151_count_coadd.fits", overwrite=True, verbose=3) if __name__ == "__main__": main()
995,557
661a44f6e222121715858c79cd75849f6c5bd5ef
#!/usr/bin/env python import numpy as np import sys import os from globalfile import readglobal from parallelfuncs import hist import argparse import matplotlib.pyplot as plt parser = argparse.ArgumentParser(description='Transform numpy vectors to txt') parser.add_argument("file", type = str, nargs='+', help = "filestotransform") args = parser.parse_args() filename = args.file for files in filename: vec = np.load(files) np.savetxt(files+".txt",vec)
995,558
79c6783e33dadd8620b0f41552ff6c4406993c9b
from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, redirect, get_object_or_404 from cart.models import Cart, CartItem from shop.models import Product import stripe from django.conf import settings from order.models import Order, OrderItem from django.template.loader import get_template, render_to_string from django.core.mail import EmailMessage from ecommerce.common.mail.sendMail import send_email # Create your views here. """ Create Cart details from the session of the request """ """ Cart_id acn also be reference as bill no or order no """ def _cart_id(request): """ get session key from the request so as to determine which user create the order """ cart = request.session.session_key if not cart: cart = request.session.create() return cart """ Add item to the cart table by product """ def add_cart(request, product_id): # product = Product.objects.get(pk=product_id) """ get product details """ product = Product.objects.get(id=product_id) """ get cart details """ try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id=_cart_id(request) ) cart.save() """ create cart list of the goods to keep track on and generate billing system Add item to the cart product wise """ try: """ product already exist increase its quantity """ cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() # cart_item.quantity += 1 # cart_item.save() except CartItem.DoesNotExist: """ product doesnot exist so create it with quantity 1 """ cart_item = CartItem.objects.create( product=product, cart=cart, quantity=1, ) cart_item.save() return redirect('cart:cart_detail') """ Get Cart Details """ def cart_detail(request, total=0, counter=0, cartItems=None): try: """ get Cart / bill no """ cart = Cart.objects.get(cart_id=_cart_id(request)) """ get items with refrence to cart_id or bill no where status is active """ cart_items = CartItem.objects.filter(cart=cart, active=True) """ calculate total amount and total no. of items """ for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) counter += cart_item.quantity except ObjectDoesNotExist: pass """ integration of stripe payment gateway integration """ stripe.api_key = settings.STRIPE_SECRET_KEY data_key = settings.STRIPE_PUBLISHABLE_KEY stripe_total = int(total) description = 'perfect cusion stipe interation test : new order' # either use step 1 or step 2, It wont matter # step 1 # return render(request, 'cart.html', { cart_item : cart_items, total : total, counter : counter }) # step 2 if request.method == 'POST': try: token = request.POST['stripeToken'] email = request.POST['stripeEmail'] billingName = request.POST['stripeBillingName'] billingAddress1 = request.POST['stripeBillingAddressLine1'] billingCity = request.POST['stripeBillingAddressCity'] billingPostCode = request.POST['stripeBillingAddressZip'] billingCountry = request.POST['stripeBillingAddressCountry'] shippingName = request.POST['stripeShippingName'] shippingAddress1 = request.POST['stripeShippingAddressLine1'] shippingCity = request.POST['stripeShippingAddressCity'] shippingPostCode = request.POST['stripeShippingAddressZip'] shippingCountry = request.POST['stripeShippingAddressCountry'] customer = stripe.Customer.create(email=email, source=token) charge = stripe.Charge.create(amount=stripe_total, currency='inr', description=description, customer=customer.id) ''' create order here ''' try: order_details = Order.objects.create( token=token, total=total, emailAddress=email, billingAddress1=billingAddress1, billingCity=billingCity, billingPostCode=billingPostCode, billingCountry=billingCountry, billingName=billingName, shippingName=shippingName, shippingAddress1=shippingAddress1, shippingCity=shippingCity, shippingPostCode=shippingPostCode, shippingCountry=shippingCountry ) order_details.save() for order_item in cart_items: oi = OrderItem.objects.create( product=order_item.product.name, quantity=order_item.quantity, price=order_item.product.price, order=order_details ) oi.save() """ reduce order stock when item placed and remove orer from shopping cart""" product = Product.objects.get(id=order_item.product.id) product.stock = int( order_item.product.stock - order_item.quantity) product.save() """ delete items from order cart """ order_item.delete() """ Terminal will print when order is placed """ print('Order has been successfully placed.') try: """ send Email fnction """ print('-----------call sendEmail------------') sendEmail(order_details.id) except IOError as e: return e # return redirect('shop:allProdCat') return redirect('order:thanks', order_details.id ) except ObjectDoesNotExist: pass except stripe.error.CardError as e: return False, e # print(request.POST) # <QueryDict: {'csrfmiddlewaretoken': ['j3k5pviaMgQGB32O7QLZmuik8yq4juMY4zTVejR8cuanPjmQXdy4pKHBwM3s7DNx'], 'stripeToken': ['tok_1HS5KPEcB39RSPvROkNWv5oj'], 'stripeTokenType': ['card'], 'stripeEmail': ['akashbindal91@gmail.com'], 'stripeBillingName': ['Akash'], 'stripeBillingAddressCountry': ['India'], 'stripeBillingAddressCountryCode': ['IN'], 'stripeBillingAddressZip': ['458470'], 'stripeBillingAddressLine1': ['D 1/2, vikram cement staff colony, nimach, madhya pradesh'], 'stripeBillingAddressCity': ['nimach'], 'stripeBillingAddressState': ['35'], 'stripeShippingName': ['Akash'], 'stripeShippingAddressCountry': ['India'], 'stripeShippingAddressCountryCode': ['IN'], 'stripeShippingAddressZip': ['458470'], 'stripeShippingAddressLine1': ['D 1/2, vikram cement staff colony, nimach, madhya pradesh'], 'stripeShippingAddressCity': ['nimach'], 'stripeShippingAddressState': ['35']}> return render(request, 'cart/cart.html', dict(cart_items=cart_items, total=total, counter=counter, data_key=data_key, description=description, stripe_total=stripe_total)) def cart_remove(request, product_id): cart = Cart.objects.get(cart_id=_cart_id(request)) product = get_object_or_404(Product, id=product_id) cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity > 1: cart_item.quantity -= 1 cart_item.save() else: cart_item.delete() return redirect('cart:cart_detail') def full_remove(request, product_id): cart = Cart.objects.get(cart_id=_cart_id(request)) product = get_object_or_404(Product, id=product_id) cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.delete() return redirect('cart:cart_detail') def sendEmail(order_id): tranaction = Order.objects.get(id=order_id) order_items = OrderItem.objects.filter(order=tranaction) """ sending order to the customer """ subject = "New Order No #{}".format(tranaction.id) to = ['{}'.format(tranaction.emailAddress)] from_email = settings.EMAIL_FROM order_conformation = { 'tranaction' : tranaction, 'order_items' : order_items } message = get_template('email/email.html').render(order_conformation) html_message = None try: sendMailStatus = send_email( subject=subject, to=to, from_email=from_email, message=message, html_message=html_message) except sendMailStatus.DoesNotExist: return False return True
995,559
e931ad586028b0ed3b0d49fdc13f7a1e1e453b19
class Customer: def __init__(self, name: str, cpf: str): self.__name = name self.__cpf = cpf @property def name(self): return self.__name @property def cpf(self): return self.__cpf
995,560
b3e16a1cd2f1bc4c1120650d8b87182874da0944
from sqlalchemy import Column, String from sqlalchemy.orm import relationship from gtfsjpdb.models.base import Base class Office(Base): filename = "office_jp.txt" __tablename__ = "office" id = Column(String(255), primary_key=True, nullable=False) name = Column(String(255), nullable=False) url = Column(String(255)) phone = Column(String(15)) trip = relationship("Trip", back_populates="offices")
995,561
33d69c9f60b026c3e2830914e38ebb1455a8488d
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 15 18:58:14 2020 @author: olamijojo """ from graphics import * #def createWindow(): # Creates a 500x500 window titled "Linear Regression" and draws # a "Done Button" in the lower left corner. The window coords # run from 0,0 to 10,10, and the upper right corner of the button # is located at (DoneX, DoneY). # Returns the window. # Use Rectangle object to draw the thumbnails def Thumbnails(): win = GraphWin("GameLet", 1300, 840) #doneButton = Rectangle(Point(.05,0), Point(1, 0.75)) #doneButton.draw(win) message = Text(Point(650, 20),"Prototype for Gamelet") message.draw(win) #Text(doneButton.getCenter(), "Done").draw(win) #win = GraphWin("GameLet", 1300, 840) thumbnails = Rectangle(Point(40,80), Point(185,250)) thumbnails.draw(win) thumbnails.setOutline("blue") Text(thumbnails.getCenter(), "QUIZ 1").draw(win) #cam_image = Image(Point(112.5,165), "cam1.gif") #cam_image.draw(win) #red, green, blue = cam_image.getPixel(445,555) #cam_image.setPixel(445,555, "pink") #cam_image.setPixel(0,0, "blue") #win.setBackground("pink") sec_thumbnail = thumbnails.clone() #an exact clon of 1st thumbnail sec_thumbnail.move(165,0) sec_thumbnail.draw(win) Text(sec_thumbnail.getCenter(), "QUIZ 2").draw(win) second_thumbnail = thumbnails.clone() #an exact clon of 1st thumbnail second_thumbnail.move(330,0) second_thumbnail.draw(win) Text(second_thumbnail.getCenter(), "QUIZ 3").draw(win) third_thumbnail = thumbnails.clone() #an exact clon of 1st thumbnail third_thumbnail.move(495,0) third_thumbnail.draw(win) Text(third_thumbnail.getCenter(), "QUIZ 4").draw(win) fourth_thumbnail = thumbnails.clone() #an exact clon of 1st thumbnail fourth_thumbnail.move(660,0) fourth_thumbnail.draw(win) Text(fourth_thumbnail.getCenter(), "QUIZ 5").draw(win) fifth_thumbnail = thumbnails.clone() #an exact clon of 1st thumbnail fifth_thumbnail.move(825,0) fifth_thumbnail.draw(win) Text(fifth_thumbnail.getCenter(), "QUIZ 6").draw(win) sixth_thumbnail = thumbnails.clone() #an exact clon of 1st thumbnail sixth_thumbnail.move(990,0) sixth_thumbnail.draw(win) Text(sixth_thumbnail.getCenter(), "QUIZ 7").draw(win) return win def getPoint(w): # w is a GraphWin # Pauses for user to click in w. If user clicks somewhere other than # the Done button, the point is drawn in w. # Returns the point clicked, or None if user clicked the Done button p = win.getMouse() if p.getX() < 165 or p.getY() <= 125: p.draw(win) return quiz1() else: return None def quiz1(): win = GraphWin("GameLet", 1300, 840) message1 = Text(Point(165, 50),"What is the capital of California?") message1.draw(win) #OptionsA, B, C ButtonA = Rectangle(Point(85,80), Point(165, 95)) ButtonA.draw(win) Text(ButtonA.getCenter(), "San Francisco").draw(win) ButtonB = ButtonA.clone() ButtonB.move(85,0) ButtonB.draw(win) Text(ButtonB.getCenter(), "Los Angeles").draw(win) ButtonC = ButtonB.clone() ButtonC.move(85, 0) ButtonC.draw(win) Text(ButtonC.getCenter(), "San Mateo").draw(win) def correct(): p = win.getMouse() if p.getX() <= 165 or p.getY() <= 95: #p.draw(win) message.setText("Click anywhere to quit.") return quiz1() else: return None ans = input("What is the capital of Carlifornia?: ") if ans != "San Francisco": print("wrong Answer") else: print("Correct") def insert_img(): pass def main(): # createWindow() Thumbnails() quiz1() main()
995,562
bc779ab073060a898135543e12214d2ec6f623a7
# coding=UTF-8 # 分析继承关系 import re import iwc_heder_db import os # class-dump 导出头文件所在的目录 IPA_HEADER_PATH = '/Users/wangsuyan/Desktop/baidu/reverse/header/wechat' def iwc_parse_header(): dirs = os.listdir(IPA_HEADER_PATH) for file_name in dirs: header_path = IPA_HEADER_PATH + '/' + file_name # 解析 header file header_file = open(header_path) for index, line in enumerate(header_file): # @interface MMUIWindow : UIWindow <IVOIPWindowExt> 解析类,父类,协议 regex = r"^@interface\s+(.{0,})\s+:\s+(.{0,})\s+<*(.{0,})>*" res = re.match(regex, line) if res == None: continue groups = res.groups() if groups == None: continue count = len(groups) if count == 1: name = groups[0] if count == 2: name = groups[0] super_name = groups[1] if count == 3: name = groups[0] super_name = groups[1] protocol = groups[2] if count == 3: iwc_heder_db.iwx_insert(name, super_name, protocol) print file_name break # 脚本入口 if __name__ == '__main__': iwc_parse_header()
995,563
e72eea4b90fca7e8d706174ef7ee5af5964beefe
a = int(input("ingresa un numero ")) b = int(input("ingresa otro numero ")) if a%2 == 0 and b%2 == 0: print("los 2 numeros son pares") elif a%2 == 0 and b%2!=0: print("el numero "+str(a) + " es par y el numero "+str(b)+" no es par") elif a%2!= 0 and b%2 == 0: print("el numero "+str(b) + " es par y el numero "+str(a)+" no es par") else: print("los numeros no son pares")
995,564
9ceaafda4708a8c062c952eb4f8058f5db17437f
from django.contrib import admin from formularioPersona.models import Persona class PersonaAdmin (admin.ModelAdmin): list_filter=("genero","experiencia","cargo") list_display=("nombre","email","tamano_empresa","pais","edad","estudios","genero","ingles_hablado","ingles_escrito","actividad","contrato","cargo","experiencia","rentaLiquida","rentaBono","duracionTrabajo","BeneficiosEmpleador","FactoresCambioEmpleo") search_fields=("nombre","email") admin.site.register(Persona,PersonaAdmin)
995,565
b97180d1c2ae030fbeceeda7a282a1fde24246d1
""" Binomial Coeffiecient nCk using DP. DP - Pascals' Triangle Using 2D Array to built up to n rows of the triangle """ def nCk(n, k): C=[[0]*(k+1) for i in range(n+1)] for i in range(n+1): for j in range(min(i+1,k+1)): if j == 0 or j == i: C[i][j]=1 else: C[i][j]=C[i-1][j-1]+C[i-1][j] print("Pascal's Triangle") for i in C: print(i) return C[n][k] if __name__ == "__main__": n,k=map(int,input().split(' ')) print(nCk(n,k))
995,566
368b005c943703aead9b3439b2bd38ac9a0f0691
import details name='mukesh' print details.name print name
995,567
948d445195088d0830d98421f2c06ede806b01ac
import pandas as pd def display_scraped_data(ids, names, p_links, c_links, cl_links): """ Helper function to display the list of data scraped from the FIFA website :param ids: IDs of players from all scraped pages :param names: Names of players from all scraped pages :param p_links: Links of players images from all scraped pages :param c_links: Links of players country flags from all scraped pages :param cl_links: Links of players club logos from all scraped pages :return: None """ # for (p_id, p_name, p_link, ctry_link, clb_link) in zip(ids, names, p_links, # c_links, cl_links): # print(p_id, p_name, p_link, ctry_link, clb_link, sep=" ") print("Finally we have {} IDs, {} player name, {} links of player-images, {} links of countries and {} " "links of clubs".format(len(ids), len(names), len(p_links), len(c_links), len(cl_links))) def create_dataframe(ids, names, p_links, c_links, cl_links): """ Creates a Pandas dataframe from the scraped data :param ids: IDs of players from all scraped pages :param names: Names of players from all scraped pages :param p_links: Links of players images from all scraped pages :param c_links: Links of players country flags from all scraped pages :param cl_links: Links of players club logos from all scraped pages :return: None """ try: dict = {'ID':ids, 'Name': names, 'Photo':p_links, 'Flag':c_links, 'Club Logo':cl_links} df = pd.DataFrame(dict) return df except Exception as e: print("Exception creating or storing the dataframe: " + str(e))
995,568
39a462d9e783a94efdefba4dc763f6566e9db13e
# Copyright (c) 2019 Riverbed Technology, Inc. # # This software is licensed under the terms and conditions of the MIT License # accompanying the software ("License"). This software is distributed "AS IS" # as set forth in the License. import os import unittest import shutil import logging from reschema.util import str_to_id as html_str_to_id logger = logging.getLogger(__name__) TEST_PATH = os.path.abspath(os.path.dirname(__file__)) SERVICE_DEF_TEST = os.path.join(TEST_PATH, 'service_test.yaml') SERVICE_DEF_TEST_REF = os.path.join(TEST_PATH, 'service_test_ref.yaml') SERVICE_DEF_BOOKSTORE = os.path.join(TEST_PATH, '../examples/bookstore.yaml') SERVICE_DEF_INVALID_REF = os.path.join(TEST_PATH, 'service_test_invalid_ref.yaml') outdir = 'test_reschema_doc_output' if os.path.exists(outdir): shutil.rmtree(outdir) os.makedirs(outdir) import reschema from reschema import ServiceDef from reschema.tohtml import ResourceToHtml, RefSchemaProxy from reschema.doc import ReschemaDoc def process_file(filename, *args): r = ReschemaDoc() rargs = ['-f', filename, '--outdir', outdir, '--html'] for arg in args: rargs.extend(['-r', arg]) r.parse_args(rargs) r.run() return class TestReschema(unittest.TestCase): def test_service(self): process_file(SERVICE_DEF_TEST) def test_service_ref(self): process_file(SERVICE_DEF_TEST_REF, SERVICE_DEF_TEST) def test_service_bookstore(self): process_file(SERVICE_DEF_BOOKSTORE) class TestReschemaInvalidRef(unittest.TestCase): def setUp(self): self.sd = ServiceDef() self.sd.load(SERVICE_DEF_INVALID_REF) def test_invalid_ref_in_property(self): """ testing when one property's ref consists of undefined types, an invalid reference exception should be raised, such as below: properties: property: { $ref: '#/types/blah' } """ with self.assertRaises(reschema.exceptions.InvalidReference): schema = list(self.sd.resources.values())[0].properties['name'] RefSchemaProxy(schema, None) def test_invalid_ref_in_links(self): """ testing when one property's ref consists of undefined resources, an invalid reference exception should be raised. such as below: properties: links: self: { path: '$/test_invalid_ref_in_lnks'} params: id: $ref: '#/types/does_not_exist' """ with self.assertRaises(reschema.exceptions.InvalidReference): resource = list(self.sd.resources.values())[0] title = "%s v%s %s" % (self.sd.title, self.sd.version, self.sd.status) htmldoc = reschema.html.Document(title, printable=False) r2h = ResourceToHtml(resource, htmldoc.content, htmldoc.menu.add_submenu(), "http://{device}/{root}", None) baseid = html_str_to_id(r2h.schema.fullid(True)) div = r2h.container.div(id=baseid) r2h.menu.add_item(r2h.schema.name, href=div) r2h.process_links(div, baseid) if __name__ == '__main__': logging.basicConfig(filename='test.log', level=logging.DEBUG) unittest.main()
995,569
e82682efec459bfa30bcf025b854068202e197cd
from django import forms from .models import unidad,leccion class Unidad(ModelForm): class Meta: model = unidad
995,570
acb7d5dec2ea2a6f215e37099126d7a533404a10
import os import time import dill as pickle import browser_cookie3 from requests_html import HTMLSession import smtplib def save_cookies(output_path): cookies = browser_cookie3.chrome(domain_name=".amazon.com") with open(output_path, "wb") as f: pickle.dump(cookies, f) def check_availability(url, cookies_path): with open(cookies_path, "rb") as f: cookies = pickle.load(f) session = HTMLSession() while True: r = session.get(url, verify=False, cookies=cookies) if "Delivery available" in r.html.html: print("Delivery available!!!") sender_email = "pikadue@gmail.com" receiver_email = "diihuu@umich.edu" password = input("Type your password and press enter: ") message = "Whole Foods delivery is available!" server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message) break else: print("Not available, sleeping for an hour...") time.sleep(3600) if __name__ == "__main__": cookies_path = "cookies_amazon.pkl" # only need to run once, to extract amazon's cookies from your local Chrome and pickle it if not os.path.exists(cookies_path): save_cookies(cookies_path) # it can be run in any server without Chrome check_availability( url='https://www.amazon.com/alm/storefront?almBrandId=VUZHIFdob2xlIEZvb2Rz&ref_=nav_cs_whole_foods_in_region', cookies_path=cookies_path, )
995,571
437a055172a8cc174224553737a2af913c2efc9c
# -*- coding: utf-8 -*- from flask import Flask, render_template, request, session, send_file, send_from_directory, redirect, url_for from werkzeug.wrappers import BaseRequest, BaseResponse from urlparse import urlparse import sys, time, io, os import urllib import gradeScore reload(sys) def uri_validator(x): if x.find('myfile:') != -1: return True try: result = urlparse(x) if result.scheme!='' and result.netloc!='' and result.path !='': return True else: return False except: return False UPLOAD_FOLDER ='/home/ubuntu/KAIST_giftedCamp_server/upload' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__)#, template_folder = '/templates') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route('/') def home(): return render_template('home.html') @app.route('/about') def about(): return render_template('about.html') @app.route('/grade') def grade(): return render_template('grade.html') @app.route('/gradecalc',methods = ['POST']) def gradecalc(): print request if request.method != 'POST': return 'Access Denied' #print request.form code= request.form['code']; foldername = str(time.time()) res = str(gradeScore.gradeScore(code)).replace('\n','<br>') return res if __name__ == "__main__": if len(sys.argv) == 1: myport = 12345 else: myport = int(sys.argv[1]) print 'asdf' app.run(host='0.0.0.0', port=myport, processes = 10)
995,572
556b95e5572c04dd87af8eafa74aef3449d4e03f
import pytest from pmast import ast_type, Pattern from ast import * @pytest.mark.parametrize('text,t', [ ('FunctionDef', FunctionDef), ('Sub', Sub), ('DoesNotExistAtAll', None), ('copy_location', None), # Actually a function ('*', AST), ]) def test_ast_type(text, t): if t is None: with pytest.raises(TypeError): ast_type(text) else: assert ast_type(text) == t @pytest.mark.parametrize('text,pattern', [ ('FunctionDef', Pattern(FunctionDef) ), ('BinOp.Add', Pattern(BinOp, child=Pattern(Add)) ), ('Expr.BinOp.Add', Pattern(Expr, child=Pattern(BinOp, child=Pattern(Add))) ), ]) def test_spec_parsing(text, pattern): assert Pattern.from_spec(text) == pattern @pytest.mark.parametrize('source,spec,ok', [ ('a + 3', 'Expr', True), ('a + 3', 'Expr.BinOp', True), ('a + 3', 'Expr.BinOp.Num', True), ('a + 3', 'Expr.BinOp.Str', False), ('a + 3', 'Expr.*.Name', True), ('a + 3', 'Expr.*.Str', False), ]) def test_match(source, spec, ok): tree = parse(source).body[0] pattern = Pattern.from_spec(spec) match = pattern.match(tree) if ok: assert isinstance(match[0], Expr) # Simple sanity check before thorough iteration pos = 0 while pattern: assert isinstance(match[pos], pattern.t) pos += 1 pattern = pattern.child else: assert match is None
995,573
3391be0425e2e7985babcbb3269105600004abf6
#!/usr/bin/env python3 from contextlib import contextmanager import json import logging import os import sys import tarfile extension_name = "aum" current_dir = os.path.dirname(__file__) archive_root = os.path.join(current_dir, "..", "archive") src_root = os.path.join(current_dir, "..", "src") common_file = "FujirouCommon.php" info_file = "INFO" def tar_reset(tarinfo): tarinfo.uid = tarinfo.gid = 99 tarinfo.uname = tarinfo.gname = "nobody" return tarinfo def do_tar(info_path): module_dir = os.path.dirname(info_path) if not os.path.exists(info_path): logging.error("INFO file does not exists. {}".format(info_path)) return False text = open(info_path, "rb").read() obj = json.loads(text) # key exists check if "module" not in obj or "version" not in obj: return False module_name = obj["name"] module_file = obj["module"] module_path = os.path.join(module_dir, module_file) module_version = obj["version"] common_path = os.path.join(module_dir, common_file) archive_file = "%s-%s.%s" % (module_name, module_version, extension_name) archive_path = os.path.abspath(os.path.join(archive_root, archive_file)) with tarfile.open(archive_path, "w:gz") as tar: tar.add(module_path, arcname=module_file, filter=tar_reset) tar.add(info_path, arcname=info_file, filter=tar_reset) tar.add(common_path, arcname=common_file, filter=tar_reset) print("create archive {}".format(archive_path)) print("including:") print("\t{} - {}".format(module_file, module_path)) print("\t{} - {}".format(info_file, info_path)) print("\t{} - {}".format(common_file, common_path)) def print_usage(): print("%s [module json path]\n" % (os.path.basename(__file__))) sys.exit(0) if __name__ == "__main__": argv = sys.argv if len(argv) < 2: print_usage() sys.exit(-1) json_path = argv[1] if not os.path.exists(json_path): print("path {} not exists".format(json_path)) sys.exit(-1) do_tar(os.path.abspath(json_path))
995,574
c46b5d23de7eff1504bd7f95ac117adbcb968c0e
import os import shutil import subprocess import sys import tempfile import threading _g_failed = [] def this_location(): return os.path.abspath(os.path.dirname(__file__)) def checkenv(sd_license, release, ssh_key_path): required_vars = ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'GOPATH'] for k in required_vars: v = os.getenv(k) if v is None: raise Exception("The environment variable %s must be set" % k) p = subprocess.Popen("docker ps", shell=True) rc = p.wait() if rc != 0: raise Exception("The docker environment is not configured") file_list = [sd_license, release, ssh_key_path] for f in file_list: if not os.path.exists(f): raise Exception("The file %s does not exist" % f) os.unsetenv('STARDOG_ADMIN_PASSWORD') def build_with_gox(): base_dir = os.path.dirname(this_location()) cmd = 'gox -osarch="linux/amd64" -osarch="darwin/amd64" ' \ '-output=release/{{.OS}}_{{.Arch}}/stardog-graviton '\ 'github.com/stardog-union/stardog-graviton/cmd/stardog-graviton' p = subprocess.Popen(cmd, shell=True, cwd=base_dir) rc = p.wait() if rc != 0: raise Exception("Failed to cross compile graviton") if not os.path.exists(os.path.join(this_location(), "linux_amd64", "stardog-graviton")): raise Exception("The linux compile failed") if not os.path.exists(os.path.join(this_location(), "darwin_amd64", "stardog-graviton")): raise Exception("The osx compile failed") def prep_run(sd_license, release, grav_exe, ssh_key_path): src_dir = this_location() work_dir = tempfile.mkdtemp(prefix="graviton", dir=os.path.abspath(os.path.dirname(__file__))) try: files_to_join_and_copy = ['rows.rdf', 'smoke_test_1.py'] for f in files_to_join_and_copy: shutil.copy(os.path.join(src_dir, f), os.path.join(work_dir, f)) shutil.copy(sd_license, os.path.join(work_dir, "stardog-license-key.bin")) shutil.copy(release, os.path.join(work_dir, os.path.basename(release))) shutil.copy(grav_exe, os.path.join(work_dir, "stardog-graviton")) shutil.copy(ssh_key_path, os.path.join(work_dir, "ssh_key")) return work_dir finally: pass def run_local(work_dir, ssh_key_name, release): print("Running in %s" % work_dir) cmd = "python %s %s %s %s %s" % ( os.path.join(work_dir, "smoke_test_1.py"), work_dir, release, ssh_key_name, os.path.dirname(this_location())) print("Running %s" % cmd) p = subprocess.Popen(cmd, shell=True, cwd=work_dir) rc = p.wait() if rc != 0: raise Exception("Failed to run the smoke test") print ("XXX Local run was successful") def build_docker(image_name): print("Building the docker container") cmd = "docker build -t %s . --no-cache" % image_name p = subprocess.Popen(cmd, shell=True, cwd=this_location()) rc = p.wait() if rc != 0: raise Exception("Failed build the container") def compile_linux(image_name): print("Compiling in a docker container") top_dir = os.path.join(this_location(), "..") try: os.makedirs(os.path.join(this_location(), "release", "linux_amd64")) except: pass internal_gopath = "/opt/go/src/" docker_cmd = "/usr/lib/go-1.10/bin/go build -o %s/src/github.com/stardog-union/stardog-graviton/release/linux_amd64/stardog-graviton github.com/stardog-union/stardog-graviton/cmd/stardog-graviton" % internal_gopath cmd = "docker run -e GOPATH=%s -v %s:%s/src/github.com/stardog-union/stardog-graviton -it %s %s" % (internal_gopath, top_dir, internal_gopath, image_name, docker_cmd) print(cmd) p = subprocess.Popen(cmd, shell=True, cwd=this_location()) rc = p.wait() if rc != 0: raise Exception("Failed build the container") def run_docker(work_dir, ssh_key_name, release, image_name): print("Running docker for testing...") cmd = "docker run -v %s:/smoke " \ "-e AWS_SECRET_ACCESS_KEY=%s " \ "-e AWS_ACCESS_KEY_ID=%s " \ "-it %s " \ "python /smoke/smoke_test_1.py /smoke %s %s" %\ (work_dir, os.environ['AWS_SECRET_ACCESS_KEY'], os.environ['AWS_ACCESS_KEY_ID'], image_name, release, ssh_key_name) p = subprocess.Popen(cmd, shell=True, cwd=work_dir) rc = p.wait() if rc != 0: raise Exception("Failed to run the smoke tests in the container") def print_usage(): print("Invalid arguments:") print("<path to stardog license> <path to stardog release file>" " <path to ssh private key> <aws key name>") def get_version(): cmd = "git describe --abbrev=0 --tags" work_dir = os.path.dirname(this_location()) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, cwd=work_dir) (o, e) = p.communicate() rc = p.wait() if rc != 0: raise Exception("Failed to zip the file") return o.strip() def zip_one(arch): ver = get_version() work_dir = os.path.join(this_location(), arch) cmd = "zip stardog-graviton_%s_%s.zip stardog-graviton" % (ver, arch) p = subprocess.Popen(cmd, shell=True, cwd=work_dir) rc = p.wait() if rc != 0: raise Exception("Failed to zip the file") def darwin_test(sd_license, release, ssh_key_path, ssh_key_name): try: darwin_binary = os.path.join(this_location(), "darwin_amd64", "stardog-graviton") release_name = os.path.basename(release) work_dir = prep_run(sd_license, release, darwin_binary, ssh_key_path) run_local(work_dir, ssh_key_name, release_name) print("Successfully smoke tested for darwin.") print("Exe: darwin_amd64/stardog-graviton") except Exception as ex: global _g_failed _g_failed.append("Darwin failed: %s" % str(ex)) print("TEST ERROR darwin %s" % str(ex)) zip_one("darwin_amd64") def linux_test(sd_license, release, ssh_key_path, ssh_key_name): try: build_docker("graviton-release-tester") compile_linux("graviton-release-tester") linux_binary = os.path.join(this_location(), "linux_amd64", "stardog-graviton") release_name = os.path.basename(release) work_dir = prep_run(sd_license, release, linux_binary, ssh_key_path) run_docker(work_dir, ssh_key_name, release_name, "graviton-release-tester") print("Successfully smoke tested for darwin.") print("Exe: linux_amd64/stardog-graviton") except Exception as ex: global _g_failed _g_failed.append("Linus failed: %s" % str(ex)) print("TEST ERROR linux %s" % str(ex)) zip_one("linux_amd64") def main(): if len(sys.argv) < 4: print_usage() return 1 sd_license = sys.argv[1] release = sys.argv[2] ssh_key_path = sys.argv[3] ssh_key_name = sys.argv[4] checkenv(sd_license, release, ssh_key_path) build_with_gox() threads = [] if sys.platform != "darwin": print("XXXXXX We cannot test of OSX on this platform") else: t = threading.Thread( target=darwin_test, args=(sd_license, release, ssh_key_path, ssh_key_name)) threads.append(t) t.start() t = threading.Thread( target=linux_test, args=(sd_license, release, ssh_key_path, ssh_key_name)) threads.append(t) t.start() print("Started %d tests, waiting for completion..." % len(threads)) for t in threads: t.join() if len(_g_failed) != 0: print("The tests failed %s" % _g_failed) return 1 print("Success!") return 0 if __name__ == "__main__": rc = main() sys.exit(rc)
995,575
5d42591e0d225cca36e44d4a038cff6b3d51b896
from decorator.translators.translator import TranslatorBase class GermanTranslator(TranslatorBase): def Translate(self, input): self._translator.Translate(input) print("The German translation is: " + self._google_trans.translate(input, lang_tgt='de')) class FrenchTranslator(TranslatorBase): def Translate(self, input): self._translator.Translate(input) print("The French translation is: " + self._google_trans.translate(input, lang_tgt='fr')) class ChineseTranslator(TranslatorBase): def Translate(self, input): self._translator.Translate(input) print("The Chinese translation is: " + self._google_trans.translate(input, lang_tgt='zh-TW')) class PersianTranslator(TranslatorBase): def Translate(self, input): self._translator.Translate(input) print("The Persian translation is: " + self._google_trans.translate(input, lang_tgt='fa')) class ZuluTranslator(TranslatorBase): def Translate(self, input): self._translator.Translate(input) print("The Zulu translation is: " + self._google_trans.translate(input, lang_tgt='zu')) class LatinTranslator(TranslatorBase): def Translate(self, input): self._translator.Translate(input) print("The Latin translation is: " + self._google_trans.translate(input, lang_tgt='la'))
995,576
96cec453891d7219fea8cb5f20a3c2fb7ba32830
# AUTHOR = '' SITENAME = 'telegram logs' SITEURL = 'index.html' # options are taken/set from there as well THEME = '../pelican-themes/Flex' CUSTOM_CSS = 'main.css' PATH = 'tmp/' # general settings MAIN_MENU = False TYPOGRIFY = True TIMEZONE = 'US/Central' USE_FOLDER_AS_CATEGORY = True DELETE_OUTPUT_DIRECTORY = True DISPLAY_PAGES_ON_MENU = True DISPLAY_CATEGORIES_ON_MENU = True DISPLAY_ARTICLE_INFO_ON_INDEX = True FORMATTED_FIELDS = [ 'summary' ] STATIC_PATHS = [ 'static/' # relative to tmp/ ] LINKS = [ ('users', 'categories.html') ] # default theme: https://github.com/getpelican/pelican-themes/tree/master/pelican-bootstrap3 # this theme allows you to chose a sub-theme # http://bootswatch.com # THEME = '../pelican-themes/pelican-bootstrap3' # BOOTSTRAP_THEME = 'flatly' # use the fluid layout # BOOTSTRAP_FLUID = True # SHOW_ARTICLE_AUTHOR = False # SHOW_ARTICLE_CATEGORY = False
995,577
6c32c2d5d99f4f465ed062dbff2b8d93f6f91e3f
# encoding:utf-8 import os import sys from os.path import dirname father_path = dirname(dirname(os.path.abspath(dirname(__file__)))) base_path = dirname(dirname(os.path.abspath(dirname(__file__)))) path = dirname(os.path.abspath(dirname(__file__))) sys.path.append(path) sys.path.append(base_path) sys.path.append(father_path) import json import scrapy from urllib.parse import urljoin from scrapy.spiders import CrawlSpider from scrapy.selector import Selector from cookbook.items import CookpadItem class MeishijieSpider(CrawlSpider): name = 'cookpad' allowed_domains = ['cookpad.com'] custom_settings = { 'DEFAULT_REQUEST_HEADERS': { 'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", 'accept-encoding': "gzip, deflate, br", 'accept-language': "zh-CN,zh;q=0.9,en;q=0.8", 'cache-control': "no-cache", # 'cookie': "cpb=00ts682p03834c65ddbcbfcf31d4e65491431c77423c5f8570; bid=00ts682p03834c65ddbcbfcf31d4e65491431c77423c5f8570; v=342-8138978-5098751; FVD=%7Bts+%272018-01-08+16%3A14%3A53%27%7D; country_code=US; ab_session=0.944272257034789; f_unique_id=436ab9c0-1717-4e95-b513-22b8d7190e37; country_suggestion_shown=1; _ga=GA1.2.1753732062.1515395695; _gid=GA1.2.2029256273.1515395695; payload_D=15326; _global_web_session=SllJNC96Q2xLbDN0Q2tNYll2Wk1uaVIrekpzbi9NTGhPLzgrMlFLU2RZQ0kwdVhlQ0hQdkk5UDlWY1d0ZURmanR3aHRqVVpRNEdObzZMdWlBakxpWGE2VXcreXpaM0NGdlRRRjFzSmdzZnI1UWNFdWllT2MxMVI3eGxRUU9GSWZJdUxjRWl0Q3hKRlo2SjRaTjFDUFN3PT0tLVNGcW1UNFlFTkQ0RVlxY2hJTzF2Tnc9PQ%3D%3D--46d06265aadfa0c59c7353abbbf457f9c4004c84", 'if-none-match': "W/\"c2014b1d64c3a1133a503a67ba71c525\"", 'upgrade-insecure-requests': "1", }, 'DOWNLOAD_DELAY': 1 } def start_requests(self): url = 'https://cookpad.com/us?page=' for i in range(1, 557): # 3063 yield scrapy.Request(url + str(i)) def parse(self, response): s = Selector(text=response.text) urls = s.xpath('//div[@class="card feed__card"]/a[@class="link-unstyled"]/@href').extract() for url in urls: list_url = urljoin(response.url, url) yield scrapy.Request(list_url, callback=self.parse_item) def parse_item(self, response): s = Selector(text=response.text) title = s.xpath('//h1/text()').extract_first().strip() pic = s.xpath('//div[@class="tofu_image"]/img/@src').extract_first() likes = s.xpath('//span[starts-with(@id, "likes_count_recipe")]/text()').re_first(r'\d+') camera = s.xpath('//a[@class="link-unstyled field-group__hide"]/text()').re_first(r'\d+') description = s.xpath('//meta[@name="description"]/@content').extract_first() author_url = s.xpath('//a[@class="media__img link-unstyled"]/@href').extract_first() author_url = urljoin(response.url, author_url) author = s.xpath('//span[@itemprop="name"]/text()').extract_first() ing_tags = s.xpath('//div[@class="ingredient__details"]') ingredients = [''.join([t.strip() for t in tag.xpath('.//text()').extract() if t]) for tag in ing_tags if tag] if ing_tags else [] servings = s.xpath('//div[starts-with(@id, "serving_recipe")]/div/text()').extract_first() cook_time = s.xpath('//div[starts-with(@id, "cooking_time_recipe")]/div/text()').extract_first() instructions = s.xpath('//div[@itemprop="recipeInstructions"]/p/text()').extract() item = CookpadItem() item['url'] = response.url item['title'] = title item['pic'] = pic item['likes'] = likes item['camera'] = camera item['description'] = description item['author_url'] = author_url item['author'] = author item['ingredients'] = json.dumps(ingredients, ensure_ascii=False) item['servings'] = servings.strip() if servings else '' item['cook_time'] = cook_time.strip() if cook_time else '' item['instructions'] = json.dumps(instructions, ensure_ascii=False) yield item
995,578
8ba3d9d368e5fe9fdb34ddf36ad0ee082f8a68a8
# -*- coding: utf-8 -*- ######################################################################## # # Copyright (c) 2016 Baidu.com, Inc. All Rights Reserved # ######################################################################## import md5 import time import urllib import re import sys import scrapy from scrapy.http import Request from bs4 import BeautifulSoup from scrapy import signals html_doc = """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="zh-cn"> <HEAD><META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=utf-8"> <title>财 政 司 司 长 出 席 立 法 会 财 经 事 务 委 员 会 会 议 的 谈 话 全 文 </title> <META http-equiv=Content-Type content="text/html; charset=UTF-8"> <META content="tc,Chinese Page," name=keywords> <META content="" name=description><link type="text/css" rel="stylesheet" href="/fsb/style.css"> <script type="text/javascript" src="../../../simpchi_script/layermenu.js"></script> <!-- .search { font-family: "Taipei"; FONT-SIZE: 0.875em; text-decoration: none} .sidebar a:visited { font-family: "Taipei"; FONT-SIZE: 0.875em; text-decoration: none ; color: #000099} .footer { font-size: 11pt; font-family: "Taipei"; color: #000000} .header { font-size: 11pt; font-family: "Taipei"; color: #3333FF } --> <style type="text/css">body{background-image:url(../../../graphics/bg.gif)}</style> </HEAD> <BODY ><p id="skipnav"><a href="#contentArea">Jump to the beginning of content</a></p> <!--NO INDEX START--><!--NO INDEX END--><!-- BEGIN CONTENT --> <SCRIPT type="text/javascript" src="../../../simpchi_script/1link.js"></SCRIPT> <TABLE cellspacing="0" cellpadding="0" border="0" style="width:760px;"> <TBODY> <TR vAlign=top> <TD> <SCRIPT type="text/javascript" src="../../../simpchi_script/1ctop.js"></SCRIPT> </TD></TR></TABLE> <TABLE cellspacing="0" cellpadding="0" border="0" style="width:760px;height:333px;margin-right:0px auto;"> <TBODY> <TR> <TD valign="top" style="text-align:left;width:170px;height:22px;background-color:#EEF8FE;"><!-- #BeginEditable "bar" --> <SCRIPT type="text/javascript" src="../../../simpchi_script/1cleft.js"></SCRIPT> <br> <!-- #EndEditable --></TD> <TD valign="top" style="text-align:left;background-color:#ffffff;"> <TABLE cellspacing="0" cellpadding="0" border="0" style="width:590px;height:333px;background-color:#ffffff;"> <TBODY> <TR> <TD valign="middle" style="width:5px;height:10px;"><IMG height=1 src="/fsb/images/spacer.gif" alt=""></TD> <TD valign="middle" colspan="2" style="text-align:left;height:10px;background-color:#ffffff;"> <div style="text-align:center; margin:0 auto;"><img src="../../images/banner-ppr.gif" width="589" height="70" alt="刊物及新闻公报"></div> </TD> <TD valign="top" style="text-align:left;width:1px;height:10px;"></TD></TR> <TR> <TD style="width:5px;height:180px;"><IMG height=1 src="/fsb/images/spacer.gif" alt=""></TD><TD class="header" valign="top" colspan="2" style="text-align:left;height:275px;background-color:#ffffff;"> <div style="text-align:center; margin:0 auto;"> <div style="text-align:center; margin:0 auto;"> <TABLE border="0" cellpadding="0" cellspacing="0" style="width:420px;margin:0 auto;"> <TR> <TD><h1 class='accessbility'>财经事务及库务局,财经事务科</h1> <h2>财 政 司 司 长 出 席 立 法 会 财 经 事 务 委 员 会 会 议 的 谈 话 全 文 </h2> <P>一 九 九 八 年 九 月 七 日 (星 期 一) <P>以 下 为 财 政 司 司 长 曾 荫 权 今 日 (星 期 一) 上 午 出 席 立 法 会 财 经 事 务 委 员 会 会 议 的 谈 话 全 文: <P>财 政 司 司 长: 上 月 十 四 日, 当 政 府 入 市 后, 议 员 们 没 有 立 刻 要 求 政 府 作 出 解 释, 避 免 给 予 那 些 造 市 的 人 多 一 个 借 口, 以 冲 击 香 港 市 场。 我 很 感 谢 各 位 议 员, 知 道 当 时 的 情 况 是 相 张 紧 张 和 敏 感, 所 以 今 日 我 很 高 兴 可 以 和 我 的 同 事 亲 自 前 来, 向 立 法 会 解 释 那 件 事 的 始 末。 今 日 我 们 除 了 解 释 事 件 的 始 末 外, 亦 想 解 释 多 些 有 关 金 管 局 上 星 期 六 所 宣 布 的 技 术 上 的 措 施, 同 向 各 位 笼 统 地 简 介 政 府 对 证 监 会、 联 合 交 易 所 、 期 货 交 易 所 和 结 算 公 司 所 需 要 准 备 做 的 各 项 新 措 施, 以 及 财 经 事 务 局 如 何 跟 进 这 些 措 施。 现 时 我 们 所 见 到 的, 很 明 显 是 政 府 和 立 法 会 需 要 和 衷 共 济, 积 极 合 作 来 解 决 我 们 所 面 对 的 问 题, 我 们 必 定 要 避 免 这 些 造 市 的 人 有 机 可 乘, 再 次 造 谣 生 事, 兴 风 作 浪。 我 们 部 分 的 新 措 施 更 需 要 透 过 立 法 程 序 来 实 施, 我 很 衷 心 希 望 我 们 能 够 和 立 法 会 全 面 合 作, 能 够 得 到 你 们 的 支 持, 以 便 进 行 我 们 这 些 立 法 行 动。 最 重 要 的 是, 我 想 趁 此 机 会 重 申, 特 区 政 府 会 坚 守 联 系 汇 率, 绝 对 不 会 实 施 任 何 的 外 汇 管 制。 <P>自 八 月 十 四 日 后, 外 间 对 特 区 政 府 入 市 的 动 机, 我 觉 得 是 有 极 深 刻 的 误 解, 他 们 对 我 们 下 一 步 的 行 动 也 有 很 多 方 面 的 揣 测。 虽 然 我 们 不 断 地 强 调, 只 要 那 些 造 市 的 人 离 场, 我 们 便 不 会 再 入 市, 但 其 他 的 人, 特 别 是 证 券 界 方 面, 对 于 我 们 会 否 奉 行 自 由 市 场 的 原 则 与 和 推 行 不 干 预 政 策, 他 们 都 表 示 关 注, 这 方 面 我 也 甚 为 谅 解。 事 实 上, 假 如 对 这 事 情 的 认 识 多 一 点, 特 别 看 看 我 们 现 在 《基 本 法》 对 有 关 的 限 制 是 怎 样, 大 家 便 会 很 清 楚 知 道 我 们 背 后 的 意 图 是 很 清 晰 的。 《基 本 法》 一 零 九 条 清 楚 指 出, 我 们 必 须 维 持 香 港 的 国 际 金 融 中 心 地 位, 这 背 后 的 意 义 是 对 外 不 能 有 封 闭, 必 定 要 继 续 自 由。 一 百 一 十 条 则 指 出, 特 区 政 府 自 行 制 定 货 币 金 融 政 策、 保 证 金 融 企 业 和 市 场 经 营 自 由, 这 也 是 一 项 重 要 的 条 款。 一 百 一 十 一 条 则 订 明 港 元 是 特 区 的 法 定 货 币。 一 百 一 十 二 条 的 规 定, 我 们 不 会 实 行 外 汇 管 制, 要 继 续 开 放 外 汇 、 证 券 和 期 货 市 场, 所 以 这 些 是 很 根 本、 很 基 本 及 很 重 要 的 政 策 方 针。 一 百 一 十 三 条 更 提 到 外  基 金 应 该 由 特 区 政 府 管 理、 支 配、 用 于 调 节 港 元 的 汇 价。 我 们 入 市 的 行 动, 是 完 全 符 合 了 上 述 这 些 条 文 的。 <P>让 我 们 谈 谈 这 些 所 谓 炒 家 的 伎 俩, 报 章 对 此 的 报 道 很 多, 或 许 我 们 首 先 笼 统 地 说 出 他 们 所 用 的 方 法 是 怎 样, 然 后 才 解 释 我 们 为 何 要 入 市。 那 些 造 市 的 炒 家 往 往 在 三 个 市 场 同 时 兴 风 作 浪, 第 一 个 在 证 券 方 面 的 现 货 和 期 货 的 市 场, 第 二 个 是 在 货 币 的 现 货 和 期 货 市 场, 第 三 个 相 当 重 要, 就 是 在 传 播 媒 界 做 工 夫 的。 这 些 造 市 的 人 利 用 个 别 地 区 所 面 临 的 政 治 或 经 济 方 面 的 动 荡, 或 社 会 基 于 任 何 原 因 而 失 去 信 心, 或 者 在 面 对 外 患 的 时 候, 他 们 便 趁 机 行 动, 这 些 炒 家 可 以 动 用 的 资 金 是 以 数 百 亿 美 元 计。 这 些 造 市 的 炒 家 对 付 香 港 时 的 伎 俩, 主 要 是 在 我 们 期 货 市 场 抛 空, 沽 空 我 们 的 股 票, 在 现 货 市 场 也 都 会 抛 售 港 元 和 港 股。 在 此 情 况 下, 香 港 的 息 口 被 挟 高 了, 然 后 透 过 自 由 的 传 媒, 散 播 不 利 的 谣 言 和 假 消 息, 导 致 人 心 惶 惶, 期 货 因 此 便 会 大 幅 下 泻, 另 外 股 票 市 场 也 会 下 泻, 继 而 对 港 汇 方 面 造 成 更 大 的 压 力。 这 方 面 使 炒 家 在 期 货 市 场 内 获 得 庞 大 利 润, 他 们 的 手 法 一 般 是 这 样 的。 香 港 有 以 下 特 别 的 环 境, 对 炒 家 来 说, 造 市 的 吸 引 力 特 别 强。 第 一, 我 们 联 系 汇 率 本 身 的 透 明 度 十 分 高, 加 上 银 行 的 总 结 余 的 数 量 很 少, 现 时 通 常 是 在 十 五 亿 至 十 八 亿 港 元 之 内, 而 且 更 是 全 面 公 开 的。 每 一 个 做 证 券 的 行 家, 打 开 电 算 机 都 可 以 见 到, 即 时 会 有 报 道, 总 结 余 的 数 额 和 升 跌 幅 度。 这 是 很 重 要 的, 你 可 以 见 到, 炒 家 所 掌 握 的 资 讯 是 很 清 楚, 在 什 么 时 候 要 造 市, 他 们 很 容 易 看 到。 第 二, 我 们 有 一 个 完 全 自 由 开 放 的 证 券 和 期 货 市 场, 我 们 没 有 像 其 他 国 际 金 融 中 心 一 样, 采 取 一 些 特 别 措 施 以 保 障 自 身 的 金 融 中 心, 这 些 凌 厉 的 措 施, 香 港 是 没 有 的, 暂 时 是 没 有 的。 第 三, 我 们 香 港 的 传 媒 是 享 有 绝 对 的 自 由, 这 是 香 港 一 个 很 大 和 很 宝 贵 的 资 产。 不 过, 我 们 这 个 传 播 媒 界 的 自 由, 当 然 我 们 可 以 报 道 有 好 消 息, 亦 可 以 报 道 坏 的 消 息, 所 以 市 场 的 谣 言 里 面 都 可 以 自 由 报 道。 但 当 我 们 经 济 下 调 时, 这 样 会 造 成 市 民 的 信 心 下 降, 是 一 个 很 大 的 因 素, 这 些 造 市 的 炒 家 很 清 楚 理 解 这 种 心 理。 所 以 炒 家 所 需 要 做 到 的, 是 首 先 借 充 足 的 港 元 和 港 股, 即 借 够 这 个 弹 药, 他 们 便 等 待 时 机 蠢 蠢 欲 动。 他 们 靠 摇 动 市 场 的 信 心 和 情 绪 行 事, 对 于 香 港 根 本 和 经 济 基 础 有 多 强, 他 们 不 会 关 心, 因 他 们 只 是 趁 机 会。 他 们 只 担 心 一 件 事, 就 是 我 们 的 外 汇 储 备 很 多, 对 他 们 可 能 是 一 种 阻 吓, 但 是 其 他 关 于 我 们 银 行 的 稳 健、 我 们 的 监 管 稳 健, 我 们 现 时 没 有 外 汇 赤 字, 这 些 对 他 们 来 说 不 成 问 题, 最 主 要 是 人 民 的 信 心 问 题。 <P>对 这 方 面, 我 们 先 要 分 辨 一 些 是 非。 有 很 多 人 说 我 们 对 对 冲 基 金、 投 资 家、 炒 家 造 市, 我 们 应 该 要 分 清 楚。 就 我 来 说, 香 港 所 欢 迎 的, 就 是 所 有 任 何 长 线 投 资 的 人 士, 或 者 短 线 投 资 的 人 士, 不 论 是 香 港 人, 外 国 人 或 内 地 人 士, 我 们 无 限 欢 迎, 随 时 都 欢 迎 他 们 来 投 资。 还 有, 香 港 是 一 个 公 开 的 自 由 市 场, 当 然 不 能 够 杜 绝 投 机 的 活 动, 投 机 的 活 动 在 某 方 面 来 看 是 有 其 正 面 和 积 极 的 作 用。 在 这 样 的 情 况 之 下, 我 们 不 会 对 这 些 所 谓 的 炒 家 或 者 投 机 者 却 步, 但 我 们 所 要 知 道 的 和 要 针 对 的, 是 那 些 刻 意 造 市 的 炒 家, 造 市 的 炒 家 就 是 在 几 个 市 场 内 做 一 些 刚 才 我 所 说 的 卖 空、 刻 意 挟 起 息 口, 令 市 场 动 乱, 并 散 播 谣 言, 这 些 是 我 们 所 要 针 对 的, 这 些 是 我 所 说 造 市 的 炒 家。 这 些 造 市 的 炒 家, 在 其 他 地 区 也 都 有 法 例 的 管 制。 有 些 人 说 这 些 对 冲 基 金 是 不 对 的, 我 们 称 这 些 为 对 冲 基 金, 已 是 不 甚 正 确 的 字 眼, 特 别 英 文 称 之 为 Hedge Fund 这 字 眼 是 不 对 劲 的, 我 们 所 指 的 是 造 市 的, 并 不 是 一 般 的 对 冲 基 金。 这 些 造 市 的 对 冲 基 金 无 所 不 为, 只 有 一 样 不 做, 就 是 不 做 对 冲, 不 做 套 戥, 他 们 做 一 样 事, 就 是 行 险 地 做 事, 我 们 不 应 称 他 们 为 投 机 者, 也 不 能 称 他 们 为 投 资 者, 不 可 称 他 们 为 一 般 的 炒 家, 我 们 应 称 他 们 为 造 市 才 对, 他 们 已 完 全 脱 离 了 这 个 所 谓 对 冲 和 套 戥 的 本 色。 <P>我 们 不 是 在 八 月 中 才 开 始 认 为 有 需 要 在 市 场 上 有 所 活 动, 根 本 由 七 月 中 开 始, 我 们 已 感 受 到 一 股 相 当 大 的 压 力。 七 月 十 四 日, 日 本 前 首 相 乔 本 先 生 辞 职, 七 月 三 十 日, 小 丸 惠 三 继 任。 在 这 段 时 间, 日 圆 对 美 金 的 兑 换 率 跌 穿 了 一 百 四 十 五 的 水 平, 跟  最 重 要 的 是 华 尔 街 杜 琼 斯 指 数 跌 至 八 千 五 的 水 平。 对 这 些 造 市 的 炒 家 来 说, 这 个 外 围 因 素 是 天 衣 无 缝 的。 在 香 港 来 说, 七 月 底、 八 月 初 有 很 多 香 港 的 大 公 司 宣 布 业 绩, 但 很 可 惜, 他 们 所 宣 布 的 是 乏 善 足 陈 的 业 绩。 股 票 和 现 货 市 场 的 交 投 量 十 分 低, 当 时 只 有 是 三、 四 十 亿, 就 业 和 贸 易 数 字 以 及 零 售 情 况 更 趋 恶 化, 所 以 香 港 的 内 部 情 况, 给 予 这 些 造 市 炒 家 一 个 良 机。 我 们 见 到 这 些 造 市 的 活 动, 在 七 月 底 已 经 在 做 工 夫, 他 们 的 方 法 是 沽 售 港 元, 他 们 沽 售 港 元 的 速 度 和 剧 烈 的 程 度 是 前 所 未 见 的。 他 们 在 开 市 时, 首 先 在 纽 约 造 市, 跟  在 悉 梨 继 续 卖 港 元, 然 后 到 香 港 则 继 续 加 深 地 卖, 他 们 接  到 伦 敦, 二 十 四 小 时 不 停 地 操 作 和 加 压, 我 们 见 到 的 计 划 是 有 部 署 的, 而 且 有 操 控 的 成 分。 举 一 个 例 子, 可 以 作 为 引 证。 八 月 分 首 个 星 期, 金 管 局 要 接 港 元 的 沽 盘, 共 达 到 二 十 亿 美 元, 我 们 在 第 二 个 星 期 要 买 入 港 元, 而 沽 出 美 元 的 数 量, 是 四 十 二 亿 美 元。 这 个 数 字, 即 换 句 话 说, 两 个 星 期 内, 我 们 要 买 入 的 港 元、 沽 出 的 美 元 已 超 过 六 十 亿。 在 一 九 九 七 年 十 月 我 们 最 恶 劣 的 时 间, 当 时 我 们 的 总 沽 盘, 以 全 段 期 间 来 说, 我 们 要 买 入 的 港 元、 沽 出 的 美 元 不 过 是 三 十 亿。 所 以 今 次 沽 盘 的 数 量 增 加 很 快, 而 且 来 势 比 当 期 时 凶 猛 得 多。 第 二 件 事, 在 我 们 的 期 交 所 市 场, 在 七 月 底 和 八 月 初, 有 三 个 交 易 日 内, 恒 指、 期 货 未 平 仓 合 约 突 然 增 加 了 一 万 张, 使 到 八 月 份 未 平 仓 合 约 一 共 达 到 九 万 二 千 张。 相 比 之 下, 在 九 七 年 十 月 二 十 八 日, 恒 指 期 货 未 平 仓 (当 时 已 是 我 们 所 遇 到 最 恶 劣 的 时 间) 只 有 七 万 张。 九 八 年 一 月 是 第 二 次 的 冲 击, 当 时 也 亦 只 有 七 万 张。 但 由 七 月 底 至 八 月 十 三 日 这 段 期 间, 大 部 分 的 时 间, 香 港 期 指 (合 约) 均 是 超 过 十 万 张, 即 比 平 常 超 过 了 大 约 三 万 张。 最 重 要 第 二 个 问 题, 是 现 货 市 场 的 成 交 量 是 比 九 七 年 时 的 数 量 跌 了 很 多。 九 七 年 十 月, 我 们 每 日 有 大 约 三 百 多 亿 元 的 成 交 量, 直 至 到 今 年 七 、 八 月 这 段 时 间, 七 月 底 时, 都 只 是 三、 四 十 亿。 所 以, 我 们 可 以 看 到 这 个 期 货 市 场 特 别 活 跃, 我 们 现 在 这 个 现 货 市 场 的 成 交 量 很 弱, 换 句 话 说, 冲 击 时 所 动 用 的 资 本 少 了 很 多, 加 上 在 外  市 场 二 十 四 小 时 不 停 地 攻 击 我 们, 跟  利 用 纽 约 的 市 场、 悉 梨 的 市 场、 本 地 香 港 的 市 场, 跟  是 伦 敦 的 市 场。 在 这 段 期 间, 七 月 底、 八 月 的 第 一 个 星 期 和 第 二 星 期, 香 港 和 外 国 的 报 章 不 停 地 报 道 人 民 币 会 贬 值 的 谣 言。 另 一 方 面, 在 香 港 和 海 外 有 些 报 章、 杂 志、 周 刊 更 不 时 刊 登 港 元 会 脱 , 这 些 谣 传 较 去 年 十 月 和 今 年 一 月 那 几 次 冲 击 的 多 了 很 多。 跟  在 外 地 的 金 融 机 构 在 那 段 期 间 发 表 了 很 多 极 看 淡 港 元 和 香 港 的 报 告, 从 这 种 种 迹 象 来 看, 我 们 在 外 围 媒 界 方 面 所 受 的 压 力 是 空 前 未 有 的。 而 且 更 在 同 一 时 期, 日 本 的 情 况 继 续 恶 化, 未 见 有 好 转 的 迹 象。 当 时 内 部 有 些 专 业 的 估 计, 如 果 我 们 继 续 这 样 下 去, 港 元 的 息 口 便 会 在 八 月 第 三 个 星 期 被 挟 上 大 约 是 五 十 厘, 而 我 们 发 现 一 些 炒 家 手 上 持 有 大 量 港 元, 可 以 继 续 沽, 沽 到 一 个 情 况, 就 是 我 们 香 港 的 息 口 会 一 段 长 时 间 维 持 在 二 十 厘 和 三 十 厘 这 个 水 平, 因 为 我 们 发 现 这 些 炒 家 今 次 已 不 需 要 在 我 们 的 银 行 获 取 所 需 的 港 元, 他 们 在 年 中、 年 头 之 间 已 经 从 港 元 的 债 券 市 场 借 入 充 足 的 港 元, 以 准 备 今 次 作 战, 所 以 如 果 我 们 再 不 做 点 工 夫, 本 港 利 息 必 定 会  升 至 很 高 的 水 平。 另 外 一 个 专 业 的 估 计, 以 现 时 的 部 署, 现 时 现 货 市 场 的 交 投 量 这 般 低, 再 加 上 恒 指 方 面 的 压 力, 如 果 再 这 样 下 去 的 话, 恒 指 很 可 能 在 短 期 内 会 跌 二 千 点 至 三 千 点。 楼 市 的 后 果 更 不 可 以 估 计, 因 为 这 样 会 加 深 香 港 有 意 置 业 人 士 的 心 理 阴 影, 对 银 行 构 造 成 一 个 很 大 的 压 力。 再 加 上 在 八 月 底 我 们 公 布 的 香 港 经 济 数 据, 我 们 整 体 经 济 的 负 增 长 数 字, 这 样, 很 可 能 会 令 香 港 市 民 面 对 这 些 内 忧 外 患 的 情 况 时, 失 去 很 大 的 信 心。 以 我 和 几 位 同 事 的 经 验, 我 们 估 计 这 个 来 势 和 一 九 八 三 年 十 月 港 币 币 值 突 然 下 滑 的 情 况 很 相 像, 而 且 其 下 滑 的 速 度 和 后 果, 我 们 没 有 办 法 可 以 估 计, 即 使 说 恒 指 会 跌 二、 三 千 点, 很 可 能 都 是 比 较 乐 观 的 估 计, 原 因 是 其 后 果 是 没 有 办 法 可 以 估 计 得 到。 因 为 当 香 港 普 罗 大 众 对 于 这 个 金 融 制 度, 对 于 政 府 应 付 这 个 制 度 失 去 信 心 的 时 候, 其 引 来 的 后 果 会 很 严 重。 所 以 在 八 月 第 一 个 星 期, 我 的 同 事 已 向 我 建 议, 在 情 况 未 曾 失 控 前, 我 们 一 定 要 考 虑 在 证 券 市 场 移 走 这 些 造 市 的 炒 家 的 肥 猪 肉, 一 定 要 入 市, 做 这 件 事。 <P>财 政 司 司 长: 我 们 从 那 天 起, 八 月 初 开 始, 我 们 每 日 都 审 慎 估 计 每 日 的 情 况, 我 有 一 段 时 间 多 次 和 行 政 长 官 商 讨, 我 在 这 两 个 星 期 每 一 日 都 多 方 面 静 观 其 变, 看 看 各 方 面 的 外 围 情 况 有 否 好 转, 香 港 的 情 况 有 否 好 转。 另 一 方 面, 我 们 同 时 亦 筹 备 在 入 市 后 的 跟 进 工 夫 要 怎 样 做。 我 更 衡 量 到 假 如 我 们 在 香 港 采 取 入 市 的 行 动 后, 对 于 外 围 对 我 们 的 批 评, 香 港 内 部 的 反 对 声 浪, 作 出 深 入 研 究, 考 虑 每 一 个 步 骤。 最 重 要 的, 是 在 法 理 上 我 们 这 样 做 是 否 构 成 问 题, 会 否 有 限 制。 特 别 在 《基 本 法》, 以 及 外 汇 基 金 条 例 所 赋 予 我 们 的 权 力, 我 们 都 很 小 心 地 了 解。 我 可 以 很 苦 心 地 向 各 位 议 员 说, 在 我 自 己 的 公 务 员 生 涯 里, 最 困 难 的 决 定 就 是 在 这 情 况 下 做 的 决 定。 我 和 我 的 同 事 一 向 坚 信 自 由 经 济 体 系, 对 进 入 任 何 股 市 和 市 场 是 一 向 都 有 诫 心, 但 当 恒 指 接 近 第 二 个 星 期 跌 破 七 千 点 时, 炒 家 再 向 我 们 加 强 压 力 沽 售 港 元, 我 觉 得 没 有 其 他 的 办 法。 所 以 在 八 月 第 三 个 星 期 末 段 时, 我 作 出 了 我 自 己 应 该 做 的 决 定, 亦 得 到 行 政 长 官 的 同 意, 并 谘 询 外 汇 基 金 资 谘 委 员 会, 得 到 他 们 全 面 的 支 持。 另 外, 很 多 位 资 深 的 委 员 说 香 港 当 时 除 此 之 外, 并 没 有 其 他 的 方 法, 所 以 我 们 决 定 了 这 样 做, 然 后 知 会 了 中 央 政 府。 八 月 十 四 日 星 期 五 当 日, 入 市 之 后, 我 立 刻 便 向 外 宣 布, 我 们 一 早 已 决 定 了 要 向 外 公 布 我 们 这 个 方 案, 我 们 不 单 因 为 我 们 的 信 念, 同 时 亦 贯 彻 一 贯 的 做 法, 就 是 要 公 开 我 们 自 己 的 做 法。 我 认 为 幕 后 入 市 这 种 做 法, 可 能 有 其 他 地 区 都 会 这 样 做, 但 我 们 觉 得 幕 后 入 市 不 是 一 个 好 的 方 法, 对 香 港 公 众 和 外 国 投 资 者 都 不 是 一 个 诚 恳 的 交 代。 入 市 后 的 每 一 天 都 是 由 金 管 局 全 权 负 责, 但 在 进 行 中 是 有 其 干 预 的 界 限, 而 这 些 界 限 是 由 我 订 定 的, 每 日 的 行 动 情 况 都 要 向 我 报 告。 金 管 局 负 责 监 管 银 行 的 同 事 是 完 全 不 准 参 与 是 次 行 动, 是 特 别 由 金 管 局 另 一 组 人 员 做 这 件 事 的。 所 购 入 的 股 份 亦 是 在 我 的 指 引 下 做, 就 是 一 定 要 大 致 和 恒 指 成 分 的 比 重 相 同, 换 句 话 说, 不 能 偏 袒 某 一 种 股 票, 亦 不 能 轻 视 某 一 种 股 票。 有 关 两 个 星 期 前, 即 八 月 十 四 日 至 八 月 底, 全 部 的 情 况 已 被 很 多 香 港 的 传 媒 生 动 地 报 道, 我 不 用 冗 赘 地 再 说 一 遍。 我 在 这 方 面 很 多 谢 本 地 的 支 持, 抵 销 了 外 地 传 媒 的 大 肆 批 评 我 的 情 况, 在 我 心 理 上 是 有 点 帮 助 的。 而 在 外 面 的 报 道, 就 我 看 来, 有 一 定 的 程 度 反 映 了 炒 家 惯 用 的 言 论。 入 市 当 然 带 来 了 不 少 的 谣 言 和 不 少 的 报 道, 事 实 上, 在 传 媒 方 面 这 些 造 市 的 人 不 停 地 在 做 工 夫, 即 使 在 八 月 底 结 算 那 日 之 前, 也 有 某 一 个 基 金 的 高 层 人 物 极 力 批 评, 在 当 时 想 再 把 市 造 低。 我 于 八 月 二 十 八 日, 即 上 星 期 五 收 市 后, 立 刻 向 外 发 表, 指 出 我 们 跟 进 的 工 作, 接 着 我 们 金 管 局 马 上 做 跟 进 的 工 夫, 而 今 天 便 是 向 各 位 议 员 简 介 其 他 在 这 市 场 内 的 跟 进 工 作。 金 管 局 在 上 星 期 六 所 公 布 的 七 项 措 施, 我 们 已 经 向 议 员 解 释 过 一 次, 今 天 陈 德 霖 先 生 (金 管 局 副 总 裁) 也 有 出 席, 我 亦 不 想 再 重 复 这 七 项 措 施 的 内 容, 但 陈 先 生 很 乐 意 解 答 议 员 对 七 项 措 施 具 体 上 的 问 题。 黎 高 颖 怡 (署 理 财 经 事 务 局 局 长) 会 介 绍 有 关 证 监 会、 交 易 所 和 中 央 结 算 的 措 施 和 法 例, 以 及 我 们 准 备 修 订 的 项 目。 这 些 措 施 与 其 他 金 融 市 场 所 采 取 的 方 法 大 致 相 同。 刚 才 我 已 解 释 过, 我 们 早 在 入 市 前, 已 构 思 了 这 些 措 施。 这 些 措 施 是 我 们 应 变 部 署 计 划 的 一 部 份, 是 我 们 金 管 局 和 政 府 长 期 应 变 计 划 的 其 中 一 部 份, 认 为 有 急 切 需 要 时 才 会 利 用。 这 些 应 变 措 施 和 跟 进 的 工 作, 每 一 项 也 要 付 出 代 价, 它 有 负 面 的 作 用, 当 然 也 有 正 面 的 作 用, 所 以 我 们 做 一 件 事 都 不 是 轻 率 而 做 的。 最 后 我 要 说 的 是, 特 区 政 府 的 目 标, 今 次 入 市 的 行 动, 是 要 想 令 到 造 市 的 炒 家 快 些 离 场, 恢 复 香 港 证 券 市 场 的 秩 序, 我 们 不 是 想 令 任 何 人 有 损 失 或 受 罚, 但 是 造 市 的 炒 家 绝 对 不 能 在 香 港 予 取 予 携, 亦 不 能 当 我 们 是 自 动 提 款 机。 我 们 知 道 这 样 做 对 于 我 们 的 国 际 声 誉 是 付 出 了 代 价, 但 为 了 捍 卫 香 港 的 制 度 和 联 系 汇 率, 我 们 迫 不 得 已 不 能 不 这 样 做。 我 们 认 为 假 如 我 们 不 入 市, 后 果 是 不 可 想 像 的。 现 在 我 们 可 以 知 道, 我 们 可 以 看 见 我 们 所 做 的 事, 当 然 有 其 正 面, 也 有 其 负 面。 我 们 一 定 要 承 担 这 个 责 任。 而 我 在 这 方 面, 全 部 有 关 这 件 事 的 决 定, 我 个 人 愿 意 作 最 大 的 承 担, 我 乐 意 这 样 做。 我 们 最 重 要 是 维 持 市 场 的 秩 序, 捍 卫 联 系 汇 率。 我 们 香 港 特 区 政 府 并 不 害 怕 经 济 调 整 带 来 的 痛 楚, 但 是 假 如 有 人 乘 着 我 们 经 济 调 整 时 才 施 以 致 命 一 击, 我 们 必 定 会 还 抗 到 底。 另 外 特 区 政 府 绝 对 不 会 托 市, 而 自 八 月 二 十 八 日 后, 金 管 局 基 本 上 已 没 有 在 市 场 内 进 行 做 任 何 活 动。 在 未 来 这 数 个 月, 我 会 尽 力 在 香 港、 在 海 外, 和 特 首、 政 务 司 司 长、 财 经 事 务 局 局 长、 金 管 局 的 总 裁 和 其 他 高 级 的 同 事, 尽 量 到 外 国, 向 香 港 立 法 会 议 员 香 港 普 罗 大 众 解 释 我 们 今 次 做 的 事 并 减 轻 他 们 对 将 来 的 担 忧。 还 有 一 点 我 想 说 的 是, 我 们 今 次 的 入 市 行 动 所 购 得 的 股 票, 是 一 项 好 的 投 资。 我 们 会 有 秩 序 地 彻 离 市 场, 当 这 些 造 市 的 炒 家 真 正 离 场 后, 我 便 会 正 式 向 议 员 和 公 众 交 代 我 们 所 持 股 份 的 数 量, 全 面 向 各 位 解 释。 另 外, 我 准 备 在 外 汇 基 金 下, 成 立 一 间 公 司, 管 理 这 些 投 资, 尽 量 防 止 出 现 利 益 冲 突 的 问 题。 当 然, 历 史 会 证 明 我 们 今 次 做 的 是 对 还 是 错, 但 对 于 市 民 对 我 的 支 持, 我 已 十 分 感 激。 我 知 道 现 在 造 市 的 炒 家, 还 在 注 视 我 们 现 时 的 情 况。 我 们 在 会 场 和 会 内 所 讨 论 的 事 情。 我 希 望 我 们 可 以 团 结 一 致。 或 许 希 望 主 席 容 许 我 的 同 事, 特 别 是 黎 太, 解 释 我 们 具 体 就 市 场 情 况 提 出 几 项 改 善 措 施。 <P>李 柱 铭 议 员: (措 施 为 什 么 这 样 迟? 干 预 市 场 的 真 正 理 由?) <P>财 政 司 司 长: 任 何 一 种 针 对 市 场 的 措 施 都 有 它 的 代 价, 它 的 回 应。 当 你 做 这 些 措 施 时 便 要 审 慎 考 虑。 除 了 这 些 措 施 外, 我 们 的 其 它 应 变 措 施 还 有 很 多, 林 林 总 总, 但 郄 要 在 不 同 时 间 才 可 以 应 用。 但 我 要 重 复 一 次 说, 每 一 件 事 都 有 它 的 代 价, 这 并 不 是 在 有 一 些 怀 疑 或 恐 惧 时 便 拿 出 来 用, 而 是 要 在 认 为 有 需 要 时 才 拿 出 来 用。 至 于 说 我 们 做 得 快 抑 或 慢 这 个 问 题, 我 们 觉 得 在 回 应 上 我 们 应 该 是 适 当 地 去 做。 你 们 可 以 看 到, (当) 这 些 措 施 出 来 时, 你 会 觉 得, 其 他 的 人, 特 别 是 外 国 或 本 地 那 些, 他 们 惯 了 是 「无 王 管」 时, 他 们 (自 然) 也 有 反 对 的 声 音, 我 们 也 不 能 不 考 虑 到 这 些 负 面 的 反 应。 所 以, 每 一 件 事, 都 不 是 说 一 想 到 便 可 以 立 即 去 做, 而 不 去 理 会 全 面 的 后 果。 所 以, 我 们 一 定 要 小 心 地 去 做。 还 有, 我 们 准 备 去 做 的, 有 部 分 是 要 经 立 法 (程 序) 的, 而 立 法 是 并 非 这 样 简 单, 一 说 要 做 便 可 以 立 刻 去 做。 一 日 三 读 并 非 是 我 们 轻 易 去 做 的 事。 (我 们) 一 定 要 想 得 清 清 楚 楚, (看) 有 没 有 这 个 需 要, 有 没 有 道 理, 才 可 以 采 用 这 个 方 法。 做 这 些 措 施, 我 们 不 但 需 要 在 本 地 方 面 我 们 要 得 到 本 地 人 的 支 持, 这 当 然 是 最 主 要 的, 另 外, 还 (需 要) 国 际 舆 论, 专 业 人 士, 如 国 际 货 币 基 金, 特 别 是 对 金 融 机 构 有 很 深 刻 认 识 的 中 央 财 长 及 财 政 部 长 等 (的 支 持)。 他 们 的 回 应 会 是 怎 样 呢? 例 如 我 们 的 措 施, 有 一 些 已 经 在 上 两 星 期 个 别 在 海 外 很 小 心 地 谘 询, 得 到 他 们 的 回 应, 亦 得 到 他 们 部 分 的 支 持, 这 便 加 强 了 我 们 今 次 推 行 这 些 措 施 的 信 心。 所 以 是 需 要 一 些 时 间 酝 酿 的。 还 有 一 点 很 重 要 的, 便 是 以 我 自 已 及 同 事 的 经 验, 当 你 推 行 一 系 列 的 措 施 时, 是 需 要 在 市 场 在 稳 定 的 情 况 下, 才 可 以 做。 当 市 场 是 混 乱 的 时 候, 向 下 调 的 时 候, 要 做 这 些 措 施 的 时 候, 可 能 会 有 反 后 果, 而 产 生 一 连 串 的 不 需 要 的 误 解, 错 误 的 信 息, 使 后 果 很 不 同, 得 不 到 (预 期) 后 果。 所 以 我 们 觉 得 这 些 更 改, 包 括 金 管 局 方 面 的 措 施, 和 刚 才 黎 太 所 解 释 的 措 施, 全 部 都 要 我 们 平 心 静 气, 市 场 已 经 安 定 下 来, 炒 家, 特 别 是 造 市 的 整 体 或 大 半 离 场 的 时 候, 才 可 以 做 这 些 事。 我 希 望 大 家 可 以 明 白。 至 于 我 们 今 次 入 市 的 目 标, 我 刚 才 己 经 说 得 很 清 楚, 我 们 并 不 是 要 惩 罚 任 何 人, 不 是 要 托 市, 不 是 要 任 何 人 有 损 伤, 只 是 希 望 造 市 的 炒 家 尽 量 不 要 以 为 我 们 是 「蒙」 的, 当 香 港 市 场 是 他 们 可 以 予 取 予 携 的, 我 们 只 是 想 制 止 这 些 活 动。 这 并 不 是 说 我 们 故 意 干 预。 我 刚 才 说 干 预 的 范 围 只 是 技 术 上 的 字 眼, 即 是 说 金 管 局 每 一 天 入 市 的 时 候 入 市 的 数 量 是 怎 样 呢? 银 码 限 制 怎 样 呢? 这 便 是 我 的 意 思。 <P>陈 鉴 林 议 员: (支 持 政 府 是 为 了 捍 卫 港 元 汇 率 和 市 场 的 自 由 健 康 的 发 展, 作 出 一 些 适 当 的 措 施 在 市 场 里 面 做 一 些 事, 但 想 知 道 政 府 除 了 严 格 执 行 T+ 2的 结 算 制 度 之 外, 会 否 整 顿 结 算 公 司, 以 维 护 这 个 自 由 市 场 里 面 的 公 平 交 易, 或 进 一 步 去 调 查 这 事 件) <P>财 政 司 司 长: 我 再 次 多 谢 陈 议 员 和 刚 才 李 议 员 所 说 的 支 持 联 系 汇 率, 和 陈 议 员 支 持 我 们 今 次 入 市 的 行 动, 但 是 有 关 于 T+ 2 这 个 问 题 和 改 变 T+ 1这 个 再 收 紧 的 问 题, 这 个 问 题 以 往 争 论 了 很 多, 或 者 我 请 黎 太 向 你 更 加 具 体 地 解 释, (但) 最 主 要 我 们 要 知 道 我 们 基 本 法 厘 定 了 我 们 做 一 个 向 外 型 的 国 际 市 场, 如 果 是 T+ 1的 话, 便 会 令 外 地 人 投 资 香 港 的 时 候, 在 交 收 方 面 做 成 极 大 的 困 难, 以 往 在 厘 定 这 个 政 策 之 前, 市 场 已 有 了 很 多 的 辩 论。 定 下 的 不 (单) 是 T+ 3, 有 些 市 场 T+ 3、 有 些 T+ 4, 香 港 做 到 T+ 2。 作 为 国 际 市 场, 以 我 所 知 已 经 是 相 当 严 紧, 是 相 当 短 速 和 有 效 率 的 了。 或 者 黎 太 会 在 这 方 面 更 具 体 地 说 明。 <P>黎 太: 正 如 财 政 司 司 长 所 说, 其 实 在 世 界 上 其 他 的 国 际 的 金 融 市 场, 我 不 计 只 是 内 向 型 的 股 票 市 场, 如 果 你 说 美 国, 甚 至 说 英 国 或 者 悉 尼 等 等 的 市 场, 他 们 现 时 的 做 法 是 T+ 3至 5的, 很 多 是 T+ 5, 因 此 T+ 2以 有 国 际 客 户 (的 市 场) 来 说 已 经 是 一 个 很 高 的 水 准。 在 有 时 差 等 等 情 况 之 下, 我 们 是 需 要 某 一 程 度 上 容 许 他 们 国 际 的 调 动, 或 者 是 授 权 他 们 的 托 管 人 要 做 些 什 么 等 等。 但 是 我 相 信 最 终 的 目 的, 最 重 要 是 说, 如 果 我 们 能 够 做 到 全 面 电 子 化, 我 们 的 交 易 系 统 和 交 收 结 算 和 金 钱 的 来 往, 全 部 都 可 以 同 步 进 行 的 时 候, 我 们 是 (希 望) 做 到 T+ 0和 即 时 做 的, 我 们 希 望 是 可 以 尽 量 落 实 得 到 整 个 大 纲 是 怎 样 做。 但 是 在 此 之 前, 如 果 在 未 有 这 个 配 套, 而 硬 是 说 T+ 1的 话, 是 比 较 不 设 实 际, 也 扼 杀 了 某 一 部 份 市 场 的 活 动。 <P>主 席: 我 相 信 陈 议 员 想 问 你 怎 样 整 顿 结 算 公 司, 因 为 他 认 为 结 算 公 司 是 有 法 不 依, 执 法 不 严。 <P>财 政 司 长: 关 于 这 件 事 是: 结 算 公 司 和 我 们 亦 都 开 过 一 次 会, 亦 在 电 话 内 谈 过 很 多 次, 今 次 他 们 有 些 少 措 手 不 及, 除 了 造 市 的 人 觉 得 措 手 不 及 之 外, 很 多 人 也 觉 得 措 手 不 及, 便 是 今 次 交 投 量 是 相 当 大, 所 以 (如 果) 某 部 份 的 交 收 不 清 楚, 是 可 以 谅 解, 但 数 量 应 否 这 么 大, 有 没 有 人 做 抛 空 的 活 动, 我 们 一 定 要 根 查。 大 家 也 知 道, 最 后 做 结 算 的 都 要 立 刻 交 票 给 金 管 局, 买 了 的 货 一 定 要 交 给 它, 我 相 信 它 一 定 会 做 得 到, 可 能 迟 了, 迟 了 的 不 是 可 以 完 全 没 有 后 果, (因 为) 第 一, 联 交 所、 期 交 所 均 有 它 们 自 己 管 制 会 员 的 办 法。 换 句 话 说, 如 果 有 迟 交 的, 他 们 会 个 别 地 和 立 刻 地 跟 进, 刚 才 黎 太 解 释 了 他 们 会 跟 进, (看 看) 个 别 会 员 有 没 有 充 份 的 理 由, 是 否 应 该 做 惩 罚 的 行 动, 还 有 的 是, 如 果 真 的 是 抛 空 的, 根 本 知 道 那 一 位 会 员 是 没 有 货 而 抛 空 的, 或 者 购 买 落 单 的 人 根 本 没 有 货 而 要 卖, 这 些 是 非 法 行 为, 我 知 道 所 有 这 些 个 案, 期 交 所 和 联 交 所 已 经 将 资 料 给 予 证 监 会, 证 监 会 会 逐 一 调 查, 使 没 有 人 能 逃 于 法 外, 换 句 话 来 说, 这 次 手 续 上 方 面 可 能 交 收 迟 了, 但 关 于 纪 律 上 的 责 任 和 法 律 上 的 责 任, 没 有 人 能 够 逃 脱。 <P>何 秀 兰 议 员:   (在 将 这 个 入 市 干 预 的 决 定 交 给 特 首 之 前, 财 政 司 司 长 有 没 有 谘 询 业 界? 谘 询 过 什 么 人? 而 这 些 人 需 否 申 报 利 益? 他 们 自 己 是 否 可 以 利 用 这 些 资 讯, 在 市 场 上 获 取 利 益?) <P>财 政 司 司 长:   所 有 政 府 职 员 和 金 管 局 的 同 事, 对 于 这 个 申 报 利 益 和 申 报 自 己 所 有 有 关 于 有 任 何 对 工 作 上 有 冲 突 的 问 题 时, 是 有 很 清 楚 的 规 定, 他 们 的 诚 信, 我 觉 得 是 没 有 怀 疑 的。 有 关 我 们 真 是 否 业 余, 各 人 有 不 同 的 见 解。 关 于 这 件 事, 我 亦 不 能 说 自 己 在 这 股 票 市 场 打 滚 数 十 年, 亦 不 是 有 这 回 事, 但 我 对 这 事 是 有 认 识 的。 最 重 要 是 在 金 管 局 里 面, 有 很 多 在 业 界 里 面 真 是 打 滚 了 很 久 的 专 家, 他 们 不 会 逊 色 于 任 何 其 他 现 时 不 在 金 管 局 里 面 的 专 家, 他 们 所 聚 积 的 经 验, 能 观 察 到 市 场 的 情 况, 和 很 清 楚 市 场 的 讯 息。 我 们 今 次 这 样 做, 你 要 求 我 们 尚 未 入 市 之 前, 在 市 场 作 出 谘 询, 我 相 信 这 是 难 倒 我 们, 没 有 办 法 可 以 做 到, 的 确 今 次 是 没 有 做 到。 但 今 次 的 决 定 不 是 即 时 决 定 的, 刚 才 我 已 详 细 地 解 释 给 各 位 听, 在 七 月 底 我 们 已 经 开 始 有 这 种 意 向, 亦 觉 得 有 这 种 需 要, 而 直 至 八 月 中 才 采 取 这 种 行 动, 整 个 过 程 之 中, 我 们 是 反 反 复 复 很 多 深 入 和 探 讨 做 这 件 事。 亦 特 别 谘 询 金 管 局 里 面 对 这 方 面 有 深 入 研 究 的 职 员 而 做 出 来 的。 <P>何 秀 兰 议 员:   (担 心 外 行 充 内 行, 不 去 谘 询 业 界 便 仓 促 做 这 个 决 定, 今 次 的 决 定 是 一 千 二 百 亿, 如 果 是 一 个 公 务 员 工 作 经 验 的 人, 去 做 如 此 重 大 的 决 定, 对 我 们 香 港 其 实 是 否 有 益?) <P>财 政 司 司 长:   当 然, 对 于 我 自 己 的 能 力 的 问 题, 要 回 应 是 很 艰 难 的。 但 外 汇 基 金 法 例 是 清 楚 指 明 我 的 法 定 责 任 是 什 么。 这 事, 无 论 如 何 我 都 一 定 要 负 责, 一 定 要 承 担, 一 定 要 执 行。 过 程 之 中 怎 样, 刚 才 我 已 向 各 位 议 员 解 释, 做 决 定 的 最 后 责 任 是 我, 问 责 亦 归 我, 但 过 程 是 怎 样, 我 是 和 很 多 同 事 一 起 讨 论。 最 后 都 要 一 个 人 负 责, 这 个 负 责 的 人 未 必 一 定 是 行 内 特 别 的 专 家, 如 果 这 样 处 理 的 话, 很 多 事 干 起 来 都 会 很 困 难。 所 以 希 望 议 员 了 解 及 体 谅 到, 是 经 过 法 律 的 正 式 程 序, 赋 予 财 政 司 司 长 的 权 力, 他 不 能 抵 赖, 他 一 定 要 负 责 任, 一 定 要 处 理 这 事。 有 时 他 不 是 航 务 的 专 家, 在 航 海 时, 一 定 要 做 一 些 决 定, 在 法 例 上 是 要 求 他 做 这 事。 有 时 他 不 是 银 行 的 专 家, 在 银 行 法 例 监 管 方 面, 他 有 自 己 的 法 定 责 任, 而 要 履 行 这 事, 很 多 其 他 事 务 亦 一 样。 任 何 在 政 府 里 面 的 人, 由 特 首 开 始, 我 自 己, 政 务 司 司 长 和 其 他 局 长 都 有 本 身 专 责 的 权 力, 不 过, 不 是 日 常 都 要 做 这 些 决 定。 但 我 们 对 整 个 财 经 界、 金 融 界 来 说 是 有 些 认 识 的, 虽 然 有 些 人 认 为 我 们 见 识 肤 浅, 但 我 觉 得 我 们 每 每 都 是 经 一 事, 长 一 智, 每 件 事 都 是 参 详 了 专 家 的 意 见 来 做。 <P>张 文 光 议 员:   (政 府 有 没 有 想 过, 怎 样 去 解 释 它 的 角 色 和 利 益 冲 突? 怎 样 实 现 有 秩 序 离 场? 怎 样 透 过 一 些 独 立 或 者 专 业 的 公 司, 用 商 业 的 原 则, 不 会 享 有 任 何 豁 免 或 者 特 权 去 维 持 这 些 股 票 的 管 理, 而 令 到 更 加 独 立 公 正 地 去 制 定 法 律 去 维 持 这 个 市 场 的 新 秩 序 和 进 行 监 管?) <P>财 政 司 司 长:谢 谢 张 议 员 说 我 们 要 共 同 面 对 这 件 事, 我 们 很 乐 意 这 样 做, 和 各 位 议 员 一 起 去 面 对 这 件 事。 我 们 将 来 法 例 的 草 案, 给 各 位 议 员 省 览 时, 希 望 我 们 能 够 达 到 这 个 目 标。 关 于 政 府 的 角 色 冲 突 和 利 益 冲 突 的 问 题, 整 体 来 说, 架 构 上 和 宪 制 上, 我 们 已 经 分 开 了 有 证 监 会 和 政 府 方 面 分 工 合 作, 而 期 交 所、 联 交 所 (也 有) 自 己 的 管 理, 有 自 己 的 责 任, 大 家 也 知 道 这 些 分 工 是 有 需 要, 亦 保 障 个 别 界 别 的 利 益, 这 件 事 原 则 上 是 没 有 大 的 问 题。 即 使 在 紧 急 的 情 况 下, 好 像 我 们 在 八 月 份 做 这 件 事, 是 不 正 常 的 做 法, 这 个 情 况, 当 然 是 一 个 很 例 外 的 情 况, 是 我 刚 才 所 说, 觉 得 好 严 峻 的 情 况 下 才 做。 我 们 会 怎 样 做 呢? 当 然 我 们 要 很 小 心。 我 刚 才 向 各 位 议 员 报 告 的 时 候 亦 说 过, 我 会 尽 快 在 外 汇 基 金 下, 设 立 一 间 独 立 的 公 司, 用 专 业 的 方 法 管 理, 正 如 张 议 员 所 说, 以 专 业 的 方 法 来 管 理 我 们 今 次 所 购 入 的 证 券, 我 希 望 这 些 证 券 不 会 如 张 议 员 所 说 做 「大 闸 蟹」, 刚 才 我 听 到 市 场 已 经 升 过 了 八 千 点。 我 们 的 股 票 买 入 时 是 六 千 至 七 千 几 点。 我 刚 才 说 这 些 是 香 港 的 资 产, 香 港 人 累 积 的 智 慧, 我 不 相 信 我 们 会 做 「大 闸 蟹」。 最 重 要 的 问 题 是, 我 们 会 尽 量 有 系 统、 有 秩 序 地 离 开 市 场, 但 期 间 便 是 用 专 业 的 方 法 和 避 免 在 有 利 益 冲 突 的 情 况 下 来 管 理 这 笔 资 产。 <P>刘 慧 卿 议 员: (你 可 否 对 我 们 说 不 会 再 在 市 场 花 钱? 政 府 怎 样 使 用 纳 税 人 的 钱, 在 这 件 事 上, 立 法 会 可 否 在 监 管 怎 样 动 用 这 些 金 钱 上 扮 演 一 个 积 极 的 功 能?) <P>财 政 司 司 长: 关 于 我 们 今 次 介 入 这 个 股 票 市 场 所 投 资 的 数 目, 我 很 希 望 尽 快 向 各 位 交 代。 不 过 暂 时 来 说, 大 家 也 知 道, 当 造 市 的 人 未 完 全 离 场 前, 在 事 件 未 稳 定 前, 我 们 这 样 公 布 这 些 资 料, 只 会 帮 了 别 人 而 不 能 帮 我 们 自 己, 我 希 望 议 员 方 面 多 些 谅 解。 而 且 对 于 公 开 和 问 责 方 面, 我 们 很 重 视, 跟 议 员 一 样 的 重 视, 你 见 到 我 们 为 何 在 入 市 的 时 间, 第 一 时 间 在 八 月 十 四 日, 立 即 向 大 众 交 代, 就 证 明 了 我 们 在 政 策 上 和 策 略 上 已 经 说 了 出 来, 但 数 量 方 面, 我 希 望 议 员 多 一 点 忍 耐, 给 我 们 多 些 时 间, 当 这 些 人 离 场 后, 我 会 尽 量 作 更 全 面 性 的 交 代。 还 有 一 件 事, 刘 议 员 说, 我 们 应 该 不 再 动 用 这 些 钱。 我 同 意 你 的 说 话, 我 们 不 想 再 在 这 股 票 市 场 作 一 些 不 需 要 的 投 资。 我 们 今 次 跟 进 的 工 夫, 特 别 是 在 金 管 局 所 作 的 技 术 性 的 调 整, 和 黎 太 向 各 位 解 释 我 们 的 策 略, 完 全 是 针 向 一 件 事, 就 是 我 们 希 望 不 需 要 香 港 特 别 行 政 区 政 府 介 入 这 些 商 业 市 场, 所 以 我 很 希 望 这 些 情 况 会 减 少。 至 于 可 否 完 全 不 做 呢? 我 不 可 以 作 一 个 绝 对 的 铁 证, 因 为 要 根 治 这 个 问 题, 并 非 香 港 本 身 的 能 力 可 以 全 部 做 得 到, 要 彻 底 令 某 部 分 炒 家 不 能 在 市 场 操 控 和 造 市, 是 需 要 一 个 国 际 监 管 的 协 议。 在 这 方 面, 我 们 在 国 际 层 面 正 在 做 很 多 的 工 夫, 但 在 此 之 前, 而 市 场 已 全 面 国 际 化, 我 们 必 定 要 保 留 我 们 的 剩 余 权 力。 假 如 我 们 没 有 这 些 权 力, 我 们 可 能 会 任 人 鱼 肉 香 港 人 的 利 益, 我 觉 得 我 们 不 能 这 样。 不 过, 我 们 的 目 标 很 清 楚, 我 们 不 想 介 入 金 融 市 场, 也 不 想 介 入 特 别 是 股 票 市 场, 但 我 们 一 定 要 维 持 纪 律 和 系 统, 使 投 资 者 能 得 到 担 保, 长 远 来 说 不 用 顾 虑。 立 法 会 发 挥 一 个 很 好 的 功 能, 角 色 很 重 要, 所 以 立 法 会 (的 功 能) 已 经 在 法 律 上 写 得 很 清 楚, 它 的 权 力 在 那 处, 基 本 法 亦 厘 定 了 这 件 事。 财 政 司 司 长 在 有 关 法 例 上 的 角 色 亦 写 得 很 清 楚, 这 些 是 立 法 机 关 厘 定 的, 我 们 会 根 据 这 些 指 标 办 事。 <P>刘 慧 卿 议 员: (你 们 为 何 不 先 问 立 法 会? 你 说 要 炒 家 离 场, 如 果 炒 家 不 离 场 又 怎 样? 他 们 何 时 才 离 场? 他 们 又 会 否 再 回 来, 这 千 多 亿 的 支 出 为 了 什 么, 能 达 到 什 么 目 的?) <P>财 政 司 司 长: 我 很 多 谢 刘 议 员 给 我 的 训 令。 (我 们) 入 市 金 融 市 场 的 确 相 当 敏 感。 假 如 在 未 入 市 前, 或 在 进 行 保 卫 港 元 的 行 动 前, 每 一 步 都 要 谘 询 立 法 会, 如 刘 议 员 说 要 开 会 才 可 作 决 定, 有 多 方 面 意 见 时, 贼 人 已 经 临 门 了。 出 现 这 个 情 况 后 才 做 的 话, 我 相 信 可 能 带 来 其 他 的 困 难 也 说 不 定。 就 我 所 知, 刘 议 员 所 说 的 方 法, 我 未 曾 见 过 有 其 他 地 区、 其 他 政 府 和 先 进 的 金 融 体 系 使 用 这 个 办 法。 但 我 亦 都 很 多 谢 刘 议 员 支 持 我 们 联 系 汇 率 的 工 作。 在 这 方 面, 我 们 可 以 分 享 到 什 么 资 料, 我 会 尽 量 去 做, 是 要 视 乎 香 港 的 整 体 利 益, 我 们 制 度 上 可 以 作 出 修 改, 我 也 可 以 考 虑, 但 是 最 重 要 的 是 我 们 目 标 是 这 样, 我 们 的 做 法 就 必 定 要 有 一 种 规 限。 <P>李 华 明 议 员: (政 府 这 场 仗 我 们 不 知 是 否 赢 了, 但 起 码 在 舆 论、 传 媒 方 面 做 到 我 们 每 一 个 议 员 都 不 能 反 对, 要 是 说 反 对 便 肯 定 被 社 会 责 骂。 政 府 在 公 关 方 面 做 得 很 好。 我 想 问, 作 为 一 个 小 市 民, 政 府 以 千 亿 元 入 市, 先 前 说 要 炒 家 夹  尾 巴 落 荒 而 逃, 到 最 后 却 说 只 希 望 他 们 不 会 得 逞, 希 望 有 一 个 健 康 市 场; 到 现 时 又 说 他 们 不 是 炒 家 而 是 造 市 者, 究 竟 他 们 是 什 么 人? 政 府 究 竟 知 不 知 道 他 们 是 什 么 人? 是 否 如 报 章 说 的 那 两 个 基 金 呢?) <P>财 政 司 司 长: 这 些 造 市 的 所 谓 「对 」 基 金, 其 手 法 是 多 样 化 的, 多 是 透 过 并 非 本 地 而 是 透 过 他 们 纽 约、 伦 敦、 瑞 士 的 银 行, 再 透 过 其 他 地 区, 再 到 达 香 港 银 行; 亦 以 多 种 名 义, 可 能 以 公 司 名 义, 或 以 British Virgin Island 的 招 牌。 但 是 我 只 觉 得, 今 次 (他 们) 攻 击 港 元 与 汇 市 的 行 动, 特 别 是 在 期 货 市 场 的 行 动 是 有 系 统 和 有 组 织 的, 有 长 远 计 划 铺 路。 他 们 拥 有 庞 大 的 基 金, 以 相 当 有 系 统 的 做 法 和 由 专 业 人 士 去 做。 <P>李 华 明 议 员: 是 否 有 本 地 公 司 配 合? <P>财 政 司 司 长: 正 如 我 刚 才 向 各 位 议 员 的 解 释, 他 们 需 要 天 时 地 利, 我 已 解 释 我 们 的 环 境 有 助 于 他 们 的 活 动。 当 然 他 们 在 香 港 做 买 卖 必 须 透 过 本 地 的 银 行 和 公 司, 这 本 是 无 可 厚 非。 香 港 公 司 开 门 做 生 意, 是 一 定 要 做 生 意 的。 但 是 我 们 要 打 击 的 并 非 是 本 地 公 司 或 在 香 港 做 生 意 的 外 国 公 司。 最 重 要 的 是 有 没 有 做 一 些 会 助 长 在 香 港 造 市 的 活 动。 今 次 金 融 管 理 局 所 作 的 手 段 和 技 术 性 的 调 整, 相 信 会 使 我 们 更 容 易 掌 握 这 方 面 的 消 息。 <P>李 卓 人 议 员: (要 追 究 为 何 政 府 需 动 用 正 如 外 界 所 说 的 千 多 亿 入 市, 还 要 延 续 至 今? 为 什 么 炒 家 们 可 以 予 取 予 携? 为 什 么 不 在 较 早 时 堵 塞 漏 洞?) <P>财 政 司 司 长: 刚 才 我 已 说 清 楚, 我 们 做 每 一 件 事 都 要 付 出 代 价。 付 出 代 价 前 要 考 虑 正 面 和 负 面 效 益。 我 们 需 要 有 充 分 理 据 才 去 做。 我 想 作 为 政 策 草 拟 者, 我 们 必 须 做 这 方 面 的 基 本 工 夫。 <P>关 于 是 否 快 或 慢 的 问 题, 这 件 事 已 争 辩 了 很 久, 但 仍 没 有 什 么 结 果。 但 是, 希 望 李 议 员 了 解, 现 时 香 港 面 对 的 是 外 来 造 成 的 局 面, 是 香 港 很 久 未 见 过, 而 世 界 上 也 未 曾 见 过 的。 其 (威 力) 巨 大 处, 已 推 毁 很 多 政 府, 使 很 多 制 度 完 全 毁 灭。 这 件 事 仍 未 得 了 结, 且 有 蔓 延 趋 势。 不 单 只 香 港 政 府、 专 家、 官 员, 连 同 我 在 内 觉 得 诧 异, 全 世 界 都 觉 得 诧 意。 根 本 上, 全 球 性 的 经 济 发 展, 与 四、 五 年 前 墨 西 哥 的 发 展 情 况 已 经 非 常 不 同, 没 有 区 限 性、 局 部 性 、 控 制 性。 我 们 作 为 国 际 金 融 市 场 需 要 以 尽 量 开 放 的 形 式 办 事 时, 在 此 情 况 下 一 定 会 有 被 人 滥 用 的 情 况 存 在, 这 是 无 办 法 的。 在 做 这 件 事 时, 我 们 是 衡 量 过 其 好 处 和 坏 处。 所 以, 我 们 觉 得 今 次 是 必 须 要 做 的。 是 否 可 以 用 其 他 方 法? 正 如 我 解 释 过, 许 多 事 情 并 非 完 全 在 意 料 之 内。 但 (最 重 要 的 是) 当 每 一 件 事 发 生 时, 我 们 都 有 适 当 的 应 变 措 施, 作 出 回 应。 相 信 香 港 所 做 的 较 其 他 地 方 已 是 先 人 一 步、 快 人 一 步, 甚 至 说 不 一 定 有 人 会 说 我 们 做 得 太 快。 希 望 李 议 员 谅 解, 我 们 当 前 面 对 的 问 题 相 当 复 杂, 不 是 香 港 人 和 财 金 官 员 可 以 完 全 掌 握。 但 是 在 这 范 围 内, 我 们 做 所 能 做 的 事 情, 最 重 要 的, 就 是 如 何 加 强 香 港 人 的 信 心。 任 何 事 如 有 更 改, 必 然 会 有 其 负 面 的 影 响。 你 能 看 到 这 情 况, 当 我 们 有 任 何 议 案 时, 希 望 得 到 李 议 员 全 面 的 支 持。 如 你 们 还 觉 得 已 经 是 迟 时, 希 望 你 更 能 尽 快 批 准 这 些 更 改。 <P>李 卓 人 议 员: (如 能 提 早 实 施 七 招, 是 否 需 要 入 市?) <P>财 政 司 司 长: 刚 才 我 所 说 只 是 一 部 份。 任 志 刚 先 生 上 星 期 所 提 的, 只 是 其 中 一 部 份。 现 时 我 们 所 说 的 是 跨 市 双 边 操 控 活 动, 是 要 多 方 面 做 的。 有 些 正 如 黎 太 所 述 是 要 修 改 法 例, 不 能 简 单 处 理。 <P>黄 宜 弘 议 员: (假 如 有 人 在 纽 约 交 易 所 进 行 抛 空 股 票, 其 指 令 并 非 与 其 他 正 常 的 一 起 做, 会 有 另 外 一 个 board处 理。 要 有 买 家 才 可 以 对 赌, 选 择 权 在 买 家 身 上, 但 香 港 并 非 如 此。) <P>署 理 财 经 事 务 局 局 长: 现 时 我 们 用 的 是 完 全 自 动 对 盘 系 统 和 中 央 交 收, 接 沽 空 盘 的 人 在 交 收 时 并 非 真 的 与 对 方 对 盘, 因 为 中 央 结 算 已 做 中 间 人。 因 此, 不 会 特 别 构 成 因 为 盲 目 承 接 一 宗 沽 空 盘 后, 如 对 方 没 有 货 交 时, 便 变 成 很 惨。 此 类 问 题 在 中 央 交 收 时 不 会 产 生。 相 反 来 说, 又 可 不 可 以 索 性 不 准 人 抛 空? 如 不 能 抛 空 则 会 有 如 你 所 说 第 二 个 市 场, 在 市 场 以 外, 有 人 专 门 做 对 赌。 这 种 做 法 始 终 需 要 在 现 货 市 场 和 期 货 市 场 做 对 冲。 如 将 这 些 活 动 完 全 隔 离, 而 不 能 与 大 市 活 动 冲 淡, 对 市 场 是 否 好 的 办 法? 我 并 非 专 家, 我 会 交 给 证 监 会 研 究, 是 否 用 那 模 式 会 更 好。 表 面 看 来 未 必 是 适 合 香 港 的 办 法。 但 有 一 个 长 远 的 解 决 方 法, 就 是 如 有 人 在 外 围 抛 空, 始 终 可 以 凭 监 管 托 管 人 和 股 票 借 贷 制 度, 以 提 高 透 明 度 和 公 平 性。 <P>丁 午 寿 议 员: (我 们 支 持 政 府 为 维 护 联 系 汇 率 所 作 的 一 系 列 的 行 动, . . . 但 很 可 惜 在 上 周, T+ 2得 不 到 实 施, 使 大 部 分 市 民 失 望。 为 何 有 关 部 门 不 知 道 政 府 在 做 什 么? 我 觉 得 惩 罚 那 些 恶 意 抛 空 者 由 一 万 元 加 到 十 万 元 仍 然 太 少, 应 该 提 高 罚 款 和 监 禁。) <P>财 政 司 司 长: 当 然 法 案 上 的 修 改 需 要 交 到 立 法 会 辩 论 和 批 准。 对 于 丁 议 员 的 意 见, 我 们 会 充 分 考 虑, 为 议 员 和 我 们 都 认 为 可 行 的 做 法, 达 致 共 识。 <P>田 北 俊 议 员: (政 府 是 否 应 首 先 统 筹 跨 市 场 监 察 小 组, 和 修 改 例, 赋 与 行 政 长 官 更 大 的 权 力, 然 后 推 出 七 招, 再 进 行 入 市 活 动? 政 府 何 时 可 以 做 到 首 两 项 工 作?) <P>财 政 司 司 长: 首 先 多 谢 田 议 员 的 支 持。 我 想 清 楚 知 道 田 议 员 所 指 的 第 五 和 第 六 段 属 于 那 份 文 件? <P>田 北 俊 议 员: 是 放 在 我 们 桌 上 的 财 经 事 务 局 文 件 第 六 页。 <P>财 政 司 司 长: 我 想 黎 太 很 乐 意 回 答 这 个 问 题。 <P>署 理 财 经 事 务 局 局 长: 主 席, 这 两 项 是 我 们 正 进 行 的 工 作。 第 五 点 研 究 是 否 需 要 修 例 才 可 让 特 首 有 绝 对 和 马 上 的 权 力, 发 出 这 些 指 令。 我 们 在 过 去 的 三 个 星 期 已 谘 询 多 方 的 法 律 意 见, 我 们 希 望 很 快 会 得 出 结 论, 知 道 是 否 有 这 个 需 要。 假 如 有 的 话, 我 们 会 向 立 法 会 (汇 报), 但 实 际 上 需 要 多 少 天, 我 现 时 不 能 答 你。 第 二 就 是 跨 市 场 的 趋 势 监 察 小 组, 我 们 会 马 上 筹 组 开 会。 <P>蔡 素 玉 议 员: (为 何 政 府 不 早 些 提 出 修 改 法 例? 政 府 何 不 采 取 更 有 效 的 措 施, 杜 绝 炒 家 将 来 继 续 在 港 造 市? 可 否 给 我 们 一 个 较 清 晰 的 时 间 表?) <P>财 政 司 司 长: 有 关 我 们 的 措 施, 主 席 你 刚 才 说 得 很 好, 我 们 认 为 要 因 事 制 宜, 不 能 马 上 把 所 有 的 东 西, 以 大 石 压 死 蟹 的 方 式, 把 市 场 践 踏, 这 样 做 法 并 不 符 合 我 们 的 长 远 利 益。 不 过, 假 如 蔡 议 员 有 什 么 宝 贵 的 意 见, 或 认 为 我 们 的 措 施 不 足, 有 些 措 施 应 该 推 行, 我 们 会 很 小 心 聆 听。 我 们 可 以 在 研 究 法 例 草 案 时, 再 提 出 来 讨 论。 我 们 认 为 现 时 所 采 取 的 措 施, 是 多 方 面 的 措 施。 金 管 局 方 面 和 黎 太 所 介 绍 二 十 多 项 的 措 施, 假 如 蔡 议 员 仍 认 为 当 中 不 完 整, 我 们 很 希 望 多 听 蔡 议 员 和 其 他 议 员 的 意 见。 特 别 你 刚 才 关 心 期 交 所 电 子 买 卖 交 易 的 问 题, 我 知 道 他 们 已 决 定 这 样 做, 已 没 有 多 大 的 异 议, 只 是 安 装 和 配 套 的 问 题, 需 要 多 一 些 时 间, 或 许 黎 太 在 这 方 面 有 更 具 体 的 资 料。 <P>署 理 财 经 事 务 局 局 长: 期 交 所 的 电 子 化 系 统 方 面, 他 们 去 年 向 临 立 会 的 财 务 小 组 解 释 时 表 示, 希 望 可 于 明 年 底 推 行。 当 时 大 家 都 认 为 这 样 太 慢 了, 为 何 要 花 上 这 么 长 的 时 间 呢? 正 如 财 政 司 司 长 所 说, 他 们 的 硬 件 安 装、 配 套 设 计 以 及 其 他 会 员 的 训 练 安 排, 是 需 要 一 些 时 间。 但 最 近 我 知 道, 期 交 所 主 席 已 承 诺 把 所 需 的 时 间 再 度 缩 短。 我 刚 才 所 公 布 的 其 中 一 项 措 施, 就 是 要 他 们 落 实 一 个 更 早 的 日 子, 可 以 指 出 甚 时 候 可 以 做 到。 当 然, 我 们 所 说 的 是 要 完 全 把 现 时 这 个 公 开 喊 价 的 交 易 模 式, 变 成 完 全 电 子 化。 我 们 不 希 望 这 是 一 个 仓 卒 的 决 定, 当 仍 未 测 试 清 楚 和 未 能 做 到 时, 便 宣 布 不 要 交 易 大 堂, 只 单 靠 电 脑, 然 后 才 发 觉 我 们 需 要 停 市, 这 是 我 们 绝 对 不 能 接 受 的 情 况。 </TD> </TR> </TABLE> <br> <br> </div> <div style="text-align:center; margin:0 auto;"> </div> </div> </TD> <TD style="width:1px;"></TD></TR> <TR> <TD style="width:5px;height:2px;"><IMG height=1 src="/fsb/images/spacer.gif" alt=""></TD> <TD valign="top" colspan="2" style="text-align:left;height:3px;"><IMG height=3 src="../../images/topimages/botdot.jpg" width=580 alt="dot dot"></TD> <TD style="width:1px;"></TD></TR> <TR> <TD style="width:5px;height:15px;"><IMG height=1 src="/fsb/images/spacer.gif" alt=""></TD> <TD style="width:301px;height:15px;background-color:#ffffff;"><B><span class="fsize1">2003</span></B><span class="fsize1"><IMG height=11 src="../../images/copy.gif" width=12 alt="Copyright">| <B><A href="../../notice/index.htm">重要告示</A></B></span></TD> <TD style="text-align:right;width:301px;height:15px;background-color:#ffffff;"><span class="fsize1">修订日期: 2004年2月19日 </span></TD> <TD style="width:1px;height:15px;"></TD> </TR></TBODY></TABLE> </TD> </TR> </TBODY> </TABLE> <!-- END CONTENT --><!--NO INDEX START--><!--NO INDEX END--></BODY></HTML> """ soup = BeautifulSoup(html_doc, "lxml") print '---------------------------------' try: con1 = soup.find('div', id = 'content-left') con2 = soup.find('td', class_ = 'header') con3 = soup.find('td', width = '579') if con1: print '+++++++++++++++++++' all_p = con1.get_text().strip() elif con2: print '-------------------' all_p = con2.get_text().strip() elif con3: print '///////////////////' all_p = con3.get_text().strip() all_p = all_p.encode('GBK', 'ignore') all_p = re.sub(r'\n', "", all_p) all_p = re.sub(r'\t', "", all_p) content = all_p print all_p except: print '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%' print '---------------------------------'
995,579
ae3f7b0c1b2abc91de8c764054edb3960114612b
nums = [val for val in range(9)] print(nums) class stack(): def __init__(self): self.data = [] def push(self,item): self.data.append(item) def pop(self): return self.data.pop() def __len__(self): return len(self.data) def reverse(sequence): s = stack() revers = [] for val in sequence: s.push(val) while s.__len__() != 0: revers.append(s.pop()) return "".join(revers) print(reverse("Gopi krishna"))
995,580
3e747aa4d0b3f351e9b81f6103661be8bfe9ac7f
import math import os import random import re import sys # Complete the triplets function below. def triplets(a, b, c): #triplet pairs cond a<=b, b>=c a.sort() b.sort() c.sort() c=0 for t1 in a: for t2 in b: if t1<=t2: for t3 in c: if t3>=t2: c = c+1 return c if __name__ == '__main__': #fptr = open(os.environ['OUTPUT_PATH'], 'w') print "Enter the lengths of three arrays" lenaLenbLenc = input().split() lena = int(lenaLenbLenc[0]) lenb = int(lenaLenbLenc[1]) lenc = int(lenaLenbLenc[2]) print "Enter elements for first array" arra = list(map(int, input().rstrip().split())) print "Enter elements for second array" arrb = list(map(int, input().rstrip().split())) print "Enter elements for third array" arrc = list(map(int, input().rstrip().split())) ans = triplets(arra, arrb, arrc) print ans #fptr.write(str(ans) + '\n') #fptr.close()
995,581
7e25f3c6495bfb5e9d1f936ca71c1cb4ac30f24b
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return root queue = deque([root]) level_order = [] while queue: # l keeps tracks of how many nodes in queue at a certain level because only immediate children will be in queue # level_indicator increments every time a node is processed # when l == level_indicator, it means all nodes in a level are processed l = len(queue) level_indicator = 0 level = [] while level_indicator < l: node = queue.popleft() level.append(node.val) level_indicator += 1 if node.left: queue.append(node.left) if node.right: queue.append(node.right) level_order.append(level) return level_order
995,582
3c9405cd158627e712c6eb5d3d812302d60b6d46
import datetime import io import json import os import threading from PIL import Image, ImageDraw, ImageFont from azure.cognitiveservices.vision.face.models import FaceAttributeType from msrest.authentication import CognitiveServicesCredentials from azure.cognitiveservices.vision.face import FaceClient key = "<ENTER KEY>" endpoint = "<ENTER ENDPOINT>" # Authentication with FaceClient. face_client = FaceClient(endpoint, CognitiveServicesCredentials(key)) IMAGES_PATH = "../media/images" # Convert width height to a point in a rectangle def getRectangle(face_dictionary): rect = face_dictionary.face_rectangle left = rect.left top = rect.top right = left + rect.width bottom = top + rect.height return (left, top), (right, bottom) def drawFaceRectangles(img, detected_faces, name): # For each face returned use the face rectangle and draw a red box. print('Drawing rectangle around face... see popup for results.') draw = ImageDraw.Draw(img) for face in detected_faces: dimensions = getRectangle(face) y = dimensions[0][1] draw.rectangle(dimensions, outline='white') emotion_json = json.loads(json.dumps(face.face_attributes.emotion.__dict__)) del emotion_json['additional_properties'] font = ImageFont.truetype("../resources/Roboto-Bold.ttf", 12) draw.text((dimensions[0][0], y), face.face_attributes.gender.upper(), align="left", font=font, fill="red") y += 12 for emotion in emotion_json: if emotion_json[emotion] != 0.0: draw.text((dimensions[0][0], y), emotion, align="left", font=font, fill="yellow") y += 12 # Save the img in a folder. name_split = name.split(".") img.save("../results\\emotionsResults\\resultado_" + name_split[0] + ".png") # Display the image in the default image browser. img.show() def startAnalyzeEmotions(files): # Path from image to analyze. for f in files: img = Image.open('{0}/{1}'.format(IMAGES_PATH, f)) # Output let us to detect an image from a folder. output = io.BytesIO() img.save(output, format='JPEG') # or another format output.seek(0) # Analyze the image with azure. detected_faces = face_client.face.detect_with_stream(image=output, detection_model='detection_01', return_face_attributes=[FaceAttributeType.emotion, FaceAttributeType.gender]) if not detected_faces: raise Exception('No face detected from image {}'.format(img)) # Uncomment this to show the face rectangles. drawFaceRectangles(img, detected_faces, f) if __name__ == "__main__": start_time = datetime.datetime.now() files = os.listdir(IMAGES_PATH) print(len(files)) if len(files) >= 4: lista1 = [] lista2 = [] for i in range(len(files)): if i % 2 == 0: lista1.append(files[i]) else: lista2.append(files[i]) thread1 = threading.Thread(target=startAnalyzeEmotions, args=(lista1,)) thread2 = threading.Thread(target=startAnalyzeEmotions, args=(lista2,)) thread1.start() thread2.start() thread1.join() thread2.join() # Api call for the text analysis else: startAnalyzeEmotions(files) end_time = datetime.datetime.now() print('Duration: {}'.format(end_time - start_time))
995,583
526cc9978923822025240be9c115d16fd135c6b1
'''from tastypie.resources import ModelResource from fuel.models import Vechicle from django.core.serializers import json from django.utils import simplejson class CarDataResource(ModelResource): class Meta: queryset = Cars.objects.all() allowed_methods = ['get'] class ModelResource(ModelResource): class Meta: # queryset = Cars.objects # '''
995,584
f6c79522f46a9ddf1e27402ba71261509b9c11d3
import numpy as np def sigmoid(x): x[np.where(x < -60)] = -60 x[np.where(x > 60)] = 60 return 1 / (1 + np.exp(-x)) def relu(x): return np.maximum(x, 0)
995,585
7018f34642e21520856ea328c55f7f7e771f7d62
for num in range (1,100+1): if num>1: for j in range(2,num): if(num % j==0): break else: print (num)
995,586
3789cfda02146a79f1e2e82afc6d0c2e2170ad28
""" UI class. Calls between program modules ui -> service -> entity ui -> entity """ from services.service import ListComplexNr, FilterEndPoint, FilterStartPoint, start_tests from domain.entity import Complex, RealPartException, ImagPartException import random from termcolor import colored class UI: def __init__(self): self._commands = {'+': self.add_number_ui} self._list = ListComplexNr() @property def complex_list(self): return self._list def add_number_ui(self): real = input("Insert real unit: ") imaginary = input("Insert imaginary unit: ") try: number = Complex(real, imaginary) self._list.add_number(number) except RealPartException or ImagPartException as val_error: print(val_error) def show_ui(self): comp_list = self._list.get_all() for number in comp_list: print(number) def filter_ui(self): start = input("Insert start point: ") end = input("Insert end point: ") try: self._list.filterr(start, end) except FilterStartPoint or FilterEndPoint as val_error: print(val_error) def undo_ui(self): self._list.undo() def random_number(self): for i in range(10): real = random.randint(-20, 20) imaginary = random.randint(-20, 20) number = Complex(real, imaginary) self._list.add_random_number(number) self._list.add_to_history() @staticmethod def print_menu(): """ Print out the menu """ print("\nMenu:") print("\t" + colored('+', 'red') + " for adding a complex number") print("\t" + colored('s', 'red') + " for showing the list of all complex numbers") print("\t" + colored('f', 'red') + " for filtering the list") print("\t\t-the new list will contain only the numbers between indices `start` and `end`") print("\t" + colored('u', 'red') + " to undo the last operation") print("\t" + colored('x', 'red') + " to close the calculator") def start(self): done = True self.print_menu() self.random_number() start_tests() while done: _command = input("\n>Command: ").strip().lower() if _command == "+": self.add_number_ui() elif _command == "s": self.show_ui() elif _command == "f": self.filter_ui() elif _command == "u": self.undo_ui() elif _command == "x": print("Goodbye!") done = False else: print("Bad command!") if __name__ == '__main__': ui = UI() ui.start()
995,587
8415b19daa7c7d31eab9d55e6da497f9abbdc662
# Copyright (c) 2017 roseengineering import os, sys # bluezero import dbus from gi.repository import GObject from bluezero import dbus_tools from bluezero import constants from bluezero import adapter from bluezero import advertisement from bluezero import localGATT from bluezero import GATT # mqtt import paho.mqtt.client as mqtt # characteristics MQTT_SRVC = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E' MQTT_RX_CHRC = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E' MQTT_TX_CHRC = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E' class Receive(localGATT.Characteristic): def __init__(self, service, chrc_id, client, newline): self.newline = newline client.on_message = self.on_message localGATT.Characteristic.__init__( self, 1, chrc_id, service, '', False, ['read', 'notify']) def on_message(self, client, userdata, msg): print('on_message: [%s]: [%s]' % (msg.topic, msg.payload)) if self.props[constants.GATT_CHRC_IFACE]['Notifying']: value = '%s %s' % (msg.topic, msg.payload.decode()) if self.newline: value = value.rstrip() + '\n' print('notify: [%s]' % value) value = dbus.ByteArray([ dbus.Byte(n) for n in value.encode() ]) d = { 'Value': value } self.PropertiesChanged(constants.GATT_CHRC_IFACE, d, []) def ReadValue(self, options): return dbus.ByteArray([]) def StartNotify(self): print('start notify') self.props[constants.GATT_CHRC_IFACE]['Notifying'] = True def StopNotify(self): print('stop notify') self.props[constants.GATT_CHRC_IFACE]['Notifying'] = False class Transmit(localGATT.Characteristic): def __init__(self, service, chrc_id, client): self.client = client localGATT.Characteristic.__init__( self, 2, chrc_id, service, '', False, ['write']) def WriteValue(self, value, options): client = self.client value = dbus.ByteArray(value).decode() print('writevalue: [%s]' % value) topic, sep, payload = value.partition(' ') if sep == ' ': client.publish(topic, payload) else: print('subscribing to', topic) client.unsubscribe('#') client.subscribe(topic) # functions def create_mqtt_proxy(client, newline): bus = dbus.SystemBus() app = localGATT.Application() srv = localGATT.Service(1, MQTT_SRVC, True) receive = Receive(srv, MQTT_RX_CHRC, client, newline) transmit = Transmit(srv, MQTT_TX_CHRC, client) app.add_managed_object(srv) app.add_managed_object(receive) app.add_managed_object(transmit) srv_mng = GATT.GattManager(adapter.list_adapters()[0]) srv_mng.register_application(app, {}) dongle = adapter.Adapter(adapter.list_adapters()[0]) if not dongle.powered: # bring hci0 up if down dongle.powered = True advert = advertisement.Advertisement(1, 'peripheral') advert.service_UUIDs = [MQTT_SRVC] ad_manager = advertisement.AdvertisingManager(dongle.address) ad_manager.register_advertisement(advert, {}) def on_connect(client, userdata, flags, rc): print("Connected to mqtt with result code %d" % rc) if rc == 0: client.subscribe('#') def create_client(hostname, port, newline): client = mqtt.Client() create_mqtt_proxy(client, newline) client.loop_start() client.on_connect = on_connect client.connect(hostname, port) return client def main(arg): newline = False global MQTT_SRVC, MQTT_RX_CHRC, MQTT_TX_CHRC while arg: if arg[0] == '-n': newline = True arg = arg[1:] else: break hostname = arg[0] if len(arg) > 0 else '127.0.0.1' port = int(arg[1]) if len(arg) > 1 else 1883 client = create_client(hostname, port, newline) try: dbus_tools.start_mainloop() except: print('stopping...') client.loop_stop() if __name__ == '__main__': main(sys.argv[1:])
995,588
1386fbaea5834169575af940c6eaeb95b7f5741a
poly = { 1: {"id": 1, "hasBlock": False, "hasConcave": False, "hasMirrored": False, "count": 3, "form": [(0, 0), (0, 1), (1, 0)]}, 2: {"id": 2, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 4, "form": [(0, 0), (0, 1), (1, 0), (2, 0)]}, -2: {"id": -2, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 4, "form": [(0, 0), (0, 1), (-1, 0), (-2, 0)]}, 3: {"id": 3, "hasBlock": False, "hasConcave": False, "hasMirrored": False, "count": 4, "form": [(0, 0), (0, 1), (1, 1), (0, 2)]}, 4: {"id": 4, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 5, "form": [(0, 0), (-1, 0), (0, -1), (0, 1), (1, 1)]}, -4: {"id": -4, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 5, "form": [(0, 0), (1, 0), (0, -1), (0, 1), (-1, 1)]}, 5: {"id": 5, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 5, "form": [(0, 0), (1, 0), (1, 1), (1, 2), (1, 3)]}, -5: {"id": -5, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 5, "form": [(0, 0), (-1, 0), (-1, 1), (-1, 2), (-1, 3)]}, 6: {"id": 6, "hasBlock": True, "hasConcave": False, "hasMirrored": True, "count": 5, "form": [(0, 0), (0, 1), (0, 2), (-1, 1), (-1, 2)]}, -6: {"id": -6, "hasBlock": True, "hasConcave": False, "hasMirrored": True, "count": 5, "form": [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2)]}, 7: {"id": 7, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 5, "form": [(0, 0), (0, 1), (1, 1), (1, 2), (1, 3)]}, -7: {"id": -7, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 5, "form": [(0, 0), (0, 1), (-1, 1), (-1, 2), (-1, 3)]}, 8: {"id": 8, "hasBlock": False, "hasConcave": False, "hasMirrored": False, "count": 5, "form": [(0, 0), (0, 1), (0, 2), (-1, 2), (1, 2)]}, 9: {"id": 9, "hasBlock": False, "hasConcave": True, "hasMirrored": False, "count": 5, "form": [(0, 0), (1, 0), (1, 1), (-1, 0), (-1, 1)]}, 10: {"id": 10, "hasBlock": False, "hasConcave": False, "hasMirrored": False, "count": 5, "form": [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2)]}, 11: {"id": 11, "hasBlock": False, "hasConcave": False, "hasMirrored": False, "count": 5, "form": [(0, 0), (1, 0), (1, 1), (2, 1), (2, 2)]}, 12: {"id": 12, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 5, "form": [(0, 0), (1, 0), (1, 1), (1, -1), (1, -2)]}, -12: {"id": -12, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 5, "form": [(0, 0), (-1, 0), (-1, 1), (-1, -1), (-1, -2)]}, 13: {"id": 13, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-4, 0), (0, 1)]}, -13: {"id": -13, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-4, 0), (0, -1)]}, 14: {"id": 14, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-4, 0), (-1, 1)]}, -14: {"id": -14, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-4, 0), (-1, -1)]}, 15: {"id": 15, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, -1), (-2, -1), (-3, -1), (-4, -1), (-1, 0)]}, -15: {"id": -15, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 1), (-2, 1), (-3, 1), (-4, 1), (-1, 0)]}, 16: {"id": 16, "hasBlock": True, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (1, 0), (2, 0), (3, 0), (2, 1), (3, 1)]}, -16: {"id": -16, "hasBlock": True, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (1, 0), (2, 0), (3, 0), (2, -1), (3, -1)]}, 17: {"id": 17, "hasBlock": False, "hasConcave": True, "hasMirrored": True, "count": 6, "form": [(0, 0), (1, 0), (2, 0), (3, 0), (1, 1), (3, 1)]}, -17: {"id": -17, "hasBlock": False, "hasConcave": True, "hasMirrored": True, "count": 6, "form": [(0, 0), (1, 0), (2, 0), (3, 0), (1, -1), (3, -1)]}, 18: {"id": 18, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-3, 1), (-3, 2)]}, -18: {"id": -18, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-3, -1), (-3, -2)]}, 19: {"id": 19, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-2, 1), (-2, 2)]}, -19: {"id": -19, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-2, -1), (-2, -2)]}, 20: {"id": 20, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-3, 1), (-2, -1)]}, -20: {"id": -20, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-3, -1), (-2, 1)]}, 21: {"id": 21, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-3, 1), (-1, -1)]}, -21: {"id": -21, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-3, -1), (-1, 1)]}, 22: {"id": 22, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 1), (-2, 1), (-2, 2)]}, -22: {"id": -22, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, -1), (-2, -1), (-2, -2)]}, 23: {"id": 23, "hasBlock": False, "hasConcave": True, "hasMirrored": True, "count": 6, "form": [(0, 0), (1, -1), (2, -1), (3, -1), (1, 0), (3, 0)]}, -23: {"id": -23, "hasBlock": False, "hasConcave": True, "hasMirrored": True, "count": 6, "form": [(0, 0), (1, 1), (2, 1), (3, 1), (1, 0), (3, 0)]}, 24: {"id": 24, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, -1), (-3, 1), (-2, 0), (-2, 1)]}, -24: {"id": -24, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 1), (-3, -1), (-2, 0), (-2, -1)]}, 25: {"id": 25, "hasBlock": True, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, -1), (-1, 1), (-2, 0), (-2, 1)]}, -25: {"id": -25, "hasBlock": True, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 1), (-1, -1), (-2, 0), (-2, -1)]}, 26: {"id": 26, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (1, 0), (0, -1), (-1, 0), (-1, 1), (-2, 1)]}, -26: {"id": -26, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (1, 0), (0, 1), (-1, 0), (-1, -1), (-2, -1)]}, 27: {"id": 27, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 2), (-2, 1), (-2, 2)]}, -27: {"id": -27, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, -2), (-2, -1), (-2, -2)]}, 28: {"id": 28, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (0, -2), (0, -1), (-1, 0), (-1, 1), (-2, 1)]}, -28: {"id": -28, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (0, -2), (0, -1), (1, 0), (1, 1), (2, 1)]}, 29: {"id": 29, "hasBlock": False, "hasConcave": True, "hasMirrored": True, "count": 6, "form": [(0, 0), (0, -1), (1, -1), (2, -1), (0, 1), (2, 0)]}, -29: {"id": -29, "hasBlock": False, "hasConcave": True, "hasMirrored": True, "count": 6, "form": [(0, 0), (0, -1), (-1, -1), (-2, -1), (0, 1), (-2, 0)]}, 30: {"id": 30, "hasBlock": False, "hasConcave": True, "hasMirrored": True, "count": 6, "form": [(0, 0), (0, -1), (1, -1), (2, -1), (0, -2), (2, 0)]}, -30: {"id": -30, "hasBlock": False, "hasConcave": True, "hasMirrored": True, "count": 6, "form": [(0, 0), (0, 1), (1, 1), (2, 1), (0, 2), (2, 0)]}, 31: {"id": 31, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, -1), (-1, 0), (1, 0), (1, 1), (2, 1)]}, -31: {"id": -31, "hasBlock": False, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (-1, 1), (-1, 0), (1, 0), (1, -1), (2, -1)]}, 32: {"id": 32, "hasBlock": True, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (0, -1), (1, 0), (2, 0), (1, 1), (2, 1)]}, -32: {"id": -32, "hasBlock": True, "hasConcave": False, "hasMirrored": True, "count": 6, "form": [(0, 0), (0, -1), (-1, 0), (-2, 0), (-1, 1), (-2, 1)]}, 33: {"id": 33, "hasBlock": False, "hasConcave": False, "hasMirrored": False, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-4, 0), (-2, 1)]}, 34: {"id": 34, "hasBlock": False, "hasConcave": True, "hasMirrored": False, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-3, 1), (0, 1)]}, 35: {"id": 35, "hasBlock": True, "hasConcave": False, "hasMirrored": False, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-2, 1), (-1, 1)]}, 36: {"id": 36, "hasBlock": False, "hasConcave": False, "hasMirrored": False, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-3, -1), (-3, 1)]}, 37: {"id": 37, "hasBlock": False, "hasConcave": False, "hasMirrored": False, "count": 6, "form": [(0, 0), (-1, 0), (-2, 0), (-3, 0), (-2, -1), (-2, 1)]}, 38: {"id": 38, "hasBlock": False, "hasConcave": True, "hasMirrored": False, "count": 6, "form": [(0, 0), (-1, 0), (-2, 1), (-2, -1), (-1, -1), (-1, 1)]}, 39: {"id": 39, "hasBlock": True, "hasConcave": False, "hasMirrored": False, "count": 6, "form": [(0, 0), (2, 2), (1, 0), (2, 0), (1, 1), (2, 1)]}, 40: {"id": 40, "hasBlock": True, "hasConcave": False, "hasMirrored": False, "count": 6, "form": [(0, 0), (2, -1), (1, 0), (2, 0), (1, 1), (1, -1)]}, } def printPolyomino(polyomino): n = polyomino["count"] f = [[0 for _ in range(-n, n + 1)] for _ in range(-n, n + 1)] for i, j in polyomino["form"]: f[n + i][n + j] = 1 for rows in f: for cell in rows: if cell == 1: print("■", end="") else: print("□", end="") print() def getPolyominos(): return poly if __name__ == "__main__": for k, v in poly.items(): print("-" * 10) print(v["id"], v["count"]) printPolyomino(v)
995,589
902a0e2d541ebf68a7e5926f3dfdd8248ebc320f
import datetime import sys import re from functools import total_ordering import calendar # Represent a single event on a calendar @total_ordering class Event: # The inputs are of the following types, although endTIme is allowed to be None. # datetime.date date # datetime.time startTime # datetime.time endTime # string description def __init__(self, date, startTime, endTime, description): self.date = date self.startTime = startTime self.endTime = endTime self.description = description # Return a textual description of the start and optionally end time. def getTimeString(self): if not self.startTime: return None if self.startTime == "All Day": return self.startTime startString = self.startTime.strftime("%I:%M %p") if self.endTime: return "-".join([startString, self.endTime.strftime("%I:%M %p")]) return startString def __str__(self): return ",".join([str(self.date), str(self.startTime), str(self.endTime), str(self.description)]) __repr__ = __str__ def __eq__(self, other): return self.__dict__ == other.__dict__ def __lt__(self, other): if self.date != other.date: return self.date < other.date if self.startTime == None or self.startTime == "All Day": return True if other.startTime == None or other.startTime == "All Day": return False return self.startTime < other.startTime def getDates(from_date, to_date, day_list): date_list = list() ## Creates a list of all the dates falling between the from_date and to_date range for x in xrange((to_date - from_date).days+1): date_record = from_date + datetime.timedelta(days=x) if date_record.weekday() in day_list: date_list.append(date_record) return date_list def parseDate(ds): parts = ds.split("-") if len(parts) == 3: t = (int(x) for x in parts) return datetime.date(t[2], t[0], t[1]) elif len(parts) == 2: return datetime.date(datetime.datetime.now().year, int(parts[0]), int(parts[1])) # An error occurred sys.stderr.write("Error parsing date '%s'" % ds) return None # Interpret start and possibly end times. def parseTime(ts): def parseOneDate(ts): ts = ts.strip() # Special cases if ts == "All Day": return "All Day" if ts == "Noon": return datetime.time(12, 0) if ts == "NULL": return None amOrPm = re.search("am|pm", ts, re.IGNORECASE) ts = re.sub("am|pm| ", "", ts, 0, re.IGNORECASE).strip() if ":" in ts: ts = ts.split(":") hours, minutes = int(ts[0]), int(ts[1]) else: hours, minutes = int(ts), 0 if amOrPm: isPm = amOrPm.group(0).lower() == 'pm' if isPm and hours != 12: hours += 12 elif not isPm and hours == 12: hours = 0 return datetime.time(hours, minutes) # Only startTime is available if '-' not in ts: return parseOneDate(ts), None else: start, end = ts.split("-") return parseOneDate(start), parseOneDate(end) def readEvent(line): parts = line.split(",", 2) date = parseDate(parts[0]) startTime, endTime = parseTime(parts[1]) return Event(date, startTime, endTime, parts[2]) def generateRecurring(line): def convertToNumber(dayNameOrAbbr): try: num = list(calendar.day_name).index(dayNameOrAbbr) except: num = list(calendar.day_abbr).index(dayNameOrAbbr) return num parts = line.split(",", 4) startDate = parseDate("1-1") if parts[1] == "NULL" else parseDate(parts[1]) endDate = parseDate("12-31") if parts[2] == "NULL" else parseDate(parts[2]) days = getDates(startDate, endDate, [convertToNumber(parts[0])]) startTime, endTime = parseTime(parts[3]) return [Event(x, startTime, endTime, parts[4]) for x in days] # Expected format: # Date: MM-DD-YYYY || MM-DD # StartTime: Noon || All Day || hh:mm (am|pm)? # EndTime: Noon || All Day || hh:mm (am|pm)? def readEvents(events_file): events = list() eventsToDelete = list() curDate = None with open(events_file) as f: for line in f: # Comments are Python style line = line.strip() if line == "" or line.startswith("#"): continue # Event negation requires short form if line.startswith("!"): eventsToDelete.append(readEvent(line[1:])) if re.match(r"^\d\d?-\d\d?(-\d{4}|\d{2})?$", line): # Long form start curDate = parseDate(line) elif re.search(r"^\d\d?-\d\d?(-\d{4}|\d{2})?", line): # Short form supercedes long form curDate = None events.append(readEvent(line)) # Line is of the form DOW,StartDate,EndDate,Time,Description elif re.search(r"^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)", line): recurringEvents = generateRecurring(line) for e in recurringEvents: events.append(e) # Continuation of long form is assumed if long form already started. # Otherwise we ignore. elif curDate: parts = line.split(",", 1) events[curDate].append(parts) events = filter(lambda x: x not in eventsToDelete, events) return events def main(): events_file = "Events.txt" print "\n".join(str(x) for x in sorted(readEvents(events_file))) if __name__ == "__main__": main()
995,590
064a9b3ae98f14fe0335b343a9d4dbf3f41ed7c1
from django.db.models import fields from rest_framework import serializers from .models import State, District class StateSerializers(serializers.ModelSerializer): class Meta: model = State fields = ['state_id', 'state_name'] class DistrictSerializers(serializers.ModelSerializer): class Meta: model = District fields = ['district_id', 'district_name']
995,591
6482b77ebe857947802a01d174cc4de0816fcbd8
#!/usr/bin/env python import time, math import numpy as np import rospy from sensor_msgs.msg import JointState from std_msgs.msg import Header import ikpy from ikpy import geometry_utils from ikpy.chain import Chain from scipy.spatial.transform import Rotation as R class Rbx1_Kinematics(object): def __init__(self): rospy.init_node('kinematics') rospy.loginfo("Kinematic thingy initializin' here...") self.chain = Chain.from_urdf_file("urdf/rbx1_urdf.urdf", active_links_mask=[False, True, True, True, True, True, True, True, False, False]) self.publisher = rospy.Publisher('/joint_states', JointState, queue_size=10) self.seq = 0 print(self.chain) def move(self, x, y, z, orientation_matrix = np.eye(3)): joint_states = self.chain.inverse_kinematics(geometry_utils.to_transformation_matrix( [x, y, z], orientation_matrix)) # joint_states = self.chain.inverse_kinematics([ [-.5, 0, 0, x], # [0, 0.5, 0, y], # [0, 0, 0.5, z], # [0, 0, 0, -.5] ]) print(joint_states) hdr = Header() hdr.seq = self.seq = self.seq + 1 hdr.stamp = rospy.Time.now() hdr.frame_id = "My-Kinematic-Thingy" js = JointState() js.header = hdr js.name = ["Joint_1", "Joint_2", "Joint_3", "Joint_4", "Joint_5", "Joint_6", "Joint_Gripper"] #, , # "Joint_Grip_Servo", "Joint_Tip_Servo", "Joint_Grip_Servo_Arm", # "Joint_Grip_Idle", "Joint_Tip_Idle", "Joint_Grip_Idle_Arm"] js.position = joint_states[1:8] js.velocity = [] js.effort = [] self.publisher.publish(js) def rpy_to_orientation_matrix(self, roll, pitch, yaw): yawMatrix = np.matrix([ [math.cos(yaw), -math.sin(yaw), 0], [math.sin(yaw), math.cos(yaw), 0], [0, 0, 1] ]) pitchMatrix = np.matrix([ [math.cos(pitch), 0, math.sin(pitch)], [0, 1, 0], [-math.sin(pitch), 0, math.cos(pitch)] ]) rollMatrix = np.matrix([ [1, 0, 0], [0, math.cos(roll), -math.sin(roll)], [0, math.sin(roll), math.cos(roll)] ]) R = yawMatrix * pitchMatrix * rollMatrix print(R) theta = math.acos(((R[0, 0] + R[1, 1] + R[2, 2]) - 1) / 2) multi = 1 / (2 * math.sin(theta)) rx = multi * (R[2, 1] - R[1, 2]) * theta ry = multi * (R[0, 2] - R[2, 0]) * theta rz = multi * (R[1, 0] - R[0, 1]) * theta # print (rx, ry, rz) if __name__ == "__main__": kin = Rbx1_Kinematics() x = 0.5 y = 0 z = 0.1 kin.move(x, y, z) # identity matrix time.sleep(2) kin.move(x, y, z, np.array([[1, 0, 0], [0, -1, 0], [0, 0, -1]])) # 180 around X time.sleep(2) kin.move(x, y, z, np.array([[-1, 0, 0], [0, 1, 0], [0, 0, -1]])) # 180 around Y time.sleep(2) kin.move(x, y, z, np.array([[-1, 0, 0], [0, -1, 0], [0, 0, 1]])) # 180 around Z # kin.move(0,3,0) # time.sleep(2) # kin.move(-3,0,0) # time.sleep(2) # kin.move(0,-3,0) # time.sleep(2) # kin.move(0,0,3) # time.sleep(2) # kin.rpy_to_orientation_matrix(180, 0, 0) # kin.move(1,2,2) # time.sleep(1) # kin.move(2,12,1) # time.sleep(1) # kin.move(12,2,0)
995,592
8bd3f601fd9647d249bfe723ac3ee4549fc82244
"""This module houses functions for parsing file objects from Plotly Dash upload components, hanldes the files with data cleaning and preparation before returning figure objects for charts in the app. This module does the work behind the file selection and uploading of a site userself. author: Babila Lima date: December 22, 2018 """ import base64 import dash_html_components as html import datetime as dt import io import numpy as np import pandas as pd import plotly.graph_objs as go ## functions for handling callbacks for dashboard row 1 charts def parse_fundriaser_file(contents, filename): if contents is not None: content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) else: pass def fundraise_piechart(dframe, target=15000): """ Returns a plotly fig item for donut chart showing the percentages and dollar amounds raised by each member through their fundraising activities. """ # find date of report run (usually appened to end of report in first column) for value in dframe['Contact Role']: try: if 'Generated' in value: for segment in value.split(): if '/' in segment: report_date = segment except: pass dframe = dframe[dframe['Amount'].notnull()] dframe['Donation Name'] = [name[0]+' '+name[1].replace('-','') for name in dframe['Donation Name'].str.split()] dframe['anonymized'] = ['id:'+str(np.round(np.random.rand(1),2)).\ strip('[]').strip() for name in dframe['Last Name']] trace = [] trace.append(go.Pie( values = dframe.groupby('Last Name')['Amount'].sum(), labels = dframe.groupby('Last Name')['Amount'].sum().index, domain = {'x': [0, .48]}, name = 'pct raised', hoverinfo = 'percent+value', hole = .4, opacity = .8)) layout = { "title": "Fundraising Outcomes {}<br><b>{}</b> members fundraised <b>{:,.1f}</b>% of target ".format(report_date,\ dframe.groupby('Last Name')['Amount'].sum().\ index.nunique(),(dframe['Amount'].sum() /\ target) * 100), "titlefont": {'color':'#CCCCCC'}, "showlegend":False, 'paper_bgcolor':'#303939', 'plot_bgcolor':'#303939', "annotations": [ { "font": {"size": 20, 'color': '#CCCCCC'}, "showarrow": False, "text": "BGS", "x": 0.20, "y": 0.5}, { "font": {"size": 13, 'color':'#CCCCCC'}, "showarrow": False, "text": "Target: $15k", "x": .75, "y": .88, 'xref':'paper', 'yref':'paper' }, { "font": {"size": 13, 'color':'#CCCCCC'}, "showarrow": False, "text": "Raised: ${:,.0f}".format(dframe['Amount'].sum()), "x": .75, "y": .83, 'xref':'paper', 'yref':'paper'}, { "font": {"size": 13, 'color':'#CCCCCC'}, "showarrow": False, "text": ('Shortfall: ${:,.0f}'.format(target - dframe['Amount'].sum())), "x": .75, "y": .78, 'xref':'paper', 'yref':'paper'} ]} fig = {'data':trace,'layout':layout} return fig # try except for filetype handling from upload try: if 'xls' in filename: # Expects excel file uploaded df = pd.read_excel(io.BytesIO(decoded)) fig = fundraise_piechart(df) except Exception as e: print(e) return html.Div([ 'There was an error processing this Excel file.' ]) return fig # pldedges horizontal barchart def parse_pledges_file(contents, filename): if contents is not None: content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) else: pass def pledges_barchart(dframe, colors = ['#8dc16a','#d6746f']): """ Returns a plotly fig item for donut chart showing the percentages and dollar amounds raised by each member through their fundraising activities. """ # anonymize members & convert dollar values to float type anonymized = [] for name in dframe['Last Name']: if str(name) == 'nan': anonymized.append('--') else: anonymized.append('M: {}'.format(np.random.randint(1,100))) dframe['anonymized'] = anonymized for col in ['Amount','Payment Amount Received','Remaining Balance']: dframe[col] = dframe[col].astype(float) # series of percentage donated against pledged pct_fulfiilled = pd.Series(dframe.groupby('Last Name')['Payment Amount Received'].sum() / dframe.groupby('Last Name')['Amount'].mean() * 100) # series of percentage donated against pledged # handle for negative values remaining for 'over achieving donors' normalized_balance_values = [0 if val < 0 else val for val in dframe.groupby('Last Name')['Remaining Balance'].sum() ] pct_outstanding = (normalized_balance_values / dframe.groupby('Last Name')['Amount'].mean() * 100) trace1 = go.Bar( x = pct_fulfiilled.values, y = pct_fulfiilled.index, name = 'received %', marker = {'color':'#8dc16a'}, hoverinfo = 'x', opacity = .8, orientation = 'h' ) trace2 = go.Bar( x = pct_outstanding.values, y = pct_outstanding.index, name = 'outstanding %', hoverinfo = 'x', marker = {'color':'#d6746f'}, opacity = .8, orientation = 'h' ) layout = go.Layout( legend = {'orientation': 'h'}, xaxis = {'title': 'pct %', 'titlefont': {'color':'#CCCCCC'}, 'tickfont': {'color': '#CCCCCC'}}, # hide y axis names by matching text color to background yaxis = {'title': '', 'tickfont': {'color':'#303939'}}, barmode = 'stack', hovermode = 'closest', title = 'Percent of Pledge Donated', titlefont = {'color':'white'}, paper_bgcolor = '#303939', plot_bgcolor = '#303939') traces = [trace1,trace2] fig = {'data':traces,'layout':layout} return fig # try except for filetype handling from upload try: if 'xls' in filename: # Expects excel file uploaded df = pd.read_excel(io.BytesIO(decoded)) fig = pledges_barchart(df) except Exception as e: print(e) return html.Div([ 'There was an error processing this Excel file.' ]) return fig # budget stacked barchart def parse_budget_file(contents, filename): if contents is not None: content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) else: pass def budget_barchart(dframe, colors=['#d6746f','green']): """ Returns a plotly fig item for stacked barchart for budget vs actuals. """ dframe = df.copy() dframe.columns = ['budget_item','actual','budgeted', 'over_budget','pct_overbudget'] dframe.drop(dframe.index[0:5],inplace=True) for col in dframe.columns[1:]: dframe[col] = dframe[col].astype(float) dframe['budget_item'] = dframe['budget_item'].str.strip() # store report run date from last row in sheet to use in chart title report_run_date_list = dframe.iloc[-1][0].split()[1:4] run_date = report_run_date_list[0]+' '+report_run_date_list[1]+' '+report_run_date_list[2] # drop stamp from quickbooks in sheet for i in range(4): dframe.drop(dframe.index[-1],inplace=True) # create budget line item identifier to create filter -- isoloate key total lines budget_line_code = [] for i,tag in enumerate(dframe.budget_item): if len(tag.split()) <= 1: budget_line_code.append('0000') elif tag.split()[0].isdigit(): budget_line_code.append('00-' + str(tag.split()[0])) elif tag.split()[1].isdigit(): budget_line_code.append(tag.split()[1]) else: budget_line_code.append('0001') dframe['budget_code'] = budget_line_code # create plot trace & figure budgeted_xaxis,budgeted_yaxis,raised_xaxis,raised_yaxis = [],[],[],[] for item,tag in zip(['Grants','Support','Government'], ['43300','43400','44500']): budgeted_xaxis.append(item) raised_xaxis.append(item) budgeted_yaxis.append(dframe[dframe.budget_code == tag].budgeted.sum() - \ dframe[dframe.budget_code == tag].actual.sum()) raised_yaxis.append(dframe[dframe.budget_code == tag].actual.sum()) traces = [] for stack,color,xaxis,yaxis in zip(['budget','actual'],colors, [budgeted_xaxis,raised_xaxis], [budgeted_yaxis,raised_yaxis]): traces.append(go.Bar( x = xaxis, y = yaxis, name = stack, marker = {'color': color}, opacity = .7)) data = traces layout = { 'barmode':'stack', 'hovermode':'closest', 'title': 'Budget Target vs Actuals<br>{}'.format(run_date), 'titlefont':{'color':'#CCCCCC'}, 'tickfont': {'color':'#CCCCCC'}, 'legend':{'font': {'color':'#CCCCCC'}}, 'yaxis':{'tickfont':{'color':'#CCCCCC'}}, 'xaxis':{'tickfont':{'color':'#CCCCCC'}}, 'paper_bgcolor': '#303939', 'plot_bgcolor':'#303939', 'annotations' : [ {'font':{'size':11, 'color': '#CCCCCC'}, 'showarrow':False, 'x':.9, 'y': 1, 'xref':'paper', 'yref':'paper', 'text':'Target: ${:,.0f}'.\ format(dframe[dframe.budget_item=='Total Income'].budgeted.sum()) }, {'font':{'size':11, 'color':'#CCCCCC'}, 'showarrow':False, 'x':.9, 'y': .93, 'xref':'paper', 'yref':'paper', 'text':'<b>Shortfall</b>: ${:,.0f}'.\ format(dframe[dframe.budget_item=='Total Income'].\ budgeted.sum() - dframe[dframe.budget_item=='Total Income'].\ actual.sum())} ]} fig = {'data':data, 'layout':layout} return fig # try except for filetype handling from upload try: if 'xls' in filename: # Expects excel file uploaded df = pd.read_excel(io.BytesIO(decoded)) fig = budget_barchart(df) except Exception as e: print(e) return html.Div([ 'There was an error processing this Excel file.' ]) return fig # grant outcomes barchart def parse_grants_file_outcomes(contents, filename): if contents is not None: content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) else: pass def grant_outcomes_barchart(dframe): """ Returns a plotly fig item for stacked barchart displaying simplified status of grant funding application activity by quarter. """ # prepare dataframe dframe = df.copy() dframe.columns = [col.lower().replace(' ','_') for col in dframe.columns] dframe = dframe[dframe['organization_name'].notnull()] dframe.drop(['thank_you_sent','report_due','report_sent'],axis=1, inplace=True) dframe.set_index(dframe['date_application_sent'],inplace=True) grant_stage = [] [grant_stage.append(status.lower().strip()) for status in dframe.stage] dframe['stage'] = grant_stage grant_status = [] # merge status to 3 primary categories, make 'awarded' tag for status in dframe.stage: if status not in ['obligations complete','pledged','posted']: grant_status.append(status) else: grant_status.append('awarded') dframe['grant_status'] = grant_status # create chart color_dict = {'awarded':'#adebad','not approved':'#d6746f', 'submitted':'#ffffb3'} grant_count_trace = [] for status in dframe.grant_status.unique(): grant_count_trace.append(go.Bar( x = dframe[dframe.grant_status==status].resample('Q')['stage'].count().index, y = dframe[dframe.grant_status==status].resample('Q')['stage'].count(), name = status, marker = {'color':color_dict[status]}, opacity = .8)) layout = {'barmode':'stack', 'hovermode':'closest', 'paper_bgcolor':'#303939', 'plot_bgcolor':'#303939', 'legend':{'font':{'color':'#CCCCCC'}}, 'yaxis':{'title':'no. applications', 'tickfont':{'color':'#CCCCCC'}, 'titlefont':{'color':'#CCCCCC'}, 'showgrid':False}, 'xaxis':{'title':'quarter submitted', 'titlefont':{'color':'#CCCCCC'}, 'tickfont': {'color':'#CCCCCC'}}, 'title':'Grant Application<br>Status Overview', 'titlefont':{'color':'#CCCCCC'}} fig = {'data':grant_count_trace, 'layout':layout} return fig # try except for filetype handling from upload try: if 'xls' in filename: # Expects excel file uploaded df = pd.read_excel(io.BytesIO(decoded)) fig = grant_outcomes_barchart(df) except Exception as e: print(e) return html.Div([ 'There was an error processing this Excel file.' ]) return fig # grant dollars barchart def parse_grants_file_dollars(contents, filename): if contents is not None: content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) else: pass def grant_dollars_barchart(dframe): """ Returns a plotly fig item for stacked barchart displaying dollar amounts for grant application activity by quarter. """ # prepare dataframe dframe = df.copy() dframe.columns = [col.lower().replace(' ','_') for col in dframe.columns] dframe = dframe[dframe['organization_name'].notnull()] dframe.drop(['thank_you_sent','report_due','report_sent'],axis=1, inplace=True) dframe.set_index(dframe['date_application_sent'],inplace=True) # create chart color_dict = {'awarded':'#adebad','not approved':'#d6746f', 'submitted':'#ffffb3'} grant_stage = [] [grant_stage.append(status.lower().strip()) for status in dframe.stage] dframe['stage'] = grant_stage grant_status = [] # merge status to 3 primary categories, make 'awarded' tag for status in dframe.stage: if status not in ['obligations complete','pledged','posted']: grant_status.append(status) else: grant_status.append('awarded') dframe['grant_status'] = grant_status # create chart grant_outcomes_trace = [] for status in dframe.grant_status.unique(): # sum 'amount' column totals for awarded grants if status == 'awarded': grant_outcomes_trace.append((go.Bar( x = dframe[dframe.grant_status==status].resample('Q')['amount'].count().index, y = dframe[dframe.grant_status==status].resample('Q')['amount'].sum(), name = status, marker = {'color': color_dict[status]}, opacity = .8))) else: # sum 'requested amount' column totals for submitted and not approved grant_outcomes_trace.append((go.Bar( x = dframe[dframe.grant_status==status].resample('Q')['requested_amount'].count().index, y = dframe[dframe.grant_status==status].resample('Q')['requested_amount'].sum(), name = status, marker = {'color': color_dict[status]}, opacity = .8))) layout = {'barmode':'stack', 'hovermode':'closest', 'legend': {'font': {'color': '#CCCCCC'}}, 'paper_bgcolor': '#303939', 'plot_bgcolor': '#303939', 'yaxis': {'title':'US$', 'tickfont':{'color':'#CCCCCC'}, 'titlefont': {'color':'#CCCCCC'}, 'showgrid':False}, 'xaxis':{'title':'quarter submitted', 'titlefont': {'color':'#CCCCCC'}, 'tickfont': {'color':'#CCCCCC'}}, 'title':'Grant Application<br>Outcomes Overview', 'titlefont': {'color':'#CCCCCC'}} fig = {'data':grant_outcomes_trace,'layout':layout} return fig # try except for filetype handling from upload try: if 'xls' in filename: # Expects excel file uploaded df = pd.read_excel(io.BytesIO(decoded)) fig = grant_dollars_barchart(df) except Exception as e: print(e) return html.Div([ 'There was an error processing this Excel file.' ]) return fig # strategic plan def parse_strategic_plan_file(contents, filename): """Read in excel sheet, generate pandas dataframe and return bar chart. Function expects the sheet named 'All Items 7.17.17' to be the first sheet in the workbook as the cleaning process is set to the format and dimensions of that file. """ if contents is not None: content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) else: pass def strategic_plan_barchart(dframe, colors=['#f4aa42','#becca5','#9fa399', '#d88668','#43a559','#edf760']): """ Returns a plotly figure object for stacked bar chart showing progress on strategic plan items by quarter. """ # prepare dataframe # check if user has changed number of columns in sheet if len(dframe.columns) != 11: issue = 'User has altered spreadsheet by {} {} columns.' if len(dframe.columns) < 11: action = 'removing' number = 11 - len(dframe.columns) print(issue.format(action,number)) else: action = 'adding' number = len(dframe.columns) - 11 print(issue.format(action,number)) dframe.drop(dframe.index[0:6],inplace=True) new_cols = ['start_qt','start_yr','goal_id','topic_area','task_name', 'task_stage','blank1','start','finish','owner','internal_status'] dframe.columns = new_cols dframe.drop('blank1',axis=1,inplace=True) dframe = dframe[dframe.task_stage.notnull()] # filter dataframe for items with a stage dframe['status'] = [x.lower().strip() for x in dframe.task_stage] dframe['start'] = [pd.to_datetime(date.split()[1]) for date in dframe.start] dframe['finish'].fillna(method='ffill',inplace=True) finish = [] for date in dframe['finish']: if (type(date)) is str: finish.append(pd.to_datetime(date.split()[1])) else: finish.append(pd.to_datetime(date)) dframe['finish'] = finish dframe['finish_qt'] = ['Q'+str(date.quarter) for date in dframe['finish']] YrQt_complete = ['{} Q{}'.format(date.year,date.quarter) for date in dframe['finish']] dframe['YrQt_complete'] = YrQt_complete # create chart if len(colors) != dframe['status'].nunique(): colors = None trace = [] clrs = dict(zip(sorted(dframe['status'].unique().tolist()),colors)) for sts, clr in zip(sorted(dframe['status'].unique()),clrs.values()): trace.append(go.Bar( x = dframe[(dframe['task_stage']==sts)].groupby('YrQt_complete')['YrQt_complete'].count().index, y = dframe[(dframe['task_stage']==sts)].groupby('YrQt_complete')['YrQt_complete'].count(), name = sts, marker = {'color': clr}, opacity = .8)) layout = { 'barmode':'stack', 'legend': {'font':{'color':'#CCCCCC'}}, 'titlefont': {'color': '#CCCCCC'}, 'hovermode':'closest', 'paper_bgcolor': '#303939', 'plot_bgcolor': '#303939', 'xaxis':{'title':'Target Completion Quarter', 'tickfont': {'color': '#CCCCCC'}, 'titlefont': {'color': '#CCCCCC'}}, 'yaxis':{'title':'No. of Activities', 'tickfont': {'color': '#CCCCCC'}, 'titlefont': {'color': '#CCCCCC'}}, 'title':'Strategic Plan Overview'} fig = {'data':trace,'layout':layout} return fig # try except for filetype handling from upload try: if 'xls' in filename: # Expects excel file uploaded df = pd.read_excel(io.BytesIO(decoded)) fig = strategic_plan_barchart(df) except Exception as e: print(e) return html.Div([ 'There was an error processing this Excel file.' ]) return fig
995,593
bcb1c881fe76095e5464c5fd229a421138bae1eb
import numpy as np from scipy import signal from scipy.interpolate import interp1d import scipy.integrate as integrate from scipy.special import spherical_jn, sph_harm from scipy.signal import butter, filtfilt, iirdesign, zpk2tf, freqz, hanning import matplotlib.pyplot as plt import matplotlib.mlab as mlab #import h5py #import datetime as dt #import pytz #import pylab #import qpoint as qp #import healpy as hp #from camb.bispectrum import threej #import quat_rotation as qr #from scipy.optimize import curve_fit #import OverlapFunctsSrc as ofs #from numpy import cos,sin #from matplotlib import cm file = np.load('problematic.npz') h1 = file['h1'] Nt = len(h1) h1 *= signal.tukey(Nt,alpha=0.05) h1_cp = np.copy(h1) print len(h1_cp) h1 = h1[:245823] h1_cp = h1_cp[:245823] print len(h1) dl = 1./4096 low_f = 30. high_f = 500. freqs = np.fft.rfftfreq(Nt, dl) freqs = freqs[:Nt] hf = np.fft.rfft(h1, n=Nt, norm = 'ortho') hf = hf[:Nt] print 'lens hf - h1:', len(hf), len(h1) print hf Pxx, frexx = mlab.psd(h1_cp, Fs=4096, NFFT=2*4096,noverlap=4096/2,window=np.blackman(2*4096),scale_by_freq=False) print 'Pxx', Pxx hf_psd = interp1d(frexx,Pxx) hf_psd_data = abs(hf.copy()*np.conj(hf.copy())) mask = (freqs>low_f) & (freqs < high_f) mask2 = (freqs>80.) & (freqs < 300.) #plt.figure() #plt.loglog(hf_psd_data[mask]) #plt.loglog(hf_psd(freqs)[mask]) #plt.savefig('compare.pdf') norm = np.mean(hf_psd_data[mask])/np.mean(hf_psd(freqs)[mask]) norm2 = np.mean(hf_psd_data[mask2])/np.mean(hf_psd(freqs)[mask2]) print norm, norm2 np.savez('hf.npz', hf = hf,Pxx = Pxx, frexx = frexx, norm = norm, norm2 = norm2) exit() file_cx1 = np.load('hf_cx1.npz') file_tom = np.load('hf_Tom.npz') hf_cx1 = file_cx1['hf'] hf_tom = file_tom['hf'] print 'lens hf - h1:', len(hf), len(h1) print 'lens hfcx1 - hftom:', len(hf_cx1), len(hf_tom) # plt.figure() # plt.loglog(hf_cx1*np.conj(hf_cx1)) # plt.loglog(hf_tom*np.conj(hf_tom)) # plt.savefig('psds_cx1_tom.pdf') # # plt.figure() # plt.loglog(np.real(hf_cx1)) # plt.loglog(np.imag(hf_cx1)) # plt.loglog(np.real(hf_tom)) # plt.loglog(np.imag(hf_tom)) # plt.savefig('realimag_cx1_tom.png') hf_psd_cx1 = abs(hf_cx1.copy()*np.conj(hf_cx1.copy())) hf_psd_tom = abs(hf_tom.copy()*np.conj(hf_tom.copy())) print len(hf_psd_cx1), len(hf_psd_tom), len(hf_psd_data) exit() print np.mean(hf_psd_cx1[mask]), np.mean(hf_psd_tom[mask]) print np.mean(hf_psd_cx1[mask2]), np.mean(hf_psd_tom[mask2]) print np.mean(hf_psd_cx1[mask])/np.mean(hf_psd(freqs)[mask]), np.mean(hf_psd_tom[mask])/np.mean(hf_psd(freqs)[mask]) print np.mean(hf_psd_cx1[mask2])/np.mean(hf_psd(freqs)[mask2]), np.mean(hf_psd_tom[mask2])/np.mean(hf_psd(freqs)[mask2]) exit()
995,594
c5e46e0058eec6bbd3d321d6d1f12f4088c075d0
from django.urls import path, re_path from django.conf.urls import url from . import views urlpatterns = [ path('', views.index, name='index'), re_path(r'^keywords/(?P<campaign_id>\d+)/', views.keywords, name='keywords'), #path('keywords/(?P<campaign_id>\w{0,50})/$', views.keywords, name='keywords'), ]
995,595
358cca0af91975aa5a87755e375483105d06ae9a
from enum import Enum class HakAkses(Enum): Admin = 1 Petugas = 2
995,596
48ee38f54ab1464e2cde9e0e8cb06bae461969dc
import scrapy class PollItem(scrapy.Item): date = scrapy.Field() pollster = scrapy.Field() client = scrapy.Field() party = scrapy.Field() share = scrapy.Field()
995,597
f47fbe7bed878cef08fb1760b41c1a81ba4e7cd8
import json def read_json(filename): data = None with open(filename, "r") as f: data = json.loads(f.read()) return data def write_json(data, filename, pretty=False): with open(filename, "w") as f: if pretty: f.write(json.dumps(data, indent=4, sort_keys=True)) else: f.write(json.dumps(data))
995,598
14a307c0ddd2e319a1a09f539b032fed59eac6e5
# Copyright 2021 National Technology & Engineering Solutions of # Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with # NTESS, the U.S. Government retains certain rights in this software. """Test metric descriptors.""" import unittest from random import randint import threading from .metric_descriptor import Metric, get_metric_object from .types import Int64, Historical, Transient from .exceptions import IcypawException class SimpleMetricTester(unittest.TestCase): def setUp(self): self.name = 'my_metric' self.type_ = Int64 class Node: my_metric = Metric(self.type_) self.node = Node() self.exp_value = randint(-10, 10) def test_get_set(self): self.assertIsInstance(self.node.my_metric, int) self.node.my_metric = self.exp_value self.assertEqual(self.node.my_metric, self.exp_value) def test_get_network(self): self.node.my_metric = self.exp_value act_value = get_metric_object(self.node, 'my_metric').get_network(self.node) self.assertIsInstance(act_value, self.type_) self.assertEqual(act_value.icpw_value, self.exp_value) def test_set_network(self): icpw_exp_value = self.type_(self.exp_value) get_metric_object(self.node, 'my_metric').set_network(self.node, icpw_exp_value) self.assertEqual(self.node.my_metric, self.exp_value) def test_get_name(self): self.assertEqual(get_metric_object(self.node, 'my_metric').name, self.name) class RenamedMetricTester(SimpleMetricTester): def setUp(self): self.name = 'folder/My Metric' self.type_ = Int64 class Node: my_metric = Metric(self.type_, name=self.name) self.node = Node() self.exp_value = randint(-10, 10) class NetHookMetricTester(SimpleMetricTester): def setUp(self): self.name = 'my_metric' self.type_ = Int64 class Node: my_metric = Metric(self.type_) @my_metric.net_hook def my_metric(self, value): return value + 1 self.node = Node() self.exp_value = randint(-10, 10) def test_get_set(self): self.assertIsInstance(self.node.my_metric, int) self.node.my_metric = self.exp_value self.assertEqual(self.node.my_metric, self.exp_value) def test_set_network(self): exp_value = self.type_(self.exp_value) get_metric_object(self.node, 'my_metric').set_network(self.node, exp_value) self.assertEqual(self.node.my_metric, self.exp_value + 1) class ReadOnlyMetricTester(SimpleMetricTester): def setUp(self): self.name = 'my_metric' self.type_ = Int64 class Node: my_metric = Metric(self.type_, read_only=True) self.node = Node() self.exp_value = randint(-10, 10) def test_set_network(self): with self.assertRaises(IcypawException): get_metric_object(self.node, 'my_metric').set_network(self.node, self.type_()) class ReadOnlyNetHookTester(unittest.TestCase): def test_fail_on_init(self): """Test that merely creating a net_hook on a read-only metric fails""" with self.assertRaises(IcypawException): class Node: my_metric = Metric(Int64, read_only=True) @my_metric.net_hook def my_metric(self, value): pass class InheritanceMetricTester(SimpleMetricTester): """Test that the metric can be accessed when it is a member of a base class.""" def setUp(self): self.name = 'my_metric' self.type_ = Int64 class NodeBase: my_metric = Metric(self.type_) class Node(NodeBase): pass self.node = Node() self.exp_value = randint(-10, 10) class MultipleInstanceTester(unittest.TestCase): def test_multiple_instances(self): """Make sure the data is being stored in the instances and not the classes.""" class Node: my_metric = Metric(Int64) self.node0 = Node() self.node1 = Node() self.node0.my_metric = 5 self.node1.my_metric = 7 self.assertEqual(self.node0.my_metric, 5) self.assertEqual(self.node1.my_metric, 7) class AssignToThread(unittest.TestCase): def test_assign_to_thread_read(self): """Test whether an exception is raised when a metric is assigned to a specific thread and read another.""" class Node: my_metric = Metric(Int64) node = Node() my_metric = get_metric_object(node, 'my_metric') t = threading.Thread(target=my_metric.assign_to_current_thread, args=(node,)) t.start() t.join() with self.assertRaises(IcypawException): node.my_metric def test_assign_to_thread_write(self): """Test whether an exception is raised when a metric is assigned to a specific thread and read another.""" class Node: my_metric = Metric(Int64) node = Node() my_metric = get_metric_object(node, 'my_metric') t = threading.Thread(target=my_metric.assign_to_current_thread, args=(node,)) t.start() t.join() with self.assertRaises(IcypawException): node.my_metric.x = 75 class AliasNetHook(unittest.TestCase): def test_net_hook_alias(self): """Test registering the net_hook under a different name from the metric and using that method directly.""" class Node: my_metric = Metric(Int64) @my_metric.net_hook def update_my_metric(self, value): return abs(value) node = Node() exp_value = 42 node.my_metric = exp_value self.assertEqual(node.my_metric, exp_value) # Just make sure the method is callable. In a real Device or # Node this would likely have some desirable side-effect. self.assertEqual(node.update_my_metric(-exp_value), exp_value) my_metric = get_metric_object(node, 'my_metric') # Make sure the net_hook is still called in the correct way exp_value = 55 my_metric.set_network(node, Int64(-exp_value)) self.assertEqual(node.my_metric, exp_value) class HistoricalTester(unittest.TestCase): def test_historical_metric_value(self): """Test setting a value to be historical.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = Historical(exp_value) self.assertTrue(my_metric.is_historical(node)) self.assertEqual(node.my_metric, exp_value) def test_non_historical_metric_value(self): """Test that values not set to historical are not historical.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = exp_value self.assertFalse(my_metric.is_historical(node)) self.assertEqual(node.my_metric, exp_value) def test_historical_resets_on_normal_value(self): """Test that a historical value becomes unhistorical after setting a normal value.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = Historical(exp_value) self.assertTrue(my_metric.is_historical(node)) self.assertEqual(node.my_metric, exp_value) node.my_metric = exp_value self.assertFalse(my_metric.is_historical(node)) self.assertEqual(node.my_metric, exp_value) class TransientTester(unittest.TestCase): def test_transient_metric_value(self): """Test setting a value to be transient.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = Transient(exp_value) self.assertTrue(my_metric.is_transient(node)) self.assertEqual(node.my_metric, exp_value) def test_non_transient_metric_value(self): """Test that values not set to transient are not transient.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = exp_value self.assertFalse(my_metric.is_transient(node)) self.assertEqual(node.my_metric, exp_value) def test_transient_resets_on_normal_value(self): """Test that a transient value becomes untransient after setting a normal value.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = Transient(exp_value) self.assertTrue(my_metric.is_transient(node)) self.assertEqual(node.my_metric, exp_value) node.my_metric = exp_value self.assertFalse(my_metric.is_transient(node)) self.assertEqual(node.my_metric, exp_value) class HistoricalTransientTester(unittest.TestCase): def test_historical_transient_metric_value(self): """Test a metric that is both historical and transient.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = Historical(Transient(exp_value)) self.assertTrue(my_metric.is_historical) self.assertTrue(my_metric.is_transient) def test_historical_transient_idempotency(self): """"Test that multiple applications of Historical and Transient have no additional effect.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = Historical(Transient(Historical(Historical( Transient(Transient(exp_value)))))) self.assertTrue(my_metric.is_historical) self.assertTrue(my_metric.is_transient) class NullTester(unittest.TestCase): def test_null_value(self): """Test setting a value to be null.""" class Node: my_metric = Metric(Int64) node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = None self.assertTrue(my_metric.is_null(node)) self.assertEqual(node.my_metric, None) def test_non_null_value(self): """Test that values not set to null are not null.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = exp_value self.assertFalse(my_metric.is_null(node)) self.assertEqual(node.my_metric, exp_value) def test_null_resets_on_normal_value(self): """Test that a null value is no longer null with a normal value.""" class Node: my_metric = Metric(Int64) node = Node() my_metric = get_metric_object(node, 'my_metric') node.my_metric = None self.assertTrue(my_metric.is_null(node)) self.assertEqual(node.my_metric, None) exp_value = 5 node.my_metric = exp_value self.assertFalse(my_metric.is_null(node)) self.assertEqual(node.my_metric, exp_value) class TahuMetricNullTester(unittest.TestCase): def test_is_null(self): """Test that the tahu metric of a null metric is null""" class Node: my_metric = Metric(Int64) node = Node() node.my_metric = None my_metric = get_metric_object(node, 'my_metric') tahu_metric = my_metric.tahu_metric(node) self.assertTrue(tahu_metric.is_null) def test_null_has_no_value(self): """Test that the value that would otherwise exist in a metric does not if it is null.""" class Node: my_metric = Metric(Int64) node = Node() node.my_metric = None my_metric = get_metric_object(node, 'my_metric') tahu_metric = my_metric.tahu_metric(node) self.assertFalse(tahu_metric.HasField('long_value')) class TahuMetricHistoricalTester(unittest.TestCase): def test_is_historical(self): """Test that the tahu metric of a historical metric is historical.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() node.my_metric = Historical(exp_value) my_metric = get_metric_object(node, 'my_metric') tahu_metric = my_metric.tahu_metric(node) self.assertTrue(tahu_metric.is_historical) self.assertEqual(tahu_metric.long_value, 42) class TahuMetricTransientTester(unittest.TestCase): def test_is_transient(self): """Test that the tahu metric of a transient metric is transient.""" class Node: my_metric = Metric(Int64) exp_value = 42 node = Node() node.my_metric = Transient(exp_value) my_metric = get_metric_object(node, 'my_metric') tahu_metric = my_metric.tahu_metric(node) self.assertTrue(tahu_metric.is_transient) self.assertEqual(tahu_metric.long_value, 42)
995,599
1e33385f586fcbdddb1505ac90c9d50d083eea80
import string as st def print_cat(df, col): gb = df.groupby(col)["churn"].value_counts().to_frame().rename({"churn": "Number of Customers"}, axis = 1).reset_index() t = col[:1].upper() + col[1:] xlabel_rotation = 0 if len(col)>10: xlabel_rotation = 90 ax = sns.barplot(x = col, y = "Number of Customers", data = gb, hue = "churn", palette = sns.color_palette("Pastel2", 8)).set_title(f"{t} and relative Churn Rates in our population") # ax.set_xticklabels(rotation=90) plt.show() def plot_contract(df, contract_type, y_limit): churn = df[(df["internetservice"] != "No") & (df["phoneservice"] == "Yes") & (df["churn"] == "Yes") & (df["contract"] == contract_type)] nonchurn = df[(df["internetservice"] != "No") & (df["phoneservice"] == "Yes") & (df["churn"] == "No") & (df["contract"] == contract_type)] bins=np.arange(0,churn['tenure'].max()+3,3) plt.rcParams.update({'font.size': 16}) plt.rcParams.update({'figure.figsize': [12.0, 5.0]}) #title for two plots plt.suptitle(contract_type + ' contract') # compare two plots # first plt.subplot(1, 2, 1) plt.title("Former Customers") plt.xlabel("Tenure Length (Months)") plt.ylabel("Frequency") #set limits on the axes plt.xlim(-2.5, 72) # y_limit - can be calculate plt.ylim(0, y_limit) # data for plot plt.hist(data=churn, x="tenure", bins=bins) #second plt.subplot(1, 2, 2) plt.title("Active Customers") plt.xlabel("Tenure Length (Months)") plt.ylabel("Frequency") # set limits on the axes plt.xlim(-2.5, 72) plt.ylim(0, y_limit) plt.hist(data=nonchurn, x="tenure", bins=bins) plt.show()