content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
# tensorflow mnist beginner tutorial # https://www.tensorflow.org/versions/r0.10/tutorials/mnist/beginners/index.html import tensorflow as tf # Download the input data. This will give three data sets: # mnist.train, mnist.test and mnist.validation from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # A placeholder for mnist images (these are dim N=784 ) x = tf.placeholder(tf.float32, [None, 784]) # (None means dimension of any length) # Weights and biasses represented by 'variables' W = tf.Variable(tf.zeros([784, 10])) # The one-hot images (784 pixels and a one-hot array giving the number) b = tf.Variable(tf.zeros([10])) # Beta values # Regression model: # Multiply multiply x by W then add b, and run through softmax # Define our cost function, 'cross entrophy' in this case y_ = tf.placeholder(tf.float32, [None, 10]) # A placeholder to store the correct answers cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) # Will train the model using gradient descent train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # Initialise the variables init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) # RUN! for i in range(1000): # Collet a batch of 100 training data points batch_xs, batch_ys = mnist.train.next_batch(100) # Feed the batch into the session, replacing the placeholders sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Evaulte the model # argmax gives the index with the largest value; here compare the most likely image to the correct one and # see how many times they are equal correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
[ 2, 11192, 273, 11125, 285, 77, 396, 31516, 11808, 198, 2, 3740, 1378, 2503, 13, 83, 22854, 11125, 13, 2398, 14, 47178, 14, 81, 15, 13, 940, 14, 83, 44917, 82, 14, 10295, 396, 14, 27471, 2741, 14, 9630, 13, 6494, 198, 198, 11748, ...
2.910891
606
""" Go Dep Workflow """ import logging from warnings import warn from aws_lambda_builders.actions import CopySourceAction from aws_lambda_builders.workflow import BaseWorkflow, Capability from .actions import DepEnsureAction, GoBuildAction from .utils import OSUtils from .subproc_exec import SubprocessExec LOG = logging.getLogger(__name__) class GoDepWorkflow(BaseWorkflow): """ A Lambda builder workflow that knows how to build Go projects using `dep` """ NAME = "GoDepBuilder" CAPABILITY = Capability(language="go", dependency_manager="dep", application_framework=None) EXCLUDED_FILES = (".aws-sam", ".git")
[ 37811, 198, 5247, 2129, 5521, 11125, 198, 37811, 198, 198, 11748, 18931, 198, 6738, 14601, 1330, 9828, 198, 198, 6738, 3253, 82, 62, 50033, 62, 50034, 13, 4658, 1330, 17393, 7416, 12502, 198, 6738, 3253, 82, 62, 50033, 62, 50034, 13, ...
3.223881
201
#!/usr/bin/env python # Specter MultiWallet Implementation # Nick Frichette 12/10/2017 """The purpose of the multiwallet is to provide an interface for users to interact with their Specter wallets. This application will show all the wallets thy currently possess, as well as allow users to create more.""" import shutil from wallet import * from blockchain import * # ANSI escape sequences FAIL = '\033[91m' END = '\033[0m' OK = '\033[92m' if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 13058, 263, 15237, 47152, 46333, 198, 2, 8047, 376, 1173, 3202, 660, 1105, 14, 940, 14, 5539, 198, 198, 37811, 464, 4007, 286, 262, 5021, 44623, 318, 284, 2148, 281, 7071, 329, 29...
3.1375
160
from output.models.nist_data.atomic.g_year_month.schema_instance.nistschema_sv_iv_atomic_g_year_month_min_exclusive_5_xsd.nistschema_sv_iv_atomic_g_year_month_min_exclusive_5 import NistschemaSvIvAtomicGYearMonthMinExclusive5 __all__ = [ "NistschemaSvIvAtomicGYearMonthMinExclusive5", ]
[ 6738, 5072, 13, 27530, 13, 77, 396, 62, 7890, 13, 47116, 13, 70, 62, 1941, 62, 8424, 13, 15952, 2611, 62, 39098, 13, 77, 1023, 2395, 2611, 62, 21370, 62, 452, 62, 47116, 62, 70, 62, 1941, 62, 8424, 62, 1084, 62, 41195, 62, 20, ...
2.433333
120
import threading import sublime main_thread = threading.current_thread()
[ 198, 11748, 4704, 278, 220, 198, 11748, 41674, 198, 198, 12417, 62, 16663, 796, 4704, 278, 13, 14421, 62, 16663, 3419, 198 ]
3.454545
22
from __future__ import annotations import asyncio import typing import discord from discord.ext import commands from .errors import InvokedMetaCommand class SettingsMenuOption(object): """ An option that can be chosen for a settings menu's selectable item, eg an option that refers to a sub-menu, or a setting that refers to grabbing a role list, etc. """ __slots__ = ('context', '_display', 'converter_args', 'callback', 'emoji', 'allow_nullable',) def __init__( self, ctx: commands.Context, display: typing.Union[str, typing.Callable[[commands.Context], str]], converter_args: typing.List[SettingsMenuConverter] = None, callback: typing.Callable[['SettingsMenuOption', typing.List[typing.Any]], None] = lambda x: None, emoji: str = None, allow_nullable: bool = True, ): """ Args: ctx (commands.Context): The context for which the menu is being invoked. display (Union[str, Callable[[commands.Context], str]]): A string (or callable that returns string) that gives the display prompt for the option. converter_args (List[SettingsMenuConverter], optional): A list of converter arguments that should be used to convert the user-provided arguments. Tuples are passed directly into `convert_prompted_information`. callback (Callable[['SettingsMenuOption', List[Any]], None], optional): A callable that's passed the information from the converter for you do to whatever with. emoji (str, optional): The emoji that this option refers to. allow_nullable (bool, optional): Whether or not this option is allowed to return None. """ self.context: commands.Context = ctx self._display: typing.Union[str, typing.Callable[[commands.Context], str]] = display self.converter_args: typing.List[SettingsMenuConverter] = converter_args or list() self.callback: typing.Callable[['SettingsMenuOption', typing.List[typing.Any]], None] = callback self.allow_nullable: bool = allow_nullable def get_display(self) -> str: """ Get the display prompt for this option. Returns: str: The string to be displayed """ if isinstance(self._display, str): return self._display return self._display(self.context) async def perform_action(self) -> None: """ Runs through the converters before calling the instance's callback method with the converted data. """ # Get data returned_data = [] for arg in self.converter_args: try: data = await self.convert_prompted_information(arg.prompt, arg.asking_for, arg.converter, arg.emojis) except SettingsMenuError as e: if not self.allow_nullable: raise e data = None returned_data.append(data) if data is None: break # Do callback if isinstance(self.callback, commands.Command): await self.callback.invoke(self.context) elif isinstance(self.callback, SettingsMenu): await self.callback.start(self.context) else: called_data = self.callback(self, *returned_data) if asyncio.iscoroutine(called_data): await called_data async def convert_prompted_information( self, prompt: str, asking_for: str, converter: commands.Converter, reactions: typing.List[discord.Emoji] = None, ) -> typing.Any: """ Ask the user for some information, convert said information, and then return that converted value. Args: prompt (str): The text that we sent to the user -- something along the lines of "what channel do you want to use" etc. asking_for (str): Say what we're looking for them to send - doesn't need to be anything important, it just goes to the timeout message. converter (commands.Converter): The converter used to work out what to change the given user value to. reactions (typing.List[discord.Emoji], optional): The reactions that should be added to the prompt message. If provided then the content of the added reaction is thrown into the converter instead. Returns: typing.Any: The converted information. Raises: InvokedMetaCommand: If converting the information timed out, raise this error to signal to the menu that we should exit. SettingsMenuError: If the converting failed for some other reason. """ # Send prompt sendable: typing.Dict[str, typing.Any] = {"content": prompt} if reactions: x = discord.ui.MessageComponents.add_buttons_with_rows(*[ discord.ui.Button(emoji=i, custom_id=str(i)) for i in reactions ]) sendable["components"] = x bot_message = await self.context.send(**sendable) # Wait for a response from the user user_message = None try: if reactions: payload = await self.context.bot.wait_for("component_interaction", timeout=120, check=check) await payload.response.defer_update() content = str(payload.component.custom_id) else: user_message = await self.context.bot.wait_for("message", timeout=120, check=check) content = user_message.content except asyncio.TimeoutError: await self.context.send(f"Timed out asking for {asking_for}.") raise InvokedMetaCommand() # Run converter conversion_failed = False value = None if hasattr(converter, 'convert'): try: converter = converter() except TypeError: pass try: value = await converter.convert(self.context, content) except commands.CommandError: conversion_failed = True else: try: value = converter(content) except Exception: conversion_failed = True # Delete prompt messages try: await bot_message.delete() except discord.NotFound: pass try: await user_message.delete() except (discord.Forbidden, discord.NotFound, AttributeError): pass # Check conversion didn't fail if conversion_failed: raise SettingsMenuError() # Return converted value return value @classmethod def get_guild_settings_mention( cls, ctx: commands.Context, attr: str, default: str = 'none', ) -> str: """ Get an item from the cached `Bot.guild_settings` object for the running guild and return either it's mention string, or the `default` arg. Args: ctx (commands.Context): The context for the command. attr (str): The attribute we want to mention. default (str, optional): If not found, what should the default be. Returns: str: The mention string. """ settings = ctx.bot.guild_settings[ctx.guild.id] return cls.get_settings_mention(ctx, settings, attr, default) @classmethod def get_user_settings_mention( cls, ctx: commands.Context, attr: str, default: str = 'none', ) -> str: """ Get an item from the cached `Bot.user_settings` object for the running user and return either it's mention string, or the `default` arg. Args: ctx (commands.Context): The context for the command. attr (str): The attribute we want to mention. default (str, optional): If not found, what should the default be. Returns: str: The mention string. """ settings = ctx.bot.user_settings[ctx.author.id] return cls.get_settings_mention(ctx, settings, attr, default) @classmethod def get_settings_mention( cls, ctx: commands.Context, settings: dict, attr: str, default: str = 'none', ) -> str: """ Get an item from the bot's settings. :meta private: Args: ctx (commands.Context): The context for the command. settings (dict): The dictionary with the settings in it that we want to grab. attr (str): The attribute we want to mention. default (str, optional): If not found, what should the default be. Returns: str: The mention string. """ # Run converters if 'channel' in attr.lower().split('_'): data = ctx.bot.get_channel(settings[attr]) elif 'role' in attr.lower().split('_'): data = ctx.guild.get_role(settings[attr]) else: data = settings[attr] if isinstance(data, bool): return str(data).lower() return data # Get mention return cls.get_mention(data, default) @staticmethod def get_mention( data: typing.Union[discord.abc.GuildChannel, discord.Role, None], default: str, ) -> str: """ Get the mention of an object. :meta private: Args: data (typing.Union[discord.abc.GuildChannel, discord.Role, None]): The object we want to mention. default (str): The default string that should be output if we can't mention the object. Returns: str: The mention string. """ mention = data.mention if data else default return mention @classmethod def get_set_guild_settings_callback( cls, table_name: str, column_name: str, serialize_function: typing.Callable[[typing.Any], typing.Any] = None, ) -> typing.Callable[[typing.Any], None]: """ Return an async method that takes the data given by `convert_prompted_information`, then saves it into the database - should be used in the SettingsMenu init. :meta private: Args: table_name (str): The name of the table the data should be inserted into. This is not used when caching information. This should NOT be a user supplied value. column_name (str): The name of the column that the data should be inserted into. This is the same name that's used for caching. This should NOT be a user supplied value. serialize_function (typing.Callable[[typing.Any], typing.Any], optional): The function that is called to convert the input data in the callback into a database-friendly value. This is *not* called for caching the value, only for databasing. The default serialize function doesn't do anything, but is provided so you don't have to provide one yourself. Returns: typing.Callable[[typing.Any], None]: A callable function that sets the guild settings when provided with data """ if serialize_function is None: serialize_function = do_nothing return cls.get_set_settings_callback(table_name, "guild_id", column_name, serialize_function) @classmethod def get_set_user_settings_callback( cls, table_name: str, column_name: str, serialize_function: typing.Callable[[typing.Any], typing.Any] = None, ) -> typing.Callable[[dict], None]: """ Return an async method that takes the data given by `convert_prompted_information`, then saves it into the database - should be used in the SettingsMenu init. :meta private: Args: table_name (str): The name of the table the data should be inserted into. This is not used when caching information. This should NOT be a user supplied value. column_name (str): The name of the column that the data should be inserted into. This is the same name that's used for caching the value. This should NOT be a user supplied value. serialize_function (typing.Callable[[typing.Any], typing.Any], optional): The function that is called to convert the input data in the callback into a database-friendly value. This is *not* called for caching the value, only for databasing. The default serialize function doesn't do anything, but is provided so you don't have to provide one yourself. Returns: typing.Callable[[dict], None]: A callable function that sets the user settings when provided with data """ if serialize_function is None: serialize_function = do_nothing return cls.get_set_settings_callback(table_name, "user_id", column_name, serialize_function) @staticmethod def get_set_settings_callback( table_name: str, primary_key: str, column_name: str, serialize_function: typing.Callable[[typing.Any], typing.Any] = None ) -> typing.Callable[[dict], None]: """ Return an async method that takes the data given by `convert_prompted_information`, then saves it into the database - should be used in the SettingsMenu init. Args: table_name (str): The name of the table the data should be inserted into. This is not used when caching information. This should NOT be a user supplied value. primary_key (str): The primary key of the table that you want to insert to. This *only* supports single primary keys and not compound ones. column_name (str): The name of the column that the data should be inserted into. This is the same name that's used for caching the value. This should NOT be a user supplied value. serialize_function (typing.Callable[[typing.Any], typing.Any], optional): The function that is called to convert the input data in the callback into a database-friendly value. This is *not* called for caching the value, only for databasing. The default serialize function doesn't do anything, but is provided so you don't have to provide one yourself. Returns: typing.Callable[[dict], None]: A callable function that sets the user settings when provided with data """ async def callback(self, data): """ The function that actually sets the data in the specified table in the database. Any input to this function should be a direct converted value from `convert_prompted_information`. If the input is a discord.Role or discord.TextChannel, it is automatcally converted to that value's ID, which is then put into the datbase and cache. """ # See if we need to get the object's ID if isinstance(data, (discord.Role, discord.TextChannel, discord.User, discord.Member, discord.Object, discord.CategoryChannel)): data = data.id # Serialize via the passed serialize function original_data, data = data, serialize_function(data) # Add to the database async with self.context.bot.database() as db: await db( "INSERT INTO {0} ({1}, {2}) VALUES ($1, $2) ON CONFLICT ({1}) DO UPDATE SET {2}=$2".format(table_name, primary_key, column_name), self.context.guild.id, data, ) # Cache self.context.bot.guild_settings[self.context.guild.id][column_name] = original_data # Return the callback return callback @staticmethod def get_set_iterable_delete_callback( table_name: str, column_name: str, cache_key: str, database_key: str, ) -> typing.Callable[[SettingsMenu, commands.Context, int], None]: """ Return an async method that takes the data retuend by `convert_prompted_information` and then saves it into the database - should be used for the SettingsMenu init. Args: table_name (str): The name of the database that you want to remove data from. column_name (str): The column name that the key is inserted into in the table. cache_key (str): The key that's used to access the cached value for the iterable in `bot.guilds_settings`. database_key (str): The key that's used to refer to the role ID in the `role_list` table. Returns: Callable[[SettingsMenu, commands.Context, int], None]: A callable for `SettingsMenuIterable` objects to use. """ def wrapper(menu, ctx, delete_key: int): """ A sync wrapper so that we can return an async callback that deletes from the database. """ async def callback(menu): """ The function that actually deletes the role from the database Any input to this function will be silently discarded, since the actual input to this function is defined in the callback definition. """ # Database it async with ctx.bot.database() as db: await db( "DELETE FROM {0} WHERE guild_id=$1 AND {1}=$2 AND key=$3".format(table_name, column_name), ctx.guild.id, delete_key, database_key ) # Remove the converted value from cache try: ctx.bot.guild_settings[ctx.guild.id][cache_key].remove(delete_key) except AttributeError: ctx.bot.guild_settings[ctx.guild.id][cache_key].pop(delete_key) return callback return wrapper @staticmethod def get_set_iterable_add_callback( table_name: str, column_name: str, cache_key: str, database_key: str, serialize_function: typing.Callable[[typing.Any], str] = None, original_data_type: type = None, ) -> typing.Callable[['SettingsMenu', commands.Context], None]: """ Return an async method that takes the data retuend by `convert_prompted_information` and then saves it into the database - should be used for the SettingsMenu init. This particular iterable can only deal with one convertable datapoint (for a list) or two (for a mapping). Any more than that and you will need to provide your own callback. Args: table_name (str): The name of the database that you want to add data to. column_name (str): The column name that the key is inserted into in the table. cache_key (str): This is the key that's used when caching the value in `bot.guild_settings`. database_key (str): This is the key that the value is added to the database table `role_list`. serialize_function (Callable[[Any], str], optional): The function run on the value to convert it into to make it database-safe. Values are automatically cast to strings after being run through the serialize function. The serialize_function is called when caching the value, but the cached value is not cast to a string. The default serialize function doesn't do anything, but is provided so you don't have to provide one yourself. Returns: Callable[[SettingsMenu, commands.Context], Callable[[SettingsMenu, Any, Optional[Any]], None]]: A callable for `SettingsMenuIterable` objects to use. """ if serialize_function is None: serialize_function = do_nothing def wrapper(menu, ctx): """ A sync wrapper so that we can return an async callback that deletes from the database. """ async def callback(menu, *data): """ The function that actually adds the role to the table in the database Any input to this function will be direct outputs from perform_action's convert_prompted_information This is a function that creates a callback, so the expectation of `data` in this instance is that data is either a list of one item for a listing, eg [role_id], or a list of two items for a mapping, eg [role_id, value] """ # Unpack the data try: role, original_value = data value = str(serialize_function(original_value)) except ValueError: role, value = data[0], None # Database it async with ctx.bot.database() as db: await db( """INSERT INTO {0} (guild_id, {1}, key, value) VALUES ($1, $2, $3, $4) ON CONFLICT (guild_id, {1}, key) DO UPDATE SET value=excluded.value""".format(table_name, column_name), ctx.guild.id, role.id, database_key, value ) # Set the original value for the cache if original_data_type is not None: ctx.bot.guild_settings[ctx.guild.id].setdefault(cache_key, original_data_type()) # Cache the converted value if value: ctx.bot.guild_settings[ctx.guild.id][cache_key][role.id] = serialize_function(original_value) else: if role.id not in ctx.bot.guild_settings[ctx.guild.id][cache_key]: ctx.bot.guild_settings[ctx.guild.id][cache_key].append(role.id) return callback return wrapper class SettingsMenu: """ A settings menu object for setting up sub-menus or bot settings using reactions. Each menu object must be added as its own command, with sub-menus being referred to by string in the MenuItem's action. Examples: :: # We can pull out the settings menu mention method so that we can more easily refer to it in our lambdas. settings_mention = vbu.menus.SettingsMenuOption.get_guild_settings_mention # Make an initial menu. menu = vbu.menus.SettingsMenu() # And now we add some options. menu.add_multiple_options( # Every option that's added needs to be an instance of SettingsMenuOption. vbu.menus.SettingsMenuOption( # The first argument is the context, always. ctx=ctx, # Display is either a string, or a function that takes context as an argument to *return* # a string. display=lambda c: "Set quote channel (currently {0})".format(settings_mention(c, 'quote_channel_id')), # Converter args should be a list of SettingsMenuConverter options if present. These are the questions # asked to the user to get the relevant information out of them. converter_args=( vbu.menus.SettingsMenuConverter( # Prompt is what's asked to the user prompt="What do you want to set the quote channel to?", # Converter is either a converter or a function that's run to convert the given argument. converter=commands.TextChannelConverter, ), ), # Callback is a function that's run with the converted information to store the data in a database # or otherwise. callback=vbu.menus.SettingsMenuOption.get_set_guild_settings_callback('guild_settings', 'quote_channel_id'), ), # This is an option that calls a subcommand, also running some SettingsMenu code. vbu.menus.SettingsMenuOption( ctx=ctx, display="Set up VC max members", callback=self.bot.get_command("setup vcmaxmembers"), ), ) # And now we can run the menu try: await menu.start(ctx) await ctx.send("Done setting up!") except voxelbotutils.errors.InvokedMetaCommand: pass """ TICK_EMOJI = "\N{HEAVY CHECK MARK}" PLUS_EMOJI = "\N{HEAVY PLUS SIGN}" def add_option(self, option: SettingsMenuOption): """ Add an option to the settings list. Args: option (SettingsMenuOption): The option that you want to add to the menu. """ self.options.append(option) def add_multiple_options(self, *option: SettingsMenuOption): """ Add multiple options to the settings list at once. Args: *option (SettingsMenuOption): A list of options that you want to add to the menu. """ self.options.extend(option) async def start(self, ctx: commands.Context, *, timeout: float = 120): """ Starts the menu running. Args: ctx (commands.Context): The context object for the called command. timeout (float, optional): How long the bot should wait for a reaction. """ message = None while True: # Send message self.emoji_options.clear() data, emoji_list = self.get_sendable_data(ctx) if message is None: message = await ctx.send(**data) else: await message.edit(**data) # Get the reaction try: payload = await ctx.bot.wait_for("component_interaction", check=check, timeout=timeout) await payload.response.defer_update() except asyncio.TimeoutError: break picked_emoji = str(payload.component.custom_id) # Get the picked option try: picked_option = self.emoji_options[picked_emoji] except KeyError: continue # Process the picked option if picked_option is None: break try: await picked_option.perform_action() except SettingsMenuError: pass # Delete all the processing stuff try: await message.delete() except (discord.NotFound, discord.Forbidden, discord.HTTPException): pass def get_sendable_data( self, ctx: commands.Context ) -> typing.Tuple[dict, typing.List[str]]: """ Get a valid set of sendable data for the destination. Args: ctx (commands.Context): Just so we can set the invoke meta flag. Returns: Tuple[dict, List[str]]: A tuple of the sendable data for the destination that can be unpacked into a `discord.abc.Messageable.send`, and a list of emoji to add to the message in question. """ ctx.invoke_meta = True # Create embed embed = discord.Embed() lines = [] emoji_list = [] index = 0 for index, i in enumerate(self.options): emoji = i.emoji if emoji is None: emoji = f"{index}" index += 1 display = i.get_display() if display: lines.append(f"{emoji}) {i.get_display()}") self.emoji_options[emoji] = i emoji_list.append(emoji) # Finish embed text_lines = '\n'.join(lines) embed.description = text_lines or "No set data" # Add tick self.emoji_options[self.TICK_EMOJI] = None emoji_list.append(self.TICK_EMOJI) buttons = [ discord.ui.Button(emoji=i, custom_id=i) for i in emoji_list ] buttons += [ discord.ui.Button(label="Done", custom_id="done", style=discord.ui.ButtonStyle.success) ] components = discord.ui.MessageComponents.add_buttons_with_rows(*buttons) # Return data return {'embed': embed, "components": components}, emoji_list class SettingsMenuIterable(SettingsMenu): """ A version of the settings menu for dealing with things like lists and dictionaries. """ def __init__( self, table_name: str, column_name: str, cache_key: str, database_key: str, key_display_function: typing.Callable[[typing.Any], str], value_display_function: typing.Callable[[typing.Any], str] = str, converters: typing.List[SettingsMenuConverter] = None, *, iterable_add_callback: typing.Callable[['SettingsMenu', commands.Context], None] = None, iterable_delete_callback: typing.Callable[['SettingsMenu', commands.Context, int], None] = None, ): """ Args: table_name (str): The name of the table that the data should be inserted into. column_name (str): The column name for the table where the key should be inserted to. cache_key (str): The key that goes into `bot.guild_settings` to get to the cached iterable. database_key (str): The key that would be inserted into the default `role_list` or `channel_list` tables. If you're not using this field then this will probably be pretty useless to you. key_display_function (typing.Callable[[typing.Any], str]): A function used to take the raw data from the key and change it into a display value. value_display_function (typing.Callable[[typing.Any], str], optional): The function used to take the saved raw value from the database and nicely show it to the user in the embed. converters (typing.List[SettingsMenuConverter], optional): A list of the converters that should be used for the user to provide their new values for the menu. iterable_add_callback (typing.Callable[['SettingsMenu', commands.Context], None], optional): A function that's run with the params of the database name, the column name, the cache key, the database key, and the value serialize function. If left blank then it defaults to making a new callback for you that just adds to the `role_list` or `channel_list` table as specified. These methods are only directly compatible with lists and dictionaries - nothing that requires multiple arguments to be saved in a database; for those you will need to write your own method. iterable_delete_callback (typing.Callable[['SettingsMenu', commands.Context, int], None], optional): A function that's run with the params of the database name, the column name, the item to be deleted, the cache key, and the database key. If left blank then it defaults to making a new callback for you that just deletes from the `role_list` or `channel_list` table as specified. These methods are only directly compatible with lists and dictionaries - nothing that requires multiple arguments to be saved in a database; for those you will need to write your own method. """ try: if converters or not converters[0]: pass except Exception as e: raise ValueError("You need to provide at least one converter.") from e super().__init__() # Set up the storage data self.table_name = table_name self.column_name = column_name self.cache_key = cache_key self.database_key = database_key # Converters self.key_display_function = key_display_function self.value_display_function = value_display_function self.converters = converters # Add callback self.iterable_add_callback = iterable_add_callback or SettingsMenuOption.get_set_iterable_add_callback( table_name=table_name, column_name=column_name, cache_key=cache_key, database_key=database_key, serialize_function=str if len(self.converters) == 1 else self.converters[1].serialize, original_data_type=list if len(self.converters) == 1 else dict, ) # This default returns an async function which takes the content of the converted values which adds to the db. # Callable[ # [SettingsMenu, commands.Context], # Callable[ # [SettingsMenu, *typing.Any], # None # ] # ] # Delete callback self.iterable_delete_callback = iterable_delete_callback or SettingsMenuOption.get_set_iterable_delete_callback( table_name=table_name, column_name=column_name, cache_key=cache_key, database_key=database_key, ) # This default returns an async function which takes the content of the converted values which removes from the db. # Callable[ # [SettingsMenu, commands.Context, int], # Callable[ # [SettingsMenu], # None # ] # ]
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 11748, 30351, 952, 198, 11748, 19720, 198, 198, 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 198, 6738, 764, 48277, 1330, 10001, 6545, 48526, 21575, 628, 628, 198, 198, 4871, ...
2.333698
14,618
# # Copyright 2021 XEBIALABS # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # import json from ispw.AssignmentClient import AssignmentClient from ispw.ReleaseClient import ReleaseClient from ispw.SetClient import SetClient from ispw.TestConnectionClient import TestConnectionClient
[ 2, 198, 2, 15069, 33448, 1395, 36, 3483, 1847, 32, 4462, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 286, 428, 3788, 290, 3917, 10314, 3696, 357, 1169, 366, 25423, 12340, ...
4.067308
312
# -*- coding: utf-8 -*- from ._metric_learning import metric_learning from ._metric_learning_minibatch import metric_learning_minibatch from ._reference_centers import reference_centers from ._spatial_reconstruction import spatial_reconstruction __version__ = '0.1.0'
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 47540, 4164, 1173, 62, 40684, 1330, 18663, 62, 40684, 198, 6738, 47540, 4164, 1173, 62, 40684, 62, 1084, 571, 963, 1330, 18663, 62, 40684, 62, 1084, 571, 963,...
3.074468
94
#간단한 인사말
[ 2, 166, 108, 226, 46695, 101, 47991, 250, 23821, 251, 116, 168, 8955, 167, 100, 238, 628 ]
0.588235
17
""" Define some functions used in concrete domain. """ import torch from torch import Tensor from torch.nn import functional as F from diffabs.abs import MetaFunc from diffabs.utils import reduce_dim_dists class ConcDist(MetaFunc): """ Similar to AbsEle in abs.py, it needs the distance for concrete data points as well. Implementation similar to the non-relational interval domain. Note that no eps is set for ConcDist, it could, but it is fine since ConcDist is mainly used for validation but not training. """ @classmethod @classmethod @classmethod @classmethod @classmethod @classmethod @classmethod @classmethod pass
[ 37811, 2896, 500, 617, 5499, 973, 287, 10017, 7386, 13, 37227, 198, 198, 11748, 28034, 198, 6738, 28034, 1330, 309, 22854, 198, 6738, 28034, 13, 20471, 1330, 10345, 355, 376, 198, 198, 6738, 814, 8937, 13, 8937, 1330, 30277, 37, 19524, ...
3.258216
213
from django.conf.urls import url from .views import serve_all urlpatterns = ( url(r'^.*$', serve_all, name="localsrv:serve_all"), )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 764, 33571, 1330, 4691, 62, 439, 198, 198, 6371, 33279, 82, 796, 357, 198, 220, 220, 220, 19016, 7, 81, 6, 61, 15885, 3, 3256, 4691, 62, 439, 11, 1438, 2625, 179...
2.472727
55
import unittest from collections import namedtuple, defaultdict import numpy as np import torch from ptan.experience import ExperienceSourceFirstLast from tqdm import tqdm from irelease.data import GeneratorData from irelease.env import MoleculeEnv from irelease.model import Encoder, PositionalEncoding, StackDecoderLayer, LinearOut, StackRNN, RNNLinearOut, RewardNetRNN from irelease.reward import RewardFunction from irelease.rl import PolicyAgent, MolEnvProbabilityActionSelector, REINFORCE, GuidedRewardLearningIRL, \ StateActionProbRegistry from irelease.stackrnn import StackRNNCell from irelease.utils import init_hidden, init_stack, get_default_tokens, init_hidden_2d, init_stack_2d, init_cell, seq2tensor gen_data_path = '../data/chembl_xsmall.smi' tokens = get_default_tokens() # print(f'Number of tokens = {len(tokens)}') gen_data = GeneratorData(training_data_path=gen_data_path, delimiter='\t', cols_to_read=[0], keep_header=True, tokens=tokens, tokens_reload=True) bz = 32 if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 201, 198, 6738, 17268, 1330, 3706, 83, 29291, 11, 4277, 11600, 201, 198, 11748, 299, 32152, 355, 45941, 201, 198, 11748, 28034, 201, 198, 6738, 279, 38006, 13, 23100, 1240, 1330, 16386, 7416, 5962, 5956, 201, 198, ...
2.70936
406
import torch from torch.utils.data import Dataset import json import numpy as np import os from PIL import Image from torchvision import transforms as T try: from .ray_utils import * except : from ray_utils import * import glob import cv2 if __name__ == '__main__': import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import random train_ds = NvisiiDataset( # root_dir='../falling_google_1/', # split='val', # root_dir='/home/titans/code/nerf_pytorch/data_tmp/falling_google_1/', root_dir='/home/jtremblay/code/conditional-gan-inverse-rendering/S-GAN/falling_1/falling_google_1/', split='train', img_wh=(400, 400) ) cam_pos = [] ray_end = [] rgbs = [] for ii in range(100): i = random.randint(0,len(train_ds)-1) data = train_ds[i]['rays'] rgbs.append(train_ds[i]['rgbs']) cam_pos.append([data[0],data[1],data[2],]) ray_end.append([data[3],data[4],data[5],]) # print(train_ds[0]['rays'] visualize_ray(np.array(cam_pos),np.array(ray_end),np.array(rgbs)) train_ds[0]['rays'] # for i in range(len(train_ds)): # item = train_ds[i] # c2w = item["c2w"] # c2w = torch.cat((c2w, torch.FloatTensor([[0, 0, 0, 1]])), dim=0) # #np.save("nvisii_c2ws/c2w{}.npy".format(i), c2w.numpy())
[ 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 16092, 292, 316, 198, 11748, 33918, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28686, 198, 6738, 350, 4146, 1330, 7412, 198, 6738, 28034, 10178, 1330, 31408, 355, 309, 198, ...
2.06305
682
from enum import Enum
[ 6738, 33829, 1330, 2039, 388, 201, 198, 201, 198 ]
2.777778
9
'''Example of class decorator to make sure some attributes are always Decimal''' from decimal import Decimal from operator import attrgetter def decimals(cls): '''A class decorator that ensures all attributes specifiec in the class __decimals__ will be Decimal. Make sure your class is a new style class (inherits from object), otherwise this won't work. Example: >>> @decimals ... class Sale(object): ... __decimals__ = ['price'] ... def __init__(self, item, price): ... self.item = item ... self.price = price ... >>> s1 = Sale('socks', 11.2) >>> type(s1.price) <class 'decimal.Decimal'> >>> s1.price = 70 >>> type(s1.price) <class 'decimal.Decimal'> >>> ''' for attr in cls.__decimals__: name = '_{}'.format(attr) getter = attrgetter(name) setter = make_setter(name) setattr(cls, attr, property(getter, setter, None, attr)) return cls if __name__ == '__main__': import doctest doctest.testmod()
[ 7061, 6, 16281, 286, 1398, 11705, 1352, 284, 787, 1654, 617, 12608, 389, 1464, 4280, 4402, 7061, 6, 198, 198, 6738, 32465, 1330, 4280, 4402, 198, 6738, 10088, 1330, 708, 81, 1136, 353, 198, 198, 4299, 875, 320, 874, 7, 565, 82, 2599...
2.407745
439
import os from numpy import * from matplotlib.pyplot import * from netCDF4 import Dataset from pylab import * from mpl_util import LevelColormap import pyroms import pyroms_toolbox from mpl_toolkits.basemap import Basemap, shiftgrid import mpl_toolkits.basemap as mp from bathy_smoother import * import mpl_util import laplace_filter from bathy_smoother import * __author__ = 'Trond Kristiansen' __email__ = 'trond.kristiansen@imr.no' __created__ = datetime.datetime(2015, 7, 30) __modified__ = datetime.datetime(2015, 7, 30) __version__ = "1.0" __status__ = "Development, 30.7.2015" """Get the grid file defined in /Users/trondkr/Projects/KINO/map/gridid.txt""" grd = pyroms.grid.get_ROMS_grid('KINO1600M') """ Check bathymetry roughness """ print "Checking rougness" RoughMat = bathy_tools.RoughnessMatrix(grd.vgrid.h, grd.hgrid.mask_rho) print '1a: Max Roughness value in file is: ', RoughMat.max()
[ 11748, 28686, 198, 6738, 299, 32152, 1330, 1635, 198, 6738, 2603, 29487, 8019, 13, 9078, 29487, 1330, 1635, 198, 6738, 2010, 34, 8068, 19, 1330, 16092, 292, 316, 198, 6738, 279, 2645, 397, 1330, 1635, 198, 6738, 285, 489, 62, 22602, 1...
2.639769
347
# Copyright (C) 2013-present The DataCentric Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import attr from datacentric.storage.data import Data from datacentric.schema.declaration.value_param_type import ValueParamType @attr.s(slots=True, auto_attribs=True) class ValueDecl(Data): """Value or atomic element declaration.""" type: ValueParamType = attr.ib(default=None, kw_only=True, metadata={'optional': True}) """Value or atomic element type enumeration."""
[ 2, 15069, 357, 34, 8, 2211, 12, 25579, 383, 6060, 19085, 1173, 46665, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846...
3.530466
279
import core from dominate.tags import * class Header(): ''' Header for pages with NavBar. ''' @staticmethod # pylama:ignore=W0401
[ 11748, 4755, 198, 6738, 17863, 13, 31499, 1330, 1635, 628, 198, 4871, 48900, 33529, 198, 220, 220, 220, 705, 7061, 48900, 329, 5468, 351, 13244, 10374, 13, 198, 220, 220, 220, 705, 7061, 628, 220, 220, 220, 2488, 12708, 24396, 198, 19...
2.754717
53
# GENERATED BY KOMAND SDK - DO NOT EDIT import insightconnect_plugin_runtime import json
[ 2, 24700, 1137, 11617, 11050, 509, 2662, 6981, 26144, 532, 8410, 5626, 48483, 198, 11748, 11281, 8443, 62, 33803, 62, 43282, 198, 11748, 33918, 628, 198, 220, 220, 220, 220, 198, 220, 220, 220, 220, 628 ]
2.833333
36
from .base import Term from .constant import Constant from .image import Image from .network import Network from .parameter import Parameter from .symbol import Symbol __all__ = ["Constant", "Image", "Network", "Parameter", "Symbol", "Term"]
[ 6738, 764, 8692, 1330, 35118, 198, 6738, 764, 9979, 415, 1330, 20217, 198, 6738, 764, 9060, 1330, 7412, 198, 6738, 764, 27349, 1330, 7311, 198, 6738, 764, 17143, 2357, 1330, 25139, 2357, 198, 6738, 764, 1837, 23650, 1330, 38357, 198, 19...
3.681818
66
""" Created on Fri Jul 23 18:02:49 2021 @author: Nelson Mosquera (Monotera) """ # Problema 1 import math import numpy as np print("Raiz cuadrarda de 7 con una tolerancia de 10^-8 ", sqrt(7, 10**-124, 1)) print("Raiz cuadrarda de 7 con una tolerancia de 10^-16 ", sqrt(7, 10**-16, 1)) print("Raiz cuadrarda de 7 utilizando funcion de python sqrt ", math.sqrt(7))
[ 37811, 198, 41972, 319, 19480, 5979, 2242, 1248, 25, 2999, 25, 2920, 33448, 198, 198, 31, 9800, 25, 12996, 5826, 421, 8607, 357, 9069, 313, 8607, 8, 198, 37811, 198, 198, 2, 1041, 903, 2611, 352, 198, 11748, 10688, 198, 11748, 299, ...
2.503401
147
# -*- coding: utf-8 -*- """ /dms/redirect/views_show.py .. zeigt den Inhalt einer Weiterleitung an Django content Management System Hans Rauch hans.rauch@gmx.net Die Programme des dms-Systems koennen frei genutzt und den spezifischen Beduerfnissen entsprechend angepasst werden. 0.01 23.01.2007 Beginn der Arbeit """ import string from django.http import HttpResponseRedirect from django.utils.translation import ugettext as _ from dms_ext.extension import * # dms-Funktionen ueberschreiben # ----------------------------------------------------- def redirect_show(request, item_container): """ zeigt den Inhalt der Weiterleitung """ if string.find(item_container.item.url_more, 'http://') < 0: site = item_container.container.site path = item_container.container.path + item_container.item.url_more length=len(site.base_folder) if length < len(path): url = site.url + path[length:] else : url = site.url + '/' else: url = item_container.item.url_more return HttpResponseRedirect(url)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 14, 67, 907, 14, 445, 1060, 14, 33571, 62, 12860, 13, 9078, 198, 198, 492, 41271, 328, 83, 2853, 554, 71, 2501, 304, 7274, 775, 2676, 293, 270, 2150, 281...
2.693095
391
# # This file is part of pyasn1-alt-modules software. # # Created by Russ Housley with assistance from asn1ate v.0.6.0. # Modified by Russ Housley to include the opentypemap manager. # # Copyright (c) 2019-2022, Vigil Security, LLC # License: http://vigilsec.com/pyasn1-alt-modules-license.txt # # RPKI Route Origin Authorizations (ROAs) # # ASN.1 source from: # https://www.rfc-editor.org/rfc/rfc6482.txt # https://www.rfc-editor.org/errata/eid5881 # from pyasn1.type import constraint from pyasn1.type import namedtype from pyasn1.type import tag from pyasn1.type import univ from pyasn1_alt_modules import rfc5652 from pyasn1_alt_modules import opentypemap cmsContentTypesMap = opentypemap.get('cmsContentTypesMap') MAX = float('inf') id_ct_routeOriginAuthz = univ.ObjectIdentifier('1.2.840.113549.1.9.16.1.24') # Update the CMS Content Types Map _cmsContentTypesMapUpdate = { id_ct_routeOriginAuthz: RouteOriginAttestation(), } cmsContentTypesMap.update(_cmsContentTypesMapUpdate)
[ 2, 198, 2, 770, 2393, 318, 636, 286, 12972, 292, 77, 16, 12, 2501, 12, 18170, 3788, 13, 198, 2, 198, 2, 15622, 416, 1887, 367, 516, 1636, 351, 6829, 422, 355, 77, 16, 378, 410, 13, 15, 13, 21, 13, 15, 13, 198, 2, 40499, 416,...
2.713514
370
"""Support for building extensions using mypyc with distutils or setuptools The main entry points are mypycify, which produces a list of extension modules to be passed to setup, and MypycifyBuildExt, which must be registered as a BuildExt command. A trivial setup.py for a mypyc built project, then, looks like: from distutils.core import setup from mypyc.build import mypycify, MypycifyBuildExt setup(name='test_module', ext_modules=mypycify(['foo.py']), cmdclass={{'build_ext': MypycifyBuildExt}}, See the mypycify docs for additional arguments. Because MypycifyBuildExt needs to inherit from the distutils/setuputils build_ext, we need to know at import-time whether we are using distutils or setuputils. We hackily decide based on whether setuptools has been imported already. """ import glob import sys import os.path import subprocess import hashlib import time import shutil from typing import List, Tuple, Any, Optional, Union, Dict, cast MYPY = False if MYPY: from typing import NoReturn from mypy.main import process_options from mypy.errors import CompileError from mypy.options import Options from mypy.build import BuildSource from mypyc.namegen import exported_name from mypyc import emitmodule # We can work with either setuptools or distutils, and pick setuptools # if it has been imported. assert 'setuptools' in sys.modules or 'distutils' in sys.modules, ( "'setuptools' or 'distutils' must be imported before mypyc.build") USE_SETUPTOOLS = 'setuptools' in sys.modules if USE_SETUPTOOLS: from setuptools import setup, Extension # type: ignore from setuptools.command.build_ext import build_ext # type: ignore else: from distutils.core import setup, Extension from distutils.command.build_ext import build_ext # type: ignore from distutils import sysconfig, ccompiler def setup_mypycify_vars() -> None: """Rewrite a bunch of config vars in pretty dubious ways.""" # There has to be a better approach to this. # The vars can contain ints but we only work with str ones vars = cast(Dict[str, str], sysconfig.get_config_vars()) if sys.platform == 'darwin': # On OS X, force the creation of dynamic libraries instead of bundles so that # we can link against multi-module shared libraries. # From https://stackoverflow.com/a/32765319 vars['LDSHARED'] = vars['LDSHARED'].replace('-bundle', '-dynamiclib') # Also disable building 32-bit binaries, since we generate too much code # for a 32-bit Mach-O object. There has to be a better way to do this. vars['LDFLAGS'] = vars['LDFLAGS'].replace('-arch i386', '') vars['CFLAGS'] = vars['CFLAGS'].replace('-arch i386', '') class MypycifyExtension(Extension): """Represents an Extension generated by mypyc. Stores a little bit of extra metadata to support that. Arguments: * is_mypyc_shared: True if this is a shared library generated to implement multiple modules * mypyc_shared_target: If this is a shim library, a reference to the shared library that actually contains the implementation of the module """ def get_mypy_config(paths: List[str], mypy_options: Optional[List[str]]) -> Tuple[List[BuildSource], Options]: """Construct mypy BuildSources and Options from file and options lists""" # It is kind of silly to do this but oh well mypy_options = mypy_options or [] mypy_options.append('--') mypy_options.extend(paths) sources, options = process_options(mypy_options) if options.python_version[0] == 2: fail('Python 2 not supported') if not options.strict_optional: fail('Disabling strict optional checking not supported') options.show_traceback = True # Needed to get types for all AST nodes options.export_types = True # TODO: Support incremental checking options.incremental = False for source in sources: options.per_module_options.setdefault(source.module, {})['mypyc'] = True return sources, options shim_template_unix = """\ #include <Python.h> PyObject *CPyInit_{full_modname}(void); PyMODINIT_FUNC PyInit_{modname}(void) {{ return CPyInit_{full_modname}(); }} """ # As far as I could tell, Windows lacks the rpath style features we # would need in automatically load the shared library (located # relative to the module library) when a module library is loaded, # which means that instead we get to do it dynamically. # # We do this by, at module initialization time, finding the location # of the module dll and using it to compute the location of the shared # library. We then load the shared library with LoadLibrary, find the # appropriate CPyInit_ routine using GetProcAddress, and call it. # # The relative path of the shared library (from the shim library) is provided # as the preprocessor define MYPYC_LIBRARY. shim_template_windows = r"""\ #include <Python.h> #include <windows.h> #include <stdlib.h> #include <stdio.h> EXTERN_C IMAGE_DOS_HEADER __ImageBase; typedef PyObject *(__cdecl *INITPROC)(); PyMODINIT_FUNC PyInit_{modname}(void) {{ char path[MAX_PATH]; char drive[MAX_PATH]; char directory[MAX_PATH]; HINSTANCE hinstLib; INITPROC proc; // get the file name of this dll DWORD res = GetModuleFileName((HINSTANCE)&__ImageBase, path, sizeof(path)); if (res == 0 || res == sizeof(path)) {{ PyErr_SetString(PyExc_RuntimeError, "GetModuleFileName failed"); return NULL; }} // find the directory this dll is in _splitpath(path, drive, directory, NULL, NULL); // and use it to construct a path to the shared library snprintf(path, sizeof(path), "%s%s%s", drive, directory, MYPYC_LIBRARY); hinstLib = LoadLibrary(path); if (!hinstLib) {{ PyErr_SetString(PyExc_RuntimeError, "LoadLibrary failed"); return NULL; }} proc = (INITPROC)GetProcAddress(hinstLib, "CPyInit_{full_modname}"); if (!proc) {{ PyErr_SetString(PyExc_RuntimeError, "GetProcAddress failed"); return NULL; }} return proc(); }} // distutils sometimes spuriously tells cl to export CPyInit___init__, // so provide that so it chills out PyMODINIT_FUNC PyInit___init__(void) {{ return PyInit_{modname}(); }} """ def generate_c_extension_shim(full_module_name: str, module_name: str, dirname: str) -> str: """Create a C extension shim with a passthrough PyInit function.""" cname = '%s.c' % full_module_name.replace('.', '___') # XXX cpath = os.path.join(dirname, cname) with open(cpath, 'w') as f: shim_template = shim_template_windows if sys.platform == 'win32' else shim_template_unix f.write(shim_template.format(modname=module_name, full_modname=exported_name(full_module_name))) return cpath def shared_lib_name(modules: List[str]) -> str: """Produce a probably unique name for a library from a list of module names.""" h = hashlib.sha1() h.update(','.join(modules).encode()) return 'mypyc_%s' % h.hexdigest()[:20] def include_dir() -> str: """Find the path of the lib-rt dir that needs to be included""" return os.path.join(os.path.abspath(os.path.dirname(__file__)), 'lib-rt') def generate_c(sources: List[BuildSource], options: Options, multi_file: bool, shared_lib_name: Optional[str], verbose: bool = False) -> Tuple[List[Tuple[str, str]], str]: """Drive the actual core compilation step. Returns the C source code and (for debugging) the pretty printed IR. """ module_names = [source.module for source in sources] # Do the actual work now t0 = time.time() try: result = emitmodule.parse_and_typecheck(sources, options) except CompileError as e: for line in e.messages: print(line) fail('Typechecking failure') t1 = time.time() if verbose: print("Parsed and typechecked in {:.3f}s".format(t1 - t0)) ops = [] # type: List[str] ctext = emitmodule.compile_modules_to_c(result, module_names, shared_lib_name, multi_file, ops=ops) t2 = time.time() if verbose: print("Compiled to C in {:.3f}s".format(t2 - t1)) return ctext, '\n'.join(ops) def build_using_shared_lib(sources: List[BuildSource], lib_name: str, cfiles: List[str], build_dir: str, extra_compile_args: List[str], ) -> List[MypycifyExtension]: """Produce the list of extension modules when a shared library is needed. This creates one shared library extension module that all of the others link against and then one shim extension module for each module in the build, that simply calls an initialization function in the shared library. We treat the shared library as a python extension so that it is cleanly processed by setuptools, but it isn't *really* a python C extension module on its own. """ shared_lib = MypycifyExtension( 'lib' + lib_name, is_mypyc_shared=True, sources=cfiles, include_dirs=[include_dir()], extra_compile_args=extra_compile_args, ) extensions = [shared_lib] for source in sources: module_name = source.module.split('.')[-1] shim_file = generate_c_extension_shim(source.module, module_name, build_dir) # We include the __init__ in the "module name" we stick in the Extension, # since this seems to be needed for it to end up in the right place. full_module_name = source.module assert source.path if os.path.split(source.path)[1] == '__init__.py': full_module_name += '.__init__' extensions.append(MypycifyExtension( full_module_name, mypyc_shared_target=shared_lib, sources=[shim_file], extra_compile_args=extra_compile_args, )) return extensions def build_single_module(sources: List[BuildSource], cfiles: List[str], extra_compile_args: List[str], ) -> List[MypycifyExtension]: """Produce the list of extension modules for a standalone extension. This contains just one module, since there is no need for a shared module. """ return [MypycifyExtension( sources[0].module, sources=cfiles, include_dirs=[include_dir()], extra_compile_args=extra_compile_args, )] def mypycify(paths: List[str], mypy_options: Optional[List[str]] = None, opt_level: str = '3', multi_file: bool = False, skip_cgen: bool = False, verbose: bool = False) -> List[MypycifyExtension]: """Main entry point to building using mypyc. This produces a list of Extension objects that should be passed as the ext_modules parameter to setup. Arguments: * paths: A list of file paths to build. It may contain globs. * mypy_options: Optionally, a list of command line flags to pass to mypy. (This can also contain additional files, for compatibility reasons.) * opt_level: The optimization level, as a string. Defaults to '3' (meaning '-O3'). """ setup_mypycify_vars() # Create a compiler object so we can make decisions based on what # compiler is being used. typeshed is missing some attribues on the # compiler object so we give it type Any compiler = ccompiler.new_compiler() # type: Any sysconfig.customize_compiler(compiler) expanded_paths = [] for path in paths: expanded_paths.extend(glob.glob(path)) build_dir = 'build' # TODO: can this be overridden?? try: os.mkdir(build_dir) except FileExistsError: pass sources, options = get_mypy_config(expanded_paths, mypy_options) # We generate a shared lib if there are multiple modules or if any # of the modules are in package. (Because I didn't want to fuss # around with making the single module code handle packages.) use_shared_lib = len(sources) > 1 or any('.' in x.module for x in sources) lib_name = shared_lib_name([source.module for source in sources]) if use_shared_lib else None # We let the test harness make us skip doing the full compilation # so that it can do a corner-cutting version without full stubs. # TODO: Be able to do this based on file mtimes? if not skip_cgen: cfiles, ops_text = generate_c(sources, options, multi_file, lib_name, verbose) # TODO: unique names? with open(os.path.join(build_dir, 'ops.txt'), 'w') as f: f.write(ops_text) cfilenames = [] for cfile, ctext in cfiles: cfile = os.path.join(build_dir, cfile) with open(cfile, 'w', encoding='utf-8') as f: f.write(ctext) if os.path.splitext(cfile)[1] == '.c': cfilenames.append(cfile) else: cfilenames = glob.glob(os.path.join(build_dir, '*.c')) cflags = [] # type: List[str] if compiler.compiler_type == 'unix': cflags += [ '-O{}'.format(opt_level), '-Werror', '-Wno-unused-function', '-Wno-unused-label', '-Wno-unreachable-code', '-Wno-unused-variable', '-Wno-trigraphs', '-Wno-unused-command-line-argument' ] if 'gcc' in compiler.compiler[0]: # This flag is needed for gcc but does not exist on clang. cflags += ['-Wno-unused-but-set-variable'] elif compiler.compiler_type == 'msvc': if opt_level == '3': opt_level = '2' cflags += [ '/O{}'.format(opt_level), '/wd4102', # unreferenced label '/wd4101', # unreferenced local variable '/wd4146', # negating unsigned int ] if multi_file: # Disable whole program optimization in multi-file mode so # that we actually get the compilation speed and memory # use wins that multi-file mode is intended for. cflags += [ '/GL-', '/wd9025', # warning about overriding /GL ] # Copy the runtime library in rt_file = os.path.join(build_dir, 'CPy.c') shutil.copyfile(os.path.join(include_dir(), 'CPy.c'), rt_file) cfilenames.append(rt_file) if use_shared_lib: assert lib_name extensions = build_using_shared_lib(sources, lib_name, cfilenames, build_dir, cflags) else: extensions = build_single_module(sources, cfilenames, cflags) return extensions class MypycifyBuildExt(build_ext): """Custom setuptools/distutils build_ext command. This overrides the build_extension method so that we can hook in before and after the actual compilation. The key thing here is that we need to hook in after compilation on OS X, because we need to use `install_name_tool` to fix up the libraries to use relative paths. We hook in before compilation to update library paths to include where the built shared library is placed. (We probably could have hacked this together without hooking in here, but we were hooking in already and build_ext makes it easy to get that information) """
[ 37811, 15514, 329, 2615, 18366, 1262, 616, 9078, 66, 351, 1233, 26791, 393, 900, 37623, 10141, 198, 198, 464, 1388, 5726, 2173, 389, 616, 9078, 66, 1958, 11, 543, 11073, 257, 1351, 286, 7552, 198, 18170, 284, 307, 3804, 284, 9058, 11,...
2.572948
6,018
from Middleware import * if __name__ == '__main__': fecth_ark_data()
[ 6738, 6046, 1574, 1330, 1635, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 277, 478, 71, 62, 668, 62, 7890, 3419 ]
2.517241
29
import os import pymongo import json import random import hashlib import time from flask import jsonify from hashlib import sha256 import redis def dummy(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`. """ if request.method == 'OPTIONS': # Allows GET requests from origin https://mydomain.com with # Authorization header headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST', 'Access-Control-Allow-Headers': '*', 'Access-Control-Max-Age': '3600', 'Access-Control-Allow-Credentials': 'true' } return ('', 204, headers) # Set CORS headers for main requests headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' } request_json = request.get_json() db = initsystem() if request.method == 'GET': msg = db.get('sahaywelcome') msg = msg.decode() return msg retjson = {} action = request_json['action'] if action == "getmeds": meds = r.get('meds') return json.dumps({"length": len(meds), "meds": meds}) if action == "getplasma": plasma = r.get('plasma') return json.dumps({"length": len(plasma), "meds": plasma}) if action == "getblood": blood = r.get('blood') return json.dumps({"length": len(blood), "meds": blood}) retstr = "action not done" if request.args and 'message' in request.args: return request.args.get('message') elif request_json and 'message' in request_json: return request_json['message'] else: return retstr
[ 11748, 28686, 198, 11748, 279, 4948, 25162, 198, 11748, 33918, 198, 11748, 4738, 198, 198, 11748, 12234, 8019, 198, 11748, 640, 198, 6738, 42903, 1330, 33918, 1958, 198, 198, 6738, 12234, 8019, 1330, 427, 64, 11645, 198, 11748, 2266, 271,...
2.223052
937
import sys from PyQt5.QtGui import QImage from PyQt5.QtWidgets import QLabel from commonwidgets import *
[ 11748, 25064, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 8205, 72, 1330, 1195, 5159, 198, 6738, 9485, 48, 83, 20, 13, 48, 83, 54, 312, 11407, 1330, 1195, 33986, 198, 198, 6738, 2219, 28029, 11407, 1330, 1635, 628, 198 ]
2.634146
41
# -*- coding: utf-8 -*- """ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and not-for-profit purposes, without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-7201, otl@berkeley.edu, http://ipira.berkeley.edu/industry-info for commercial licensing opportunities. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. Simple utility functions. Authors ------- Jeff Mahler, Vishal Satish, Lucas Manuelli """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from functools import reduce import os import sys import numpy as np from autolab_core import Logger from .enums import GripperMode # Set up logger. logger = Logger.get_logger("gqcnn/utils/utils.py") def set_cuda_visible_devices(gpu_list): """Sets CUDA_VISIBLE_DEVICES environment variable to only show certain gpus. Note ---- If gpu_list is empty does nothing. Parameters ---------- gpu_list : list List of gpus to set as visible. """ if len(gpu_list) == 0: return cuda_visible_devices = "" for gpu in gpu_list: cuda_visible_devices += str(gpu) + "," logger.info( "Setting CUDA_VISIBLE_DEVICES = {}".format(cuda_visible_devices)) os.environ["CUDA_VISIBLE_DEVICES"] = cuda_visible_devices def pose_dim(gripper_mode): """Returns the dimensions of the pose vector for the given gripper mode. Parameters ---------- gripper_mode: :obj:`GripperMode` Enum for gripper mode, see optimizer_constants.py for all possible gripper modes. Returns ------- :obj:`numpy.ndarray` Sliced pose_data corresponding to gripper mode. """ if gripper_mode == GripperMode.PARALLEL_JAW: return 1 elif gripper_mode == GripperMode.SUCTION: return 2 elif gripper_mode == GripperMode.MULTI_SUCTION: return 1 elif gripper_mode == GripperMode.LEGACY_PARALLEL_JAW: return 1 elif gripper_mode == GripperMode.LEGACY_SUCTION: return 2 else: raise ValueError( "Gripper mode '{}' not supported.".format(gripper_mode)) def read_pose_data(pose_arr, gripper_mode): """Read the pose data and slice it according to the specified gripper mode. Parameters ---------- pose_arr: :obj:`numpy.ndarray` Full pose data array read in from file. gripper_mode: :obj:`GripperMode` Enum for gripper mode, see optimizer_constants.py for all possible gripper modes. Returns ------- :obj:`numpy.ndarray` Sliced pose_data corresponding to input data mode. """ if gripper_mode == GripperMode.PARALLEL_JAW: if pose_arr.ndim == 1: return pose_arr[2:3] else: return pose_arr[:, 2:3] elif gripper_mode == GripperMode.SUCTION: if pose_arr.ndim == 1: return np.r_[pose_arr[2], pose_arr[4]] else: return np.c_[pose_arr[:, 2], pose_arr[:, 4]] elif gripper_mode == GripperMode.MULTI_SUCTION: if pose_arr.ndim == 1: return pose_arr[2:3] else: return pose_arr[:, 2:3] elif gripper_mode == GripperMode.LEGACY_PARALLEL_JAW: if pose_arr.ndim == 1: return pose_arr[2:3] else: return pose_arr[:, 2:3] elif gripper_mode == GripperMode.LEGACY_SUCTION: if pose_arr.ndim == 1: return pose_arr[2:4] else: return pose_arr[:, 2:4] else: raise ValueError( "Gripper mode '{}' not supported.".format(gripper_mode)) def reduce_shape(shape): """Get shape of a layer for flattening.""" shape = [x.value for x in shape[1:]] f = lambda x, y: 1 if y is None else x * y # noqa: E731 return reduce(f, shape, 1) def weight_name_to_layer_name(weight_name): """Convert the name of weights to the layer name.""" tokens = weight_name.split("_") type_name = tokens[-1] # Modern naming convention. if type_name == "weights" or type_name == "bias": if len(tokens) >= 3 and tokens[-3] == "input": return weight_name[:weight_name.rfind("input") - 1] return weight_name[:weight_name.rfind(type_name) - 1] # Legacy. if type_name == "im": return weight_name[:-4] if type_name == "pose": return weight_name[:-6] return weight_name[:-1]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 15269, 10673, 5539, 13, 383, 3310, 658, 286, 262, 2059, 286, 3442, 357, 8081, 658, 737, 198, 3237, 6923, 33876, 13, 2448, 3411, 284, 779, 11, 4866, 11, 130...
2.488308
2,181
import torch.utils.data as data from PIL import Image import os # refer to https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif'] def has_file_allowed_extension(filename, extensions): """Checks if a file is an allowed extension. Args: filename (string): path to a file extensions (iterable of strings): extensions to consider (lowercase) Returns: bool: True if the filename ends with one of given extensions """ filename_lower = filename.lower() return any(filename_lower.endswith(ext) for ext in extensions)
[ 11748, 28034, 13, 26791, 13, 7890, 355, 1366, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 28686, 198, 198, 2, 3522, 284, 3740, 1378, 12567, 13, 785, 14, 9078, 13165, 354, 14, 10178, 14, 2436, 672, 14, 9866, 14, 13165, 354, 10178, ...
2.898678
227
import re from tools.general import load_input rules, messages = parse_input_data(load_input("day19.txt")) pattern = re.compile("^" + resolve_rule(rules, 0) + "$") print(f"Part 1 => {sum(1 for msg in messages if pattern.match(msg))}") special_cases = { 8 : resolve_rule(rules, 42) + '+', 11 : '(' + '|'.join( resolve_rule(rules, 42) + '{' + str(i) + '}' + resolve_rule(rules, 31) + '{' + str(i) + '}' for i in range(1, 6) ) + ')' } pattern = re.compile("^" + resolve_rule(rules, 0, special_cases) + "$") print(f"Part 2 => {sum(1 for msg in messages if pattern.match(msg))}")
[ 11748, 302, 198, 6738, 4899, 13, 24622, 1330, 3440, 62, 15414, 198, 198, 38785, 11, 6218, 796, 21136, 62, 15414, 62, 7890, 7, 2220, 62, 15414, 7203, 820, 1129, 13, 14116, 48774, 198, 198, 33279, 796, 302, 13, 5589, 576, 7203, 61, 1,...
2.19398
299
from glouton.modules.telemetryModuleBase import TelemetryModuleBase from glouton.shared.logger import logger import json import os
[ 198, 6738, 1278, 448, 261, 13, 18170, 13, 46813, 41935, 26796, 14881, 1330, 14318, 41935, 26796, 14881, 198, 6738, 1278, 448, 261, 13, 28710, 13, 6404, 1362, 1330, 49706, 198, 11748, 33918, 198, 11748, 28686, 628 ]
3.694444
36
# однострочный комментарий ''' первая строка вторая строка ''' # Ввод / вывод информации print('Hello!') # более сложный выыод print('Hello!', 'student!') # вывод с разделитетем - sep print('Hello!', 'student!', 123, sep='xxx') # бывает важно что бы конец строки был другим символом - and print('Hello!', 'student!', 123, sep='xxx', end='yyy') print() # Ввод age = input('Input your age') # Тип переменной которая возвращает input это всегда строка # ОПЕРАЦИЯ ПРИВЕДЕНИЯ ТИПОВ ИЗ СТРОКИ СДЕЛАЛИ ЧИСЛО print(age, type(int(age)))
[ 2, 12466, 122, 43666, 22177, 15166, 21727, 20375, 21169, 15166, 141, 229, 22177, 45035, 140, 117, 12466, 118, 25443, 120, 43108, 16843, 22177, 20375, 16142, 21169, 18849, 140, 117, 198, 7061, 6, 198, 140, 123, 16843, 21169, 38857, 16142, ...
1.226328
433
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod from collections import namedtuple from datetime import datetime from typing import Any, Dict, Iterable, List, Optional, Text from bs4 import BeautifulSoup from yyutil.cache import DummyCache from yyutil.time import astimezone from yyutil.url import UrlFetcher Item = namedtuple('Item', 'id title publish_date link description')
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 450, 66, 1330, 9738, 48526, 11, 12531, 24396, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 6738, 19720, 1330, 4377, 11, 3...
3.297521
121
import numpy as np import matplotlib.pyplot as plt from hs_digitizer import * import glob import scipy.signal as ss from scipy.optimize import curve_fit import re, sys plt.rcParams.update({'font.size': 14}) paths = ['/daq2/20190618/pramp_tests/outgassing', \ #'/daq2/20190624/pramp/outgassing_test1', \ '/daq2/20190625/pramp/outgassing_test2', \ '/daq2/20190626/bead1/spinning/pramp/outgassing/50kHz_4Vpp'] labels = ['Old data', 'Reseated Window', 'Much Later'] chan_to_plot = 2 time_arrs = [] pressure_arrs = [] for path in paths: files, lengths = bu.find_all_fnames(path, sort_time=True) nfiles = len(files) init_file = 0 times = [] pressures = [] for fileind, file in enumerate(files): bu.progress_bar(fileind, nfiles) obj = hsDat(file) pressures.append(obj.attribs["pressures"]) times.append(obj.attribs["time"] * 1e-9) pressures = np.array(pressures) times = np.array(times) - times[0] pressure_arrs.append(pressures) time_arrs.append(times) for pathind, path in enumerate(paths): plt.plot(time_arrs[pathind], pressure_arrs[pathind][:,chan_to_plot], \ label=labels[pathind]) plt.xlabel('Time [s]') plt.ylabel('Chamber Pressure [torr]') plt.suptitle('Leak Got Better') plt.legend() plt.tight_layout() plt.subplots_adjust(top=0.91) plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 289, 82, 62, 12894, 3029, 263, 1330, 1635, 198, 11748, 15095, 198, 11748, 629, 541, 88, 13, 12683, 282, 355, 37786, 198, 6738, 629...
2.399628
538
""" W2UI Layout Widget Implementation """ from .raw_w2ui_layout import Layout as w2ui_raw_layout class Layout: """W2UI Layout class""" @property @property def init_widget(self): """Initialize the layout to be displayed""" if not self._has_panel: self.content_top = { "id": self.name, "type": "main", "height": "100%", "resizable": False } self._build_config() self._raw_layout.initLayout(self.config, name=self.name) def attach_widget(self, widget_id, panel_id, config): """Attach a widget to a panel in the layout""" self._build_config() self._raw_layout.content( cell_id=self._get_type(panel_id), widget_id=widget_id, config=config ) def repaint(self): """Repaint the layout on the screen""" self._raw_layout.refresh() def hide_panel(self, panel): """Hide a panel on the layout""" self._raw_layout.hide(self._get_type(panel), True) def show_panel(self, panel): """Show a hidden panel on the layout""" self._raw_layout.show(self._get_type(panel), True) def toggle_panel(self, panel): """Toggle between hiding and showing a layout""" self._raw_layout.toggle(self._get_type(panel)) def add_top_header(self, **kwargs): """Add the top header panel to the layout""" self.top_header = _panel_config_update(kwargs, "height") def add_bottom_footer(self, **kwargs): """Add the bottom footer panel to the layout""" self.bottom_footer = _panel_config_update(kwargs, "height") def add_left_side(self, **kwargs): """Add the left side panel to the layout""" self.left_side = _panel_config_update(kwargs, "width") def add_right_side(self, **kwargs): """Add the right side palen to the layout""" self.right_side = _panel_config_update(kwargs, "width") def add_content_top(self, **kwargs): """Add the content top panel to the layout""" self.content_top = _panel_config_update(kwargs, "height") def add_content_bottom(self, **kwargs): """Add the content bottom panel to the layout""" self.content_bottom = _panel_config_update(kwargs, "height") def on_panel_hide(self, event_callable, ret_widget_values=None, block_signal=False): """Hook to the panel hide event""" #TODO Implementation of ret_widget_values #TODO Implementation of block_signal?? or removal self.on_panel_hide_callable = event_callable self._raw_layout.onHide( self.on_panel_hide_return, ret_widget_values=ret_widget_values, block_signal=block_signal ) def on_panel_hide_return(self, event): """Panel hide event return""" self.on_panel_hide_callable(event["target"]) def on_panel_show(self, event_callable, ret_widget_values=None, block_signal=False): """Hook to the panel show event""" #TODO Implementation of ret_widget_values #TODO Implementation of block_signal?? or removal self.on_panel_show_callable = event_callable self._raw_layout.onShow( self.on_panel_show_return, ret_widget_values=ret_widget_values, block_signal=block_signal ) def on_panel_show_return(self, event): """Panel show event return""" self.on_panel_show_callable(event["target"]) def on_panel_resize(self, event_callable, ret_widget_values=None, block_signal=False): """Hook to the panel resize event""" #TODO Implementation of ret_widget_values #TODO Implementation of block_signal?? or removal self.on_panel_resize_callable = event_callable self._raw_layout.resize( self.on_panel_resize_return, ret_widget_values=ret_widget_values, block_signal=block_signal ) def on_panel_resize_return(self, event): """Panel resize event return""" self.on_panel_resize_callable(event["target"]) def before_panel_resize(self, event_callable, ret_widget_values=None, block_signal=False): """Hook to the Before panel resize event""" #TODO Implementation of ret_widget_values #TODO Implementation of block_signal?? or removal self.before_panel_resize_callable = event_callable self._raw_layout.beforeResizeStart( self.before_panel_resize_return, ret_widget_values=ret_widget_values, block_signal=block_signal ) def before_panel_resize_return(self, event): """Before Panel resize event return""" self.before_panel_resize_callable(event["target"])
[ 37811, 198, 54, 17, 10080, 47639, 370, 17484, 46333, 198, 37811, 198, 198, 6738, 764, 1831, 62, 86, 17, 9019, 62, 39786, 1330, 47639, 355, 266, 17, 9019, 62, 1831, 62, 39786, 628, 198, 198, 4871, 47639, 25, 198, 220, 220, 220, 37227...
2.348441
2,052
# This problem was recently asked by Twitter: # Given a string with the initial condition of dominoes, where: # . represents that the domino is standing still # L represents that the domino is falling to the left side # R represents that the domino is falling to the right side # Figure out the final position of the dominoes. If there are dominoes that get pushed on both ends, the force cancels out and that domino remains upright. print (Solution().pushDominoes('..R...L..R.')) # ..RR.LL..RR
[ 2, 770, 1917, 373, 2904, 1965, 416, 3009, 25, 198, 198, 2, 11259, 257, 4731, 351, 262, 4238, 4006, 286, 2401, 2879, 274, 11, 810, 25, 198, 198, 2, 764, 6870, 326, 262, 2401, 2879, 318, 5055, 991, 198, 2, 406, 6870, 326, 262, 240...
3.75188
133
base_id = 0 base_gms = 23580 base_state_transfer = 28366 base_sst = 37683 base_rdmc = 31675 base_external = 32645 num_senders = 8 num_clients = 2 for i in range(num_senders + num_clients): print('\n\nfor id {}:\n'.format(i)) print('# my local id - each node should have a different id') print('local_id = {}'.format(base_id + i)) print('# my local ip address') print('local_ip = 127.0.0.1') print('# derecho gms port') print('gms_port = {}'.format(base_gms + i)) print('# derecho rpc port') print('state_transfer_port = {}'.format(base_state_transfer + i)) print('# sst tcp port') print('sst_port = {}'.format(base_sst + i)) print('# rdmc tcp port') print('rdmc_port = {}'.format(base_rdmc + i)) print('# external port') print('external_port = {}'.format(base_external + i))
[ 8692, 62, 312, 796, 657, 198, 8692, 62, 70, 907, 796, 28878, 1795, 198, 8692, 62, 5219, 62, 39437, 796, 2579, 32459, 198, 8692, 62, 82, 301, 796, 5214, 47521, 198, 8692, 62, 4372, 23209, 796, 34131, 2425, 198, 8692, 62, 22615, 796, ...
2.48368
337
# -*- coding: utf-8 -*-
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 628 ]
1.785714
14
# Make sure to edit this configuration file with your database connection details # and Alpha Vantage API key DB_USER = 'user' DB_PASS = 'passwd' DB_HOST = 'host' DB_PORT = '000' DB_NAME = 'db' APIKEY = 'alpha_vantage_apikey'
[ 2, 6889, 1654, 284, 4370, 428, 8398, 2393, 351, 534, 6831, 4637, 3307, 198, 2, 290, 12995, 569, 36403, 7824, 1994, 198, 11012, 62, 29904, 796, 705, 7220, 6, 198, 11012, 62, 47924, 796, 705, 6603, 16993, 6, 198, 11012, 62, 39, 10892,...
2.960526
76
import sys from collections import namedtuple from pathlib import Path from dl_plus import ytdl from dl_plus.config import get_config_home from dl_plus.exceptions import DLPlusException from dl_plus.pypi import load_metadata backends_dir = get_config_home() / 'backends' BackendInfo = namedtuple( 'BackendInfo', 'import_name,version,path,is_managed,metadata')
[ 11748, 25064, 198, 6738, 17268, 1330, 3706, 83, 29291, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 288, 75, 62, 9541, 1330, 331, 8671, 75, 198, 6738, 288, 75, 62, 9541, 13, 11250, 1330, 651, 62, 11250, 62, 11195, 198, 6738, ...
3.04878
123
import numpy as np import matplotlib.pyplot as plt import math from numpy import random omega = np.array([-1/2, 1/2]) beta = 1/4 sigma = 1 N = 16 ND = 30 dt = 0.01 T_list = np.linspace(0, ND, num=int(ND/dt)) (res, phase) = solve_diffeqs(N, sigma, beta, omega, ND, dt) plt.figure(figsize=(10, 7), dpi=100) plt.grid(color='k', linestyle='--', linewidth=0.5) for i in range(N): plt.plot(T_list, res[:, i, 0], label='Oscillator Number={i}') plt.xlabel('Time(sec)') plt.ylabel('θ(t)') #plt.legend(loc=1) plt.savefig('1') #plt.show() plt.figure(figsize=(10, 7), dpi=100) plt.grid(color='k', linestyle='--', linewidth=0.5) for i in range(N): plt.plot(T_list, res[:, i, 1], label='Oscillator Number={i}') plt.xlabel('Time(sec)') plt.ylabel('φ(t)') plt.savefig('2') #plt.legend(loc=1) #plt.show() plt.figure(figsize=(10, 7), dpi=100) plt.grid(color='k', linestyle='--', linewidth=0.5) for i in range(N): plt.plot(T_list, phase[:, i, 0], label='Oscillator Number={i}') plt.xlabel('Time(sec)') plt.ylabel("θ'(t)") #plt.legend(loc=0) plt.savefig('3') #plt.show() plt.figure(figsize=(10, 7), dpi=100) plt.grid(color='k', linestyle='--', linewidth=0.5) for i in range(N): plt.plot(T_list, phase[:, i, 1], label='Oscillator Number={i}') plt.xlabel('Time(sec)') plt.ylabel("φ'(t)") #plt.legend(loc=0) plt.savefig('4') #plt.show() plt.figure(figsize=(10, 7), dpi=100) plt.grid(color='k', linestyle='--', linewidth=0.5) for i in range(N): plt.plot(res[:, i, 0], phase[:, i, 0], label='Oscillator Number={i}') plt.xlabel('θ(t)') plt.ylabel("θ'(t)") #plt.legend(loc=0) plt.savefig('5') #plt.show() plt.figure(figsize=(10, 7), dpi=100) plt.grid(color='k', linestyle='--', linewidth=0.5) for i in range(N): plt.plot(res[:, i, 1], phase[:, i, 1], label='Oscillator Number={i}') plt.xlabel('φ(t)') plt.ylabel("φ'(t)") plt.savefig('6') #plt.legend(loc=0) #plt.show()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 10688, 198, 6738, 299, 32152, 1330, 4738, 628, 628, 198, 462, 4908, 796, 45941, 13, 18747, 26933, 12, 16, 14, 17, 11, 352, 14, ...
2.019376
929
""" Deep Deterministic Policy Gradient (DDPG) ----------------------------------------- An algorithm concurrently learns a Q-function and a policy. It uses off-policy data and the Bellman equation to learn the Q-function, and uses the Q-function to learn the policy. Reference --------- Deterministic Policy Gradient Algorithms, Silver et al. 2014 Continuous Control With Deep Reinforcement Learning, Lillicrap et al. 2016 MorvanZhou's tutorial page: https://morvanzhou.github.io/tutorials/ Environment ----------- Openai Gym Pendulum-v0, continual action space Prerequisites ------------- tensorflow >=2.0.0a0 tensorflow-probability 0.6.0 tensorlayer >=2.0.0 To run ------ python tutorial_DDPG.py --train/test """ import argparse import os import time import gym import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import tensorlayer as tl parser = argparse.ArgumentParser(description='Train or test neural net motor controller.') parser.add_argument('--train', dest='train', action='store_true', default=True) parser.add_argument('--test', dest='train', action='store_false') args = parser.parse_args() ##################### hyper parameters #################### ENV_NAME = 'Pendulum-v0' # environment name RANDOMSEED = 1 # random seed LR_A = 0.001 # learning rate for actor LR_C = 0.002 # learning rate for critic GAMMA = 0.9 # reward discount TAU = 0.01 # soft replacement MEMORY_CAPACITY = 10000 # size of replay buffer BATCH_SIZE = 32 # update batchsize MAX_EPISODES = 200 # total number of episodes for training MAX_EP_STEPS = 200 # total number of steps for each episode TEST_PER_EPISODES = 10 # test the model per episodes VAR = 3 # control exploration ############################### DDPG #################################### class DDPG(object): """ DDPG class """ def ema_update(self): """ Soft updating by exponential smoothing :return: None """ paras = self.actor.trainable_weights + self.critic.trainable_weights self.ema.apply(paras) for i, j in zip(self.actor_target.trainable_weights + self.critic_target.trainable_weights, paras): i.assign(self.ema.average(j)) def choose_action(self, s): """ Choose action :param s: state :return: act """ return self.actor(np.array([s], dtype=np.float32))[0] def learn(self): """ Update parameters :return: None """ indices = np.random.choice(MEMORY_CAPACITY, size=BATCH_SIZE) bt = self.memory[indices, :] bs = bt[:, :self.s_dim] ba = bt[:, self.s_dim:self.s_dim + self.a_dim] br = bt[:, -self.s_dim - 1:-self.s_dim] bs_ = bt[:, -self.s_dim:] with tf.GradientTape() as tape: a_ = self.actor_target(bs_) q_ = self.critic_target([bs_, a_]) y = br + GAMMA * q_ q = self.critic([bs, ba]) td_error = tf.losses.mean_squared_error(y, q) c_grads = tape.gradient(td_error, self.critic.trainable_weights) self.critic_opt.apply_gradients(zip(c_grads, self.critic.trainable_weights)) with tf.GradientTape() as tape: a = self.actor(bs) q = self.critic([bs, a]) a_loss = -tf.reduce_mean(q) # maximize the q a_grads = tape.gradient(a_loss, self.actor.trainable_weights) self.actor_opt.apply_gradients(zip(a_grads, self.actor.trainable_weights)) self.ema_update() def store_transition(self, s, a, r, s_): """ Store data in data buffer :param s: state :param a: act :param r: reward :param s_: next state :return: None """ s = s.astype(np.float32) s_ = s_.astype(np.float32) transition = np.hstack((s, a, [r], s_)) index = self.pointer % MEMORY_CAPACITY # replace the old memory with new memory self.memory[index, :] = transition self.pointer += 1 def save_ckpt(self): """ save trained weights :return: None """ if not os.path.exists('model'): os.makedirs('model') tl.files.save_weights_to_hdf5('model/ddpg_actor.hdf5', self.actor) tl.files.save_weights_to_hdf5('model/ddpg_actor_target.hdf5', self.actor_target) tl.files.save_weights_to_hdf5('model/ddpg_critic.hdf5', self.critic) tl.files.save_weights_to_hdf5('model/ddpg_critic_target.hdf5', self.critic_target) def load_ckpt(self): """ load trained weights :return: None """ tl.files.load_hdf5_to_weights_in_order('model/ddpg_actor.hdf5', self.actor) tl.files.load_hdf5_to_weights_in_order('model/ddpg_actor_target.hdf5', self.actor_target) tl.files.load_hdf5_to_weights_in_order('model/ddpg_critic.hdf5', self.critic) tl.files.load_hdf5_to_weights_in_order('model/ddpg_critic_target.hdf5', self.critic_target) if __name__ == '__main__': env = gym.make(ENV_NAME) env = env.unwrapped # reproducible env.seed(RANDOMSEED) np.random.seed(RANDOMSEED) tf.random.set_seed(RANDOMSEED) s_dim = env.observation_space.shape[0] a_dim = env.action_space.shape[0] a_bound = env.action_space.high ddpg = DDPG(a_dim, s_dim, a_bound) if args.train: # train reward_buffer = [] t0 = time.time() for i in range(MAX_EPISODES): t1 = time.time() s = env.reset() ep_reward = 0 for j in range(MAX_EP_STEPS): # Add exploration noise a = ddpg.choose_action(s) a = np.clip(np.random.normal(a, VAR), -2, 2) # add randomness to action selection for exploration s_, r, done, info = env.step(a) ddpg.store_transition(s, a, r / 10, s_) if ddpg.pointer > MEMORY_CAPACITY: ddpg.learn() s = s_ ep_reward += r if j == MAX_EP_STEPS - 1: print( '\rEpisode: {}/{} | Episode Reward: {:.4f} | Running Time: {:.4f}'.format( i, MAX_EPISODES, ep_reward, time.time() - t1 ), end='' ) plt.show() # test if i and not i % TEST_PER_EPISODES: t1 = time.time() s = env.reset() ep_reward = 0 for j in range(MAX_EP_STEPS): a = ddpg.choose_action(s) # without exploration noise s_, r, done, info = env.step(a) s = s_ ep_reward += r if j == MAX_EP_STEPS - 1: print( '\rEpisode: {}/{} | Episode Reward: {:.4f} | Running Time: {:.4f}'.format( i, MAX_EPISODES, ep_reward, time.time() - t1 ) ) reward_buffer.append(ep_reward) if reward_buffer: plt.ion() plt.cla() plt.title('DDPG') plt.plot(np.array(range(len(reward_buffer))) * TEST_PER_EPISODES, reward_buffer) # plot the episode vt plt.xlabel('episode steps') plt.ylabel('normalized state-action value') plt.ylim(-2000, 0) plt.show() plt.pause(0.1) plt.ioff() plt.show() print('\nRunning time: ', time.time() - t0) ddpg.save_ckpt() # test ddpg.load_ckpt() while True: s = env.reset() for i in range(MAX_EP_STEPS): env.render() s, r, done, info = env.step(ddpg.choose_action(s)) if done: break
[ 37811, 201, 198, 29744, 45559, 49228, 7820, 17701, 1153, 357, 35, 6322, 38, 8, 201, 198, 3880, 45537, 201, 198, 2025, 11862, 47480, 22974, 257, 1195, 12, 8818, 290, 257, 2450, 13, 201, 198, 1026, 3544, 572, 12, 30586, 1366, 290, 262, ...
1.935242
4,262
from __future__ import unicode_literals from django.core.exceptions import ObjectDoesNotExist from django.forms.models import ModelForm, model_to_dict from .constants import (MODERATION_STATUS_PENDING, MODERATION_STATUS_REJECTED) from .utils import django_17
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 7295, 13, 1069, 11755, 1330, 9515, 13921, 3673, 3109, 396, 198, 6738, 42625, 14208, 13, 23914, 13, 27530, 1330, 9104, 8479, 11, 2746, 62, 1462...
3.156627
83
import csv import platform from time import time from statistics import mean from collections import deque from datetime import datetime import psutil import log from cpu import Cpu from __init__ import __version__ from process import ProcessReader class History(deque): ''' A double ended queue with methods for streaming data, change detection and delta computation ''' def update(self, value): '''Stream value into deque''' if self.__len__() == self.maxlen: _ = self.popleft() self.append(value) else: self.append(value) def delta(self): '''Returns the difference between the last and first value''' if self.__len__() > 1: return self[-1] - self[0] else: return None def changed(self) -> bool: '''Returns true if field's last value is different from the second last one''' if self.__len__() > 1: return self[-1] != self[-2] else: return None
[ 11748, 269, 21370, 198, 11748, 3859, 198, 6738, 640, 1330, 640, 198, 6738, 7869, 1330, 1612, 198, 6738, 17268, 1330, 390, 4188, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 26692, 22602, 198, 198, 11748, 2604, 198, 6738, 42804, ...
2.490385
416
from __future__ import absolute_import as _abs from ._ffi.node import NodeBase, NodeGeneric, register_node from ._ffi.runtime_ctypes import TVMType, TypeCode from . import make as _make from . import generic as _generic from . import _api_internal class Expr(ExprOp, NodeBase): """Base class of all tvm Expressions""" # In Python3, We have to explicitly tell interpreter to retain __hash__ if we overide __eq__ # https://docs.python.org/3.1/reference/datamodel.html#object.__hash__ __hash__ = NodeBase.__hash__ @register_node("Variable") class Var(Expr): """Symbolic variable. Parameters ---------- name : str The name dtype : int The data type """
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 355, 4808, 8937, 198, 6738, 47540, 487, 72, 13, 17440, 1330, 19081, 14881, 11, 19081, 46189, 11, 7881, 62, 17440, 198, 6738, 47540, 487, 72, 13, 43282, 62, 310, 9497, 1330, 3195, 44, 603...
2.878543
247
from abc import ABC from typing import Dict, Any from allenact.utils.viz_utils import VizSuite, AgentViewViz from projects.gym_baselines.experiments.gym_base import GymBaseConfig
[ 6738, 450, 66, 1330, 9738, 198, 6738, 19720, 1330, 360, 713, 11, 4377, 198, 198, 6738, 477, 268, 529, 13, 26791, 13, 85, 528, 62, 26791, 1330, 36339, 5606, 578, 11, 15906, 7680, 53, 528, 198, 198, 6738, 4493, 13, 1360, 76, 62, 120...
3.137931
58
import pandas as pd from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier from sklearn.model_selection import train_test_split # Import train_test_split function from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation from fastapi import FastAPI import uvicorn data = pd.read_csv("clothing_weather.csv") app = FastAPI() @app.get("/") async def root(): """Weather Advisor Welcome""" return {"message": "Hello, welcome to Weather advisor! Enter a temp, whether there is a chance of rain, and whether there is a chance of snow in the format temp/rain/snow."} @app.get("/weatheradvisor/{temp}/{rain}/{snow}") if __name__ == '__main__': uvicorn.run(app, port=8080, host='0.0.0.0')
[ 11748, 19798, 292, 355, 279, 67, 198, 6738, 1341, 35720, 13, 21048, 1330, 26423, 27660, 9487, 7483, 1303, 17267, 26423, 12200, 5016, 7483, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 4512, 62, 9288, 62, 35312, 1303, 17267, 4512, ...
3.167364
239
# Generated by Django 3.2 on 2021-06-11 18:47 from django.db import migrations, models import wagtail.core.fields
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 319, 33448, 12, 3312, 12, 1157, 1248, 25, 2857, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 266, 363, 13199, 13, 7295, 13, 25747, 628 ]
2.974359
39
... txt = ['[', ']'] * N ... random.shuffle( txt ) ... return ''.join(txt) ... ... braced = 0 ... for ch in txt: ... if ch == '[': braced += 1 ... if ch == ']': ... braced -= 1 ... if braced < 0: return False ... return braced == 0 ... >>> for txt in (gen(N) for N in range(10)): ... print ("%-22r is%s balanced" % (txt, '' if balanced(txt) else ' not')) ... '' is balanced '[]' is balanced '[][]' is balanced '][[[]]' is not balanced '[]][[][]' is not balanced '[][[][]]][' is not balanced '][]][][[]][[' is not balanced '[[]]]]][]][[[[' is not balanced '[[[[]][]]][[][]]' is balanced '][[][[]]][]]][[[[]' is not balanced
[ 986, 220, 220, 220, 220, 256, 742, 796, 37250, 58, 3256, 705, 60, 20520, 1635, 399, 198, 986, 220, 220, 220, 220, 4738, 13, 1477, 18137, 7, 256, 742, 1267, 198, 986, 220, 220, 220, 220, 1441, 705, 4458, 22179, 7, 14116, 8, 198, ...
1.902613
421
#!/usr/bin/env python # encoding: utf-8 ''' Created on Mar 12, 2017 @author: Yusuke Kawatsu ''' import numpy as np import matplotlib.pyplot as plt if __name__ == '__main__': plot()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 21004, 25, 3384, 69, 12, 23, 198, 198, 7061, 6, 198, 41972, 319, 1526, 1105, 11, 2177, 198, 198, 31, 9800, 25, 41749, 4649, 23043, 19231, 198, 7061, 6, 198, 198, 11748, 299, 321...
2.480519
77
# -*-coding: utf-8 -*- """ @Project: tools @File : debug.py @Author : panjq @E-mail : pan_jinquan@163.com @Date : 2019-05-10 16:24:49 """ import datetime import logging import sys import time ''' url:https://cuiqingcai.com/6080.html level级别:debug、info、warning、error以及critical ''' # logging.basicConfig(level=logging.DEBUG, # filename='output.log', # datefmt='%Y/%m/%d %H:%M:%S', # format='%(asctime)s - %(name)s - %(levelname)s - %(lineno)d - %(module)s - %(message)s') logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(filename)s - %(funcName)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) def RUN_TIME(deta_time): ''' 返回毫秒,deta_time.seconds获得秒数=1000ms,deta_time.microseconds获得微妙数=1/1000ms :param deta_time: ms :return: ''' time_ = deta_time.seconds * 1000 + deta_time.microseconds / 1000.0 return time_ if __name__ == '__main__': T0 = TIME() # do something time.sleep(5) T1 = TIME() print("rum time:{}ms".format(RUN_TIME(T1 - T0))) logger.info('This is a log info') logger.debug('Debugging') logger.warning('Warning exists') logger.error('Finish')
[ 2, 532, 9, 12, 66, 7656, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 2488, 16775, 25, 4899, 198, 220, 220, 220, 2488, 8979, 220, 220, 1058, 14257, 13, 9078, 198, 220, 220, 220, 2488, 13838, 1058, 3425, 73, ...
1.979751
642
""" Copyright (C) 2010 CNRS Author: Florent Lamiraux, Nicolas Mansard """ from __future__ import print_function import types from enum import Enum from . import signal_base, wrap from .attrpath import setattrpath if 'display' not in globals().keys(): # --- FACTORY ------------------------------------------------------------------ class PyEntityFactoryClass(type): """ The class build dynamically a new class type, and return the reference on the class-type object. The class type is not added to any context. """ def PyEntityFactory(className, context): """ Build a new class type by calling the factory, and add it to the given context. """ EntityClass = PyEntityFactoryClass(className) context[className] = EntityClass return EntityClass def updateEntityClasses(dictionary): """ For all c++entity types that are not in the pyentity class list (entityClassNameList) run the factory and store the new type in the given context (dictionary). """ cxx_entityList = wrap.factory_get_entity_class_list() for e in filter(lambda x: x not in Entity.entityClassNameList, cxx_entityList): # Store new class in dictionary with class name PyEntityFactory(e, dictionary) # Store class name in local list Entity.entityClassNameList.append(e) # --- ENTITY ------------------------------------------------------------------- class VerbosityLevel(Enum): """ Enum class for setVerbosityLevel """ VERBOSITY_ALL = 8 VERBOSITY_INFO_WARNING_ERROR = 4 VERBOSITY_WARNING_ERROR = 2 VERBOSITY_ERROR = 1 VERBOSITY_NONE = 0 class Entity(object): """ This class binds dynamicgraph::Entity C++ class """ obj = None """ Store list of entities created via python """ entities = dict() def __init__(self, className, instanceName): """ Constructor: if not called by a child class, create and store a pointer to a C++ Entity object. """ object.__setattr__(self, 'obj', wrap.create_entity(className, instanceName)) Entity.entities[instanceName] = self @staticmethod def initEntity(self, name): """ Common constructor of specialized Entity classes. This function is bound by the factory to each new class derivated from the Entity class as the constructor of the new class. """ Entity.__init__(self, self.className, name) if not self.__class__.commandCreated: self.boundClassCommands() self.__class__.__doc__ = wrap.entity_get_docstring(self.obj) self.__class__.commandCreated = True @property @property def signal(self, name): """ Get a signal of the entity from signal name """ signalPt = wrap.entity_get_signal(self.obj, name) return signal_base.SignalBase(name="", obj=signalPt) def hasSignal(self, name): """ Indicates if a signal with the given name exists in the entity """ return wrap.entity_has_signal(self.obj, name) def displaySignals(self): """ Print the list of signals into standard output: temporary. """ signals = list(self.signals()) if len(signals) == 0: display("--- <" + self.name + "> has no signal") else: display("--- <" + self.name + "> signal list: ") for s in signals[:-1]: display(" |-- <" + str(s)) display(" `-- <" + str(signals[-1])) def signals(self): """ Return the list of signals """ sl = wrap.entity_list_signals(self.obj) return map(lambda pyObj: signal_base.SignalBase(obj=pyObj), sl) def commands(self): """ Return the list of commands. """ return wrap.entity_list_commands(self.obj) def globalHelp(self): """ Print a short description of each command. """ if self.__doc__: print(self.__doc__) print("List of commands:") print("-----------------") for cstr in self.commands(): ctitle = cstr + ':' for i in range(len(cstr), 15): ctitle += ' ' for docstr in wrap.entity_get_command_docstring(self.obj, cstr).split('\n'): if (len(docstr) > 0) and (not docstr.isspace()): display(ctitle + "\t" + docstr) break def help(self, comm=None): """ With no arg, print the global help. With arg the name of a specific command, print the help associated to the command. """ if comm is None: self.globalHelp() else: display(comm + ":\n" + wrap.entity_get_command_docstring(self.obj, comm)) # --- COMMANDS BINDER ----------------------------------------------------- # List of all the entity classes from the c++ factory, that have been bound # bind the py factory. entityClassNameList = [] # This function dynamically create the function object that runs the command. @staticmethod def boundClassCommands(self): """ This static function has to be called from a class heritating from Entity. It should be called only once. It parses the list of commands obtained from c++, and bind each of them to a python class method. """ # Get list of commands of the Entity object commands = wrap.entity_list_commands(self.obj) # for each command, add a method with the name of the command for cmdstr in commands: docstr = wrap.entity_get_command_docstring(self.obj, cmdstr) cmdpy = Entity.createCommandBind(cmdstr, docstr) setattrpath(self.__class__, cmdstr, cmdpy) def boundNewCommand(self, cmdName): """ At construction, all existing commands are bound directly in the class. This method enables to bound new commands dynamically. These new bounds are not made with the class, but directly with the object instance. """ if (cmdName in self.__dict__) | (cmdName in self.__class__.__dict__): print("Warning: command ", cmdName, " will overwrite an object attribute.") docstring = wrap.entity_get_command_docstring(self.obj, cmdName) cmd = Entity.createCommandBind(cmdName, docstring) # Limitation (todo): does not handle for path attribute name (see setattrpath). setattr(self, cmdName, types.MethodType(cmd, self)) def boundAllNewCommands(self): """ For all commands that are not attribute of the object instance nor of the class, a new attribute of the instance is created to bound the command. """ cmdList = wrap.entity_list_commands(self.obj) cmdList = filter(lambda x: x not in self.__dict__, cmdList) cmdList = filter(lambda x: x not in self.__class__.__dict__, cmdList) for cmd in cmdList: self.boundNewCommand(cmd) def setLoggerVerbosityLevel(self, verbosity): """ Specify for the entity the verbosity level. - param verbosity should be one of the attribute of the enum dynamic_graph.entity.VerbosityLevel """ return wrap.entity_set_logger_verbosity(self.obj, verbosity) def getLoggerVerbosityLevel(self): """ Returns the entity's verbosity level (as a dynamic_graph.entity.VerbosityLevel) """ r = wrap.entity_get_logger_verbosity(self.obj) if r == 8: return VerbosityLevel.VERBOSITY_ALL elif r == 4: return VerbosityLevel.VERBOSITY_INFO_WARNING_ERROR elif r == 2: return VerbosityLevel.VERBOSITY_WARNING_ERROR elif r == 1: return VerbosityLevel.VERBOSITY_ERROR return VerbosityLevel.VERBOSITY_NONE def setTimeSample(self, timeSample): """ Specify for the entity the time at which call is counted. """ return wrap.entity_set_time_sample(self.obj, timeSample) def getTimeSample(self): """ Returns for the entity the time at which call is counted. """ return wrap.entity_get_time_sample(self.obj) def setStreamPrintPeriod(self, streamPrintPeriod): """ Specify for the entity the period at which debugging information is printed """ return wrap.entity_set_stream_print_period(self.obj, streamPrintPeriod) def getStreamPrintPeriod(self): """ Returns for the entity the period at which debugging information is printed """ return wrap.entity_get_stream_print_period(self.obj)
[ 37811, 198, 220, 15069, 357, 34, 8, 3050, 31171, 6998, 628, 220, 6434, 25, 23347, 429, 10923, 343, 14644, 11, 29737, 18580, 446, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 3858, 198, 6738, 33829, ...
2.539216
3,468
from typing import List from reinvent_models.link_invent.model_vocabulary.vocabulary import Vocabulary, SMILESTokenizer, create_vocabulary
[ 6738, 19720, 1330, 7343, 201, 198, 201, 198, 6738, 36608, 62, 27530, 13, 8726, 62, 259, 1151, 13, 19849, 62, 18893, 22528, 13, 18893, 22528, 1330, 47208, 22528, 11, 9447, 4146, 6465, 4233, 7509, 11, 2251, 62, 18893, 22528, 201, 198, 2...
3.372093
43
from logging import getLogger from pathlib import Path from sanic import Blueprint, HTTPResponse, Request from sanic.response import file from .reload import setup_livereload logger = getLogger("booktracker") bp = Blueprint("Frontend") setup_livereload(bp) @bp.get("/<path:path>")
[ 6738, 18931, 1330, 651, 11187, 1362, 198, 6738, 3108, 8019, 1330, 10644, 198, 198, 6738, 5336, 291, 1330, 39932, 11, 7154, 51, 4805, 9774, 2591, 11, 19390, 198, 6738, 5336, 291, 13, 26209, 1330, 2393, 198, 198, 6738, 764, 260, 2220, 1...
3.108696
92
from setuptools import setup, find_packages from Cython.Build import cythonize import numpy setup( name='hdestimator', version='0.9', install_requires=[ 'h5py', 'pyyaml', 'numpy', 'scipy', 'mpmath', 'matplotlib', 'cython', ], packages=find_packages(), include_package_data=True, py_modules=['hdestimator'], url='', license='MIT', author='', author_email='', description='The history dependence estimator tool', ext_modules=cythonize(["src/hde_fast_embedding.pyx"], # "hde_fast_utils.pyx"], annotate=False), include_dirs=[numpy.get_include()] )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 6738, 327, 7535, 13, 15580, 1330, 3075, 400, 261, 1096, 198, 11748, 299, 32152, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 71, 16520, 320, 1352, 3256, 198, 220, ...
2.034384
349
import cv2 import numpy as np class roi: """docstring for roi."""
[ 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 628, 198, 4871, 686, 72, 25, 198, 220, 220, 220, 37227, 15390, 8841, 329, 686, 72, 526, 15931, 198 ]
2.482759
29
""" Common functions for creating enrich2 datasets (for GB1 and Bgl3) """ from os.path import join from subprocess import call import pandas as pd import utils def create_e2_config_file(inp_fn, sel_fn, e2_output_dir, config_file_save_dir): """ create a config file specifying parameters for enrich2 """ text = """{"libraries": [ { "counts file": "INP_COUNTS_FN", "identifiers": {}, "name": "T0", "report filtered reads": false, "timepoint": 0 }, { "counts file": "SEL_COUNTS_FN", "identifiers": {}, "name": "T1", "report filtered reads": false, "timepoint": 1 } ], "name": "C1", "output directory": "OUTPUT_DIR"}""" text = text.replace("INP_COUNTS_FN", inp_fn) text = text.replace("SEL_COUNTS_FN", sel_fn) text = text.replace("OUTPUT_DIR", e2_output_dir) with open(join(config_file_save_dir, "e2_config"), "w") as f: f.write(text) return join(config_file_save_dir, "e2_config") def create_tsv_dataset(e2_scores_fn, save_fn): """ create a simple tsv dataset file using the output from enrich2 """ e2_data = pd.HDFStore(e2_scores_fn) # get the e2 scores, removing the wild-type and moving the variant index into a column e2_scores = e2_data.select("/main/identifiers/scores") e2_scores = e2_scores.loc[e2_scores.index != "_wt"] e2_scores.reset_index(inplace=True) # get the input and selected counts e2_counts = e2_data.select("/main/identifiers/counts") if "_wt" in e2_counts.index: e2_counts = e2_counts.drop("_wt") variants = e2_scores["index"].values num_mutations = e2_scores["index"].apply(lambda x: len(x.split(","))).values scores = e2_scores["score"].values inp = e2_counts["c_0"].values sel = e2_counts["c_1"].values cols = ["variant", "num_mutations", "inp", "sel", "score"] data = {"variant": variants, "num_mutations": num_mutations, "inp": inp, "sel": sel, "score": scores} df = pd.DataFrame(data, columns=cols) if save_fn is not None: df.to_csv(save_fn, sep="\t", index=False) return df def create_e2_dataset(count_df, output_dir, output_fn=None): """ creates an enrich2 dataset (saves input files for enrich2, runs enrich2, then converts to my format) """ # create a special output directory for enrich2 e2_output_dir = join(output_dir, "e2_output") utils.ensure_dir_exists(e2_output_dir) # create enrich2 input files inp = count_df["inp"] sel = count_df["sel"] inp_fn = join(e2_output_dir, "idents_inp.tsv") sel_fn = join(e2_output_dir, "idents_sel.tsv") inp.to_csv(inp_fn, sep="\t", header=["count"], index_label=False) sel.to_csv(sel_fn, sep="\t", header=["count"], index_label=False) # create enrich2 config file for this ds e2_config_fn = create_e2_config_file(inp_fn, sel_fn, e2_output_dir, e2_output_dir) # run e2 call(['conda', 'run', '-n', 'enrich2', 'enrich_cmd', '--no-plots', '--no-tsv', e2_config_fn, 'ratios', 'wt']) if output_fn is None: output_fn = "dataset.tsv" create_tsv_dataset(join(e2_output_dir, "C1_sel.h5"), save_fn=join(output_dir, output_fn))
[ 37811, 8070, 5499, 329, 4441, 22465, 17, 40522, 357, 1640, 13124, 16, 290, 347, 4743, 18, 8, 37227, 198, 6738, 28686, 13, 6978, 1330, 4654, 198, 6738, 850, 14681, 1330, 869, 198, 198, 11748, 19798, 292, 355, 279, 67, 198, 198, 11748, ...
2.107252
1,641
# Generated by Django 3.1.4 on 2020-12-30 02:30 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 19, 319, 12131, 12, 1065, 12, 1270, 7816, 25, 1270, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
'''Main tests in API''' import unittest import pandas as pd from model.charts.base import BaseChart class BaseChartGetFillColorTest(): # class BaseChartGetFillColorTest(unittest.TestCase): ''' Test behaviours linked to getting the fill color from a color array ''' def test_get_fill_color(self): ''' Tests if an element from collor array is correctly fetched ''' options_from_yaml = {'chart_options': {'colorArray': ['red', 'yellow', 'green']}} self.assertEqual( BaseChart.get_fill_color(1, options_from_yaml), 'yellow' ) class BaseChartLegendNamesTest(): # class BaseChartLegendNamesTest(unittest.TestCase): ''' Test behaviours linked to fetching legend names for series ''' def test_legend_names_no_options(self): ''' Tests if no legend names are returned when there's no option ''' dataframe = pd.DataFrame([{'idx': 'A'}, {'idx': 'B'}]) self.assertEqual( BaseChart.get_legend_names(dataframe, None), {} ) def test_legend_names_no_chart_options(self): ''' Tests if no legend names are returned when there's no chart_options ''' dataframe = pd.DataFrame([{'idx': 'A'}, {'idx': 'B'}]) self.assertEqual( BaseChart.get_legend_names(dataframe, {}), {} ) def test_legend_names_no_dataframe(self): ''' Tests if no legend names are returned when there's no dataframe ''' options_from_yaml = {'chart_options': {'id': 'idx'}} self.assertEqual( BaseChart.get_legend_names(None, options_from_yaml), {} ) def test_legend_names_empty_dataframe(self): ''' Tests if no legend names are returned when the dataframe is empty ''' options_from_yaml = {'chart_options': {'id': 'idx'}} self.assertEqual( BaseChart.get_legend_names(pd.DataFrame([]), options_from_yaml), {} ) def test_legend_names_no_id_field(self): ''' Tests if no legend names are returned when no ID field is given ''' options_from_yaml = {'chart_options': {'legend_field': 'lgnd'}} dataframe = pd.DataFrame([{'idx': 'A'}, {'idx': 'B'}]) self.assertEqual( BaseChart.get_legend_names(dataframe, options_from_yaml), {} ) def test_legend_names_no_label_field(self): ''' Tests if legend names are built from series ID in the dataframe ''' options_from_yaml = {'chart_options': {'id': 'idx'}} dataframe = pd.DataFrame([{'idx': 'A'}, {'idx': 'B'}]) self.assertEqual( BaseChart.get_legend_names(dataframe, options_from_yaml), {'A': 'A', 'B': 'B'} ) def test_legend_names(self): ''' Tests if legend names are built from series ID in the dataframe, with a mirror legend name specified ''' options_from_yaml = {'chart_options': {'legend_field': 'lgnd', 'id': 'idx'}} dataframe = pd.DataFrame([ {'idx': 'A', 'lgnd': 'A_lbl'}, {'idx': 'B', 'lgnd': 'B_lbl'} ]) self.assertEqual( BaseChart.get_legend_names(dataframe, options_from_yaml), {'A': 'A_lbl', 'B': 'B_lbl'} ) class BaseChartTooltipTest(): # class BaseChartTooltipTest(unittest.TestCase): ''' Test behaviours linked to creating tooltip structure ''' def test_tooltip_no_option(self): ''' Tests if default tooltip is returned when no option is given ''' self.assertEqual( BaseChart.build_tooltip(None), 'Tooltip!' ) def test_tooltip_no_headers(self): ''' Tests if default tooltip is returned when no headers are given ''' self.assertEqual( BaseChart.build_tooltip({}), 'Tooltip!' ) def test_tooltip(self): ''' Tests if tooltips are built correctly ''' options_from_yaml = {'headers': [ {'text': 'Value A:', 'value': 'field_a'}, {'text': 'Value B:', 'value': 'field_b'} ]} self.assertEqual( BaseChart.build_tooltip(options_from_yaml), '<table>' '<tr style="text-align: left;">' '<th style="padding: 4px; padding-right: 10px;">Value A:</th>' '<td style="padding: 4px;">@field_a</td>' '</tr>' '<tr style="text-align: left;">' '<th style="padding: 4px; padding-right: 10px;">Value B:</th>' '<td style="padding: 4px;">@field_b</td>' '</tr>' '</table>' )
[ 7061, 6, 13383, 5254, 287, 7824, 7061, 6, 198, 11748, 555, 715, 395, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 2746, 13, 354, 5889, 13, 8692, 1330, 7308, 45488, 198, 198, 4871, 7308, 45488, 3855, 33762, 10258, 14402, 33529, 198...
2.14299
2,154
from django.conf.urls import include, url from django.contrib import admin import django if django.VERSION >= (1, 8): urlpatterns = [ url(r'^', include('blog.urls', namespace="blog")), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('libs.ckeditor_uploader.urls')), ] else: from django.conf.urls import patterns admin.autodiscover() urlpatterns = patterns( '', url(r'^', include('blog.urls', namespace="blog")), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('libs.ckeditor_uploader.urls')), )
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 2291, 11, 19016, 198, 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 11748, 42625, 14208, 198, 198, 361, 42625, 14208, 13, 43717, 18189, 357, 16, 11, 807, 2599, 198, 220, 220, 2...
2.295203
271
import chatexchange import live_testing if live_testing.enabled:
[ 11748, 442, 378, 87, 3803, 198, 198, 11748, 2107, 62, 33407, 628, 198, 361, 2107, 62, 33407, 13, 25616, 25, 198 ]
3.238095
21
''' for i in all_title: individual_title = i.text print(individual_title) x +=1 sheet1.write(x+1,1,individual_title) wb.save('냉장고2.xls') ''' ''' for j in all_price: individual_price = re.sub("[^0-9]", "", j.text) print(individual_price) x +=1 sheet1.write(x+1,2,individual_title) wb.save('냉장고.xls') b =[] def remove_tag(content): cleanr = re.compile('<.*?>') cleantext = re.sub(cleanr, '', content) return cleantext '''
[ 198, 7061, 6, 198, 1640, 1312, 287, 477, 62, 7839, 25, 198, 220, 220, 220, 1981, 62, 7839, 796, 1312, 13, 5239, 198, 220, 220, 220, 3601, 7, 43129, 62, 7839, 8, 198, 220, 220, 220, 2124, 15853, 16, 198, 220, 220, 220, 9629, 16, ...
1.979424
243
sth = 0 # BUG: solve me
[ 48476, 796, 657, 198, 198, 2, 347, 7340, 25, 8494, 502, 198 ]
2.083333
12
from importlib import import_module from .Connector import Connector # formatters for making life easier, don't you want it that way? fmt_params = '{}&api_action={}&api_output={}&{}'.format fmt_noparams = '{}&api_action={}&api_output={}'.format
[ 6738, 1330, 8019, 1330, 1330, 62, 21412, 198, 6738, 764, 34525, 1330, 8113, 273, 198, 198, 2, 5794, 1010, 329, 1642, 1204, 4577, 11, 836, 470, 345, 765, 340, 326, 835, 30, 198, 69, 16762, 62, 37266, 796, 705, 90, 92, 5, 15042, 62,...
2.883721
86
# 读入数据 from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn import preprocessing import numpy as np import matplotlib.pyplot as plt diabetes = datasets.load_diabetes() X = diabetes.data y = diabetes.target # 划分数据集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33) # 直接解法 a = np.ones(len(X_train)) XX_train = np.c_[a,X_train] y_mytest = np.c_[np.ones(len(X_test)),X_test].dot(np.linalg.pinv(XX_train).dot(y_train.reshape(-1,1))) # 计算直接解法 RMSE rmse = np.sqrt(1/len(X_test)*np.sum((y_test.reshape(-1,1)-y_mytest)**2)) print('the rmse of least squares is %f \n' %rmse ) ## -------------------梯度下降法---------------------------- # 使用 RMSProp # 初始化参数 Beta 和 学习率 alpha,mu, vt row,col = XX_train.shape Beta = np.random.random([col,1]) vt = np.ones([col,1]) alpha = 0.5 mu = 0.9 # 梯度的负方向 delta_Beta = 2/row *( XX_train.T.dot(y_train.reshape(row,1)) - XX_train.T.dot(XX_train).dot(Beta)) # 更新Beta 运用RMSProp new_vt = mu*vt + (1-mu)* delta_Beta**2 new_Beta = Beta + alpha * delta_Beta/(np.sqrt(new_vt)+np.spacing(1)) loss = [] for idx in range(100000): tmp_loss = 1/row * np.linalg.norm(y_train.reshape(row,1)-XX_train.dot(Beta))**2 loss.append(tmp_loss) if tmp_loss < 50: print(idx) break else: Beta = new_Beta vt = new_vt delta_Beta = 2/row *( XX_train.T.dot(y_train.reshape(row,1)) - XX_train.T.dot(XX_train).dot(Beta)) new_vt = mu*vt + (1-mu)* delta_Beta**2 new_Beta = Beta + alpha * delta_Beta/(np.sqrt(new_vt)+np.spacing(1)) ## -------------------End---------------------------- # 打印 直接解法和迭代解法的解 print('The direct solution of Beta is: \n') print(Beta) print('\n\n') print('The solution of Gradient Descent is: \n') print(np.linalg.pinv(XX_train).dot(y_train).reshape(col,1)) print('\n') y_mytest_GD = np.c_[np.ones(len(X_test)),X_test].dot(Beta) rmse_GD = np.sqrt(1/len(X_test)*np.sum((y_test.reshape(-1,1)-y_mytest_GD.reshape(-1,1))**2)) print('the rmse of least squares with Gradient Descent is %f' %rmse_GD)
[ 198, 2, 5525, 107, 119, 17739, 98, 46763, 108, 162, 235, 106, 198, 6738, 1341, 35720, 1330, 40522, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 4512, 62, 9288, 62, 35312, 198, 6738, 1341, 35720, 1330, 662, 36948, 198, 11748, 29...
2.022505
1,022
from __future__ import absolute_import from __future__ import division from __future__ import print_function import types import cv2 import pandas as pd import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from models import get_model from losses import get_loss from transforms import from_norm_bgr if __name__ == '__main__': import cProfile
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 3858, 198, 198, 11748, 269, 85, 17, 198, 11748, 19798, 292, 355, 279, 67, 1...
3.433628
113
## @ingroup Attributes-Propellants #Jet A # # Created: Unk 2013, SUAVE TEAM # Modified: Feb 2016, M. Vegh # ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- from .Propellant import Propellant from SUAVE.Core import Data # ---------------------------------------------------------------------- # Jet_A Propellant Class # ---------------------------------------------------------------------- ## @ingroup Attributes-Propellants class Jet_A(Propellant): """Holds values for this propellant Assumptions: None Source: None """ def __defaults__(self): """This sets the default values. Assumptions: None Source: Values commonly available Inputs: None Outputs: None Properties Used: None """ self.tag = 'Jet_A' self.reactant = 'O2' self.density = 820.0 # kg/m^3 (15 C, 1 atm) self.specific_energy = 43.02e6 # J/kg self.energy_density = 35276.4e6 # J/m^3 self.max_mass_fraction = Data({'Air' : 0.0633,'O2' : 0.3022}) # kg propellant / kg oxidizer # critical temperatures self.temperatures.flash = 311.15 # K self.temperatures.autoignition = 483.15 # K self.temperatures.freeze = 233.15 # K self.temperatures.boiling = 0.0 # K
[ 2235, 2488, 278, 3233, 49213, 12, 2964, 23506, 1187, 198, 2, 42273, 317, 198, 2, 198, 2, 15622, 25, 220, 791, 74, 2211, 11, 13558, 32, 6089, 33536, 198, 2, 40499, 25, 3158, 1584, 11, 337, 13, 8016, 456, 198, 198, 2, 16529, 23031, ...
2.116915
804
""" done """ import numpy as np from ..misc_functions import random_data from ..stability_selection import ( stability, biggest_indexes, selected_param, build_submatrix, build_subset, )
[ 37811, 198, 28060, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 11485, 44374, 62, 12543, 2733, 1330, 4738, 62, 7890, 198, 198, 6738, 11485, 301, 1799, 62, 49283, 1330, 357, 198, 220, 220, 220, 10159, 11, 198, 2...
2.619048
84
from typing import Union from plantuml2freemind.custom_types import ChildNode, RootNode AnyNode = Union[RootNode, ChildNode] def convert_tree_into_puml(root: RootNode) -> str: """Generate PlantUML mindmap from tree.""" puml = generate_puml_node(root, 1) if root.right: puml = concat_pumls(puml, generate_branch(root.right, 2)) puml += f"\nleft side" if root.left: puml = concat_pumls(puml, generate_branch(root.left, 2)) return "\n".join(("@startmindmap", puml, "@endmindmap"))
[ 6738, 19720, 1330, 4479, 198, 198, 6738, 4618, 388, 75, 17, 19503, 368, 521, 13, 23144, 62, 19199, 1330, 5932, 19667, 11, 20410, 19667, 198, 198, 7149, 19667, 796, 4479, 58, 30016, 19667, 11, 5932, 19667, 60, 628, 628, 628, 198, 198, ...
2.342105
228
# # Copyright 2020- IBM Inc. All rights reserved # SPDX-License-Identifier: Apache2.0 # from typing import Optional, Callable import numpy as np from abc import ABC, abstractmethod
[ 2, 198, 2, 15069, 12131, 12, 19764, 3457, 13, 1439, 2489, 10395, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 17, 13, 15, 198, 2, 198, 6738, 19720, 1330, 32233, 11, 4889, 540, 198, 11748, 299, 32152, 355, 45941, 198, ...
3.425926
54
## Created the 05/03/19 ## By Data Templar ## ## The purpose of this script is to remove all space in all files ## and folders' name. So we can share the "server url" directly try: from tqdm import tqdm tqdmimport = True except ImportError as e: tqdmimport = False print("enable to import the progress bar value. Please install tqdm if you want a progress bar") import argparse, sys, re, os, time # Argument creation parser = argparse.ArgumentParser() parser.add_argument("--begin", help="The folder you want to make a modification by default its the current folder", default=os.getcwd()) args = parser.parse_args() root_dir = args.begin print(root_dir) with open(root_dir+"\log.csv",'w',encoding='utf-8') as target: scanRecurse(root_dir,target)
[ 2235, 15622, 262, 8870, 14, 3070, 14, 1129, 198, 2235, 2750, 6060, 41741, 198, 2235, 198, 2235, 383, 4007, 286, 428, 4226, 318, 284, 4781, 477, 2272, 287, 477, 3696, 198, 2235, 290, 24512, 6, 1438, 13, 1406, 356, 460, 2648, 262, 366...
3.05
260
import abc import tensorflow as tf from tensor_annotations import tensorflow as ttf from tensor_annotations import axes from src.channelcoding.dataclasses import FixedPermuteInterleaverSettings, RandomPermuteInterleaverSettings from .codes import Code from .types import Batch, Time, Channels
[ 11748, 450, 66, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 6738, 11192, 273, 62, 34574, 602, 1330, 11192, 273, 11125, 355, 256, 27110, 198, 6738, 11192, 273, 62, 34574, 602, 1330, 34197, 198, 198, 6738, 12351, 13, 17620, 66, ...
3.183673
98
# 顺序查找 # 二分查找 # 二分查找 递归 前提是已排序的
[ 2, 16268, 94, 118, 41753, 237, 162, 253, 98, 33699, 122, 628, 198, 2, 220, 12859, 234, 26344, 228, 162, 253, 98, 33699, 122, 628, 198, 2, 220, 12859, 234, 26344, 228, 162, 253, 98, 33699, 122, 16268, 222, 240, 37605, 240, 10263, 2...
0.62069
58
import asyncio import pytest import aetcd import aetcd.exceptions import aetcd.watcher @pytest.mark.asyncio @pytest.mark.asyncio @pytest.mark.asyncio
[ 11748, 30351, 952, 198, 198, 11748, 12972, 9288, 198, 198, 11748, 257, 316, 10210, 198, 11748, 257, 316, 10210, 13, 1069, 11755, 198, 11748, 257, 316, 10210, 13, 86, 34734, 628, 198, 31, 9078, 9288, 13, 4102, 13, 292, 13361, 952, 628,...
2.46875
64
from itertools import groupby from datetime import date, timedelta from operator import itemgetter from sqlalchemy import func from .utm_db import session_utm from .models import PaymentTransaction, BalanceHistory, User from .helpers import get_timestamp_from_date def fetch_pays_from_utm(date_begin, date_end): ''' Получить данные из БД UTM ''' date_begin_timestamp = get_timestamp_from_date(date_begin) date_end_timestamp = get_timestamp_from_date(date_end + timedelta(days=1)) pays_raw = session_utm.query( PaymentTransaction.payment_enter_date, PaymentTransaction.payment_absolute ).filter( PaymentTransaction.method == 5, PaymentTransaction.payment_enter_date >= date_begin_timestamp, PaymentTransaction.payment_enter_date < date_end_timestamp ).all() return group_pays_by_date(pays_raw) def calculate_pays_stat_periods(pays, report_periods): '''Функция рассчитывает статистику по платежам за каждый период в report_periods ''' pays_periods_dicts = [] # sum_tmp и count_tmp используется для расчёта смещения относительно # предыдущего отчётного периода sum_tmp = 0 count_tmp = 0 for date_begin, date_end in report_periods: pays_period = [ pay for pay in pays if (pay.get('date') >= date_begin and pay.get('date') < date_end) ] # Расчитываем среднее значение и количество summ = 0 count = 0 for pay in pays_period: summ += pay.get('summ', 0) count += pay.get('count', 0) # Считаем среднее значение платежа (ARPU) avg_pay = summ/count if count > 0 else 0 # Расчитываем изменение относительно предыдущего отчетного периода sum_dif = 0 sum_dif_p = 0 count_dif = 0 count_dif_p = 0 if sum_tmp > 0 and count_tmp > 0: sum_dif = summ - sum_tmp sum_dif_p = sum_dif*100/sum_tmp count_dif = count - count_tmp count_dif_p = count_dif*100/count_tmp sum_tmp = summ count_tmp = count pays_periods_dicts.append( {'date': date_begin, 'summ': summ, 'count': count, 'avg': round(avg_pay, 2), 'sum_dif': sum_dif, 'sum_dif_p': round(sum_dif_p, 2), 'count_dif': count_dif, 'count_dif_p': round(count_dif_p, 2), } ) # Запрашиваем помесячную статистику по исходящему остаткуна # на начало месяца и по количеству активных абонентов на начало месяца # Если статистика не помесячная, то balances_periods = None balances_periods = fetch_balances_periods(report_periods) # Объединяем pays_stat_periods и balances_periods if not balances_periods: return pays_periods_dicts for pays_period_dict, balance_period in zip(pays_periods_dicts, balances_periods): pays_period_dict.update( { 'count_active': balance_period.get('count', 0), 'avg_balance': balance_period.get('avg', 0), 'avg_balance_all': balance_period.get('avg_all', 0), 'sum_balance': balance_period.get('summ', 0), } ) return pays_periods_dicts def calculate_summary_statistic_pays(pays_stat_periods, report_periods, last): ''' Считаем статистику по всем платежам ''' summ_pay, count_pay = 0, 0 for pay in pays_stat_periods: summ_pay += pay['summ'] count_pay += pay['count'] if last == '': count_period = len(report_periods) avg_summ = summ_pay/count_period if count_period > 0 else 0 avg_count = count_pay/count_period if count_period > 0 else 0 else: # Не учитываем последний месяц (он чаще всего не полный) count_period = len(report_periods) - 1 avg_summ = (summ_pay - pays_stat_periods[-1]['summ'])/count_period \ if count_period > 0 else 0 avg_count = (count_pay - pays_stat_periods[-1]['count'])/count_period \ if count_period > 0 else 0 avg_pays = summ_pay/count_pay if count_pay > 0 else 0 return { 'summ': summ_pay, 'count': count_pay, 'avg_summ': avg_summ, 'avg_count': avg_count, 'avg_pay': avg_pays, # ARPU } def fetch_balances_periods(report_periods): ''' Функция расчёта баланса по заданным периодам ''' # Расчитываем только в случае если отчёт помесячный date_begin, date_end = report_periods[0] if (date_end - date_begin) < timedelta(days=28): return balances_dicts = [] for date_begin, date_end in report_periods: # считаем сколько людей с положительным балансом перешло # на текущий месяц, какой у них средний баланс timestamp_begin = get_timestamp_from_date(date_begin) timestamp_end = get_timestamp_from_date(date_begin+timedelta(days=1)) active_balance = session_utm.query( func.count(BalanceHistory.out_balance), func.avg(BalanceHistory.out_balance), func.sum(BalanceHistory.out_balance), ).join( User, BalanceHistory.account_id == User.basic_account ).filter( BalanceHistory.date >= timestamp_begin, BalanceHistory.date < timestamp_end, User.login.op('~')('^\d\d\d\d\d$'), BalanceHistory.out_balance >= 0, BalanceHistory.out_balance < 15000 ).all() # Смотрим средний баланс среди всех абонентов all_balance = session_utm.query( func.count(BalanceHistory.out_balance), func.avg(BalanceHistory.out_balance), func.sum(BalanceHistory.out_balance), ).join( User, BalanceHistory.account_id == User.basic_account ).filter( BalanceHistory.date >= timestamp_begin, BalanceHistory.date < timestamp_end, User.login.op('~')('^\d\d\d\d\d$'), BalanceHistory.out_balance > -15000, BalanceHistory.out_balance < 15000 ).all() count, avg, summ = active_balance[0] if len(active_balance) == 1 else (0, 0, 0) avg_all = all_balance[0][0] if len(all_balance) == 1 else 0 balances_dicts.append( {'date': date_begin, 'count': count, 'avg': avg, 'summ': summ, 'avg_all': avg_all, } ) return balances_dicts
[ 6738, 340, 861, 10141, 1330, 1448, 1525, 198, 6738, 4818, 8079, 1330, 3128, 11, 28805, 12514, 198, 6738, 10088, 1330, 2378, 1136, 353, 198, 198, 6738, 44161, 282, 26599, 1330, 25439, 198, 198, 6738, 764, 26841, 62, 9945, 1330, 6246, 62,...
1.782311
3,652
""" Block Permutations ============================= The permutations of :class:`hyppo.independence.Dcorr` can be restricted to appropriately match known dependencies of samples under the null distribution (i.e. multilevel and longitudinal data). Without such modifications, calculated pvalues are invalid as the default space of permutations are misspecified. In order to restrict the permutations, we pass in a list of group labels. Each column is a list of labels which partitions the observations by shared label into blocks and multiple columns repeat this process recursively. At each level, blocks are exchangeable unless the label is a negative number, in which case it is fixed, and all elements of the final blocks are exchangeable. This defines the space of allowable permutations and the :math:`Y` matrix is permuted accordingly. The block labels used in this notebook are visualized below, corresponding to data where observations are dependent within pairs. Because of the :math:`Y` values in our 2-sample testing case, block labels of :math:`[1, 1, 2, 2, \ldots]` would also have been allowable for both cases but would lead to unnecessary permutations being computed. As shown in the following figures, pvalues under the default permutations are heavily skewed and certainly not uniform, thus presenting either an inflated false positive rate or potentially incredibly low power. When the permutations are restricted, the pvalues under the null distribution are empirically approximately uniformly distributed, as we would hope for. 95% binomial proportion confidence interval error bars are displayed on the histogram of empirical p-values for each bin. """ from collections import defaultdict import matplotlib.pyplot as plt import numpy as np import seaborn as sns from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy.spatial.distance import pdist, squareform # custom seaborn plot options to make the figures pretty sns.set(color_codes=True, style="white", context="notebook", font_scale=1.25) PALETTE = sns.color_palette("Set1") sns.set_palette(PALETTE[3:]) import warnings warnings.filterwarnings("ignore") from hyppo.independence import Dcorr def simulate_2sample_null(n1, n2=None, d=100, group_std=0.1, seed=None): """ Simulates a set of paired observations for a 2-sample test. n1,n2 : size of the two groups. Are both n1 if n2 is None d : dimension of observations group_std : standard deviation of normal distribution around group mean """ np.random.seed(seed) # Means for each observation mus1 = np.random.normal(0, 1, (n1, d)) if n2 is not None: mus2 = np.random.normal(0, 1, (n2, d)) # Paired observations X = np.vstack( [np.random.normal(mu, group_std, (2, d)) for mu in mus1] + [np.random.normal(mu, group_std, (2, d)) for mu in mus2] ) return X # Simulation parameters n1 = 25 n2 = 25 d = 100 group_std = 0.1 # Labels Y_within = np.asarray([0, 1] * (n1 + n2)) Y_across = np.hstack(([0] * n1 * 2, [1] * n2 * 2)) # Permutation tree blocks blocks_within = -1 * np.hstack([[i + 1] * 2 for i in range(n1 + n2)]).T blocks_across = np.c_[ np.hstack([[i + 1] * 2 for i in range(n1 + n2)]), -1 * Y_within - 1 ] # Test params test_blocks = [None, None, blocks_within, blocks_across] test_names = [ "Unrestricted within", "Unrestricted across", "Restricted within", "Restricted across", ] test_Ys = [Y_within, Y_across, Y_within, Y_across] # Plot permutation tree blocks figure fig, axes = plt.subplots(1, 2, figsize=(6, 6)) for ax, data in zip(axes, (blocks_within[:, np.newaxis], blocks_across)): ax.matshow(data[:10], cmap="Set3") for (i, j), z in np.ndenumerate(data[:10]): ax.text(j, i, "{:}".format(int(z)), ha="center", va="center", fontsize=20) ax.set_xticks([]) ax.set_yticks([]) axes[0].set_title("Within", fontsize=30) axes[1].set_title("Across", fontsize=30) plt.suptitle("Permutation Tree Blocks", y=1.07, fontsize=30) plt.show() # Independence tests figures N_DATASETS = 100 REPS = 100 test_results = defaultdict(list) for i in range(N_DATASETS): X = simulate_2sample_null(n1, n2, d, group_std, seed=i) for test, block, Y in zip(test_names, test_blocks, test_Ys): _, pval = Dcorr().test( X, Y, reps=REPS, workers=-1, perm_blocks=block, ) test_results[test].append(pval) # fig, axes = plt.subplots(2,3, figsize=(4, 4*len(data_dict.keys()))) fig = plt.figure(figsize=(16, 8)) # Show data example ax = fig.add_subplot(241) X = simulate_2sample_null(n1, n2, d, group_std, seed=0)[:10, :] X = squareform(pdist(X)) heatmap = ax.pcolor(X, cmap=plt.cm.Blues) ax.invert_yaxis() ax.xaxis.tick_top() ax.set_xticks([]) ax.set_yticks([]) ax.set_title("X distance matrix") divider = make_axes_locatable(ax) cax = divider.append_axes("bottom", size="5%", pad=0.05) plt.colorbar(heatmap, cax=cax, ticks=[0, 10], orientation="horizontal") # Plot Y matrices ax = fig.add_subplot(242) heatmap = ax.pcolor(squareform(pdist(Y_within[:10, np.newaxis])), cmap=plt.cm.Blues) # ax.colorbar(heatmap) ax.invert_yaxis() ax.xaxis.tick_top() ax.set_xticks([]) ax.set_yticks([]) ax.set_title("Y within distance matrix") divider = make_axes_locatable(ax) cax = divider.append_axes("bottom", size="5%", pad=0.05) plt.colorbar(heatmap, cax=cax, ticks=[0, 1], orientation="horizontal") ax = fig.add_subplot(246) heatmap = ax.pcolor( squareform(pdist(np.hstack((Y_across[:5], Y_across[-5:]))[:, np.newaxis])), cmap=plt.cm.Blues, ) # ax.colorbar(heatmap) ax.invert_yaxis() ax.xaxis.tick_top() ax.set_xticks([]) ax.set_yticks([]) ax.set_title("Y across distance matrix") divider = make_axes_locatable(ax) cax = divider.append_axes("bottom", size="5%", pad=0.05) plt.colorbar(heatmap, cax=cax, ticks=[0, 1], orientation="horizontal") # Plot pvalue histograms and errorbars using binomial CIs ax = None for i, test_name in zip([3, 7, 4, 8], test_names): ax = fig.add_subplot(int(str(f"24{i}"))) # , sharey=ax) n = len(test_results[test_name]) entries, edges, _ = ax.hist( test_results[test_name], bins=np.arange(0, 1.1, 0.1), weights=np.ones(n) / n, color="b", ) # entries = height of each column = proportion in that bin # calculate bin centers bin_centers = 0.5 * (edges[:-1] + edges[1:]) ax.axhline(y=sum(entries) / len(bin_centers), ls="--", c="#333333") # errorbars are binomial proportion confidence intervals ax.errorbar( bin_centers, entries, yerr=1.96 * np.sqrt(entries * (1 - entries) / n), fmt=".", c="#333333", ) ax.set_title(f"{test_name} pvalues") # ax.set_xlim(0,1) if i in [3, 4]: ax.set_xticks([]) else: ax.set_xticks([0, 1]) if i in [4, 8]: ax.set_yticks([0, 0.1]) else: ax.set_yticks([0, 0.1, 1]) plt.subplots_adjust(hspace=0.3, wspace=0.3) plt.show()
[ 37811, 198, 12235, 2448, 21973, 602, 198, 4770, 25609, 28, 198, 198, 464, 9943, 32855, 286, 1058, 4871, 25, 63, 12114, 16634, 13, 39894, 13, 35, 10215, 81, 63, 460, 307, 10770, 284, 20431, 2872, 1900, 198, 45841, 3976, 286, 8405, 739,...
2.550672
2,753
""" Module description: """ __version__ = '0.1' __author__ = 'Felice Antonio Merra, Vito Walter Anelli, Claudio Pomo' __email__ = 'felice.merra@poliba.it, vitowalter.anelli@poliba.it, claudio.pomo@poliba.it' import os import numpy as np import tensorflow as tf from tensorflow import keras os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' tf.random.set_seed(0)
[ 37811, 198, 26796, 6764, 25, 198, 198, 37811, 198, 198, 834, 9641, 834, 796, 705, 15, 13, 16, 6, 198, 834, 9800, 834, 796, 705, 42493, 501, 11366, 4638, 430, 11, 569, 10094, 15819, 1052, 23225, 11, 1012, 24051, 350, 17902, 6, 198, ...
2.493056
144
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """The state of the trainer.""" from __future__ import annotations import collections.abc import logging import warnings from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, Optional, Sequence, Union, cast import torch import torch.nn.modules.utils from torch.nn.parallel import DistributedDataParallel from torch.optim import Optimizer from composer.core.precision import Precision from composer.core.serializable import Serializable from composer.core.time import Time, Timestamp, TimeUnit from composer.utils import batch_get, batch_set, dist, ensure_tuple if TYPE_CHECKING: import deepspeed import composer.core.types as types from composer.core.algorithm import Algorithm from composer.core.callback import Callback from composer.core.evaluator import Evaluator from composer.profiler import Profiler __all__ = ["State"] logger = logging.getLogger(__name__) _STATE_DICT_SERIALIZED_ATTRIBUTES = [ # List of attributes that are serialized with state_dict # Only the attributes listed in state.serialized_attributes will actually be saved. "model", "optimizers", "schedulers", "algorithms", "callbacks", "scaler", "timestamp", ] class State(Serializable): """The state of the trainer. Contains variables that the trainer tracks throughout the training loop. Note that all the necessary parts (i.e., :attr:`serialized_attributes`) of state are serialized when the trainer is checkpointed so that it can be used restore the trainer and continue training from a checkpoint. :mod:`~composer.algorithms` are able to modify an instance of this class in-place. .. note:: An instance of this class is automatically constructed by the :class:`~.Trainer` constructor. A user need not instantiate this class. Args: model (torch.nn.Module): The model, typically as a subclass of :class:`~.ComposerModel`. rank_zero_seed (int): The seed used on the rank zero process. It is assumed that each rank's seed is ``rank_zero_seed + dist.get_global_rank()``. grad_accum (int, optional): The number of gradient accumulation steps to use. With this argument, micro batch size for each device becomes ``microbatch_size = train_batch_size / (num_devices * grad_accum)``. train_dataloader (types.DataLoader, optional): Dataloader used for training evaluators (Evalutor | Evaluators, optional): :class:`.Evaluator` used for evaluation. dataloader (types.DataLoader, optional): The active DataLoader. dataloader_len (int | Time[int], optional): The number of batches per dataloader iteration (e.g. epoch). The trainer will yield the first ``dataloader_len`` batches per iteration. If ``-1`` (the default), the entire dataloader will be iterated over. dataloader_label (str, optional): The name for the dataloader. Required if ``dataloader`` is specified. (default: ``None``) By convention, the training dataloader is called ``'train'``. The evaluator dataloader is called ``'eval'``, or when multiple evaluators are used, the name of the evaluator. max_duration (str | Time, optional): The maximum duration to train for. (default: ``None``) precision (str | Precision): The numerical precision to use for training. See :class:`~.Precision` for the supported precisions. optimizers (torch.optim.Optimizer | Sequence[torch.optim.Optimizer], optional): The optimizer being used to train the model. Multiple optimizers are not currently supported. schedulers (types.PyTorchScheduler | Sequence[types.PyTorchScheduler], optional): The learning rate scheduler (can also be a list or tuple of schedulers). scaler (torch.cuda.amp.GradScaler, optional): The gradient scaler in use for mixed precision training. algorithms (Algorithm | Sequence[Algorithm], optional): The algorithms used for training. callbacks (Callback | Sequence[Callback], optional): The callbacks used for training. profiler (Optional[Profiler]): The Composer profiler. Attributes: batch (types.Batch): The batch. This will be the entire batch during the :attr:`.Event.AFTER_DATALOADER`, or a microbatch between :attr:`.Event.BATCH_START` and :attr:`.Event.BATCH_END`. current_metrics (Dict[str, Dict[str, Any]]): The current computed metrics, organized by dataloader label and then by metric name. The train dataloader is labeled ``'train'``. If not using an :class:`.Evaluator`, the eval dataloader is labeled ``'eval'``. Otherwise, the evaluator label is used. For example: >>> trainer = Trainer( ... ..., ... compute_training_metrics=True, ... train_dataloader=train_dataloader, ... eval_dataloader=eval_dataloader, ... ) >>> trainer.fit() >>> trainer.state.current_metrics {'train': {'Accuracy': tensor(...)}, 'eval': {'Accuracy': tensor(...)}} Or, when using an :class:`.Evaluator`: .. testsetup:: eval_1_dl = eval_dataloader eval_2_dl = eval_dataloader >>> from torchmetrics import Accuracy >>> from composer.core import Evaluator >>> trainer = Trainer( ... ..., ... compute_training_metrics=True, ... train_dataloader=train_dataloader, ... eval_dataloader=[ ... Evaluator(label='eval1', dataloader=eval_1_dl, metrics=Accuracy()), ... Evaluator(label='eval2', dataloader=eval_2_dl, metrics=Accuracy()), ... ], ... ) >>> trainer.fit() >>> trainer.state.current_metrics {'train': {'Accuracy': tensor(...)}, 'eval1': {'Accuracy': tensor(...)}, 'eval2': {'Accuracy': tensor(...)}} eval_timestamp (Timestamp): The timestamp for the current evaluation dataloader. This timestamp is reset before the dataloader is evaluated. The :attr:`~Timestamp.epoch` attribute for this timestamp is always ``0``. grad_accum (int): The number of gradient accumulation steps per batch. loss (torch.Tensor | Sequence[torch.Tensor]): The most recently computed loss. model (torch.nn.Module): The training model. .. note:: When using DeepSpeed or multi-rank training, the model will be wrapped with :class:`~deepspeed.DeepSpeedEngine` or :class:`~torch.nn.parallel.DistributedDataParallel`, respectively. outputs (torch.Tensor | Sequence[torch.Tensor]): The most recently computed output from the model's forward pass. predict_timestamp (Timestamp): The timestamp for the current prediction dataloader. This timestamp is reset before the dataloader is used. The :attr:`~Timestamp.epoch` attribute for this timestamp is always ``0``. profiler (Profiler): The profiler (if profiling is enabled), or ``None`` if not profiling. rank_zero_seed (int): The seed of the rank zero process. scaler (torch.cuda.amp.GradScaler): The gradient scaler if using mixed-precision training, or ``None`` if not using mixed-precision training. serialized_attributes (List[str]): The names of the attribute which are serialized in a checkpoint. By default, the following attributes are serialized: +-----------------------+-------------------------------------------------------------+ | Attribute | Description | +=======================+=============================================================+ | model | The model under training. | +-----------------------+-------------------------------------------------------------+ | optimizers | The optimizers being used to train the model. | +-----------------------+-------------------------------------------------------------+ | schedulers | The learning rate schedulers. | +-----------------------+-------------------------------------------------------------+ | algorithms | The algorithms used for training. | +-----------------------+-------------------------------------------------------------+ | callbacks | The callbacks used for training. | +-----------------------+-------------------------------------------------------------+ | scaler | The gradient scaler in use for mixed precision training. | +-----------------------+-------------------------------------------------------------+ | timestamp | The timestamp that tracks training loop progress. | +-----------------------+-------------------------------------------------------------+ | rank_zero_seed | The seed of the rank zero process. | +-----------------------+-------------------------------------------------------------+ | current_metrics | The current metrics. | +-----------------------+-------------------------------------------------------------+ timestamp (Timestamp): The current training timestamp. train_dataloader (Iterable): The training dataloader. (May be ``None`` if not training.) """ @property def seed(self): """The seed for the current rank.""" return self.rank_zero_seed + dist.get_global_rank() @property def max_duration(self): """The maximum training duration.""" return self._max_duration @max_duration.setter def get_elapsed_duration(self) -> Optional[Time[float]]: """Get the elapsed training duration. Returns: Optional[Time[float]]: The elapsed duration, in :attr:`TimeUnit.DURATION`. ``Time(0.0, TimeUnit.DURATION)`` represents the beginning of training and ``Time(1.0, TimeUnit.DURATION)`` represents a completed training process. Returns ``None`` if ``max_duration`` is None. """ if self.max_duration is None: return None return self.timestamp.get(self.max_duration.unit) / self.max_duration @property def optimizers(self): """The optimizers.""" return self._optimizers @optimizers.setter @property def schedulers(self): """The schedulers.""" return self._schedulers @schedulers.setter def batch_get_item(self, key: Union[str, int, Callable, Any]) -> Any: """Gets element from batch either specified by key or user-specified function. See batch_get in `utils/batch_helpers.py` for examples. Args: key (str | int | Tuple[Callable, Callable] | Any, optional): A key to index into the batch or a user-specified function to do the extracting. A pair of callables is also supported for cases where a get and set function pair are both passed (like in Algorithms). The getter is assumed to be the first of the pair. Returns: The part of the batch specified by the key. This could be any type depending on what the batch is composed of. """ return batch_get(self.batch, key) def batch_set_item(self, key: Union[str, int, Callable, Any], value: Any): """Sets the element specified by the key of the set_fn to the specified value. This is not an in-place operation, as for tuple-typed batches, a new batch object must be created to modify them. See batch_set in `utils/batch_helpers.py` for examples. Args: key (str | int | Tuple[Callable, Callable] | Any, optional): A key to index into the batch or a user-specified function to do the setting. A pair of callables is also supported for cases where a get and set function pair are both passed (like in Algorithms). The setter is assumed to be the second of the pair. value (Any): The value that batch[key] or batch.key gets set to or that the user-defined set function sets a part of the batch to. Returns: batch (Any): The updated batch with value set at key. """ self.batch = batch_set(self.batch, key=key, value=value) @property def callbacks(self): """The callbacks.""" return self._callbacks @callbacks.setter @property def algorithms(self): """The algorithms.""" return self._algorithms @algorithms.setter @property def evaluators(self): """The evaluators.""" return self._evaluators @evaluators.setter def load_model_state(self, state_dict: Dict[str, Any], strict: bool): """Loads the model's state from a ``state_dict``. Args: state_dict (Dict[str, Any]): The state dict, generated from a previous call to :meth:`state_dict`. strict (bool): Whether the keys (i.e., model parameter names) in the model state dict should perfectly match the keys in the model instance. """ if state_dict.get("is_model_ddp", False) and not self.is_model_ddp: # This check is for backwards compatibility, as pre-v0.6.0 checkpoints serialized the state # with the `module.` prefix torch.nn.modules.utils.consume_prefix_in_state_dict_if_present(state_dict['model'], "module.") missing_keys, unexpected_keys = self.model.load_state_dict(state_dict['model'], strict=strict) if len(missing_keys) > 0: logger.warning(f"Found these missing keys in the checkpoint: {', '.join(missing_keys)}") if len(unexpected_keys) > 0: logger.warning(f"Found these unexpected keys in the checkpoint: {', '.join(unexpected_keys)}") def load_state_dict(self, state: Dict[str, Any], strict: bool = False): """Loads the state. Args: state (Dict[str, Any]): object returned from call to :meth:`state_dict`. strict (bool): whether the keys in the ``state["model"]`` should perfectly match the keys in the ``self.model``. Defaults to False. """ state = _ensure_backwards_compatible_checkpointing(state) for attribute_name, serialized_value in state.items(): if attribute_name not in self.serialized_attributes: # it's possible some attributes we removed continue if attribute_name == "model": self.load_model_state(state, strict=strict) continue state_field_value = getattr(self, attribute_name) if attribute_name in _STATE_DICT_SERIALIZED_ATTRIBUTES: for target in ensure_tuple(state_field_value): if type(target).__qualname__ not in serialized_value: warnings.warn( f"{type(target).__qualname__} is not in the state_dict. Its state will not be restored.", category=UserWarning) continue source = serialized_value[type(target).__qualname__] target.load_state_dict(source) else: # direct serialization try: setattr(self, attribute_name, serialized_value) except AttributeError: # ignore AttributeError for properties that have getters but not setters. pass @property def dataloader(self): """The active dataloader.""" return self._dataloader @property def dataloader_label(self): """The dataloader label for the active dataloader. By default, the training dataloader is called ``'train'``. The evaluator dataloader is called ``'eval'``, or when multiple evaluators are used, the name of the evaluator. However, the dataloader label can be explicitely specified in :meth:`.Trainer.fit` and :meth:`.Trainer.eval`. Returns: Optional[str]: The dataloader label, or None if no dataloader is set. """ return self._dataloader_label def set_dataloader( self, dataloader: Optional[Iterable] = None, dataloader_label: Optional[str] = None, dataloader_len: Union[int, Time[int]] = -1, ): """Update the active dataloader and dataloader label. Args: dataloader (Iterable, optional): The dataloader. Defaults to None. dataloader_label (str, optional): The dataloader label. Must be ``None`` if and only if ``dataloader`` is None. Defaults to None. dataloader_len (int, int): The number of batches per dataloader iteration (e.g. epoch), as used by the trainer. Set to ``-1`` to iterate over the entire dataset. (Default: ``-1``.) """ if dataloader is None: dataloader_label = None else: if dataloader_label is None: raise ValueError("If the `dataloader` is specified, then `dataloader_label` must not be None.") self._dataloader = dataloader self._dataloader_label = dataloader_label if dataloader is not None: self.dataloader_len = dataloader_len # setting it to -1 will do a failsafe read of len(dataloader) else: self._dataloader_len = None @property def dataloader_len(self): """The number of batches per dataloader iteration (e.g. epoch), as used by the trainer. .. note:: If not explicitely specified, this value is an approximation, as it depends on ``len(self.dataloader)``. See the :doc:`PyTorch DataLoader Documentation <torch:data>` for more information. Returns: Optional[Time[int]]: The number of batches per dataloader iteration (e.g. epoch), or None if no dataloader is defined or if the dataloader has an unknown length (e.g. streaming dataloaders). """ return self._dataloader_len @dataloader_len.setter @property def precision(self): """The numerical precision to use for training. See :class:`~.Precision` for the supported precisions. """ return self._precision @precision.setter @property def is_model_deepspeed(self) -> bool: """Whether :attr:`model` is an instance of a :class:`~deepspeed.DeepSpeedEngine`.""" try: import deepspeed except ImportError: return False else: return isinstance(self.model, deepspeed.DeepSpeedEngine) @property def is_model_ddp(self): """Whether :attr:`model` is an instance of a :class:`.DistributedDataParallel`.""" return isinstance(self.model, DistributedDataParallel) @property def deepspeed_model(self) -> deepspeed.DeepSpeedEngine: """Cast :attr:`model` to :class:`~deepspeed.DeepSpeedEngine`.""" if self.is_model_deepspeed: return cast("deepspeed.DeepSpeedEngine", self.model) raise TypeError("state.model is not a DeepSpeed model")
[ 2, 15069, 33160, 5826, 18452, 5805, 29936, 263, 7035, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 37811, 464, 1181, 286, 262, 21997, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, ...
2.503197
7,977
# -------------- # import the libraries import numpy as np import pandas as pd import seaborn as sns from sklearn.model_selection import train_test_split import warnings warnings.filterwarnings('ignore') # Code starts here df = pd.read_csv(path) df.head() X = df.iloc[:,: -1] y = df.iloc[:,-1] X_train, X_test , y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 6) # Code ends here # -------------- import matplotlib.pyplot as plt # Code starts here plt.boxplot(X_train['bmi']) q_value = X_train['bmi'].quantile(.95) y_train.value_counts() # Code ends here # -------------- # Code starts here relation = X_train.corr() print(relation) sns.pairplot(X_train) # Code ends here # -------------- import seaborn as sns import matplotlib.pyplot as plt # Code starts here cols = ['children','sex','region','smoker'] # create subplot fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(20,20)) # create loop for plotting countplot for i in range(0,2): for j in range(0,2): col=cols[i*2 + j] sns.countplot(x=X_train[col], hue=y_train, ax=axes[i,j]) # Code ends here # -------------- from sklearn.model_selection import GridSearchCV, RandomizedSearchCV from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score # parameters for grid search parameters = {'C':[0.1,0.5,1,5]} # Code starts here lr = LogisticRegression() grid = GridSearchCV(estimator = lr, param_grid= parameters) grid.fit(X_train, y_train) y_pred = grid.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(accuracy) # Code ends here # -------------- from sklearn.metrics import roc_auc_score from sklearn import metrics # Code starts here score = roc_auc_score(y_test, y_pred) y_pred_proba = grid.predict_proba(X_test)[:,1] fpr, tpr, thresholds = metrics.roc_curve(y_test, y_pred_proba) roc_auc = roc_auc_score(y_test, y_pred_proba) plt.plot(fpr,tpr,label="Logistic model, auc="+str(roc_auc)) # Code ends here
[ 2, 220, 26171, 198, 2, 1330, 262, 12782, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 384, 397, 1211, 355, 3013, 82, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 4512, 62, 9288, 62, 35...
2.559645
788
from .local_settings import *
[ 6738, 764, 12001, 62, 33692, 1330, 1635, 198 ]
3.75
8
from KratosMultiphysics import Parameters import ethier_benchmark_analysis BaseAnalysis = ethier_benchmark_analysis.EthierBenchmarkAnalysis
[ 6738, 509, 10366, 418, 15205, 13323, 23154, 1330, 40117, 198, 11748, 4555, 959, 62, 26968, 4102, 62, 20930, 198, 14881, 32750, 796, 4555, 959, 62, 26968, 4102, 62, 20930, 13, 40226, 959, 44199, 4102, 32750, 198 ]
3.888889
36
from pydantic.dataclasses import dataclass from ..vae import VAEConfig @dataclass class BetaVAEConfig(VAEConfig): r""" :math:`\beta`-VAE model config config class Parameters: input_dim (tuple): The input_data dimension. latent_dim (int): The latent space dimension. Default: None. reconstruction_loss (str): The reconstruction loss to use ['bce', 'mse']. Default: 'mse' beta (float): The balancing factor. Default: 1 """ beta: float = 1.0
[ 6738, 279, 5173, 5109, 13, 19608, 330, 28958, 1330, 4818, 330, 31172, 198, 198, 6738, 11485, 33353, 1330, 13753, 2943, 261, 5647, 628, 198, 31, 19608, 330, 31172, 198, 4871, 17993, 11731, 2943, 261, 5647, 7, 11731, 2943, 261, 5647, 2599...
2.681081
185
import queue if __name__ == '__main__': main()
[ 11748, 16834, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 198 ]
2.454545
22
"""This program is to fetch the words from an url online. Example: $python words.py "http://sixty-north.com/c/t.txt" """ import sys from urllib.request import urlopen # Do Something nice: if __name__ == "__main__": print_items(fetch_words(sys.argv[1]))
[ 37811, 1212, 1430, 318, 284, 21207, 262, 2456, 422, 281, 19016, 2691, 13, 198, 198, 16281, 25, 198, 3, 29412, 2456, 13, 9078, 366, 4023, 1378, 82, 19404, 12, 43588, 13, 785, 14, 66, 14, 83, 13, 14116, 1, 198, 37811, 198, 11748, 25...
2.721649
97
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from kubernetes.client.configuration import Configuration class ComCoreosMonitoringV1PrometheusStatus(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'available_replicas': 'int', 'paused': 'bool', 'replicas': 'int', 'unavailable_replicas': 'int', 'updated_replicas': 'int' } attribute_map = { 'available_replicas': 'availableReplicas', 'paused': 'paused', 'replicas': 'replicas', 'unavailable_replicas': 'unavailableReplicas', 'updated_replicas': 'updatedReplicas' } def __init__(self, available_replicas=None, paused=None, replicas=None, unavailable_replicas=None, updated_replicas=None, local_vars_configuration=None): # noqa: E501 """ComCoreosMonitoringV1PrometheusStatus - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._available_replicas = None self._paused = None self._replicas = None self._unavailable_replicas = None self._updated_replicas = None self.discriminator = None self.available_replicas = available_replicas self.paused = paused self.replicas = replicas self.unavailable_replicas = unavailable_replicas self.updated_replicas = updated_replicas @property def available_replicas(self): """Gets the available_replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 Total number of available pods (ready for at least minReadySeconds) targeted by this Prometheus deployment. # noqa: E501 :return: The available_replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 :rtype: int """ return self._available_replicas @available_replicas.setter def available_replicas(self, available_replicas): """Sets the available_replicas of this ComCoreosMonitoringV1PrometheusStatus. Total number of available pods (ready for at least minReadySeconds) targeted by this Prometheus deployment. # noqa: E501 :param available_replicas: The available_replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 :type: int """ if self.local_vars_configuration.client_side_validation and available_replicas is None: # noqa: E501 raise ValueError("Invalid value for `available_replicas`, must not be `None`") # noqa: E501 self._available_replicas = available_replicas @property def paused(self): """Gets the paused of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 Represents whether any actions on the underlying managed objects are being performed. Only delete actions will be performed. # noqa: E501 :return: The paused of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 :rtype: bool """ return self._paused @paused.setter def paused(self, paused): """Sets the paused of this ComCoreosMonitoringV1PrometheusStatus. Represents whether any actions on the underlying managed objects are being performed. Only delete actions will be performed. # noqa: E501 :param paused: The paused of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 :type: bool """ if self.local_vars_configuration.client_side_validation and paused is None: # noqa: E501 raise ValueError("Invalid value for `paused`, must not be `None`") # noqa: E501 self._paused = paused @property def replicas(self): """Gets the replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 Total number of non-terminated pods targeted by this Prometheus deployment (their labels match the selector). # noqa: E501 :return: The replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 :rtype: int """ return self._replicas @replicas.setter def replicas(self, replicas): """Sets the replicas of this ComCoreosMonitoringV1PrometheusStatus. Total number of non-terminated pods targeted by this Prometheus deployment (their labels match the selector). # noqa: E501 :param replicas: The replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 :type: int """ if self.local_vars_configuration.client_side_validation and replicas is None: # noqa: E501 raise ValueError("Invalid value for `replicas`, must not be `None`") # noqa: E501 self._replicas = replicas @property def unavailable_replicas(self): """Gets the unavailable_replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 Total number of unavailable pods targeted by this Prometheus deployment. # noqa: E501 :return: The unavailable_replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 :rtype: int """ return self._unavailable_replicas @unavailable_replicas.setter def unavailable_replicas(self, unavailable_replicas): """Sets the unavailable_replicas of this ComCoreosMonitoringV1PrometheusStatus. Total number of unavailable pods targeted by this Prometheus deployment. # noqa: E501 :param unavailable_replicas: The unavailable_replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 :type: int """ if self.local_vars_configuration.client_side_validation and unavailable_replicas is None: # noqa: E501 raise ValueError("Invalid value for `unavailable_replicas`, must not be `None`") # noqa: E501 self._unavailable_replicas = unavailable_replicas @property def updated_replicas(self): """Gets the updated_replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 Total number of non-terminated pods targeted by this Prometheus deployment that have the desired version spec. # noqa: E501 :return: The updated_replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 :rtype: int """ return self._updated_replicas @updated_replicas.setter def updated_replicas(self, updated_replicas): """Sets the updated_replicas of this ComCoreosMonitoringV1PrometheusStatus. Total number of non-terminated pods targeted by this Prometheus deployment that have the desired version spec. # noqa: E501 :param updated_replicas: The updated_replicas of this ComCoreosMonitoringV1PrometheusStatus. # noqa: E501 :type: int """ if self.local_vars_configuration.client_side_validation and updated_replicas is None: # noqa: E501 raise ValueError("Invalid value for `updated_replicas`, must not be `None`") # noqa: E501 self._updated_replicas = updated_replicas def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ComCoreosMonitoringV1PrometheusStatus): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, ComCoreosMonitoringV1PrometheusStatus): return True return self.to_dict() != other.to_dict()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 37811, 198, 220, 220, 220, 12554, 527, 3262, 274, 628, 220, 220, 220, 1400, 6764, 2810, 357, 27568, 416, 4946, 15042, 35986, 3740, 1378, 12567, 13, 785, 14, 9654, 499, 270, 10141, 14, 9654, ...
2.564794
3,596
# Copyright (c) 2018 Dow Jones & Company, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from sast_controller.drivers.cx.Checkmarx import Checkmarx ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) INCREMENTAL_SCAN_ERROR = 'full scan should be submitted for accurate results' NO_SOURCES_ERROR = 'worker failed to retrieve scan' NO_SOURCES = "No supported files to scan in Checkmarx. \n Please find details by the link:\n " \ "https://checkmarx.atlassian.net/wiki" \ "/spaces/KC/pages/141328390/8.5.0+Supported+Code+Languages+and+Frameworks " class CxIncrementalScanException(Exception): """Use when unable to start Checkmarx incremental scan""" class CxNoSourceScanException(Exception): """Use when no supported files in zip""" def scan_project(local_path=None, project=None, incremental_scan=False): """ Scan project using Checkmarx :param local_path: path to folder with project :param project: name of Checkmarx project :param incremental_scan: :return: :raise: CxIncrementalScanException if unable to start incremental scan """ cxClient = Checkmarx(project) report = None if not cxClient.valid: cxClient.logger.critical("Invalid connection") return report response = cxClient.run_scan(local_path=local_path, incremental_scan=incremental_scan) if not response: cxClient.logger.critical("No response") return report run_id = response.RunId if run_id: currently_running = None scan_id = None while currently_running != 'Finished': scan = cxClient.get_status_of_single_run(run_id) status = scan.CurrentStatus currently_running = status if currently_running == 'Finished': cxClient.logger.info("Scan Finished") try: scan_id = scan.ScanId except Exception: cxClient.logger.critical(str(scan)) raise if currently_running == 'Failed': cxClient.logger.critical("Scan Failed") if scan.StageMessage.find(NO_SOURCES_ERROR) > -1: raise CxNoSourceScanException(NO_SOURCES) cxClient.logger.critical(str(scan)) if str(scan).find(INCREMENTAL_SCAN_ERROR) > -1: raise CxIncrementalScanException(str(scan)) break if currently_running != "Failed": report_id = cxClient.create_scan_report(scan_id).ID while not cxClient.get_scan_report_status(report_id).IsReady: cxClient.logger.info("Report generation in progress") report = cxClient.get_scan_report(report_id) return report
[ 2, 220, 15069, 357, 66, 8, 2864, 21842, 5437, 1222, 5834, 11, 3457, 13, 198, 2, 198, 2, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 220, 345, 743, 407, 779, 428, 2393, 2845, ...
2.445335
1,372
from django.conf.urls import url from . import views app_name= "app" urlpatterns = [ # ex : /book/ url(r'^$', views.Index, name="Index"), url(r'^test$', views.test, name="test"), # ex : /book/list url(r'^list/$', views.Book_list, name="book-list"), # ex : /book/1/ url(r'^(?P<pk>[0-9]+)/$', views.Book_detail, name="book-detail"), # ex : /author/ url(r'^author/$', views.Author, name="author"), # ex : /author/1/ url(r'^author/(?P<pk>[0-9]+)/$', views.Author_detail, name="author-detail"), ]
[ 6738, 42625, 14208, 13, 10414, 13, 6371, 82, 1330, 19016, 198, 6738, 764, 1330, 5009, 198, 198, 1324, 62, 3672, 28, 366, 1324, 1, 198, 198, 6371, 33279, 82, 796, 685, 198, 220, 220, 220, 1303, 409, 1058, 1220, 2070, 14, 198, 220, ...
2.219008
242
from django.shortcuts import render from rest_framework import status from rest_framework import generics from rest_framework import viewsets from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.permissions import (IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly) from django.contrib.auth import authenticate from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token from . import models from . import serializers from .permissions import IsOwnArticleOrReadOnly # @api_view(["GET"]) # def home(request): # return Response({"message":"Welcome Home!"}, # status=status.HTTP_200_OK) # class ArticleListCreateAPIView(APIView): # def get(self, request): # articles = models.Article.objects.all() # serializer = serializers.ArticleSerializer(articles, many=True) # return Response(serializer.data) # def post(self, request): # serializer = serializers.ArticleSerializer(data=request.data) # if serializer.is_valid(): # serializer.save() # return Response(serializer.data, status=status.HTTP_201_CREATED) # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # class ArticleDetailAPIView(APIView): # def get(self, request, pk): # article = models.Article.objects.get(id=pk) # serializer = serializers.ArticleSerializer(article) # return Response(serializer.data) # def put(self, request, pk): # article = models.Article.objects.get(id=pk) # serializer = serializers.ArticleSerializer(article, request.data) # if serializer.is_valid(): # serializer.save() # return Response(serializer.data) # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # def delete(self, request, pk): # article = models.Article.objects.get(id=pk) # article.delete() # return Response(status=status.HTTP_204_NO_CONTENT) # class ArticleListCreateView(generics.ListCreateAPIView): # queryset = models.Article.objects.all() # serializer_class = serializers.ArticleSerializer # class ArticleDetailView(generics.RetrieveUpdateDestroyAPIView): # queryset = models.Article.objects.all() # serializer_class = serializers.ArticleSerializer @csrf_exempt @api_view(['POST'])
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 1334, 62, 30604, 1330, 3722, 198, 6738, 1334, 62, 30604, 1330, 1152, 873, 198, 6738, 1334, 62, 30604, 1330, 5009, 1039, 198, 6738, 1334, 62, 30604, 13, 12501, 273, 2024, 1330,...
2.621926
976
import logging from abc import ABC, abstractmethod from oshino.util import current_ts, timer
[ 11748, 18931, 198, 198, 6738, 450, 66, 1330, 9738, 11, 12531, 24396, 198, 198, 6738, 267, 1477, 2879, 13, 22602, 1330, 1459, 62, 912, 11, 19781, 628 ]
3.555556
27
"""Functions for building tensorflow graph """ # MIT License # # Copyright (c) 2018 Debayan Deb # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import tensorflow as tf import tensorflow.contrib.slim as slim def average_grads(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of gradients. The outer list is over different towers. The inner list is over the gradient calculation in each tower. Returns: List of gradients where the gradient has been averaged across all towers. """ if len(tower_grads) == 1: return tower_grads[0] else: average_grads = [] for grad_ in zip(*tower_grads): # Note that each grad looks like the following: # (grad0_gpu0, ... , grad0_gpuN) average_grad = None if grad_[0]==None else average_tensors(grad_) average_grads.append(average_grad) return average_grads def collect_watch_list(): '''Collect the variables in watch list. Tensors or Varialbes can be addto collection 'watchlist' with the type of tuple ('name', var/tensor). The functions collects them and returns a dict for evaluate ''' watch_list = {} for pair in tf.get_collection('watch_list'): watch_list[pair[0]] = pair[1] return watch_list def restore_model(sess, var_list, model_dir, restore_scopes=None): ''' Load the variable values from a checkpoint file into pre-defined graph. Filter the variables so that they contain at least one of the given keywords.''' with sess.graph.as_default(): if restore_scopes is not None: var_list = [var for var in var_list if any([scope in var.name for scope in restore_scopes])] model_dir = os.path.expanduser(model_dir) ckpt_file = tf.train.latest_checkpoint(model_dir) print('Restoring variables from %s ...' % ckpt_file) saver = tf.train.Saver(var_list) saver.restore(sess, ckpt_file) def load_model(sess, model_path, scope=None): ''' Load the the graph and variables values from a model path. Model path is either a a frozen graph or a directory with both a .meta file and checkpoint files.''' with sess.graph.as_default(): model_path = os.path.expanduser(model_path) if (os.path.isfile(model_path)): # Frozen grpah print('Model filename: %s' % model_path) with gfile.FastGFile(model_path,'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name='') else: # Load grapha and variables separatedly. meta_files = [file for file in os.listdir(model_path) if file.endswith('.meta')] assert len(meta_files) == 1 meta_file = os.path.join(model_path, meta_files[0]) ckpt_file = tf.train.latest_checkpoint(model_path) print('Metagraph file: %s' % meta_file) print('Checkpoint file: %s' % ckpt_file) saver = tf.train.import_meta_graph(meta_file, clear_devices=True, import_scope=scope) saver.restore(sess, ckpt_file) def euclidean_distance(X, Y, sqrt=False): '''Compute the distance between each X and Y. Args: X: a (m x d) tensor Y: a (d x n) tensor Returns: diffs: an m x n distance matrix. ''' with tf.name_scope('EuclideanDistance'): XX = tf.reduce_sum(tf.square(X), 1, keep_dims=True) YY = tf.reduce_sum(tf.square(Y), 0, keep_dims=True) XY = tf.matmul(X, Y) diffs = XX + YY - 2*XY if sqrt == True: diffs = tf.sqrt(tf.maximum(0.0, diffs)) return diffs
[ 37811, 24629, 2733, 329, 2615, 11192, 273, 11125, 4823, 198, 37811, 198, 2, 17168, 13789, 198, 2, 220, 198, 2, 15069, 357, 66, 8, 2864, 8965, 22931, 8965, 198, 2, 220, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, ...
2.479095
2,033
"""Corma, one time report to rule them all!""" import argparse # corma report test-dev -t 7h -d 2020-10-12 # corma report vacation # corma submit bombardier -t 2020-09 if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("register") parser.parse_args()
[ 37811, 34, 579, 64, 11, 530, 640, 989, 284, 3896, 606, 477, 2474, 15931, 628, 198, 11748, 1822, 29572, 198, 198, 2, 269, 579, 64, 989, 1332, 12, 7959, 532, 83, 767, 71, 532, 67, 12131, 12, 940, 12, 1065, 198, 2, 269, 579, 64, ...
2.768519
108
#!/usr/bin/env python import argparse import numpy as np import pandas as pd import logging main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 18931, 628, 198, 12417, 3419 ]
3.060606
33
# Copyright (c) 2017 Hitachi, Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from http import client as http_client from ironic_lib import metrics_utils from oslo_utils import uuidutils from pecan import rest from ironic import api from ironic.api.controllers import link from ironic.api.controllers.v1 import collection from ironic.api.controllers.v1 import notification_utils as notify from ironic.api.controllers.v1 import utils as api_utils from ironic.api import method from ironic.common import args from ironic.common import exception from ironic.common.i18n import _ from ironic import objects METRICS = metrics_utils.get_metrics_logger(__name__) _DEFAULT_RETURN_FIELDS = ['uuid', 'node_uuid', 'type', 'connector_id'] CONNECTOR_SCHEMA = { 'type': 'object', 'properties': { 'connector_id': {'type': 'string'}, 'extra': {'type': ['object', 'null']}, 'node_uuid': {'type': 'string'}, 'type': {'type': 'string'}, 'uuid': {'type': ['string', 'null']}, }, 'required': ['connector_id', 'node_uuid', 'type'], 'additionalProperties': False, } CONNECTOR_VALIDATOR_EXTRA = args.dict_valid( node_uuid=args.uuid, uuid=args.uuid, ) CONNECTOR_VALIDATOR = args.and_valid( args.schema(CONNECTOR_SCHEMA), CONNECTOR_VALIDATOR_EXTRA ) PATCH_ALLOWED_FIELDS = [ 'connector_id', 'extra', 'node_uuid', 'type' ] class VolumeConnectorsController(rest.RestController): """REST controller for VolumeConnectors.""" invalid_sort_key_list = ['extra'] @METRICS.timer('VolumeConnectorsController.get_all') @method.expose() @args.validate(node=args.uuid_or_name, marker=args.uuid, limit=args.integer, sort_key=args.string, sort_dir=args.string, fields=args.string_list, detail=args.boolean) def get_all(self, node=None, marker=None, limit=None, sort_key='id', sort_dir='asc', fields=None, detail=None): """Retrieve a list of volume connectors. :param node: UUID or name of a node, to get only volume connectors for that node. :param marker: pagination marker for large data sets. :param limit: maximum number of resources to return in a single result. This value cannot be larger than the value of max_limit in the [api] section of the ironic configuration, or only max_limit resources will be returned. :param sort_key: column to sort results by. Default: id. :param sort_dir: direction to sort. "asc" or "desc". Default: "asc". :param fields: Optional, a list with a specified set of fields of the resource to be returned. :param detail: Optional, whether to retrieve with detail. :returns: a list of volume connectors, or an empty list if no volume connector is found. :raises: InvalidParameterValue if sort_key does not exist :raises: InvalidParameterValue if sort key is invalid for sorting. :raises: InvalidParameterValue if both fields and detail are specified. """ api_utils.check_policy('baremetal:volume:get') if fields is None and not detail: fields = _DEFAULT_RETURN_FIELDS if fields and detail: raise exception.InvalidParameterValue( _("Can't fetch a subset of fields with 'detail' set")) resource_url = 'volume/connectors' return self._get_volume_connectors_collection( node, marker, limit, sort_key, sort_dir, resource_url=resource_url, fields=fields, detail=detail) @METRICS.timer('VolumeConnectorsController.get_one') @method.expose() @args.validate(connector_uuid=args.uuid, fields=args.string_list) def get_one(self, connector_uuid, fields=None): """Retrieve information about the given volume connector. :param connector_uuid: UUID of a volume connector. :param fields: Optional, a list with a specified set of fields of the resource to be returned. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: VolumeConnectorNotFound if no volume connector exists with the specified UUID. """ api_utils.check_policy('baremetal:volume:get') if self.parent_node_ident: raise exception.OperationNotPermitted() rpc_connector = objects.VolumeConnector.get_by_uuid( api.request.context, connector_uuid) return convert_with_links(rpc_connector, fields=fields) @METRICS.timer('VolumeConnectorsController.post') @method.expose(status_code=http_client.CREATED) @method.body('connector') @args.validate(connector=CONNECTOR_VALIDATOR) def post(self, connector): """Create a new volume connector. :param connector: a volume connector within the request body. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: VolumeConnectorTypeAndIdAlreadyExists if a volume connector already exists with the same type and connector_id :raises: VolumeConnectorAlreadyExists if a volume connector with the same UUID already exists """ context = api.request.context api_utils.check_policy('baremetal:volume:create') if self.parent_node_ident: raise exception.OperationNotPermitted() # NOTE(hshiina): UUID is mandatory for notification payload if not connector.get('uuid'): connector['uuid'] = uuidutils.generate_uuid() node = api_utils.replace_node_uuid_with_id(connector) new_connector = objects.VolumeConnector(context, **connector) notify.emit_start_notification(context, new_connector, 'create', node_uuid=node.uuid) with notify.handle_error_notification(context, new_connector, 'create', node_uuid=node.uuid): new_connector.create() notify.emit_end_notification(context, new_connector, 'create', node_uuid=node.uuid) # Set the HTTP Location Header api.response.location = link.build_url('volume/connectors', new_connector.uuid) return convert_with_links(new_connector) @METRICS.timer('VolumeConnectorsController.patch') @method.expose() @method.body('patch') @args.validate(connector_uuid=args.uuid, patch=args.patch) def patch(self, connector_uuid, patch): """Update an existing volume connector. :param connector_uuid: UUID of a volume connector. :param patch: a json PATCH document to apply to this volume connector. :returns: API-serializable volume connector object. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: PatchError if a given patch can not be applied. :raises: VolumeConnectorNotFound if no volume connector exists with the specified UUID. :raises: InvalidParameterValue if the volume connector's UUID is being changed :raises: NodeLocked if node is locked by another conductor :raises: NodeNotFound if the node associated with the connector does not exist :raises: VolumeConnectorTypeAndIdAlreadyExists if another connector already exists with the same values for type and connector_id fields :raises: InvalidUUID if invalid node UUID is passed in the patch. :raises: InvalidStateRequested If a node associated with the volume connector is not powered off. """ context = api.request.context api_utils.check_policy('baremetal:volume:update') if self.parent_node_ident: raise exception.OperationNotPermitted() api_utils.patch_validate_allowed_fields(patch, PATCH_ALLOWED_FIELDS) for value in api_utils.get_patch_values(patch, '/node_uuid'): if not uuidutils.is_uuid_like(value): message = _("Expected a UUID for node_uuid, but received " "%(uuid)s.") % {'uuid': str(value)} raise exception.InvalidUUID(message=message) rpc_connector = objects.VolumeConnector.get_by_uuid(context, connector_uuid) connector_dict = rpc_connector.as_dict() # NOTE(smoriya): # 1) Remove node_id because it's an internal value and # not present in the API object # 2) Add node_uuid rpc_node = api_utils.replace_node_id_with_uuid(connector_dict) connector_dict = api_utils.apply_jsonpatch(connector_dict, patch) try: if connector_dict['node_uuid'] != rpc_node.uuid: rpc_node = objects.Node.get( api.request.context, connector_dict['node_uuid']) except exception.NodeNotFound as e: # Change error code because 404 (NotFound) is inappropriate # response for a PATCH request to change a Port e.code = http_client.BAD_REQUEST # BadRequest raise api_utils.patched_validate_with_schema( connector_dict, CONNECTOR_SCHEMA, CONNECTOR_VALIDATOR) api_utils.patch_update_changed_fields( connector_dict, rpc_connector, fields=objects.VolumeConnector.fields, schema=CONNECTOR_SCHEMA, id_map={'node_id': rpc_node.id} ) notify.emit_start_notification(context, rpc_connector, 'update', node_uuid=rpc_node.uuid) with notify.handle_error_notification(context, rpc_connector, 'update', node_uuid=rpc_node.uuid): topic = api.request.rpcapi.get_topic_for(rpc_node) new_connector = api.request.rpcapi.update_volume_connector( context, rpc_connector, topic) api_connector = convert_with_links(new_connector) notify.emit_end_notification(context, new_connector, 'update', node_uuid=rpc_node.uuid) return api_connector @METRICS.timer('VolumeConnectorsController.delete') @method.expose(status_code=http_client.NO_CONTENT) @args.validate(connector_uuid=args.uuid) def delete(self, connector_uuid): """Delete a volume connector. :param connector_uuid: UUID of a volume connector. :raises: OperationNotPermitted if accessed with specifying a parent node. :raises: NodeLocked if node is locked by another conductor :raises: NodeNotFound if the node associated with the connector does not exist :raises: VolumeConnectorNotFound if the volume connector cannot be found :raises: InvalidStateRequested If a node associated with the volume connector is not powered off. """ context = api.request.context api_utils.check_policy('baremetal:volume:delete') if self.parent_node_ident: raise exception.OperationNotPermitted() rpc_connector = objects.VolumeConnector.get_by_uuid(context, connector_uuid) rpc_node = objects.Node.get_by_id(context, rpc_connector.node_id) notify.emit_start_notification(context, rpc_connector, 'delete', node_uuid=rpc_node.uuid) with notify.handle_error_notification(context, rpc_connector, 'delete', node_uuid=rpc_node.uuid): topic = api.request.rpcapi.get_topic_for(rpc_node) api.request.rpcapi.destroy_volume_connector(context, rpc_connector, topic) notify.emit_end_notification(context, rpc_connector, 'delete', node_uuid=rpc_node.uuid)
[ 2, 15069, 357, 66, 8, 2177, 7286, 14299, 11, 12052, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 28...
2.307394
5,667
import requests from bs4 import BeautifulSoup SEARCH_URL = "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=" CVE_URL = "https://cve.mitre.org/cgi-bin/cvename.cgi?name="
[ 11748, 7007, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 5188, 31315, 62, 21886, 796, 366, 5450, 1378, 66, 303, 13, 2781, 260, 13, 2398, 14, 37157, 12, 8800, 14, 66, 303, 2539, 13, 37157, 30, 2539, 4775, 2625, 198, 31436, ...
2.463768
69
#!/usr/bin/python # Classification (U) """Program: run_program.py Description: Unit testing of run_program in mongo_perf.py. Usage: test/unit/mongo_perf/run_program.py Arguments: """ # Libraries and Global Variables # Standard import sys import os if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest # Third-party import mock # Local sys.path.append(os.getcwd()) import mongo_perf import lib.gen_libs as gen_libs import version __version__ = version.__version__ def mongo_stat(server, args_array, **kwargs): """Method: mongo_stat Description: Function stub holder for mongo_perf.mongo_stat. Arguments: (input) server (input) args_array (input) **kwargs class_cfg """ status = True if server and args_array and kwargs.get("class_cfg", True): status = True return status class Server(object): """Class: Server Description: Class stub holder for mongo_class.Server class. Methods: __init__ """ def __init__(self): """Method: __init__ Description: Class initialization. Arguments: """ self.status = True self.err_msg = None def connect(self): """Method: connect Description: Stub method holder for mongo_class.Server.connect. Arguments: """ return self.status, self.err_msg class CfgTest(object): """Class: CfgTest Description: Class which is a representation of a cfg module. Methods: __init__ """ def __init__(self): """Method: __init__ Description: Initialization instance of the CfgTest class. Arguments: """ self.name = "Mongo" self.user = "mongo" self.japd = None self.host = "hostname" self.port = 27017 self.auth = True self.auth_db = "admin" self.use_arg = True self.use_uri = False self.repset = None self.repset_hosts = None class CfgTest2(object): """Class: CfgTest2 Description: Class which is a representation of a cfg module. Methods: __init__ """ def __init__(self): """Method: __init__ Description: Initialization instance of the CfgTest class. Arguments: """ self.name = "Mongo" self.user = "mongo" self.japd = None self.host = "hostname" self.port = 27017 self.auth = True self.auth_db = "admin" self.use_arg = True self.use_uri = False self.repset = None self.repset_hosts = None self.auth_mech = "SCRAM-SHA-1" class UnitTest(unittest.TestCase): """Class: UnitTest Description: Class which is a representation of a unit testing. Methods: setUp test_rep_arg test_no_rep_arg test_conn_fail_suppress test_connection_fail test_connection_success test_auth_mech test_no_auth_mech test_replica_set test_mongo test_run_program """ def setUp(self): """Function: setUp Description: Initialization for unit testing. Arguments: """ self.cfg = CfgTest() self.cfg2 = CfgTest2() self.server = Server() self.func_dict = {"-S": mongo_stat} self.args_array = {"-m": True, "-d": True, "-c": True, "-S": True} self.args_array2 = {"-m": True, "-d": True, "-c": True, "-S": True, "-e": "ToEmail", "-s": "SubjectLine"} self.args_array3 = {"-d": True, "-c": True, "-S": True} self.args_array4 = {"-w": True, "-d": True, "-c": True, "-S": True} self.repset_list = ["host1:27017", "host2:27017"] self.req_arg_list = ["--authenticationDatabase="] @mock.patch("mongo_perf.mongo_libs.disconnect") @mock.patch("mongo_perf.gen_libs.load_module") @mock.patch("mongo_perf.mongo_class.RepSet") def test_rep_arg(self, mock_inst, mock_cfg, mock_disconn): """Function: test_rep_arg Description: Test with passing rep_arg argument. Arguments: """ self.cfg2.repset = "replicasetname" self.cfg2.repset_hosts = self.repset_list mock_inst.return_value = self.server mock_cfg.side_effect = [self.cfg2, self.cfg2] mock_disconn.return_value = True self.assertFalse( mongo_perf.run_program( self.args_array, self.func_dict, req_arg=self.req_arg_list)) @mock.patch("mongo_perf.mongo_libs.disconnect") @mock.patch("mongo_perf.gen_libs.load_module") @mock.patch("mongo_perf.mongo_class.RepSet") def test_no_rep_arg(self, mock_inst, mock_cfg, mock_disconn): """Function: test_no_rep_arg Description: Test with not passing rep_arg argument. Arguments: """ self.cfg2.repset = "replicasetname" self.cfg2.repset_hosts = self.repset_list mock_inst.return_value = self.server mock_cfg.side_effect = [self.cfg2, self.cfg2] mock_disconn.return_value = True self.assertFalse(mongo_perf.run_program(self.args_array, self.func_dict)) @mock.patch("mongo_perf.mongo_libs.disconnect") @mock.patch("mongo_perf.gen_libs.load_module") @mock.patch("mongo_perf.mongo_libs.create_instance") def test_conn_fail_suppress(self, mock_inst, mock_cfg, mock_disconn): """Function: test_conn_fail_suppress Description: Test with failed connection with suppression. Arguments: """ self.server.status = False self.server.err_msg = "Error Connection Message" mock_inst.return_value = self.server mock_cfg.side_effect = [self.cfg, True] mock_disconn.return_value = True self.assertFalse(mongo_perf.run_program(self.args_array4, self.func_dict)) @mock.patch("mongo_perf.mongo_libs.disconnect") @mock.patch("mongo_perf.gen_libs.load_module") @mock.patch("mongo_perf.mongo_libs.create_instance") def test_connection_fail(self, mock_inst, mock_cfg, mock_disconn): """Function: test_connection_fail Description: Test with failed connection. Arguments: """ self.server.status = False self.server.err_msg = "Error Connection Message" mock_inst.return_value = self.server mock_cfg.side_effect = [self.cfg, True] mock_disconn.return_value = True with gen_libs.no_std_out(): self.assertFalse(mongo_perf.run_program(self.args_array, self.func_dict)) @mock.patch("mongo_perf.mongo_libs.disconnect") @mock.patch("mongo_perf.gen_libs.load_module") @mock.patch("mongo_perf.mongo_libs.create_instance") def test_connection_success(self, mock_inst, mock_cfg, mock_disconn): """Function: test_connection_success Description: Test with successful connection. Arguments: """ mock_inst.return_value = self.server mock_cfg.side_effect = [self.cfg, True] mock_disconn.return_value = True self.assertFalse(mongo_perf.run_program(self.args_array, self.func_dict)) @mock.patch("mongo_perf.mongo_libs.disconnect") @mock.patch("mongo_perf.gen_libs.load_module") @mock.patch("mongo_perf.mongo_class.RepSet") def test_auth_mech(self, mock_inst, mock_cfg, mock_disconn): """Function: test_auth_mech Description: Test with authorization mechanism setting. Arguments: """ self.cfg2.repset = "replicasetname" self.cfg2.repset_hosts = self.repset_list mock_inst.return_value = self.server mock_cfg.side_effect = [self.cfg2, self.cfg2] mock_disconn.return_value = True self.assertFalse(mongo_perf.run_program(self.args_array, self.func_dict)) @mock.patch("mongo_perf.mongo_libs.disconnect") @mock.patch("mongo_perf.gen_libs.load_module") @mock.patch("mongo_perf.mongo_class.RepSet") def test_no_auth_mech(self, mock_inst, mock_cfg, mock_disconn): """Function: test_no_auth_mech Description: Test with no authorization mechanism setting. Arguments: """ self.cfg.repset = "replicasetname" self.cfg.repset_hosts = self.repset_list mock_inst.return_value = self.server mock_cfg.side_effect = [self.cfg, True] mock_disconn.return_value = True self.assertFalse(mongo_perf.run_program(self.args_array, self.func_dict)) @mock.patch("mongo_perf.mongo_libs.disconnect") @mock.patch("mongo_perf.gen_libs.load_module") @mock.patch("mongo_perf.mongo_class.RepSet") def test_replica_set(self, mock_inst, mock_cfg, mock_disconn): """Function: test_replica_set Description: Test connecting to Mongo replica set. Arguments: """ self.cfg.repset = "replicasetname" self.cfg.repset_hosts = self.repset_list mock_inst.return_value = self.server mock_cfg.side_effect = [self.cfg, True] mock_disconn.return_value = True self.assertFalse(mongo_perf.run_program(self.args_array, self.func_dict)) @mock.patch("mongo_perf.mongo_libs.disconnect") @mock.patch("mongo_perf.gen_libs.load_module") @mock.patch("mongo_perf.mongo_libs.create_instance") def test_mongo(self, mock_inst, mock_cfg, mock_disconn): """Function: test_mongo Description: Test with mongo option. Arguments: """ mock_inst.return_value = self.server mock_cfg.side_effect = [self.cfg, True] mock_disconn.return_value = True self.assertFalse(mongo_perf.run_program(self.args_array, self.func_dict)) @mock.patch("mongo_perf.gen_libs.load_module") @mock.patch("mongo_perf.mongo_libs.disconnect") @mock.patch("mongo_perf.mongo_libs.create_instance") def test_run_program(self, mock_inst, mock_disconn, mock_cfg): """Function: test_run_program Description: Test run_program function. Arguments: """ mock_inst.return_value = self.server mock_disconn.return_value = True mock_cfg.return_value = self.cfg self.assertFalse(mongo_perf.run_program(self.args_array3, self.func_dict)) if __name__ == "__main__": unittest.main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 40984, 357, 52, 8, 198, 198, 37811, 15167, 25, 220, 1057, 62, 23065, 13, 9078, 628, 220, 220, 220, 12489, 25, 220, 11801, 4856, 286, 1057, 62, 23065, 287, 285, 25162, 62, 525, 69, 13, ...
2.122211
5,155
""" CBAM-ResNet for ImageNet-1K, implemented in Chainer. Original paper: 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. """ __all__ = ['CbamResNet', 'cbam_resnet18', 'cbam_resnet34', 'cbam_resnet50', 'cbam_resnet101', 'cbam_resnet152'] import os import chainer.functions as F import chainer.links as L from chainer import Chain from functools import partial from chainer.serializers import load_npz from .common import SimpleSequential, conv1x1_block, conv7x7_block from .resnet import ResInitBlock, ResBlock, ResBottleneck class MLP(Chain): """ Multilayer perceptron block. Parameters: ---------- channels : int Number of input/output channels. reduction_ratio : int, default 16 Channel reduction ratio. """ class ChannelGate(Chain): """ CBAM channel gate block. Parameters: ---------- channels : int Number of input/output channels. reduction_ratio : int, default 16 Channel reduction ratio. """ class SpatialGate(Chain): """ CBAM spatial gate block. """ class CbamBlock(Chain): """ CBAM attention block for CBAM-ResNet. Parameters: ---------- channels : int Number of input/output channels. reduction_ratio : int, default 16 Channel reduction ratio. """ class CbamResUnit(Chain): """ CBAM-ResNet unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Stride of the convolution. bottleneck : bool Whether to use a bottleneck or simple block in units. """ class CbamResNet(Chain): """ CBAM-ResNet model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- channels : list of list of int Number of output channels for each unit. init_block_channels : int Number of output channels for the initial unit. bottleneck : bool Whether to use a bottleneck or simple block in units. in_channels : int, default 3 Number of input channels. in_size : tuple of two ints, default (224, 224) Spatial size of the expected input image. classes : int, default 1000 Number of classification classes. """ def get_resnet(blocks, model_name=None, pretrained=False, root=os.path.join("~", ".chainer", "models"), **kwargs): """ Create CBAM-ResNet model with specific parameters. Parameters: ---------- blocks : int Number of blocks. conv1_stride : bool Whether to use stride in the first or the second convolution layer in units. use_se : bool Whether to use SE block. width_scale : float Scale factor for width of layers. model_name : str or None, default None Model name for loading pretrained model. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ if blocks == 18: layers = [2, 2, 2, 2] elif blocks == 34: layers = [3, 4, 6, 3] elif blocks == 50: layers = [3, 4, 6, 3] elif blocks == 101: layers = [3, 4, 23, 3] elif blocks == 152: layers = [3, 8, 36, 3] else: raise ValueError("Unsupported CBAM-ResNet with number of blocks: {}".format(blocks)) init_block_channels = 64 if blocks < 50: channels_per_layers = [64, 128, 256, 512] bottleneck = False else: channels_per_layers = [256, 512, 1024, 2048] bottleneck = True channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] net = CbamResNet( channels=channels, init_block_channels=init_block_channels, bottleneck=bottleneck, **kwargs) if pretrained: if (model_name is None) or (not model_name): raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.") from .model_store import get_model_file load_npz( file=get_model_file( model_name=model_name, local_model_store_dir_path=root), obj=net) return net def cbam_resnet18(**kwargs): """ CBAM-ResNet-18 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_resnet(blocks=18, model_name="cbam_resnet18", **kwargs) def cbam_resnet34(**kwargs): """ CBAM-ResNet-34 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_resnet(blocks=34, model_name="cbam_resnet34", **kwargs) def cbam_resnet50(**kwargs): """ CBAM-ResNet-50 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_resnet(blocks=50, model_name="cbam_resnet50", **kwargs) def cbam_resnet101(**kwargs): """ CBAM-ResNet-101 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_resnet(blocks=101, model_name="cbam_resnet101", **kwargs) def cbam_resnet152(**kwargs): """ CBAM-ResNet-152 model from 'CBAM: Convolutional Block Attention Module,' https://arxiv.org/abs/1807.06521. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' Location for keeping the model parameters. """ return get_resnet(blocks=152, model_name="cbam_resnet152", **kwargs) if __name__ == "__main__": _test()
[ 37811, 198, 220, 220, 220, 10078, 2390, 12, 4965, 7934, 329, 7412, 7934, 12, 16, 42, 11, 9177, 287, 609, 10613, 13, 198, 220, 220, 220, 13745, 3348, 25, 705, 23199, 2390, 25, 34872, 2122, 282, 9726, 47406, 19937, 4032, 3740, 1378, 2...
2.562713
2,639
from . import cpu from . import gpu
[ 6738, 764, 1330, 42804, 198, 6738, 764, 1330, 308, 19944 ]
3.5
10
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import httpretty import json import uuid from collections import Mapping from faker import Faker from tests.test_api.utils import TestBaseApi from polyaxon_client.api.base import BaseApiHandler from polyaxon_client.api.bookmark import BookmarkApi from polyaxon_client.schemas import ( ExperimentConfig, ExperimentGroupConfig, JobConfig, ProjectConfig ) faker = Faker()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 11748, 2638, 16100, 198, 11748, 33918, 198, 11748, 334, 27112, 198, 198, 6738, 17...
3.096774
155
import tensorflow as tf import os os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' os.environ['CUDA_VISIBLE_DEVICES'] = '0' print('physical devices:', str(tf.config.experimental.list_physical_devices()))
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 28686, 198, 198, 418, 13, 268, 2268, 17816, 43633, 5631, 62, 7206, 27389, 62, 12532, 1137, 20520, 796, 705, 5662, 40, 62, 45346, 62, 2389, 6, 198, 418, 13, 268, 2268, 17816, 43633, 563...
2.636364
77
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2021, Cisco Systems # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) DOCUMENTATION = r""" --- module: trigger_image_activation short_description: Manage TriggerImageActivation objects of SoftwareImageManagementSwim description: - Activates a software image on a given device. Software image must be present in the device flash. version_added: '1.0.0' author: Rafael Campos (@racampos) options: schedule_validate: description: - ScheduleValidate, validates data before schedule (Optional). type: bool payload: description: - An object to send in the Request body. type: list required: True elements: dict suboptions: activateLowerImageVersion: description: - It is the trigger image activation's activateLowerImageVersion. type: bool deviceUpgradeMode: description: - It is the trigger image activation's deviceUpgradeMode. type: str deviceUuid: description: - It is the trigger image activation's deviceUuid. type: str distributeIfNeeded: description: - It is the trigger image activation's distributeIfNeeded. type: bool imageUuidList: description: - It is the trigger image activation's imageUuidList. type: list smuImageUuidList: description: - It is the trigger image activation's smuImageUuidList. type: list requirements: - dnacentersdk seealso: # Reference by module name - module: cisco.dnac.plugins.module_utils.definitions.trigger_image_activation # Reference by Internet resource - name: TriggerImageActivation reference description: Complete reference of the TriggerImageActivation object model. link: https://developer.cisco.com/docs/dna-center/api/1-3-3-x # Reference by Internet resource - name: TriggerImageActivation reference description: SDK reference. link: https://dnacentersdk.readthedocs.io/en/latest/api/api.html#v2-1-1-summary """ EXAMPLES = r""" - name: trigger_software_image_activation cisco.dnac.trigger_image_activation: state: create # required payload: # required - activateLowerImageVersion: True # boolean deviceUpgradeMode: SomeValue # string deviceUuid: SomeValue # string distributeIfNeeded: True # boolean imageUuidList: - SomeValue # string smuImageUuidList: - SomeValue # string schedule_validate: True # boolean """ RETURN = r""" dnac_response: description: A dictionary with the response returned by the DNA Center Python SDK returned: always type: dict sample: {"response": 29, "version": "1.0"} sdk_function: description: The DNA Center SDK function used to execute the task returned: always type: str sample: software_image_management_swim.trigger_software_image_activation missing_params: description: Provided arguments do not comply with the schema of the DNA Center Python SDK function returned: when the function request schema is not satisfied type: list sample: """
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 15069, 25, 357, 66, 8, 33448, 11, 28289, 11998, 198, 2, 22961, 3611, 5094, 13789, 410, 18, 13, 15, 10, 357, 3826, ...
2.96516
1,062