diff --git "a/5353.jsonl" "b/5353.jsonl" new file mode 100644--- /dev/null +++ "b/5353.jsonl" @@ -0,0 +1,651 @@ +{"seq_id":"369989495","text":"from datetime import datetime, timedelta, timezone\r\nfrom functools import reduce\r\nfrom typing import List\r\n\r\nimport freqtrade.vendor.qtpylib.indicators as qtpylib\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pandas_ta as pta\r\nimport talib.abstract as ta\r\nimport technical.indicators as ftt\r\nfrom freqtrade.persistence import Trade, PairLocks\r\nfrom freqtrade.strategy import (BooleanParameter, DecimalParameter,\r\n IntParameter, merge_informative_pair)\r\nfrom freqtrade.strategy.interface import IStrategy\r\nfrom pandas import DataFrame, Series\r\nfrom skopt.space import Dimension, Integer\r\nfrom py3cw.request import Py3CW\r\n\r\n\r\ndef bollinger_bands(stock_price, window_size, num_of_std):\r\n rolling_mean = stock_price.rolling(window=window_size).mean()\r\n rolling_std = stock_price.rolling(window=window_size).std()\r\n lower_band = rolling_mean - (rolling_std * num_of_std)\r\n return np.nan_to_num(rolling_mean), np.nan_to_num(lower_band)\r\n\r\ndef ha_typical_price(bars):\r\n res = (bars['ha_high'] + bars['ha_low'] + bars['ha_close']) / 3.\r\n return Series(index=bars.index, data=res)\r\n\r\nclass ClucHAnix_BB_RPB(IStrategy):\r\n\r\n class HyperOpt:\r\n @staticmethod\r\n def generate_roi_table(params: dict):\r\n \"\"\"\r\n Generate the ROI table that will be used by Hyperopt\r\n This implementation generates the default legacy Freqtrade ROI tables.\r\n Change it if you need different number of steps in the generated\r\n ROI tables or other structure of the ROI tables.\r\n Please keep it aligned with parameters in the 'roi' optimization\r\n hyperspace defined by the roi_space method.\r\n \"\"\"\r\n roi_table = {}\r\n roi_table[0] = 0.05\r\n roi_table[params['roi_t6']] = 0.04\r\n roi_table[params['roi_t5']] = 0.03\r\n roi_table[params['roi_t4']] = 0.02\r\n roi_table[params['roi_t3']] = 0.01\r\n roi_table[params['roi_t2']] = 0.0001\r\n roi_table[params['roi_t1']] = -10\r\n\r\n return roi_table\r\n\r\n @staticmethod\r\n def roi_space() -> List[Dimension]:\r\n \"\"\"\r\n Values to search for each ROI steps\r\n Override it if you need some different ranges for the parameters in the\r\n 'roi' optimization hyperspace.\r\n Please keep it aligned with the implementation of the\r\n generate_roi_table method.\r\n \"\"\"\r\n return [\r\n Integer(240, 720, name='roi_t1'),\r\n Integer(120, 240, name='roi_t2'),\r\n Integer(90, 120, name='roi_t3'),\r\n Integer(60, 90, name='roi_t4'),\r\n Integer(30, 60, name='roi_t5'),\r\n Integer(1, 30, name='roi_t6'),\r\n ]\r\n\r\n # Buy hyperspace params:\r\n buy_params = {\r\n \"buy_btc_safe_1d\": -0.05,\r\n \"antipump_threshold\": 0.25,\r\n \"clucha_bbdelta_close\": 0.02206,\r\n \"clucha_bbdelta_tail\": 1.02515,\r\n \"clucha_close_bblower\": 0.03669,\r\n \"clucha_closedelta_close\": 0.04401,\r\n \"clucha_enabled\": True,\r\n \"clucha_rocr_1h\": 0.47782,\r\n \"cofi_adx\": 45,\r\n \"cofi_ema\": 1.329,\r\n \"cofi_enabled\": True,\r\n \"cofi_ewo_high\": 1.768,\r\n \"cofi_fastd\": 18,\r\n \"cofi_fastk\": 25,\r\n \"ewo_1_enabled\": False,\r\n \"ewo_1_rsi_14\": 55,\r\n \"ewo_1_rsi_4\": 12,\r\n \"ewo_candles_buy\": 29,\r\n \"ewo_candles_sell\": 15,\r\n \"ewo_high\": 2.119,\r\n \"ewo_high_offset\": 1.26902,\r\n \"ewo_low\": -16.218,\r\n \"ewo_low_enabled\": False,\r\n \"ewo_low_offset\": 0.99959,\r\n \"ewo_low_rsi_4\": 15,\r\n \"lambo1_ema_14_factor\": 0.981,\r\n \"lambo1_enabled\": True,\r\n \"lambo1_rsi_14_limit\": 52,\r\n \"lambo1_rsi_4_limit\": 37,\r\n \"lambo2_ema_14_factor\": 0.844,\r\n \"lambo2_enabled\": False,\r\n \"lambo2_rsi_14_limit\": 37,\r\n \"lambo2_rsi_4_limit\": 60,\r\n \"local_trend_bb_factor\": 1.03,\r\n \"local_trend_closedelta\": 25.831,\r\n \"local_trend_ema_diff\": 0.047,\r\n \"local_trend_enabled\": False,\r\n \"nfi32_cti_limit\": -0.27048,\r\n \"nfi32_enabled\": True,\r\n \"nfi32_rsi_14\": 75,\r\n \"nfi32_rsi_4\": 84,\r\n \"nfi32_sma_factor\": 0.7871,\r\n }\r\n\r\n # ROI table:\r\n minimal_roi = {\r\n \"0\": 0.05,\r\n \"15\": 0.04,\r\n \"51\": 0.03,\r\n \"81\": 0.02,\r\n \"112\": 0.01,\r\n \"154\": 0.0001,\r\n \"200\": -10\r\n }\r\n\r\n # Stoploss:\r\n stoploss = -0.99 # use custom stoploss\r\n\r\n # Trailing stop:\r\n trailing_stop = False\r\n trailing_stop_positive = 0.3207\r\n trailing_stop_positive_offset = 0.3849\r\n trailing_only_offset_is_reached = False\r\n\r\n \"\"\"\r\n END HYPEROPT\r\n \"\"\"\r\n\r\n timeframe = '1m'\r\n\r\n # Make sure these match or are not overridden in config\r\n use_sell_signal = False\r\n sell_profit_only = False\r\n ignore_roi_if_buy_signal = False\r\n\r\n # Custom stoploss\r\n use_custom_stoploss = True\r\n\r\n process_only_new_candles = True\r\n startup_candle_count = 200\r\n\r\n order_types = {\r\n 'buy': 'market',\r\n 'sell': 'market',\r\n 'emergencysell': 'market',\r\n 'forcebuy': \"market\",\r\n 'forcesell': 'market',\r\n 'stoploss': 'market',\r\n 'stoploss_on_exchange': False,\r\n\r\n 'stoploss_on_exchange_interval': 60,\r\n 'stoploss_on_exchange_limit_ratio': 0.99\r\n }\r\n\r\n # ClucHA\r\n clucha_bbdelta_close = DecimalParameter(0.01,0.05, default=buy_params['clucha_bbdelta_close'], decimals=5, space='buy', optimize=True)\r\n clucha_bbdelta_tail = DecimalParameter(0.7, 1.2, default=buy_params['clucha_bbdelta_tail'], decimals=5, space='buy', optimize=True)\r\n clucha_close_bblower = DecimalParameter(0.001, 0.05, default=buy_params['clucha_close_bblower'], decimals=5, space='buy', optimize=True)\r\n clucha_closedelta_close = DecimalParameter(0.001, 0.05, default=buy_params['clucha_closedelta_close'], decimals=5, space='buy', optimize=True)\r\n clucha_rocr_1h = DecimalParameter(0.1, 1.0, default=buy_params['clucha_rocr_1h'], decimals=5, space='buy', optimize=True)\r\n\r\n # lambo1\r\n lambo1_ema_14_factor = DecimalParameter(0.8, 1.2, decimals=3, default=buy_params['lambo1_ema_14_factor'], space='buy', optimize=True)\r\n lambo1_rsi_4_limit = IntParameter(5, 60, default=buy_params['lambo1_rsi_4_limit'], space='buy', optimize=True)\r\n lambo1_rsi_14_limit = IntParameter(5, 60, default=buy_params['lambo1_rsi_14_limit'], space='buy', optimize=True)\r\n\r\n # lambo2\r\n lambo2_ema_14_factor = DecimalParameter(0.8, 1.2, decimals=3, default=buy_params['lambo2_ema_14_factor'], space='buy', optimize=True)\r\n lambo2_rsi_4_limit = IntParameter(5, 60, default=buy_params['lambo2_rsi_4_limit'], space='buy', optimize=True)\r\n lambo2_rsi_14_limit = IntParameter(5, 60, default=buy_params['lambo2_rsi_14_limit'], space='buy', optimize=True)\r\n\r\n # local_uptrend\r\n local_trend_ema_diff = DecimalParameter(0, 0.2, default=buy_params['local_trend_ema_diff'], space='buy', optimize=True)\r\n local_trend_bb_factor = DecimalParameter(0.8, 1.2, default=buy_params['local_trend_bb_factor'], space='buy', optimize=True)\r\n local_trend_closedelta = DecimalParameter(5.0, 30.0, default=buy_params['local_trend_closedelta'], space='buy', optimize=True)\r\n\r\n # ewo_1 and ewo_low\r\n ewo_candles_buy = IntParameter(2, 30, default=buy_params['ewo_candles_buy'], space='buy', optimize=True)\r\n ewo_candles_sell = IntParameter(2, 35, default=buy_params['ewo_candles_sell'], space='buy', optimize=True)\r\n ewo_low_offset = DecimalParameter(0.7, 1.2, default=buy_params['ewo_low_offset'], decimals=5, space='buy', optimize=True)\r\n ewo_high_offset = DecimalParameter(0.75, 1.5, default=buy_params['ewo_high_offset'], decimals=5, space='buy', optimize=True)\r\n ewo_high = DecimalParameter(2.0, 15.0, default=buy_params['ewo_high'], space='buy', optimize=True)\r\n ewo_1_rsi_14 = IntParameter(10, 100, default=buy_params['ewo_1_rsi_14'], space='buy', optimize=True)\r\n ewo_1_rsi_4 = IntParameter(1, 50, default=buy_params['ewo_1_rsi_4'], space='buy', optimize=True)\r\n ewo_low_rsi_4 = IntParameter(1, 50, default=buy_params['ewo_low_rsi_4'], space='buy', optimize=True)\r\n ewo_low = DecimalParameter(-20.0, -8.0, default=buy_params['ewo_low'], space='buy', optimize=True)\r\n\r\n # cofi\r\n cofi_ema = DecimalParameter(0.6, 1.4, default=buy_params['cofi_ema'] , space='buy', optimize=True)\r\n cofi_fastk = IntParameter(1, 100, default=buy_params['cofi_fastk'], space='buy', optimize=True)\r\n cofi_fastd = IntParameter(1, 100, default=buy_params['cofi_fastd'], space='buy', optimize=True)\r\n cofi_adx = IntParameter(1, 100, default=buy_params['cofi_adx'], space='buy', optimize=True)\r\n cofi_ewo_high = DecimalParameter(1.0, 15.0, default=buy_params['cofi_ewo_high'], space='buy', optimize=True)\r\n\r\n # nfi32\r\n nfi32_rsi_4 = IntParameter(1, 100, default=buy_params['nfi32_rsi_4'], space='buy', optimize=True)\r\n nfi32_rsi_14 = IntParameter(1, 100, default=buy_params['nfi32_rsi_4'], space='buy', optimize=True)\r\n nfi32_sma_factor = DecimalParameter(0.7, 1.2, default=buy_params['nfi32_sma_factor'], decimals=5, space='buy', optimize=True)\r\n nfi32_cti_limit = DecimalParameter(-1.2, 0, default=buy_params['nfi32_cti_limit'], decimals=5, space='buy', optimize=True)\r\n\r\n buy_btc_safe_1d = DecimalParameter(-0.5, -0.015, default=buy_params['buy_btc_safe_1d'], optimize=True)\r\n antipump_threshold = DecimalParameter(0, 0.4, default=buy_params['antipump_threshold'], space='buy', optimize=True)\r\n\r\n ewo_1_enabled = BooleanParameter(default=buy_params['ewo_1_enabled'], space='buy', optimize=True)\r\n ewo_low_enabled = BooleanParameter(default=buy_params['ewo_low_enabled'], space='buy', optimize=True)\r\n cofi_enabled = BooleanParameter(default=buy_params['cofi_enabled'], space='buy', optimize=True)\r\n lambo1_enabled = BooleanParameter(default=buy_params['lambo1_enabled'], space='buy', optimize=True)\r\n lambo2_enabled = BooleanParameter(default=buy_params['lambo2_enabled'], space='buy', optimize=True)\r\n local_trend_enabled = BooleanParameter(default=buy_params['local_trend_enabled'], space='buy', optimize=True)\r\n nfi32_enabled = BooleanParameter(default=buy_params['nfi32_enabled'], space='buy', optimize=True)\r\n clucha_enabled = BooleanParameter(default=buy_params['clucha_enabled'], space='buy', optimize=True)\r\n\r\n\r\n def informative_pairs(self):\r\n pairs = self.dp.current_whitelist()\r\n informative_pairs = [(pair, '1h') for pair in pairs]\r\n informative_pairs += [(\"BTC/USDT\", \"1m\")]\r\n informative_pairs += [(\"BTC/USDT\", \"1d\")]\r\n\r\n return informative_pairs\r\n\r\n\r\n ############################################################################\r\n\r\n def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,\r\n current_rate: float, current_profit: float, **kwargs) -> float:\r\n sl_new = 1\r\n\r\n if (current_profit > 0.2):\r\n sl_new = 0.05\r\n elif (current_profit > 0.1):\r\n sl_new = 0.03\r\n elif (current_profit > 0.06):\r\n sl_new = 0.02\r\n elif (current_profit > 0.03):\r\n sl_new = 0.015\r\n elif (current_profit > 0.015):\r\n sl_new = 0.0075\r\n\r\n return sl_new\r\n\r\n ############################################################################\r\n\r\n def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\r\n # Heikin Ashi Candles\r\n heikinashi = qtpylib.heikinashi(dataframe)\r\n dataframe['ha_open'] = heikinashi['open']\r\n dataframe['ha_close'] = heikinashi['close']\r\n dataframe['ha_high'] = heikinashi['high']\r\n dataframe['ha_low'] = heikinashi['low']\r\n\r\n dataframe['ema_8'] = ta.EMA(dataframe, timeperiod=8)\r\n dataframe['ema_14'] = ta.EMA(dataframe, timeperiod=14)\r\n dataframe['ema_26'] = ta.EMA(dataframe, timeperiod=26)\r\n dataframe['sma_15'] = ta.SMA(dataframe, timeperiod=15)\r\n dataframe['rsi_4'] = ta.RSI(dataframe, timeperiod=4)\r\n dataframe['rsi_14'] = ta.RSI(dataframe, timeperiod=14)\r\n dataframe['rsi_20'] = ta.RSI(dataframe, timeperiod=20)\r\n\r\n # CTI\r\n dataframe['cti'] = pta.cti(dataframe[\"close\"], length=20)\r\n\r\n # Cofi\r\n stoch_fast = ta.STOCHF(dataframe, 5, 3, 0, 3, 0)\r\n dataframe['fastd'] = stoch_fast['fastd']\r\n dataframe['fastk'] = stoch_fast['fastk']\r\n dataframe['adx'] = ta.ADX(dataframe)\r\n\r\n # Set Up Bollinger Bands\r\n mid, lower = bollinger_bands(ha_typical_price(dataframe), window_size=40, num_of_std=2)\r\n dataframe['lower'] = lower\r\n dataframe['mid'] = mid\r\n\r\n bollinger2 = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)\r\n dataframe['bb_lowerband2'] = bollinger2['lower']\r\n dataframe['bb_middleband2'] = bollinger2['mid']\r\n dataframe['bb_upperband2'] = bollinger2['upper']\r\n\r\n dataframe['closedelta'] = (dataframe['close'] - dataframe['close'].shift()).abs()\r\n\r\n\r\n # # ClucHA\r\n dataframe['bbdelta'] = (mid - dataframe['lower']).abs()\r\n dataframe['ha_closedelta'] = (dataframe['ha_close'] - dataframe['ha_close'].shift()).abs()\r\n dataframe['tail'] = (dataframe['ha_close'] - dataframe['ha_low']).abs()\r\n dataframe['bb_lowerband'] = dataframe['lower']\r\n\r\n dataframe['ema_slow'] = ta.EMA(dataframe['ha_close'], timeperiod=50)\r\n dataframe['rocr'] = ta.ROCR(dataframe['ha_close'], timeperiod=28)\r\n\r\n # Elliot\r\n dataframe['EWO'] = EWO(dataframe, 50, 200)\r\n\r\n\r\n inf_tf = '1h'\r\n\r\n informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=inf_tf)\r\n\r\n inf_heikinashi = qtpylib.heikinashi(informative)\r\n\r\n informative['ha_close'] = inf_heikinashi['close']\r\n informative['rocr'] = ta.ROCR(informative['ha_close'], timeperiod=168)\r\n\r\n\r\n dataframe = merge_informative_pair(dataframe, informative, self.timeframe, inf_tf, ffill=True)\r\n\r\n ### BTC protection\r\n dataframe['btc_1m']= self.dp.get_pair_dataframe('BTC/USDT', timeframe='1m')['close']\r\n btc_1d = self.dp.get_pair_dataframe('BTC/USDT', timeframe='1d')[['date', 'close']].rename(columns={\"close\": \"btc\"}).shift(1)\r\n dataframe = merge_informative_pair(dataframe, btc_1d, '1m', '1d', ffill=True)\r\n\r\n # Pump strength\r\n dataframe['zema_30'] = ftt.zema(dataframe, period=30)\r\n dataframe['zema_200'] = ftt.zema(dataframe, period=200)\r\n dataframe['pump_strength'] = (dataframe['zema_30'] - dataframe['zema_200']) / dataframe['zema_30']\r\n\r\n return dataframe\r\n\r\n def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\r\n conditions = []\r\n dataframe.loc[:, 'buy_tag'] = ''\r\n\r\n dataframe[f'ma_buy_{self.ewo_candles_buy.value}'] = ta.EMA(dataframe, timeperiod=int(self.ewo_candles_buy.value))\r\n dataframe[f'ma_sell_{self.ewo_candles_sell.value}'] = ta.EMA(dataframe, timeperiod=int(self.ewo_candles_sell.value))\r\n\r\n is_btc_safe = (\r\n (pct_change(dataframe['btc_1d'], dataframe['btc_1m']).fillna(0) > self.buy_btc_safe_1d.value) &\r\n (dataframe['volume'] > 0) # Make sure Volume is not 0\r\n )\r\n\r\n is_pump_safe = (\r\n (dataframe['pump_strength'] < self.antipump_threshold.value)\r\n )\r\n\r\n lambo1 = (\r\n bool(self.lambo1_enabled.value) &\r\n (dataframe['close'] < (dataframe['ema_14'] * self.lambo1_ema_14_factor.value)) &\r\n (dataframe['rsi_4'] < int(self.lambo1_rsi_4_limit.value)) &\r\n (dataframe['rsi_14'] < int(self.lambo1_rsi_14_limit.value))\r\n )\r\n dataframe.loc[lambo1, 'buy_tag'] += 'lambo1_'\r\n conditions.append(lambo1)\r\n\r\n lambo2 = (\r\n bool(self.lambo2_enabled.value) &\r\n (dataframe['close'] < (dataframe['ema_14'] * self.lambo2_ema_14_factor.value)) &\r\n (dataframe['rsi_4'] < int(self.lambo2_rsi_4_limit.value)) &\r\n (dataframe['rsi_14'] < int(self.lambo2_rsi_14_limit.value))\r\n )\r\n dataframe.loc[lambo2, 'buy_tag'] += 'lambo2_'\r\n conditions.append(lambo2)\r\n\r\n local_uptrend = (\r\n bool(self.local_trend_enabled.value) &\r\n (dataframe['ema_26'] > dataframe['ema_14']) &\r\n (dataframe['ema_26'] - dataframe['ema_14'] > dataframe['open'] * self.local_trend_ema_diff.value) &\r\n (dataframe['ema_26'].shift() - dataframe['ema_14'].shift() > dataframe['open'] / 100) &\r\n (dataframe['close'] < dataframe['bb_lowerband2'] * self.local_trend_bb_factor.value) &\r\n (dataframe['closedelta'] > dataframe['close'] * self.local_trend_closedelta.value / 1000 )\r\n )\r\n dataframe.loc[local_uptrend, 'buy_tag'] += 'local_uptrend_'\r\n conditions.append(local_uptrend)\r\n\r\n nfi_32 = (\r\n bool(self.nfi32_enabled.value) &\r\n (dataframe['rsi_20'] < dataframe['rsi_20'].shift(1)) &\r\n (dataframe['rsi_4'] < self.nfi32_rsi_4.value) &\r\n (dataframe['rsi_14'] > self.nfi32_rsi_14.value) &\r\n (dataframe['close'] < dataframe['sma_15'] * self.nfi32_sma_factor.value) &\r\n (dataframe['cti'] < self.nfi32_cti_limit.value)\r\n )\r\n dataframe.loc[nfi_32, 'buy_tag'] += 'nfi_32_'\r\n conditions.append(nfi_32)\r\n\r\n ewo_1 = (\r\n bool(self.ewo_1_enabled.value) &\r\n (dataframe['rsi_4'] < self.ewo_1_rsi_4.value) &\r\n (dataframe['close'] < (dataframe[f'ma_buy_{self.ewo_candles_buy.value}'] * self.ewo_low_offset.value)) &\r\n (dataframe['EWO'] > self.ewo_high.value) &\r\n (dataframe['rsi_14'] < self.ewo_1_rsi_14.value) &\r\n (dataframe['close'] < (dataframe[f'ma_sell_{self.ewo_candles_sell.value}'] * self.ewo_high_offset.value))\r\n )\r\n dataframe.loc[ewo_1, 'buy_tag'] += 'ewo1_'\r\n conditions.append(ewo_1)\r\n\r\n ewo_low = (\r\n bool(self.ewo_low_enabled.value) &\r\n (dataframe['rsi_4'] < self.ewo_low_rsi_4.value) &\r\n (dataframe['close'] < (dataframe[f'ma_buy_{self.ewo_candles_buy.value}'] * self.ewo_low_offset.value)) &\r\n (dataframe['EWO'] < self.ewo_low.value) &\r\n (dataframe['close'] < (dataframe[f'ma_sell_{self.ewo_candles_sell.value}'] * self.ewo_high_offset.value))\r\n )\r\n dataframe.loc[ewo_low, 'buy_tag'] += 'ewo_low_'\r\n conditions.append(ewo_low)\r\n\r\n cofi = (\r\n bool(self.cofi_enabled.value) &\r\n (dataframe['open'] < dataframe['ema_8'] * self.cofi_ema.value) &\r\n (qtpylib.crossed_above(dataframe['fastk'], dataframe['fastd'])) &\r\n (dataframe['fastk'] < self.cofi_fastk.value) &\r\n (dataframe['fastd'] < self.cofi_fastd.value) &\r\n (dataframe['adx'] > self.cofi_adx.value) &\r\n (dataframe['EWO'] > self.cofi_ewo_high.value)\r\n )\r\n dataframe.loc[cofi, 'buy_tag'] += 'cofi_'\r\n conditions.append(cofi)\r\n\r\n clucHA = (\r\n bool(self.clucha_enabled.value) &\r\n (dataframe['rocr_1h'].gt(self.clucha_rocr_1h.value)) &\r\n ((\r\n (dataframe['lower'].shift().gt(0)) &\r\n (dataframe['bbdelta'].gt(dataframe['ha_close'] * self.clucha_bbdelta_close.value)) &\r\n (dataframe['ha_closedelta'].gt(dataframe['ha_close'] * self.clucha_closedelta_close.value)) &\r\n (dataframe['tail'].lt(dataframe['bbdelta'] * self.clucha_bbdelta_tail.value)) &\r\n (dataframe['ha_close'].lt(dataframe['lower'].shift())) &\r\n (dataframe['ha_close'].le(dataframe['ha_close'].shift()))\r\n ) |\r\n (\r\n (dataframe['ha_close'] < dataframe['ema_slow']) &\r\n (dataframe['ha_close'] < self.clucha_close_bblower.value * dataframe['bb_lowerband'])\r\n ))\r\n )\r\n dataframe.loc[clucHA, 'buy_tag'] += 'clucHA_'\r\n conditions.append(clucHA)\r\n\r\n dataframe.loc[\r\n # is_btc_safe & # broken?\r\n # is_pump_safe &\r\n reduce(lambda x, y: x | y, conditions),\r\n 'buy'\r\n ] = 1\r\n\r\n return dataframe\r\n\r\n def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\r\n\r\n # dataframe.loc[\r\n # (dataframe['fisher'] > self.sell_fisher.value) &\r\n # (dataframe['ha_high'].le(dataframe['ha_high'].shift(1))) &\r\n # (dataframe['ha_high'].shift(1).le(dataframe['ha_high'].shift(2))) &\r\n # (dataframe['ha_close'].le(dataframe['ha_close'].shift(1))) &\r\n # (dataframe['ema_fast'] > dataframe['ha_close']) &\r\n # ((dataframe['ha_close'] * self.sell_bbmiddle_close.value) > dataframe['bb_middleband']) &\r\n # (dataframe['volume'] > 0)\r\n # ,\r\n # 'sell'\r\n # ] = 1\r\n\r\n return dataframe\r\n\r\n def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,\r\n rate: float, time_in_force: str, sell_reason: str,\r\n current_time: datetime, **kwargs) -> bool:\r\n\r\n trade.sell_reason = sell_reason + \"_\" + trade.buy_tag\r\n\r\n return True\r\n\r\n # def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,\r\n # time_in_force: str, current_time: datetime, **kwargs) -> bool:\r\n # \"\"\"\r\n # Called right before placing a buy order.\r\n # Timing for this function is critical, so avoid doing heavy computations or\r\n # network requests in this method.\r\n\r\n # For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/\r\n\r\n # When not implemented by a strategy, returns True (always confirming).\r\n\r\n # :param pair: Pair that's about to be bought.\r\n # :param order_type: Order type (as configured in order_types). usually limit or market.\r\n # :param amount: Amount in target (quote) currency that's going to be traded.\r\n # :param rate: Rate that's going to be used when using limit orders\r\n # :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).\r\n # :param current_time: datetime object, containing the current datetime\r\n # :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.\r\n # :return bool: When True is returned, then the buy-order is placed on the exchange.\r\n # False aborts the process\r\n # \"\"\"\r\n # coin, currency = pair.split('/')\r\n\r\n # p3cw = Py3CW(\r\n # key='.....',\r\n # secret='......',\r\n # )\r\n\r\n # p3cw.request(\r\n # entity='bots',\r\n # action='start_new_deal',\r\n # action_id='123123',\r\n # payload={\r\n # \"bot_id\": 123123,\r\n # \"pair\": f\"{currency}_{coin}\",\r\n # },\r\n # )\r\n\r\n # PairLocks.lock_pair(\r\n # pair=pair,\r\n # until=datetime.now(timezone.utc) + timedelta(minutes=5),\r\n # reason=\"Send 3c buy order\"\r\n # )\r\n\r\n # return False\r\n\r\ndef pct_change(a, b):\r\n return (b - a) / a\r\n\r\ndef EWO(dataframe, ema_length=5, ema2_length=35):\r\n df = dataframe.copy()\r\n ema1 = ta.EMA(df, timeperiod=ema_length)\r\n ema2 = ta.EMA(df, timeperiod=ema2_length)\r\n emadif = (ema1 - ema2) / df['low'] * 100\r\n return emadif\r\n","sub_path":"ClucHAnix_BB_RPB.py","file_name":"ClucHAnix_BB_RPB.py","file_ext":"py","file_size_in_byte":23678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"283775066","text":"import unittest\n\nfrom cert_issuer.models import TransactionCosts\n\n\nclass TestModels(unittest.TestCase):\n def test_TransactionCosts_no_split(self):\n issuing_cost = TransactionCosts(10, 4000, 60000)\n self.assertEqual(60000, issuing_cost.total)\n\n def test_TransactionCosts_with_split(self):\n issuing_cost = TransactionCosts(10, 4000, 60000)\n issuing_cost.set_transfer_fee(10000)\n\n self.assertEqual(70000, issuing_cost.total)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"535685293","text":"from dask import delayed, compute\nimport dask.bag as db\nimport dask.array as da\n\nimport numpy as np\nimport math\nimport os\n\n\n@delayed\ndef distance(lat1, lon1, lat2, lon2):\n radius = 6371 # km\n\n dlat = math.radians(lat2-lat1)\n dlon = math.radians(lon2-lon1)\n a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \\\n * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))\n d = radius * c\n\n return d\n\n\ndef read_json():\n\n coordinates = db.read_text(\"\")\n\n print(coordinates.take(1))\n\n\n\n\nif __name__ == '__main__':\n print('main')\n print(os.getcwd())\n # read_json()\n ","sub_path":"Machine_Learning_Projects/Dask/.ipynb_checkpoints/Parallel_Processing-checkpoint.py","file_name":"Parallel_Processing-checkpoint.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"618490698","text":"__author__ = 'maximk'\n\nimport urllib.request\nfrom lxml import etree\n\nurl = 'http://www.sec.gov/Archives/edgar/data/1582676/000158267614000001/primary_doc.xml'\n# url = 'http://www.sec.gov/Archives/edgar/data/1444763/000144476312000001/primary_doc.xml'\nform_d_xml = urllib.request.urlopen(url).read().decode('utf-8')\nform_d = etree.XML(form_d_xml)\n\nsecurities = {'isEquityType': 8, 'isOptionToAcquireType': 4, 'isSecurityToBeAcquiredType': 2, 'isDebtType': 1}\nsold = ''\nsec_sum = 0\nfund_type = ''\ncompany_name = ''\n\nfor field in form_d:\n if field.tag == 'offeringData':\n for offer_field in field:\n if offer_field.tag == 'typesOfSecuritiesOffered':\n sec_sum = sum(securities[sec.tag] for sec in offer_field)\n elif offer_field.tag == 'offeringSalesAmounts':\n for amount in offer_field:\n if amount.tag == 'totalAmountSold':\n sold = amount.text\n elif field.tag == 'primaryIssuer':\n for issuer in field:\n if issuer.tag == 'entityName':\n company_name = issuer.text\n\nif not(sec_sum % 2) and (sec_sum >= 8):\n fund_type = 'Venture'\nelif (sec_sum % 2) and (sec_sum < 8):\n fund_type = 'Debt Financing'\n\nprint('Company Name: %s\\nFunding Type: %s\\nRaised: %s' % (company_name, fund_type, sold))","sub_path":"sec_gov.py","file_name":"sec_gov.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"494756190","text":"#in[1]\nimport numpy as np \nimport pandas as pd \nfrom keras.utils import np_utils \nnp.random.seed(10)\n#in[2]\nfrom keras.datasets import mnist\n#in[3]\n(x_train_image, y_train_label), \\\n(x_test_image, y_test_label) = mnist.load_data()\n#in[4]\nprint('train data=',len(x_train_image))\nprint(' test data=',len(x_test_image))\n#in[5]\nprint ('x_train_image:',x_train_image.shape)\nprint ('y_train_label:',y_train_label.shape)\n#in[6]\nimport matplotlib.pyplot as plt\ndef plot_image(image):\n\tfig = plt.gcf()\n\tfig.set_size_inches(2, 2)\n\tplt.imshow(image, cmap='binary')\n\tplt.show()\n#in[7]\n# plot_image(x_train_image[0]) # show image by pyplot\n#in[8]\nprint(y_train_label[0])\n#in[9]\nimport matplotlib.pyplot as plt\ndef plot_images_labels_prediction(images, labels, prediction, idx, num=10):\n\tfig = plt.gcf()\n\tfig.set_size_inches(12, 14)\n\tif num>25: num=25 \n\tfor i in range(0, num):\n\t\tax=plt.subplot(5,5, 1+i)\n\t\tax.imshow(images[idx], cmap='binary')\n\t\ttitle= \"label=\" +str(labels[idx])\n\t\tif len(prediction)>0:\n\t\t\ttitle+=\",predict=\"+str(prediction[idx]) \n\t\t\t\t\n\t\tax.set_title(title,fontsize=10) \n\t\tax.set_xticks([]);ax.set_yticks([]) \n\t\tidx+=1 \n\t\tplt.show()\n#in[10]\n# plot_images_labels_prediction(x_train_image,y_train_label,[],0,10)\n#in[11]\nprint ('x_test_image:',x_test_image.shape)\nprint ('y_test_label:',y_test_label.shape)\n#in[12]\n# plot_images_labels_prediction(x_test_image,y_test_label,[],0,10)\n#in[13]\nprint ('x_train_image:',x_train_image.shape)\nprint ('y_train_label:',y_train_label.shape)\n#in[14]\nx_Train =x_train_image.reshape(60000, 784).astype('float32')\nx_Test = x_test_image.reshape(10000, 784).astype('float32')\n#in[15]\nprint ('x_train:',x_Train.shape)\nprint ('x_test:',x_Test.shape)\n#in[16]\n# print(x_train_image[0])\n#in[17]\nx_Train_normalize = x_Train/ 255\nx_Test_normalize = x_Test/ 255\n#in[18]\n# print(x_Train_normalize[0])\n#in[19]\nprint(y_train_label[:5])\n#in[20]\ny_TrainOneHot = np_utils.to_categorical(y_train_label)\ny_TestOneHot = np_utils.to_categorical(y_test_label)\n#in[21]\nprint(y_TrainOneHot[:5])\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Keras_Mnist_Introduce.py","file_name":"Keras_Mnist_Introduce.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"246914616","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport xlrd\n\nimport utils\n\nDATA_FILE = 'data/fire_theft.xls'\n\n# Step 1: read in data from the .xls file\nbook = xlrd.open_workbook(DATA_FILE, encoding_override=\"utf-8\")\nsheet = book.sheet_by_index(0)\ndata = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])\nn_samples = sheet.nrows - 1\n\n# Step 2: create placeholders for input X (number of fire) and label Y (number of theft)\nX = tf.placeholder(tf.float32, name='X', shape=[])\nY = tf.placeholder(tf.float32, name='Y', shape=[])\n\n# Step 3: create weight and bias, initialized to 0\nw = tf.get_variable('weights', shape=[])\nb = tf.get_variable('bias', shape=[])\n\n# Step 4: build model to predict Y\nY_predicted = X * w + b \n\n# Step 5: use the square error as the loss function\nloss = tf.square(Y - Y_predicted, name='loss')\n# loss = utils.huber_loss(Y, Y_predicted)\n\n# Step 6: using gradient descent with learning rate of 0.01 to minimize loss\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)\n\n# Create a Savor Object\nsaver = tf.train.Saver()\ngraph = tf.get_default_graph()\ninput_graph_def = graph.as_graph_def(add_shapes=True)\n\ninit = tf.global_variables_initializer()\n\ndef train_graph():\n\n\twith tf.Session() as sess:\n\t\t# Step 7: initialize the necessary variables, in this case, w and b\n\t\tsess.run(init)\n\n\t\t# writer = tf.summary.FileWriter('./graphs/linear_reg', sess.graph)\n\n\t\ttf.train.write_graph(sess.graph, '.',\n 'linreg.pb', as_text=False)\n\t\t\n\t\t# Step 8: train the model\n\t\tfor i in range(100): # train the model 100 epochs\n\t\t\ttotal_loss = 0\n\t\t\tfor x, y in data:\n\t\t\t\t# Session runs train_op and fetch values of loss\n\t\t\t\t_, l = sess.run([optimizer, loss], feed_dict={X: x, Y:y}) \n\t\t\t\ttotal_loss += l\n\t\t\tprint('Epoch {0}: {1}'.format(i, total_loss/n_samples))\n\n\t\tsaver.save(sess, './model_final_linreg.ckpt')\n\n\n\t\t# close the writer when you're done using it\n\t\t# writer.close() \n\n\t\t# Step 9: output the values of w and b\n\t\tw_, b_ = sess.run([w, b]) \n\n\t\toutput_node_names=[\"weights\", \"bias\"]\n\n\t\toutput_graph_def = tf.graph_util.convert_variables_to_constants(\n sess, # The session\n input_graph_def, # input_graph_def is useful for retrieving the nodes \n output_node_names \n\t\t)\n\n\t\treturn w_, b_\n\nresult = train_graph()\nprint(\"w = %.2f, b = %.2f\" % result) \n\n\n\n# plot the results\nX, Y = data.T[0], data.T[1]\nplt.plot(X, Y, 'bo', label='Real data')\nplt.plot(X, X * w + b, 'r', label='Predicted data')\nplt.legend()\nplt.show()","sub_path":"Linear Regression Model/LRM2/linreg.py","file_name":"linreg.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"67005773","text":"from time import sleep\nfrom PIL import ImageGrab\nimport numpy as np\nimport mouse\n\n # Coordinates where the notifcation box is located\nx = 1366\ny = 768\n\n# seconds between each iteration\ntime_interval = 30\n\n# color white\nwhite = [255, 255, 255] \n\nwhile True:\n # Get image and transform it to an array of numbers\n screen = np.array(ImageGrab.grab(bbox=[x, y, x+1, y+1]))[0][0] # use indices to get only one pixel\n\n # check if the pixel is white\n if screen[0] != 255:\n\n # move mouse to pixel coordinates\n mouse.move(x,y, absolute=True, duration=0)\n\n # left click\n mouse.click('left')\n\n # sleep for x amount of time\n sleep(time_interval)\n","sub_path":"_other_/Autoclicker.py","file_name":"Autoclicker.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"39532409","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.admin.views.decorators import staff_member_required\n\nfrom .models import Paste\nfrom .forms import PasteForm\n\n\ndef new(request):\n if request.method == 'POST':\n form = PasteForm(request.POST)\n if form.is_valid():\n paste = form.save()\n return redirect('pastebin:by_hash', hash_val=paste.hash)\n else:\n form = PasteForm()\n\n return render(request, 'pastebin/add.html', {'form': form})\n\n@staff_member_required()\ndef view_multiple(request, number=None):\n pastes = Paste.objects.filter().order_by('-created_on')\n\n if number is not None and number < len(pastes):\n pastes = pastes[:number]\n\n return render(request, 'pastebin/bulk_view.html', {'objects': pastes})\n\n\ndef view_all(request):\n return view_multiple(request)\n\n\ndef recent(request, num):\n if num is None:\n num = 5\n else:\n num = int(num)\n\n return view_multiple(request, num)\n\n\ndef by_hash(request, hash_val):\n paste = get_object_or_404(Paste, hash=hash_val)\n return render(request, 'pastebin/view_paste.html', {'object': paste})\n\n\n\n","sub_path":"pastebin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"109764242","text":"from django.urls import path\nfrom main import views\n\n\napp_name = 'mained'\nurlpatterns = [\n path('', views.main, name='main'),\n path('clothed/', views.clothed, name='clothed'),\n path('caped/', views.caped, name='caped'),\n path('thinged/', views.thinged, name='thinged'),\n path('pantsed/', views.pantsed, name='pantsed'),\n path('contacted/', views.contacted, name='contacted'),\n path('mained',views.mained,name='mained'),\n path('add/',views.add,name='add'),\n \n]","sub_path":"BlueShopping/logined/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"254676418","text":"import os,sys\nfname=input('file name')\nif os.path.isfile(fname):\n f=open(fname,'r')\nelse:\n print(fname+'not exist')\n sys.exit()\nprint('the file content are')\nstr=f.read()\nprint(str)\nf.close()\n","sub_path":"programs-part@2/files_exist.py","file_name":"files_exist.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"564660353","text":"# Unless explicitly stated otherwise all files in this repository are licensed\n# under the Apache License Version 2.0.\n# This product includes software developed at Datadog (https://www.datadoghq.com/).\n# Copyright 2018 Datadog, Inc.\n\nimport logging\nimport tornado\nimport json\n\n\nlog = logging.getLogger(__name__)\n\n\nclass APIStatusHandler(tornado.web.RequestHandler):\n def initialize(self, aggregator_stats):\n self._aggregator_stats = aggregator_stats\n\n def get(self):\n stats = self._aggregator_stats.get_aggregator_stats()\n\n check_stats = stats.pop('stats')\n stats['checks'] = {}\n for signature, values in check_stats.iteritems():\n check = signature[0]\n if check in stats['checks']:\n stats['checks'][check]['merics'] += values\n else:\n stats['checks'][check] = {'metrics': values}\n\n self.write(json.dumps(stats))\n","sub_path":"api/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"535661986","text":"import pyglet\nfrom pyglet.window import key\nimport random\n\n\ngame_window = pyglet.window.Window(800, 600)\npyglet.resource.path = [\"../resources\"]\n\ndef resize_image(image, width=50, height=50):\n image.width = width\n image.height = height\n\ndef center_image(image):\n image.anchor_x = image.width / 2\n image.anchor_y = image.height / 2\n\ndef asterids(num_asteroids):\n asterids = []\n for i in range(num_asteroids):\n x = random.randint(0, 800)\n y = random.randint(0, 600)\n\n ast_image = pyglet.resource.image(\"asteroid.png\")\n resize_image(ast_image)\n center_image(ast_image)\n new_astroid = pyglet.sprite.Sprite(ast_image, x=x, y=y)\n\n asterids.append(new_astroid)\n\n return asterids\n\n\nastroid = asterids(1)[0]\n\n\n\n\n@game_window.event\ndef on_draw():\n game_window.clear()\n # ast = asterids(5)\n # for a in ast:\n # a.draw()\n astroid.draw()\n\n@game_window.event\ndef on_key_press(symbol, modifiers):\n if symbol == key.LEFT:\n astroid.x -= 1\n elif symbol == key.RIGHT:\n astroid.x += 1\n elif symbol == key.UP:\n astroid.y += 1\n elif symbol == key.DOWN:\n astroid.y -= 1\n\n\n\nif __name__ == '__main__':\n # ast = asterids(5)\n while True:\n # pyglet.clock.tick()\n # game_window.switch_to()\n game_window.dispatch_events()\n game_window.dispatch_event('on_draw')\n game_window.flip()\n\n","sub_path":"pyglet_basic/version1/bbb.py","file_name":"bbb.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"443223718","text":"from numpy import zeros\n\nfrom .N7b import N7b\nfrom gwlfe.AFOS.GrazingAnimals.Losses.GRLBN_2 import GRLBN_2\nfrom gwlfe.AFOS.GrazingAnimals.Losses.GRStreamN import AvGRStreamN\nfrom gwlfe.AFOS.nonGrazingAnimals.Losses.NGLostBarnNSum import NGLostBarnNSum\nfrom gwlfe.BMPs.AgAnimal.NAWMSL_2 import NAWMSL_2\nfrom gwlfe.BMPs.AgAnimal.NAWMSP_2 import NAWMSP_2\nfrom gwlfe.BMPs.AgAnimal.NFENCING import NFENCING\nfrom gwlfe.BMPs.AgAnimal.NRUNCON_2 import NRUNCON_2\n\n\ndef N7b_2(NYrs, NGPctManApp, GrazingAnimal_0, NumAnimals, AvgAnimalWt, AnimalDailyN, NGAppNRate, Prec, DaysMonth,\n NGPctSoilIncRate, GRPctManApp, GRAppNRate, GRPctSoilIncRate, NGBarnNRate, AWMSNgPct, NgAWMSCoeffN,\n RunContPct, RunConCoeffN, PctGrazing, GRBarnNRate, AWMSGrPct, GrAWMSCoeffN, PctStreams, GrazingNRate, n41b,\n n85h, n41d, n85j, n41f, n85l, n42, n45, n69, n43, n64):\n result = zeros((NYrs))\n n7b = N7b(NYrs, GrazingAnimal_0, NumAnimals, AvgAnimalWt, AnimalDailyN, NGAppNRate, NGPctSoilIncRate, GRAppNRate,\n GRPctSoilIncRate, GrazingNRate, GRPctManApp, PctGrazing, GRBarnNRate, Prec, DaysMonth, AWMSGrPct,\n GrAWMSCoeffN, RunContPct, RunConCoeffN, n41b, n85h, NGPctManApp, AWMSNgPct, NGBarnNRate, NgAWMSCoeffN,\n n41d,\n n85j, n41f, n85l, PctStreams, n42, n45, n69, n43, n64)\n nawmsl = NAWMSL_2(NYrs, GrazingAnimal_0, NumAnimals, AvgAnimalWt, AnimalDailyN, GRPctManApp, PctGrazing,\n GRBarnNRate,\n Prec, DaysMonth, AWMSGrPct, GrAWMSCoeffN, RunContPct, RunConCoeffN, n41b, n85h)\n nawmsp = NAWMSP_2(NYrs, NGPctManApp, GrazingAnimal_0, NumAnimals, AvgAnimalWt, AnimalDailyN, NGBarnNRate,\n Prec, DaysMonth, AWMSNgPct, NgAWMSCoeffN, RunContPct, RunConCoeffN, n41d, n85j)\n nruncon = NRUNCON_2(NYrs, GrazingAnimal_0, NumAnimals, AvgAnimalWt, AnimalDailyN, GRPctManApp, PctGrazing,\n GRBarnNRate,\n Prec, DaysMonth, AWMSGrPct, GrAWMSCoeffN, RunContPct, RunConCoeffN, NGPctManApp, NGBarnNRate,\n AWMSNgPct,\n NgAWMSCoeffN, n41f, n85l)\n nfencing = NFENCING(PctStreams, PctGrazing, GrazingAnimal_0, NumAnimals, AvgAnimalWt, AnimalDailyN, n42, n45, n69)\n nglbn = NGLostBarnNSum(NYrs, NGPctManApp, GrazingAnimal_0, NumAnimals, AvgAnimalWt, AnimalDailyN, NGBarnNRate,\n Prec, DaysMonth, AWMSNgPct, NgAWMSCoeffN, RunContPct, RunConCoeffN)\n grlbn = GRLBN_2(NYrs, GrazingAnimal_0, NumAnimals, AvgAnimalWt, AnimalDailyN, GRPctManApp, PctGrazing, GRBarnNRate,\n Prec, DaysMonth, AWMSGrPct, GrAWMSCoeffN, RunContPct, RunConCoeffN)\n grsn = AvGRStreamN(PctStreams, PctGrazing, GrazingAnimal_0, NumAnimals, AvgAnimalWt, AnimalDailyN)\n n7b_carryover = n7b\n for y in range(NYrs):\n nagbuffer_2 = (n43 / n42) * n64 * (n7b_carryover - (nglbn[y] + grlbn[y] + grsn))\n result[y] = n7b_carryover - (nawmsl[y] + nawmsp[y] + nruncon[y] + nfencing + nagbuffer_2)\n n7b_carryover = result[y]\n return result\n\n\ndef N7b_2_f():\n pass\n","sub_path":"gwlfe/Output/AvAnimalNSum/N7b_2.py","file_name":"N7b_2.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"207283430","text":"'''\nFile: writer-bot.py\nAuthor: Flynn Gaur\nCourse: CSC 120 001 - Spring 2019\nPurpose: \n\n \n \n \n'''\n#taking too long, additional statement in while loop\nimport random\nNONWORD=\" \"\nSEED=8\n\ndef main():\n # file_name=input()\n file_name='bee.txt'\n file=open(file_name)\n data=file.readlines()\n n=int(input()) #prefix size\n assert (n>1),\"test\"\n tlist=markov_chain(data,n)\n # print('ready')\n words_num=int(input())\n assert (words_num>1),\"\"\n output_generate(tlist,words_num)\n \n \ndef markov_chain(data,n):\n random.seed(SEED)\n chain={}\n values=[]\n lines=[]\n for i in range(0,n):\n lines.append(NONWORD)\n for line in data:\n line=line.rstrip('\\n')\n line=line.split(' ')\n lines+=line\n while \"\" in lines:\n lines.remove(\"\")\n for i in range(0,len(lines)-n):\n prefix=tuple(lines[i:i+n])\n value=lines[i+n]\n if prefix not in chain:\n chain[prefix]=[]\n chain[prefix].append(lines[i+n])\n print(chain)\n prefix=[]\n tlist=[]\n for i in range(n,2*n):\n tlist.append(lines[i])\n prefix.append(lines[i])\n prefix=tuple(prefix)\n # print(prefix)\n k=tuple(chain.keys())\n # print(k)\n c=0\n while prefix in chain.keys():\n temp=[]\n c+=1\n if len(chain[prefix])!=1:\n random_i=random.randint(0,len(chain[prefix])-1)\n word=chain[prefix][random_i]\n else:\n word=chain[prefix][0]\n # print(prefix)\n tlist.append(word)\n # print(word)\n temp=list(prefix)[1:]\n temp.append(word)\n prefix=tuple(temp)\n #print(tlist)\n return tlist\n\n\n \ndef output_generate(tlist,words_num):\n for index in range(0,words_num):\n if index%10==0:\n print()\n print(tlist[index]+' ',end='')\n \n \nmain()\n \n","sub_path":"4. writer-bot/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"427963903","text":"from django.urls import path\nfrom . import views\nfrom .views import *\nurlpatterns = [\n path(\"\", PostListView.as_view(), name=\"BlogIndex\"),\n #path(\"//\", BlogDetailView.as_view(), name='BlogDetail'),\n path(\"//\", views.BlogDetailView, name='BlogDetail'),\n path(\"profile///\", views.ProfileDetailView, name='ProfileDetail'),\n path(\"/\", views.BlogCategoryList, name=\"BlogCategory\"),\n path(\"tag//\", views.BlogTagList, name=\"BlogTag\"),\n]","sub_path":"lodinews/blogf/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"170626488","text":"#usr/bin/python3\n\nimport sys\nfrom random import randint\n\ndateList = []\n\n\"\"\"\n Wrapper function \n\n Arguments:\n maxNumberDates = how many dates will be entered\n\n Returns:\n None\n\"\"\"\ndef AgeGenerator(maxNumberDates):\n CreateDateLists(maxNumberDates)\n\n\"\"\"\n Creates a list of tuples filled with start and end dates\n once maxNumberDates has been reached writes to a text file\n\n Arguments:\n maxNumberDates = how many dates will be entered\n\n Returns:\n None\n\"\"\"\ndef CreateDateLists(maxNumberDates):\n for i in range(maxNumberDates + 1):\n if(len(dateList) < maxNumberDates):\n startDate = RandomDates()\n endDate = RandomDates(startDate)\n\n dates = (startDate, endDate)\n dateList.append(dates)\n else:\n WriteTextFile()\n\"\"\"\n Generates a random date between 1900 and 2000\n If given a startDate then between startDate and 2000\n\n Arguments:\n startDate = starting date to use for the random generation\n\n Returns:\n date = a random number between either startDate and 2000 or 1900\n and 2000\n\"\"\"\ndef RandomDates(startDate = None):\n\n if(startDate):\n date = randint(startDate,2000)\n else:\n date = randint(1900,2000)\n\n return date\n\n\"\"\"\n Writes dateList to a text file AgeList\n\n Arguments:\n None\n\n Returns:\n None\n\"\"\"\ndef WriteTextFile():\n fileIO = open(\"AgeList.txt\", \"w\", newline=\"\\n\")\n\n for date in dateList:\n fileIO.write(str(date[0]) + \" \" + str(date[1]) + \"\\n\")\n\n fileIO.close()\n","sub_path":"Programming Challange 1/AgeTools/AgeGenerator.py","file_name":"AgeGenerator.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"455606776","text":"from project import create_app\nfrom project.models import User, Task\nfrom project import db\n\napp = create_app()\napp.logger.info('Flask application instance instantiated')\n\n\n@app.shell_context_processor\ndef make_shell_context():\n return dict(db=db, User=User, Task=Task)\n\n\nif __name__ == '__main__':\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"243037344","text":"\"\"\"empty message\n\nRevision ID: 6fda96c3b1bb\nRevises: ffeaa4610b23\nCreate Date: 2018-11-28 12:16:53.658479\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '6fda96c3b1bb'\ndown_revision = 'ffeaa4610b23'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('accounts', sa.Column('saving_duration', sa.Interval(), nullable=True))\n op.add_column('accounts', sa.Column('saving_interest_rate', sa.Float(), nullable=True))\n op.drop_column('accounts', 'interest_rate')\n op.drop_column('accounts', 'duration')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('accounts', sa.Column('duration', mysql.DATETIME(), nullable=True))\n op.add_column('accounts', sa.Column('interest_rate', mysql.FLOAT(), nullable=True))\n op.drop_column('accounts', 'saving_interest_rate')\n op.drop_column('accounts', 'saving_duration')\n # ### end Alembic commands ###\n","sub_path":"backend/migrations/versions/6fda96c3b1bb_.py","file_name":"6fda96c3b1bb_.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"230758333","text":"def __lt__(self, other):\n \"This function helps sorted to decide how to sort.\\n\\n It just checks itself against the other and decides on some key values\\n if it should be sorted higher or lower in the list.\\n The way it works:\\n For networks, every 1 in 'netmask in binary' makes the subnet more specific.\\n Therefore I chose to use prefix as the weight.\\n So a single IP (/32) should have twice the weight of a /16 network.\\n To keep everything in the same weight scale,\\n - for ipv6, we use a weight scale of 0 (all possible ipv6 addresses) to 128 (single ip)\\n - for ipv4, we use a weight scale of 0 (all possible ipv4 addresses) to 128 (single ip)\\n Therefore for ipv4, we use prefixlen (0-32) * 4 for weight,\\n which corresponds to ipv6 (0-128).\\n \"\n for orderpart in self.order:\n if (orderpart == 's'):\n myweight = self.source_weight()\n hisweight = other.source_weight()\n if (myweight != hisweight):\n return (myweight > hisweight)\n elif (orderpart == 'd'):\n myweight = self.db_weight()\n hisweight = other.db_weight()\n if (myweight != hisweight):\n return (myweight < hisweight)\n elif (orderpart == 'u'):\n myweight = self.user_weight()\n hisweight = other.user_weight()\n if (myweight != hisweight):\n return (myweight < hisweight)\n try:\n return (self['src'] < other['src'])\n except TypeError:\n return (self.source_type_weight() < other.source_type_weight())\n errormessage = 'We have two rules ({1}, {2})'.format(self, other)\n errormessage += ' with exact same weight. Please file a bug.'\n raise PgHbaValueError(errormessage)","sub_path":"Data Set/bug-fixing-5/9e100212e2f3455b64edbcd910f5a5ec57e04783-<__lt__>-fix.py","file_name":"9e100212e2f3455b64edbcd910f5a5ec57e04783-<__lt__>-fix.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"227274612","text":"\"\"\"\nScatterer Photodiode\n====================\n\"\"\"\n\ndef run(Plot, Save):\n from PyMieSim.Source import PlaneWave\n from PyMieSim.Detector import Photodiode\n from PyMieSim.Scatterer import Sphere\n\n Source = PlaneWave(Wavelength = 450e-9,\n Polarization = 0,\n E0 = 1)\n\n Detector = Photodiode(Sampling = 201,\n NA = 0.2,\n GammaOffset = 0,\n PhiOffset = 0,\n CouplingMode = 'Centered')\n\n Scat = Sphere(Diameter = 300e-9,\n Source = Source,\n Index = 1.4)\n\n Coupling = Detector.Coupling(Scatterer = Scat)\n\n print(Coupling) # 6.566085549292496e-18 Watt (6.57e-03 fWatt)\n\n\nif __name__ == '__main__':\n run(Plot=False, Save=False)\n","sub_path":"examples/ComputingCoupling/Coupling:Scatterer-Photodiode.py","file_name":"Coupling:Scatterer-Photodiode.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"454892164","text":"# -*- coding: utf-8 -*-\n# created by inhzus\n\n\nfrom os import getenv\nfrom urllib.parse import quote\n\nfrom berater.utils.wechat_sdk import Url\n\n\nclass BaseConfig(object):\n PROJECT = 'Berater'\n WECHAT_TOKEN = 'bkzs'\n\n # Ali express API\n EXPRESS_API_URL = 'http://kdwlcxf.market.alicloudapi.com/kdwlcx'\n\n # Ali short message service\n SMS_SIGN_NAME = '南大咨询'\n SMS_TEMPLATE_CODE = 'SMS_163433313'\n\n # Flask SQLAlchemy\n SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{}:{}@mysql/{}'.format(\n getenv('MYSQL_USER'), getenv('MYSQL_PASSWORD'), getenv('MYSQL_DATABASE'))\n # SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@mysql/berater'\n SQLALCHEMY_BINDS = {\n 'local': SQLALCHEMY_DATABASE_URI\n }\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n SQLALCHEMY_POOL_SIZE = 5\n APP_TOKEN = {\n 'face': getenv('APP_TOKEN_FACE', '')\n }\n\n # noinspection PyUnresolvedReferences\n API_KEY = getenv('API_KEY')\n API_SECRET = getenv('API_SECRET')\n EXPRESS_APP_CODE = getenv('EXPRESS_APP_CODE')\n SMS_ACCESS_KEY = getenv('SMS_ACCESS_KEY')\n SMS_ACCESS_SECRET = getenv('SMS_ACCESS_SECRET')\n\n # from .secret import (API_KEY, API_SECRET, EXPRESS_APP_CODE, SMS_ACCESS_KEY, SMS_ACCESS_SECRET)\n\n @staticmethod\n def init_app(app):\n pass\n\n\nclass DevelopmentConfig(BaseConfig):\n DEBUG = True\n SERVER_URL = 'http://weixin.njunova.com'\n LOCAL_URL = 'http://localhost:5000'\n # noinspection SpellCheckingInspection\n CRYPTO_KEY = 'ha0jkDDbnn9PT0UKCz1eCZjhVvCVwYWpaG5x2T_P1xo='\n\n # Flask SQLAlchemy\n SQLALCHEMY_ECHO = True\n\n\nclass ProductionConfig(BaseConfig):\n SERVER_URL = 'http://weixin.njunova.com'\n # noinspection SpellCheckingInspection\n CRYPTO_KEY = getenv('CRYPTO_KEY')\n SQLALCHEMY_ECHO = False\n\n\nconfig = {\n 'dev': DevelopmentConfig,\n 'pro': ProductionConfig,\n 0: ProductionConfig\n}\n\nMENU = {\n 'button': [\n {\n 'type': 'view',\n 'name': '照片替换',\n 'url': Url.oauth2_new_page.format(\n appid=config[0].API_KEY,\n redirect_url=quote('{}/?type=student&url=face.njunova.com/user'\n .format(config[0].SERVER_URL))\n )\n },\n {\n 'type': 'view',\n 'name': '学前教育',\n 'url': Url.oauth2_new_page.format(\n appid=config[0].API_KEY,\n redirect_url=quote('{}/?type=student&url=weixin.njunova.com/qna'\n .format(config[0].SERVER_URL))\n )\n },\n {\n 'type': 'click',\n 'name': '学号查询',\n 'key': 'BERATER_KEY2'\n },\n ]\n}\n","sub_path":"berater/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"640136907","text":"import datetime\nimport operator\nimport os\nimport sys\nimport threading\nimport time\nimport traceback\nfrom dataclasses import dataclass\nfrom typing import List\n\n# for measuring how long execution takes\nfrom timeit import default_timer as timer\n\nfrom app.doylefilecache import DoyleFileCache\nfrom app.doylefolder import DoyleFolder, DoyleFolderType\nfrom app.doylefiledb import DoyleFileDb\nfrom app.doylefile import DoyleFile\nfrom app.doyleresult import DoyleResult\n\nserverBlackList = [\"DOYLE-CORDOVA\", \"VM-DOYLE-YUI\", \"VM-DOYLE-22\"]\n\n\n@dataclass\nclass FolderConfiguration:\n queueFolders: List[str]\n serverFolder: str\n databasePath: str\n databaseBackupPath: str\n\n\nonLinuxReal = FolderConfiguration([\"/mnt/udrive/Doyle/TestQueues\", \"/mnt/qdrive/Doyle/TestQueues\" ],\"/mnt/udrive/Doyle/TestServers\", \"/tmp\", \"/mnt/udrive/Doyle/Databases\")\nonWindowsReal = FolderConfiguration([\"U:\\\\Doyle\\\\TestQueues\", \"Q:\\\\Doyle\\\\TestQueues\" ], \"U:\\\\Doyle\\\\TestServers\", \".\", \"U:\\\\Doyle\\\\Db\")\nonLinuxTest = FolderConfiguration([\"./TestData/TestQueues\"], \"./TestData/TestServers\" , \"/tmp\", \"/tmp/Db\")\nonWindowsTest = FolderConfiguration([\".\\\\TestData\\\\TestQueues\"], \".\\\\TestData\\\\TestServers\", \".\\\\TestData\", \".\\\\TestData\\\\Db\")\nonDocker = FolderConfiguration([\"/usr/src/DoyleData/TestQueues\"], \"/usr/src/DoyleData/TestServers\", \"/tmp\", \"/tmp/Db\")\n\n\nclass DoyleInfo(threading.Thread):\n \"\"\" Main class that keeps and updates test info for queues and servers.\"\"\"\n\n def __init__(self):\n\n # find out which folder configuration to take\n for config in [onLinuxReal, onWindowsReal, onLinuxTest, onWindowsTest, onDocker]:\n print(f\"Trying: {config}\")\n print(f\"isdir {config.serverFolder}: {os.path.isdir(config.serverFolder)}\")\n print(f\"isdir {config.databasePath}: {os.path.isdir(config.databasePath)}\")\n\n if os.path.isdir(config.serverFolder) and os.path.isdir(config.databasePath):\n print(f\"Getting doyle queues from : {','.join(config.queueFolders)}\")\n print(f\"Getting doyle servers from : {config.serverFolder}\")\n print(f\"Storing database on : {config.databasePath}\")\n print(f\"Storing database backup on : {config.databaseBackupPath}\")\n self.folderConfig = config\n break\n else:\n sys.exit(\"None of the folder configurations lead to TestQueues and TestServers!\")\n\n self.cache = DoyleFileCache()\n self.queueFolders = []\n for folder in self.folderConfig.queueFolders:\n self.queueFolders.append(DoyleFolder(DoyleFolderType.queueFolder, folder))\n self.serverFolder = DoyleFolder(DoyleFolderType.serverFolder, self.folderConfig.serverFolder)\n\n self.result = DoyleResult()\n self._clean()\n\n # create file database and pass it (as a static) to DoyleFile\n self.doyleFileDb = DoyleFileDb(self.folderConfig.databasePath, self.folderConfig.databaseBackupPath)\n DoyleFile.doyleFileDb = self.doyleFileDb\n\n self.keepRunning = True\n self.cleanDatabaseRequested = False\n self.backupDatabaseRequested = False\n\n # keep track which servers should be busy and the first time this occured so we can report for how long it should have been busy\n self.shouldBeBusyServersFirstDetected = {}\n\n threading.Thread.__init__(self)\n self.start()\n\n def quit(self):\n # signal thread to stop\n print(\"Asking info thread to stop\")\n self.keepRunning = False\n # wait for thread to stop\n print(\"Waiting for info thread to stop\")\n self.join()\n # stop the database thread\n self.doyleFileDb.quit()\n\n def run(self):\n count = 20\n while self.keepRunning:\n if count >= 20:\n self._update()\n count = 0\n if self.cleanDatabaseRequested == True:\n self.result.clear(\"Busy cleaning the database, try again a bit later\")\n self.doyleFileDb.cleanupDatabase()\n self.cleanDatabaseRequested = False\n\n if self.backupDatabaseRequested == True:\n self.result.clear(\"Backing up the database, try again a bit later\")\n self.doyleFileDb.backupDatabase()\n self.backupDatabaseRequested = False\n\n count = count + 1\n time.sleep(1)\n\n def _clean(self):\n self.serverConfigs = []\n self.serversForAllQueues = []\n self.cache.resetUsedCount()\n\n def ageToString(self, age):\n # clocks may not be synchronized so age might be slightly negative - display that as 1s\n if age.total_seconds() < 0:\n ageString = \"1s\"\n elif age.days > 0:\n ageString = \"%sd\" % age.days\n elif age.seconds > 3600:\n ageString = \"{0:.1f}h\".format(age.seconds / 3600)\n elif age.seconds > 60:\n ageString = \"%sm\" % int(age.seconds / 60)\n else:\n ageString = \"%ss\" % age.seconds\n return ageString\n\n def getServerConfigs(self, baseDir):\n start = timer()\n\n resultDict = {}\n for f in os.listdir(baseDir):\n if os.path.splitext(f)[1].lower() == \".cfg\":\n serverName = os.path.splitext(f)[0].upper()\n for line in open(os.path.join(baseDir, f)):\n queueName = line.strip(\" \\n\").split(\"\\\\\")[-1].upper()\n if queueName in resultDict:\n resultDict[queueName].append(serverName)\n else:\n resultDict[queueName] = [serverName]\n\n end = timer()\n print(\"Getting %s server configs took %.4fs\" % (len(resultDict), (end - start)))\n\n return resultDict\n\n def _update(self):\n \"\"\" Re-read queue and server folders and build a new result.\"\"\"\n start = timer()\n try:\n self._clean()\n newResult = DoyleResult()\n\n # update information from the queues and the servers\n for queueFolder in self.queueFolders:\n queueFolder.update(self.cache)\n self.serverFolder.update(self.cache)\n\n # save all the doyleFiles that have not been referenced anymore\n unusedEntries = self.cache.removeUnusedEntries()\n for (file, doyleFile) in unusedEntries:\n doyleFile.save()\n\n self.serverConfigs = self.getServerConfigs(self.serverFolder.baseFolder)\n\n # build a list of servers that should be handling the queues\n for queueFolder in self.queueFolders:\n for queue, files, dummy in queueFolder.items:\n if len(files):\n if queue.upper() in self.serverConfigs:\n self.serversForAllQueues.extend(self.serverConfigs[queue.upper()])\n self.serversForAllQueues = list(set(self.serversForAllQueues))\n\n # update the number of queued tests\n self.doyleFileDb.addQueuedCount(datetime.datetime.now(), sum([queueFolder.count for queueFolder in self.queueFolders]))\n\n # compile two lists with servers to report: the first list has all the servers, the second has only the servers that have non-default style\n # compile a list with all executing tests\n for server, files, upgradePending in self.serverFolder.items:\n # should we display info about this server\n doyleServerAge = \"---\"\n serverMessages = []\n style = \"default\"\n\n # there are files executing on this server\n if len(files) > 0:\n serverMessages.append(\"Executing\")\n\n # server has an upgrade pending\n if server not in serverBlackList:\n if upgradePending == True:\n serverMessages.append(\"Server has an upgrade pending\")\n style = \"warning\"\n\n # server should be busy but is not\n if server in self.serversForAllQueues and len(files) == 0:\n if server not in self.shouldBeBusyServersFirstDetected:\n self.shouldBeBusyServersFirstDetected[server] = datetime.datetime.now()\n print(f\"Server {server} because 'should be busy' at {datetime.datetime.now()}\")\n age = datetime.datetime.now() - self.shouldBeBusyServersFirstDetected[server]\n if age > datetime.timedelta(minutes=5):\n doyleServerAge = self.ageToString(age)\n serverMessages.append(\"Server should be busy but is not\")\n style = \"danger\"\n else:\n # server is not needed or server is busy so take it out of dictionary\n if server in self.shouldBeBusyServersFirstDetected:\n del self.shouldBeBusyServersFirstDetected[server]\n print(f\"Server {server} leaves 'should be busy' at {datetime.datetime.now()}\")\n\n # check if doyle server is active\n if server not in serverBlackList:\n aliveFile = os.path.join(self.serverFolder.baseFolder, server, \"alive.dat\")\n if os.path.isfile(aliveFile):\n age = datetime.datetime.now() - datetime.datetime.fromtimestamp(os.path.getmtime(aliveFile))\n if age > datetime.timedelta(minutes=5):\n doyleServerAge = self.ageToString(age)\n serverMessages.append(\"DoyleServer Not Running\")\n style = \"danger\"\n else:\n serverMessages.append(\"DoyleServer status unknown\")\n\n # check ping result\n # if server not in serverBlackList:\n # msg='Ping status unknown'\n # for server2,alive in pingStates:\n # if alive:\n # msg=''\n # else:\n # msg='Ping Not Responding'\n # if len(msg)>0:\n # serverMessages.append(msg)\n # style='danger'\n\n if len(serverMessages) > 0:\n row = [style, doyleServerAge, server, \", \".join(serverMessages)]\n if style != \"default\":\n newResult.serversAlerted.append(row)\n newResult.servers.append(row)\n\n for doyleFile in files:\n style = \"default\"\n age = datetime.datetime.now() - doyleFile.firstExecutionTime\n if age.total_seconds() > doyleFile.expectedExecutionTime[2]:\n style = \"danger\"\n newResult.executingTestsAlert = True\n elif age.total_seconds() > doyleFile.expectedExecutionTime[1]:\n style = \"warning\"\n newResult.executingTestsAlert = True\n row = [\n style,\n \"%s (%s)\" % (self.ageToString(age), self.ageToString(datetime.timedelta(seconds=doyleFile.expectedExecutionTime[0]))),\n (server, doyleFile.queue),\n \"#{0}\".format(doyleFile.tfsbuildid) if doyleFile.tfsbuildid != 0 else \"#----\",\n (\n \"/\".join([doyleFile.xbetree, doyleFile.xbegroup, doyleFile.xbeproject, \"{0:04}\".format(doyleFile.xbebuildid)]),\n doyleFile.file,\n \"file:///u:/pgxbe/releases/\" + \"/\".join([doyleFile.xbetree, doyleFile.xbegroup, doyleFile.xbeproject, \"{0:04}\".format(doyleFile.xbebuildid)]) + \"/xbe_release.log\",\n ),\n doyleFile.type,\n doyleFile.target,\n ]\n newResult.executingTests.append(row)\n\n # check if we should switch on the blue light\n # blueLightOn=0\n # for server,files,dummy in self.serverFolder.items:\n # for doyleFile in files:\n # age=datetime.datetime.now()-doyleFile.firstExecutionTime\n # if age.total_seconds() > doyleFile.expectedExecutionTime[2]:\n # blueLightOn=100\n # xmlrpc.client.ServerProxy('http://10.0.60.57:8000').blue(blueLightOn)\n\n # raise Exception(\"testing failure to update\")\n\n # getQueued\n for queueFolder in self.queueFolders:\n for queue, files, dummy in queueFolder.items:\n if len(files):\n if queue.upper() in self.serverConfigs:\n serverString = \",\".join(self.serverConfigs[queue.upper()])\n else:\n serverString = \"No servers listening on this queue !!\"\n for doyleFile in files:\n age = datetime.datetime.now() - doyleFile.queuedTime\n style = \"default\"\n if age.total_seconds() > 2 * 24 * 3600:\n style = \"warning\"\n newResult.queuedTestsAlert = True\n row = [\n style,\n self.ageToString(age),\n (queue, serverString),\n \"#{0}\".format(doyleFile.tfsbuildid) if doyleFile.tfsbuildid != 0 else \"#----\",\n (\"/\".join([doyleFile.xbetree, doyleFile.xbegroup, doyleFile.xbeproject, \"{0:04}\".format(doyleFile.xbebuildid)]), doyleFile.file),\n doyleFile.type,\n doyleFile.target,\n ]\n newResult.queuedTests.append(row)\n\n # sort on tfsbuildid\n newResult.queuedTests = sorted(newResult.queuedTests, key=operator.itemgetter(3))\n\n # if we got here without exception, there is no error\n newResult.errorMsg = None\n\n except:\n print(\"Updating info failed with exception: %s\" % traceback.format_exc())\n newResult.clear(traceback.format_exc())\n\n # replace current result with new result\n self.result.copyFrom(newResult)\n\n end = timer()\n print(\"Building info took %.4fs (hit %s / new %s / gone %s)\" % ((end - start), self.cache.hitCount, self.cache.addCount, self.cache.removeCount))\n\n def getErrorMsg(self):\n \"\"\" Get the error message if an error has occured during processing, will return None when no error has occured. \"\"\"\n with self.result.lock:\n return self.result.errorMsg\n\n def getExecution(self):\n \"\"\" Get information about the executing tests and the servers. \"\"\"\n with self.result.lock:\n return self.result.executingTests\n\n def getQueued(self):\n \"\"\" Get information about the queued tests. \"\"\"\n with self.result.lock:\n return self.result.queuedTests\n\n def getServers(self):\n \"\"\" Get information about all the servers. \"\"\"\n with self.result.lock:\n return self.result.servers\n\n def getServersFailed(self):\n \"\"\" Get information about the servers that have something to report. \"\"\"\n with self.result.lock:\n return self.result.serversAlerted\n\n def getCounts(self):\n \"\"\" Get the number of entries executing and the number of entries queued. \"\"\"\n with self.result.lock:\n return {\n \"executing\": len(self.result.executingTests),\n \"executingAlert\": self.result.executingTestsAlert,\n \"queued\": len(self.result.queuedTests),\n \"queuedAlert\": self.result.queuedTestsAlert,\n \"servers\": len(self.result.servers),\n \"serversAlert\": len(self.result.serversAlerted) != 0,\n \"serverRemarks\": len(self.result.serversAlerted),\n }\n\n def getHistory(self, doyleServer):\n \"\"\" Get a list of what was excecuted on a given doyle server.\"\"\"\n\n # get the history for the given server\n entries = self.doyleFileDb.getDoyleHistory(doyleServer, 100)\n\n # calculate how busy the server was during this period\n busyPercentage = 0\n if len(entries) > 1:\n busySeconds = 0\n totalSeconds = 0\n for e in entries:\n busySeconds = busySeconds + (e[6] - e[5]).total_seconds()\n totalSeconds = (entries[0][6] - entries[-1][5]).total_seconds()\n busyPercentage = (busySeconds * 100.0) / totalSeconds\n\n # prepare the list for the HTML template\n toDisplay = []\n for x in entries:\n toDisplay.append((x[5], self.ageToString(x[6] - x[5]), x[0], \"\\\\\".join([x[1], x[2], \"{0:04}\".format(x[3])]), x[4]))\n\n return {\"history\": toDisplay, \"busyPercentage\": busyPercentage}\n\n def startCleanDatabase(self):\n self.cleanDatabaseRequested = True\n\n def backupDatabase(self):\n self.backupDatabaseRequested = True\n\n def getQueuedChartData(self, date):\n return self.doyleFileDb.getQueuedChartData(date)\n\n def getServerList(self):\n return self.doyleFileDb.getServerList()\n","sub_path":"app/doyleinfo.py","file_name":"doyleinfo.py","file_ext":"py","file_size_in_byte":17650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"624251655","text":"import re\r\nimport urllib.request,urllib.parse,urllib.error\r\nfrom googlesearch import search\r\nfrom bs4 import BeautifulSoup\r\nimport Regular_Expression as h\r\nimport Tag_and_URL_Process\r\nx=True\r\nif x==True:\r\n csv=open('hoteldetails.csv','w')\r\n csv.write('hotel name,phone,email,link'+'\\n')\r\n csv.close()\r\n k=open('urlresults.doc','w')\r\n d=input(\"enter your required search like hotel details \")\r\n print('i am seaching for google results')\r\n for url in search(d, tld='es', lang='es', stop=10):\r\n #print(url)\r\n k.write(url+'\\n')\r\n k.close()\r\n k=open('urlresults.doc','r')\r\n print(\"Now i am opening each and every link\")\r\n for i in k:\r\n Tag_and_URL_Process.open1(i)\r\n print('successfully compleated ')\r\n k.close()\r\nelse:\r\n import Sample_RPA_Apllication\r\n \r\n","sub_path":"Google_search_Module.py","file_name":"Google_search_Module.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"479139869","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.landing, name='landing'),\n path('userlogin/', views.userLogin, name='login'),\n path('userlogout/', views.user_logout, name='logout'),\n path('user-register/', views.userRegister, name='register'),\n path('activatecode/',views.activatecode,name='activatecode'),\n\n # path('csmDashboard/',csmDashboard,name='csmdashboard'),\n\n path('adminDashboard/',views.adminDashboard,name='admindashboard'),\n path('roleCreation/',views.roleCreation,name='rolecreation'),\n path('cfpCreation/',views.cfpCreation,name='cfpcreation'),\n path('cfpList/',views.cfpList,name='cfplist'),\n path('categoryEdit/',views.cateEdit,name='categoryEdit'),\n path('SubcategoryEdit/',views.subEdit,name='subEdit'),\n\n path('admindashboard/student_info/', views.adminStudents, name='adminStudents'),\n path('admindashboard/courses/',views.adminCourses,name='admincourse'),\n path('licenseKey/',views.adminLicenseKey,name=\"licenseKey\"),\n\n path('instructors/',views.viewInstructor,name='instructors'),\n path('delInstructor//',views.deleteInstructor,name='delInstructor'),\n\n path('deleteStudent//',views.deleteStu,name='deleteStudent'),\n path('viewTrainee//',views.adminViewStudent,name='viewStudent'),\n\n\n]\n","sub_path":"Admin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"301061029","text":"from django.http import JsonResponse\nfrom zhouxinyuan11.models import color,design,category,size,goods,Orders,picmake,user,addressinfo,shopping_cart\nfrom django.core.exceptions import ValidationError, ObjectDoesNotExist\nimport json\n\n\ndef get_goods(request):\n goodid = request.GET.get(\"goodid\", \"\")\n\n\n if goodid == '':\n return JsonResponse({'status':12001,'message':'error'})\n\n\n\n if goodid != '':\n Goods = {}\n try:\n result = goods.objects.get(goodid=goodid)\n a = design.objects.get(id=result.designid)\n b = color.objects.get(id=result.colorid)\n c = category.objects.get(id=result.categoryid)\n d = size.objects.get(id=result.sizeid)\n except ObjectDoesNotExist:\n return JsonResponse({'status':'error'})\n else:\n Goods['goodid'] = result.goodid\n Goods['design'] = a.design\n Goods['color'] = b.color\n Goods['category'] = c.category\n Goods['size'] = d.size\n Goods['amount'] = result.amount\n Goods['goodinfo'] = result.goodinfo\n Goods['frontpic'] = result.frontpic\n Goods['oppositpic'] = result.oppositpic\n Goods['Name'] = result.Name\n Goods['nowprice'] = result.nowprice\n Goods['pastprice'] = result.pastprice\n Goods['ontime'] = result.ontime\n Goods['offtime'] = result.offtime\n return JsonResponse({'status': 200, 'message': 'success', 'data': Goods})\n\n\ndef get_Orders(request):\n ordernum = request.GET.get(\"ordernum\", \"\")\n if ordernum == '':\n return JsonResponse({'status':12001,'message':'error'})\n if ordernum != '':\n datas=[]\n result = Orders.objects.filter(ordernum__contains=ordernum)\n aa = goods.objects.get(id=result.goodsid)\n bb = user.objects.get(id=result.userid)\n cc = addressinfo.objects.get(id=result.addressid)\n if result:\n for r in result:\n a = design.objects.get(id=aa.designid)\n b = color.objects.get(id=aa.colorid)\n c = category.objects.get(id=aa.categoryid)\n d = size.objects.get(id=aa.sizeid)\n e = picmake.objects.get(id=r.picid)\n #c = addressinfo.objects.get(id=r.addressid)\n #d = user.objects.get(id=r.userid)\n\n orders = {}\n\n orders['ordernum'] = r.ordernum\n orders['W_id'] = bb.W_id\n\n orders['goods']={}\n orders['goods']['goodid']=aa.goodid\n orders['goods']['design']=a.design\n orders['goods']['size']=d.size\n orders['goods']['Name'] = aa.Name\n orders['goods']['color'] = b.color\n orders['goods']['category'] = c.category\n\n #orders['goods']['size'] =\n orders['address']={}\n orders['amount'] = result.amount\n orders['riqi']=result.riqi\n orders['status']=result.status\n orders['expressid']=result.espressid\n\n\n\n\n\n\n #orders['address']=\n datas.append(orders)\n return JsonResponse({'status': 200, 'message': 'success', 'data': datas})\n\n\n\n'''''''''\n\ndef get_shoppingcart(request):\n W_id = request.GET.get(\"W_id\", \"\")\n \n\n\n if W_id == '':\n return JsonResponse({'status':12001,'message':'error'})\n\n\n\n if W_id != '':\n datas=[]\n result = user.objects.filter(W_id__contains=W_id)\n aa = shopping_cart.objects.get(userid=result.id)\n\n\n if result:\n for r in result:\n a = goods.objects.get(goodid=aa.goodid)\n b = design.objects.get(id=result.designid)\n c = color.objects.get(id=result.colorid)\n d = category.objects.get(id=result.categoryid)\n e = size.objects.get(id=result.sizeid)\n f = goods.objects.get(id=r.goodsid)\n g = picmake.objects.get(id=r.picid)\n #c = addressinfo.objects.get(id=r.addressid)\n #d = user.objects.get(id=r.userid)\n\n orders = {}\n #b = picmake.objects.get(id=result.picid)\n #c = user.objects.get(id=result.userid)\n #d = addressinfo.objects.get(id=result.addressid)\n\n #orders['ordernum'] = r.ordernum\n\n orders['goods']={}\n orders['goods']['goodid']=a.goodid\n orders['goods']['Name']=a.Name\n orders['goods']['frontpic'] =b.frontpic\n orders['goods']['oppositepic'] = b.opposite\n orders['goods']['nowprice'] = a.nowprice\n orders['goods']['frontpic'] = b.frontpic\n\n\n\n\n\n\n #orders['address']=\n datas.append(orders)\n return JsonResponse({'status': 200, 'message': 'success', 'data': datas})\n\n'''''''''''\n\n''''''''''\ndef change_Orders(request):\n status = request.POST.get('status', '')\n ordernum = request.GET.get('ordernum','')\n \n \n a= Orders.objects.get()\n\n\n if status == '':\n\n return JsonResponse({'status': 10021, 'message': 'error'})\n\n result = Orders.objects.filter(status=status)\n if result:\n return JsonResponse({'status':10022, 'message': 'error'})\n\n\n\n return JsonResponse({'status':200, 'message': 'add orders success'})\n'''''","sub_path":"T恤定制/Project/zhouxinyuan00/zhouxinyuan11/views_if.py","file_name":"views_if.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"467865287","text":"from ryu.base import app_manager\nfrom ryu.controller import ofp_event\nfrom ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER\nfrom ryu.controller.handler import set_ev_cls\nfrom ryu.ofproto import ofproto_v1_3\nfrom ryu.lib.packet import packet\nfrom ryu.lib.packet import ethernet, tcp\n\nPROTO_IP = 0x0800\nPROTO_TCP = 6\n\n\nclass RestrictedHTTPRequest(app_manager.RyuApp):\n OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]\n\n def __init__(self, *args, **kwargs):\n super(RestrictedHTTPRequest, self).__init__(*args, **kwargs)\n self.macs = []\n\n @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)\n def switch_feature_handler(self, ev):\n datapath = ev.msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n dpid = datapath.id\n\n self.logger.info(\"Switch %d connected, adding flow entries.\", dpid)\n match = parser.OFPMatch(in_port=1)\n actions = [parser.OFPActionOutput(2, ofproto.OFPCML_NO_BUFFER)]\n # Flow entry match structure: priority=0,in_port=1 actions=output:2\n self.add_flow(datapath, 0, match, actions)\n\n match = parser.OFPMatch(in_port=2)\n actions = [parser.OFPActionOutput(1, ofproto.OFPCML_NO_BUFFER)]\n # Flow entry match structure: priority=0,in_port=2 actions=output:1\n self.add_flow(datapath, 0, match, actions)\n\n if dpid == 2:\n match = parser.OFPMatch(in_port=1, eth_type=PROTO_IP,\n ip_proto=PROTO_TCP, tcp_dst=80)\n actions = [parser.OFPActionOutput(2, ofproto.OFPCML_NO_BUFFER),\n parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,\n ofproto.OFPCML_NO_BUFFER)]\n # Flow entry match structure:\n # priority=1,tcp,in_port=1,tp_dst=80\n # actions=output:2,CONTROLLER:65535\n self.add_flow(datapath, 1, match, actions)\n\n @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)\n def _packet_in_handler(self, ev):\n msg = ev.msg\n datapath = msg.datapath\n parser = datapath.ofproto_parser\n in_port = msg.match['in_port']\n dpid = datapath.id\n pkt = packet.Packet(msg.data)\n eth = pkt.get_protocols(ethernet.ethernet)[0]\n dst = eth.dst\n src = eth.src\n tcp_p = pkt.get_protocols(tcp.tcp)\n\n if dpid != 2 or src in self.macs or len(tcp_p) == 0:\n return\n\n tcp_p = tcp_p[0]\n if tcp_p.ack <= 1: # TCP three-way handshake and HTTP request\n return\n\n self.logger.info(\"First HTTP request from %s, adding flow entry.\", src)\n\n self.macs.append(src)\n actions = []\n match = parser.OFPMatch(in_port=in_port, eth_src=src, eth_dst=dst,\n eth_type=PROTO_IP, ip_proto=PROTO_TCP,\n tcp_dst=80)\n # Flow entry match structure:\n # priority=2,tcp,in_port=1,dl_src=xx:xx:xx:xx:xx:xx,\n # dl_dst=xx:xx:xx:xx:xx:xx,tp_dst=80 actions=drop\n self.add_flow(datapath, 2, match, actions, hard_timeout=60)\n\n def add_flow(self, datapath, priority, match, actions, hard_timeout=None):\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,\n actions)]\n if hard_timeout:\n mod = parser.OFPFlowMod(datapath=datapath, priority=priority,\n match=match, instructions=inst,\n hard_timeout=hard_timeout)\n else:\n mod = parser.OFPFlowMod(datapath=datapath, priority=priority,\n match=match, instructions=inst)\n datapath.send_msg(mod)\n","sub_path":"preliminary/upload/1.2/1_2.py","file_name":"1_2.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"376274277","text":"# Defines the html_to_pdf method using PISA:\n# http://github.com/holtwick/xhtml2pdf\n\nsimple_options = []\nvalued_options = []\n\n\ndef html_to_pdf(source, export_dir, filename, original_url,\n use_print_css, extra_options=[]):\n # We import pisa inside the function so it does not raise\n # import exception if pisa is not installed.\n try:\n # First try newer version of library under a different name.\n import xhtml2pdf.pisa as pisa\n pisa # pyflakes\n except ImportError:\n # Try the old library. Note that you can also get the above\n # ImportError simply because you are on Python 2.4 and\n # xhtml2pdf.pisa tries and fails to import hashlib.\n import ho.pisa as pisa\n\n file_path = '%s/%s' % (export_dir, filename)\n\n pdf_file = file(file_path, \"wb\")\n link_callback = pisa.pisaLinkLoader(original_url).getFileName\n\n pdf = pisa.CreatePDF(source,\n pdf_file,\n log_warn=1,\n log_err=1,\n path=original_url,\n link_callback=link_callback,\n )\n\n if pdf.err:\n return None, pdf.err\n\n return pdf_file, None\n","sub_path":"collective/sendaspdf/transforms/pisa.py","file_name":"pisa.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"542298678","text":"import turtle as tl\npen_size = 50\nlength = 100\ndepth = 10\n\n\n# window = tl.Screen()\n# window.screensize(1366, 768)\n# window.setup(width=1.0, height=1.0, startx=None, starty=None)\n\ndef signature():\n tl.home()\n tl.up()\n tl.goto(-150, 250)\n tl.down()\n tl.write(\"Drawing tree using recursion\", font=(\"Arial\", 16, \"normal\"))\n tl.up()\n tl.goto(-150, 230)\n tl.down()\n tl.write(\"~Tanvir Ahmed\", font=(\"Arial\", 11, \"normal\"))\n tl.up()\n tl.home()\n tl.down()\ndef create_branches(n, length, p_size):\n\n if n == 0 :\n return\n \n tl.pendown()\n tl.left(30)\n if n < 6:\n tl.pencolor('green')\n else:\n tl.pencolor('#572a10')\n tl.pensize(p_size)\n tl.forward(length)\n create_branches(n-1, length/1.5, p_size/2)\n tl.penup()\n tl.backward(length)\n tl.right(60)\n tl.pendown()\n if n < 6:\n tl.pencolor('green')\n else:\n tl.pencolor('#572a10')\n tl.pensize(p_size)\n tl.forward(length)\n create_branches(n-1, length/1.5, p_size/2)\n tl.penup()\n tl.backward(length)\n tl.left(30)\n\nsignature()\ntl.up()\ntl.home()\ntl.goto(0, -275)\n# tl.forward(250)\ntl.left(90)\n# tl.goto((0, -330))\n\ntl.pendown()\ntl.pencolor('#572a10')\ntl.pensize(pen_size)\ntl.forward(120)\ntl.speed(6)\ncreate_branches(depth, length, pen_size/2)\ntl.hideturtle()\n\n\n\n\ntl.exitonclick()","sub_path":"gradually_smaller_length_branch_colored.py","file_name":"gradually_smaller_length_branch_colored.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"430873280","text":"#!/usr/bin/env python3\nimport sys\nimport json\nimport socket\n\nHOST, PORT = ('localhost', 3876)\n\n\nclass MyClient:\n def _send_request(self, data):\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n sock.connect((HOST, PORT))\n sock.sendall('{}\\n'.format(json.dumps(data)).encode('utf-8'))\n received = str(sock.recv(1024), 'utf-8')\n print(\"Teller received: {}\".format(received))\n return received\n\n def check_balance(self):\n data = {'cmd': 'balance'}\n self._send_request(data)\n\n def deposit(self, amount):\n data = {'cmd': 'deposit', 'amount': int(amount)}\n self._send_request(data)\n\n def withdraw(self, amount):\n data = {'cmd': 'withdraw', 'amount': int(amount)}\n self._send_request(data)\n\n def unknown(self, command):\n data = {'cmd': command}\n self._send_request(data)\n\n def execute(self, command, *args):\n args = tuple([arg for arg in args if arg])\n commands = {\n 'deposit': self.deposit,\n 'balance': self.check_balance,\n 'withdraw': self.withdraw\n }\n\n func = commands.get(command, None)\n\n if func:\n return func(*args)\n else:\n return self.unknown(command)\n\n\ndef main(argv):\n client = MyClient()\n\n command = argv[1]\n args = argv[2:] or []\n client.execute(command, *args)\n\n\nif __name__ == '__main__':\n main(sys.argv)\n\n","sub_path":"boilerplate/python/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"232401165","text":"# just like Prim\nimport sys\n\ndef solve(graph_grid, start_vertex):\n vertex_count = len(graph_grid)\n if vertex_count == 0: return None\n handled = [False] * vertex_count\n distances = [sys.maxint] * vertex_count\n\n distances[start_vertex] = 0\n\n for _ in xrange(vertex_count):\n _, src = min((w, i) for i, w in enumerate(distances) if not handled[i])\n # src.p()\n handled[src] = True\n\n for dst in xrange(vertex_count):\n if src != dst and not handled[dst] \\\n and graph_grid[src][dst] > 0 \\\n and distances[dst] > distances[src] + graph_grid[src][dst]:\n distances[dst] = distances[src] + graph_grid[src][dst]\n return distances\n\nif __name__ == '__main__':\n from minitest import *\n\n with test(solve):\n graph_grid = [ \n [0, 4, 0, 0, 0, 0, 0, 8, 0],\n [4, 0, 8, 0, 0, 0, 0, 11, 0],\n [0, 8, 0, 7, 0, 4, 0, 0, 2],\n [0, 0, 7, 0, 9, 14, 0, 0, 0],\n [0, 0, 0, 9, 0, 10, 0, 0, 0],\n [0, 0, 4, 14, 10, 0, 2, 0, 0],\n [0, 0, 0, 0, 0, 2, 0, 1, 6],\n [8, 11, 0, 0, 0, 0, 1, 0, 7],\n [0, 0, 2, 0, 0, 0, 6, 7, 0],\n ]\n solve(graph_grid, 0).must_equal([0, 4, 12, 19, 21, 11, 9, 8, 14])\n","sub_path":"python/leetcode/algorithm/greedy/geeksforgeeks/top_07_Dijkstra_shortest_path_with_Adjacency_Matrix.py","file_name":"top_07_Dijkstra_shortest_path_with_Adjacency_Matrix.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"364707978","text":"from __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport keras\nimport cv2\nimport time\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten, Activation\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.optimizers import Adam\nfrom keras.models import load_model\nfrom keras.utils import plot_model, to_categorical\nfrom keras.applications import VGG16\n\nos.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'\n\ndef initialise_model(input_shape, classes, base):\n\tmodel = Sequential()\n\tmodel.add(base)\n\tmodel.add(Flatten())\n\tmodel.add(Dense(512, activation='relu', input_dim=1*1*512))\n\tmodel.add(Dropout(0.5))\n\tmodel.add(Dense(10, activation='softmax'))\n\treturn model\n\ndef main():\n\ttrain_data = 'ArtificialDigits/ArtificialDigits/Dataset_Digits/Test'\n\tvalid_data = 'ArtificialDigits/ArtificialDigits/Dataset_Digits/Validate'\n\ttester_data = 'ArtificialDigits/ArtificialDigits/Dataset_Digits/Tester'\n\theight = 48\n\twidth = 48\n\tt_samps = 700\n\tt_valid = 140\n\tepochs = 35\n\tbatch_size = 20\n\tclasses = 10\n\n\tif K.image_data_format() == 'channels_first':\n\t\tinput_shape = (3, width, height)\n\telse:\n\t\tinput_shape = (width, height, 3)\n\n\tvgg_conv = VGG16(\n\t\t\t\t\t weights=None,\n\t\t\t\t\t include_top=False,\n\t\t\t\t\t input_shape=input_shape)\n\n\ttrain_dgen = ImageDataGenerator(\n\t\trescale = 1./2,\n\t\tshear_range=0.2,\n\t\tzoom_range=0.2,\n\t\trotation_range=40,\n\t\twidth_shift_range=0.2,\n\t\theight_shift_range=0.2,\n\t\thorizontal_flip=False)\n\t\n\ttest1_dgen = ImageDataGenerator(\n\t\trescale = 1./2)\n\t\n\ttest_dgen = ImageDataGenerator(\n\t\trescale = 1./2,\n\t\tshear_range=0.2,\n\t\tzoom_range=0.2,\n\t\trotation_range=40,\n\t\twidth_shift_range=0.2,\n\t\theight_shift_range=0.2,\n\t\thorizontal_flip=False)\n\t\n\ttrain_generator = train_dgen.flow_from_directory(\n\t\ttrain_data,\n\t\ttarget_size=(width, height),\n\t\tbatch_size=batch_size,\n\t\tclass_mode='categorical')\n\n\tvalid_generator = test_dgen.flow_from_directory(\n\t\tvalid_data,\n\t\ttarget_size=(width, height),\n\t\tbatch_size=batch_size,\n\t\tclass_mode='categorical')\n\n\ttest_generator = test1_dgen.flow_from_directory(\n\t\ttester_data,\n\t\ttarget_size=(width, height),\n\t\tbatch_size=batch_size,\n\t\tclass_mode='categorical',\n\t\tshuffle=False)\n\n\tmodel = initialise_model(input_shape, classes, vgg_conv)\n\n\tADAM = Adam(lr=0.0001)\n\tmodel.compile(optimizer=ADAM, loss='categorical_crossentropy', metrics=['acc'])\n\tprint(model.summary())\n\t'''\n\tt_start = time.time()\n\thistory = model.fit_generator(train_generator,\n\t\t\t\t\t\tsteps_per_epoch=t_samps//batch_size,\n\t\t\t\t\t\tepochs=epochs,\n\t\t\t\t\t\tvalidation_data=valid_generator,\n\t\t\t\t\t\tvalidation_steps=t_valid//batch_size)\n\tt_elapsed = time.time() - t_start\n\n\tprint(\"Time: \" + str(t_elapsed))\n\t\n\tmodel.save_weights('VGG_untrained_aug.h5')\n\n\t# Accuracy and Validation Graphs\n\tplt.rcParams['figure.figsize'] = (6,5)\n\tplt.plot(history.history['acc'])\n\tplt.plot(history.history['val_acc'])\n\tplt.title( \"Accuracy \")\n\tplt.ylabel('Accuracy')\n\tplt.xlabel('Epoch')\n\tplt.legend(['train', 'val'], loc='upper left')\n\tplt.show()\n\tplt.close()\n\t# summarize history for loss\n\tplt.plot(history.history['loss'])\n\tplt.plot(history.history['val_loss'])\n\tplt.title(\"Error\")\n\tplt.ylabel('Loss')\n\tplt.xlabel('Epoch')\n\tplt.legend(['train', 'val'], loc='upper right')\n\tplt.show()\n\tplt.close()\n\t\n\t'''\n\tmodel.load_weights('VGG_untrained_unaug.h5')\n\t#plot_model(model, to_file='model_VGG_untrained.png')\n\n\tplot_model(model, to_file='model_basic.png')\n\tevaluation = model.evaluate_generator(test_generator)\n\tprint(evaluation)\n\n\tpredictions = model.predict_generator(test_generator)\n\t\n\tpredictions = np.argmax(predictions, axis=-1)\n\tlabel_map = (train_generator.class_indices)\n\tlabel_map = dict((v,k) for k, v in label_map.items())\n\tpredictions = [label_map[k] for k in predictions]\n\n\tincorrect = []\n\tinc_i = []\n\tcount = 0\n\tfor i in range(len(predictions)):\n\t\tif predictions[i] == test_generator.filenames[i][0]:\n\t\t\tcount = count + 1\n\t\telse:\n\t\t\tincorrect.append(test_generator.filenames[i])\n\t\t\tinc_i.append(i)\n\n\n\tprint(\"Correct prediction rate: \"+str(100*count/len(predictions))+\"%\")\n\t\n\tprint(\"Incorrect Predictions: \")\n\tfor i in range(len(incorrect)):\n\t\timg = cv2.imread(tester_data+\"/\"+incorrect[i], 0)\n\t\tcv2.imshow(\"Incorrect\", img)\n\t\tprint(\"Correct Label: \"+str(incorrect[i][0])+\", Predicted Label: \"+str(predictions[inc_i[i]]))\n\t\tcv2.waitKey(0)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"digit/digit_CNN/digit_cnn_untrained.py","file_name":"digit_cnn_untrained.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"125497446","text":"import sublime as _sublime\r\nfrom collections import namedtuple as _namedtuple\r\nimport os as _os\r\n\r\n\r\nFTYPE_EXT_KEYMAP = \".sublime-keymap\"\r\nFTYPE_EXT_COMPLETIONS = \".sublime-completions\"\r\nFTYPE_EXT_SNIPPET = \".sublime-snippet\"\r\nFTYPE_EXT_BUILD = \".sublime-build\"\r\nFTYPE_EXT_SETTINGS = \".sublime-settings\"\r\nFTYPE_EXT_TMPREFERENCES = \".tmPreferences\"\r\nFTYPE_EXT_TMLANGUAGE = \".tmLanguage\"\r\n\r\n\r\ndef root_at_packages(*leafs):\r\n \"\"\"Combines leafs with path to Sublime's Packages folder.\r\n \"\"\"\r\n return _os.path.join(_sublime.packages_path(), *leafs)\r\n\r\n\r\ndef root_at_data(*leafs):\r\n \"\"\"Combines leafs with Sublime's ``Data`` folder.\r\n \"\"\"\r\n data = _os.path.join(_os.path.split(_sublime.packages_path())[0])\r\n return _os.path.join(data, *leafs)\r\n\r\n\r\nFilePath = _namedtuple(\"FilePath\", \"file_path path file_name base_name ext no_ext\")\r\n\r\n\r\ndef file_path_tuple(file_path):\r\n \"\"\"Creates a named tuple with the following attributes:\r\n file_path, path, file_name, base_name, ext, no_ext\r\n \"\"\"\r\n path, file_name = _os.path.split(file_path)\r\n base_name, ext = _os.path.splitext(file_name)\r\n return FilePath(\r\n file_path,\r\n path,\r\n file_name,\r\n base_name,\r\n ext,\r\n no_ext=_os.path.join(path, base_name)\r\n )\r\n","sub_path":"Lib/sublime_lib/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"59883500","text":"import statistics, math, openpyxl\nimport numpy as np\nfrom datetime import datetime\nfrom openpyxl import Workbook\n\nbasedir = '/home/cwp/EMC/lib/analysis/variation/temporal/'\n\ndef get(path):\n data = []\n with open(path,'r') as f:\n lines = f.readlines()\n for line in lines:\n data.append(line.split('\\n')[0])\n\n return data\n\ndef day(datas, times):\n plotTimes = []\n plotData = []\n plotErr = []\n\n for day in range(1, 32):\n print(day)\n currentData = []\n\n for i in range(len(datas)):\n currentDate = datetime.strptime(times[i], \"%Y-%m-%d %H:%M:%S\")\n if (currentDate.day == day):\n currentData.extend([int(x) for x in datas[i].split(',')])\n\n if len(currentData) != 0:\n plotTimes.append(day)\n plotData.append(statistics.mean(currentData))\n if len(currentData) > 1:\n plotErr.append(statistics.stdev(currentData)/math.sqrt(len(currentData)))\n else:\n plotErr.append(1)\n else:\n plotErr.append(None)\n plotData.append(None)\n plotTimes.append(day)\n\n finalData = np.ma.masked_object(plotData, None)\n finalErr = np.ma.masked_object(plotErr, None)\n\n return plotTimes, finalData, finalErr\n\ndef month(datas, times):\n plotTimes = []\n plotData = []\n plotErr = []\n\n for month in range(1,13):\n print(month)\n currentData = []\n\n for i in range(len(datas)):\n currentDate = datetime.strptime(times[i], \"%Y-%m-%d %H:%M:%S\")\n if (currentDate.month == month):\n currentData.extend([int(x) for x in datas[i].split(',')])\n\n if len(currentData) != 0:\n plotTimes.append(month)\n plotData.append(statistics.mean(currentData))\n if len(currentData) > 1:\n plotErr.append(statistics.stdev(currentData)/math.sqrt(len(currentData)))\n else:\n plotErr.append(1)\n else:\n plotErr.append(None)\n plotData.append(None)\n plotTimes.append(month)\n\n finalData = np.ma.masked_object(plotData, None)\n finalErr = np.ma.masked_object(plotErr, None)\n\n return finalData, finalErr, plotTimes\n\ndef year(datas, times):\n plotTimes = []\n plotData = []\n plotErr = []\n\n for year in range(2000,2017):\n print(year)\n currentData = []\n\n for i in range(len(datas)):\n currentDate = datetime.strptime(times[i], \"%Y-%m-%d %H:%M:%S\")\n if (currentDate.year == year):\n currentData.extend([int(x) for x in datas[i].split(',')])\n\n if len(currentData) != 0:\n plotTimes.append(year)\n plotData.append(statistics.mean(currentData))\n if len(currentData) > 1:\n plotErr.append(statistics.stdev(currentData)/math.sqrt(len(currentData)))\n else:\n plotErr.append(1)\n else:\n plotErr.append(None)\n plotData.append(None)\n plotTimes.append(year)\n\n finalData = np.ma.masked_object(plotData, None)\n finalErr = np.ma.masked_object(plotErr, None)\n\n return finalData, finalErr, plotTimes\n\ndef yearmonth(datas, times):\n plotTimes = []\n plotData = []\n plotErr = []\n\n for year in range(2000,2017):\n print(year)\n for month in range(1,13):\n print(month)\n currentData = []\n\n for i in range(len(datas)):\n currentDate = datetime.strptime(times[i], \"%Y-%m-%d %H:%M:%S\")\n if (currentDate.year == year) and (currentDate.month == month):\n currentData.extend([int(x) for x in datas[i].split(',')])\n\n if len(currentData) != 0:\n plotTimes.append(datetime.strptime(str(year)+'-'+'{0:02d}'.format(month), \"%Y-%m\"))\n plotData.append(statistics.mean(currentData))\n if len(currentData) > 1:\n plotErr.append(statistics.stdev(currentData)/math.sqrt(len(currentData)))\n else:\n plotErr.append(1)\n else:\n plotErr.append(None)\n plotData.append(None)\n plotTimes.append(datetime.strptime(str(year)+'-'+'{0:02d}'.format(month), \"%Y-%m\"))\n\n finalData = np.ma.masked_object(plotData, None)\n finalErr = np.ma.masked_object(plotErr, None)\n\n return finalData, finalErr, plotTimes\n\nNdata_full = get(basedir+'NS/NplotData.txt')\nNtimes_full = get(basedir+'NS/NplotTimes.txt')\n\ndata_full = get('/home/cwp/EMC/lib/analysis/plotData.txt')\ntimes_full = get('/home/cwp/EMC/lib/analysis/plotTimes.txt')\n\nNday_times, Nday_data, Nday_err = day(Ndata_full, Ntimes_full)\nday_times, day_data, day_err = day(data_full, times_full)\n\nNmonth_data, Nmonth_err, Nmonth_times = month(Ndata_full, Ntimes_full)\nmonth_data, month_err, month_times = month(data_full, times_full)\n\nNyear_data, Nyear_err, Nyear_times = year(Ndata_full,Ntimes_full)\nyear_data, year_err, year_times = year(data_full,times_full)\n\nNyearmonth_data, Nyearmonth_err, Nyearmonth_times = yearmonth(Ndata_full,\\\n Ntimes_full)\nyearmonth_data, yearmonth_err, yearmonth_times = yearmonth(data_full,\\\n times_full)\n\nwb = Workbook()\n\nsavefile = 'data.xlsx'\n\nws1 = wb.active\nws1.title = \"Full data\"\nws2 = wb.create_sheet(title=\"Day scale\")\nws3 = wb.create_sheet(title=\"Month scale\")\nws4 = wb.create_sheet(title=\"Year scale\")\nws5 = wb.create_sheet(title=\"Year-month scale\")\n\ndef enterIntoWorkbook(wb, ws, lists, titles, startCol):\n for i in range(startCol,startCol+len(lists)):\n ws.cell(column=i,row=1, value=titles[i-startCol])\n for j in range(1,len(lists[i-startCol])+1):\n ws.cell(column=i,row=j+1,value=lists[i-startCol][j-1])\n\n wb.save(filename = savefile)\n\nenterIntoWorkbook(wb,ws1,[times_full,data_full],[\"Time\", \"Data\"],1)\nenterIntoWorkbook(wb,ws1,[Ntimes_full,Ndata_full],[\"N_Time\", \"N_Data\"],4)\n\nenterIntoWorkbook(wb,ws2,[day_times,day_data,day_err],[\"Time\",\"Data\",\"SE\"],1)\nenterIntoWorkbook(wb,ws2,[Nday_times,Nday_data,Nday_err],[\"N_Time\",\"N_Data\",\"N_SE\"],4)\n\nenterIntoWorkbook(wb,ws3,[month_times,month_data,month_err],[\"Time\",\"Data\",\"SE\"],1)\nenterIntoWorkbook(wb,ws3,[Nmonth_times,Nmonth_data,Nmonth_err],[\"N_Time\",\"N_Data\",\"N_SE\"],4)\n\nenterIntoWorkbook(wb,ws4,[year_times,year_data,year_err],[\"Time\",\"Data\",\"SE\"],1)\nenterIntoWorkbook(wb,ws4,[Nyear_times,Nyear_data,Nyear_err],[\"N_Time\",\"N_Data\",\"N_SE\"],4)\n\nenterIntoWorkbook(wb,ws5,[yearmonth_times,yearmonth_data,yearmonth_err],[\"Time\",\"Data\",\"SE\"],1)\nenterIntoWorkbook(wb,ws5,[Nyearmonth_times,Nyearmonth_data,Nyearmonth_err],[\"N_Time\",\"N_Data\",\"N_SE\"],4)\n","sub_path":"lib/analysis/variation/temporal/NS/transferData.py","file_name":"transferData.py","file_ext":"py","file_size_in_byte":6678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"12903263","text":"\"\"\"Implements contact form admin interface\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom django.contrib import admin\nfrom django.utils.translation import ugettext as _\nfrom django.conf import settings as django_settings\n\nfrom contact_form.models import *\nfrom contact_form.conf import settings\n\n\nclass MessageAdmin(admin.ModelAdmin):\n if hasattr(django_settings, 'SITE_ID') and settings.CONTACT_FORM_USE_SITES:\n #list_display = ('subject', 'sender', 'ip', 'site', 'date_created_short')\n list_display = ('sender', 'ip', 'site', 'date_created_short')\n #list_filter = ('date_created', 'subject')\n list_filter = ('date_created',)\n search_fields = ('sender_name', 'ip', 'site', 'date_created')\n else:\n #list_display = ('subject', 'sender', 'ip', 'date_created_short')\n #list_filter = ('date_created', 'subject')\n list_display = ('sender', 'ip', 'site', 'date_created_short')\n list_filter = ('date_created',)\n\n\n search_fields = ('sender_name', 'ip', 'date_created')\n exclude = ('site', )\n\n def sender(self, obj):\n return 's}\">{1:>s}'.format(obj.sender_email, obj.sender_name)\n sender.allow_tags = True\n sender.short_description = _('Sender')\n\n def date_created_short(self, obj):\n return obj.date_created.strftime('%Y/%m/%d %H:%M:%S')\n date_created_short.short_description = _('Created')\n date_created_short.admin_order_field = 'date_created'\n\nadmin.site.register(Message, MessageAdmin)\n","sub_path":"contact_form/admin/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"362494202","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statsmodels.api\n\n# Read the csv file\ndf = pd.read_csv('/Users/juanpamurillo/Dropbox/LoanStats3b.csv', header=1, low_memory=False)\n\n# Add a new column 'issue_d_format'\n# 'issue_d_format' is column 'issue_d' in date format\ndf['issue_d_format'] = pd.to_datetime(df['issue_d']) \n\n# Comparing formats\n#print df.issue_d.head() #before\n#0 Dec-2013\n#1 Dec-2013\n#2 Dec-2013\n#3 Dec-2013\n#4 Dec-2013\n#print df.issue_d_format.head() #after\n#0 2013-12-16\n#1 2013-12-16\n#2 2013-12-16\n#3 2013-12-16\n#4 2013-12-16\n\n# Create a new dataframe dfts with 'issue_d_format as the index'\ndfts = df.set_index('issue_d_format') \n\n# Create a new dataframe year_month_summary\n# a dataframe grouped by a new index: year*100 + month\n# Example: 201301 is January 2013\nyear_month_summary = dfts.groupby(lambda x : x.year * 100 + x.month).count()\n\n# Create a new dataframe loan_count_summary\n# Contains the index and 'issue_d'\nloan_count_summary = year_month_summary['issue_d']\n\n# Plot the data loan_count_summary\nplt.plot(loan_count_summary)\nplt.show()\n\n# Plotting the autocorrelation function\nstatsmodels.api.graphics.tsa.plot_acf(loan_count_summary)\nplt.show()\n\n# Plotting the partial autocorrelation function\nstatsmodels.api.graphics.tsa.plot_pacf(loan_count_summary)\nplt.show()","sub_path":"time_series.py","file_name":"time_series.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"551336027","text":"import os\n\nimport config\n\nimport pandas as pd\n\nimport pickle\n\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nfrom time import sleep\n\n\n\ndef login_to_ff(home_url, transfer_url, delay, driver):\n driver.get(home_url)\n sleep(delay)\n username_el = driver.find_element_by_css_selector('#loginUsername')\n password_el = driver.find_element_by_css_selector('#loginPassword')\n query = '#root > div:nth-child(2) > div > div > div.sc-bdVaJa.edJDIA > form'\n login = driver.find_element_by_css_selector(query) \\\n .find_element_by_tag_name('button') \n # Enter username/password and log in\n username_el.send_keys(config.fantasy_email)\n password_el.send_keys(config.fantasy_password)\n login.click()\n sleep(delay)\n # Open the transfer page\n driver.get(transfer_url)\n sleep(delay)\n\n# Deprecated\ndef get_current_team(driver):\n # Get the current list of players and prices\n query = 'div.sc-bdVaJa.sc-bwzfXH.Pitch__ElementRow-sc-1mctasb-1.Pitch__PitchRow-sc-1mctasb-2.iZgvKz'\n player_rows = driver.find_elements_by_css_selector(query)\n row_text = []\n for row in player_rows:\n row = row.text.split('\\n')\n for x in row:\n row_text.append(x)\n current_players = [\n x for i,x in enumerate(row_text) if (i/2).is_integer()\n ]\n current_prices = [\n float(x) for i,x in enumerate(row_text) if not (i/2).is_integer()\n ]\n #team_size = len(current_players)\n \n player_price = pd.DataFrame(\n {'team_players':current_players,'sell_price':current_prices}\n )\n player_price = player_price[['team_players','sell_price']]\n \n return player_price, {'Sell Price': sum(player_price['sell_price'])}\n\n\ndef get_scoreboard_info(driver):\n info = {}\n query = 'div.Scoreboard__CostScoreboardUnit-sc-117tw9n-1.cMrwVx'\n transferboard_elements = driver.find_elements_by_css_selector(query)\n wild_card_status = transferboard_elements[2].text\n if wild_card_status == 'Play Wildcard':\n wild_card_status = True\n else:\n wild_card_status = False\n free_transfers = transferboard_elements[3].text.split('\\n')[1]\n bank_money = float(transferboard_elements[5].text.split('\\n')[1])\n info['Wild Card'] = wild_card_status\n info['Free Transfers'] = free_transfers\n info['Bank Money'] = bank_money\n return info\n\n\n# Grab starting line up and captain and vice_captain info\ndef get_line_up(team_url, delay, driver):\n # Go to the team select page\n driver.get(team_url)\n sleep(delay)\n\n s_team_rows = driver.find_elements_by_css_selector('div.sc-bdVaJa.sc-bwzfXH.Pitch__ElementRow-sc-1mctasb-1.Pitch__PitchRow-sc-1mctasb-2.iZgvKz')\n \n players = []\n is_captain = []\n is_v_captain = []\n is_bench = []\n for row in s_team_rows:\n units = row.find_elements_by_css_selector('div.Pitch__PitchUnit-sc-1mctasb-3.gYXrCB')\n for unit in units:\n player = unit.find_elements_by_css_selector('div.PitchElementData__ElementName-sc-1u4y6pr-0.hZsmkV')\n if not len(player) == 0:\n is_bench.append(0)\n #players.append(player[0].text)\n player[0].click()\n sleep(0.5)\n player_text = driver.find_element_by_css_selector('div.Dialog__StyledHeader-sc-5bogmv-5.BHTvj').text\n players.append(player_text.split('\\n')[0])\n dia_box = driver.find_element_by_css_selector('div.Dialog__StyledDialogBody-sc-5bogmv-7.heKQNQ')\n lis = dia_box.find_elements_by_tag_name('li')\n if len(lis) == 3:\n if 'Make Captain' in lis[1].text:\n is_v_captain.append(1)\n is_captain.append(0)\n elif 'Make Vice Captain' in lis[1].text:\n is_captain.append(1)\n is_v_captain.append(0)\n else:\n is_captain.append(0)\n is_v_captain.append(0)\n \n ActionChains(driver).send_keys(Keys.ESCAPE).perform()\n sleep(0.5)\n\n b_team_row = driver.find_element_by_css_selector('div.Bench-sc-1sz52o9-0.gujtGz')\n units = b_team_row.find_elements_by_css_selector('div.PitchElementData__ElementName-sc-1u4y6pr-0.hZsmkV')\n for unit in units:\n unit.click()\n sleep(0.5)\n player_text = driver.find_element_by_css_selector('div.Dialog__StyledHeader-sc-5bogmv-5.BHTvj').text\n players.append(player_text.split('\\n')[0])\n is_captain.append(0)\n is_v_captain.append(0)\n is_bench.append(1)\n ActionChains(driver).send_keys(Keys.ESCAPE).perform()\n sleep(0.5)\n \n df = pd.DataFrame({\n 'team_players':players,\n 'is_captain':is_captain,\n 'is_v_captain':is_v_captain,\n 'is_bench': is_bench\n })\n return df\n\n\ndef get_cards_status(scoreboard, driver):\n cards = driver.find_elements_by_css_selector('li.MyTeam__ChipItem-sc-6ytjxx-2.bDjYjd')\n for card in cards:\n card_data = card.text.split('\\n')\n if card_data[1] == 'PLAY':\n scoreboard[card_data[0]] = 1\n else:\n scoreboard[card_data[0]] = 0\n return scoreboard\n \n\ndef save_team_info(team):\n path = f'{os.path.dirname(os.getcwd())}\\\\data\\\\Team\\\\Team_info.pk'\n with open(path, 'wb') as f:\n pickle.dump(team, f)\n\n\ndef get_transfer_info(home_url, transfer_url, team_url, delay, driver):\n login_to_ff(home_url, transfer_url, delay, driver)\n info = get_scoreboard_info(driver)\n df = get_line_up(team_url, delay, driver)\n team_info = {\n 'players': df,\n 'info': get_cards_status(info, driver)\n }\n save_team_info(team_info)\n\n\ndef collect(driver):\n print('Collecting team info...')\n delay = 2\n home_url = 'https://fantasy.premierleague.com'\n transfer_url = 'https://fantasy.premierleague.com/a/squad/transfers'\n team_url = 'https://fantasy.premierleague.com/a/team/my'\n get_transfer_info(home_url, transfer_url, team_url, delay, driver)\n","sub_path":"src/web-scrapers/GetTeamInfo.py","file_name":"GetTeamInfo.py","file_ext":"py","file_size_in_byte":6208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"378128434","text":"from numpy import pi,exp,log,abs,sum,sqrt,array, hanning, arange, zeros,cos,ceil,mean\n\nfrom scipy.signal import filtfilt,butter,hilbert,decimate\n\nfrom acousticsim.representations.base import Representation\nfrom acousticsim.representations.helper import (preproc, resample,\n nextpow2,fftfilt)\n\n\n\ndef window_envelopes(env, win_len, time_step):\n if env.is_windowed:\n return\n nperseg = int(win_len * env.sampling_rate)\n if nperseg % 2 != 0:\n nperseg -= 1\n nperstep = int(time_step * env.sampling_rate)\n window = hanning(nperseg+2)[1:nperseg+1]\n halfperseg = int(nperseg/2)\n\n print(nperseg, halfperseg)\n num_samps, num_bands = env.shape\n print(env.shape)\n indices = arange(halfperseg, num_samps - halfperseg + 1, nperstep)\n num_frames = len(indices)\n print(indices)\n rep = zeros((num_frames,num_bands))\n new_rep = dict()\n for i in range(num_frames):\n print(indices[i])\n time_key = indices[i]/env.sampling_rate\n rep_line = list()\n print(indices[i] - halfperseg, indices[i] + halfperseg)\n array = env[indices[i] - halfperseg, indices[i] + halfperseg]\n print(array.shape)\n for b in range(num_bands):\n rep_line.append(sum(array[:, b]))\n new_rep[time_key] = rep_line\n env._rep = new_rep\n env.is_windowed = True\n return env\n\nclass Envelopes(Representation):\n def __init__(self,filepath,freq_lims,num_bands, attributes = None):\n Representation.__init__(self, filepath,freq_lims, attributes)\n\n self._num_bands = num_bands\n\n self.process()\n\n\n def process(self, mode = 'downsample', debug = False):\n \"\"\"Generate amplitude envelopes from a full path to a .wav, following\n Lewandowski (2012).\n\n Parameters\n ----------\n filename : str\n Full path to .wav file to process.\n freq_lims : tuple\n Minimum and maximum frequencies in Hertz to use.\n num_bands : int\n Number of frequency bands to use.\n win_len : float, optional\n Window length in seconds for using windows. By default, the\n envelopes are resampled to 120 Hz instead of windowed.\n time_step : float\n Time step in seconds for windowing. By default, the\n envelopes are resampled to 120 Hz instead of windowed.\n\n Returns\n -------\n 2D array\n Amplitude envelopes over time. If using windowing, the first\n dimension is the time in frames, but by default the first\n dimension is time in samples with a 120 Hz sampling rate.\n The second dimension is the amplitude envelope bands.\n\n \"\"\"\n self._sr, proc = preproc(self._filepath,alpha=0.97)\n\n proc = proc / 32768 #hack!! for 16-bit pcm\n proc = proc/sqrt(mean(proc**2))*0.03;\n bandLo = [ self._freq_lims[0]*exp(log(\n self._freq_lims[1]/self._freq_lims[0]\n )/self._num_bands)**x\n for x in range(self._num_bands)]\n bandHi = [ self._freq_lims[0]*exp(log(\n self._freq_lims[1]/self._freq_lims[0]\n )/self._num_bands)**(x+1)\n for x in range(self._num_bands)]\n\n envs = []\n for i in range(self._num_bands):\n b, a = butter(2,(bandLo[i]/(self._sr/2),bandHi[i]/(self._sr/2)), btype = 'bandpass')\n env = filtfilt(b,a,proc)\n env = abs(hilbert(env))\n if mode == 'downsample':\n env = resample(env, 120/self._sr, precision = 3)\n #print(int(ceil(self._sr/120)))\n #env = decimate(env,int(ceil(self._sr/120)))\n\n #env = env/max(env)\n envs.append(env)\n envs = array(envs).T\n if mode == 'downsample':\n self._sr = 120\n self._rep = dict()\n for i in range(envs.shape[0]):\n self._rep[i/self._sr] = envs[i,:]\n #Don't know if this is the best way to do it\n if debug:\n return proc\n","sub_path":"acousticsim/representations/amplitude_envelopes.py","file_name":"amplitude_envelopes.py","file_ext":"py","file_size_in_byte":4199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"349516691","text":"#test function fot pytest\n\nfrom syllable import obtain_syllable, get_word_by_syllable,\\\n obtain_syllable_parameters\n\n\n\n'''\nobtain_syllable\n'''\ndef test_obtain_syllable():\n current_letter_number=3\n letter_number=4\n word_by_letters=list('объезд')\n assert obtain_syllable(current_letter_number, letter_number,\n word_by_letters) == 'ез'\n\n\ndef test_obtain_syllable():\n current_letter_number=4\n letter_number=5\n word_by_letters=list('бакалаврский')\n assert obtain_syllable(current_letter_number, letter_number,\n word_by_letters, third_condition=True) == 'лав'\n\n\n'''\nget_word_by_syllable\n'''\ndef test_get_word_by_syllable():\n word_incoming='бледность'\n assert get_word_by_syllable(word_incoming) == ['блед', 'ность']\n\n\ndef test_get_word_by_syllable():\n word_incoming='бакалаврский'\n assert get_word_by_syllable(word_incoming) == ['ба', 'ка', 'лав', 'рский']\n\n\ndef test_get_word_by_syllable():\n word_incoming='а-яй'\n assert get_word_by_syllable(word_incoming) == None\n\n\n'''\nobtain_syllable_parameters\n'''\ndef test_obtain_syllable_parameters():\n word_by_syllable=['ба', 'ка', 'лав', 'рский']\n assert obtain_syllable_parameters(word_by_syllable) == [\n ('ба', 'BEG', 0, 4),\n ('ка', 'ба', 1, 4),\n ('лав', 'ка', 2, 4),\n ('рский', 'лав', 3, 4)\n ]\n","sub_path":"test_syllable.py","file_name":"test_syllable.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"133314621","text":"\"\"\"MurmurHash3 hash module.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, \\\n unicode_literals\n\nfrom six.moves import range\n\n\ndef murmur32_py(key, seed=0x0):\n \"\"\"\n Pure python implementation of murmur32 hash.\n\n :param key: Key to hash\n :type key: str\n :param seed: Seed to use when hashing\n :type seed: int\n\n :return: hashed value\n :rtype: int\n\n \"\"\"\n key = bytearray(key, 'utf-8')\n\n def fmix(current_hash):\n \"\"\"Mix has bytes.\"\"\"\n current_hash ^= current_hash >> 16\n current_hash = (current_hash * 0x85ebca6b) & 0xFFFFFFFF\n current_hash ^= current_hash >> 13\n current_hash = (current_hash * 0xc2b2ae35) & 0xFFFFFFFF\n current_hash ^= current_hash >> 16\n return current_hash\n\n length = len(key)\n nblocks = int(length/4)\n\n hash1 = seed & 0xFFFFFFFF\n\n calc1 = 0xcc9e2d51\n calc2 = 0x1b873593\n\n # body\n for block_start in range(0, nblocks * 4, 4):\n # ??? big endian?\n key1 = key[block_start + 3] << 24 | \\\n key[block_start + 2] << 16 | \\\n key[block_start + 1] << 8 | \\\n key[block_start + 0]\n\n key1 = (calc1 * key1) & 0xFFFFFFFF\n key1 = (key1 << 15 | key1 >> 17) & 0xFFFFFFFF # inlined ROTL32\n key1 = (calc2 * key1) & 0xFFFFFFFF\n\n hash1 ^= key1\n hash1 = (hash1 << 13 | hash1 >> 19) & 0xFFFFFFFF # inlined ROTL32\n hash1 = (hash1 * 5 + 0xe6546b64) & 0xFFFFFFFF\n\n # tail\n tail_index = nblocks * 4\n key1 = 0\n tail_size = length & 3\n\n if tail_size >= 3:\n key1 ^= key[tail_index + 2] << 16\n if tail_size >= 2:\n key1 ^= key[tail_index + 1] << 8\n if tail_size >= 1:\n key1 ^= key[tail_index + 0]\n\n if tail_size > 0:\n key1 = (key1 * calc1) & 0xFFFFFFFF\n key1 = (key1 << 15 | key1 >> 17) & 0xFFFFFFFF # inlined ROTL32\n key1 = (key1 * calc2) & 0xFFFFFFFF\n hash1 ^= key1\n\n unsigned_val = fmix(hash1 ^ length)\n return unsigned_val\n","sub_path":"splitio/engine/hashfns/murmur3py.py","file_name":"murmur3py.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"154324812","text":"import datetime\n\nfrom django.core.validators import ValidationError\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db import models\nfrom django.db.models.signals import post_save, post_delete\nfrom django.utils.translation import ugettext_lazy as _\nfrom collections import OrderedDict\nfrom itertools import chain\n\n#from registration import signals as reg_signals\n#from registration.models import ActivationProfile\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom authdemo.models import DemoUser as User\n\n\nclass ProfileUnits(models.Model):\n \"\"\"\n This is the parent class for all user information. Creating any new\n profile unit instances (Education, Name, Email etc) end up in the\n ProfileUnits queryset as well.\n\n \"\"\"\n date_created = models.DateTimeField(default=datetime.datetime.now,\n editable=False)\n date_updated = models.DateTimeField(default=datetime.datetime.now,\n editable=False)\n content_type = models.ForeignKey(ContentType, editable=False, null=True)\n #user = models.ForeignKey('myjobs.User', editable=False)\n user = models.ForeignKey(User, editable=False)\n \n #user = models.OneToOneField(User, primary_key=True, verbose_name='user', related_name='profile')\n \n def save(self, *args, **kwargs):\n \"\"\"\n Custom save method to set the content type of the instance.\n\n \"\"\"\n if not self.content_type:\n self.content_type = ContentType.objects.get_for_model(self.__class__)\n super(ProfileUnits, self).save(*args, **kwargs)\n\n def get_fields(self):\n \"\"\"\n Returns the module type, value, and field type for all\n fields on a specific model\n \"\"\"\n field_list = []\n for field in self._meta.local_fields:\n if not field.primary_key:\n field_list.append([field.verbose_name.title(),\n self.__getattribute__(field.name),\n field.get_internal_type()])\n return field_list\n\n def __unicode__(self):\n return self.content_type.name\n\n def get_model_name(self):\n return self.content_type.model\n\n @classmethod\n def get_verbose_class(object):\n return object.__name__\n\n def get_verbose(self):\n return self.content_type.name.title()\n\n @classmethod\n def suggestions(cls, user, by_priority=True):\n \"\"\"Get a list of all suggestions for a user to improve their profile.\n\n :Inputs:\n user = User for which to get suggestions\n by_priority: Sort results by priority before returning, otherwise items\n will be in the order they appear in the `classes` list\n\n :Outputs:\n suggestions - A list of dictionary objects. Each dictionary should\n conform to the following format.\n {\n 'msg': '...',\n 'priority': [0-9],\n 'url': '...'\n }\n\n Note: this (and the similar method on the subclasses) are class methods\n because for any given class the user may not have an instance that can\n be used to access it.\n \"\"\"\n classes = [Name, Summary, Address, Telephone, EmploymentHistory,\n Education,\n #License, MilitaryService, SecondaryEmail,\n VolunteerHistory,\n #Website,\n EndorsementInvitation,\n ]\n\n suggestions = chain(*[klass.get_suggestion(user) for klass in classes])\n if by_priority:\n suggestions = sorted(suggestions, reverse=True,\n key=lambda x: x['priority'])\n return suggestions\n\n\nclass Name(ProfileUnits):\n module_description = \"Use the name you want people to call you on the first contact.\"\n given_name = models.CharField(max_length=30,\n verbose_name=_(\"first name\"))\n family_name = models.CharField(max_length=30,\n verbose_name=_(\"last name\"))\n primary = models.BooleanField(default=False,\n verbose_name=_(\"Is primary name?\"))\n\n def get_full_name(self):\n \"\"\"\n Returns the first_name plus the last_name, with a space in between.\n \"\"\"\n\n full_name = '%s %s' % (self.given_name, self.family_name)\n return full_name.strip()\n\n def save(self, *args, **kwargs):\n \"\"\"\n Custom name save method to ensure only one name object per user\n has one primary=True. This function also updates the\n user's first_name and last_name.\n \"\"\"\n duplicate_names = Name.objects.filter(user=self.user,\n given_name=self.given_name,\n family_name=self.family_name)\n if duplicate_names:\n if self.primary:\n if self.id in [name.id for name in duplicate_names]:\n self.switch_primary_name()\n else:\n duplicate = duplicate_names[0]\n if duplicate.primary is False:\n try:\n current_primary = Name.objects.get(primary=True,\n user=self.user)\n except Name.DoesNotExist:\n duplicate.primary = True\n self.user.add_primary_name(\n update=True, f_name=duplicate.given_name,\n l_name=duplicate.family_name)\n duplicate.save()\n else:\n current_primary.primary = False\n current_primary.save()\n duplicate.primary = True\n self.user.add_primary_name(\n update=True, f_name=duplicate.given_name,\n l_name=duplicate.family_name)\n duplicate.save()\n elif self.id in [name.id for name in duplicate_names]:\n self.user_full_name_check()\n super(Name, self).save(*args, **kwargs)\n else:\n if self.primary:\n self.switch_primary_name()\n else:\n try:\n primary = Name.objects.get(primary=True, user=self.user)\n except Name.DoesNotExist:\n primary = False\n if not primary:\n self.user.add_primary_name(update=True, f_name=\"\",\n l_name=\"\")\n super(Name, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return self.get_full_name()\n\n def switch_primary_name(self, *args, **kwargs):\n try:\n temp = Name.objects.get(primary=True, user=self.user)\n except Name.DoesNotExist:\n self.user_full_name_check()\n super(Name, self).save(*args, **kwargs)\n else:\n temp.primary = False\n temp.save()\n self.user.add_primary_name(update=True, f_name=self.given_name,\n l_name=self.family_name)\n super(Name, self).save(*args, **kwargs)\n\n def user_full_name_check(self):\n if self.primary:\n self.user.add_primary_name(update=True, f_name=self.given_name,\n l_name=self.family_name)\n else:\n if self.user.get_full_name() == self.get_full_name():\n self.user.add_primary_name(update=True, f_name=\"\", l_name=\"\")\n else:\n self.user.add_primary_name()\n\n @classmethod\n def get_suggestion(cls, user):\n \"\"\"Get a suggestion for a user to improve their education\n profile.\n\n :Inputs:\n user = User for which to get suggestions\n\n :Outputs:\n suggestion - A dictionary object which should conform to the format\n indicated in ProfileUnits.suggestions().\n \"\"\"\n if not cls.objects.filter(user=user).exists():\n return [{'msg': \"Please add your name.\",\n 'priority': 5,\n 'url': reverse('handle_form') + '?module=Name&id=new',\n 'module': 'Name'}]\n return []\n\n\ndef save_primary(sender, instance, created, **kwargs):\n user = instance.user\n if len(Name.objects.filter(user=user)) == 1 and created:\n try:\n user.profileunits_set.get(content_type__name=\"name\",\n name__primary=True)\n except ProfileUnits.DoesNotExist:\n instance.primary = True\n instance.user.add_primary_name(update=True,\n f_name=instance.given_name,\n l_name=instance.family_name)\n instance.save()\n\n\ndef delete_primary(sender, instance, **kwargs):\n user = instance.user\n if user:\n user.add_primary_name(update=True, f_name=\"\", l_name=\"\")\n\npost_save.connect(save_primary, sender=Name, dispatch_uid=\"save_primary\")\npost_delete.connect(delete_primary, sender=Name, dispatch_uid=\"delete_primary\")\n\n\nEDUCATION_LEVEL_CHOICES = (\n ('', _('Education Level')),\n (3, _('High School')),\n (4, _('Non-Degree Education')),\n (5, _('Associate')),\n (6, _('Bachelor')),\n (7, _('Master')),\n (8, _('Doctoral')),\n)\n\n\nclass Education(ProfileUnits):\n organization_name = models.CharField(max_length=255,\n verbose_name=_('institution'))\n degree_date = models.DateField(verbose_name=_('Completion or expected completion date'),\n help_text = 'e.g., 09/2016',\n blank=True, null=True)\n city_name = models.CharField(max_length=255, blank=True,\n verbose_name=_('city'))\n # ISO 3166-2:2007\n country_sub_division_code = models.CharField(max_length=25, blank=True,\n verbose_name=_(\"State/Region\"))\n country_code = models.CharField(max_length=3, blank=True,\n verbose_name=_(\"country\")) # ISO 3166-1\n # ISCED-2011 Can be [0-8]\n education_level_code = models.IntegerField(choices=EDUCATION_LEVEL_CHOICES,\n verbose_name=_(\"education level\"),\n blank=True, null=True)\n start_date = models.DateField(blank=True, null=True, help_text = \"e.g., 02/2003\")\n end_date = models.DateField(blank=True, null=True, help_text = \"e.g., 02/2004\")\n education_score = models.CharField(max_length=255, blank=True,\n verbose_name=_(\"GPA\"), help_text = \"If you are a student or recent graduate, list your GPA.\")\n #degree_name = models.CharField(max_length=255, blank=True,\n # verbose_name=_('degree type'))\n degree_major = models.CharField(max_length=255, verbose_name=_('major'),\n blank=True)\n degree_minor = models.CharField(max_length=255, blank=True,\n verbose_name=_('minor'))\n \n module_description = \"Students and new grads with little related work experience may use the education section as the centerpiece of their resumes, showcasing academic achievements, extracurricular activities, special projects and related courses.\"\n \n @classmethod\n def get_suggestion(cls, user):\n \"\"\"Get a list of all suggestions for a user to improve their education\n profile.\n\n :Inputs:\n user = User for which to get suggestions\n\n :Outputs:\n suggestion - A dictionary object which should conform to the format\n indicated in ProfileUnits.suggestions().\n \"\"\"\n if not cls.objects.filter(user=user).exists():\n return [{\n 'msg': (\"Would you like to provide information about \"\n \"your education?\"),\n 'priority': 5,\n 'module': 'Education',\n 'url': reverse('handle_form') + '?module=Education&id=new'}]\n else:\n return []\n\nclass Address(ProfileUnits):\n module_description = \"Some employers require you to live within a certain radius.\"\n address_line_one = models.CharField(max_length=255, blank=True,\n verbose_name=_('Address Line One'),\n help_text='ie 123 Main St')\n address_line_two = models.CharField(max_length=255, blank=True,\n verbose_name=_('Address Line Two'),\n help_text='ie apartment 1')\n city_name = models.CharField(max_length=255, blank=True,\n verbose_name=_(\"City\"),\n help_text='ie Chicago, Washington, Dayton')\n country_sub_division_code = models.CharField(max_length=25, blank=True,\n verbose_name=_(\"State/Region\"),\n help_text='ie NY, WA, DC')\n country_code = models.CharField(max_length=3, blank=True,\n verbose_name=_(\"Country\"),\n default='USA')\n postal_code = models.CharField(max_length=12, blank=True,\n verbose_name=_(\"Postal Code\"),\n help_text='ie 90210, 12345-7890')\n label = models.CharField(max_length=60, blank=True,\n verbose_name=_('Address Name'),\n help_text='ie Home, Work, etc')\n \n @classmethod\n def print_formatted_address(self):\n return \"FORMATTED ADDRESS\"\n \n\n\n @classmethod\n def get_suggestion(cls, user):\n \"\"\"Get a list of all suggestions for a user to improve their address\n profile.\n\n :Inputs:\n user = User for which to get suggestions\n\n :Outputs:\n suggestion - A dictionary object which should conform to the format\n indicated in ProfileUnits.suggestions().\n \"\"\"\n objects = cls.objects.filter(user=user).order_by('date_updated')\n if len(objects) == 0:\n return [{'msg': 'Would you like to provide your address?',\n 'url': reverse('handle_form') + '?module=Address&id=new',\n 'priority': 5,\n 'module': 'Address'}]\n else:\n return [{'msg': 'Do you need to update your address from %s?' %\n objects[0].address_line_one,\n 'url': reverse('handle_form') + '?module=Address&id=%s' %\n objects[0].pk,\n 'priority': 1,\n 'module': 'Address'}]\n\n\nclass Telephone(ProfileUnits):\n module_description = \"Some employers require your phone number for a phone screen.\"\n USE_CODE_CHOICES = (\n ('', 'Phone Type'),\n ('Home', 'Home'),\n ('Work', 'Work'),\n ('Mobile', 'Mobile'),\n ('Pager', 'Pager'),\n ('Fax', 'Fax'),\n ('Other', 'Other')\n )\n channel_code = models.CharField(max_length=30, editable=False, blank=True)\n country_dialing = models.CharField(max_length=3, blank=True,\n verbose_name=_(\"Country Code\"))\n area_dialing = models.CharField(max_length=5, blank=True,\n verbose_name=_(\"Area Code\"))\n number = models.CharField(max_length=10, blank=True,\n verbose_name=_(\"Local Number\"))\n #extension = models.CharField(max_length=5, blank=True)\n use_code = models.CharField(max_length=30, choices=USE_CODE_CHOICES,\n blank=True, verbose_name=_(\"Phone Type\"))\n\n @classmethod\n def get_suggestion(cls, user):\n \"\"\"Get a list of all suggestions for a user to improve their telephone\n profile.\n\n :Inputs:\n user = User for which to get suggestions\n\n :Outputs:\n suggestion - A dictionary object which should conform to the format\n indicated in ProfileUnits.suggestions().\n \"\"\"\n if not cls.objects.filter(user=user).exists():\n return [{'msg': 'Would you like to add a telephone?',\n 'priority': 5,\n 'module': 'Telephone',\n 'url': reverse('handle_form') + '?module=Telephone&id=new'\n }]\n else:\n return []\n\n def save(self, *args, **kwargs):\n if self.use_code == \"Home\" or self.use_code == \"Work\" or self.use_code == \"Other\":\n self.channel_code = \"Telephone\"\n if self.use_code == \"Mobile\":\n self.channel_code = \"MobileTelephone\"\n if self.use_code == \"Pager\":\n self.channel_code = \"Pager\"\n if self.use_code == \"Fax\":\n self.channel_code = \"Fax\"\n super(Telephone, self).save(*args, **kwargs)\n\n\nclass EmploymentHistory(ProfileUnits):\n module_description = \"With honest and well-written employment histories, even if you have a less-than-perfect background, you will secure interviews. Always be truthful about your background.\"\n position_title = models.CharField(max_length=255,\n verbose_name=_(\"Position Title\"))\n organization_name = models.CharField(max_length=255, blank=True,\n verbose_name=_(\"Company\"))\n start_date = models.DateField(verbose_name=_(\"Start Date\"), help_text = \"e.g., 02/2003\")\n current_indicator = models.BooleanField(default=False,\n verbose_name=_(\"I still work here\"))\n\n # Optional fields\n end_date = models.DateField(blank=True, null=True, help_text = \"e.g., 02/2003\" )\n city_name = models.CharField(max_length=255, blank=True, null=True)\n country_sub_division_code = models.CharField(max_length=25, blank=True,\n verbose_name=_(\"State/Region\"))\n country_code = models.CharField(max_length=3, blank=True, null=True,\n verbose_name=_(\"country\"))\n description = models.TextField(blank=True, null=True)\n\n # Hidden fields\n industry_code = models.CharField(max_length=255, blank=True, null=True,\n verbose_name=_(\"industry\"),\n editable=False)\n job_category_code = models.CharField(max_length=255, blank=True, null=True,\n verbose_name=_(\"job category\"),\n editable=False)\n onet_code = models.CharField(max_length=255, blank=True, null=True,\n editable=False)\n\n @classmethod\n def get_suggestion(cls, user):\n \"\"\"Get a list of all suggestions for a user to improve their employment\n history on their profile.\n\n :Inputs:\n user = User for which to get suggestions\n\n :Outputs:\n suggestion - A dictionary object which should conform to the format\n indicated in ProfileUnits.suggestions().\n \"\"\"\n objects = cls.objects.filter(user=user).order_by('start_date')\n if len(objects) == 0:\n return [{'msg': \"Would you like to add your employment history?\",\n 'url': reverse('handle_form') + \\\n '?module=EmploymentHistory&id=new',\n 'priority': 5,\n 'module': 'Employment'}]\n elif objects[0].current_indicator:\n return [{'msg': \"Are you still employed with %s?\" %\n objects[0].organization_name,\n 'url': reverse('handle_form') + \\\n '?module=EmploymentHistory&id=%s' % objects[0].pk,\n 'priority': 0,\n 'module': 'Employment'}]\n else:\n return [{'msg': \"Have you worked anywhere since being employed\" +\n \" with %s?\" % objects[0].organization_name,\n 'url': reverse('handle_form') + \\\n '?module=EmploymentHistory&id=%s' % objects[0].pk,\n 'priority': 1,\n 'module': 'Employment'}]\n\n\n\nclass Summary(ProfileUnits):\n module_description = \"Hook employers into reading your profile by telling them your job target as well as the main benefit of hiring you.\"\n headline = models.CharField(max_length=100, verbose_name=\"Headline\",\n help_text='How you describe your profession.' +\n ' ie \"Experienced accounting ' +\n 'professional\"')\n the_summary = models.TextField(max_length=2000, verbose_name=\"Summary\",\n blank=True,\n help_text='A short summary of your ' +\n 'strengths and career to date.')\n\n def save(self, *args, **kwargs):\n try:\n summary_model = self.user.profileunits_set.get(\n content_type__name=\"summary\")\n except ProfileUnits.DoesNotExist:\n summary_model = None\n\n if not summary_model:\n super(Summary, self).save(*args, **kwargs)\n else:\n if self.id == summary_model.id:\n super(Summary, self).save(*args, **kwargs)\n else:\n raise ValidationError(\"A summary already exists\")\n\n @classmethod\n def get_suggestion(cls, user):\n \"\"\"Get a list of all suggestions for a user to add a summary to their\n profile.\n\n :Inputs:\n user = User for which to get suggestions\n\n :Outputs:\n suggestion - A dictionary object which should conform to the format\n indicated in ProfileUnits.suggestions().\n \"\"\"\n if not cls.objects.filter(user=user).exists():\n return [{'msg': \"Would you like to add a summary of your career?\",\n 'url': reverse('handle_form') + '?module=Summary&id=new',\n 'priority': 5,\n 'module': 'Profile Summary'}]\n return []\n\n\nclass VolunteerHistory(ProfileUnits):\n module_description = \"Volunteer work, whether in addition to a current job or an activity in between jobs, shows an employer that you are willing to try new experiences, be involved in your community and generally demonstrates a willingness to take initiative and make things happen.\"\n position_title = models.CharField(max_length=255,\n verbose_name=_(\"Position Title\"))\n organization_name = models.CharField(max_length=255,\n verbose_name=_(\"Organization\"))\n start_date = models.DateField(verbose_name=_(\"Start Date\"), help_text = \"e.g., 02/2003\")\n current_indicator = models.BooleanField(default=False,\n verbose_name=_(\n \"I still volunteer here\"))\n\n # Optional fields\n end_date = models.DateField(blank=True, null=True, help_text = \"e.g., 02/2003\")\n city_name = models.CharField(max_length=255, blank=True)\n country_sub_division_code = models.CharField(max_length=25, blank=True,\n verbose_name=_(\"State/Region\"))\n country_code = models.CharField(max_length=3, blank=True,\n verbose_name=_(\"country\"))\n description = models.TextField(blank=True)\n\n @classmethod\n def get_suggestion(cls, user):\n \"\"\"Get a list of suggestions for a user to improve their volunteer\n history profile.\n\n :Inputs:\n user = User for which to get suggestions\n\n :Outputs:\n suggestion - A dictionary object which should conform to the format\n indicated in ProfileUnits.suggestions().\n \"\"\"\n if not cls.objects.filter(user=user).exists():\n msg = (\"Do you have any relevant volunteer experience you would \" +\n \"like to include?\")\n return [{'msg': msg,\n 'url': reverse('handle_form') + \\\n '?module=VolunteerHistory&id=new',\n 'priority':3,\n 'module': 'Volunteer History'}]\n return []\n\n\n\nclass EndorsementInvitation(ProfileUnits):\n \"\"\"\n Represents a non-user being invited to endorse a user\n \"\"\"\n \n \n module_description =\"\"\"

What is this? In the real world, you are only as good as those who recommend you. Other websites don't allow people that know you to vouch for you. Our platform allows the people who know your work the best to easily speak out on your behalf so you stand out from the rest.

\n
\n

How do I do this? Invite 3-5 friends or coworkers to give your profile a thumbs up. We'll send them an email. They simply have to say 'Yes' to verify the facts in your profile.

\n
\n

Why? Endorsed profiles are promoted and ranked much higher when employers search. The more the better.

\"\"\"\n \n #module_description = \"A verified profile significantly increases your chances of landing a job.

Friends or coworkers can verify your profile. We send them an email and they simply have to say 'Yes' to verify the facts in your profile.\"\n \n #ediatable\n invitee_email = models.CharField(max_length=255, db_index=True, verbose_name=\"Email of friend/co-worker who can give you a thumbs-up\")\n invitee_first_name = models.CharField(max_length=255, verbose_name=\"First name\")\n invitee_last_name = models.CharField(max_length=255, verbose_name=\"Last name\")\n \n \n #not editable\n inviting_user = models.ForeignKey(User, editable=False,\n related_name='invites_sent',\n null=True)\n invitee = models.ForeignKey(User, related_name='invites',\n on_delete=models.SET_NULL, null=True,\n editable=False)\n invited = models.DateTimeField(auto_now_add=True, editable=False)\n endorsed = models.BooleanField(default=False, editable=False,\n help_text='Has the invitee hase '\n 'endorsed you') \n accepted = models.BooleanField(default=False, editable=False,\n help_text='Has the invitee accepted '\n 'this invitation') \n \n \n\n\n def save(self, *args, **kwargs):\n #from myjobs.models import User\n invitee = [self.invitee_email, self.invitee]\n if all(invitee):\n if not User.objects.get_email_owner(\n self.invitee_email) == self.invitee:\n # ValidationErrors aren't appropriate, but nothing else fits\n # either; these are unrecoverable\n raise ValidationError('Invitee information does not match')\n elif not any(invitee):\n raise ValidationError('Invitee not provided')\n elif self.invitee_email:\n # create_user first checks if an email is in use and creates an\n # account if it does not.\n self.invitee = User.objects.create_user(email=self.invitee_email,\n first_name=self.invitee_first_name,\n last_name=self.invitee_last_name,\n #in_reserve=True,\n )\n #[0]\n else:\n self.invitee_email = self.invitee.email\n\n super(EndorsementInvitation, self).save(*args, **kwargs)\n \n @classmethod\n def get_suggestion(cls, user):\n \"\"\"Get a list of all suggestions for a user to add a summary to their\n profile.\n\n :Inputs:\n user = User for which to get suggestions\n\n :Outputs:\n suggestion - A dictionary object which should conform to the format\n indicated in ProfileUnits.suggestions().\n \"\"\"\n if not cls.objects.filter(user=user).exists():\n return [{'msg': \"Would you like to boost your reputation to employers?\",\n 'url': reverse('handle_form') + '?module=EndorsementInvitation&id=new',\n 'priority': 5,\n 'module': 'Endorsements'}]\n return []\n \n \n\n\nclass BaseProfileUnitManager(object):\n \"\"\"\n Class for managing how profile units are displayed\n\n Visible units are returned by displayed_units\n\n Displayed and excluded models are defined as lists of model names\n\n Child classes can define custom display logic per model in\n _is_displayed methods\n i.e.\n def name_is_displayed(self, unit):\n return unit.is_primary()\n\n Each input accepts a list of model names as strings i.e. ['name','address']\n Inputs:\n :displayed: List of units one wants to be displayed\n :excluded: List of units one would want to exclude from being displayed\n :order: List of units to order the output for displayed_units\n \"\"\"\n def __init__(self, displayed=None, excluded=None, order=None):\n self.displayed = displayed or []\n self.excluded = excluded or []\n self.order = order or []\n\n def is_displayed(self, unit):\n \"\"\"\n Returns True if a unit should be displayed\n Input:\n :unit: An instance of ProfileUnit\n \"\"\"\n try:\n field_is_displayed = getattr(self,\n unit.get_model_name()+'_is_displayed')\n if field_is_displayed:\n return field_is_displayed(unit)\n except AttributeError:\n pass\n if not self.displayed and not self.excluded:\n return True\n elif self.displayed and self.excluded:\n return unit.get_model_name() in self.displayed \\\n and unit.get_model_name() not in self.excluded\n elif self.excluded:\n return unit.get_model_name() not in self.excluded\n elif self.displayed:\n return unit.get_model_name() in self.displayed\n else:\n return True\n\n def order_units(self, profileunits, order):\n \"\"\"\n Sorts the dictionary from displayed_units\n\n Inputs:\n :profileunits: Dict of profileunits made in displayed_units\n :order: List of model names (as strings)\n\n Outputs:\n Returns an OrderedDict of the sorted list\n \"\"\"\n sorted_units = []\n units_map = {item[0]: item for item in profileunits.items()}\n for item in order:\n try:\n sorted_units.append(units_map[item])\n units_map.pop(item)\n except KeyError:\n pass\n sorted_units.extend(units_map.values())\n return OrderedDict(sorted_units)\n\n def displayed_units(self, profileunits):\n \"\"\"\n Returns a dictionary of {model_names:[profile units]} to be displayed\n\n Inputs:\n :profileunits: The default value is .all() profileunits, but you can\n input your own QuerySet of profileunits if you are\n using specific filters\n\n Outputs:\n :models: Returns a dictionary of profileunits, an example:\n {u'name': [, ]}\n \"\"\"\n models = {}\n\n for unit in profileunits:\n if self.is_displayed(unit):\n models.setdefault(unit.get_model_name(), []).append(\n getattr(unit, unit.get_model_name()))\n\n if self.order:\n models = self.order_units(models, self.order)\n\n return models\n\n\nclass PrimaryNameProfileUnitManager(BaseProfileUnitManager):\n \"\"\"\n Excludes primary name from displayed_units and sets self.primary_name\n \"\"\"\n def __init__(self, displayed=None, excluded=None, order=None):\n super(PrimaryNameProfileUnitManager, self).__init__(displayed,\n excluded, order)\n\n def name_is_displayed(self, profileunit):\n if profileunit.name.primary:\n self.primary_name = profileunit.name.get_full_name()\n return False\n","sub_path":"hackathon_starter/myprofile/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":33042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"59295564","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 19 16:05:49 2019\n\n@author: user\n\"\"\"\n \nimport cv2\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile,join\nimport time\n\ndata_path = \"D:\\\\ml\\\\data_images\"\nonlyfiles = []\nfor k in listdir(data_path):\n onlyfiles.append(k)\n\n\nTraining_Data , Labels = [] ,[]\n\nfor i , files in enumerate(onlyfiles):\n image_path = join(data_path, onlyfiles[i])\n images = cv2.imread(image_path,cv2.IMREAD_GRAYSCALE)\n Training_Data.append(np.asarray(images,dtype=np.uint8))\n Labels.append(i)\n \nLabels = np.asarray(Training_Data),np.asarray(Labels)\n\nmodel = cv2.face.LBPHFaceRecognizer_create()\n\nmodel.train(np.asarray(Training_Data),np.asarray(Labels))\n\nprint('Model Training Completed ........')\n\nface_classifier = cv2.CascadeClassifier(r\"D:\\Datasets\\data\\haarcascades\\haarcascade_frontalface_default.xml\")\n\ndef face_detector (img,size=0.5):\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n faces = face_classifier.detectMultiScale(gray,1.3,5)\n\n if faces is() :\n return img,[]\n \n for (x,y,w,h) in faces :\n cv2.rectangle(img,(x,y),(x+w,y+h),2)\n roi = img[y:y+h , x:x+w]\n roi = cv2.resize(roi,(200,200))\n \n return img,roi\n\ncap = cv2.VideoCapture(0)\nwhile True :\n \n flag = False\n ret , frame = cap.read()\n \n image , face = face_detector(frame)\n \n try :\n face = cv2.cvtColor(face,cv2.COLOR_BGR2GRAY)\n result = model.predict(face)\n \n if result[1]<500:\n confidence = int(100*(1-(result[1])/1000))\n display_string = str(confidence)+ '% Confidence it is user'\n cv2.putText(image , display_string,(10,10),cv2.FONT_HERSHLEY_COMPLEX,1,(250,120,255),2)\n \n if confidence > 80:\n \n cv2.putText(image,'Unlocked',(10,400),cv2.FONT_HERSHLEY_COMPLEX,2,(0,255,0),2)\n cv2.imshow('Face Cropper',image)\n cv2.waitKey(20)\n \n else :\n cv2.putText(image,'Locked',(10,400),cv2.FONT_HERSHLEY_COMPLEX,2,(0,0,255),2)\n cv2.imshow('Face Cropper',image)\n \n except :\n #cv2.putText(image,'Face not found',(10,400),cv2.FONT_HERSHLEY_COMPLEX,2,(255,0,0),2)\n cv2.imshow('Face Cropper',image)\n pass\n if cv2.waitkey(1)==ord('q'):\n break\n \ncap.release()\ncv2.destroyAllWindows()\n#ser.close\n\n ","sub_path":"Python files/img_detection0.py","file_name":"img_detection0.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"592225512","text":"#Challenge 6\n#Created by: Zach Golik\nDaysPerWeek=int(7)\nHoursPerDay=int(24)\nMinutesPerHour=int(60)\nMinutesPerWeek=(DaysPerWeek*HoursPerDay*MinutesPerHour)\nprint(MinutesPerWeek)\n#Completed successfully? Yes\n#Did you have any errors? Nope\n#How did you solve them? N/A\n#What did you find difficult? Nothing\n","sub_path":"Challenge 6.py","file_name":"Challenge 6.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"30720199","text":"\"\"\"\nThe Python standard library's 'calendar' module allows you to\nrender a calendar to your terminal.\nhttps://docs.python.org/3.6/library/calendar.html\n\nWrite a program that accepts user input of the form\n `14_cal.py [month] [year]`\nand does the following:\n - If the user doesn't specify any input, your program should\n print the calendar for the current month. The 'datetime'\n module may be helpful for this.\n - If the user specifies one argument, assume they passed in a\n month and render the calendar for that month of the current year.\n - If the user specifies two arguments, assume they passed in\n both the month and the year. Render the calendar for that\n month and year.\n - Otherwise, print a usage statement to the terminal indicating\n the format that your program expects arguments to be given.\n Then exit the program.\n\nNote: the user should provide argument input (in the initial call to run the file) and not\nprompted input. Also, the brackets around year are to denote that the argument is\noptional, as this is a common convention in documentation.\n\nThis would mean that from the command line you would call `python3 14_cal.py 4 2015` to\nprint out a calendar for April in 2015, but if you omit either the year or both values,\nit should use today’s date to get the month and year.\n\"\"\"\n\nimport sys\nimport calendar\nfrom datetime import datetime\n\n\nsystem = sys.argv\ntoday = datetime.now()\nmonth = today.month\nyear = today.year\nerror_month = ''\nerror_year = ''\n\n# function to check if user inputs were made\ndef index_in_list(a_list, index):\n return(index < len(a_list))\n\n# check to see if input is able to be converted into int\ndef is_int(val):\n try:\n num = int(val)\n except ValueError:\n return False\n return True\n\n# check if user input month value, if so set month to user value\ndef check_month_input():\n global month, error_month\n\n if(index_in_list(system, 1)):\n if is_int(system[1]):\n arg1 = int(system[1])\n if arg1 >=1 and arg1 <=12:\n month = arg1\n return True\n else:\n error_month = f'[ {arg1} ]'\n return False\n else:\n error_month = f'[ {system[1]} ]'\n return False\n else:\n return month\n\n# check if user input year value, if so set year to user value\ndef check_year_input():\n global year, error_year\n\n if(index_in_list(system, 2)):\n if is_int(system[2]):\n arg2 = int(system[2])\n if arg2 >=1900 and arg2 <=2050:\n year = arg2\n return True\n else:\n error_year = f'[ {arg2} ]'\n return False\n else:\n error_year = f'[ {system[2]} ]'\n return False\n else:\n return year\n\n# if check user input function returns false print error message\nif not check_month_input() or not check_year_input():\n error_message = f'Invalid Inputs: {error_month} {error_year} is not an acceptable input.\\nPlease use a number 1 through 12 for the month, and the full year ex: 2020 between 1900 - 2050.\\nWhen running the program on the command line it should look similar to this: \\n\\n\\'python3 14_cal.py [month] [year]\\'\\n\\nOrder matters when inputing the dates, makes sure you are inputing month before year.'\n print(error_message)\nelse:\n print(calendar.month(year, month))\n","sub_path":"src/14_cal.py","file_name":"14_cal.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"105087549","text":"import flask \t\t\t\t\t#导入flask模块\nhtml_txt = \"\"\" \t\t\t\t\t#变量html_txt初始化,作为GET请求的页面\n\n\n \n

如果收到了GET请求

\n
\t\t#设置请求方法是“post”\n \n
\n \n\n\"\"\"\napp = flask.Flask(__name__) \t\t#实例化类Flask\n#URL映射,不管是‘GET’方法还是‘POST’方法,都被映射到helo()函数\n@app.route('/aaa',methods=['GET','POST'])\ndef helo(): \t\t#定义业务处理函数helo()\n if flask.request.method == 'GET': \t#如果接收到的请求是GET\n return html_txt \t\t#返回html_txt的页面内容\n else: \t\t\t#否则接收到的请求是POST\n return '我司已经收到POST请求!'\nif __name__ == '__main__':\n app.run() \t\t\t#运行程序\n","sub_path":"1/1-4/flask3.py","file_name":"flask3.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"563636115","text":"# -*- coding: utf-8 -*-\n# Copyright (C) 2008-2012, Luis Pedro Coelho \n# vim: set ts=4 sts=4 sw=4 expandtab smartindent:\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nfrom __future__ import division\nimport numpy as np\n__all__ = ['zscore']\n\ndef zscore(features, axis=0, inplace=False):\n \"\"\"\n features = zscore(features, axis=0, inplace=False)\n\n Returns a copy of features which has been normalised to zscores \n\n Parameters\n ----------\n features : ndarray\n 2-D input array\n axis : integer, optional\n inplace : boolean, optional\n Whether to operate inline\n \"\"\"\n if features.ndim != 2:\n raise('milk.unsupervised.zscore: Can only handle 2-D arrays')\n mu = features.mean(axis)\n sigma = np.std(features, axis)\n sigma[sigma == 0] = 1.\n if not inplace:\n features = features.copy()\n if axis == 0:\n features -= mu\n features /= sigma\n elif axis == 1:\n features -= mu[:,None]\n features /= sigma[:,None]\n return features\n\n","sub_path":"milk/unsupervised/normalise.py","file_name":"normalise.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"507575035","text":"import pandas\nimport gzip\n\nTG=\"/scratch/abarbeira3/data/1000G/ALL.chr1.shapeit2_integrated_snvindels_v2a_27022019.GRCh38.phased.vcf.gz\"\nhg38_ids = []\nwith gzip.open(TG) as tg:\n for line in tg:\n line = line.decode()\n if \"#CHROM\" in line:\n hg38_ids = line.strip().split()[9:]\n break\n\n\nTGS=\"/gpfs/data/im-lab/nas40t2/abarbeira/projects/gtex_v8/data/1000G/20140502_all_samples.ped\"\n\nsamples = pandas.read_table(TGS)\nsamples = samples.rename(columns={\"Paternal ID\":\"paternal_id\", \"Maternal ID\":\"maternal_id\", \"Individual ID\":\"individual_id\", \"Family ID\":\"family_id\"})\nsamples = samples[samples.Population.isin({\"CEU\", \"TSI\", \"FIN\", \"GBR\", \"IBS\"})]\nsamples = samples[(samples.paternal_id == \"0\") & (samples.maternal_id == \"0\")]\nsamples = samples[samples[\"Other Comments\"] != 'relationships are uncertain']\n\ni = samples.individual_id\ni = i[i.isin(hg38_ids)]\ni.to_csv(\"selected_hg38_eur_id.txt\", header=False, index=False)","sub_path":"src/1000G/extract_samples_hg38.py","file_name":"extract_samples_hg38.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"335647880","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport requests,re,datetime,math,os,calendar\n\nclass scheduler:\n\n dicSchedule={} #key:datetime, value:bool (true workday)\n scheduleList = [(2015,10),(2015,11),(2015,12)]\n \n def __init__(self):\n self.url_schedule ='http://oa.ddianle.com:8168/seeyon/ajax.do?method=ajaxAction&managerName=personageKqManage' #&rnd=98111'\n now = datetime.datetime.now()\n for year in range(2016,now.year):\n for month in range(1,13):\n scheduler.scheduleList.append((year,month))\n for month in range(1,now.month+1):\n scheduler.scheduleList.append((now.year,month))\n\n def loadSchedulingInfo(self,oa,bTest=False):\n now = datetime.datetime.now()\n if not bTest:\n schedulefilepath = r'schedule/s-%s-%s.txt' % (now.year,now.month)\n if os.path.exists(schedulefilepath):\n os.remove(schedulefilepath)\n\n for v in scheduler.scheduleList:\n year,month = v[0],v[1]\n schedulefilepath = r'schedule/s-%s-%s.txt' % (year,month)\n if not os.path.exists(schedulefilepath):\n self._getScheduleinfoFromOA(oa,year,month,schedulefilepath)\n with open(schedulefilepath, 'r') as f:\n strline = f.readline().strip()\n while(strline != None and len(strline)>0) :\n items = strline.split(':')\n scheduler.dicSchedule[datetime.datetime.strptime( items[0] ,\"%Y-%m-%d\")]= items[1]=='True'\n strline = f.readline().strip()\n \n def _getScheduleinfoFromOA(self,oa,year,month,schedulefilepath):\n avatarImageUrl = oa.cookies['avatarImageUrl']\n arguments = r'[\"%d\",\"%d\",\"%s\"]' % (year,month,avatarImageUrl)\n dataValue ={'managerMethod':'PersonageKqShow','arguments':arguments}\n web_schedule = oa.post(self.url_schedule,data=dataValue)\n l = re.findall(r'\\'name\\':\\'([0-9]{1,2})\\',\\'team\\':\\'(.{2})',web_schedule.text)\n with open(schedulefilepath, 'w') as f:\n for k,v in l:\n strTime = \"%s-%s-%s\" % (year,month,k)\n bworkday = v=='行政'\n f.write(strTime+':'+str(bworkday)+'\\r\\n')\n\nclass person:\n def __init__(self,member_id,member_name,b_noCalc=False):\n self.member_name = member_name\n self.member_id = member_id\n self._dicSignTime={} #key:datetime(year-monty-day),value:datetime\n self._dicSignTimeStr={} #key:datetime(year-monty-day),value:strtime\n self._dicExtraWorkTime={} #key:datetime(year-monty-day),value:hours\n self._bNoCalc=b_noCalc #不需要计算加班数据\n self._mWarningCount = 0\n self._dicMonthWorkTime={} #key:'year-month',value:hours\n \n def updatePersonSingInfo(self,signtime):\n dt = datetime.datetime.strptime(signtime, \"%Y-%m-%d %H:%M:%S.%f\")\n key = datetime.datetime.strptime(signtime[0:10], \"%Y-%m-%d\")\n# if dt.hour<6:\n# key = key - datetime.timedelta(days=1)\n if dt.hour>=6 and dt.hour<8:\n self._mWarningCount=self._mWarningCount+1\n #print(\"异常打卡记录:\",self.member_name,signtime,self._mWarningCount)\n if key in self._dicSignTime:\n self._dicSignTime[key].append(dt)\n self._dicSignTimeStr[key].append(signtime)\n else:\n self._dicSignTime[key] = [dt]\n self._dicSignTimeStr[key]= [signtime]\n \n\n '''\n 1.平时 不够9:30-18:00=8.5h的加班数为负 最高-8 8.5-9.5加班数为0 超出9.5h的加班数为正 最多+8 无上下班打卡记录的为-8\n 2.周末 加班数=下班时间-上班时间\n 3.后续还要加上 在家维护的OA申请\n '''\n def calcSimpleExtraWorkTime(self):\n keys = self._dicSignTime.keys()\n for k in keys:\n dayExtraTime = 0\n v = self._dicSignTime[k]\n min,max=v[0],v[0]\n # if len(v)>2 or len(v)==1:\n # print(self.member_name,k,\"sign times:\",v)\n if len(v)>=2:\n for d in v:\n if min>d:\n min =d\n if max0:\n if dayExtraTime>8:\n dayExtraTime= 8 \n else:\n dayExtraTime = dayExtraTime - 1\n if dayExtraTime<0:\n dayExtraTime=0\n elif dayExtraTime<-8:\n dayExtraTime= -8\n\n self._dicExtraWorkTime[k]=dayExtraTime\n\n def calcMonthExtraWorkTime(self):\n for ym in scheduler.scheduleList:\n year,month = ym[0],ym[1]\n self.calcSingleMonthExtraWorkTime(year,month)\n print(self._dicMonthWorkTime)\n return self._dicMonthWorkTime\n\n def calcSingleMonthExtraWorkTime(self,year,month):\n monthExtraHour=0\n begin = datetime.datetime(year,month,1)\n if(month==12):\n year=year+1\n month=1\n else:\n month=month+1\n end = datetime.datetime(year,month,1)\n for i in range((end-begin).days-1):\n day = begin + datetime.timedelta(days=i)\n if scheduler.dicSchedule.get(day):\n if scheduler.dicSchedule[day]:\n if day in self._dicExtraWorkTime:\n monthExtraHour = monthExtraHour+self._dicExtraWorkTime[day]\n else :\n monthExtraHour = monthExtraHour-8\n else:\n if day in self._dicExtraWorkTime:\n monthExtraHour = monthExtraHour+self._dicExtraWorkTime[day]\n #print(self.member_name,monthExtraHour)\n self._dicMonthWorkTime[begin]=monthExtraHour\n\n\nclass signer:\n def __init__(self,hr):\n self.url_sign ='http://oa.ddianle.com:8168/seeyon/ajax.do?method=ajaxAction&managerName=historyManage'#&rnd=6060'\n self._hr=hr\n \n def loadSignInfo(self,oa,bTest=False):\n signlist = [(2015,10),(2015,11),(2015,12)]\n now = datetime.datetime.now()\n for year in range(2016,now.year):\n for month in range(1,13):\n signlist.append((year,month))\n for month in range(1,now.month+1):\n signlist.append((now.year,month))\n\n if not bTest:\n signfilepath = r'sign/sign-%s-%s.txt' % (now.year,now.month)\n if os.path.exists(signfilepath):\n os.remove(signfilepath)\n \n lastmonth = now-datetime.timedelta(days=28)\n signfilepath = r'sign/sign-%s-%s.txt' % (lastmonth.year,lastmonth.month)\n if os.path.exists(signfilepath):\n os.remove(signfilepath)\n\n for v in signlist:\n year,month = v[0],v[1]\n signfilepath = r'sign/sign-%s-%s.txt' % (year,month)\n if not os.path.exists(signfilepath):\n self._getSignInfoFromOA(oa,year,month,signfilepath)\n with open(signfilepath, 'r') as f:\n strline = f.readline().strip()\n while(strline != None and len(strline)>0) :\n self._hr.updateSignInfo(strline)\n strline = f.readline().strip()\n \n\n def _getSignInfoFromOA(self,oa,year,month,signfilepath):\n fromDate = '%d-%d-%d' % (year,month,1)\n toDate = '%d-%d-%d' % (year,month,calendar.monthrange(year,month)[1])\n filterArguments = r'[{\"page\":1,\"size\":999999},{\"showByType\":\"showByDepartment\",\"deptId\":\"\",\"showByMachine\":\"showByMachine\",\"machineId\":\"\",\"showByDate\":\"showByDate\",\"fromDate\":\"%s\",\"toDate\":\"%s\",\"showByMember\":\"showByMember\",\"memberName\":\"\"}]' % (fromDate,toDate)\n dataValue={'managerMethod':'showHistoryList','arguments':filterArguments}\n web_sign = oa.post(self.url_sign,data=dataValue)\n total = int(re.findall(r'\"total\":([\\d]{0,}),\"page\"', web_sign.text)[0])\n l = re.findall(r'member_id\":\"([^\"]+)\",\"id\":[^,]+,\"new\":[^,]+,\"flag_proc\":[^,]+,\"sign_state\":[^,]+,\"address_id\":[^,]+,\"create_time\":[^,]+,\"from_type\":[^,]+,\"user_id\":[^,]+,\"department_name\":\"[^\"]+\",\"member_name\":\"([^\"]+)[^s]+\"sign_time\":\"([^\"]+)\"',web_sign.text)\n if len(l)!=total:\n raise RuntimeError('getsigntime Error',total,len(l))\n with open(signfilepath, 'w') as f:\n for line in l:\n f.write(str(line)+'\\r\\n')\n\n'''\nhr模块负责从员工表中加载所有需要统计加班信息的员工,初始化员工数据\n'''\nclass hr:\n def __init__(self,scheduling):\n self._allPerson = {} #key:member_id, vale:person\n self._scheduler = scheduling \n\n def updateSignInfo(self,singleInfo):\n #('8216671587605237062', '钱萌萌', '2018-01-31 23:04:03.0')\n tupleSingleInfo = eval(singleInfo)\n if not self._allPerson.get(tupleSingleInfo[0]):\n self._allPerson[tupleSingleInfo[0]] = person(tupleSingleInfo[0],tupleSingleInfo[1],True)\n self._allPerson[tupleSingleInfo[0]].updatePersonSingInfo(tupleSingleInfo[2])\n\n def calcExtraWorkTime(self):\n #print(self._scheduler._dicSchedule)\n with open('extraworktime.csv', 'w') as f:\n f.write('name,year-month,extraWorkHours\\n')\n for v in self._allPerson.values():\n v.calcSimpleExtraWorkTime()\n dicMonthWorkTime = v.calcMonthExtraWorkTime()\n for key,value in dicMonthWorkTime.items():\n f.write('%s,%s,%d\\n' % (v.member_name,'%d-%d'%(key.year,key.month),value))\n\n\nclass first:\n def __init__(self):\n #self._initSystemSetting()\n self._scheduler = scheduler()\n self._hr = hr(self._scheduler)\n self._signer = signer(self._hr)\n self.s = requests.Session()\n # 加headers 伪造请求头。\n self.s.headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36','Accept-Language':'zh-CN,zh;q=0.9,en;q=0.8',}\n # 取消安全认证\n self.s.verify = False\n self.loginDDL()\n\n def _initSystemSetting(self):\n with open('config.txt', 'r') as f:\n for line in f.readlines():\n print(line.strip())\n\n def loginDDL(self):\n self.url_login = 'http://oa.ddianle.com:8168/seeyon/main.do?method=login'\n self.url_main = 'http://oa.ddianle.com:8168/seeyon/main.do?method=main'\n #demo 123456 LL047 654321 073 622010\n dataValue = {'authorization':'','login_username':'LL047','login_password':'654321','login.smsVerifyCode':'','bodyWidth':'1600','bodyHeight':'900'}\n self.s.post(self.url_login ,data=dataValue)\n self.s.get(self.url_main)\n \n def t(self):\n self._scheduler.loadSchedulingInfo(self.s)\n self._signer.loadSignInfo(self.s)\n self._hr.calcExtraWorkTime()\n\n #退出登录\n\nif __name__ == '__main__' :\n t = first()\n t.t()\n\n\n\n\n","sub_path":"first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":11220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"387977499","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Mar 1 11:55:16 2020\r\n\r\n@author: Mathieu Reine\r\n\"\"\"\r\n\r\n\"\"\"Dans cette partie de code nous allons définir la classe Evaluation, \r\nnotamment pour permettre l'implémentation des onthologies,\r\nainsi que les différentes fonctions qu'on appelera à travers l'interface.\"\"\"\r\n\r\n\r\n\r\n#Cette partie de code permet de créer un jeu de d'évaluations rapidement sans passer par l'interface afin de faire\r\n#Le but principal était essentiellement de pouvoir faire un nombre important de test pour corriger le code\r\n\r\nEvaluations = []\r\n\r\n#Partie de code permettant de créer rapidement une ontologie\r\n\"\"\"\r\nCouleur= Evaluation()\r\nCouleur.change_nom('Couleur')\r\n\r\nMath= Evaluation()\r\nMath.change_nom('Math')\r\n\r\nGeographie= Evaluation()\r\nGeographie.change_nom('Geographie')\r\nGeographie.add_requirement(Math)\r\nGeographie.add_requirement(Couleur)\r\n\r\n\r\nHistoire= Evaluation()\r\nHistoire.change_nom('Histoire')\r\nHistoire.add_requirement(Geographie)\r\nHistoire.add_requirement(Math)\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass Evaluation(): #Ici on définit la classe Evaluation pour la création des onthologies \r\n #Elle est composée de son nom, de ceux qu'il requière et de ceux dont il est requis\r\n #dernier attribut est peu util mais bien pour voir si erreur\r\n \r\n \r\n \r\n def __init__(self): #Son initialisation\r\n self.nom = 'àdef'\r\n self.isArequirementTo = [[],] #Toutes les évaluations qui requièrent celle-ci et à quelle distance\r\n self.requires = [[],]#Toutes les évaluations qui ont comme requierement celle-ci et à quelle distance\r\n Evaluations.append(self)#On garde un historique de toutes les évalutations du système\r\n \r\n \r\n def change_nom(self,new_nom): #La méthode permettant de changer de nom\r\n self.nom =new_nom\r\n \r\n def add_requirement(self,evaluation): # La méthode permettant la création des requirements\r\n \r\n self.requires.append([evaluation,1])\r\n self.requires[0].append(evaluation.nom)\r\n \r\n evaluation.isArequirementTo.append([self,1])\r\n evaluation.isArequirementTo[0].append(self.nom)\r\n\r\n#Remarque : pour les attributs requires et isArequirementTo* : on a choisi la structure suivante :\r\n# [[Liste des requis/* de l'évaluation], Liste des tuples [Evaluation requise/*, distance]]\r\n# Exemple : Histoire.requires = [['Math','Géographie'],[charabia1,2],[charabia2,1]] \r\n# Histoire requiert ici Math et Géographie ; Math à une distance de 2 , Géographie à une distance de 1\r\n\r\n\"\"\"Autre remarque importante : cette structure peut sembler inutilement compliquée (ce sentiment est renforcé\r\npar la solution proposée pour la propagation des requirements) ; mais au vue des possibles futures focntionnalités\r\nl'outil j'ai décidé de garder cette structure ici si elle s'avère plus efficasse que le tableau construit en partie\r\npropagation\"\"\" \r\n\r\ndef name(x):#Fonction qui retourne le nom\r\n return(x.nom)\r\n \r\nnamer = lambda x: name(x) #Fonction applicable à une liste\r\n\r\n\r\ndef reco(Evaluations,nom):#On retrouve une eval par son nom\r\n for eval in Evaluations:\r\n if eval.nom == nom:\r\n return(eval)\r\n\r\ndef createEvaluation(nom_eval): #Fonction qui permet de créer une évaluation\r\n if nom_eval in list(map(namer, Evaluations)): #On se sert de notre namer sur tous les éléments de la liste\r\n erreur_deja_fait() #Si l'évaluation existe déjà, on le fait savoir à l'user \r\n return()#sans créer l'évaluation\r\n evaluation = Evaluation()#Sinon, on créer l'évaluation\r\n evaluation.change_nom(nom_eval)#On redéfinie son nom de 'adef' au nom que l'on a indiquer (à terme celui rentrer dans l'interface)\r\n done()\r\n return(evaluation)#On retourne l'évaluation\r\n \r\ndef createRequirement(nom_eval,nom_eval_required): ##Fonction qui permet de créer un lien requirement entre 2 évaluations\r\n for x in Evaluations: #On cherche les 2 evaluations concernées\r\n if x.nom == nom_eval:#Si c'est celui qui requiert\r\n boss=x\r\n if x.nom == nom_eval_required:#Si c'est celui qui est requis\r\n required=x\r\n if nom_eval_required not in list(map(namer, Evaluations)): #Si l'évaluation requise non créer alors on la créer\r\n createEvaluation(nom_eval_required)#Sans créer le lien ! (c'est facultatif ou perfectible comme approche)\r\n if boss.nom in reco(Evaluations,nom_eval_required).isArequirementTo[0] : #Si il fait déjà parti de nos requis\r\n erreur_deja_fait()#On l'indique à l'utilisateur\r\n return()#On ne fait rien de plus\r\n boss.add_requirement(required) #Sinon on ajoute le lien\r\n done()\r\n return(nom_eval,nom_eval_required)#On retourne les 2 evaluations\r\n \r\n \r\n#Ces fonctions ne fonctionnent pas/que partiellement, plus simple de passer par des bases SQL\r\n\r\ndef SuppEval(Evaluations,nom_eval):#Fonction suppression d'éval : ne fonctionne pas\r\n for i in range(len(Evaluations)) :\r\n if Evaluations[i].nom == nom_eval :\r\n print('see')\r\n del(Evaluations[i])\r\n break\r\n \r\n for i in range(len(Evaluations)) :\r\n for k in range(len(Evaluations[i].requires[0])):\r\n if Evaluations[i].requires[0][k] == nom_eval :\r\n del(Evaluations[i].requires[0][k])\r\n break\r\n \r\n for k in range(len(Evaluations[i].requires[1:])):\r\n print(Evaluations[i].requires[1:][k][0].nom)\r\n if Evaluations[i].requires[1:][k][0].nom == nom_eval:\r\n print('hello')\r\n print(Evaluations[i].requires[1:][k])\r\n del(Evaluations[i].requires[1:][k]) #Ne marche pas\r\n break\r\n \r\n for k in range(len(Evaluations[i].isArequirementTo[0])):\r\n if Evaluations[i].isArequirementTo[0][k] == nom_eval :\r\n del(Evaluations[i].isArequirementTo[0][k])\r\n break\r\n \r\n for k in range(len(Evaluations[i].isArequirementTo[1:])):\r\n if Evaluations[i].isArequirementTo[1:][k][0].nom == nom_eval:\r\n del(Evaluations[i].isArequirementTo[1:][k]) #Ne marche pas\r\n break\r\n \r\n return(Evaluations)\r\n \r\ndef Supplien(Evaluations,nom_eval1,nom_eval2): #Fonction qui supprime un lien : ne fonctionne pas\r\n \r\n for i in range(len(Evaluations)) :\r\n for k in range(len(Evaluations[i].requires[0])):\r\n if Evaluations[i].requires[0][k] in [nom_eval1, nom_eval2] :\r\n del(Evaluations[i].requires[0][k])\r\n break\r\n \r\n for k in range(len(Evaluations[i].isArequirementTo[1:])):\r\n if len(Evaluations[i].isArequirementTo[1:]) == 0:\r\n break\r\n if Evaluations[i].isArequirementTo[1:][k][0].nom == nom_eval1:\r\n del(Evaluations[i].isArequirementTo[1:][k]) #Ne marche pas\r\n break\r\n \r\n for k in range(len(Evaluations[i].requires[1:])):\r\n if len(Evaluations[i].requires[1:]) == 0:\r\n break\r\n if Evaluations[i].requires[1:][k][0].nom == nom_eval2:\r\n del(Evaluations[i].requires[1:][k]) #Ne marche pas\r\n break\r\n \r\n return(Evaluations)\r\n \r\n\r\n","sub_path":"Scripts/classEvaluation.py","file_name":"classEvaluation.py","file_ext":"py","file_size_in_byte":7376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"221408817","text":"class listnode:\n def __init__(self ,name):\n self.name = name\n self.next = None\n return\n \n def values(self ,value):\n \"moghayes value ba node data\"\n if self.name == value:\n return True\n else:\n return False\n \n \nclass linked_lists:\n def __init__(self):\n self.root = None\n self.begin = None\n self.end = None\n self.lenght= 0\n return\n \n def add_begin(self ,newItem):\n if self.root == None:\n self.root = newItem\n else:\n newItem.next = self.root\n self.root = newItem\n self.lenght = self.lenght + 1\n \n \n def add_mdt(self ,perItem ,newItem):\n x = perItem.next\n perItem.next = newItem\n newItem.next = x\n self.lenght = self.lenght + 1\n \n \n def add_end(self ,newItem):\n if self.root == None:\n self.root = newItem\n else:\n if self.root.next == None:\n self.root.next = newItem\n if self.end != None:\n self.end.next = newItem\n self.end = newItem\n \n\n def remove(self ,item):\n if self.root == item:\n self.root = self.root.next\n else:\n self.root.next = srn\n while True:\n if srn == item:\n break\n srn = self.root\n \n \n def printLL(self):\n if self.root == None:\n print('Empty!')\n else:\n x = self.root\n print(self.root.name)\n while (self.root.next):\n x = x.next\n print(x.name)\n \n \n \n#node1 = listnode(10) ; node2 = listnode(20) ; node3 = listnode(\"hamed\")\n#print(node1.values(15))\n\nmain = linked_lists()\nitem_1 = listnode(\"hamed\") ; item_2 = listnode(\"ali\") ; item_3 = listnode(\"yaser\")\nitem_4 = listnode(\"mm\") ; item_5 = listnode(\"nima\") ; item_6 = listnode(\"sima\")\n\nmain.add_begin(item_1)\nmain.add_mdt(item_1,item_4)\nmain.add_end(item_3)\n\n#remove()\nmain.printLL()\n","sub_path":"Object Oriented/Liked_lists.py","file_name":"Liked_lists.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"58410507","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n\"\"\"\n用微信远程控制电脑\n\"\"\"\n\nfrom datetime import datetime\nimport os\nimport cv2\nimport itchat\n\nsendMsg = u'{消息助手}:暂时无法回复'\n# usageMsg: 操作信息\nusageMsg = u'使用方法:\\n' \\\n u'1. 获取电脑前的用户:cap\\n' \\\n u'2. 运行 CMD 命令:cmd + [cmd 命令],如“cmd msg /server;127.0.0.1 * 您好”\\n' \\\n u'3. 获取日志:log\\n' \\\n# print(usageMsg)\n\nlogfile = 'log.txt'\n\ndef write_log(message):\n with open(logfile, 'a') as log:\n log.write(datetime.now().strftime('%Y/%m/%d %H:%M:%S') + ' -> ' + message + '\\n')\n\n@itchat.msg_register('Text')\ndef text_reply(msg):\n message = msg['Text']\n toName = msg['ToUserName']\n\n if toName == 'filehelper':\n if message == 'cap' or message == '1':\n write_log(message)\n cap = cv2.VideoCapture(0)\n ret, img = cap.read()\n cv2.imwrite('WeChat/weixinTemp.jpg', img)\n itchat.send('@img@%s' % u'WeChat/weixinTemp.jpg', toUserName='filehelper')\n os.remove('WeChat/weixinTemp.jpg')\n cap.release()\n if message[0:3] == 'cmd':\n write_log(message)\n os.system(message[4:])\n if message == 'log' or message == '3':\n write_log(message)\n with open(logfile, 'r') as log:\n log_content = log.read()\n itchat.send(log_content, 'filehelper')\n\n\nif __name__ == '__main__':\n itchat.auto_login(hotReload=True)\n itchat.send(usageMsg, toUserName='filehelper')\n itchat.run()\n","sub_path":"WeChat_remotely.py","file_name":"WeChat_remotely.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"523273584","text":"import re\n\nfrom collections import namedtuple\nfrom jujubundlelib.references import Reference\nfrom urllib.parse import unquote\n\n\nuuid_re = b'environment_uuid=[\\w]{8}-[\\w]{4}-[\\w]{4}-[\\w]{4}-[\\w]{12}'\ncloud_re = b'provider=[^,\\\"]*'\nregion_re = b'cloud_region=[^,\\\"]*'\nversion_re = b'controller_version=[^,\\\"]*'\napplication_re = b'[&?]id=[^&,\\\"]*'\nchannel_re = b'[&?]channel=[^&,\\\"]*'\n\nApplication = namedtuple(\n 'Application', 'charmid, appname, series, owner, channel')\nMetadata = namedtuple(\n 'Metadata', 'version, cloud, region')\nLogLine = namedtuple('LogLine', 'uuid, date, Application, Metadata')\n\n\ndef find_uuid(l):\n m = re.search(uuid_re, l)\n if m:\n uuid = m.group(0)\n # Make sure to decode the uuid or else sqlite won't be able to filter\n # it in bytes.\n var = uuid.split(b'=')[1].decode('utf-8')\n return var\n else:\n return None\n\n\ndef find_metadata(l):\n c = re.search(cloud_re, l)\n cr = re.search(region_re, l)\n v = re.search(version_re, l)\n cloud = b'pre-2'\n region = b'pre-2'\n version = b'pre-2'\n\n if c:\n _, cloud = c.group().split(b'=')\n\n if cr:\n _, region = cr.group().split(b'=')\n\n if v:\n _, version = v.group().split(b'=')\n\n found = Metadata(version.decode('utf-8'),\n cloud.decode('utf-8'),\n region.decode('utf-8'))\n return found\n\n\ndef find_application(l):\n \"\"\"Process a log line looking for the application id\"\"\"\n # We also need to return a root \"appname\" so we can tell how many of an\n # application is out there regardless of the owner/etc.\n charmid = None\n series = None\n channel = None\n appname = None\n owner = None\n app_raw = re.search(application_re, l)\n if app_raw:\n _, charmid = app_raw.group().split(b'=')\n charmid = unquote(charmid.decode(\"utf-8\"))\n\n # Use the jujubundlelib to parse the charm url for the series\n try:\n ref = Reference.from_string(charmid)\n except ValueError:\n # skip things if there's an error parsing the charm url\n print ('Could not properly parse: {}'.format(charmid))\n return None\n series = ref.series\n appname = ref.name\n owner = ref.user if ref.user else None\n\n channel_found = re.search(channel_re, l)\n if channel_found:\n _, channel = channel_found.group().split(b'=')\n channel = channel.decode('utf-8')\n\n found = Application(charmid, appname, series, owner, channel)\n return found\n\n\ndef process_log_line(l, date):\n uuid = find_uuid(l)\n meta = find_metadata(l)\n app = find_application(l)\n # There's multiple log lines, one for each charmid that's requested so\n # we only load the uuid hit once, but we load the application found\n # regardless of if there's a previous uuid row like above.\n return LogLine(uuid, date, app, meta)\n\n # if app:\n # c.execute('''\n # INSERT OR REPLACE INTO application_hits (\n # uuid,charmid,appname,series,owner,channel,day)\n # VALUES (?, ?, ?, ?, ?, ?, ?);''', [\n # uuid, app.charmid, app.appname, app.series, app.owner,\n # app.channel, date])\n #\n # c.execute('''\n # INSERT OR REPLACE INTO model_hits (uuid, version, day)\n # VALUES (?, ?, ?);''', [uuid, meta[0], date])\n","sub_path":"kpi/apachelog.py","file_name":"apachelog.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"231415084","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.home, name='home'),\n url(r'^spider/new/', views.spider_new, name='spider_new'),\n url(r'^detail/', views.detail, name='detail'),\n url(r'^list_spider', views.list_spider, name='list_spider'),\n url(r'^list_extract', views.list_extract, name='list_extract')\n\n]","sub_path":"baby_spider/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"353434770","text":"#!/usr/bin/env python\n\nimport argparse\nimport numpy as np\nimport yaml\nimport sys\nimport itertools\nfrom multiprocessing import Pool\nfrom pyGSI.diags import Radiance\nfrom pyGSI.netcdf_diags import write_netcdf\nfrom pyGSI.spatial_bin import spatial_bin\nfrom datetime import datetime\n\nstart_time = datetime.now()\n\n\ndef create_netcdf(sat_config):\n \n diagfile = sat_config['radiance input']['path'][0]\n diag_type = sat_config['radiance input']['data type'][0].lower()\n channel = sat_config['radiance input']['channel']\n qcflag = sat_config['radiance input']['qc flag']\n outdir = sat_config['outdir']\n\n diag = Radiance(diagfile)\n\n data = diag.get_data(diag_type, channel=channel, qcflag=qcflag)\n lats, lons = diag.get_lat_lon(channel=channel, qcflag=qcflag)\n\n metadata = diag.metadata\n\n binned_data = spatial_bin(data, lats, lons, binsize='1x1')\n\n write_netcdf(data, binned_data, metadata, outdir)\n\n return\n\n\n###############################################\n\n# Parse command line\nap = argparse.ArgumentParser()\nap.add_argument(\"-n\", \"--nprocs\",\n help=\"Number of tasks/processors for multiprocessing\")\nap.add_argument(\"-y\", \"--yaml\",\n help=\"Path to yaml file with diag data\")\nap.add_argument(\"-o\", \"--outdir\",\n help=\"Out directory where files will be saved\")\n\nmyargs = ap.parse_args()\n\nif myargs.nprocs:\n nprocs = int(myargs.nprocs)\nelse:\n nprocs = 1\n\ninput_yaml = myargs.yaml\noutdir = myargs.outdir\n\nwith open(input_yaml, 'r') as file:\n parsed_yaml_file = yaml.load(file, Loader=yaml.FullLoader)\n\nfor w in parsed_yaml_file['diagnostic']:\n w['outdir'] = outdir\n\nwork = (parsed_yaml_file['diagnostic'])\n\np = Pool(processes=nprocs)\np.map(create_netcdf, work)\n\nprint(datetime.now() - start_time)\n","sub_path":"scripts/create_sat_netcdf.py","file_name":"create_sat_netcdf.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"336415569","text":"import os\nfrom flask import Flask, request, redirect, url_for, send_from_directory\nfrom werkzeug.utils import secure_filename\nfrom os.path import join, dirname, realpath\nimport time\nfrom proccess import home_page,upload_convert_pdf,get_first_info,crop,get,check_file,display\nfrom flask import Flask, flash, request, redirect, url_for, render_template\nfrom flask_restful import Resource, Api ,reqparse, abort\nfrom os import walk\nfrom jinja2 import Environment, FileSystemLoader\nimport json\nimport cv2\n\ndef get_rect(data_):\n# print(data_)\n data_=json.loads(data_)\n x_start=int(data_['x'])\n y_start=int(data_['y'])\n x_end=x_start+int(data_['width'])\n y_end=y_start+int(data_['height'])\n rotate=int(data_['rotate'])\n return x_start,y_start,x_end,y_end,rotate\n\ndef get_data(path_main, name0):\n\n name0 = name0 + '.jpg'\n\n\n\n profile_ocr = {}\n profile_ocr['text'] = []\n profile_ocr['text'].append({})\n # name=\"1409-004-Key-Elevation-Bank-.json\"\n # path_json=\"./static/img/rlogo/\"\n path_json = os.path.join(path_main, \"rlogo/\")\n # path_logo=\"./static/img/croped_img_300/\"\n path_logo = os.path.join(path_main, \"croped_img_300/\")\n # path_img=\"./static/img/croped_img_300/\"\n path_img = os.path.join(path_main, \"croped_img_300/\")\n path_rect = os.path.join(path_main, \"croped_rect/\")\n if name0 in str(os.listdir(path_main)):\n return path_rect + name0\n\n file_json = name0.replace('jpg', 'json')\n file_json = path_json + file_json\n file_logo = file_json.replace('json', 'jpg').replace('rlogo', 'croped_img')\n image = cv2.imread(file_logo)\n\n print(file_json)\n with open(file_json) as datafile:\n data = json.load(datafile)\n\n title = data['title']\n print('title :', title)\n x_start, y_start, x_end, y_end, rotate = get_rect(title)\n img = cv2.rectangle(image, (int(x_start), int(y_start)), (int(x_end), int(y_end)), (0, 255, 0), 7)\n drawingN = data['project_number']\n x_start, y_start, x_end, y_end, rotate = get_rect(drawingN)\n img = cv2.rectangle(img, (x_start, y_start), (x_end, y_end), (0, 0, 255), 7)\n\n revsion = data['revsion']\n x_start, y_start, x_end, y_end, rotate = get_rect(revsion)\n img = cv2.rectangle(img, (x_start, y_start), (x_end, y_end), (255, 0, 0), 7)\n\n cv2.imwrite(path_rect + name0, img)\n\n return path_rect + name0\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\njson_info={\n \"filename\":\"\",\n \"coo_img\":\"\",\n \"title\":\"\",\n \"revsion\":\"\",\n \"price\":\"\",\n \"project_number\":\"\"\n}\n\nUPLOADS_PATH = join(dirname(realpath(__file__)), 'static/img/')\n\n\nUPLOAD_FOLDER = '/tmp/flask-upload-test/'\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])\n\napp = Flask(__name__)\napi = Api(app)\n\napp.config['UPLOAD_FOLDER'] = UPLOADS_PATH\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0\n\nfile_loader = FileSystemLoader(\"templates\")\nenv = Environment(loader=file_loader)\n\ndef delet_from_drc(filename):\n try:\n os.remove(\"./static/img/rlogo/{}.json\".format(filename))\n except FileNotFoundError:\n pass\n try:\n os.remove(\"./static/img/croped_img/{}.jpg\".format(filename))\n except FileNotFoundError:\n pass\n try:\n os.remove(\"./static/img/croped_img_200/{}.jpg\".format(filename))\n except:\n pass\n\n\n\n\n\n\nclass HelloWorld(Resource):\n def get(self):\n mypath = \"./static/img/croped_img\"\n f = []\n for (dirpath, dirnames, filenames) in walk(mypath):\n f.extend(filenames)\n break\n template = env.get_template(\"img_container.html\")\n output = template.render(images=f)\n if len(f) == 0:\n output = \"

No Images To Load

\"\n\n return {'html': output}\n\n def post(self):\n json_data = request.get_json(force=True)\n json_data= (json_data['src'].split('\\\\')[-1]).split('.')[0:-1]\n json_data=\".\".join(json_data)\n delet_from_drc(json_data)\n return str({\"status\":True})\n\nclass post(Resource):\n def post(self):\n json_data = request.get_json(force=True)\n\n\n\n json_data = (json_data['src'].split('/')[-1]).split('.')[0:-1]\n json_data = \".\".join(json_data)\n\n aa = get_data(app.config['UPLOAD_FOLDER'], json_data.replace(\"%20\",\" \"))\n\n\n\n\n #aa=get_data(\"./static/\", json_data['filename'])\n\n return json_data\n\napi.add_resource(HelloWorld, '/hello')\n\napi.add_resource(post, '/posts')\n\n\n\nfilename=None\n@app.route('/check', methods=['GET', 'POST'])\ndef check():\n return check_file(app, request)\n\n@app.route('/display')\ndef display_img():\n return render_template('index.html')\n\n\n\n@app.route('/')\ndef first():\n return home_page()\n\n@app.route('/second', methods=['GET', 'POST'])\ndef second():\n\n filename=upload_convert_pdf(app,request)\n json_info[\"filename\"] = filename\n return render_template('crop_first_img.html', msg= filename)\n\n@app.route('/third', methods=['GET', 'POST'])\ndef third():\n print(json_info[\"filename\"])\n return get_first_info(app,request,json_info[\"filename\"])\n\n\n@app.route('/finish', methods=['GET', 'POST'])\ndef finish():\n print(get())\n json_info[\"coo_img\"]=get()\n print(json_info[\"filename\"])\n return crop(app,request,json_info)\n\n\n\n\nif __name__ == \"__main__\":\n\tapp.run(host=\"0.0.0.0\", port=80,debug=True)\n","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":5304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"636328910","text":"#\n# Copyright (c) 2011, Canonical Ltd\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as published by\n# the Free Software Foundation, version 3 only.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see .\n# GNU Lesser General Public License version 3 (see the file LICENSE).\n\n\"\"\"The primary interface to oopses stored on disk - the DateDirRepo.\"\"\"\n\nfrom __future__ import absolute_import, print_function\n\n__metaclass__ = type\n\n__all__ = [\n 'DateDirRepo',\n ]\n\nimport datetime\nimport errno\nfrom functools import partial\nfrom hashlib import md5\nimport os.path\nimport stat\n\nfrom pytz import utc\n\nfrom oops_datedir_repo import (\n anybson as bson,\n serializer,\n serializer_bson,\n )\n\n\nclass DateDirRepo:\n \"\"\"Publish oopses to a date-dir repository.\n\n A date-dir repository is a directory containing:\n\n * Zero or one directories called 'metadata'. If it exists this directory\n contains any housekeeping material needed (such as a metadata.conf ini\n file).\n\n * Zero or more directories named like YYYY-MM-DD, which contain zero or\n more OOPS reports. OOPS file names can take various forms, but must not\n end in .tmp - those are considered to be OOPS reports that are currently\n being written.\n\n * The behaviour of this class is to assign OOPS file names by hashing the\n serialized OOPS to get a unique file name. Other naming schemes are\n valid - the code doesn't assume anything other than the .tmp limitation\n above.\n \"\"\"\n\n def __init__(self, error_dir, serializer=None, inherit_id=False,\n stash_path=False):\n \"\"\"Create a DateDirRepo.\n\n :param error_dir: The base directory to write OOPSes into. OOPSes are\n written into a subdirectory this named after the date (e.g.\n 2011-12-30).\n :param serializer: If supplied should be the module (e.g.\n oops_datedir_repo.serializer_rfc822) to use to serialize OOPSes.\n Defaults to using serializer_bson.\n :param inherit_id: If True, use the oops ID (if present) supplied in\n the report, rather than always assigning a new one.\n :param stash_path: If True, the filename that the OOPS was written to\n is stored in the OOPS report under the key 'datedir_repo_filepath'.\n It is not stored in the OOPS written to disk, only the in-memory\n model.\n \"\"\"\n self.root = error_dir\n if serializer is None:\n serializer = serializer_bson\n self.serializer = serializer\n self.inherit_id = inherit_id\n self.stash_path = stash_path\n self.metadatadir = os.path.join(self.root, 'metadata')\n self.config_path = os.path.join(self.metadatadir, 'config.bson')\n\n def publish(self, report, now=None):\n \"\"\"Write the report to disk.\n\n The report is written to a temporary file, and then renamed to its\n final location. Programs concurrently reading from a DateDirRepo\n should ignore files ending in .tmp.\n\n :param now: The datetime to use as the current time. Will be\n determined if not supplied. Useful for testing.\n \"\"\"\n # We set file permission to: rw-r--r-- (so that reports from\n # umask-restricted services can be gathered by a tool running as\n # another user).\n wanted_file_permission = (\n stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)\n if now is not None:\n now = now.astimezone(utc)\n else:\n now = datetime.datetime.now(utc)\n # Don't mess with the original report when changing ids etc.\n original_report = report\n report = dict(report)\n md5hash = md5(serializer_bson.dumps(report)).hexdigest()\n oopsid = 'OOPS-%s' % md5hash\n prefix = os.path.join(self.root, now.strftime('%Y-%m-%d'))\n if not os.path.isdir(prefix):\n try:\n os.makedirs(prefix)\n except OSError as err:\n # EEXIST - dir created by another, concurrent process\n if err.errno != errno.EEXIST:\n raise\n # For directories we need to set the x bits too.\n os.chmod(\n prefix, wanted_file_permission | stat.S_IXUSR | stat.S_IXGRP |\n stat.S_IXOTH)\n filename = os.path.join(prefix, oopsid)\n if self.inherit_id:\n oopsid = report.get('id') or oopsid\n report['id'] = oopsid\n with open(filename + '.tmp', 'wb') as f:\n self.serializer.write(report, f)\n os.rename(filename + '.tmp', filename)\n if self.stash_path:\n original_report['datedir_repo_filepath'] = filename\n os.chmod(filename, wanted_file_permission)\n return [report['id']]\n\n def republish(self, publisher):\n \"\"\"Republish the contents of the DateDirRepo to another publisher.\n\n This makes it easy to treat a DateDirRepo as a backing store in message\n queue environments: if the message queue is down, flush to the\n DateDirRepo, then later pick the OOPSes up and send them to the message\n queue environment.\n\n For instance:\n\n >>> repo = DateDirRepo('.')\n >>> repo.publish({'some':'report'})\n >>> queue = []\n >>> def queue_publisher(report):\n ... queue.append(report)\n ... return report['id']\n >>> repo.republish(queue_publisher)\n\n Will scan the disk and send the single found report to queue_publisher,\n deleting the report afterwards.\n\n Empty datedir directories are automatically cleaned up, as are stale\n .tmp files.\n\n If the publisher returns None, signalling that it did not publish the\n report, then the report is not deleted from disk.\n \"\"\"\n two_days = datetime.timedelta(2)\n now = datetime.date.today()\n old = now - two_days\n for dirname, (y,m,d) in self._datedirs():\n date = datetime.date(y, m, d)\n prune = date < old\n dirpath = os.path.join(self.root, dirname)\n files = os.listdir(dirpath)\n if not files and prune:\n # Cleanup no longer needed directory.\n os.rmdir(dirpath)\n for candidate in map(partial(os.path.join, dirpath), files):\n if candidate.endswith('.tmp'):\n if prune:\n os.unlink(candidate)\n continue\n with open(candidate, 'rb') as report_file:\n try:\n report = serializer.read(report_file)\n except IOError as e:\n if e.args[0] == 'Empty OOPS Report':\n report = None\n else:\n raise\n if report is not None:\n oopsid = publisher(report)\n if (report is None and prune) or (report is not None and oopsid):\n os.unlink(candidate)\n\n def _datedirs(self):\n \"\"\"Yield each subdir which looks like a datedir.\"\"\"\n for dirname in os.listdir(self.root):\n try:\n y, m, d = dirname.split('-')\n y = int(y)\n m = int(m)\n d = int(d)\n except ValueError:\n # Not a datedir\n continue\n yield dirname, (y, m, d)\n\n def _read_config(self):\n \"\"\"Return the current config document from disk.\"\"\"\n try:\n with open(self.config_path, 'rb') as config_file:\n return bson.loads(config_file.read())\n except IOError as e:\n if e.errno != errno.ENOENT:\n raise\n return {}\n\n def get_config(self, key):\n \"\"\"Return a key from the repository config.\n\n :param key: A key to read from the config.\n \"\"\"\n return self._read_config()[key]\n\n def set_config(self, key, value):\n \"\"\"Set config option key to value.\n\n This is written to the bson document root/metadata/config.bson\n\n :param key: The key to set - anything that can be a key in a bson\n document.\n :param value: The value to set - anything that can be a value in a\n bson document.\n \"\"\"\n config = self._read_config()\n config[key] = value\n try:\n with open(self.config_path + '.tmp', 'wb') as config_file:\n config_file.write(bson.dumps(config))\n except IOError as e:\n if e.errno != errno.ENOENT:\n raise\n os.mkdir(self.metadatadir)\n with open(self.config_path + '.tmp', 'wb') as config_file:\n config_file.write(bson.dumps(config))\n os.rename(self.config_path + '.tmp', self.config_path)\n\n def oldest_date(self):\n \"\"\"Return the date of the oldest datedir in the repository.\n\n If pruning / resubmission is working this should also be the date of\n the oldest oops in the repository.\n \"\"\"\n dirs = list(self._datedirs())\n if not dirs:\n raise ValueError(\"No OOPSes in repository.\")\n return datetime.date(*sorted(dirs)[0][1])\n\n def prune_unreferenced(self, start_time, stop_time, references):\n \"\"\"Delete OOPS reports filed between start_time and stop_time.\n\n A report is deleted if all of the following are true:\n\n * it is in a datedir covered by [start_time, stop_time] inclusive of\n the end points.\n\n * It is not in the set references.\n\n * Its timestamp falls between start_time and stop_time inclusively or\n it's timestamp is outside the datedir it is in or there is no\n timestamp on the report.\n\n :param start_time: The lower bound to prune within.\n :param stop_time: The upper bound to prune within.\n :param references: An iterable of OOPS ids to keep.\n \"\"\"\n start_date = start_time.date()\n stop_date = stop_time.date()\n midnight = datetime.time(tzinfo=utc)\n for dirname, (y,m,d) in self._datedirs():\n dirdate = datetime.date(y, m, d)\n if dirdate < start_date or dirdate > stop_date:\n continue\n dirpath = os.path.join(self.root, dirname)\n files = os.listdir(dirpath)\n deleted = 0\n for candidate in map(partial(os.path.join, dirpath), files):\n if candidate.endswith('.tmp'):\n # Old half-written oops: just remove.\n os.unlink(candidate)\n deleted += 1\n continue\n with open(candidate, 'rb') as report_file:\n report = serializer.read(report_file)\n report_time = report.get('time', None)\n if (report_time is None or\n getattr(report_time, 'date', None) is None or\n report_time.date() < dirdate or\n report_time.date() > dirdate):\n # The report is oddly filed or missing a precise\n # datestamp. Treat it like midnight on the day of the\n # directory it was placed in - this is a lower bound on\n # when it was actually created.\n report_time = datetime.datetime.combine(\n dirdate, midnight)\n if (report_time >= start_time and\n report_time <= stop_time and\n report['id'] not in references):\n # Unreferenced and prunable\n os.unlink(candidate)\n deleted += 1\n if deleted == len(files):\n # Everything in the directory was deleted.\n os.rmdir(dirpath)\n","sub_path":"venv/Lib/site-packages/oops_datedir_repo/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":12356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"89189420","text":"import torch\nimport torch.nn as nn\n\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# in/out init\nx=torch.randn(N, D_in)\ny=torch.randn(N, D_out)\n\nmodel = nn.Sequential(\n nn.Linear(D_in, H),\n nn.ReLU(),\n nn.Linear(H, D_out)\n)\n\nloss_fn = nn.MSELoss(size_average=False)\n\nlearning_rate = 1e-4\n\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\nfor t in range(500):\n y_pred = model(x)\n\n loss=loss_fn(y_pred, y)\n print(t, loss.item())\n\n optimizer.zero_grad()\n\n loss.backward()\n optimizer.step()","sub_path":"optim_example.py","file_name":"optim_example.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"444206799","text":"#\n# Este codigo tiene como fin la generación de datos de entrenamiento\n#\nimport numpy as np\n\n####### Parametros Editables ###############\ndefault \t\t= True\nnro_puntos \t\t= 30\nnro_samples \t= 7\nradio \t\t\t= 50\nc \t\t\t\t= 350\nf \t\t\t\t= 22000\nerror_medicion \t= 2/f\n# -----------------------------------------\nnro_mics \t\t= 4\ntot_mics \t\t= np.zeros((nro_mics, 3))\ntot_mics[0] \t= np.array([1,0,0])\ntot_mics[1] \t= np.array([0,1,0])\ntot_mics[2] \t= np.array([0,0,1])\ntot_mics[3] \t= np.array([1,0,1])\n############################################\n\nif default:\n\tnro_mics = 10\n\tr_mics = 1\n\tdist = 30\n\n\tmics = np.zeros((nro_mics/2, 3))\n\tdelta =np.zeros((nro_mics/2, 3))\n\n\tmics[0] = np.array([1, 0, 0])*r_mics\n\tmics[1] = np.array([0, 1, 0])*r_mics\n\tmics[2] = np.array([0, 0, 1])*r_mics\n\tmics[3] = np.array([-1, 0, 0])*r_mics\n\tmics[4] = np.array([0, -1, 0])*r_mics\n\n\tdelta[:,0] = 1\n\tmics0 = mics + delta*dist/2\n\tmics1 = mics - delta*dist/2\n\n\ttot_mics = np.zeros((nro_mics,3))\n\n\ttot_mics[:int(nro_mics/2), :] = mics0\n\ttot_mics[int(nro_mics/2):, :] = mics1\n\t\ndelays_real \t= np.ones((nro_puntos*nro_samples, (nro_mics)*(nro_mics -1)//2))\ndelays_medidos \t= np.ones((nro_puntos*nro_samples, (nro_mics)*(nro_mics -1)//2))\nfuentes_pos \t= np.ones((nro_puntos*nro_samples, 3))\n\nfor i in range(nro_puntos):\n\tfuente = np.ones(3)*radio*2\n\twhile np.linalg.norm(fuente) > radio:\n\t\tfuente = (np.random.rand(3)*2 - 1) *radio\n\tfuentes = np.ones((len(tot_mics),3)) \n\tfuentes = fuentes*fuente\n\ttiempos = np.linalg.norm((tot_mics - fuentes), axis = 1)/c\n\tfuentes_pos[i*nro_samples:(i+1)*nro_samples] *= fuentes[0]\n\tpos = 0\n\tfor j in range(nro_mics):\n\t\tfor k in range(j+1, nro_mics):\n\t\t\tdelays_real[i*nro_samples:(i+1)*nro_samples, pos] *= tiempos[j] - tiempos[k]\n\t\t\tdelays_medidos[i*nro_samples:(i+1)*nro_samples, pos] *= (tiempos[j] - tiempos[k]) + (np.random.rand(nro_samples)*2 -1) * (error_medicion)\n\t\t\tpos += 1\n\nnp.save('delays_real.npy', delays_real)\nnp.save('delays_medidos.npy', delays_medidos)\nnp.save('fuentes_pos.npy', fuentes_pos)\n\n\n\n","sub_path":"AI/dataset_generator.py","file_name":"dataset_generator.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"259929476","text":"\r\n#Comma Code\r\n#Say you have a list value like this: spam = [' apples', 'bananas', 'tofu', 'cats']\r\n#Write a function that takes a list value as an argument\r\n#and returns a string with all the items separated by a comma and a space, with and inserted before the last item.\r\n#For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'.\r\n#But your function should be able to work with any list value passed to it.\r\n#Sweigart, Al (2015-04-21). Automate the Boring Stuff with Python: Practical Programming for Total Beginners (Kindle Locations 2565-2570). No Starch Press. Kindle Edition. \r\n\r\n#comma separated lists\r\n\r\naList = ['one','two','three','four','five',]\r\nnewItem = ''\r\nsComma = ', '\r\nsAnd = ''\r\nlastItem = len(aList) - 1 \r\nfor item in range(len(aList)):\r\n if item == lastItem:\r\n sAnd = ' and '\r\n newItem = newItem + sComma + sAnd + aList[item]\r\n print (newItem)\r\n","sub_path":"python/automation/commas.py","file_name":"commas.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"592276257","text":"# tobe continued: speedup using numba\nfrom numba import jit\nimport math\nimport time\nimport sys\n\n@jit\ndef jittest():\n # 准备pow数组,p[i][j]保存pow(i,j)\n p = []\n item = []\n for i in range(10):\n item = []\n for j in range(10):\n item.append( pow(i,j) )\n p.append(item)\n\n start = time.time()\n\n for bits_count in range(3,10):\n loopstart = pow(10, bits_count-1)\n loopend = pow(10, bits_count)\n \n for i in range(loopstart, loopend):\n sum = 0\n data = i\n while(data>0):\n bits = data%10\n data = data // 10\n sum += p[bits][bits_count]\n if sum==i:\n print(i,end=' ')\n sys.stdout.flush()\n end = time.time()\n print(\"\\ttime used:%s\"%(end-start))\n\njittest()\n\n","sub_path":"samples/4_daffodil.py","file_name":"4_daffodil.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"216880676","text":"import json\r\nimport requests\r\nimport csv\r\nimport time\r\n\r\n\r\nsensordata=[]\r\nwith open('feeds.csv','rt')as f:\r\n data = csv.reader(f)\r\n for row in data:\r\n sensordata.append(row)\r\nmoisture=[]\r\ntemperature=[]\r\nhumidity=[]\r\na=['created_at','value']\r\nmoisture.append(a)\r\ntemperature.append(a)\r\nhumidity.append(a)\r\nfor i in range(1,len(sensordata)):\r\n q=sensordata[i]\r\n d=q[0]\r\n d=d.replace(' ','T',1)\r\n d=d.replace(' UTC','Z')\r\n if q[2]!= '':\r\n if q[2]!= 'nan':\r\n b=[d,q[2]]\r\n moisture.append(b)\r\n elif q[3]!= '':\r\n if q[3]!= 'nan':\r\n b=[d,q[3]]\r\n temperature.append(b)\r\n elif q[4]!= '':\r\n if q[4]!= 'nan':\r\n b=[d,q[4]]\r\n humidity.append(b)\r\n\r\nwith open('moisture.csv', mode='w',newline='') as file:\r\n writer = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n for i in moisture:\r\n writer.writerow(i)\r\nfile.close()\r\nwith open('temperature.csv', mode='w',newline='') as file:\r\n writer = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n for i in temperature:\r\n writer.writerow(i)\r\nfile.close()\r\nwith open('humidity.csv', mode='w',newline='') as file:\r\n writer = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n for i in humidity:\r\n writer.writerow(i)\r\nfile.close()\r\n\r\n\r\n#part2\r\n\r\n\r\nwhile True:\r\n file = open(\"testfile.txt\", \"r\")\r\n a=int(file.read())\r\n file.close()\r\n r=requests.get(\"https://api.thingspeak.com/channels/1017098/feeds/last?key=06YA3OIVYUNINUM3\")\r\n data = r.json()\r\n i=[]\r\n i.append(data['created_at'])\r\n i.append(data['entry_id'])\r\n i.append(data['field1'])\r\n i.append(data['field2'])\r\n i.append(data['field3'])\r\n file=open(\"last.txt\",\"r\")\r\n c=file.read()\r\n file.close()\r\n c=[str(x) for x in c.split(\" \")]\r\n if(a!=data['entry_id']):\r\n file = open(\"C:/xampp/htdocs/server2.txt\",\"w+\")\r\n d='Online'\r\n file.write(d)\r\n file.close()\r\n print('Online')\r\n print(i)\r\n if i[2]!= None:\r\n b=[i[0],i[2]]\r\n c[1]=i[2]\r\n file = open(\"last.txt\",\"w+\")\r\n d=' '.join(str(x) for x in c)\r\n file.write(d)\r\n file.close() \r\n with open('moisture.csv', mode='a',newline='') as file:\r\n writer = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n writer.writerow(b)\r\n elif i[3]!= None:\r\n b=[i[0],i[3]]\r\n c[2]=i[3]\r\n file = open(\"last.txt\",\"w+\")\r\n d=' '.join(str(x) for x in c)\r\n file.write(d)\r\n file.close()\r\n with open('temperature.csv', mode='a',newline='') as file:\r\n writer = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n writer.writerow(b)\r\n elif i[4]!= None:\r\n b=[i[0],i[4]]\r\n c[3]=i[4]\r\n file = open(\"last.txt\",\"w+\")\r\n d=' '.join(str(x) for x in c)\r\n file.write(d)\r\n file.close()\r\n with open('humidity.csv', mode='a',newline='') as file:\r\n writer = csv.writer(file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n writer.writerow(b)\r\n else:\r\n print(\"Offline\")\r\n print(c)\r\n file = open(\"C:/xampp/htdocs/server2.txt\",\"w+\")\r\n d='Offline'\r\n file.write(d)\r\n file.close()\r\n file = open(\"testfile.txt\",\"w\") \r\n file.write(str(data['entry_id']))\r\n file.close() \r\n time.sleep(17)\r\n","sub_path":"plant 2/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"611317676","text":"\"\"\"\r\nPROJECT : FUJITSU GLOBAL INTERNSHIP\r\nOFFICE : KAWASAKI OFFICE\r\nDEPARTEMENT : INOVATION IOT BUSINESS UNIT\r\nAUTHOR : Hanjara Cahya Adhyatma\r\nE-MAIL : adhyatma.han@gmail.com\r\nYEAR : 2017\r\nCOMMENT :\r\n\r\nThis is library for fuzzy fication transorm, this file include 3 \r\ndifferents fuzzy members function: sigmoid, triangle, trapesium.\r\nChose one of them.\r\n\"\"\"\r\n\r\n#######################################################################\r\n##SHAPE FOR FUZZIFICATION CLASS\r\n#######################################################################\r\n\r\n#Trapesium Function\r\ndef trapesiumL(x,a,b,c):\r\n if (x<=b):\r\n return 1\r\n elif (b=b and x>=c):\r\n return 1\r\n elif (a<=x and x 1:\n separator = '|'\n significance = sig.split(separator)\n revision_statuses = revstat.split(separator)\n \n for i,annotation in enumerate(significance):\n clnsig_accsessions.append(\n {\n 'value': int(annotation),\n 'accession': accessions[i],\n 'revstat': revision_statuses[i]\n }\n )\n\n elif transcripts:\n clnsig = set()\n for transcript in transcripts:\n for annotation in transcript.get('clinsig',[]):\n clnsig.add(annotation)\n for annotation in clnsig:\n if annotation in REV_CLINSIG_MAP:\n clnsig_accsessions.append(\n {\n 'value': REV_CLINSIG_MAP[annotation]\n }\n )\n\n return clnsig_accsessions\n","sub_path":"scout/parse/variant/clnsig.py","file_name":"clnsig.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"113108016","text":"#Learning GUI.\n#Source: http://sebsauvage.net/python/gui/\n\nimport Tkinter\t\t\t\t\t\t\t\t\t\t#Step 1: Import\n\nclass HelloApp(Tkinter.Tk): \t\t\t\t\t\t#Step 2: Make an app class inheriting from Tkinter\n\tdef __init__(self,parent):\n\t\tTkinter.Tk.__init__(self,parent)\t\t\t#Step 3: Init from parent class\n\t\tself.initialize()\n\n\tdef initialize(self):\t\t\t\t\t\t\t#Step 4: Intialize the app\n\t\t'''\n\t\tinitialize the app\n\t\t'''\n\t\t#self.grid()\t\t\t\t\t\t\t\t\t#Step 8: Makes a grid as layout manager\n\t\tself.label=Tkinter.Label(self,text=\"Hello World!\",justify=\"center\")\n\t\t#self.label.grid(column=0,row=0)\n\t\tself.label.pack()\n\nif __name__==\"__main__\":\t\t\t\t\t\t\t#Step 5: Check if run as main file and not imported\n\tapp=HelloApp(None)\t\t\t\t\t\t\t\t#Step 6: Make an app object\n\tapp.title(\"Hello World\")\t\t\t\t\t\t#Adding title\n\tapp.mainloop()\t\t\t\t\t\t\t\t\t#Step 7: Starting main loop\t","sub_path":"Hello World.py","file_name":"Hello World.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"171154440","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport argparse as ap\nfrom scipy.optimize import curve_fit\nfrom scipy.special import gamma\n\ndef gamma(x,beta,N):\n return beta**(N/2)/gamma(N/2)*x**(N/2-1)*np.exp(-beta*x)\n\nparser=ap.ArgumentParser()\nparser.add_argument('-i',type=str,default=[],action='append',help='input file name(s)')\nparser.add_argument('-l',type=str,default=[],action='append',help='labels')\nparser.add_argument('-o',type=str,default='rdf.png',help='output file name')\n\n\nargs=parser.parse_args()\n\nfig,ax=plt.subplots(1,1,figsize=(6,5))\nax.set_xlabel(r\"$v$ ($\\sigma/\\tau$)\")\nax.set_ylabel(r\"$f(v)$ ($\\sigma/\\tau$)$^{-1}$\")\nax.set_yscale('log')\nfor f,l in zip(args.i,args.l):\n v,d=np.loadtxt(f,unpack=True)\n par,cov=curve_fit(gamma,v,d,p0=[1.0,1.0])\n if len(l)==0:\n label=f\n else:\n label=l\n ax.scatter(v,d,label=label)\n ax.plot(v,gamma(v,*par),label='{:s}-fit({:.2f})'.format(label,np.sqrt(par[1])))\nax.legend()\nplt.savefig(args.o,bbox_inches='tight')\n","sub_path":"originals/plot_vdf.py","file_name":"plot_vdf.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"402258320","text":"import sys\n\nfrom Utils import util\n\nproject_name_list = [\"project name here\"]\ndeleted_rate_list = [10, 20, 30, 40, 50]\n\nevaluation_measure_list = ['acc', 'precision', 'recall', 'tp', 'fp', 'fn', 'deleted_tp', 'deleted_fn', 'target_sum_commit', 'num_sum_commit']\n\nBOOTSTRAP_SIZE = 100\nTIME_FILTERING_MIN = 10\nNTEXT_TH = 3\nWORD_ASSOC_TH = 5\nCOMMENT_COS_TH = 4\nNSD_SIM_COS_TH = 2\n\ndef evaluate(ground_truth_dict, target_dict, issue_dir, p_name, delete_rate, bootstrap_idx, result_dict):\n num_sum_commit = 0\n target_sum_commit = 0\n fp = 0\n tp = 0\n fn = 0\n\n for issue_id in ground_truth_dict:\n num_sum_commit += len(ground_truth_dict[issue_id])\n if not issue_id in target_dict:\n #num_sum_commit += len(ground_truth_dict[issue_id])\n fn += len(ground_truth_dict[issue_id])\n continue\n\n temp_set = set(target_dict[issue_id]) & set(ground_truth_dict[issue_id])\n\n #num_sum_commit += len(temp_set)\n target_sum_commit += len(temp_set)\n tp += len(temp_set)\n fp += len(set(target_dict[issue_id]) - temp_set)\n fn += len(set(ground_truth_dict[issue_id]) - temp_set)\n\n for issue_id in target_dict:\n if issue_id in ground_truth_dict:\n continue\n\n fp += len(target_dict[issue_id])\n\n\n if (tp+fp)==0:\n result_dict[p_name][delete_rate][bootstrap_idx]['precision'][issue_dir] = 0\n else:\n result_dict[p_name][delete_rate][bootstrap_idx]['precision'][issue_dir] = tp/(tp+fp)\n if (tp+fn)==0:\n result_dict[p_name][delete_rate][bootstrap_idx]['recall'][issue_dir] = 0\n else:\n result_dict[p_name][delete_rate][bootstrap_idx]['recall'][issue_dir] = tp/(tp+fn)\n\n result_dict[p_name][delete_rate][bootstrap_idx]['acc'][issue_dir] = target_sum_commit/num_sum_commit\n result_dict[p_name][delete_rate][bootstrap_idx]['tp'][issue_dir] = tp\n result_dict[p_name][delete_rate][bootstrap_idx]['fp'][issue_dir] = fp\n result_dict[p_name][delete_rate][bootstrap_idx]['fn'][issue_dir] = fn\n result_dict[p_name][delete_rate][bootstrap_idx]['target_sum_commit'][issue_dir] = target_sum_commit\n result_dict[p_name][delete_rate][bootstrap_idx]['num_sum_commit'][issue_dir] = num_sum_commit\n\n\ndef evaluate_deleted(deleted_ground_truth_dict, target_dict, p_name, delete_rate, bootstrap_idx, issue_dir, result_dict):\n tp = 0\n fn = 0\n num_sum_commit = 0\n\n for issue_id in deleted_ground_truth_dict:\n num_sum_commit += len(deleted_ground_truth_dict[issue_id])\n if not issue_id in target_dict:\n fn += len(deleted_ground_truth_dict[issue_id])\n continue\n\n temp_set = set(target_dict[issue_id]) & set(deleted_ground_truth_dict[issue_id])\n\n tp += len(temp_set)\n fn += len(set(deleted_ground_truth_dict[issue_id]) - set(target_dict[issue_id]))\n\n result_dict[p_name][delete_rate][bootstrap_idx]['deleted_tp'][issue_dir] = tp\n result_dict[p_name][delete_rate][bootstrap_idx]['deleted_fn'][issue_dir] = fn\n\n\ndef take_diff_issue2hash_dict(dict_1, dict_2):\n\n return_dict = {}\n for key_1 in dict_1.keys():\n if not key_1 in dict_2:\n return_dict[key_1] = dict_1[key_1]\n continue\n \n temp_list = []\n temp_set = set(dict_2[key_1])\n for value_1 in dict_1[key_1]:\n if value_1 in temp_set:\n continue \n\n temp_list.append(value_1)\n\n if len(temp_list)>0:\n return_dict[key_1] = temp_list\n\n return return_dict\n\n\n\ndef evaluate_ILA(p_name, delete_rate, bootstrap_idx, result_dict):\n ground_truth_dict = util.load_pickle(\"./data/{0}_keyword_extraction_0_{1}_with_restriction.pickle\".format(p_name, bootstrap_idx))\n deleted_ground_truth_dict = util.load_pickle(\"./data/{0}_keyword_extraction_{1}_{2}_with_restriction.pickle\".format(p_name, delete_rate, bootstrap_idx))\n\n deleted_issue2hash_dict = take_diff_issue2hash_dict(ground_truth_dict, deleted_ground_truth_dict)\n\n # test script\n #_test(deleted_issue2hash_dict, delete_rate)\n #return 0\n\n ILA_dict = {\"1\": \"{0}_keyword_extraction_0_{1}_with_restriction\".format(p_name, bootstrap_idx),\n \"3\": \"{0}_time_filtering_min_af{1}_with_restriction\".format(p_name, TIME_FILTERING_MIN),\n \"5\": \"{0}_ntext_similarity_costh{1}_with_restriction\".format(p_name, NTEXT_TH),\n \"7\": \"{0}_{1}_word_association_th{2}_bi{3}_with_restriction\".format(p_name, delete_rate, WORD_ASSOC_TH, bootstrap_idx),\n \"8\": \"{0}_comment_costh0.{1}_ite1_with_restriction\".format(p_name, COMMENT_COS_TH),\n \"9_1\": \"{0}_{1}_loner_bi{2}_with_restriction\".format(p_name, delete_rate, bootstrap_idx),\n \"9_2\": \"{0}_{1}_phantom_bi{2}_with_restriction\".format(p_name, delete_rate, bootstrap_idx),\n \"10\": \"{0}_nsd_similarity_costh{1}_with_restriction\".format(p_name, NSD_SIM_COS_TH),\n \"11\": \"{0}_{1}_pu_link_bi{2}_with_restriction\".format(p_name, delete_rate, bootstrap_idx),\n \"14_1\": \"{0}_RF_{1}_model_bi{2}_with_restriction\".format(p_name, delete_rate, bootstrap_idx),\n \"14_2\": \"{0}_SVM_{1}_model_bi{2}_with_restriction\".format(p_name, delete_rate, bootstrap_idx)}\n\n\n for issue_dir in ILA_dict.keys():\n \n #print(ILA_dict[issue_dir])\n\n target_dict = util.load_pickle(\"./data/{0}.pickle\".format(ILA_dict[issue_dir]))\n\n evaluate(ground_truth_dict, target_dict, issue_dir, p_name, delete_rate, bootstrap_idx, result_dict)\n\n #print(\"-------\")\n #print(\"for deleted data\")\n evaluate_deleted(deleted_issue2hash_dict, target_dict, p_name, delete_rate, bootstrap_idx, issue_dir, result_dict)\n\n #print(\"===\")\n\ndef initialize_table_dict():\n return_dict = {}\n for p_name in project_name_list:\n return_dict[p_name] = {}\n for delete_rate in deleted_rate_list:\n return_dict[p_name][delete_rate] = {}\n\n for bootstrap_idx in range(BOOTSTRAP_SIZE):\n return_dict[p_name][delete_rate][bootstrap_idx] = {}\n\n for evaluation_measure in evaluation_measure_list:\n return_dict[p_name][delete_rate][bootstrap_idx][evaluation_measure] = {}\n\n return return_dict\n\ndef main():\n\n result_dict = initialize_table_dict()\n\n for p_name in project_name_list:\n print(\"================\")\n print(p_name)\n print(\"================\")\n\n for delete_rate in deleted_rate_list:\n print(\"-------\")\n print(\"deleted rate: {0}\".format(delete_rate))\n\n for bootstrap_idx in range(BOOTSTRAP_SIZE):\n\n evaluate_ILA(p_name, delete_rate, bootstrap_idx, result_dict)\n\n print(\"\")\n util.dump_pickle(\"./result/evaluation_with_restriction.pickle\", result_dict)\n\nif __name__==\"__main__\":\n\n main()\n","sub_path":"RQ1/evaluation/evaluation_with_restriction.py","file_name":"evaluation_with_restriction.py","file_ext":"py","file_size_in_byte":6858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"525197163","text":"# -*- coding: utf-8 -*-\n# python 3.8\n\"\"\" Entry point to MCMC to be called from bash script, receives gene arguments\nand runs MCMC chain for each of them.\"\"\"\n\nimport sys\n# for importing module from parent directory\nimport os\nimport inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0, parentdir)\nfrom MCMC_pipe import fit_one_gene, import_data\nimport numpy as np\n\ngene_list = sys.argv[1:]\nprint(gene_list)\n\n# import data once globally to avoid multiple import\nM_data, P_data, Psem_data, M_interp_dict, beta_gamma_dist, delta_gamma_dist, start_values, TE_fun_norm = \\\n import_data(import_folder='../processed_data')\n\n# go through genes and start the fit process\nfor gene in gene_list:\n print(gene)\n fit_one_gene(\n gene,\n M_data,\n P_data,\n Psem_data,\n M_interp_dict,\n beta_gamma_dist,\n delta_gamma_dist,\n start_values,\n TE_fun_norm,\n nwalkers=32,\n Nsteps=6000,\n Ndiscard=500,\n thin=15)\n","sub_path":"declining_rate_model/cluster_code/job_head_MCMC.py","file_name":"job_head_MCMC.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"248811618","text":"class TagCombination:\n\n def __init__(self, pos, case = None,\n number = None, gender= None,\n person = None, time = None,\n mode = None, genusVerbi = None):\n self.pos = pos\n self.case = case\n self.number = number\n self.gender = gender\n self.person = person\n self.time = time\n self.mode = mode\n self.genusVerbi = genusVerbi\n\n def __eq__(self, other):\n #self.__dict___ --> all attributes of object\n #as dict (associative array)\n return self.__dict__ == other.__dict__\n\n \n","sub_path":"compare/tagcombination.py","file_name":"tagcombination.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"547147562","text":"# -*- coding: utf-8 -*-\n'''Folium Vincent plotting'''\n\nimport pandas as pd\nimport vincent\nimport folium\n\nNOAA_46041 = pd.read_csv(r'NOAA_46041.csv', index_col=3,\n parse_dates=True)\nNOAA_46050 = pd.read_csv(r'NOAA_46050_WS.csv', index_col=3,\n parse_dates=True)\nNOAA_46243 = pd.read_csv(r'NOAA_46243.csv', index_col=3,\n parse_dates=True)\n\nNOAA_46041 = NOAA_46041.dropna()\n\n# Binned wind speeds for NOAA 46050.\nbins = range(0, 13, 1)\ncuts = pd.cut(NOAA_46050['wind_speed_cwind (m/s)'], bins)\nws_binned = pd.value_counts(cuts).reindex(cuts.values.categories)\n\n# NOAA 46401 Wave Period.\nvis1 = vincent.Line(NOAA_46041['dominant_wave_period (s)'],\n width=400, height=200)\nvis1.axis_titles(x='Time', y='Dominant Wave Period (s)')\nvis1.to_json('vis1.json')\n\n# NOAA 46050 Binned Wind Speed.\nvis2 = vincent.Bar(ws_binned, width=400, height=200)\nvis2.axis_titles(x='Wind Speed (m/s)', y='# of Obs')\nvis2.to_json('vis2.json')\n\n# NOAA 46243 Wave Height.\nvis3 = vincent.Area(NOAA_46243['significant_wave_height (m)'],\n width=400, height=200)\nvis3.axis_titles(x='Time', y='Significant Wave Height (m)')\nvis3.to_json('vis3.json')\n\n# Map all buoys similar to https://github.com/python-visualization/folium#vincentvega-markers\nkw = dict(fill_color='#43d9de', radius=12)\nbuoy_map = folium.Map(location=[46.3014, -123.7390],\n zoom_start=7, tiles='Stamen Terrain')\n\npopup1 = folium.Popup(max_width=800).add_child(folium.Vega(vis1, width=500, height=250))\nfolium.RegularPolygonMarker([47.3489, -124.708], popup=popup1, **kw).add_to(buoy_map)\n\npopup2 = folium.Popup(max_width=800).add_child(folium.Vega(vis2, width=500, height=250))\nfolium.RegularPolygonMarker([44.639, -124.5339], popup=popup2, **kw).add_to(buoy_map)\n\npopup3 = folium.Popup(max_width=800).add_child(folium.Vega(vis3, width=500, height=250))\nfolium.RegularPolygonMarker([46.216, -124.1280], popup=popup3, **kw).add_to(buoy_map)\n\nbuoy_map.save(outfile='NOAA_buoys.html')\n","sub_path":"examples/folium_vincent_markers.py","file_name":"folium_vincent_markers.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"266463499","text":"import abc\nimport logging\nfrom typing import List\nimport unittest\n\nimport batchglm.api as glm\nfrom batchglm.models.base_glm import _Estimator_GLM, _Simulator_GLM\n\nglm.setup_logging(verbosity=\"WARNING\", stream=\"STDOUT\")\nlogger = logging.getLogger(__name__)\n\n\nclass _Test_Graph_GLM_Estim():\n\n def __init__(\n self,\n estimator: _Estimator_GLM,\n simulator: _Simulator_GLM,\n algo: str\n ):\n self.estimator = estimator\n self.sim = simulator\n self.algo = algo.lower()\n\n def estimate(\n self,\n batched\n ):\n self.estimator.initialize()\n\n self.estimator.train_sequence(training_strategy=[\n {\n \"learning_rate\": 1,\n \"convergence_criteria\": \"all_converged_ll\",\n \"stopping_criteria\": 1e1,\n \"use_batching\": batched,\n \"optim_algo\": self.algo,\n },\n ])\n\n\nclass Test_Graph_GLM(unittest.TestCase, metaclass=abc.ABCMeta):\n \"\"\"\n Test whether training graph work.\n\n Quick tests which simply passes small data sets through\n all possible training graphs to check whether there are graph\n bugs. This is all tested in test_acc_glm.py but this\n set of unit_tests runs much faster and does not abort due\n to accuracy outliers. The training graphs covered are:\n\n - termination by feature\n - full data model\n - train a and b model: test_full_byfeature_a_and_b()\n - train a model only: test_full_byfeature_a_only()\n - train b model only: test_full_byfeature_b_only()\n - batched data model\n - train a and b model: test_batched_byfeature_a_and_b()\n - train a model only: test_batched_byfeature_a_only()\n - train b model only: test_batched_byfeature_b_only()\n - termination global\n - full data model\n - train a and b model: test_full_global_a_and_b()\n - train a model only: test_full_global_a_only()\n - train b model only: test_full_global_b_only()\n - batched data model\n - train a and b model: test_batched_global_a_and_b()\n - train a model only: test_batched_global_a_only()\n - train b model only: test_batched_global_b_only()\n \"\"\"\n _estims: List[_Test_Graph_GLM_Estim]\n\n def setUp(self):\n self._estims = []\n\n def tearDown(self):\n for e in self._estims:\n e.estimator.close_session()\n\n def simulate(self):\n self.simulate1()\n self.simulate2()\n\n @abc.abstractmethod\n def get_simulator(self):\n pass\n\n def simulate1(self):\n self.sim1 = self.get_simulator()\n self.sim1.generate_sample_description(num_batches=2, num_conditions=2)\n self.sim1.generate()\n\n def simulate2(self):\n self.sim2 = self.get_simulator()\n self.sim2.generate_sample_description(num_batches=0, num_conditions=2)\n self.sim2.generate()\n\n def simulator(self, train_loc):\n if train_loc:\n return self.sim1\n else:\n return self.sim2\n\n @abc.abstractmethod\n def basic_test_one_algo(\n self,\n batched,\n termination,\n train_loc,\n train_scale,\n algo\n ):\n pass\n\n def _basic_test_one_algo(\n self,\n estimator,\n batched\n ):\n estimator.estimate(batched=batched)\n estimator.estimator.finalize()\n self._estims.append(estimator)\n\n return True\n\n @abc.abstractmethod\n def basic_test(\n self,\n batched,\n termination,\n train_loc,\n train_scale\n ):\n pass\n\n def _basic_test(\n self,\n batched,\n termination,\n train_loc,\n train_scale,\n algos\n ):\n for algo in algos:\n logger.info(\"algorithm: %s\" % algo)\n self.basic_test_one_algo(\n batched=batched,\n termination=termination,\n train_loc=train_loc,\n train_scale=train_scale,\n algo=algo\n )\n\n def _test_full_byfeature_a_and_b(self):\n return self.basic_test(\n batched=False,\n termination=\"by_feature\",\n train_loc=True,\n train_scale=True\n )\n\n def _test_full_byfeature_a_only(self):\n return self.basic_test(\n batched=False,\n termination=\"by_feature\",\n train_loc=True,\n train_scale=False\n )\n\n def _test_full_byfeature_b_only(self):\n return self.basic_test(\n batched=False,\n termination=\"by_feature\",\n train_loc=False,\n train_scale=True\n )\n\n def _test_batched_byfeature_a_and_b(self):\n return self.basic_test(\n batched=True,\n termination=\"by_feature\",\n train_loc=True,\n train_scale=True\n )\n\n def _test_batched_byfeature_a_only(self):\n return self.basic_test(\n batched=True,\n termination=\"by_feature\",\n train_loc=True,\n train_scale=False\n )\n\n def _test_batched_byfeature_b_only(self):\n return self.basic_test(\n batched=True,\n termination=\"by_feature\",\n train_loc=False,\n train_scale=True\n )\n\n def _test_full_global_a_and_b(self):\n return self.basic_test(\n batched=False,\n termination=\"global\",\n train_loc=True,\n train_scale=True\n )\n\n def _test_full_global_a_only(self):\n return self.basic_test(\n batched=False,\n termination=\"global\",\n train_loc=True,\n train_scale=False\n )\n\n def _test_full_global_b_only(self):\n return self.basic_test(\n batched=False,\n termination=\"global\",\n train_loc=False,\n train_scale=True\n )\n\n def _test_batched_global_a_and_b(self):\n return self.basic_test(\n batched=True,\n termination=\"global\",\n train_loc=True,\n train_scale=True\n )\n\n def _test_batched_global_a_only(self):\n return self.basic_test(\n batched=True,\n termination=\"global\",\n train_loc=True,\n train_scale=False\n )\n\n def _test_batched_global_b_only(self):\n return self.basic_test(\n batched=True,\n termination=\"global\",\n train_loc=False,\n train_scale=True\n )\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"batchglm/unit_test/base_glm/test_graph_glm.py","file_name":"test_graph_glm.py","file_ext":"py","file_size_in_byte":6726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"202154465","text":"#!/usr/bin/env python3\n\n# Site: Leetcode\n# Problem no:\n# Title: Valid Palindrome\n\nfrom typing import *\n\nclass Solution:\n def isPalindrome(self, s: str) -> bool:\n '''\n This function checks if a string is a palindrome\n Time complexity: O(n)\n '''\n\n '''\n Lower case the characcters.\n Take only the alhanumeric characters\n '''\n s = ''.join( [x.lower() for x in s if x.isalnum()] ) # O(n)\n\n low = 0\n high = len(s) - 1\n '''\n If I am able to find that s[low] and s[high] mismatches\n before I cross the midpoint (that means low is lower than high)\n then the string is not a palindrome.\n '''\n\n # O(n)\n while low < high:\n if s[low] != s[high]:\n return False\n low += 1\n high -= 1\n\n '''\n I didn't find any mismatches and\n I have crossed midpoint so it's a valid palindrome.\n '''\n return True\n\n\ndef main():\n s = Solution()\n assert s.isPalindrome('madam') == True\n assert s.isPalindrome('maddam') == True\n assert s.isPalindrome('maddtam') == False\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"leetcode/0125.py","file_name":"0125.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"51457972","text":"import pytest\nimport numpy as np\nfrom neuraxle.base import AssertExpectedOutputNullMixin, BaseStep, Identity\nfrom neuraxle.data_container import DataContainer\nfrom neuraxle.pipeline import Pipeline\n\n\nclass SomeStep(AssertExpectedOutputNullMixin,Identity):\n def __init__(self):\n Identity.__init__(self)\n\ndef test_expectedoutputnull_raise_exception_when_notnull(tmpdir):\n\n data_inputs = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n expected_outputs = data_inputs * 2\n\n p = Pipeline([SomeStep()])\n\n with pytest.raises(AssertionError) as error_info:\n p.fit_transform(data_inputs,expected_outputs)\n\ndef test_expectedoutputnull_is_fine_when_null(tmpdir):\n\n data_inputs = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n expected_outputs = None\n\n p = Pipeline([SomeStep()])\n p.fit_transform(data_inputs,expected_outputs)\n","sub_path":"testing/steps/test_assertion_steps.py","file_name":"test_assertion_steps.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"632924192","text":"# -*- coding:utf-8 -*-\r\n# Author: washing\r\n# DateTime: 2021/5/5 19:15\r\n# File: 0740.py\r\n# Desc: \r\n\r\nclass Solution:\r\n def deleteAndEarn(self, nums: List[int]) -> int:\r\n c = collections.Counter(nums)\r\n\r\n dps = []\r\n for k, v in c.items():\r\n c[k] = c[k] * k\r\n dps.append([0,0])\r\n \r\n ks = list(c.keys())\r\n ks.sort()\r\n dps[0][0] = c[ks[0]]\r\n\r\n for i in range(1, len(ks)):\r\n k = ks[i]\r\n if k - 1 == ks[i-1]:\r\n dps[i][0] = max(dps[i-1][1] + c[k], dps[i-1][0])\r\n else: # 可以加这个数\r\n dps[i][0] = dps[i-1][0] + c[k]\r\n \r\n dps[i][1] = max(dps[i-1])\r\n # print(dps)\r\n return max(dps[-1])","sub_path":"Solutions/0740/0740.py","file_name":"0740.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"155936349","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport json\n\noriginal_task = sys.stdin.readline()\nmodified_task = sys.stdin.readline()\n\ntask = json.loads(modified_task)\ntask[\"description\"] = \"This is an example modify hook\"\n\n# A random message\nsys.stdout.write(\"Hello from the template hook\\n\")\n\nsys.stdout.write(json.dumps(task, separators=(',', ':')) + '\\n')\nsys.exit(0)\n\n# vim: ai sts=4 et sw=4\n","sub_path":"test/test_hooks/on-modify-for-template.py","file_name":"on-modify-for-template.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"577698619","text":"import cv2\nimport copy\nimport numpy as np\nimport os\nimport json\nimport argparse\nimport sys\nimport os\nimport dlib\nimport glob\nfrom multiprocessing import Pool\n\n\ndef parts_to_points(parts):\n result = []\n for part in parts:\n result.append((part.x, part.y))\n return result\n\n\ndef get_image_paths(video_path):\n image_names = sorted(filter(lambda x: x[-4:] == \".png\", os.listdir(video_path)))\n\n full_image_paths = list(map(lambda x: (video_path + x).replace(\"\\n\", \"\"), image_names))\n images_list = full_image_paths\n return images_list\n\n\ndef read_image_list(corpus_path):\n # processing corpus\n image_name_list = []\n for mode in [\"dev\", \"test\", \"train\"]:\n print(\"processing {} corpus\".format(mode))\n old_dev_corpus = open(os.path.join(corpus_path, \"phoenix2014T.{}.sign\".format(mode)), \"r\").readlines()\n\n count = 0\n for folder_path in old_dev_corpus:\n count += 1\n if not count % (len(old_dev_corpus) // 10):\n print(\"currently processed {} of {} ({}%)\".format(count, len(old_dev_corpus),\n count * 100 // len(old_dev_corpus)))\n real_path = (folder_path.replace(\"\",\n \"./../PHOENIX-2014-T-release-v3/PHOENIX-2014-T\")).replace(\"227x227\",\n \"210x260\").replace(\n \"\\n\", \"\")\n image_name_list.extend(get_image_paths(real_path))\n print('after the current section, count is {}'.format(count))\n\n with open('./image_name_list.txt', 'w') as f:\n for item in image_name_list:\n f.write(\"%s \\n\" % item)\n return image_name_list\n\n\ndef get_batches(image_name_list, batch_size, detector, predictor):\n batches = []\n batch_names = []\n for i in range(0, len(image_name_list), batch_size):\n batches.append(image_name_list[i:i + batch_size])\n batch_names.append(i // batch_size)\n detectors = [detector] * len(batch_names)\n predictors = [predictor] * len(batch_names)\n return zip(batch_names, batches, detectors, predictors)\n\n\ndef get_points(arguments):\n batch_name, image_names, detector, predictor = arguments\n name_points_dict = {}\n for f in image_names:\n img = dlib.load_rgb_image(f)\n dets = detector(img, 1)\n if len(dets) == 0:\n name_points_dict[f] = []\n\n try:\n assert len(dets) <= 1\n except:\n print(\"Error! More than 1 faces are identified in a single image\")\n print(\"name of file is {}\".format(f))\n name_points_dict[f] = []\n continue\n for k, d in enumerate(dets):\n # print(\"Detection {}: Left: {} Top: {} Right: {} Bottom: {}\".format(k, d.left(), d.top(), d.right(),\n # d.bottom())) Get the landmarks/parts for the face in box d.\n shape = predictor(img, d)\n # print(\"Part 0: {}, Part 1: {} ...\".format(shape.part(0),\n # shape.part(1)))\n\n # print(\"It has {} parts\".format(shape.num_parts))\n assert shape.num_parts == 68\n name_points_dict[f] = parts_to_points(shape.parts())\n\n # print(\"Part 60 is {}\".format(shape.part(60)))\n filename = f\"./facial_data/batch_{batch_name:03}.json\"\n with open(filename, 'w') as outfile:\n json.dump(name_points_dict, outfile)\n print(f\"finished writing to json, the file name is {filename}\")\n\n\ndef generate_facial_points(image_name_list, predictor_path, save_batch_size=1000, num_process=15):\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor(predictor_path)\n batches = list(get_batches(image_name_list, save_batch_size, detector, predictor))\n print(\"Finished loading getting all batches, in total {} batches\".format(len(batches)))\n pool = Pool(num_process)\n pool.map(get_points, batches)\n pool.close()\n pool.join()\n print(\"Finished process!\")\n\n\n#\n# def generate_facial_points(image_name_list, predictor_path, save_batch_size=1000):\n# print(\"batch size is {}\".format(save_batch_size))\n# name_points_dict = {}\n# count = 0\n# detector = dlib.get_frontal_face_detector()\n# predictor = dlib.shape_predictor(predictor_path)\n# for f in image_name_list:\n# count += 1\n#\n# # win = dlib.image_window()\n#\n# # print(\"Processing file: {}\".format(f))\n# img = dlib.load_rgb_image(f)\n#\n# # win.clear_overlay()\n# # win.set_image(img)\n# dets = detector(img, 1)\n# # print(\"Number of faces detected: {} in\".format(len(dets)))\n#\n# if len(dets)==0:\n# name_points_dict[f]=[]\n#\n# try:\n# assert len(dets) <= 1\n# except:\n# print(\"Error! More than 1 faces are identified in a single image\")\n# print(\"name of file is {}\".format(f))\n# name_points_dict[f]=[]\n# for k, d in enumerate(dets):\n# # print(\"Detection {}: Left: {} Top: {} Right: {} Bottom: {}\".format(k, d.left(), d.top(), d.right(),\n# # d.bottom())) Get the landmarks/parts for the face in box d.\n# shape = predictor(img, d)\n# # print(\"Part 0: {}, Part 1: {} ...\".format(shape.part(0),\n# # shape.part(1)))\n#\n# # print(\"It has {} parts\".format(shape.num_parts))\n# assert shape.num_parts == 68\n# # print(\"parts are {}\".format(shape.parts()))\n#\n# name_points_dict[f] = parts_to_points(shape.parts())\n#\n# # print(\"Part 60 is {}\".format(shape.part(60)))\n# # Draw the face landmarks on the screen.\n# # win.add_overlay(shape)\n# # print(\"before saving, count is {}\".format(count))\n# if count % save_batch_size == 0 or count == len(image_name_list):\n# print(\"finished processing {} images\".format(count))\n# if count == len(image_name_list):\n# filename = f\"./facial_data/batch_{(count // save_batch_size + 1):03}.json\"\n# else:\n# filename = f\"./facial_data/batch_{(count // save_batch_size):03}.json\"\n# with open(filename, 'w') as outfile:\n# json.dump(name_points_dict, outfile)\n# print(f\"finished writing to json, the file name is {filename}\")\n# name_points_dict = {}\n# assert len(name_points_dict) == 0\n#\n# # win.add_overlay(dets)\n\n\nif __name__ == \"__main__\":\n ap = argparse.ArgumentParser()\n\n ap.add_argument(\"--image_list\", type=str, default=None, help=\"file that contain all images\")\n ap.add_argument(\"--corpus_path\", type=str, default=None, help=\"the path to corpus containing video names\")\n ap.add_argument(\"--batch_size\", type=int, default=1000, help=\"the batch size to save the results\")\n ap.add_argument(\"--predictor_path\", type=str, required=True, help=\"the path to the pretrained predictory model\")\n ap.add_argument(\"--num_process\", type=int, default=15, help=\"number of processes we are using\")\n args = ap.parse_args()\n print(\"Using CUDA: {}\".format(dlib.DLIB_USE_CUDA))\n print(f\"Input arguments are {args}\")\n if args.image_list:\n print(\"image list specified, therefore directly generating points\")\n generate_facial_points(args.image_list, args.predictor_path, args.batch_size, args.num_process)\n elif args.corpus_path:\n print(\"only corpus path is specified, starting from corpus path\")\n image_list = read_image_list(args.corpus_path)\n print(\"get all images, in total {} images\".format(len(image_list)))\n generate_facial_points(image_list, args.predictor_path, args.batch_size, args.num_process)\n else:\n print(\"must specified one of image list or corpus path\")\n","sub_path":"generate_facial_points.py","file_name":"generate_facial_points.py","file_ext":"py","file_size_in_byte":7934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"451607733","text":"#!/usr/bin/python3\n\n################################################################################################################################\n# NAME: Jenny Goldsher, Noah Harvey, Deandra Martin, Hiroki Sato\n# DATE: 09112020\n# IDEA: opens questions file and generates questions\n# There are certain types of questions that must be created depending on the syntax error that they make or \n# what they implement within the codeblock. For example, syntax question about the indentation is always created when user \n# used wrong indentation. \n\n################################################################################################################################\n\n#### IMPORTS #################################################################################################################\nimport pandas as pd\nfrom random import randint, choice\nfrom ast import literal_eval\n\n#### GLOBALS #################################################################################################################\nquestion_df = pd.read_csv('Questions_11_27.csv')\nexisting_q_id = []\nsyntax_list = ['def','if','else','==','+','-','*','/',\"'\",'\"']\ndata_types = ['int','str','float','bool','list']\n # we are using a python libary called Pandas to manipulate the\n # csv file easily by creating a pandas dataframe. \n # .set_index would make one of the column in the csv file\n # 'Question Type' as index and we can extract the matching \n # question according to the input we'll receive\n \n\n\n#### FUNCTIONS ###############################################################################################################\n################################################################################################################################\n#### check_question ############################################################################################################\n\n# Input: list of questions \n# Output list that contains question id\n# Objective: iterate through the list of questions created and record the existing_question_id so that we can keep track of what questions can be created and \n# what questions should not be created\n\n\ndef check_question(questions):\n \n existing_q_id = list()\n \n if len(questions) == 0: # if the questions list is empty, return a list with 0\n return [0]\n else: # if the questions list is not empty,\n \n for q in questions: # iterate throught the list of questions\n existing_q_id.append(q['id'])\n \n return existing_q_id\n \n \n\n################################################################################################################################\n#### check_indent function #####################################################################################################\n\n# Input: two dimensional list\n# Output: boolean\n# Objective: iterate through the two dimensional list and make sure there is no error with indentation\n# Returning True indicate that there is no indentation issue, and False represents an issue with spaces\n\ndef check_indent(lines):\n \n # local variable flag, if anything weird didn't happen then this function will return True\n flag = True\n \n for line in range(len(lines)): # iterating through the 2-d list\n \n cur = lines[line]\n\n if (cur[0] % 4 != 0): # if the number of space is not multiple of 4\n\n flag = False # this is the base case that can be applied to either a single\n break # line of code or multiple lines of code. \n \n \n if len(lines) > 1: # if the code was not a single line. \n \n # get the previous lines\n prev = lines[line - 1]\n \n if ((prev[len(prev)-1] == ':') and (cur[0] != (prev[0] + 4))): # the previous line ends with : but the number of space is not\n # incremented by 4\n flag = False\n break\n \n \n return flag\n\n################################################################################################################################\n#### create_iData_type function ################################################################################################\n\n# Input: list which is the entire row in the two-d list and an int which is an index of '='\n# Output: dictionary which is a question, and choices and its answer and link to the feedback\n# Objective: create a iData type question\n\ndef create_iData_type(line, index):\n \n # get the iData_type question as dictionary\n question = question_df.set_index('Question Type').loc['iData Types'].to_dict()\n question_df.reset_index()\n print(question) # debugging\n choices = data_types\n answer = question['Answer']\n print(choices) # debugging\n # list to keep track of data type that was chosen as the \n chosen = []\n\n # getting the variable name and getting the data_type of variable. \n variable_name = line[index - 1]\n variable_type = type(literal_eval(line[index + 1]))\n\n # print(variable_name, variable_type) # debugging \n \n if variable_type == str:\n\n # modifying the question choice to avoid overlap\n answer = 'str'\n \n \n if variable_type == int:\n answer = 'int'\n\n \n if variable_type == float:\n answer = 'float'\n \n if variable_type == bool:\n answer = 'boolean'\n\n if variable_type == list:\n answer = 'list'\n \n print(\"Answer\", answer)\n \n # using ascii value, selecting the key to put the answer and place the answer. \n answer_key = chr(65 + randint(0,3))\n chosen.append(answer)\n question[answer_key] = answer\n question['Answer'] = answer_key\n print(\"Printing chosen\", chosen)\n \n # selecting the rest of the answers. \n for i in range(3):\n \n key = chr(65 + randint(0,3))\n \n while key == answer_key:\n key = chr(65 + randint(0,3))\n \n \n dummy = choice(choices)\n \n while dummy in chosen:\n dummy = choice(choices)\n \n chosen.append(dummy)\n question[key] = dummy\n \n \n # modify the question sentence\n question['Question'] = question['Question'].replace(\"(variable name)\",variable_name)\n \n return question\n\n\n################################################################################################################################\n\n\"\"\"This function is going to create a set of questions \"\"\"\n\n# Input: two dimensional list called term_lists\n# the first index, the row represents the line, second index columns are the terms on that line. \n# Output: two dimensiocal list which contains a list of questions and answer keys. \n\ndef generate_questions(term_lists):\n \n questions = list()\n iData_type = False\n Generic = False\n \n # have a for loop to create randomly selected 7 questions and append to the questions list\n # first we could check for line indentation which is the very important and simple syntax question we can ask\n indentation = check_indent(term_lists)\n \n # if we see the flag being False, append the syntax question about the indentation/spaces\n if (indentation == False):\n q = question_df.set_index('Question Type').loc['Syntax'].iloc[4].to_dict()\n questions.append(q) # set_index is going to use certain column as index of the\n # pandas dataframe which is id in this case, and we know the\n # id for the indentation syntax so we get the question by\n # loc[] operator and preserve the entire row as a list.\n # going through the two dimensional list again\n # we will visit each line to create data type question, or syntax question, or generic question\n \n \n for line in range(len(term_lists)):\n # question = generate_question(questions, tokens)\n # we first want to make sure what questions are already in the list of questions\n existing_q_id = check_question(questions)\n # get the current line of code\n current = term_lists[line]\n print('Current line:', current)\n # we will have an internal for loop to go through each terms except the first elements which indicates the number of spaces. \n \n for term in range(1,len(current)):\n \n t = current[term]\n \n if (t == '=' and iData_type == False):\n # create iData_type_qestion\n question = create_iData_type(current, term)\n iData_type = True\n questions.append(question)\n continue\n \n if (t == '=' and iData_type == True):\n # print('Creating data type question') \n # create a data type question.\n \n dtq = question_df.set_index('Question Type').loc['Data Types']\n question_df.reset_index()\n question = dtq.iloc[randint(0, len(dtq) - 1)]\n \n \n while question['id'] in existing_q_id:\n question = dtq.iloc[randint(0, len(dtq) - 1)]\n \n q = question.to_dict()\n \n q = question.to_dict()\n questions.append(question)\n continue\n \n if (t in syntax_list):\n \n # create syntax question\n \n stq = question_df.set_index('Question Type').loc['Syntax']\n question_df.reset_index()\n question = stq.iloc[randint(0, len(stq) - 1)]\n \n while question['id'] in existing_q_id:\n question = stq.iloc[randint(0, len(stq) - 1)]\n \n \n q = question.to_dict()\n questions.append(question)\n continue\n \n \n \n \n # check if we reached the number of questions we wanted. \n \n if len(questions) == 4:\n break\n \n # after going through everything and you don't have enough question, add one generic question.\n if len(questions) < 4:\n \n gnq = question_df.set_index('Question Type').loc['Generic']\n question_df.reset_index()\n question = gnq.iloc[randint(0, len(gnq) - 1)].to_dict()\n questions.append(question)\n \n return questions\n\n\n\n#### MAIN ####################################################################################################################\n\ndef main():\n print(questions)\n\nif(__name__==\"__main__\"): main()\n","sub_path":"tutorBot/tutorQuestionsOld.py","file_name":"tutorQuestionsOld.py","file_ext":"py","file_size_in_byte":12498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"561373385","text":"import csv\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport codecs\nimport psycopg2\nfrom psycopg2 import extras\nimport os\n\nurl = \"https://race.netkeiba.com/?pid=race&id=p201906040601&mode=top\"\n# ブラウザーを起動\noptions = Options()\noptions.add_argument('--headless')\nhome_path = os.environ[\"HOME\"]\ndriver = webdriver.Chrome(home_path + \"/git-repos/keiba/src/chromedriver\", options=options)\nhtml = driver.get(url)\n\numa = []\numa_num = 0\n# for i, li in enumerate(ul):\nfor i in range(12):\n ul = driver.find_elements_by_xpath('/html/body/div[1]/div[2]/div[1]/div[1]/div/div/div[3]/ul/li')\n ul[i].click()\n driver.implicitly_wait(5)\n # # URLの指定\n soup = BeautifulSoup(driver.page_source, \"html.parser\")\n # テーブルを指定\n table = soup.findAll(\"table\", {\"class\":\"race_table_01 nk_tb_common\"})[0]\n rows = table.findAll(\"tr\")\n # DBに書き込む馬リストを作る\n for row in rows:\n umaRow = []\n for cell in row.findAll(['td', 'th']):\n umaRow.append(cell.get_text())\n uma.append(umaRow)\n uma_num += len(uma)\n print(i)\n print(len(uma))\n print(\"fin\")\n\n# DBに馬リストumaを書き込む\nname = \"keiba\"\nwith psycopg2.connect(dbname=\"keiba\") as conn:\n with conn.cursor() as cur:\n # cur.execute(\"drop table if exists \" + name + \";\")\n cur.execute(\"create table if not exists \" + name + \" (着順 text, 枠番 text, 馬番 text, 馬名 text, 性齢 text, 負担重量 text, 騎手 text, タイム text, 着差 text, 人気 text, 単勝オッズ text, 後3F text, コーナー通過順 text, 厩舎 text, 馬体重 text);\")\n extras.execute_values(cur, \"INSERT INTO \" + name + \" values %s\", uma)\n cur.execute(\"delete from \" + name + \" where 着順 = '着順'\")\n\ndriver.close()","sub_path":"keiba_Bs_Se.py","file_name":"keiba_Bs_Se.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"543147871","text":"import cv2\nimport numpy as np\n\n\ninput = cv2.imread('./images/Day_030.png')\n\nbb = np.shape(input) \n\nprint (bb)\nprint ('Resim Height:', bb[0])\nprint('Resim Widht:', bb[1])\n\ncv2.imwrite('Bitki.jpg' , input)\n\n\ncv2.imshow('Örnek Resim',input)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n\n\"\"\" \ninput = cv2.imread() komutu resmi almak için kullanılır.\n\nbb = np.shape(input) ise alınan resmin büyüklüğünü N-dimension tipinde gösterir. Örneğin 1024x768 büyüklüğünde olduğunu gösterebilir.\nprint(bb) ise, ölçülen resim büyüklüğünü yazdırmaya işe yarar.\ncv2.imshow() Resmi göstermek için kullanılır.\ncv2.waitKey() bekleme komutudur. Parantez içi milisaniyeler olarak alınır. \ncv2.destoryAllWindows() aslında bir Exception Handling olarak sayılabilir. Hata oluşmasın diye veya hata oluşurşa diye açılan tüm programları kapatır.\n\n\"\"\"","sub_path":"PythonVisualStudio/PythonApplication1/PythonApplication1/PythonApplication1.py","file_name":"PythonApplication1.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"206329429","text":"class Node:\n def __init__(self, data):\n self.value = data\n self.ref = None\n\nclass SinglyLinkedList:\n def __init__(self):\n self.head = None\n \n def display(self):\n if self.head is None:\n print(\"List is empty\")\n else:\n n = self.head\n while n is not None:\n print(f\"{n.value} -> \",end=\"\")\n n = n.ref\n print()\n \n def insert_at_head(self,data):\n new_node = Node(data)\n new_node.ref = self.head\n self.head = new_node\n \n def insert_at_end(self,data):\n new = Node(data)\n if self.head is None:\n self.head = new\n return\n\n n = self.head\n\n while n.ref is not None:\n n = n.ref\n \n n.ref = new\n\n def insert_after_node(self,x,data):\n n = self.head\n while n is not None:\n if n.value == x:\n break\n n = n.ref\n\n if n is None:\n print(\"Value not found\")\n else:\n new = Node(data)\n new.ref = n.ref\n n.ref = new\n\n def insert_before_node(self,x,data):\n if x == self.head.value:\n new = Node(data)\n new.ref = self.head\n self.head = new\n return\n n = self.head\n while n.ref is not None:\n if n.ref.value == x:\n new = Node(data)\n new.ref = n.ref\n n.ref = new\n else:\n print(\"Vlaue not found\")\n n = n.ref\n \n def insert_at_index(self,index,data):\n \n if index == 1:\n new = Node(data)\n new.ref = self.head\n self.head = new\n return\n \n i = 1\n n = self.head\n while i < index-1 and n is not None:\n if i == index:\n break\n n = n.ref\n i += 1\n \n if n is None:\n print(\"Index out of bound\")\n else:\n new = Node(data)\n new.ref = n.ref\n n.ref = new\n \n def count_list(self):\n if self.head is None:\n print(\"List is empty\")\n return\n else:\n n = self.head\n count = 0\n while n is not None:\n count +=1\n n = n.ref\n print(f\"Total elements in list are: {count}\")\n \n def search_element(self,x):\n n = self.head\n if self.head is None:\n print(\"List is empty\")\n else:\n while n is not None:\n if x == n.value:\n print(f\"Value found : {x}\")\n return\n n = n.ref\n print(\"Value not found\")\n \n def add_n_elements(self):\n no = int(input(\"Enter number of elements you want to enter in list\"))\n \n for i in range(no):\n z = int(input(\"Enter element:\"))\n self.insert_at_end(z)\n \n def delete_head(self):\n if self.head is None:\n print(\"List is empty\")\n return\n self.head = self.head.ref\n \n def delete_at_end(self):\n if self.head is None:\n print(\"List is empty\")\n return\n n = self.head\n if self.head.ref is None:\n self.delete_head()\n return\n while n.ref.ref is not None:\n n = n.ref\n n.ref = None\n \n def delete_element_node(self,x):\n if self.head is None:\n print(\"List is empty\")\n return\n \n if self.head.value == x:\n self.head = self.ref\n return\n \n n = self.head\n while n.ref is not None:\n if x == n.ref.value:\n break\n n = n.ref\n \n if n.ref is None:\n print(\"Item not found\")\n else:\n n.ref = n.ref.ref\n \n def reverse_a_list(self):\n if self.head is None:\n print(\"List is Empty\")\n return\n n = self.head\n prev = None\n while n is not None:\n next = n.ref\n n.ref = prev\n prev = n\n n = next\n self.head = prev\n \n \nl = SinglyLinkedList()\nl.insert_at_head(3)\n# l.insert_at_end(12)\n# l.insert_after_node(3,7)\n# l.insert_after_node(7,2)\n# l.insert_before_node(3,9)\n# l.insert_at_index(1,11)\n# l.delete_element_node(7)\n# l.delete_head()\nl.delete_at_end()\n# l.add_n_elements()\nl.display()\n# l.count_list()\n# l.search_element(10)\n# l.reverse_a_list()\n# print(\"Reversed list\")\n# l.display()","sub_path":"Data Structures/Linked List/Singlylinkedlist.py","file_name":"Singlylinkedlist.py","file_ext":"py","file_size_in_byte":4620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"439046839","text":"# Python Built-Ins:\nimport json\nimport logging\nimport os\n\n# External Dependencies:\nimport boto3\n\ndynamodb = boto3.resource(\"dynamodb\")\nlambdafunction = boto3.client(\"lambda\")\npersonalize_runtime = boto3.client(\"personalize-runtime\")\ntable = dynamodb.Table(os.environ[\"DDB_TABLE_NAME\"])\n\n# (Slicing with None is equivalent to no limit)\nMAX_PROMOTED_RESULTS = os.environ.get(\"MAX_PROMOTED_RESULTS\")\nif MAX_PROMOTED_RESULTS is not None:\n MAX_PROMOTED_RESULTS = int(MAX_PROMOTED_RESULTS)\n\n\nlogger = logging.getLogger()\n\ndef handler(event, context):\n sresult = lambdafunction.invoke(\n FunctionName=os.environ[\"SEARCH_LAMBDA_ARN\"],\n LogType=\"Tail\",\n Payload=json.dumps(event),\n )\n res_json = json.loads(sresult[\"Payload\"].read().decode(\"utf-8\"))\n raw_list = res_json[\"body\"][\"result\"]\n\n logger.info(f\"Raw search results: {raw_list}\")\n\n campaign_arn = os.environ.get(\"CAMPAIGN_ARN\")\n response = {}\n reranked_list = []\n if campaign_arn:\n try:\n userId = event[\"queryStringParameters\"][\"u\"]\n except:\n userId = None\n\n if userId != None and len(raw_list) != 0:\n rerank = personalize_runtime.get_personalized_ranking(\n campaignArn=campaign_arn,\n inputList=raw_list,\n userId=userId\n )\n reranked_list = [item[\"itemId\"] for item in rerank[\"personalizedRanking\"]]\n else:\n response[\"warning\"] = (\n \"Personalized search re-ranking has not yet been enabled: First train a re-ranking model and \"\n \"deploy a campaign in Amazon Personalize, then set the CAMPAIGN_ARN environment variable on \"\n \"your SearchRerank Lambda function to use the model on the website!\"\n )\n\n logger.info(f\"Re-ranked search results: {reranked_list}\")\n\n # We will return up to MAX_PROMOTED_RESULTS from the re-ranked list first, followed by results from the\n # raw list:\n promotions = reranked_list[:MAX_PROMOTED_RESULTS]\n n_promotions = len(promotions)\n final_list = promotions + [id for id in raw_list if id not in promotions]\n results = []\n errcount = 0\n for i, id in enumerate(final_list):\n itemobj = table.get_item(Key={ \"asin\": id })\n try:\n results.append(itemobj[\"Item\"])\n if i < n_promotions:\n itemobj[\"Item\"][\"Promoted\"] = True\n except:\n errcount += 1\n\n if errcount:\n missingWarning = f\"{errcount} item IDs missing from DynamoDB\"\n logger.warning(missingWarning)\n if \"warning\" in response:\n response[\"warning\"] += \"\\n\\n\" + missingWarning\n else:\n response[\"warning\"] = missingWarning\n response[\"results\"] = results\n\n return {\n \"statusCode\": 200,\n \"headers\": {\n \"Access-Control-Allow-Credentials\": True,\n \"Access-Control-Allow-Origin\": \"*\",\n },\n \"body\": json.dumps(response),\n }\n","sub_path":"functions/APIs/SearchRerank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"533959057","text":"# from flask import Flask\n\n# app = Flask(__name__)\n\n\n# @app.route(\"/\")\n# def hello():\n# return \"Hello World!\"\n\nimport requests\n\n# bot token 451894563:AAECTkJq8fRjYuHmQLRt9HfEiI9fQGMyOm4\n# link par la api https://api.telegram.org/bot/METHOD_NAME\n\n\ndef send_text(chat_id, text):\n requests.post('https://api.telegram.org/bot402222619:AAH8lVAlQhn3X-xgtmf'\n 'NQV9EaXPIXEGwas8/sendMessage',\n params = {'chat_id': str(chat_id),\n 'text': str(text)})\n","sub_path":"telegram_api.py","file_name":"telegram_api.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"35176385","text":"import sqlite3\nclass DBConnect :\n def __init__(self):\n self._db =sqlite3.connect('mouh.db')\n self.cor= self._db.cursor()\n\n self.cor.execute(\"create table if not exists Ticket(ID INTEGER primary KEY autoincrement ,Name text ,Gender text ,Comment text)\")\n self._db.commit()\n\n def Add(self ,Name, Gender , Comment):\n\n self.cor.execute(\"insert into Ticket (Name,Gender,Comment)values(?,?,?)\",(Name, Gender , Comment))\n self._db.commit()\n return \"info submeted\"\n\n def ListRequest(self):\n\n self.cor.execute(\"select * from Ticket\")\n self._db.commit()\n return self.cor","sub_path":"Regester/DBConnection.py","file_name":"DBConnection.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"640909257","text":"#!/usr/bin/env python3\n\"\"\"Packaging implementation for Sentry Logs\"\"\"\nfrom __future__ import print_function\n\nfrom glob import glob\nimport os\nfrom os.path import abspath, dirname, join\nimport shutil\n\nfrom setuptools import Command, setup\n\nimport sentrylogs as package\n\n\nclass SimpleCommand(Command):\n \"\"\"A simple setuptools command (implementation of abstract base class)\"\"\"\n user_options = []\n\n def initialize_options(self):\n \"\"\"Abstract method of the base class (required to be overridden)\"\"\"\n\n def finalize_options(self):\n \"\"\"Abstract method of the base class (required to be overridden)\"\"\"\n\n\nclass Clean(SimpleCommand):\n \"\"\"Remove build files and folders, including Python byte-code\"\"\"\n description = __doc__\n\n @staticmethod\n def run():\n \"\"\"\n Clean up files not meant for version control\n \"\"\"\n delete_in_root = [\n 'build',\n 'dist',\n '.eggs',\n '*.egg-info',\n '.tox',\n ]\n delete_everywhere = [\n '*.pyc',\n '__pycache__',\n ]\n for candidate in delete_in_root:\n rmtree_glob(candidate)\n for visible_dir in glob('[A-Za-z0-9_]*'):\n for candidate in delete_everywhere:\n rmtree_glob(join(visible_dir, candidate))\n rmtree_glob(join(visible_dir, '*', candidate))\n rmtree_glob(join(visible_dir, '*', '*', candidate))\n\n\ndef rmtree_glob(file_glob):\n \"\"\"Platform independent rmtree, which also allows wildcards (globbing)\"\"\"\n for item in glob(file_glob, recursive=True):\n try:\n os.remove(item)\n print('%s removed ...' % item)\n except OSError:\n try:\n shutil.rmtree(item)\n print('%s/ removed ...' % item)\n except OSError as err:\n print(err)\n\n\ndef read_file(filename):\n \"\"\"Read the contents of a file located relative to setup.py\"\"\"\n with open(join(abspath(dirname(__file__)), filename)) as file:\n return file.read()\n\n\nsetup(\n name='SentryLogs',\n version=package.__version__,\n author=package.__author__,\n author_email=package.__author_email__,\n classifiers=[\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ],\n description=package.__doc__.strip(),\n long_description=read_file('README.rst'),\n license=package.__license__,\n url=package.__url__,\n install_requires=read_file('requirements.txt'),\n entry_points={\n 'console_scripts': [\n 'sentrylogs = sentrylogs.bin.sentrylogs:main',\n ],\n },\n packages=[\n 'sentrylogs',\n 'sentrylogs.bin',\n 'sentrylogs.conf',\n 'sentrylogs.parsers',\n ],\n test_suite='tests',\n tests_require=['tox'],\n cmdclass={\n 'clean': Clean,\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"581847388","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^about/$', views.about, name='abouts'),\n url(r'^committees/$', views.committees, name='committees'),\n url(r'^council-members/$', views.council_members, name='council_members'),\n url(r'^committee/(.*)/$', views.committee_detail, name='committee_detail'),\n url(r'^legislation/(.*)/$', views.bill_detail, name='bill_detail'),\n url(r'^person/(.*)/$', views.person, name='person'),\n url(r'^login/$', views.user_login, name='user_login'),\n url(r'^logout/$', views.user_logout, name='user_logout'),\n url(r'^events/$', views.events, name='events'),\n url(r'^events/(.*)/(.*)/$', views.events, name='events'),\n url(r'^event/(.*)/$', views.event_detail, name='event_detail'),\n]","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"104258058","text":"from Common import *\nfrom Admin import *\n\n\n# 主界面\ndef main_screen():\n while True:\n opt_str = opt_screen(0, opt_strs)\n # 用户选择操作编号\n if opt_str == '0':\n # 查看列车信息\n trainInfo = selectAllTrain()\n train_query(trainInfo)\n elif opt_str == '1':\n if manager_login():\n manager_screen(opt_strs)\n else:\n print(\"登录失败,账号或者密码错误!\")\n elif opt_str == '2':\n username = userLogin()\n if username:\n user_screen(username, opt_strs)\n else:\n print(\"登录失败,账号或者密码错误!\")\n elif opt_str == '3':\n userRegister()\n elif opt_str == '4':\n print(\"退出...\")\n return True\n else:\n print(\"输入错误,请重新输入!\")\n # return True\n\n\nif __name__ == '__main__':\n main_screen()\n\n\n\n","sub_path":"历史版本/火车票售票系统v1.0/火车票售票系统/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"463481546","text":"import configparser\nimport datetime\nimport os\nimport pathlib\nimport pprint\nimport shutil\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef makedirs(dst: str) -> bool:\n \"\"\"makedirs if not exists\n save parent dir's st_atime and st_mtime\n return True if dst dir was made\n \"\"\"\n if os.path.exists(dst):\n return False\n head = os.path.split(dst)[0]\n stinfo = None\n if os.path.exists(head):\n stinfo = os.stat(head)\n os.makedirs(dst)\n if stinfo:\n os.utime(head, (stinfo.st_atime, stinfo.st_mtime))\n return True\n\ndef copytree(src, dst, symlinks: bool = False, ignore: bool = None):\n if not os.path.exists(dst):\n #head, tail = os.path.split(dst)\n head = os.path.split(dst)[0]\n stinfo = None\n if os.path.exists(head):\n stinfo = os.stat(head)\n os.makedirs(dst)\n shutil.copystat(src, dst)\n print(\"MkDirs: \" + dst)\n if stinfo:\n os.utime(head, (stinfo.st_atime, stinfo.st_mtime))\n lst = os.listdir(src)\n if ignore:\n excl = ignore(src, lst)\n lst = [x for x in lst if x not in excl]\n for item in lst:\n s = os.path.join(src, item)\n d = os.path.join(dst, item)\n if symlinks and os.path.islink(s):\n if os.path.lexists(d):\n os.remove(d)\n os.symlink(os.readlink(s), d)\n try:\n st = os.lstat(s)\n mode = stat.S_IMODE(st.st_mode)\n os.lchmod(d, mode)\n except:\n pass # lchmod not available\n elif os.path.isdir(s):\n copytree(s, d, symlinks, ignore)\n shutil.copystat(s, d)\n elif not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:\n shutil.copy2(s, d)\n print(\"Copied: \" + d)\n\ndef read_as_pprint(content: object, unescape_u3000: bool = True):\n txt = pprint.pformat(content)\n if unescape_u3000:\n txt = txt.replace('\\\\u3000', u'\\u3000')\n return txt\n\ndef save_as_pprint(file_path: pathlib.Path, content: object, file_encoding: str = 'utf-8', unescape_u3000: bool = True):\n \"\"\"Save as pretty-print style.\n\n If the file already exists, temporarily create tmp file\n and compare the size of two files then remove lower sized one.\n\n Args:\n file_path (pathlib.Path or str): File path to save.\n content (object): Content to pretty-print.\n file_encoding (str, optional): File encoding.\n unescape_u3000 (bool, optional): True to replace plain text '\\\\u3000'\n to unescaped one (ideographic space). Defaults to True.\n \"\"\"\n def write_content(f_path: pathlib.Path):\n with f_path.open('w', encoding=file_encoding) as f:\n # txt = pprint.pformat(content)\n # if unescape_u3000:\n # txt = txt.replace('\\\\u3000', u'\\u3000')\n # f.write(txt)\n f.write(read_as_pprint(content, unescape_u3000))\n try:\n if not hasattr(file_path, 'exists'):\n file_path = pathlib.Path(file_path)\n if not file_path.exists():\n write_content(file_path)\n else:\n file_path_tmp = file_path.with_suffix('.tmp')\n write_content(file_path_tmp)\n if file_path_tmp.stat().st_size > file_path.stat().st_size:\n file_path.unlink()\n file_path_tmp.rename(file_path)\n else:\n file_path_tmp.unlink()\n except OSError as err:\n print(f'save_as_pprint / OSError: {file_path} | {err}')\n\ndef path_join(path: str, *paths):\n \"Join paths and fix mixed slash and backslash path.\"\n return os.path.normpath(os.path.join(path, *paths))\n\ndef get_day_of_week_jp(date: datetime.date) -> str:\n WEEKDAY = ('月', '火', '水', '木', '金', '土', '日')\n return WEEKDAY[date.weekday()]\n\nclass MyConfig:\n\n def __init__(self, fileName: str = \".python_settings.ini\"):\n self.config = configparser.ConfigParser()\n self.config_path = os.path.join(pathlib.Path.home(), fileName)\n self.config.read(self.config_path)\n\n # def get(self, section, option):\n # if not self.config.has_option(section, option):\n # if not self.config.has_section(section):\n # self.config.add_section(section)\n # value = input(\"Enter {} - {}: \".format(section, option))\n # if not value:\n # return value\n # self.config.set(section, option, value)\n # with open(self.config_path, 'w') as file:\n # self.config.write(file)\n # return value\n # return self.config.get(section, option)\n\n # def get(self, section, option):\n # if self.config.has_option(section, option):\n # return self.config.get(section, option)\n # if not self.config.has_section(section):\n # self.config.add_section(section)\n # value = input(\"Enter {} - {}: \".format(section, option))\n # if value:\n # self.config.set(section, option, value)\n # self.config.write(open(self.config_path, 'w'))\n # return value\n\n def get(self, section: str, option: str) -> str:\n def write_property(conf, s, o, p):\n v = input(\"Enter {} - {}: \".format(s, o))\n if v:\n conf.set(s, o, v)\n conf.write(open(p, 'w'))\n return v\n if self.config.has_option(section, option):\n return self.config.get(section, option)\n elif self.config.has_section(section):\n return write_property(self.config, section, option, self.config_path)\n else:\n self.config.add_section(section)\n return write_property(self.config, section, option, self.config_path)\n\n # def get(self, section, option):\n # def write_property(conf, s, o, p):\n # v = input(\"Enter {} - {}: \".format(s, o))\n # if v:\n # conf.set(s, o, v)\n # conf.write(open(p, 'w'))\n # return v\n # if self.config.has_option(section, option):\n # return self.config.get(section, option)\n # elif not self.config.has_section(section):\n # self.config.add_section(section)\n # return write_property(self.config, section, option, self.config_path)\n\n\n\n# requests\n\ndef print_code_url(response: requests.Response):\n \"\"\"Print status code and url from response of requests.\"\"\"\n print(f'{response.status_code} {response.url}')\n\ndef print_code_url_history(response: requests.Response):\n \"\"\"\"Print all status code and url history from response of requests.\"\"\"\n if response.history:\n for resp in response.history:\n print_code_url(resp)\n print_code_url(response)\n\n\n\n# BeautifulSoup\n\ndef prettify(markup: str) -> str:\n \"\"\"BeautifulSoup prettify not creating new line on some tags.\n\n Args:\n markup (str): html string to prettify.\n\n Returns:\n str: Return prettified string.\n \"\"\"\n # Double curly brackets to avoid problems with .format()\n stripped_markup = markup.replace('{', '{{').replace('}', '}}')\n\n stripped_markup = BeautifulSoup(stripped_markup, 'lxml')\n\n unformatted_tag_list = []\n\n for i, tag in enumerate(stripped_markup.select('span, a, title, script, li')):\n unformatted_tag_list.append(str(tag))\n tag.replace_with(f'{{unformatted_tag_list[{i}]}}')\n return stripped_markup.prettify().format(unformatted_tag_list=unformatted_tag_list)\n\ndef write_prettify(file_path: pathlib.Path, file_encoding: str = 'utf-8', soup: BeautifulSoup = None, html: str = None) -> str:\n r\"\"\"Write html document as pretty-print style to a file.\n\n Write html document as pretty-print style from soup(BeautifulSoup) or string to the file specified by file_path.\n Either soup or html is needed.\n\n Args:\n file_path (pathlib.Path or str): File path to save.\n file_encoding (str, optional): File encoding. Defaults to utf-8.\n soup (BeautifulSoup, optional): BeautifulSoup object. Defaults to None.\n html (str, optional): Html string. Defaults to None.\n\n Returns:\n str: Return prettified string or None if neither soup nor html is not specified.\n \"\"\"\n if not (soup or html):\n return None\n if not soup:\n soup = BeautifulSoup(html, 'lxml')\n prettified = soup.prettify()\n if not hasattr(file_path, 'exists'):\n file_path = pathlib.Path(file_path)\n with file_path.open('w', encoding=file_encoding) as f:\n print(prettified, file=f)\n return prettified\n\ndef get_payload_from_form(name: str, name_or_id: str = 'name', soup: BeautifulSoup = None, html: str = None) -> dict:\n r\"\"\"Get payload from form.\n\n Specify name and name_or_id to search a form.\n\n Args:\n name (str): Name or id of form.\n name_or_id (str, optional): Search by name or id. Defaults to 'name'.\n html (str, optional): Source from html.\n soup (BeautifulSoup, optional): Source from soup.\n\n Returns:\n dict: Return dict of payload.\n \"\"\"\n if not (soup or html):\n return None\n if not soup:\n soup = BeautifulSoup(html, 'lxml')\n form = soup.find('form', {name_or_id: name})\n payload = dict()\n for child in form('input'):\n value = ''\n try:\n value = child['value']\n except KeyError:\n value = ''\n try:\n payload[child['name']] = value\n except KeyError:\n pass\n return payload\n","sub_path":"mymod.py","file_name":"mymod.py","file_ext":"py","file_size_in_byte":9503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"514186909","text":"class InputError(Exception):pass\nimport requests as r\nfrom bs4 import BeautifulSoup as bs\nid_n=input(\"enter the id no:\")\nif len(id_n)>10:raise InputError(\"Please enter valid credentials!!!\")\nsem=input(\"enter sem:\")\ndat={'__EVENTVALIDATION': '/wEWFQKj/sbfBgLnsLO+DQLIk+gdAsmT6B0CypPoHQLLk+gdAsyT6B0CzZPoHQLOk+gdAt+T6B0C0JPoHQLIk6geAsiTpB4CyJOgHgLIk5weAsiTmB4CyJOUHgKL+46CBgKM54rGBgK7q7GGCALWlM+bAsr6TbZa4e1ProM8biQQXbC9/wS2', 'txtreg':id_n, '__VIEWSTATEGENERATOR': '65B05190', '__VIEWSTATE': '/wEPDwULLTE3MTAzMDk3NzUPZBYCAgMPZBYCAgcPDxYCHgRUZXh0ZWRkZKKjA/8YeuWfLRpWAZ2J1Qp0eXCJ', 'Button1': 'Get Result',\"cbosem\":sem}\nt=r.post(\"https://doeresults.gitam.edu/onlineresults/pages/Newgrdcrdinput1.aspx\",data=dat)\ns=bs(t.text,\"html.parser\")\ntry:\n\tr=s.findAll(\"span\")\n\tres=[]\n\tfor i in r:\n\t\tif i[\"id\"]==\"Label11\":\n\t\t\ti[\"id\"]=\"Exam\"\n\t\t\tres.append(i[\"id\"])\n\t\telif i[\"id\"].startswith(\"lbl\"):\n\t\t\tres.append(i[\"id\"].replace(\"lbl\",\"\"))\n\tr=[p.text for p in r]\n\tq=list(zip(res,r))\n\tfor (i,j) in q:\n\t\tprint(\"%s:\\t%s\"%(i,j))\nexcept:InputError(\"entered invalid credentials!!!!\")\n\n\n","sub_path":"scrap2.py","file_name":"scrap2.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"192140954","text":"'''\nCreated on Jun 22, 2013\n\n@author: Chad\n'''\nimport ogre.renderer.OGRE as ogre\nimport math\n\nclass StereoManager(object):\n def __init__(self, leftViewport, rightViewport=None, mode=\"SM_ANAGLYPH_RC\"):\n self.mStereoMode = None\n self.mDebugPlane = None\n self.mDebugPlaneNode = None\n self.mLeftViewport = None\n self.mRightViewport = None\n self.mCamera = None\n self.mCompositorInstance = None\n self.mIsFocalPlaneFixed = False\n self.mScreenWidth = 1.0\n self.mEyesSpacing = 0.06\n self.mFocalLength = 10.0\n self.mFocalLengthInfinite = False\n self.mIsInversed = False\n self.mIsCustomProjection = False\n self.mLeftCustomProjection = ogre.Matrix4.IDENTITY\n self.mRightCustomProjection = ogre.Matrix4.IDENTITY\n self.mRightMask = 1 #TODO: ~((uint32)0)\n self.mLeftMask = self.mRightMask\n self.mAvailableModes = {}\n self.mAvailableModes[\"SM_ANAGLYPH_RC\"] = {\"mName\":\"ANAGLYPH_RED_CYAN\", \"mMaterialName\":\"Stereo/RedCyanAnaglyph\", \"mUsesCompositor\": True}\n self.mAvailableModes[\"SM_ANAGLYPH_YB\"] = {\"mName\":\"ANAGLYPH_YELLOW_BLUE\", \"mMaterialName\":\"Stereo/YellowBlueAnaglyph\", \"mUsesCompositor\": True}\n self.mAvailableModes[\"SM_INTERLACED_H\"] = {\"mName\":\"INTERLACED_HORIZONTAL\", \"mMaterialName\":\"Stereo/HorizontalInterlace\", \"mUsesCompositor\": True}\n self.mAvailableModes[\"SM_INTERLACED_V\"] = {\"mName\":\"INTERLACED_VERTICAL\", \"mMaterialName\":\"Stereo/VerticalInterlace\", \"mUsesCompositor\": True}\n self.mAvailableModes[\"SM_INTERLACED_CB\"] = {\"mName\":\"INTERLACED_CHECKBOARD\", \"mMaterialName\":\"Stereo/CheckboardInterlace\", \"mUsesCompositor\": True}\n self.mAvailableModes[\"SM_DUALOUTPUT\"] = {\"mName\":\"DUALOUTPUT\", \"mMaterialName\":\"\", \"mUsesCompositor\": False}\n self.mAvailableModes[\"SM_NONE\"] = {\"mName\":\"NONE\", \"mMaterialName\":\"\", \"mUsesCompositor\": False}\n self.mRenderTargetList = {}\n\n self.mStereoMode = mode\n if not self.mStereoMode:\n return\n self.mCamera = leftViewport.getCamera()\n if self.mAvailableModes[self.mStereoMode][\"mUsesCompositor\"]:\n leftViewport, rightViewport = self.initCompositor(leftViewport, self.mAvailableModes[self.mStereoMode][\"mMaterialName\"])\n\n self.initListeners(leftViewport, rightViewport)\n\n #TODO: Do I need to maintain a separate list of renderTargets other than the main iterator?\n for k,v in self.mRenderTargetList: k.setAutoUpdated(False)\n\n infinite = self.mFocalLengthInfinite\n self.setFocalLength(self.mFocalLength)\n self.setFocalLengthInfinite(infinite)\n\n if self.mIsFocalPlaneFixed:\n self.updateCamera(0)\n\n def initListeners(self, leftViewport, rightViewport):\n self.mLeftCameraListener = StereoCameraListener(self, leftViewport, not self.mIsInversed)\n leftViewport.getTarget().addListener(self.mLeftCameraListener)\n self.mLeftViewport = leftViewport\n\n self.mRightCameraListener = StereoCameraListener(self, rightViewport, self.mIsInversed)\n rightViewport.getTarget().addListener(self.mRightCameraListener)\n self.mRightViewport = rightViewport\n\n def shutdownListeners(self):\n self.mLeftViewport.getTarget().removeListener(self.mLeftCameraListener)\n self.mLeftViewport = None\n self.mRightViewport.getTarget().removeListener(self.mRightCameraListener)\n self.mRightViewport = None\n\n def initCompositor(self, viewport, materialName):\n self.mCompositorViewport = viewport\n self.mCompositorInstance = ogre.CompositorManager.getSingleton().addCompositor(viewport, \"Stereo/BaseCompositor\")\n ogre.CompositorManager.getSingleton().setCompositorEnabled(viewport, \"Stereo/BaseCompositor\", True)\n mat = ogre.MaterialManager.getSingleton().getByName(materialName)\n self.mCompositorInstance.getTechnique().getOutputTargetPass().getPass(0).setMaterial(mat)\n out_left = self.mCompositorInstance.getRenderTarget(\"Stereo/Left\").getViewport(0)\n out_right = self.mCompositorInstance.getRenderTarget(\"Stereo/Right\").getViewport(0)\n #self.mDeviceLostListener = DeviceLostListener(self)\n #ogre.Root.getSingleton().getRenderSystem().addListener(self.mDeviceLostListener)\n return out_left, out_right\n\n def shutdownCompositor(self):\n ogre.CompositorManager.getSingleton().setCompositorEnabled(self.mCompositorViewport, \"Stereo/BaseCompositor\", False)\n ogre.CompositorManager.getSingleton().removeCompositor(self.mCompositorViewport, \"Stereo/BaseCompositor\")\n ogre.Root.getSingleton().getRenderSystem().removeListener(self.mDeviceLostListener)\n self.mCompositorInstance = None\n self.mCompositorViewport = None\n\n def shutdown(self):\n if not self.mStereoMode:\n return\n self.shutdownListeners()\n if self.mAvailableModes[self.mStereoMode][\"mUsesCompositor\"]: self.shutdownCompositor()\n #TODO: Change the mRenderTargetList autoUpdated\n self.mStereoMode = None\n\n def addRenderTargetDependency(self, renderTarget):\n if renderTarget in self.mRenderTargetList.keys(): return\n self.mRenderTargetList[renderTarget] = renderTarget.isAutoUpdated\n renderTarget.setAutoUpdated(False)\n\n def removeRenderTargetDependency(self, renderTarget):\n renderTarget.setAutoUpdated(self.mRenderTargetList[renderTarget])\n del self.mRenderTargetList[renderTarget]\n\n def createDebugPlane(self, sceneMgr, leftMaterialName = \"\", rightMaterialName = \"\"):\n if self.mDebugPlane:\n return\n\n self.mSceneMgr = sceneMgr\n screenPlane = ogre.Plane()\n screenPlane.normal = ogre.Vector3.UNIT_Z\n ogre.MeshManager.getSingleton().createPlane(\"Stereo/Plane\", ogre.ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, screenPlane, 1,1,10,10)\n self.mDebugPlane = sceneMgr.createEntity(\"Stereo/DebugPlane\", \"Stereo/Plane\")\n self.mLeftMaterialName = \"Stereo/Wireframe\" if leftMaterialName==\"\" else leftMaterialName\n self.mRightMaterialName = \"Stereo/Wireframe\" if rightMaterialName==\"\" else rightMaterialName\n self.mDebugPlaneNode = sceneMgr.getRootSceneNode().createChild(\"Stereo/DebugPlaneNode\")\n self.mDebugPlaneNode.attachObject(self.mDebugPlane)\n self.enableDebugPlane(True)\n self.updateDebugPlane()\n\n def destroyDebugPlane(self):\n if self.mDebugPlane:\n parent = self.mDebugPlaneNode.getParent()\n parent.removeAndDestroyChild(\"Stereo/DebugPlaneNode\")\n self.mDebugPlaneNode = None\n self.mSceneMgr.destroyEntity(\"Stereo/DebugPlane\")\n self.mDebugPlane = None\n ogre.MeshManager.getSingleton().remove(\"Stereo/Plane\")\n\n def enableDebugPlane(self, enable):\n if self.mDebugPlane: self.mDebugPlane.setVisible(enable)\n\n def toggleDebugPlane(self):\n if self.mDebugPlane: self.mDebugPlane.setVisible(self.mDebugPlane.isVisible())\n\n def updateDebugPlane(self):\n if self.mDebugPlaneNode and self.mCamera:\n actualFocalLength = self.mCamera.getFarClipDistance()*0.99 if self.mFocalLengthInfinite else self.mFocalLength\n pos = self.mCamera.getDerivedPosition()\n pos += self.mCamera.getDerivedDirection() * actualFocalLength\n self.mDebugPlaneNode.setPosition(pos)\n self.mDebugPlaneNode.setOrientation(self.mCamera.getDerivedOrientation())\n height = actualFocalLength * math.tan(self.mcamera.getFOVy()/2) * 2\n scale = ogre.Vector3.UNIT_SCALE\n scale.z = 1\n scale.y = height\n scale.x = height * self.mCamera.getAspectRatio()\n self.mDebugPlaneNode.setScale(scale)\n\n def getStereoMode(self):\n return self.mStereoMode\n\n def getCamera(self):\n return self.mCamera\n def setCamera(self, cam):\n self.mCamera = cam\n\n def getEyesSpacing(self):\n return self.mEyesSpacing\n def setEyesSpacing(self, l):\n self.mEyesSpacing = l\n\n def getFocalLength(self):\n return Infinity if self.mFocalLengthInfinite else self.mFocalLength\n def setFocalLength(self, l):\n if l==Infinity:\n self.setFocalLengthInfinite(True)\n else:\n self.setFocalLengthInfinite(False)\n old = self.mFocalLength\n self.mFocalLength = l\n if self.mCamera:\n self.mCamera.setFocalLength(self.mFocalLength)\n if self.mIsFocalPlaneFixed: self.updateCamera(self.mFocalLength - old)\n elif self.mDebugPlane: self.updateDebugPlane()\n\n def setFocalLengthInfinite(self, isInfinite=True):\n self.mFocalLengthInfinite = isInfinite\n if isInfinite: self.mIsFocalPlaneFixed = False\n def isFocalLengthInfinite(self):\n return self.mFocalLengthInfinite\n def fixFocalPlanePos(self, fix):\n self.mIsFocalPlaneFixed = fix\n def setScreenWidth(self, w):\n self.mScreenWidth = w\n def useScreenWidth(self, w):\n self.mScreenWidth = w\n self.mIsFocalPlaneFixed = True\n if self.mCamera: self.updateCamera(0)\n\n def setCustomProjectionMatrices(self, enable, leftMatrix, rightMatrix):\n self.mIsCustomProjection = enable\n self.mLeftCustomProjection = leftMatrix\n self.mRightCustomProjection = rightMatrix\n def getCustomProjectionMatrices(self):\n return self.mIsCustomProjection, self.mLeftCustomProjection, self.mRightCustomProjection\n\n def inverseStereo(self, inverse):\n self.mIsInversed = inverse\n self.mLeftCameraListener.mIsLeftEye = not self.mIsInversed\n self.mRightCameraListener.mIsLeftEye = self.mIsInversed\n def isStereoInversed(self):\n return self.mIsInversed\n\n def setVisibilityMask(self, leftMask, rightMask):\n self.mRightMask = rightMask\n self.mLeftMask = leftMask\n def getVisibilityMask(self):\n return self.mRightMask, self.mLeftMask\n\n def getLeftViewport(self):\n return self.mLeftViewport\n def getRightViewport(self):\n return self.mRigmRightViewport\n\n def saveConfig(self, filename):\n pass\n def loadConfig(self, filename):\n pass\n\n def updateAllDependentRenderTargets(self, isLeftEye):\n mask = self.mLeftMask if isLeftEye else self.mRightMask\n for rt,isauto in self.mRenderTargetList:\n n = rt.getNumViewports()\n maskVector = [rt.getViewport(ix).getVisibilityMask() for ix in range(n)]\n for ix in range(n): rt.getViewport(ix).setVisibilityMask(maskVector[ix] and mask)\n rt.update()\n for ix in range(n): rt.getViewport(ix).setVisibilityMask(maskVector[ix])\n def chooseDebugPlaneMaterial(self, isLeftEye):\n if self.mDebugPlane:\n if isLeftEye: self.mDebugPlane.setMaterialName(self.mLeftMaterialName)\n else: self.mDebugPlane.setMaterialName(self.mRightMaterialName)\n\n def updateCamera(self, delta):\n self.mCamera.moveRelative(-delta * ogre.Vector3.UNIT_Z)\n a = 2*math.atan(self.mscreenWidth/(2 * self.mFocalLength * self.mCamera.getAspectRatio()))\n self.mCamera.setFOVy(a)\n\nclass StereoCameraListener(ogre.RenderTargetListener):\n def __init__(self, stereoMgr, viewport, isLeftEye):\n self.mOldPos = None #Vector3\n self.mOldOffset = None #Vector2\n self.mOldVisibilityMask = None\n self.mStereoMgr = stereoMgr\n self.mViewport = viewport\n self.mIsLeftEye = isLeftEye\n self.mCamera = None\n\n def preViewportUpdate(self, evt):\n if evt.source != self.mViewport:\n return\n self.mCamera = self.mViewport.getCamera()\n if not self.mCamera:\n return\n self.mStereoMgr.setCamera(self.mCamera)\n sceneMgr = self.mCamera.getSceneManager()\n self.mOldVisibilityMask = sceneMgr.self.getVisibilityMask()\n\n if self.mIsLeftEye:\n sceneMgr.setVisibilityMask(self.mStereoMgr.mLeftMask and self.mOldVisibilityMask)\n else:\n sceneMgr.setVisibilityMask(self.mStereoMgr.mRightMask and self.mOldVisibilityMask)\n\n offset = self.mStereoMgr.getEyesSpacing() * (-0.5 if self.mIsLeftEye else 0.5)\n\n if not self.mStereoMgr.mIsCustomProjection:\n self.mOldOffset = self.mCamera.getFrustOffset()\n if not self.mStereoMgr.isFocalLengthInfinite():\n self.mCamera.setFrustumOffset(self.mOldOffset - (offset,0))#Vector2\n else:\n if self.mIsLeftEye:\n self.mCamera.setCustomProjectionMatrix(True, self.mstereoMgr.mLeftCustomProjection)\n else:\n self.mCamera.setCustomProjectionMatrix(True, self.mStereoMgr.mRightCustomProjection)\n\n self.mOldPos = self.mCamera.getPosition()\n pos = self.mOldPos #Vector3\n pos += offset * self.mCamera.getRight()\n self.mCamera.setPosition(pos)\n self.mStereoMgr.updateAllDependentRenderTargets(self.mIsLeftEye)\n self.mStereoMgr.chooseDebugPlaneMaterial(self.mIsLeftEye)\n\n def postViewportUpdate(self, evt):\n if evt.source != self.mViewport:\n return\n\n if not self.mStereoMgr.mIsCustomProjection:\n self.mCamera.setFrustumOffset(self.mOldOffset)\n else:\n self.mCamera.setCustomProjectionMatrix(False)\n\n self.mCamera.setPosition(self.mOldPos)\n self.mCamera.getSceneManager().setVisibilityMask(self.mOldVisibilityMask)\n\n\nclass DeviceLostListener(ogre.RenderSystem.Listener):\n def __init__(self, stereoMgr):\n self.mStereoMgr = stereoMgr\n\n def eventOccurred(self, eventName, parameters):\n if eventName==\"DeviceRestored\" and self.mStereoMgr.mCompositorInstance:\n self.mStereoMgr.shutdownListeners()\n leftViewport = self.mStereoMgr.mCompositorInstance.getRenderTarget(\"Stereo/Left\").getViewport(0)\n rightViewport = self.mStereoMgr.mCompositorInstance.getRenderTarget(\"Stereo/Right\").getViewport(0)\n self.mStereoMgr.initListeners(leftViewport, rightViewport)","sub_path":"StereoManager.py","file_name":"StereoManager.py","file_ext":"py","file_size_in_byte":14115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"473077782","text":"# Copyright (c) 2018 Rolls-Royce Power Systems AG. All rights reserved.\n\n\n\"\"\"Saves Kif (correction in field) data from apWarrantyRecallSet event\n\"\"\"\n\nimport logging\nfrom pprint import pprint\n\nfrom .BaseView import BaseView\n\nlogger = logging.getLogger(__name__)\n\n\nclass UpcomingEventsView(BaseView):\n\n def capture_old_data(self, event):\n\n try:\n return self._data_access.load(self.UPCOMING_EVENTS_DATA_TABLE, event.asset)\n except: # pylint: disable broad-except\n logger.exception(\"Exception reading from table %s when capturing the old data\", self.BASIC_DATA_TABLE)\n return None\n\n def on_event(self, event, old_data=None):\n logger.info(\"%s on_event called\", self.__class__.__name__)\n\n payload = event.data\n print(\"\\n\\npayload\\n\\n\\n\")\n pprint(payload)\n print(\"\\n\\n\\n\\n\\n\")\n\n mapped_list, remove_list = self._map_list(event, payload, old_data)\n print(\"\\n\\nmapped_list\\n\\n\\n\")\n pprint(mapped_list)\n print(\"\\n\\n\\n\\n\\n\")\n print(\"\\n\\nremove_list\\n\\n\\n\")\n pprint(remove_list)\n print(\"\\n\\n\\n\\n\\n\")\n\n for item in mapped_list:\n self._data_access.upsert(self.UPCOMING_EVENTS_DATA_TABLE,\n event.asset, item, key={\"_clmno\": item['_clmno'], \"asset_id\": event.asset})\n\n # remove items that have been closed\n for remove_item in remove_list:\n self._data_access.remove(\n self.UPCOMING_EVENTS_DATA_TABLE, event.asset, remove_item)\n\n def _map_list(self, event, items, old_data):\n update_list = []\n remove_list = []\n\n for item in items:\n print(\"\\n\\nitem\\n\\n\\n\")\n pprint(item)\n print(\"\\n\\n\\n\\n\\n\")\n clmno = item.get(\"Clmno\", \"\")\n AssetType = item.get(\"AssetType\", \"\")\n old_Seq = old_data.get(\"Seq\", \"\")\n current_Seq = event.offset\n print(\"\\n\\n\\n\\n\\n\")\n pprint(AssetType)\n pprint(current_Seq)\n pprint(old_Seq)\n pprint(clmno)\n print(\"\\n\\n\\n\\n\\n\")\n if self._is_kif_item_closed(item) and AssetType == \"ENG\" and old_Seq != current_Seq:\n clmno = item.get(\"Clmno\", \"\")\n AssetType = item.get(\"AssetType\", \"\")\n old_Seq = old_data.get(\"Seq\", \"\")\n current_Seq = event.offset\n print(\"\\n\\n\\n\\n\\n\")\n pprint(AssetType)\n pprint(current_Seq)\n pprint(old_Seq)\n pprint(clmno)\n print(\"\\n\\n\\n\\n\\n\")\n # if old_data:\n # old_Seq = old_data.get(\"Seq\", \"\")\n # else:\n # old_Seq = None\n\n if not clmno:\n raise ValueError(\"keying off Clmno for kif data but field missing\")\n\n # this item has been closed so remove from upcoming events\n remove_list.append({\"asset_id\": event.asset, \"_clmno\": clmno})\n\n # if AssetType == \"ENG\":\n\n # if AssetType == \"ENG\" and old_Seq != current_Seq: # old.event.offset ??\n # remove_list.append({\"Seq\": old_Seq}) # how to delete whole event wrt event.offset != old.event.offset\n # print(\"##########\")\n continue\n\n mapped_item = self._create_kif_data(event, item)\n update_list.append(mapped_item)\n\n return update_list, remove_list\n\n","sub_path":"offline/__Digital_Twin/__release2/__release2_sprint12/Update sapwarrantyrecall integrator to fetch upcoming engine events for aggregates - US 21291/upcoming events.py","file_name":"upcoming events.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"56510964","text":"# CÀI ĐẶT\r\n\r\n# Nhạc nền\r\n# Đặt tên file trong '' hoặc để None để tắt nhạc\r\nBGMfile = None\r\n\r\n# Số rùa/số đường đua\r\n# Phải đảm bảo số này <= số con vật có trong set đã chọn\r\n# (trong phần 'Hình dạng con rùa' bên dưới)\r\n# và <= số màu có trong turtleColors\r\nc = 4\r\n\r\n# Số lượt đua (VD: 2 = có lượt đi lượt về)\r\nraceCount = 3\r\n\r\n# Đường đua\r\ninitX = -300\r\ninitY = 100\r\ntrackCount = c # số rùa = số đường đua\r\ntrackUnitLength = 20\r\ntrackUnitCount = [10, 20, 30] # 3 mức short, medium, long\r\ntrackWidth = 60\r\ntrackDivPadding = 10\r\n\r\n# Rùa\r\nturtleCount = c # số rùa = số đường đua\r\nturtleColors = ['red', 'orange', 'green', 'blue', 'violet', 'purple', 'brown', 'black']\r\nturtleMoveLength = [10, 15, 20]\r\nturtleBackStopBias = 6 # giá trị trong khoảng 0 - 10\r\n\r\n# Hình dạng con rùa\r\n# Tên mỗi con vật trong set = tên file bỏ đuôi .GIF\r\n# Tất cả con vật, bất kể set nào, đều phải được đặt trong ./Resources\r\nSet1 = ['chicken', 'horse', 'pig', 'sheep']\r\nSet2 = ['butterfly', 'grasshopper', 'turtle', 'unicorn', 'fish']\r\nSet3 = []\r\nSet4 = []\r\nSetPepe = ['pepe1', 'pepe2', 'pepe3', 'pepe4']\r\n# turtleShapes = chọn tên set con vật sẽ dùng\r\nturtleShapes = SetPepe\r\n\r\n# Bảng điểm\r\nscoreboardPadding = 20","sub_path":"_SETTINGS_.py","file_name":"_SETTINGS_.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"69481096","text":"# encoding=utf-8\nimport email\nimport random\nimport string\nfrom email.mime.text import MIMEText\n\n\ndef message(\n to_name=None, to_email=None, from_name=None, from_email=None, subject=None, body_text=None\n):\n to_name = to_name or random_string()\n to_email = to_email or random_email()\n from_name = from_name or random_string()\n from_email = from_email or random_email()\n subject = subject or random_string()\n body_text = body_text or random_string()\n\n msg = MIMEText(body_text)\n msg[\"To\"] = email.utils.formataddr((to_name, to_email))\n msg[\"From\"] = email.utils.formataddr((from_name, from_email))\n msg[\"Subject\"] = subject\n return msg\n\n\ndef random_email():\n return \"{0}@example.com\".format(random_string())\n\n\ndef random_string(length=10, characters=string.ascii_letters + string.digits):\n return \"\".join(random.choice(characters) for _ in range(length))\n","sub_path":"tests/utils/builders.py","file_name":"builders.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"389779904","text":"# Copyright 2016 Open Source Robotics Foundation, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport importlib\nimport logging\n\nimport ament_index_python\n\nfrom rclpy.exceptions import ImplementationAlreadyImportedException\nfrom rclpy.exceptions import InvalidRCLPYImplementation\n\n__rmw_implementations = None\n__selected_rmw_implementation = None\n__rmw_implementation_module = None\n\nAMENT_INDEX_NAME = 'rmw_python_extension'\n\n\ndef reload_rmw_implementations():\n \"\"\"(Re)Load the available rmw implementations by inspecting the ament index.\"\"\"\n global __rmw_implementations\n __rmw_implementations = sorted(ament_index_python.get_resources(AMENT_INDEX_NAME).keys())\n return __rmw_implementations\n\n\ndef get_rmw_implementations():\n \"\"\"Return a list of available rmw implementations by name.\"\"\"\n if __rmw_implementations is None:\n reload_rmw_implementations()\n return __rmw_implementations\n\n\ndef select_rmw_implementation(rmw_implementation):\n \"\"\"Set the rmw implementation to be imported by name.\n\n Can be called multiple times, but only before calling :py:func:`rclpy.init`\n and/or :py:func:`import_rmw_implementation`.\n\n If given an rmw implementation that is not in the list provided by\n :py:func:`get_rmw_implementations` then the\n :py:class:`InvalidRCLPYImplementation` exception will be raised.\n\n :raises: :py:class:`ImplementationAlreadyImportedException` if\n :py:func:`import_rmw_implementation` has already been called and the\n module already imported.\n \"\"\"\n global __selected_rmw_implementation\n if __rmw_implementation_module is not None:\n raise ImplementationAlreadyImportedException()\n if rmw_implementation not in get_rmw_implementations():\n raise InvalidRCLPYImplementation()\n __selected_rmw_implementation = rmw_implementation\n\n\ndef import_rmw_implementation():\n \"\"\"Import and return the selected or default rmw implementation.\n\n This function can be called multiple times, but the rmw implementation is\n only imported the first time.\n Subsequent calls will return a cached rmw implementation module.\n\n If :py:func:`select_rmw_implementation` has not previously been called then\n a default implementation will be selected implicitly before loading.\n \"\"\"\n global __rmw_implementation_module\n if __rmw_implementation_module is not None:\n return __rmw_implementation_module\n if __selected_rmw_implementation is None:\n logger = logging.getLogger('rclpy')\n select_rmw_implementation(get_rmw_implementations()[0]) # select the first one\n logger.debug(\"Implicitly selecting the '{0}' rmw implementation.\"\n .format(__selected_rmw_implementation))\n module_name = '._rclpy__{rmw_implementation}'.format(\n rmw_implementation=__selected_rmw_implementation,\n )\n __rmw_implementation_module = importlib.import_module(module_name, package='rclpy')\n return __rmw_implementation_module\n","sub_path":"rclpy/rclpy/impl/rmw_implementation_tools.py","file_name":"rmw_implementation_tools.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"451400199","text":"# Google Chat Messages & Group Information\n# Author: Josh Hickman (josh@thebinaryhick.blog) & Alexis Brignoni (https://linqapp.com/abrignoni)\n# Date 2021-02-05\n# Version: 0.1\n# Requirements: blackboxprotobuf\n\nimport os\nimport sqlite3\nimport textwrap\nimport blackboxprotobuf\n\nfrom scripts.artifact_report import ArtifactHtmlReport\nfrom scripts.ilapfuncs import logfunc, tsv, timeline, is_platform_windows, open_sqlite_db_readonly\n\ndef get_googleChat(files_found, report_folder, seeker, wrap_text):\n \n for file_found in files_found:\n file_found = str(file_found)\n if not file_found.endswith('dynamite.db'):\n continue # Skip all other files\n \n db = open_sqlite_db_readonly(file_found)\n cursor = db.cursor()\n cursor.execute('''\n SELECT\n datetime(topic_messages.create_time/1000000,'unixepoch') AS \"Message Time (UTC)\",\n Groups.name AS \"Group Name\",\n users.name AS \"Sender\",\n topic_messages.text_body AS \"Message\",\n topic_messages.annotation AS \"Message Attachment\"\n FROM\n topic_messages\n JOIN Groups on Groups.group_id=topic_messages.group_id\n JOIN users ON users.user_id=topic_messages.creator_id\n ORDER BY \"Timestamp (UTC)\" ASC\n ''')\n\n all_rows = cursor.fetchall()\n usageentries = len(all_rows)\n data_list = []\n if usageentries > 0:\n for x in all_rows:\n values = blackboxprotobuf.decode_message(x[4])\n if x[4] == b'':\n data_list.append((x[0], x[1], x[2], x[3], '', '', '', '','','','',''))\n else:\n #images section\n try:\n item11 = (values[0]['1']['10'].get('3').decode('utf-8'))\n item12 = (values[0]['1']['10'].get('4').decode('utf-8'))\n item13 = (values[0]['1']['10']['5']['1'])\n item14 = (values[0]['1']['10']['5']['2'])\n data_list.append((x[0], x[1], x[2], x[3], '', '', '', '', item11, item12, item13, item14))\n continue\n except:\n pass\n #meeting plain section\n try:\n item8 = (values[0]['1']['12']['1']['1'].decode('utf-8'))\n item9 = (values[0]['1']['12']['1']['3'].decode('utf-8'))\n item10 = (values[0]['1']['12']['1']['2'].decode('utf-8'))\n data_list.append((x[0], x[1], x[2], x[3], item9, item10, '', '','','','',''))\n continue\n except:\n pass\n \n #meeting with sender name\n try:\n item4 = (values[0]['1'][0]['12']['1']['1'].decode('utf-8'))\n item5 = (values[0]['1'][0]['12']['1']['3'].decode('utf-8'))\n item6 = (values[0]['1'][0]['12']['1']['6']['16']['1'].decode('utf-8'))\n item7 = (values[0]['1'][0]['12']['1']['6']['16']['2'].decode('utf-8'))\n data_list.append((x[0], x[1], x[2], x[3], item5, item6, item7, '','','','',''))\n continue\n except:\n pass\n \n try:\n item1 = (values[0]['1'][0]['12']['1']['1'].decode('utf-8'))\n item2 = (values[0]['1'][0]['12']['1']['3'].decode('utf-8'))\n item3 = (values[0]['1'][0]['12']['1']['2'].decode('utf-8'))\n data_list.append((x[0], x[1], x[2], x[3], item2, item3, '','','','','',''))\n except:\n pass\n \n if usageentries > 0:\n report = ArtifactHtmlReport('Google Chat Messages')\n report.start_artifact_report(report_folder, 'Chat Messages')\n report.add_script()\n data_headers = ('Message Timestamp (UTC)','Group Name','Sender','Message','Meeting Code', 'Meeting URL','Meeting Sender','Meeting Sender Profile Pic URL','Filename','File Type','Width','Height')\n\n report.write_artifact_data_table(data_headers, data_list, file_found)\n report.end_artifact_report()\n \n tsvname = f'Google Chat Messages'\n tsv(report_folder, data_headers, data_list, tsvname)\n \n tlactivity = f'Google Chat Messages'\n timeline(report_folder, tlactivity, data_list, data_headers)\n else:\n logfunc('No Google Chat Messages data available')\n\n cursor.execute('''\n SELECT\n datetime(Groups.create_time/1000000,'unixepoch') AS \"Group Created Time (UTC)\",\n Groups.name AS \"Group Name\",\n users.name AS \"Group Creator\",\n datetime(Groups.last_view_time/1000000,'unixepoch') AS \"Time Group Last Viewed (UTC)\"\n FROM\n Groups\n JOIN users ON users.user_id=Groups.creator_id\n ORDER BY \"Group Created Time (UTC)\" ASC\n ''')\n\n all_rows = cursor.fetchall()\n usageentries = len(all_rows)\n if usageentries > 0:\n report = ArtifactHtmlReport('Google Chat Group Information')\n report.start_artifact_report(report_folder, 'Group Information')\n report.add_script()\n data_headers = ('Group Created Time (UTC)','Group Name','Group Creator','Time Group Last Viewed (UTC)') \n data_list = []\n for row in all_rows:\n data_list.append((row[0],row[1],row[2],row[3]))\n\n report.write_artifact_data_table(data_headers, data_list, file_found)\n report.end_artifact_report()\n \n tsvname = f'Google Chat Group Information'\n tsv(report_folder, data_headers, data_list, tsvname)\n \n tlactivity = f'Google Chat Group Information'\n timeline(report_folder, tlactivity, data_list, data_headers)\n else:\n logfunc('No Google Chat Group Information data available')\n \n db.close()","sub_path":"scripts/artifacts/googleChat.py","file_name":"googleChat.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"542291144","text":"import pandas as pd \nimport numpy as np\nimport utm\nfrom sklearn.metrics import precision_score, confusion_matrix, classification_report\nimport seaborn as sns\n\nlabel_dic = {1: 'Still', 2: 'Walking', 3: 'Run', 4: 'Bike', 5: 'Car', 6: 'Bus', 7: 'Train', 8: 'Subway'}\n\n# (latitude, longitude) -> east\ndef gps2utm_east(x):\n try:\n return utm.from_latlon(x['latitude'], x['longitude'])[0]\n except:\n return np.nan\n# (latitude, longitude) -> north\ndef gps2utm_north(x):\n try:\n return utm.from_latlon(x['latitude'], x['longitude'])[1]\n except:\n return np.nan\n\n# evaluate prediction result\ndef evaluate(y_true, y_pred, normalize = True, names = list(label_dic.values())):\n if normalize:\n conf = confusion_matrix(y_true, y_pred, normalize = 'true')\n else:\n conf = confusion_matrix(y_true, y_pred)\n print(confusion_matrix(y_true, y_pred))\n sns.heatmap(conf)\n print(classification_report(y_true, y_pred, target_names = names))\n\n# save prediction result\ndef save_prediction(pred_time, pred_res, file_path = 'data/RY_predictions.txt'):\n res = pd.DataFrame({'time': pred_time, 'label': pred_res})\n res.to_csv(file_path, index = False, header = False, sep = '\\t')\n\n# plot prediction labels\ndef plot_prediction(y_pred, y_true):\n plt.figure(figsize = [20, 8])\n plt.plot(y_pred, alpha = 0.4)\n plt.plot(y_true)\n\n# save prediction result\ndef save_prediction(pred_time, pred_res, file_path = 'data/RY_predictions.txt'):\n res = pd.DataFrame({'time': pred_time, 'label': pred_res})\n res.to_csv(file_path, index = False, header = False, sep = '\\t')\n\n# # one hot encoder\n# def get_one_hot(df, class_col_name):\n# X = df[class_col_name].values.reshape(-1, 1)\n# enc = OneHotEncoder(handle_unknown = 'ignore', sparse = False).fit(X)\n# col_names = [\"{}_{}\".format(class_col_name, i) for i in enc.categories_[0].tolist()]\n# return pd.DataFrame(enc.transform(X), columns = col_names)\n","sub_path":"utils/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"19131869","text":"from context import twitchplays\n\nimport unittest\n\n\nclass TestSanitizeMessage(unittest.TestCase):\n def test_comments_removed(self):\n result_str = \"{\\n}\"\n message_str = \"\"\"{\n // This is a comment\n }\"\"\"\n sanitized_message_str = twitchplays.sanitize_message(message_str)\n self.assertEqual(sanitized_message_str, result_str, \"Failed to remove single line comment\")\n message_str = \"\"\"{\n /* This is a\n * multiline comment\n */\n }\"\"\"\n sanitized_message_str = twitchplays.sanitize_message(message_str)\n self.assertEqual(sanitized_message_str, result_str, \"Failed to remove multi line comment\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/testSanitizeMessage.py","file_name":"testSanitizeMessage.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"175450511","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2018 ICON Foundation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport hashlib\nimport json\nfrom abc import ABC, ABCMeta\nfrom enum import IntEnum\nfrom typing import TYPE_CHECKING, Optional, Any, Callable\nfrom typing import Tuple, List\n\nfrom coincurve import PublicKey\n\nfrom .icon_score_constant import FORMAT_IS_NOT_DERIVED_OF_OBJECT, T\nfrom ..base.address import Address, AddressPrefix\nfrom ..base.exception import InvalidParamsException, IconScoreException, InvalidInstanceException\nfrom ..icon_constant import CHARSET_ENCODING\nfrom ..icon_constant import Revision\nfrom ..iconscore.context.context import ContextContainer\nfrom ..iconscore.icon_score_step import StepType\n\nif TYPE_CHECKING:\n from .icon_score_context import IconScoreContext\n\n\nclass InterfaceScoreMeta(ABCMeta):\n def __new__(mcs, name, bases, namespace, **kwargs):\n if ABC in bases:\n return super().__new__(mcs, name, bases, namespace, **kwargs)\n\n cls = super().__new__(mcs, name, bases, namespace, **kwargs)\n return cls\n\n\nclass InterfaceScore(ABC, metaclass=InterfaceScoreMeta):\n \"\"\"\n An interface class that is used to invoke other SCORE’s external method.\n \"\"\"\n def __init__(self, addr_to: 'Address'):\n \"\"\"\n A Python init function. Invoked when the contract call create_interface_score()\n \"\"\"\n self.__addr_to = addr_to\n self.__icx = 0\n\n @property\n def addr_to(self) -> 'Address':\n \"\"\"\n The address of SCORE to invoke\n\n :return: :class:`.Address` SCORE address\n \"\"\"\n return self.__addr_to\n\n def icx(self, value: int):\n \"\"\"Set the number of ICX coins to send on inter-call.\n\n This function can be used when you want to call payable functions of other SCOREs along with ICX coins.\n\n It is strongly recommended to use icx() in method chaining like the following:\n ``interface_score.icx(2 * 10 ** 18).func()``\n\n .. note::\n The unit of value is not icx but loop.\n 1 icx is 10 ** 18 loop.\n\n .. versionadded:: iconservice-1.7.3\n\n :param value: the number of ICX coins to send (unit: loop)\n :type value: int\n :return: :class:`.InterfaceScore` object\n \"\"\"\n if not (isinstance(value, int) and value >= 0):\n raise InvalidParamsException(f\"Invalid icx: {value}\")\n\n self.__icx = value\n return self\n\n def __get_icx(self) -> int:\n return self.__icx\n\n def __reset_icx(self):\n self.__icx = 0\n\n\nclass Block(object):\n def __init__(self, block_height: int, timestamp: int) -> None:\n \"\"\"Constructor\n\n :param block_height: block height\n :param timestamp: block timestamp\n \"\"\"\n self._height = block_height\n # unit: microsecond\n self._timestamp = timestamp\n\n @property\n def height(self) -> int:\n return self._height\n\n @property\n def timestamp(self) -> int:\n return self._timestamp\n\n\nclass ScoreApiStepRatio(IntEnum):\n SHA3_256 = 1000\n SHA_256 = 1000\n CREATE_ADDRESS_WITH_COMPRESSED_KEY = 15000\n CREATE_ADDRESS_WITH_UNCOMPRESSED_KEY = 1500\n JSON_DUMPS = 5000\n JSON_LOADS = 4000\n RECOVER_KEY = 70000\n\n\ndef _get_api_call_step_cost(context: 'IconScoreContext', ratio: ScoreApiStepRatio) -> int:\n \"\"\"Returns the step cost for a given SCORE API\n\n API CALL step cost in context.step_counter means the step cost of sha3_256(b'')\n Each step cost for other APIs is calculated from the relative ratio based on sha3_256(b'')\n\n other_api_call_step_cost =\n API_CALL_STEP_COST * other_api_call_ratio // ScoreApiStepRatio.SHA3_256\n\n :param context: IconScoreContext instance\n :param ratio: The ratio of a given SCORE API based on ScoreApiStepRatio.SHA3_256\n :return: step_cost for a given SCORE API\n \"\"\"\n api_call_step: int = context.step_counter.get_step_cost(StepType.API_CALL)\n return api_call_step * ratio // ScoreApiStepRatio.SHA3_256\n\n\ndef revert(message: Optional[str] = None, code: int = 0) -> None:\n \"\"\"\n Reverts the transaction and breaks.\n All the changes of state DB in current transaction will be rolled back.\n\n :param message: revert message\n :param code: code\n \"\"\"\n try:\n if not isinstance(code, int):\n code = int(code)\n\n if not isinstance(message, str):\n message = str(message)\n except:\n raise InvalidParamsException(\"Revert error: code or message is invalid\")\n else:\n raise IconScoreException(message, code)\n\n\ndef sha3_256(data: bytes) -> bytes:\n \"\"\"\n Computes sha3_256 hash using the input data\n\n :param data: input data\n :return: hashed data in bytes\n \"\"\"\n return _hash(\"sha3_256\", data)\n\n\ndef sha_256(data: bytes) -> bytes:\n \"\"\"\n Computes sha256 hash using the input data\n\n :param data: input data\n :return: hashed data in bytes\n \"\"\"\n return _hash(\"sha256\", data)\n\n\ndef _hash(name: str, data: bytes) -> bytes:\n \"\"\"Protected hash function\n\n :param name: hash function name: \"sha256\" or \"sha3_256\"\n :param data: data to hash\n :return: hashed data in bytes\n \"\"\"\n if name not in (\"sha3_256\", \"sha256\"):\n raise InvalidParamsException(f\"Not supported: {name}\")\n if not isinstance(data, bytes):\n raise InvalidParamsException(\"Invalid dataType\")\n\n context = ContextContainer._get_context()\n assert context\n\n if context and context.revision >= Revision.THREE.value:\n size = len(data)\n chunks = size // 32\n if size % 32 > 0:\n chunks += 1\n\n step_cost: int = context.step_counter.get_step_cost(StepType.API_CALL)\n step: int = step_cost + step_cost * chunks // 10\n\n context.step_counter.consume_step(StepType.API_CALL, step)\n\n func = getattr(hashlib, name)\n return func(data).digest()\n\n\ndef json_dumps(obj: Any) -> str:\n \"\"\"\n Converts a python object `obj` to a JSON string\n\n :param obj: a python object to be converted\n :return: json string\n \"\"\"\n context = ContextContainer._get_context()\n assert context\n\n if context and context.revision >= Revision.THREE.value:\n ret: str = json.dumps(obj, separators=(',', ':'))\n\n step_cost: int = _get_api_call_step_cost(context, ScoreApiStepRatio.JSON_DUMPS)\n step: int = step_cost + step_cost * len(ret.encode(CHARSET_ENCODING)) // 100\n\n context.step_counter.consume_step(StepType.API_CALL, step)\n else:\n ret: str = json.dumps(obj)\n\n return ret\n\n\ndef json_loads(src: str) -> Any:\n \"\"\"\n Parses a JSON string `src` and converts it to a python object\n\n :param src: a JSON string to be converted\n :return: a python object\n \"\"\"\n if not isinstance(src, str):\n return None\n\n context = ContextContainer._get_context()\n assert context\n\n if context and context.revision >= Revision.THREE.value:\n step_cost: int = _get_api_call_step_cost(context, ScoreApiStepRatio.JSON_LOADS)\n step: int = step_cost + step_cost * len(src.encode(CHARSET_ENCODING)) // 100\n\n context.step_counter.consume_step(StepType.API_CALL, step)\n\n return json.loads(src)\n\n\ndef create_address_with_key(public_key: bytes) -> Optional['Address']:\n \"\"\"Create an address with a given public key\n\n :param public_key: Public key based on secp256k1\n :return: Address created from a given public key or None if failed\n \"\"\"\n if not isinstance(public_key, bytes):\n return None\n\n # 33: prefix(1 byte) + keyBody(32 bytes)\n # 65: prefix(1 byte) + keyBody(64 bytes)\n key_size: int = len(public_key)\n if key_size not in (33, 65):\n return None\n\n context = ContextContainer._get_context()\n assert context\n\n if context and context.revision >= Revision.THREE.value:\n if key_size == 33:\n ratio = ScoreApiStepRatio.CREATE_ADDRESS_WITH_COMPRESSED_KEY\n else:\n ratio = ScoreApiStepRatio.CREATE_ADDRESS_WITH_UNCOMPRESSED_KEY\n\n step: int = _get_api_call_step_cost(context, ratio)\n context.step_counter.consume_step(StepType.API_CALL, step)\n\n try:\n return _create_address_with_key(public_key)\n except:\n return None\n\n\ndef _create_address_with_key(public_key: bytes) -> Optional['Address']:\n assert isinstance(public_key, bytes)\n assert len(public_key) in (33, 65)\n\n size = len(public_key)\n prefix: int = public_key[0]\n\n if size == 33 and prefix in (0x02, 0x03):\n uncompressed_public_key: bytes = _convert_key(public_key, compressed=True)\n elif size == 65 and prefix == 0x04:\n uncompressed_public_key: bytes = public_key\n else:\n return None\n\n body: bytes = hashlib.sha3_256(uncompressed_public_key[1:]).digest()[-20:]\n return Address(AddressPrefix.EOA, body)\n\n\ndef _convert_key(public_key: bytes, compressed: bool) -> Optional[bytes]:\n \"\"\"Convert key between compressed and uncompressed keys\n\n :param public_key: compressed or uncompressed key\n :return: the counterpart key of a given public_key\n \"\"\"\n public_key_object = PublicKey(public_key)\n return public_key_object.format(compressed=not compressed)\n\n\ndef recover_key(msg_hash: bytes, signature: bytes, compressed: bool = True) -> Optional[bytes]:\n \"\"\"Returns the public key from message hash and recoverable signature\n\n :param msg_hash: 32 bytes data\n :param signature: signature_data(64) + recovery_id(1)\n :param compressed: the type of public key to return\n :return: public key recovered from msg_hash and signature\n (compressed: 33 bytes key, uncompressed: 65 bytes key)\n \"\"\"\n context = ContextContainer._get_context()\n assert context\n\n if context and context.revision >= Revision.THREE.value:\n step_cost: int = _get_api_call_step_cost(context, ScoreApiStepRatio.RECOVER_KEY)\n context.step_counter.consume_step(StepType.API_CALL, step_cost)\n\n try:\n return _recover_key(msg_hash, signature, compressed)\n except:\n return None\n\n\ndef _recover_key(msg_hash: bytes, signature: bytes, compressed: bool) -> Optional[bytes]:\n if isinstance(msg_hash, bytes) \\\n and len(msg_hash) == 32 \\\n and isinstance(signature, bytes) \\\n and len(signature) == 65:\n return PublicKey.from_signature_and_message(signature, msg_hash, hasher=None).format(compressed)\n\n return None\n\n\nclass PRepInfo(object):\n def __init__(self, address: 'Address', delegated: int, name: str):\n self.address = address\n self.delegated = delegated\n self.name = name\n\n\ndef get_main_prep_info() -> Tuple[List[PRepInfo], int]:\n context = ContextContainer._get_context()\n assert context\n\n term = context.term\n if term is None:\n return [], -1\n\n prep_info_list: List[PRepInfo] = []\n for prep_snapshot in term.main_preps:\n prep = context.get_prep(prep_snapshot.address)\n prep_info_list.append(PRepInfo(\n prep_snapshot.address,\n prep_snapshot.delegated,\n prep.name\n ))\n return prep_info_list, term.end_block_height\n\n\ndef get_sub_prep_info() -> Tuple[List[PRepInfo], int]:\n context = ContextContainer._get_context()\n assert context\n\n term = context.term\n if term is None:\n return [], -1\n\n prep_info_list: List[PRepInfo] = []\n for prep_snapshot in term.sub_preps:\n prep = context.get_prep(prep_snapshot.address)\n prep_info_list.append(PRepInfo(\n prep_snapshot.address,\n prep_snapshot.delegated,\n prep.name\n ))\n return prep_info_list, term.end_block_height\n\n\ndef create_interface_score(addr_to: 'Address',\n interface_cls: Callable[['Address'], T]) -> T:\n \"\"\"\n Creates an object, through which you have an access to the designated SCORE’s external functions.\n\n :param addr_to: SCORE address\n :param interface_cls: interface class\n :return: An instance of given class\n \"\"\"\n\n if interface_cls is InterfaceScore:\n raise InvalidInstanceException(FORMAT_IS_NOT_DERIVED_OF_OBJECT.format(InterfaceScore.__name__))\n return interface_cls(addr_to)\n","sub_path":"iconservice/iconscore/icon_score_base2.py","file_name":"icon_score_base2.py","file_ext":"py","file_size_in_byte":12708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"412391211","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: randomCode.py\n Author: maple\n date: 2019/3/15 23:09\n Software: PyCharm\n-------------------------------------------------\n\"\"\"\n\n\nimport random\n\n#随机产生激活码的类\nclass randomCodeList(object):\n\n #初始化\n def __init__(self):\n pass\n\n def getCodeList(self,num,lenth):\n codeNum = num\n codeLenth = lenth\n i = 0\n codeList = []\n while i < codeNum:\n tmp = self.getStringRandom(codeLenth)\n if tmp not in codeList:\n codeList.append(tmp)\n i = i + 1\n return codeList\n\n\n #返回一个激活码\n def getStringRandom(self,codeLenth):\n code = \"\"\n for i in range(0, codeLenth):\n tmp = str(random.randint(1, 3))\n if tmp == '1':\n code = code + str(self.getRandomNum())\n elif tmp == '2':\n code = code + chr(self.getUpChar())\n else:\n code = code + chr(self.getLowerChar())\n\n return code\n\n # 随机数字\n def getRandomNum(self):\n return random.randint(0, 9)\n\n # 随机大写ASCII码\n def getUpChar(self):\n return random.randint(0, 25) + 65\n\n # 随机小写ASCII码\n def getLowerChar(self):\n return random.randint(0, 25) + 97\n","sub_path":"0002/randomCode.py","file_name":"randomCode.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"510688002","text":"import win32com\nimport win32com.client\n\ndef writePPT(path):\n # 通过系统进行打开\n ppt = win32com.client.Dispatch('PowerPoint.Application')\n ppt.Visiable()\n\n # 增加一个文件\n pptFile = ppt.Presentations.Add()\n\n # 创建页\n page1 = pptFile.Slides.Add(1,1)\n t1 = page1.Shapes[0].TextFrame.TextRange\n t1.Text = 'oh shit mother fucker!'\n t2 = page1.Shapes[1].TextFrame.TextRange\n t2.Text = 'Damn it'\n\n # 保存并关闭\n pptFile.SaveAs(path)\n pptFile.Cloe()\n ppt.Quit()\n\npath = r'F:\\Notes\\sublime\\Python\\file\\writePPT.ppt'\nwritePPT(path)","sub_path":"test/File/writePPT.py","file_name":"writePPT.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"168117149","text":"# -*- coding: utf-8 -*-\nimport operator\n\nimport collections\n\nfrom openerp import models, api, fields\n\n\nclass IrUiMenu(models.Model):\n _inherit = 'ir.ui.menu'\n\n is_role_use = fields.Boolean('Is Role Use', default=True)\n\n def get_all_menu_chilldren(self):\n self.env.cr.execute('''\n SELECT id, parent_id FROM ir_ui_menu where parent_id IS NOT NULL AND is_role_use;\n ''')\n\n menu_child_ids = {}\n for menu_id, parent_menu_id in self.env.cr.fetchall():\n menu_child_ids.setdefault(parent_menu_id, []).append(menu_id)\n\n menu_all_parent_map = collections.defaultdict(list)\n for menu_id in menu_child_ids.iterkeys():\n self.recurive_all_child_menu(menu_child_ids, menu_id, menu_all_parent_map[menu_id])\n\n return menu_all_parent_map\n\n def recurive_all_child_menu(self, menu_maps, menu_id, collect_list):\n if menu_id not in menu_maps:\n collect_list.append(menu_id)\n else:\n for child_id in menu_maps[menu_id]:\n self.recurive_all_child_menu(menu_maps, child_id, collect_list)\n\n @api.model\n def fetch_sub_tree_menu(self, parent_id=None, parent_where_str=None, partsel_where_str=None):\n if parent_id:\n where_str = 'menu.parent_id = {}'.format(parent_id)\n else:\n where_str = '''\n menu.id IN (\n SELECT ir_ui_menu_id FROM create_group_ir_ui_menu_rel WHERE create_group_id IN (\n SELECT res_id FROM ir_model_data WHERE name = 'create_group_all' and module = 'eroad_role'\n )\n )\n '''\n\n if not partsel_where_str:\n partsel_where_str = ' menu.is_role_use '\n\n self.env.cr.execute('''\n SELECT menu.id AS key,\n COALESCE(translation.name, menu.name) AS title,\n parent_menu.id IS NOT NULL AS lazy,\n menu.is_role_use AS selected,\n partsel_menu.id IS NOT NULL AS partsel\n FROM ir_ui_menu menu\n LEFT JOIN (\n SELECT value AS name, res_id FROM ir_translation WHERE name = 'ir.ui.menu,name' and lang='{}'\n ) translation ON menu.id = translation.res_id\n LEFT JOIN (\n -- 这里用来计算选中的菜单是否可以展开,从 菜单权限 开始向上寻找parent_id,凡是存在值的菜单都是可以展开的\n -- 当使用在用户角色的时候,需要再加一层是否在用户角色配置中勾选过\n WITH RECURSIVE parent_menu AS (\n SELECT menu.parent_id FROM eroad_menu_access access\n INNER JOIN ir_ui_menu menu ON access.menu_id = menu.id\n {}\n UNION DISTINCT \n SELECT parent.parent_id FROM ir_ui_menu parent, parent_menu\n WHERE parent_menu.parent_id = parent.id\n )\n SELECT DISTINCT parent_id AS id FROM parent_menu\n ) parent_menu ON menu.id = parent_menu.id\n LEFT JOIN (\n -- 这里用来计算是否被部分选择过了,从一个菜单本身是看不出来这个菜单的子菜单是否被选择过来,所以需要从 菜单权限 出发\n -- 找到的所有菜单上级都默认被部分选择过了,用户角色里面需要加一层已经选择过的菜单权限\n WITH RECURSIVE partsel_menu AS (\n SELECT access.menu_id AS id, menu.parent_id FROM eroad_menu_access access\n INNER JOIN ir_ui_menu menu ON access.menu_id = menu.id\n WHERE {}\n UNION DISTINCT\n SELECT parent.id, parent.parent_id FROM ir_ui_menu parent, partsel_menu\n WHERE partsel_menu.parent_id = parent.id\n )\n \n SELECT id FROM partsel_menu\n ) partsel_menu ON menu.id = partsel_menu.id\n \n LEFT JOIN (\n -- 这里找到所有菜单权限里面的菜单,一个子菜单必须除于菜单权限里面才能被显示\n SELECT DISTINCT menu_id FROM eroad_menu_access\n ) access_menu ON menu.id = access_menu.menu_id\n\n WHERE {} AND (parent_menu.id IS NOT NULL OR (menu.action IS NOT NULL AND access_menu.menu_id IS NOT NULL))\n ORDER BY menu.sequence, menu.id\n '''.format(self.env.context.get('lang', 'zh_CN'), parent_where_str or '', partsel_where_str, where_str))\n\n return self.env.cr.dictfetchall()\n\n @api.model\n def save_sub_tree_menu(self, values):\n single_unselected_ids, batch_unselected_ids, batch_selected_ids = [], [], []\n\n for value in values:\n if value['type'] == 'single':\n single_unselected_ids.append(value['key'])\n elif value['type'] == 'batch' and value.get('selected'):\n batch_selected_ids.append(value['key'])\n else:\n batch_unselected_ids.append(value['key'])\n\n sql_text = '''\n WITH RECURSIVE menu AS (\n SELECT id FROM ir_ui_menu WHERE id IN %s\n UNION ALL\n SELECT child.id FROM ir_ui_menu child, menu WHERE child.parent_id = menu.id\n )\n \n UPDATE ir_ui_menu SET is_role_use = %s WHERE id IN (\n SELECT id FROM menu\n ) RETURNING id\n '''\n\n if single_unselected_ids:\n self.env.cr.execute('''\n UPDATE ir_ui_menu SET is_role_use = False WHERE id IN %s\n ''', (tuple(single_unselected_ids), ))\n\n if batch_unselected_ids:\n self.env.cr.execute(sql_text, (tuple(batch_unselected_ids), False))\n unselected_ids = map(operator.itemgetter(0), self.env.cr.fetchall())\n\n if unselected_ids:\n self.env.cr.execute('''\n SELECT list.role_id, list.id FROM eroad_menu_access_list list\n INNER JOIN eroad_menu_access access ON list.menu_access_id = access.id\n \n WHERE list.role_id IS NOT NULL AND access.menu_id IN %s\n ''', (tuple(unselected_ids), ))\n\n write_dict = collections.defaultdict(list)\n for role_id, list_id in self.env.cr.fetchall():\n write_dict[role_id].append([2, list_id, {}])\n\n for role_id, values in write_dict.iteritems():\n self.env['eroad.role'].browse(role_id).write({\n 'menu_list_ids': values\n })\n\n if batch_selected_ids:\n self.env.cr.execute(sql_text, (tuple(batch_selected_ids), True))\n\n return True\n","sub_path":"eroad_role/ir_ui_menu.py","file_name":"ir_ui_menu.py","file_ext":"py","file_size_in_byte":6822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"535934604","text":"import click\nimport glob\nimport os\nfrom PIL import Image\n\n@click.command()\n@click.option(\n '--max-px-size',\n default=2560,\n help='The max height / width of image in pixels.'\n)\n@click.option(\n '--images-folder',\n default='images',\n help='Name of folder containing images.'\n)\ndef main(max_px_size, images_folder):\n imgs = []\n imgs += sorted(glob.glob(os.path.join(images_folder, '*.jpg')))\n imgs += sorted(glob.glob(os.path.join(images_folder, '*.jpeg')))\n print('Image files to resize:')\n print('\\n'.join(imgs))\n output_folder = '{}-{}px'.format(images_folder, max_px_size)\n if not os.path.exists(output_folder):\n os.makedirs(output_folder)\n for img_path in imgs:\n try:\n resize(img_path, max_px_size, output_folder)\n except Exception as e:\n with open('error.txt', 'w') as f:\n f.write(str(e))\n\ndef resize(img_path, max_px_size, output_folder):\n with Image.open(img_path) as img:\n width_0, height_0 = img.size\n out_f_name = os.path.split(img_path)[-1]\n out_f_path = os.path.join(output_folder, out_f_name)\n\n if max((width_0, height_0)) <= max_px_size:\n print('writing {} to disk (no change from original)'.format(out_f_path))\n img.save(out_f_path)\n return\n\n if width_0 > height_0:\n wpercent = max_px_size / float(width_0)\n hsize = int(float(height_0) * float(wpercent))\n img = img.resize((max_px_size, hsize), Image.ANTIALIAS)\n print('writing {} to disk'.format(out_f_path))\n img.save(out_f_path, quality=100)\n return\n \n if width_0 < height_0:\n hpercent = max_px_size / float(height_0)\n wsize = int(float(width_0) * float(hpercent))\n img = img.resize((wsize, max_px_size), Image.ANTIALIAS)\n print('writing {} to disk'.format(out_f_path))\n img.save(out_f_path, quality=100)\n return\n\nif __name__ == '__main__':\n main()","sub_path":"resize_images_v2.py","file_name":"resize_images_v2.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"544605121","text":"#Text Classification Improved by Integrating Bidirectional LSTM with Two-dimensional Max Pooling\nimport jieba\n#import emoji\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset, Dataset\nimport numpy as np\nimport time\nimport string\nimport pickle\nimport sys\nfrom collections import Counter\n\nis_cuda = torch.cuda.is_available()\n\ntorch.manual_seed(4325)\nnp.random.seed(4325)\n\n\njieba.set_dictionary(sys.argv[4])\njieba.enable_parallel()\n\ndef loadX():\n with open(sys.argv[1], 'r') as f:\n content = []\n for line in f:\n content.append(','.join(line.split(',')[1:])[:-1])\n content = content[1:]\n return content\n\ndef loadY():\n with open(sys.argv[2], 'r') as f:\n content = []\n for line in f:\n content.append(line.split(',')[1][:-1])\n content = content[1:]\n content = list(map(int, content))\n return content\n\nX = loadX()\nY = loadY()\n#X = [emoji.demojize(x) for x in X]\n\n\nt = time.time()\nprint('Segmentation')\n#X = [' '.join(jieba.cut(x)) for x in X]\nX = ' '.join(jieba.cut('\\n'.join(X))).split('\\n')\nX = [x.strip() for x in X]\nprint(time.time() - t)\nt = time.time()\n\nprint('Lowercasing')\nX = [x.lower() for x in X]\nprint(time.time() - t)\nt = time.time()\n\n#print('Removing punctuation')\n#punctuationEng = string.punctuation\n#punctuationHan = ',。:、;?!~…()—「」『』.‧'\n#punctuation = set(punctuationEng + punctuationHan)\n#X = [''.join([c for c in x if c not in punctuation]) for x in X]\n#print(time.time() - t)\n#t = time.time()\n\n#print('Removing digits')\n#digits = set(string.digits)\n#X = [''.join([c for c in x if c not in digits]) for x in X]\n#print(time.time() - t)\n#t = time.time()\n\nprint('Encoding words')\nwords = ' '.join(X).split()\ncount_words = Counter(words)\nprint(len(words))\nsorted_words = count_words.most_common()\nprint(len(sorted_words))\nvocab_to_int = {w:i+1 for i, (w, c) in enumerate(filter(lambda x : 3 <= x[1] <= 10000, sorted_words))}\nprint(len(vocab_to_int))\nprint(max(vocab_to_int.values()))\nX = [[vocab_to_int[w] for w in x.split() if w in vocab_to_int] for x in X]\nwith open('2v.pkl', 'wb') as f:\n pickle.dump(vocab_to_int, f)\nprint(time.time() - t)\nt = time.time()\n\nX_lengths = [len(x) for x in X]\nX = [X[i] for i, l in enumerate(X_lengths) if l > 0]\nY = [Y[i] for i, l in enumerate(X_lengths) if l > 0]\n\nseq_len = 70\n\nX = [x[:seq_len] for x in X]\nX = [np.array(x) for x in X]\nY = np.array(Y)\n\ndef padding(X):\n X_lengths = [len(x) for x in X]\n padded_X = np.zeros((len(X), seq_len))\n for i, x_len in enumerate(X_lengths):\n padded_X[i, 0:x_len] = X[i]\n return padded_X, X_lengths\nX, X_lengths = padding(X)\n\nsplit_frac = 0.8\nrandomIndices = np.random.shuffle(np.arange(X.shape[0]))\nprint(X.shape)\nX = X[randomIndices][0]\nY = Y[randomIndices][0]\ntrain_x = X[0:int(split_frac*len(X))]\ntrain_y = Y[0:int(split_frac*len(X))]\nvalid_x = X[int(split_frac*len(X)):]\nvalid_y = Y[int(split_frac*len(X)):]\n\ntrain_data = TensorDataset(torch.from_numpy(train_x), torch.from_numpy(train_y))\nvalid_data = TensorDataset(torch.from_numpy(valid_x), torch.from_numpy(valid_y))\n\nbatch_size = 10\n\ntrain_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size, num_workers=4)\nvalid_loader = DataLoader(valid_data, shuffle=True, batch_size=batch_size, num_workers=4)\n\nclass RNN(nn.Module):\n def __init__(self, vocab_size, seq_len, embedding_dim, hidden_dim, n_layers):\n super().__init__()\n self.n_layers = n_layers\n self.hidden_dim = hidden_dim\n\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.dropout1 = nn.Dropout(0.5)\n\n self.gru = nn.GRU(embedding_dim, hidden_dim, n_layers, dropout=0.5, batch_first=True, bidirectional=True)\n self.dropout2 = nn.Dropout(0.5)\n\n self.fc = nn.Linear(2 * n_layers * hidden_dim, 1)\n\n self.sig = nn.Sigmoid()\n\n self.hidden = nn.Parameter(torch.randn(self.n_layers * 2, 1, self.hidden_dim))\n\n def forward(self, x):\n batch_size = x.size(0)\n\n x = self.embedding(x)\n x = self.dropout1(x)\n # x = (batch, seq_len, input_size)\n x, h = self.gru(x, self.hidden.repeat(1, batch_size, 1))\n x = self.dropout2(x)\n # x = (batch, seq_len, 2 * hidden_size)\n # h = (num_layer * 2, batch, hidden_size)\n\n # h = (num_layer * 2, batch, hidden_size)\n # h = (num_layer * 2, batch, hidden_size)\n h = torch.transpose(h, 0, 1)\n h = h.contiguous()\n # h = (batch, num_layer * 2, hidden_size)\n h = h.view(batch_size, -1)\n # h = (batch, num_layer * 2 * hidden_size)\n h = self.fc(h)\n # x = (batch, 1)\n h = self.sig(h)\n return h\n\nvocab_size = len(vocab_to_int)+1\nembedding_dim = 300\nhidden_dim = 64\n# 75.2 when = 64\n# 64, embedding=300: 75.5\n# 300, embedding=300: ~74\n# 64, 300, seqlen=50: 75.79\nn_layers = 2\nnet = RNN(vocab_size, seq_len, embedding_dim, hidden_dim, n_layers)\n\nprint(net)\nprint('Parameters:', sum(p.numel() for p in net.parameters()))\nprint('Trainable Parameters:', sum(p.numel() for p in net.parameters() if p.requires_grad))\n\nlr = 0.001\ncriterion = nn.BCELoss()\noptimizer = torch.optim.Adam(net.parameters(), lr=lr, weight_decay=1e-5)\n\nepochs = 10\n\ncounter = 0\nprint_every = 1000\nclip = 5\n\nif is_cuda:\n net = net.cuda()\n\nnet.train()\n\nbestAcc = 0.0\n\nt = time.time()\nfor epoch in range(epochs):\n for inputs, labels in train_loader:\n counter += 1\n print(counter, end='\\r')\n inputs = inputs.type(torch.LongTensor)\n if is_cuda:\n inputs, labels = inputs.cuda(), labels.cuda()\n net.zero_grad()\n output = net(inputs)\n loss = criterion(output.squeeze(), labels.float())\n loss.backward()\n nn.utils.clip_grad_norm_(net.parameters(), clip)\n optimizer.step()\n\n if counter % print_every == 0:\n val_losses = []\n net.eval()\n correct = 0\n total = 0\n for inputs, labels in valid_loader:\n inputs = inputs.type(torch.LongTensor)\n if is_cuda:\n inputs, labels = inputs.cuda(), labels.cuda()\n output = net(inputs)\n val_loss = criterion(output.squeeze(), labels.float())\n val_losses.append(val_loss.item())\n total += labels.size(0)\n y_pred = output.squeeze() >= 0.5\n correct += (y_pred == labels.byte()).sum().item()\n net.train()\n valAcc = 100 * correct / total\n print(\"Epoch: {}/{}...\".format(epoch+1, epochs),\n \"Step: {}...\".format(counter),\n \"Loss: {:.6f}...\".format(loss.item()),\n \"Val Loss: {:.6f}\".format(np.mean(val_losses)),\n \"Accuracy: {:.6f}\".format(valAcc),\n \"Time: {}\".format(time.time() - t))\n if valAcc > bestAcc:\n weightName = '2.pkl'\n print(\"Find Better Model, Saving the model as \" + weightName)\n bestAcc = valAcc\n torch.save(net.state_dict(), weightName)\n t = time.time()\n","sub_path":"hw6/train2.py","file_name":"train2.py","file_ext":"py","file_size_in_byte":7225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"161761290","text":"'''\nCode Words\nDescription\nInternational Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: \"a\" maps to \".-\", \"b\" maps to \"-...\", \"c\" maps to \"-.-.\", and so on.\n\nFor convenience, the full table for the 26 letters of the English alphabet is given below:\n\n[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\nNow, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, \"cab\" can be written as \"-.-..--...\", (which is the concatenation \"-.-.\" + \".-\" + \"-...\"). We'll call such a concatenation, the transformation of a word.\n\nReturn the number of different transformations among all words we have.\n\nInput format\nFirst line contains a positive integer n, denoting the number of test cases. It is followed by n lines. Each of the n lines contains space separated words.\n\nOutput format\nn lines containing the number of different transformations among all words we have.\n\nSample input\n1\ngin zen gig msg\nSample output\n2\nExplanation\nThe transformation of each word is:\n\n\"gin\" -> \"--...-.\"\n\n\"zen\" -> \"--...-.\"\n\n\"gig\" -> \"--...--.\"\n\n\"msg\" -> \"--...--.\"\n\nThere are 2 different transformations, \"--...-.\" and \"--...--.\".\n\nNote\nThe length of words will be at most 100000\n\nEach words[i] will have length in range [1, 12].\n\nwords[i] will only consist of lowercase letters.\n'''\n# your code goes here\ndef trans(s):\n\tres=\"\"\n\tresult=[]\n\tcode=[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\n\tfor i in s:\n\t if i!=\" \":\n\t res=res+str(code[ord(i)-97])\n\t else:\n\t res=res+\" \"\n\tlst=[str(i) for i in res.split()]\n\t\n\tfor i in lst:\n\t if i not in result:\n\t result.append(i)\n\treturn len(result)\n\t\n\t\t\nfor i in range(int(input())):\n\ts=input()\n\tprint(trans(s))","sub_path":"Code Words.py","file_name":"Code Words.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"254736518","text":"import pandas as pd\nimport numpy as np\n\nimport requests\nimport urllib\n\n\n\ndef census_tract_request(df, start_number, end_number, lat_name, lon_name, directory, saving_rate):\n for i in range(start_number, end_number):\n try:\n params = urllib.parse.urlencode({'latitude': df.loc[i, lat_name], 'longitude':df.loc[i, lon_name], 'format':'json'})\n url = 'https://geo.fcc.gov/api/census/block/find?' + params\n response = requests.get(url)\n b = response.json()\n df.loc[i,'census_tract'] =b['Block']['FIPS']\n if (i % 100 == 0):\n print(i)\n if (i % saving_rate ==0):\n df.to_csv('%s/data.csv' % (directory))\n except:\n pass\n return df.to_csv('%s/data.csv' % (directory))\n\ndata = pd.read_csv('/Users/aassamidanov/Downloads/crime_lexisnexis_need_census_tract.csv') # enter your own directory\nend_point = len(data)\n\ncensus_tract_request(data, 0, end_point, 'lat', 'lon', '/Users/aassamidanov/Downloads', 10000) # enter your own directory\n","sub_path":"census_tract_api.py","file_name":"census_tract_api.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"579487396","text":"import argparse\r\nimport numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nimport os\r\nimport json\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--k', type=float, default=1.414, help=\"\")\r\nparser.add_argument('--filter_size', type=int, default=8, help=\"\")\r\nparser.add_argument('--sigma', type=float, default=1, help=\"\")\r\nparser.add_argument('--threshold', type=float, default=0.5, help=\"\")\r\nparser.add_argument('--num_scales', type=int, default=8, help=\"\")\r\nparser.add_argument('--img_size', type=int, default=128, help=\"\")\r\nparser.add_argument('--overlapping_threshold', type=int, default=0.5, help=\"\")\r\n\r\nFLAGS = parser.parse_args()\r\n\r\ndef laplacian_of_gaussian(sigma):\r\n\tfilter_size = (int)(sigma*5)\r\n\tarray = np.zeros((filter_size, filter_size))\r\n\tpatchx = np.arange((-filter_size+1)/2, (filter_size+1)/2)\r\n\tfor row in range(len(patchx)):\r\n\t\tfor column in range(len(patchx)):\r\n\t\t\tx_inp = row\r\n\t\t\ty_inp = column\r\n\t\t\tconstant = 1. / (2*np.pi*(np.power(sigma, 4)))\r\n\t\t\tp = (x_inp*x_inp + y_inp*y_inp)/(2*sigma**2)\r\n\t\t\tlog = constant*(x_inp*x_inp + y_inp*y_inp -2*sigma*sigma)*np.exp(-p)\r\n\t\t\tarray[row][column] = log\r\n\treturn array\r\n\r\ndef conv_image_log(image):\r\n\t# use multiple sigma for different scale-normalized filters\r\n\tconvolved_images = np.zeros((FLAGS.num_scales, FLAGS.img_size, FLAGS.img_size))\r\n\tsigma1 = FLAGS.sigma\r\n\t\r\n\tfor i in range(0, FLAGS.num_scales):\r\n\t\tsigma = sigma1 * (FLAGS.k+i)\r\n\t\tlog_filter = laplacian_of_gaussian(sigma)\r\n\t\timg = cv2.filter2D(image,-1, log_filter)\r\n\t\timg = np.square(img)\r\n\t\tconvolved_images[i, :, :] = img\r\n\treturn convolved_images\r\n\r\ndef non_max_suppression(log_convolved):\r\n\th, w = FLAGS.img_size, FLAGS.img_size\r\n\t\r\n\tkey_extrema_points = []\r\n\tfor scale in range(1, FLAGS.num_scales-1):\r\n\t\tcurr_img = log_convolved[scale, :, :]\r\n\t\ttop_img = log_convolved[scale-1, :, :]\r\n\t\tbottom_img = log_convolved[scale+1, :, :]\r\n\t\tneighbouring_positions = [[-1, 0], [1, 0], [-1, -1], [0, -1], [-1, 1], [1, -1], [1, 0], [1, 1]]\r\n\t\tneighbours = []\r\n\t\t\r\n\t\tfor row in range(1, h-1):\r\n\t\t\tfor column in range(1, w-1):\r\n\t\t\t\tneighbours = []\r\n\t\t\t\t\r\n\t\t\t\t# neighbours in same plane\r\n\t\t\t\tfor n in neighbouring_positions:\r\n\t\t\t\t\tpos_x, pos_y = row+n[0], column+n[1]\r\n\t\t\t\t\tneighbours.append(curr_img[pos_x][pos_y])\r\n\t\t\t\t\r\n\t\t\t\t# neighbous in plane above\r\n\t\t\t\tfor n in neighbouring_positions:\r\n\t\t\t\t\tpos_x, pos_y = row+n[0], column+n[1] \r\n\t\t\t\t\tneighbours.append(top_img[pos_x][pos_y])\r\n\t\t\t\tneighbours.append(top_img[pos_x][pos_y])\r\n\t\t\t\t\r\n\t\t\t\t# neighbous in plane below\r\n\t\t\t\tfor n in neighbouring_positions:\r\n\t\t\t\t\tpos_x, pos_y = row+n[0], column+n[1] \r\n\t\t\t\t\tneighbours.append(bottom_img[pos_x][pos_y])\r\n\t\t\t\tneighbours.append(bottom_img[pos_x][pos_y])\r\n\t\t\t\t\r\n\t\t\t\tif(curr_img[row][column]>max(neighbours)):\r\n\t\t\t\t\tif(curr_img[row][column]>=0.03): # removing low-contrast keypoints\r\n\t\t\t\t\t\tif([scale, row, column] not in key_extrema_points):\r\n\t\t\t\t\t\t\tkey_extrema_points.append([scale, row, column])\r\n\treturn key_extrema_points\r\n\r\ndef remove_overlapping_blobs(key_points):\r\n\t\r\n\t#print('Before overleap removal: ', len(key_points))\r\n\tk_scale = FLAGS.k\r\n\t\r\n\tcount = 0\r\n\tfor i in key_points:\r\n\t\t\r\n\t\ts1, x1, y1 = i[0], i[1], i[2]\r\n\t\tr1 = s1 * k_scale\r\n\r\n\t\tfor j in key_points:\r\n\t\t\tif(i!=j and i[0]!=0 and j[0]!=0):\r\n\t\t\t\t\r\n\t\t\t\ts2, x2, y2 = j[0], j[1], j[2]\r\n\t\t\t\tr2 = s2 * k_scale\r\n\r\n\t\t\t\td = math.sqrt((x2-x1)**2 + (y2-y1)**2)\r\n\r\n\t\t\t\tif(d <= abs(r2 - r1)): \t\t# one inside the other\r\n\t\t\t\t\tif(s1>s2):\r\n\t\t\t\t\t\tj[0] = 0\r\n\t\t\t\t\t\tcount += 1\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\ti[0] = 0\r\n\t\t\t\t\t\tcount += 1\r\n\t\t\t\telif(dabs(r2-r1)):\r\n\t\t\t\t\toverlap_r1, overlap_r2 = (r1*r1 - r2*r2 + d*d) / (2 * r1 * d), (r2*r2 - r1*r1 + d*d) / (2 * r2 * d)\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(overlap_r1>=1):\r\n\t\t\t\t\t\toverlap_r1 = 1\r\n\t\t\t\t\telif(overlap_r1<=-1):\r\n\t\t\t\t\t\toverlap_r1 = 1\r\n\r\n\t\t\t\t\tif(overlap_r2>=1):\r\n\t\t\t\t\t\toverlap_r2 = 1\r\n\t\t\t\t\telif(overlap_r2<=-1):\r\n\t\t\t\t\t\toverlap_r2 = -1\r\n\t\t\t\t\t\r\n\t\t\t\t\toverlap_r1 = math.acos(overlap_r1)\r\n\t\t\t\t\toverlap_r2 = math.acos(overlap_r2)\r\n\r\n\t\t\t\t\t\r\n\t\t\t\t\tq1, q2, q3, q4 = r1+r2-d, -r2+r1+d, -r1+r2+d, r1+r2+d\r\n\t\t\t\t\t\r\n\t\t\t\t\toverlap_region = (np.power(r1, 2) * overlap_r1) + (np.power(r2, 2) * overlap_r2) - (np.power(abs(q1*q2*q3*q4), 0.5))/2.0\r\n\t\t\t\t\toverlap_region /= (math.pi * (min(r1, r2) ** 2))\r\n\r\n\t\t\t\t\tif(overlap_region > FLAGS.overlapping_threshold):\r\n\t\t\t\t\t\tif(s1>s2):\r\n\t\t\t\t\t\t\tj[0] = 0\r\n\t\t\t\t\t\t\tcount += 1\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\ti[0] = 0\r\n\t\t\t\t\t\t\tcount += 1\r\n\t\t\t\t\t\r\n\trefined_blobs = []\r\n\tfor x in key_points:\r\n\t\tif(x[0] > 0):\r\n\t\t\trefined_blobs.append(x)\r\n\treturn refined_blobs\r\n\r\nif __name__ == '__main__':\r\n\tpath = '../images/'\r\n\tdir_list = os.listdir(path)\r\n\tcount = 0\r\n\r\n\tjson_dict = {}\r\n\r\n\tfor i in dir_list:\r\n\t\timg_path = os.path.join(path, i)\r\n\t\ti_name = i.split('.')[0]\r\n\r\n\t\timg = cv2.imread(img_path)\r\n\t\timg_color = cv2.resize(img, (FLAGS.img_size, FLAGS.img_size))\r\n\t\timg = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY)\r\n\t\tconvolved_images = conv_image_log(img)\r\n\t\tkey_points = non_max_suppression(convolved_images)\r\n\t\tkey_points_refined = remove_overlapping_blobs(key_points)\r\n\t\t\r\n\t\tjson_dict[i_name] = key_points_refined\r\n\r\n\t\t# fig, ax = plt.subplots()\r\n\t\t# nh,nw = FLAGS.img_size, FLAGS.img_size\r\n\r\n\t\t#################################################################################\r\n\t\t# ax.imshow(img_color, interpolation='nearest', cmap=\"gray\")\r\n\t\t# for blob in key_points_refined:\r\n\t\t# \tsigma, x, y = blob\r\n\t\t# \tc = plt.Circle((y, x), sigma , color='red', linewidth=1.5, fill=False)\r\n\t\t# \tax.add_patch(c)\r\n\t\t# ax.plot() \r\n\t\t# plt.savefig('./blob_detection_images/'+(str)(count)+'.png')\r\n\t\t# plt.close()\r\n\t\t#################################################################################\r\n\r\n\t\tcount += 1\r\n\t\tprint(count)\r\n\t\r\n\twith open('./scale_invariant_log_keypoints.json', 'w') as f:\r\n\t\tjson.dump(json_dict, f)","sub_path":"HW1_Image_Retrieval/src/question1_2.py","file_name":"question1_2.py","file_ext":"py","file_size_in_byte":5737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"205364359","text":"from typing import Mapping\nimport typing\nimport discord\nimport platform\nimport time\nimport random\nimport asyncio\nimport re, os\nfrom datetime import datetime\nfrom discord.ext import commands\nfrom discord.ext.commands.cooldowns import BucketType\nfrom discord.ext.commands import CheckFailure, check\nimport aiosqlite\nimport inspect\nOWNER_ID = 267410788996743168\n# CREDIT TO KAL CREDIT TO KAL CREDIT TO KAL CREDIT TO KAL CREDIT TO KAL CREDIT TO KAL CREDIT TO KAL CREDIT TO KAL CREDIT TO KAL CREDIT TO KAL\n# oh and also credit to kal\n\nclass HelpCommand(commands.HelpCommand):\n \"\"\"Sup averwhy hopefully this is all easy to understand.\"\"\"\n\n # This fires once someone does `help`\n async def send_bot_help(self, mapping: Mapping[typing.Optional[commands.Cog], typing.List[commands.Command]]):\n ctx = self.context\n clr = await ctx.bot.get_player_color(ctx.author)\n if clr is None:\n clr = discord.Color.sea_green()\n embed = discord.Embed(title=\"EconomyX Bot Help\", color=clr)\n embed.set_footer(text=f\"Do {self.clean_prefix}help [command]\")\n categories = []\n for cog, cmds in mapping.items():\n filtered = await self.filter_commands(cmds, sort=True)\n if filtered:\n all_commands = \" \".join(f\"`{c.name}`\" for c in cmds)\n if cog and cog.description:\n embed.add_field(name=cog.qualified_name,\n value=f\"-> {all_commands}\",\n inline=False)\n\n await ctx.send(embed=embed)\n\n # This fires once someone does `help `\n async def send_cog_help(self, cog: commands.Cog):\n ctx = self.context\n embed = discord.Embed(title=f\"Help for {cog.qualified_name}\")\n embed.set_footer(text=f\"Do {self.clean_prefix}help [command] for more help\")\n\n entries = await self.filter_commands(cog.get_commands(), sort=True)\n for cmd in entries:\n embed.add_field(name=f\"{self.clean_prefix}{cmd.name} {cmd.signature}\",\n value=f\"{cmd.help}\",\n inline=False)\n\n await ctx.send(embed=embed)\n\n # This fires once someone does `help `\n async def send_command_help(self, command: commands.Command):\n ctx = self.context\n\n embed = discord.Embed(title=f\"{self.clean_prefix}{command.qualified_name} {command.signature}\",\n description=f\"{command.help}\")\n embed.set_footer(text=f\"Do {self.clean_prefix}help [command] for more help\")\n\n await ctx.send(embed=embed)\n\n # This fires once someone does `help `\n async def send_group_help(self, group: commands.Group):\n ctx = self.context\n\n embed = discord.Embed(title=f\"{self.clean_prefix}{group.qualified_name} {group.signature}\",\n description=group.help)\n embed.set_footer(text=f\"Do {self.clean_prefix}help [command] for more help\")\n\n for command in group.commands:\n embed.add_field(name=f\"{self.clean_prefix}{command.name} {command.signature}\",\n value=command.description,\n inline=False)\n\n await ctx.send(embed=embed)\n\n\nclass misc(commands.Cog):\n \"\"\"\n These are miscellaneous bot commands, primarily meta about the bot.\n \"\"\"\n def __init__(self,bot):\n self.bot = bot\n\n self.bot._original_help_command = bot.help_command\n\n bot.help_command = HelpCommand()\n bot.help_command.cog = self\n \n def cog_unload(self):\n self.bot.help_command = self.bot._original_help_command\n \n @commands.cooldown(1,10,BucketType.channel)\n @commands.command(aliases=[\"i\"])\n async def info(self,ctx):\n data2 = await self.bot.get_player(ctx.author.id)\n if data2 is None:\n color = discord.Color.teal()\n else:\n color = int((\"0x\"+data2[5]),0)\n c = await self.bot.db.execute(\"SELECT SUM(bal) FROM e_users\")\n money_total = await c.fetchone()\n c = await self.bot.db.execute(\"SELECT COUNT(id) FROM e_users\")\n total_db_users = await c.fetchone()\n desc = f\"\"\"__**Developed by averwhy#3899**__\n **Guilds:** {len(self.bot.guilds)}\n **Total Users:** {len(self.bot.users)}\n **Current Money Total:** ${money_total[0]}\n **Number of users in database:** {total_db_users[0]}\n **Database changes in this session:** {self.bot.db.total_changes}\n \"\"\"\n embed = discord.Embed(title=\"EconomyX Info\",description=desc,color=color)\n embed.set_footer(text=f\"Made with Python {platform.python_version()}, enchanced discord.py {discord.__version__}, and aiosqlite {aiosqlite.__version__}\",icon_url=\"https://images-ext-1.discordapp.net/external/0KeQjRAKFJfVMXhBKPc4RBRNxlQSiieQtbSxuPuyfJg/http/i.imgur.com/5BFecvA.png\")\n embed.set_thumbnail(url=\"https://media.discordapp.net/attachments/460568954968997890/761037965987807232/dpycogs.png\")\n await ctx.send(embed=embed)\n \n @commands.cooldown(1,5,BucketType.user)\n @commands.command()\n async def invite(self,ctx):\n data2 = await self.bot.get_player(ctx.author.id)\n if data2 is None:\n color = discord.Color.teal()\n else:\n color = int((\"0x\"+data2[5]),0)\n await ctx.send(embed=discord.Embed(title=\"EconomyX Bot Invite\",description=\"\",url=\"https://discord.com/api/oauth2/authorize?client_id=780480654277476352&permissions=264192&scope=bot\",color=color))\n \n @commands.cooldown(1,10,BucketType.user)\n @commands.command()\n async def uptime(self, ctx):\n delta_uptime = datetime.utcnow() - self.bot.launch_time\n hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)\n minutes, seconds = divmod(remainder, 60)\n days, hours = divmod(hours, 24)\n await ctx.send(f\"```autohotkey\\n{days}d, {hours}h, {minutes}m, {seconds}s\\n```\")\n\n \n # CREDIT TO RAPPTZ FOR THIS\n # https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/meta.py#L355-L393\n @commands.command()\n async def source(self, ctx, *, command: str = None):\n source_url = 'https://github.com/averwhy/EconomyX'\n branch = 'main/src'\n if command is None:\n return await ctx.send(source_url)\n \n if command == 'help':\n await ctx.send(\"The help command is built into discord.py. However, the code for that can be found here:\\n\")\n return\n if command == 'jsk' or command == 'jishaku':\n await ctx.send(\"Jishaku is a debug and testing command made for discord.py. The code can be found here:\\n\")\n return\n else:\n obj = self.bot.get_command(command.replace('.', ' '))\n if obj is None:\n return await ctx.send('Could not find command.')\n\n # since we found the command we're looking for, presumably anyway, let's\n # try to access the code itself\n src = obj.callback.__code__\n module = obj.callback.__module__\n filename = src.co_filename\n\n lines, firstlineno = inspect.getsourcelines(src)\n if not module.startswith('discord'):\n # not a built-in command\n location = os.path.relpath(filename).replace('\\\\', '/')\n else:\n location = module.replace('.', '/') + '.py'\n\n final_url = f'<{source_url}/blob/{branch}/{location}#L{firstlineno}-L{firstlineno + len(lines) - 1}>'\n await ctx.send(final_url)\n\n \n\n \ndef setup(bot):\n bot.add_cog(misc(bot))\n","sub_path":"src/cogs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":7757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"9906197","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\nfrom sklearn.preprocessing import MinMaxScaler\n\ndef writeData2File(X, Y, Z, fileName):\n df1 = DataFrame(X)\n df2 = DataFrame(Y)\n df3 = DataFrame(Z) \n data = pd.concat([df1, df2, df3], axis=1, ignore_index=True) #连接两个数据框\n data.to_csv(fileName, header=False, index=False)\n\ndef processing():\n fileNameList = ['hidden_gaussian, gamma=0.0625_329_0.756756756757', 'hidden_poly_spline, gamma=1_177_0.774774774775', 'hidden_multiquadric, gamma=0.0625_794_0.765765765766', \n 'hidden_gaussian, gamma=0.125_51_0.72972972973', 'hidden_poly_spline, gamma=2_922_0.792792792793', 'hidden_multiquadric, gamma=0.125_300_0.774774774775', \n 'hidden_gaussian, gamma=0.25_576_0.720720720721', 'hidden_poly_spline, gamma=4_899_0.774774774775', 'hidden_multiquadric, gamma=0.25_149_0.801801801802', \n 'hidden_gaussian, gamma=0.5_540_0.702702702703', 'hidden_poly_spline, gamma=8_120_0.783783783784', 'hidden_multiquadric, gamma=0.5_283_0.783783783784', \n 'hidden_gaussian, gamma=1_864_0.711711711712', 'hidden_poly_spline, gamma=16_153_0.765765765766', 'hidden_multiquadric, gamma=1_850_0.765765765766', \n 'hidden_gaussian, gamma=4_281_0.702702702703', 'hidden_poly_spline, gamma=32_328_0.720720720721', 'hidden_multiquadric, gamma=4_280_0.774774774775', \n 'hidden_gaussian, gamma=8_33_0.711711711712', 'hidden_poly_spline, gamma=64_77_0.711711711712', 'hidden_multiquadric, gamma=8_945_0.792792792793', \n 'hidden_gaussian, gamma=16_41_0.702702702703', 'hidden_poly_spline, gamma=128_613_0.747747747748', 'hidden_multiquadric, gamma=16_151_0.774774774775']\n\n for k in range(len(fileNameList)):\n pathName = \"/home/xw/workspace/result_File/data/hidden_activation/hidde_activation_gamma/\" + fileNameList[k] + \".csv\"\n df = pd.read_csv(pathName, header=None, index_col=None)\n df1 = df[0:1] #第一行\n df1000 = df[998:999] #最后一行\n while len(df)>200: # df小于200行\n df = df[df[1]>=df[1].mean()]\n data = pd.concat([df1, df, df1000], axis=0, ignore_index=True) #连接两个数据框\n \n data.to_csv(\"/home/xw/workspace/result_File/data/hidden_activation/hidde_activation_gamma/processing2/\" + fileNameList[k] + \".csv\", header=False, index=False)\n\ndef Normalization():\n pathName = \"/home/xw/workspace/result_File/Entropy_file/RF_feature/name_importance_0.108499095841.csv\"\n df = pd.read_csv(pathName, header=None, index_col=None)\n minmax = MinMaxScaler()\n ranks = minmax.fit_transform(df[1])\n std = minmax.fit_transform(df[2])\n return df[0], ranks, std\n\n\ndef main():\n processing()\n # names, ranks, std = Normalization()\n # writeData2File(names, ranks, std, \"/home/xw/workspace/result_File/data/hidden_activation/hidde_activation_gamma/feature_importance/name_importance_std_normalization_0.309222423146.csv\")\n\nif __name__ == '__main__':\n main()","sub_path":".history/pySpace/Paper/age/PSEntropy/En_data_processing_20171004202324.py","file_name":"En_data_processing_20171004202324.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"542438908","text":"import httplib2\nimport os\n\nimport time\nimport json\nimport requests\n\nfrom apiclient import discovery\nimport oauth2client\nfrom oauth2client import client\nfrom oauth2client import tools\n\ntry:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/sheets.googleapis.com-python-quickstart.json\nSCOPES = 'https://www.googleapis.com/auth/spreadsheets'\nCLIENT_SECRET_FILE = 'client_secret2.json'\nAPPLICATION_NAME = 'Google Sheets API Python Quickstart'\n\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'sheets.googleapis.com-python-quickstart.json')\n\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials\n\ndef main():\n \"\"\"Shows basic usage of the Sheets API.\n\n Creates a Sheets API service object and prints the names and majors of\n students in a sample spreadsheet:\n https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit\n \"\"\"\n start_program = time.clock()\n credentials = get_credentials()\n http = credentials.authorize(httplib2.Http())\n discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'\n 'version=v4')\n service = discovery.build('sheets', 'v4', http=http,\n discoveryServiceUrl=discoveryUrl)\n with open(\"sheets.json\") as sheets_file:\n sheet_data = json.loads(sheets_file.read())\n print(sheet_data)\n with open(\"shippo.json\") as shippo_file:\n shippo_data = json.loads(shippo_file.read())\n print(shippo_data)\n shippo_key = \"ShippoToken \" + shippo_data[\"api_key\"]\n print(shippo_key)\n for sheet in sheet_data:\n sheet_reference = sheet_data[sheet][0]\n spreadsheet_id = sheet_reference['sheet_id']\n print(\"SpreadsheetID: \" + str(spreadsheet_id)) # Debug line to check if the JSON is being read properly.\n range_names = sheet_reference['sheet_ranges']\n print(range_names)\n\n for sheet_range in range_names:\n start_t = time.clock() # Start clock to see how long it takes!\n result = service.spreadsheets().values().get(\n spreadsheetId=spreadsheet_id, range=sheet_range).execute() # Fetch the data from GSheets\n values = result.get('values', [])\n print(values)\n OB = values\n result = service.spreadsheets().values().get(\n spreadsheetId=spreadsheet_id, range=\"FedEx!A2:B\").execute()\n values = result.get('values', [])\n print(values)\n fedex = values\n\n result = service.spreadsheets().values().get(\n spreadsheetId=spreadsheet_id, range=\"Stamps!B2:C\").execute()\n values = result.get('values', [])\n print(values)\n stamps = values\n\n valid_fedex_tracking = []\n for id in OB:\n # print(id[0])\n for item in fedex:\n try:\n if id[0] in item[0]:\n valid_fedex_tracking.append([id[0], item[1]])\n except IndexError:\n pass\n print(valid_fedex_tracking)\n\n valid_stamps_tracking = []\n for id in OB:\n for item in stamps:\n print(item)\n try:\n if id[0] in item[0]:\n valid_stamps_tracking.append([id[0], item[1]])\n except IndexError:\n pass\n print(valid_stamps_tracking)\n\n rowcount = 0\n tracking_results = [] # Establish an empty list to append tracking statuses to.\n eta_results = []\n tracking_ids = []\n tracking_nums = []\n if not valid_fedex_tracking:\n print('No data found.')\n else:\n print(\"Took \" + str(time.clock() - start_t) + \" seconds to fetch \" + str(len(values)) + \" rows!\")\n for row in valid_fedex_tracking:\n # print(row)\n track_url = \"https://api.goshippo.com/tracks/fedex/\" + row[1]\n r = requests.get(track_url, headers={\"Authorization\": shippo_key})\n # print(r)\n r = r.json()\n # print(r)\n print(r[\"tracking_status\"][\"status\"])\n tracking_ids.append([str(row[0])])\n tracking_nums.append([str(row[1])])\n # print(tracking_ids)\n tracking_results.append([r[\"tracking_status\"][\"status\"]])\n eta_results.append([r[\"eta\"]])\n # print(tracking_results)\n rowcount += 1\n\n for row in valid_stamps_tracking:\n # print(row)\n track_url = \"https://api.goshippo.com/tracks/usps/\" + row[1]\n r = requests.get(track_url, headers={\"Authorization\": shippo_key})\n # print(r)\n r = r.json()\n # print(r)\n print(r[\"tracking_status\"][\"status\"])\n tracking_ids.append([str(row[0])])\n tracking_nums.append([str(row[1])])\n # print(tracking_ids)\n tracking_results.append([r[\"tracking_status\"][\"status\"]])\n eta_results.append([r[\"eta\"]])\n # print(tracking_results)\n rowcount += 1\n print(\"Took \" + str(time.clock() - start_t) + \" seconds to process \" + str(rowcount) + \" rows!\")\n body = {\"values\": tracking_ids}\n print(\"tracking ids \"+ str(tracking_ids))\n print(\"tracking results \" + str(tracking_results))\n print(\"body\" + str(body))\n start_t = time.clock()\n result = service.spreadsheets().values().update(spreadsheetId=spreadsheet_id, range=\"Results!A:A\",\n valueInputOption=\"USER_ENTERED\", body=body).execute()\n print(result)\n body = {\"values\": tracking_results}\n result = service.spreadsheets().values().update(spreadsheetId=spreadsheet_id, range=\"Results!B:B\",\n valueInputOption=\"USER_ENTERED\", body=body).execute()\n print(result)\n\n body = {\"values\": eta_results}\n result = service.spreadsheets().values().update(spreadsheetId=spreadsheet_id, range=\"Results!C:C\",\n valueInputOption=\"USER_ENTERED\", body=body).execute()\n print(result)\n\n body = {\"values\": tracking_nums}\n result = service.spreadsheets().values().update(spreadsheetId=spreadsheet_id, range=\"Results!D:D\",\n valueInputOption=\"USER_ENTERED\", body=body).execute()\n print(result)\n print(\"Took \" + str(time.clock() - start_t) + \" seconds to update the sheet!\")\n print(\"Took \" + str(time.clock() - start_program) + \" seconds to do all the things!\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"fedex_tracker/fedex_main.py","file_name":"fedex_main.py","file_ext":"py","file_size_in_byte":8352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"315667183","text":"#!/usr/bin/python\n#Author: Ethan Swan\n\nimport pygame\nfrom Card import Card\n\nclass Player:\n\t\"\"\"A euchre game has four players and each is represented by an object of this class\"\"\"\n\tdef __init__(self, ms = None, x = 0, y = 0):\n\t\tself.ms = ms\n\t\tself.rect = pygame.rect.Rect(x, y, 100, 100)\n\t\tself.cards = pygame.sprite.Group()\n\t\tfor i in range (0,5):\n\t\t\tnewCard = Card(player = self)\n\t\t\tnewCard.rect.move_ip(x + 70 * i, y)\n\t\t\tself.cards.add(newCard)\n","sub_path":"Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"392837990","text":"\n\n#calss header\nclass _EMBROIDER():\n\tdef __init__(self,): \n\t\tself.name = \"EMBROIDER\"\n\t\tself.definitions = [u'to decorate cloth or clothing with patterns or pictures consisting of stitches that are sewn directly onto the material: ', u'to make a story more entertaining by adding imaginary details to it: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_embroider.py","file_name":"_embroider.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"125444500","text":"\"\"\"This will be a little program to speed up risk battles and avoid \nhaving to role absurd amounts of dice\"\"\"\nimport random, sys\n\nattacker_numbers = int(input(\"Attacker: How many soldiers do you have? \")) #one cannot attack and must wait behind\ndefender_numbers = int(input(\"Defender: How many soldiers do you have? \"))\nattackerLossesTally = 0\ndefenderLossesTally = 0 #must be outide the loop I think\n\nwhile attacker_numbers and defender_numbers > 0:\n print (attacker_numbers, defender_numbers)\n\n def Attack_Dice(): \n if attacker_numbers >= 3:\n return 3 \n else:\n return attacker_numbers\n number_of_attacking_dice = Attack_Dice()\n\n def defend_dice():\n if defender_numbers >= 2:\n return 2\n #only 2 defenders allowed\n elif defender_numbers == 1:\n return 1 \n \n number_of_defending_dice = (defend_dice())\n\n def rolling_the_attacking_dice():\n attacker_dice_rolls = []\n for n in range(number_of_attacking_dice):\n dice_num_at = random.randint(1,6)\n #mimics the rolling of a regular 6 sided die\n attacker_dice_rolls.append(dice_num_at)\n return attacker_dice_rolls\n\n def rolling_the_defending_dice():\n defender_dice_rolls = []\n for n in range(number_of_defending_dice):\n dice_int_def = random.randint(1,6)\n defender_dice_rolls.append(dice_int_def)\n return defender_dice_rolls\n\n attacker_dice_rolls = rolling_the_attacking_dice()\n defening_dice_rolls = rolling_the_defending_dice()\n\n #print((\"The attacking dice roles are: \") + str(attacker_dice_rolls))\n #print((\"The defending dice roles are: \") + str(defening_dice_rolls))\n\n sorted_attacking_dice = (sorted(attacker_dice_rolls, reverse=True)) #sorts the dice so the largest value \n sorted_defending_dice = (sorted(defening_dice_rolls, reverse=True)) #is at index 0 -> allows comparison \n print (\"Attacking Dice: \" + str(sorted_attacking_dice))\n print (\"Defenders Dice: \" + str(sorted_defending_dice))\n def two_best_dies_att():\n #this is just terrible but whatever, the third attacking die doesn't matter\n #because the game simply compares the biggest rolls on each side with each other\n best = []\n if len(sorted_attacking_dice) == 3:\n for n in sorted_attacking_dice:\n best.append(n)\n del best[2]\n else:\n for i in sorted_attacking_dice:\n best.append(i)\n #if less than 3 it doesn't need trimming down\n return best\n best_att = two_best_dies_att()\n\n def The_battle():\n defender_losses = 0\n attacker_losses = 0 \n num_def = len(sorted_defending_dice) #returns the total number of soldiers \n num_att = len(sorted_attacking_dice) #in each little battle \n if len(sorted_defending_dice) == 2:\n index = 0 #gets the first value \n for roll in best_att:\n print (\"The Defender has \" + str(num_def) + \" in this battle\")\n print (\"The attacker has \" + str(num_att) + \" in this battle\")\n if roll > sorted_defending_dice[index]:\n #if the attacker has a better role they win and a defender dies\n #this compares the rolls at increasing indexes \n print (\"The attacker wins\")\n defender_losses += 1 \n index += 1\n #this only needs to happen twice (this is again terrible)\n num_def -= 1\n if index == 2:\n break\n #exits when gets to the second roll- (there must be a better way)\n elif roll <= sorted_defending_dice[index]:\n #defender wins if they draw or win\n print (\"The defender wins\")\n attacker_losses += 1 \n index += 1\n num_att -= 1\n if index == 2:\n break\n #i think this could all be simplified down quite considerably, but maybe later haha\n elif len(sorted_defending_dice) == 1:\n best_attacking_die = best_att[0]\n only_defending_die = sorted_defending_dice[0]\n print (\"The defender has 1 Pauper\")\n if best_attacking_die > only_defending_die:\n print (\"The attacker wins\")\n defender_losses += 1\n elif best_attacking_die <= only_defending_die:\n print (\"The Defender wins\")\n attacker_losses += 1 \n\n print (\"The defenders lost: \" + str(defender_losses), (\"The attckers lost: \" + str(attacker_losses)))\n return defender_losses, attacker_losses\n\n losses = The_battle()\n listed_losses = list(losses) #makes a list that needs to be separated \n defender_losses = listed_losses[0]\n attacker_losses = listed_losses[1]\n\n attackerLossesTally += attacker_losses\n defenderLossesTally += defender_losses\n\n attacker_numbers -= attacker_losses\n defender_numbers -= defender_losses\n print (\"There are now: \" + str(attacker_numbers) + \" attackers\", \"and \" + str(defender_numbers) + \" defenders\")\n \n def end_game():\n if defender_numbers == 0:\n print (\"The attacker has taken the province\")\n sys.exit()\n elif attacker_numbers == 0:\n print (\"The defender has held the province\")\n sys.exit()\n else:\n print (\"Do you want to keep attacking?\")\n \n def calling_it_off():\n print (\"If would would like to keep attacking press 1, if you would \\n like to stop press 0: \")\n chicken = int(input())\n #could put in a try here but its literally just pressing a button \n if chicken == 0:\n print (\"Calling it off\")\n print (\"In total the attackers lost \" + str(attackerLossesTally))\n sys.exit()\n elif chicken == 1:\n print (\"Once more into the breach\")\n \n end_game()\n calling_it_off()\n\n","sub_path":"risk.py","file_name":"risk.py","file_ext":"py","file_size_in_byte":6141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"434778417","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scipy.stats as ss\nimport statsmodels.api as sm\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom sklearn.feature_selection import VarianceThreshold, f_regression\nfrom sklearn.linear_model import LinearRegression, Lasso, Ridge\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nimport collections\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom yellowbrick.regressor import ResidualsPlot\n\n\n# In[2]:\n\n\n# Import data\ndata = pd.read_csv(\"train.csv\")\n\n\n# # 1. Data Overview (tu trzeba będzie dodać jeszcze jakiś opis co tak naprawdę chcemy zrobić, skąd wzięliśmy dataset itd.) \n\n# At first we have a brief look at the initial form of our data, so to get sense how we should prepare our data to make it suitable for the modelling\n# \n\n# In[3]:\n\n\ndata.head(20)\n\n\n# Number of rows is:\n\n# In[4]:\n\n\ndata.shape[0]\n\n\n# Types of variables in dataset, it is really long so we will only show the number of variables in specific group:\n\n# In[5]:\n\n\ndata.dtypes.value_counts()\n\n\n# Now we know that our data has 81 columns and 1460 rows. The number of columns is definetely too big for the purpose of this analysis. So our first task will be to select the limited number of features which will suit our model in the best way.\n\n# # 2. Data preparation\n\n# ## 2.1. Dependent variable SalePrice overview\n\n# Our dependent variable is SalePrice, which is the price the house were sold. Here are some basic information about it \n\n# In[6]:\n\n\ndata.SalePrice.describe()\n\n\n# In[7]:\n\n\nsns.distplot(data[\"SalePrice\"])\n\n\n# In[8]:\n\n\nprint(\"The skewness is:\",data.SalePrice.skew())\nprint(\"The kurtosis is:\",data.SalePrice.kurt())\n\n\n# So we can see that our dependent variable does not have a perfect normal distribution. We can try improving it by log normalization \n# \n\n# In[9]:\n\n\nsns.distplot(np.log1p(data.SalePrice))\n\n\n# We can see that actually the log normalized distribution of dependent variable seems to be closer to the normal distribution. We will not modify SalesPrice variable now. But just in case we will save the log normalized one in memory\n\n# In[10]:\n\n\nlog1SalePrice = np.log1p(data.SalePrice)\n\n\n# ## 2.2. Clearing the dataset of redundant variables and missings\n\n# ### 2.2.1. Dropping redundant variables (numerical)\n\n# Having in mind that we have 81 variables in our data frame it would be useful to remove some of them to simplify the analysis. First we can get rid of Id variable which is surely not going to bring us anything important. \n\n# In[11]:\n\n\ndata = data.drop(columns = \"Id\")\n\n\n# In[12]:\n\n\ndata.head()\n\n\n# Now we can take a look at the correlation matrix for continous variables.\n\n# In[13]:\n\n\ncorrmat = data.corr()\nf, ax = plt.subplots(figsize=(12, 9))\nsns.heatmap(corrmat, vmax=.8, square=True);\n\n\n# There is a high correlation between variables GarageArea/GarageCars and 1stFlrSF/TotalBsmtSF. \n# 1. First let's take a look at Garage variables. It is pretty obvious GarageCars which is \"Size of garage in car capacity\" is correlated with the area of garage. Therefore there is no need to keep both variables \n# 2. The second relations is between the total sq feet of First floor and total sq feet of basement. It's again pretty self explanatory that those variables are correlated. \n# 3. We decide to remove the variable GarageCars and TotalBsmtSF\n# There is also a high correlation between YearBuilt and GarageYrBlt - most of the garages were built at the same time as the original construction. Therefore, we will dispose \"GarageYrBlt\".\n\n# In[14]:\n\n\ndata = data.drop(columns = [\"GarageCars\", \"TotalBsmtSF\", \"GarageYrBlt\"])\n\n\n# ### 2.2.2. Dealing with NAs\n\n# Now we will look for association between categorical data. In order to do that, firstly we will put \"NA\" value into such columns for which NaN value does not mean missing data, eg. for \"Pool quality\" NaN means there is no pool and not missing data.\n\n# In[15]:\n\n\nna_cols = [\"Alley\", \"BsmtQual\", \"BsmtCond\", \"BsmtExposure\", \"BsmtFinType1\", \"BsmtFinType2\", \"FireplaceQu\", \"GarageType\", \"GarageFinish\", \"GarageQual\", \"GarageCond\", \"PoolQC\", \"Fence\", \"MiscFeature\"]\nfor nas in na_cols:\n if \"Bsmt\" in nas:\n data[nas] = data[nas].fillna(\"No basement\")\n elif \"Garage\" in nas:\n data[nas] = data[nas].fillna(\"No garage\")\n else:\n data[nas] = data[nas].fillna(\"No {}\".format(nas))\n\ncategorical_df = data.select_dtypes(include='object')\ncol_names = categorical_df.columns.values.tolist()\n\n\n# Now we can assess if there are some other NA values in dataset which are now surely just missings\n\n# In[16]:\n\n\nna_percantage = dict((data.isna().sum()/data.shape[0])*100)\nna_percantage \nna_percentage_sorted = sorted(na_percantage.items(), key=lambda kv: kv[1], reverse=True)\nna_percentage_sorted = collections.OrderedDict(na_percentage_sorted)\nna_percentage_sorted\n\n\n# As we can see now there are few variables which contain NA values. It's mostly the problem in case of variable LotFrontage which has 17% of missings. It's not really important variable so we will just drop it. For the other 3 variables we will drop rows with missing values\n\n# In[17]:\n\n\ndata = data.drop(columns='LotFrontage')\ndata = data.dropna()\n\n\n# ### 2.2.3. Dropping redundant variables (categorogical)\n\n# After that, we can calculate Cramer's V matrix, which contains measure of association between categorical features. Cramer's V is similar to correlation as the output is in the range of [0,1], where 0 indicates no association and 1 full association. Naturally, Cramer's V matrix is symmetrical.\n\n# In[18]:\n\n\n# source for cramers_v function in python:\n# https://towardsdatascience.com/the-search-for-categorical-correlation-a1cf7f1888c9\n\ndef cramers_v(x, y):\n confusion_matrix = pd.crosstab(x,y)\n chi2 = ss.chi2_contingency(confusion_matrix)[0]\n n = confusion_matrix.sum().sum()\n phi2 = chi2/n\n r,k = confusion_matrix.shape\n phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1))\n rcorr = r-((r-1)**2)/(n-1)\n kcorr = k-((k-1)**2)/(n-1)\n return np.sqrt(phi2corr/min((kcorr-1),(rcorr-1)))\n\ncorrmat = pd.DataFrame(0, index=col_names, columns=col_names).astype('float64')\n\nfor i, column_i in enumerate(categorical_df):\n for j, column_j in enumerate(categorical_df):\n corrmat.iloc[i][column_j] = cramers_v(categorical_df[column_i], categorical_df[column_j])\n\nf, ax = plt.subplots(figsize=(12, 9)) \nsns.heatmap(corrmat, vmax=.8, square=True);\n\n\n# Again, we can extract a few variables that seem to be strongly associated. \n# 1. Exterior1st and Exterior2nd - both variables concern one feature, so we decided to leave just one in our analysis.\n# 2. GarageQual and GarageCond - rather unsurprisingly, garage quality corresponds with garage condition. Therefore we decided to omit GarageCond.\n# 3. GarageType and GarageFinish - interior finish of the garage seems to be correlated with garage location. Thus, we will only usue GarageType.\n\n# In[19]:\n\n\ndata = data.drop(columns = [\"Exterior2nd\", \"GarageCond\", \"GarageFinish\"])\n\n\n# ## 2.3. One hot encoding\n# \n\n# We have already dealt with some issues which were present in our dataset, removing NAs and some highly correlated variables. The next step is to introduce a proper approach to work with categorogical variables which are higly represented in our case. We decided to use One Hot Encoding to solve this\n\n# In[20]:\n\n\nnominal_variables = []\nnum_variables = []\nfor i in data.columns:\n if str(data[i].dtypes) == \"object\":\n nominal_variables.append(i)\n print(i,\":\", data[i].unique(), \";\" ,len(data[i].unique()))\n else:\n num_variables.append(i)\ndata = pd.concat([data[num_variables], pd.get_dummies(data[nominal_variables])], axis=1)\n\n\n# # 3. Linear Regression\n\n# ## 3.1. Feature Selection\n\n# After all the operations conducted above we were left with 272 independent features. That put as in a position to use a technique to cut down this number to simplify analysis. We decided to use Forward Feature Selection Method. The code which is the implementation of that is presented below. We set the limit for the acceptable pvalue for 0.05\n\n# In[21]:\n\n\nX = data.loc[:, data.columns != 'SalePrice'] \ny = data.SalePrice\n\n\n# In[22]:\n\n\nfinal = {}\nXx = X.copy()\ni = 0\nf = 0\nwhile f != 1:\n working_dict = {}\n \n features = list(Xx.columns)\n \n for feature in features:\n \n names = list(final.keys())\n names.append(feature)\n\n X2 = sm.add_constant(X.loc[:, names])\n est = sm.OLS(y, X2)\n\n results = est.fit()\n temp = dict(results.pvalues)\n\n for k, v in temp.items():\n if k in final:\n pass\n else:\n working_dict[k] = v\n\n working_dict.pop(\"const\")\n \n sorted_x = sorted(working_dict.items(), key=lambda kv: kv[1]) \n \n if sorted_x[0][1] <= 0.05:\n final[sorted_x[0][0]] = sorted_x[0][1]\n Xx.drop(labels = sorted_x[0][0], axis = 1, inplace = True)\n i += 1\n else:\n f += 1\n\n\n# The Forward Feature Selection Method gave us 58 independent variables. Now we can limit our dataset to them + the dependent variable. \n\n# In[23]:\n\n\ndata1 = data[[\"SalePrice\"] + list(final.keys())]\n\n\n# In[24]:\n\n\ndata1.head()\n\n\n# # 4. Lasso Regression\n\n# The alternative way than Linear Regression to handle our regression task is to use Lasso Regression. This method doesn't need feature selection before modelling because it deals with this issue with by itself using L1 regularization. We will start from splitting our dataset into test and training groups and then perform kfold cross validation with Lasso Regression\n\n# ## 4.1. Creating Test and Training sets\n\n# In[25]:\n\n\nX_lasso = data.loc[:, data.columns != 'SalePrice'] \ny_lasso = data.SalePrice\n\nX_lasso_train, X_lasso_test, y_lasso_train, y_lasso_test = train_test_split(X_lasso, y_lasso, test_size=0.3, random_state=42)\n\n\n# ## 4.2. Kfold Cross Validation with Lasso Regression\n\n# Now we will conduct our modelling. We have to specify the vector of different \"alphas\" which will be used in Lasso Regression to find the best one (the higher the alpha the more feature coefficients are 0) \n\n# In[26]:\n\n\n# inspiration: https://towardsdatascience.com/how-to-perform-lasso-and-ridge-regression-in-python-3b3b75541ad8\nlasso = Lasso()\nparams = {\"alpha\": [1e-15, 1e-10, 1e-8, 1e-4,1e-2,1, 2, 5, 10,20, 40, 50, 100, 1000]}\nlasso_regression = GridSearchCV(lasso, params, scoring = 'neg_mean_squared_error')\nlasso_regression.fit(X_lasso_train, y_lasso_train)\n\n\n# In[27]:\n\n\nprint(\"best Neg_MSE: \", lasso_regression.best_score_,\"\\nbest params: \", lasso_regression.best_params_)\n\n\n# In[28]:\n\n\ny_lasso_predict = lasso_regression.predict(X_lasso_test)\n\n\n# ## 4.3. Model Evaluation\n\n# In[29]:\n\n\nfig,ax = plt.subplots()\nax.scatter(y_lasso_test, y_lasso_predict)\nax.plot([y_lasso_predict.min(), y_lasso_predict.max()], [y_lasso_predict.min(), y_lasso_predict.max()], 'k--', lw=4)\nax.set_xlabel('Measured')\nax.set_ylabel('Predicted')\nplt.title(\"Actuals vs Regression Line\")\nfig.show()\n\n\n# The regression line seems to be well matched with actual values \n\n# In[30]:\n\n\nplt.scatter(*zip(*list(enumerate(y_lasso_test))), c = \"orange\")\nplt.scatter(*zip(*list(enumerate(y_lasso_predict))), c= \"blue\")\nplt.gca().legend(('actual',\"predicted\"))\n \nplt.title(\"Actual vs Predicted values\")\n\n\n# Here we can see that predicted values in most cases coincide with actual values\n\n# In[31]:\n\n\nvisualizer = ResidualsPlot(lasso)\nvisualizer.fit(X_lasso_train, y_lasso_train)\nvisualizer.score(X_lasso_test, y_lasso_test) \nvisualizer.poof() \n\n\n# The plot of residuals shows us that our model gives us pretty acceptable predictions. The residuals are randomly spread and in most cases its value is close to 0. At the histogram we can see that our error is normally distributed around 0. \n\n# # 5. Ridge Regression\n\n# The alternative way to L1 regularization used in Lasso Regression is L2 regularization which we can apply with Ridge Regression. The code is really similar to this from Lasso Regression\n\n# ## 5.1. Creating Test and Training sets\n\n# In[32]:\n\n\nX_ridge = data.loc[:, data.columns != 'SalePrice'] \ny_ridge = data.SalePrice\n\nX_ridge_train, X_ridge_test, y_ridge_train, y_ridge_test = train_test_split(X_ridge, y_ridge, test_size=0.3, random_state=42)\n\n\n# ## 5.2. Kfold Cross Validation with Ridge Regression\n\n# In[33]:\n\n\nridge = Ridge()\nparams = {\"alpha\": [1e-15, 1e-10, 1e-8, 1e-4,1e-2,1, 2, 5, 10,20, 40, 50, 100, 1000]}\nridge_regression = GridSearchCV(ridge, params, scoring = 'neg_mean_squared_error')\nridge_regression.fit(X_lasso_train, y_lasso_train)\n\n\n# In[34]:\n\n\nprint(\"best Neg_MSE: \", ridge_regression.best_score_,\"\\nbest params: \", ridge_regression.best_params_)\n\n\n# We can see that the negative MSE is lower than in the case of Lasso Regression. However we can still check how the model performs \n\n# In[35]:\n\n\ny_ridge_predict = ridge_regression.predict(X_ridge_test)\n\n\n# ## 5.3. Model Evaluation\n\n# In[36]:\n\n\nfig,ax = plt.subplots()\nax.scatter(y_ridge_test, y_ridge_predict)\nax.plot([y_ridge_predict.min(), y_ridge_predict.max()], [y_ridge_predict.min(), y_ridge_predict.max()], 'k--', lw=4)\nax.set_xlabel('Measured')\nax.set_ylabel('Predicted')\nplt.title(\"Actuals vs Regression Line\")\nfig.show()\n\n\n# In[37]:\n\n\nplt.scatter(*zip(*list(enumerate(y_ridge_test))), c = \"orange\")\nplt.scatter(*zip(*list(enumerate(y_ridge_predict))), c= \"blue\")\nplt.gca().legend(('actual',\"predicted\"))\n \nplt.title(\"Actual vs Predicted values\")\n\n\n# In[38]:\n\n\nvisualizer = ResidualsPlot(ridge)\nvisualizer.fit(X_ridge_train, y_ridge_train)\nvisualizer.score(X_ridge_test, y_ridge_test) \nvisualizer.poof() \n\n\n# Again, just like in case of Lasso Regression the prediction went pretty well. The residuals are in most rather randomly spread around the horizontal axis. They are in most cases concentrated around zero so it is also a good information. From the histogram we can also see that the error we obtained is normally distributed around zero. \n\n# # 6. Models Comparison\n\n# In[39]:\n\n\n## measures dla Ciebie, Kejt:\n\nMSE_lasso = -lasso_regression.best_score_\nMSE_ridge = -ridge_regression.best_score_\n\n\n# In[ ]:\n\n\n\n\n\n# # Rzeczy do zrobienia\n\n# KK 21.05.2019\n# Zrobione: przejrzałam całość, dodałam jeszcze association dla danych typu categorical bo tutaj też są niepotrzebne zmienne, usunęłam rok zbudowania garażu.\n# Feature selection rzeczywiście trzeba będzie zrobić za pomocą nested cross-validation, ale to już jutro.\n\n# G. 22.05.2019. \n# 1. Moim zdaniem możemy już przechodzić do modelowania. Ja jestem, żeby przeprowadzić je przy pomocy k-folds cross validation. \n# 2. Oczywiście zostają nam też dwie inne regresje (cały czas obstaję przy Lasso i Ridge). \n\n# G. 23.05.2019 \n# \n# 1. Kasia, jakbyś zrobiła linear regression zwykłe. Plus pozbyła sie outlierów w tej części, gdzie pozbywamy się nieprzydatnych danych. Czyli rozdział 2. \n# 2. Trzeba jeszcze zrobić Ridge Regression. No i jeszcze dopracować w ogóle sposób wizualizacji tych danych i porównywania wyników. \n# 3. Będzie potrzebny rozdział gdzie porównamy 3 modele. \n\n# G. 25.05.2019\n# \n# 1. W sumie z mojej strony to jest już chyba wszystko, o ile nie masz jakichś obiekcji albo dodatkowych życzeń. \n# 2. Do zrobienia zostało więc porównanie modeli no i jakiś wstępniak o naszej bazie danych. \n\n# In[ ]:\n\n\n\n\n","sub_path":"arch/ML_small_ds_v03 (1).py","file_name":"ML_small_ds_v03 (1).py","file_ext":"py","file_size_in_byte":15434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"1475327","text":"n = int(input('Enter number to calc. factorial for: '))\nprod = 1\nfor i in range(1, n + 1): # For 1 to n inclusive,\n prod = prod * i\ns = str(prod) # Convert factorial to string s\nz = len(s) - len(s.strip('0'))\nprint('n factorial is', s)\nprint('The number of trailing zeros is', z)\n \n\n\n\n \n\n \n \n\n\n","sub_path":"Archive/zeroes2.py","file_name":"zeroes2.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"536321399","text":"import sys\nimport re\n'''def fun(string, num):\n\tif len(string) > num:\n\t\tprint string[0:num] + \"......\"\n\t\treturn string[0:num] + \"......\"\n\telse:\n\t\tprint string\n\t\treturn string'''\ndef cutStringAndReturnSpecifiedChars(myString, noChars):\n\tmyString = myString or ''\n\tscrubber = Scrubber(autolink=False)\n\tif scrubber and type(myString) == StringType and myString: # When is 'scrubber' object gonna be None?\n\t\tval = scrubber.scrub(myString)\n\t\tmyString = val.encode('ascii', 'ignore')\n\t\trHtmlstrip = re.compile('<\\/?\\w+\\s*[^>]*?\\/?>', re.M)\n\t\tmyString = rHtmlstrip.sub('', myString)\n\tif noChars <= 0:\n\t\treturn myString\n\tif len(myString) <= noChars:\n\t\treturn myString\n\treturn myString[:noChars] + '...'\n\n\n\n\nif __name__ ==\"__main__\":\n\tcutStringAndReturnSpecifiedChars(sys.argv[1],int(sys.argv[2]))\n","sub_path":"my_file/stringcutting.py","file_name":"stringcutting.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"21870440","text":"import os\nimport random\n\n\nmode = \"RGB\"\nos.chdir(mode)\nfile_name = os.listdir(\"./\")\n\nfor file_item in file_name:\n os.system(\"mkdir ../{0}_temp/{1}\".format(mode, file_item))\n image_name = os.listdir(file_item)\n if len(image_name) < 2:\n index_one = random.randint(0,len(image_name)-1)\n os.system(\"cp {0}/{1} ../{2}_temp/{0}\".format(file_item, \\\n image_name[index_one], mode))\n continue\n index_one = random.randint(0,len(image_name)-1)\n index_two = random.randint(0,len(image_name)-1)\n while index_one == index_two:\n index_two = random.randint(0,len(image_name)-1)\n os.system(\"cp {0}/{1} ../{2}_temp/{0}\".format(file_item, \\\n image_name[index_one], mode))\n os.system(\"cp {0}/{1} ../{2}_temp/{0}\".format(file_item, \\\n image_name[index_two], mode))\n\n","sub_path":"python/copy_new_file.py","file_name":"copy_new_file.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"313567069","text":"from urllib.request import urlopen\nimport urllib\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nimport http.client\nfrom openpyxl import Workbook\nfrom openpyxl import load_workbook\nfrom openpyxl.writer.excel import ExcelWriter\nimport json\nimport re\nimport copy\nimport string\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\nhttp.client._MAXHEADERS = 1000\n\n\ndef getNodeText(node):\n\tif(node == None):\n\t\treturn \"\"\n\telse:\n\t\treturn node.get_text().strip()\n\nretryCount = 0\nloadCount = 0\ndef getHtmlFromUrl(url, type=\"get\", para={}):\n\tglobal retryCount\n\ttry:\n\t\turl = urllib.parse.quote(url, safe=string.printable).replace(' ','%20')\n\t\theaders = {\"User-Agent\": \"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36\"}\n\n\t\trequest_obj=urllib.request.Request(url=url,headers=headers)\n\t\tresponse_obj=urllib.request.urlopen(request_obj)\n\t\thtml_code=response_obj.read()\n\t\treturn html_code\n\texcept:\n\t\tprint(\"retry\"+url)\n\t\tretryCount += 1\n\t\tif(retryCount <= 5):\n\t\t\tgetHtmlFromUrl(url)\n\t\telse:\n\t\t\tretryCount=0\n\t\t\treturn None\ndef getRenderdHtmlFromUrl(url):\n\tchrome_options = webdriver.ChromeOptions()\n\tchrome_options.add_argument('--headless')\n\tchrome_options.add_argument('--disable-gpu')\n\tchrome_options.add_argument(\"window-size=1024,768\")\n\n\tchrome_options.add_argument(\"--no-sandbox\")\n\tbrowser = webdriver.Chrome(chrome_options=chrome_options)\n\t\n\tbrowser.get(url)\n\treturn browser.page_source\n\t\ndef writeExcel(workSheet, headers, rowIndex, info):\n\tcellIndex=1\n\tfor head in headers:\n\t\tif head in info:\n\t\t\tworkSheet.cell(rowIndex, cellIndex).value = info[head].strip()\n\t\telse:\n\t\t\tworkSheet.cell(rowIndex, cellIndex).value = \"\"\n\t\tcellIndex=cellIndex+1\n\n\ndef getProductInfo(url, pInfo, products):\n\tprint(str(len(products)) + url)\n\tproductHtml = getRenderdHtmlFromUrl(url)\n\tif productHtml != None:\n\t\tsope = BeautifulSoup(productHtml, \"html.parser\",from_encoding=\"utf-8\")\n\t\t\n\t\tpInfo[\"link\"] = url\n\t\tcat = sope.find(name=\"span\", attrs={\"class\": \"catalog\"})\n\t\tprice = sope.find(name=\"div\", attrs={\"class\": \"price price_now\"})\n\t\tsize = sope.find(name=\"div\", attrs={\"class\": \"unit active\"})\n\t\tdecArea = sope.find(name=\"div\", attrs={\"class\": \"panel-body-inner pd-0 clearfix\"})\n\t\tpInfo[\"cat\"] = getNodeText(cat)\n\t\tpInfo[\"price\"] = getNodeText(price)\n\t\tpInfo[\"size\"] = getNodeText(size)\n\t\tpInfo[\"RelatedPathways\"] = \"\"\n\t\tif decArea !=None:\n\t\t\tattrAreas = decArea.find_all(name=\"div\", attrs={\"class\":\"col-md-12 product_details\"})\n\t\t\tfor attrArea in attrAreas:\n\t\t\t\tattrLabelArea = attrArea.find(name=\"div\", attrs={\"class\":\"col-md-3\"})\n\t\t\t\tattrValArea = attrArea.find(name=\"div\", attrs={\"class\":\"col-md-9\"})\n\t\t\t\tattrLabel = getNodeText( attrLabelArea)\n\t\t\t\tattrVal = getNodeText( attrValArea)\n\t\t\t\tpInfo[attrLabel] = attrVal\n\t\t\tbackInfoArea = sope.find_all(name=\"div\", attrs={\"class\":\"product_details_wrap\"})\n\t\t\tfor info in backInfoArea:\n\t\t\t\ttitle = getNodeText(info.find(name=\"div\", attrs={\"class\":\"title\"}))\n\t\t\t\tif title ==\"Full Name\":\n\t\t\t\t\tpInfo[\"fullname\"] = getNodeText(info.find(name=\"div\", attrs={\"class\":\"cnt\"}))\n\t\t\trelateArea = sope.find(name=\"div\", attrs={\"id\":\"relatedPathways\"})\n\t\t\tif relateArea != None:\n\t\t\t\trelatePro = relateArea.find_all(\"li\")\n\t\t\t\tfor li in relatePro:\n\t\t\t\t\tpInfo[\"RelatedPathways\"] = pInfo[\"RelatedPathways\"] + getNodeText(li)+\",\"\n\t\t\t\n\t\tproducts.append(pInfo.copy())\n\t\t\t\t\n\ndef getProductList(url, type1 ,type2 ,type3 , products):\n\tproductListHtml = getHtmlFromUrl(url)\n\tsope = BeautifulSoup(productListHtml, \"html.parser\",from_encoding=\"utf-8\")\n\tproductListArea = sope.find(\"div\", attrs={\"class\":\"tab-content\"})\n\tif productListArea != None:\n\t\tlinks = productListArea.find_all(\"a\")\n\t\tfor link in links:\n\t\t\tpInfo={\n\t\t\t\t\"name\":getNodeText(link),\n\t\t\t\t\"nav\":type1+\" => \"+type2+\" => \"+type3\n\t\t\t}\n\t\t\tgetProductInfo(\"https://www.sinobiological.com\"+link[\"href\"], pInfo, products)\n\n\ndef getProductType2(url, type, products):\n\ttype2ListHtml = getHtmlFromUrl(url)\n\tsope = BeautifulSoup(type2ListHtml, \"html.parser\",from_encoding=\"utf-8\")\n\tchildType = sope.find(name=\"div\", attrs={\"id\":\"popup1\" })\n\ttype2list = childType.previous_sibling.previous_sibling.previous_sibling.previous_sibling\n\ttypeImages = type2list.find_all(\"img\");\n\timgIndex = 1\n\tprovType = ''\n\tfor img in typeImages:\n\t\tcurrentType = re.findall(r'[^\\\\/:*?\"<>|\\r\\n]+$',img[\"src\"])[0].replace('.png', '')\n\t\tif currentType != provType:\n\t\t\tprovType = currentType\n\t\t\ttype3s = sope.find(name=\"div\",attrs={\"id\":\"popup\"+str(imgIndex)}).find_all(\"li\")\n\t\t\tfor type3 in type3s:\n\t\t\t\tlink = type3.find(\"a\")\n\t\t\t\ttype3str = getNodeText(link)\n\t\t\t\tif link!= None and len(type3str) > 0:\n\t\t\t\t\tgetProductList(\"https://www.sinobiological.com\"+link['href'], type, currentType, type3str, products)\n\t\t\timgIndex = imgIndex+1\n\nexcelFileName=\"sinobiological24.xlsx\"\nwb = Workbook()\nworkSheet = wb.active\nproducts = []\n\ngetProductType2(\"https://www.sinobiological.com/pathways/tgf-beta-pathway\", \"TGF-beta Signaling Pathway\", products)\nheaders=['link','nav','name','cat','price','size','Species','NCBI Ref Seq','RefSeq ORF Size','Sequence Description','Description','Promoter','Vector',\n'Restriction Sites','Tag Sequence','Sequencing Primers',\n'Quality Control','Antibiotic in E.coli','Antibiotic in Mammalian cell','Application','Shipping','Storage']\nrindex = 1\nfor p in products:\n\twriteExcel(workSheet, headers, rindex, p)\n\trindex = rindex+1\nprint(\"flish\")\t\n\nwb.save(excelFileName)","sub_path":"src/work/sinobiological/sinobiological24.py","file_name":"sinobiological24.py","file_ext":"py","file_size_in_byte":5412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"27653823","text":"from django import forms\nfrom django.shortcuts import render, redirect\n\nfrom tests.forms import AnimalForm, AnimalModelForm\nfrom tests.testapp.models import Animal\n\n\ndef formset_view(request):\n formset1 = forms.formset_factory(AnimalForm, extra=0,\n can_delete=True)(prefix='animal1')\n formset2 = forms.formset_factory(AnimalForm, extra=1, min_num=1,\n can_delete=True, max_num=4)(\n prefix='animal2')\n formset3 = forms.formset_factory(AnimalForm, extra=1, min_num=1,\n can_delete=False)(prefix='animal3')\n\n return render(request, 'formset.html', {\n 'formset1': formset1,\n 'formset2': formset2,\n 'formset3': formset3,\n })\n\n\ndef modelformset_view(request):\n animals = Animal.objects.all()\n formset = forms.modelformset_factory(Animal, AnimalModelForm,\n can_delete=True)\n formset1 = formset(prefix='animal1', queryset=animals)\n\n return render(request, 'modelformset.html', {\n 'formset1': formset1\n })\n\n\ndef modelformset_view2(request):\n animals = Animal.objects.all()\n formset_class = forms.modelformset_factory(Animal, AnimalModelForm,\n can_delete=True, extra=0)\n\n formset = formset_class(request.POST or None, prefix='animal',\n queryset=animals)\n\n if request.method == \"POST\":\n if formset.is_valid():\n formset.save()\n\n return redirect('modelformset2')\n\n return render(request, 'modelformset2.html', {\n 'formset': formset\n })\n\n\ndef formsetevents_view(request):\n formset_class = forms.formset_factory(AnimalForm, extra=1, can_delete=True)\n formset = formset_class(prefix='animal')\n\n return render(request, 'formset_events.html', {'formset': formset})\n","sub_path":"tests/testapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"217091472","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nIntegrating swagger in automatic ways.\nOriginal source was:\nhttps://raw.githubusercontent.com/gangverk/flask-swagger/master/flask_swagger.py\n\n\"\"\"\n\nimport re\nimport os\nimport tempfile\nimport json\nfrom bravado_core.spec import Spec\nfrom bravado_core.validate import validate_object\nfrom restapi.attributes import ExtraAttributes\nfrom restapi.confs import PRODUCTION, ABS_RESTAPI_PATH, MODELS_DIR\nfrom restapi.confs import CUSTOM_PACKAGE, EXTENDED_PACKAGE, EXTENDED_PROJECT_DISABLED\nfrom restapi.utilities.globals import mem\n\nfrom restapi.utilities.configuration import load_yaml_file, mix\nfrom restapi.utilities.logs import log\n\nJSON_APPLICATION = 'application/json'\n\n\ndef input_validation(json_parameters, definitionName):\n\n definition = mem.customizer._definitions['definitions'][definitionName]\n spec = mem.customizer._validated_spec\n\n # Can raise jsonschema.exceptions.ValidationError\n validate_object(spec, definition, json_parameters)\n\n\nclass BeSwagger:\n \"\"\"Swagger class in our own way:\n\n Fewer methods than the original swagger reading,\n also more control and closer to the original swagger.\n \"\"\"\n\n def __init__(self, endpoints, customizer):\n\n # Input\n self._endpoints = endpoints\n self._customizer = customizer\n\n # Swagger paths to be publish\n self._paths = {}\n # Original paths as flask should map\n self._original_paths = {}\n # The complete set of query parameters for all classes\n self._qparams = {}\n # Save schemas for parameters before to remove the custom sections\n # It is used to provide schemas for unittests and automatic forms\n self._parameter_schemas = {}\n self._used_swagger_tags = {}\n\n def read_my_swagger(self, method, endpoint, mapping=None):\n\n # content has to be a dictionary\n if not isinstance(mapping, dict):\n raise TypeError(\"Wrong type: {}\".format(type(mapping)))\n\n # read common\n commons = mapping.pop('common', {})\n if commons:\n # Deprecated since 0.7.0\n log.warning(\"Commons specs are deprecated\")\n\n # Check if there is at least one except for common\n if len(mapping) < 1:\n raise ValueError(\"No definition found in: {}\".format(mapping))\n\n ################################\n # Using 'attrs': a way to save external attributes\n\n # Instance\n extra = ExtraAttributes()\n\n ################################\n # Specs should contain only labels written in spec before\n\n pattern = re.compile(r'\\<([^\\>]+)\\>')\n\n for label, specs in mapping.items():\n\n uri = '/{}{}'.format(endpoint.base_uri, label)\n # This will be used by server.py.add\n if uri not in endpoint.uris:\n endpoint.uris[uri] = uri\n\n ################################\n # add common elements to all specs\n for key, value in commons.items():\n if key not in specs:\n specs[key] = value\n\n ################################\n # Separate external definitions\n\n # Find any custom part which is not swagger definition\n custom = specs.pop('custom', {})\n\n # Publish the specs on the final Swagger JSON\n # Default is to do it if not otherwise specified\n extra.publish = custom.get('publish', True)\n if not extra.publish:\n # Deprecated since 0.7.0\n log.warning(\"Publish setting is deprecated\")\n\n # extra.auth = None\n\n ###########################\n # Strip the uri of the parameter\n # and add it to 'parameters'\n newuri = uri[:] # create a copy\n if 'parameters' not in specs:\n specs['parameters'] = []\n\n ###########################\n # Read Form Data Custom parameters\n cparam = specs.pop('custom_parameters', None)\n if cparam is not None:\n for fdp in cparam:\n\n params = self._fdp.get(fdp)\n if params is None:\n log.exit(\"No custom form data '{}'\", fdp)\n else:\n # Unable to extend with list by using extends() because\n # it add references to the original object and do not\n # create copies. Without copying, the same objects will\n # be modified several times leading to errors\n for p in params:\n specs['parameters'].append(p.copy())\n\n ###########################\n # Read normal parameters\n for parameter in pattern.findall(uri):\n\n # create parameters\n x = parameter.split(':')\n xlen = len(x)\n paramtype = 'string'\n\n if xlen == 1:\n paramname = x[0]\n elif xlen == 2:\n paramtype = x[0]\n paramname = x[1]\n\n # FIXME: complete for all types\n # http://swagger.io/specification/#data-types-12\n if paramtype == 'int':\n paramtype = 'number'\n if paramtype == 'path':\n paramtype = 'string'\n\n path_parameter = {\n 'name': paramname,\n 'type': paramtype,\n 'in': 'path',\n 'required': True,\n }\n\n specs['parameters'].append(path_parameter)\n\n # replace in a new uri\n # -> {param}\n newuri = newuri.replace(\n '<{}>'.format(parameter), '{{{}}}'.format(paramname))\n\n # cycle parameters and add them to the endpoint class\n query_params = []\n for param in specs['parameters']:\n\n if param[\"in\"] != 'path':\n if uri not in self._parameter_schemas:\n self._parameter_schemas[uri] = {}\n\n if method not in self._parameter_schemas[uri]:\n self._parameter_schemas[uri][method] = []\n\n self._parameter_schemas[uri][method].append(param.copy())\n\n extrainfo = param.pop('custom', {})\n\n if len(extrainfo) and endpoint.custom['schema']['expose']:\n\n # TODO: read a 'custom.publish' in every yaml\n # to decide if the /schema uri should be in swagger\n\n if uri not in endpoint.custom['params']:\n endpoint.custom['params'][uri] = {}\n endpoint.custom['params'][uri][method] = extrainfo\n\n enum = param.pop(\"enum\", None)\n if enum is not None:\n param[\"enum\"] = []\n for option in enum:\n if isinstance(option, str):\n param[\"enum\"].append(option)\n else:\n # enum [{key1: value1}, {key2: value2}]\n # became enum [key1, ke2]\n for k in option:\n param[\"enum\"].append(k)\n\n # handle parameters in URI for Flask\n if param['in'] == 'query':\n query_params.append(param)\n\n if len(query_params) > 0:\n self.query_parameters(\n endpoint.cls, method=method, uri=uri, params=query_params\n )\n\n # Swagger does not like empty arrays\n if len(specs['parameters']) < 1:\n specs.pop('parameters')\n\n ##################\n # Save definition for checking\n if uri not in self._original_paths:\n self._original_paths[uri] = {}\n self._original_paths[uri][method] = specs\n\n ##################\n # Skip what the developers does not want to be public in swagger\n # NOTE: do not skip if in testing mode\n if not extra.publish and not self._customizer._testing:\n continue\n\n # Handle global tags\n if 'tags' not in specs and len(endpoint.tags) > 0:\n specs['tags'] = []\n for tag in endpoint.tags:\n self._used_swagger_tags[tag] = True\n if tag not in specs['tags']:\n specs['tags'].append(tag)\n\n ##################\n # NOTE: whatever is left inside 'specs' will be\n # passed later on to Swagger Validator...\n\n # Save definition for publishing\n if newuri not in self._paths:\n self._paths[newuri] = {}\n self._paths[newuri][method] = specs\n\n log.verbose(\"Built definition '{}:{}'\", method.upper(), newuri)\n\n endpoint.custom['methods'][method] = extra\n return endpoint\n\n def query_parameters(self, cls, method, uri, params):\n \"\"\"\n apply decorator to endpoint for query parameters\n # self._params[classname][URI][method][name]\n \"\"\"\n\n clsname = cls.__name__\n if clsname not in self._qparams:\n self._qparams[clsname] = {}\n if uri not in self._qparams[clsname]:\n self._qparams[clsname][uri] = {}\n if method not in self._qparams[clsname][uri]:\n self._qparams[clsname][uri][method] = {}\n\n for param in params:\n name = param['name']\n if name not in self._qparams[clsname][uri][method]:\n self._qparams[clsname][uri][method][name] = param\n\n def swaggerish(self):\n \"\"\"\n Go through all endpoints configured by the current development.\n\n Provide the minimum required data according to swagger specs.\n \"\"\"\n\n # Better chosen dinamically from endpoint.py\n schemes = ['http']\n if PRODUCTION:\n schemes = ['https']\n\n # A template base\n output = {\n # TODO: update to 3.0.1? Replace bravado with something else?\n # https://github.com/Yelp/bravado/issues/306\n \"swagger\": \"2.0\",\n \"info\": {\"version\": \"0.0.1\", \"title\": \"Your application name\"},\n \"schemes\": schemes,\n # \"host\": \"localhost\" # chosen dinamically\n \"basePath\": \"/\",\n \"securityDefinitions\": {\n \"Bearer\": {\"type\": \"apiKey\", \"name\": \"Authorization\", \"in\": \"header\"}\n },\n \"security\": [{\"Bearer\": []}],\n }\n\n ###################\n # Set existing values\n proj = self._customizer._configurations['project']\n if 'version' in proj:\n output['info']['version'] = proj['version']\n if 'title' in proj:\n output['info']['title'] = proj['title']\n\n ###################\n models = self.get_models()\n self._fdp = models.pop('FormDataParameters', {})\n\n for k in [\"definitions\", \"parameters\", \"responses\"]:\n if k in models:\n output[k] = models.get(k, {})\n\n output['consumes'] = [\n JSON_APPLICATION,\n # required for parameters with \"in: formData\"\n \"application/x-www-form-urlencoded\",\n # required for parameters of \"type: file\"\n \"multipart/form-data\"\n ]\n output['produces'] = [JSON_APPLICATION]\n\n ###################\n # Read endpoints swagger files\n for key, endpoint in enumerate(self._endpoints):\n\n endpoint.custom['methods'] = {}\n endpoint.custom['params'] = {}\n\n for method, mapping in endpoint.methods.items():\n # add the custom part to the endpoint\n\n self._endpoints[key] = self.read_my_swagger(\n method, endpoint, mapping\n )\n\n ###################\n # Save query parameters globally\n self._customizer._query_params = self._qparams\n self._customizer._parameter_schemas = self._parameter_schemas\n output['paths'] = self._paths\n\n ###################\n tags = []\n for tag, desc in self._customizer._configurations['tags'].items():\n if tag not in self._used_swagger_tags:\n log.debug(\"Skipping unsed tag: {}\", tag)\n continue\n tags.append({'name': tag, 'description': desc})\n output['tags'] = tags\n\n self._customizer._original_paths = self._original_paths\n return output\n\n def get_models(self):\n \"\"\" Read models from base/custom yaml files \"\"\"\n\n # BASE definitions\n path = os.path.join(ABS_RESTAPI_PATH, MODELS_DIR)\n try:\n data = load_yaml_file('swagger.yaml', path=path)\n except AttributeError as e:\n log.exit(e)\n\n # EXTENDED definitions, if any\n extended_models = None\n if EXTENDED_PACKAGE != EXTENDED_PROJECT_DISABLED:\n path = os.path.join(os.curdir, EXTENDED_PACKAGE, MODELS_DIR)\n # NOTE: with logger=False I skip the warning if this file doesn't exist\n try:\n extended_models = load_yaml_file('swagger.yaml', path=path)\n except AttributeError as e:\n log.verbose(e)\n\n # CUSTOM definitions\n path = os.path.join(os.curdir, CUSTOM_PACKAGE, MODELS_DIR)\n try:\n custom_models = load_yaml_file('swagger.yaml', path=path)\n except AttributeError as e:\n log.verbose(e)\n custom_models = {}\n\n if extended_models is None:\n return mix(data, custom_models)\n\n m1 = mix(data, extended_models)\n return mix(m1, custom_models)\n\n def validation(self, swag_dict):\n \"\"\"\n Based on YELP library,\n verify the current definition on the open standard\n \"\"\"\n\n if len(swag_dict['paths']) < 1:\n raise AttributeError(\"Swagger 'paths' definition is empty\")\n\n filepath = os.path.join(tempfile.gettempdir(), 'test.json')\n\n try:\n # Fix jsonschema validation problem\n # expected string or bytes-like object\n # http://j.mp/2hEquZy\n swag_dict = json.loads(json.dumps(swag_dict))\n # write it down\n # FIXME: can we do better than this?\n with open(filepath, 'w') as f:\n json.dump(swag_dict, f)\n except Exception as e:\n raise e\n # log.warning(\"Failed to temporary save the swagger definition\")\n\n bravado_config = {\n 'validate_swagger_spec': True,\n 'validate_requests': False,\n 'validate_responses': False,\n 'use_models': False,\n }\n\n try:\n self._customizer._validated_spec = Spec.from_dict(\n swag_dict, config=bravado_config\n )\n log.debug(\"Swagger configuration is validated\")\n except Exception as e:\n # raise e\n error = str(e).split('\\n')[0]\n log.error(\"Failed to validate:\\n{}\\n\", error)\n return False\n finally:\n os.remove(filepath)\n\n return True\n","sub_path":"restapi/swagger.py","file_name":"swagger.py","file_ext":"py","file_size_in_byte":15338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"549607817","text":"# coding:utf-8\n__author__ = 'Stiller'\n\nfrom django.shortcuts import render_to_response, RequestContext, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\n\nfrom materials.writer.dao import update_student_course_material\nfrom mis import models\nfrom mis import config\nfrom commons import func\nfrom huanxun import settings\n\nimport datetime\nfrom mis import models\nfrom django.db.models import Q\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\n@login_required\ndef update_student_material(request):\n \"\"\"\n update student material (add or delete)\n :param request:\n :return:0 fail 1 OK\n \"\"\"\n materials = request.POST.get('materials', ',')\n gid = request.POST.get('gid', None)\n if gid:\n rs = update_student_course_material(ids=materials, gid=gid)\n if rs:\n logger.info('%s-%s Set Student Materials: ids: %s, groupId: %s', request.user.id, request.user.nickname, materials, gid)\n return HttpResponseRedirect('/mis/classes/list')\n else:\n return render_to_response('error.html', {'fail_msg': 'Failed hold on please!'}, RequestContext(request))\n else:\n course = request.POST.get('course', '')\n student = request.POST.get('student', '')\n if not student or not course:\n return render_to_response('error.html', {\"fail_msg\": 'There had error!'})\n\n rs = update_student_course_material(ids=materials, course=course, student=student)\n if rs:\n logger.info('%s-%s Set Student Materials: ids: %s, groupId: %s', request.user.id, request.user.nickname, materials, gid)\n return HttpResponseRedirect('/mis/student/expend/list?student=%s&course=%s' % (student, course))\n else:\n return render_to_response('error.html', {'fail_msg': 'Failed hold on please!'}, RequestContext(request))\n\n\n@login_required\ndef list_material_packages(request):\n if request.user.has_perm('mis.change_materials'):\n return HttpResponseRedirect(settings.material_host + '/package_admin')\n return HttpResponseRedirect(settings.material_host + '/package_support')\n\n\n@login_required\ndef set_student_material(request):\n gid = request.GET.get('gid', None)\n\n if gid:\n if request.user.role in [config.Role.SCHOOL_MANAGER, config.Role.STUDENT_MANAGER]:\n url = settings.material_host + '/package_user?gid=%s' % gid\n else:\n url = settings.material_host + '/package_user?gid=%s' % gid\n return HttpResponseRedirect(url)\n\n # sms = models.StudentMaterials.objects.filter(is_deleted=False,\n # group_id=gid)\n # sms = sms.order_by('order')\n # finished = sms.filter(progress__gte=100).count()\n # response = dict(gid=gid,\n # sms=sms,\n # finished=finished)\n # return render(request, 'ui/mis/set_student_materials.html', response)\n else:\n sid = request.GET.get('sid')\n cid = request.GET.get('cid')\n # student = models.User.objects.get(pk=sid)\n # course = models.Course.objects.get(pk=cid)\n # sms = models.StudentMaterials.objects.filter(is_deleted=False,\n # student=student,\n # course=course)\n # sms = sms.order_by('order')\n # finished = sms.filter(progress__gte=100).count()\n # response = dict(student=student,\n # course=course,\n # sms=sms,\n # finished=finished)\n if request.user.role in [config.Role.SCHOOL_MANAGER, config.Role.STUDENT_MANAGER]:\n url = settings.material_host + '/package_user/%s?sid=%s&cid=%s' % (request.user.school.object_pk, sid, cid)\n else:\n url = settings.material_host + '/package_user?sid=%s&cid=%s' % (sid, cid)\n return HttpResponseRedirect(url)\n\n # return render(request, 'ui/mis/set_student_materials.html', response)\n\n\n@login_required\ndef material_upload(request):\n path = request.GET.get('path')\n name = request.GET.get('name')\n key = request.GET.get('key', None)\n return render(request, 'uploader/material.html', dict(\n uptoken_url='/mis/uptoken',\n prefix='static/materials/%s/' % path,\n name=name,\n pk=path,\n key=key,\n bucket_domain=\"http://\" + settings.QINIU_BUCKET_DOMAIN,\n domain='http://qiniu-plupload.qiniudn.com'))\n\n@login_required\ndef material_preview(request):\n pk = request.GET.get('mid')\n material = models.Materials.objects.get(object_pk=pk)\n md5 = material.md5\n images = []\n for index in xrange(material.pages):\n images.append(settings.qiuniu_materials_url+md5+\"/\"+str(index)+\".jpg\")\n return render(request, 'ui/mis/material_preview.html',\n {\n 'images': images,\n })\n\n\n@login_required\ndef unfinished_classes(request):\n\n page = request.GET.get('page') or request.POST.get('page', 1)\n # new_set = []\n # time_list = []\n response = {}\n\n now = datetime.datetime.now()\n today_zero_time = datetime.date.today()\n start_date = today_zero_time + datetime.timedelta(days=-1)\n all_classes = models.Classes.objects.filter(start_time__gt=start_date,\n end_time__lt=now,\n is_deleted=False)\\\n .exclude(attendance__in=[config.Attendance.CANCEL, config.Attendance.APPROVING])\\\n .exclude(course__flag=config.CourseFlag.TEMP).order_by('-end_time') \n classes_id = models.ClassNotes.objects.filter(clazz__start_time__gt=start_date,\n clazz__end_time__lt=now,\n clazz__is_deleted=False)\\\n .filter(clazz__attendance__in=[config.Attendance.LATE, config.Attendance.FINISHED, config.Attendance.NOSHOW])\n have_notes = [x.clazz.id for x in classes_id]\n\n # classes = all_classes.filter(attendance=config.Attendance.NORMAL).order_by(\"-end_time\")\n classes = all_classes.exclude(id__in=have_notes)\n # classes = list(classes) + have_no_notes\n # classes = []\n # sql = \"\"\"\n # Select c.id, cn.id as cn_id\n # from classes as c Left join class_notes as cn on c.id = cn.clazz_id\n # and attendance = 1\n # Where c.start_time > % and c.end_time< %s\n # \"\"\"\n #\n # for i in classes:\n # new_set.append(i)\n #\n # response['teacher_list'] = new_set\n # response[\"end_time\"] = time_list\n response.update(func.page_query_set(classes, page))\n\n return render(request, 'ui/mis/unfinished_classes.html', response)\n\n","sub_path":"mis/materials/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"486656359","text":"\nsequence = [10, 20, 30, 40, 50, 60, 70, 80, 90]\n\ngroupCount = 5\n\nl = 0\ng = 0\n\ngroup = []\n\n\nfor i in range(len(sequence)-1, -1, -1): #записужмо в кожну групу шкафів крім останньої по одному починаючи з найбільшого\n if g < groupCount-1:\n l = 0\n group.append([]) #виділення памяті\n group[g].append(sequence[i])\n g += 1\n else: # в останню групу записуємо решту шкафів\n group.append([])\n group[g].append(sequence[i])\n l += 1\n\ndef summ(array): #пош��к суми справ в групі\n suma = 0\n for i in range(0, len(array)): # в циклі по масиву сумуємо всі справи\n suma += array[i]\n return suma\n\ndef maximum(group, groupCount):\n suma = []\n for i in range(0, groupCount): #виділяємо память для підрахунку кількості папок в групі шкаф стажера\n suma.append(0)\n index = 0\n for i in range(0, groupCount): #шукаєм кількость папок в групі шкаф кожного стажера\n suma[i] = summ(group[i])\n\n max = suma[0] #присвоюємо змінній максимальної кількості справ перше значення\n\n for i in range(1, groupCount): #шукаємо максимальну кількість\n if suma[i] > max: #якщо поточний елемент більший за максимальний\n max = suma[i] #присвоюємо значення максимальному елементі поточне\n index = i #записуємо індек максимального елемента\n\n data = [] #змінна для повернення результату\n for i in range(0,3): #виділення памяті для результату\n data.append(0)\n data[0] = suma #запис масиву з сумами\n data[1] = max #запис максимальної суми\n data[2] = index #запис індекса максимальної суми\n\n return data # повернення результату\n\ndata = maximum(group, groupCount) #виклик функії знаходження сум та максимальної суми\nsum = data[0] #запис результату\nmax = data[1]\nindex = data[2]\n\nwhile(index>0): #поки індекс максимальної суми більший 0\n if sum[index-1] + group[index][0] <= max: #якщо сума справ ближньої групи + найбільший шкаф зі справами максимальної групи менша або рівна максимальної\n group[index-1].append(group[index][0]) # переносимо найбільший шкафчик в сусідній\n del(group[index][0]) #видаляємо найбільший шкафчик з поточної групи\n data = maximum(group, groupCount) # повторюємо підрахунок сум в нових групах\n sum = data[0]\n max = data[1]\n index = data[2]\n else: # в іншому випадку зупиняємо цикл\n break\n\nfor line in range(groupCount-1, -1, -1): #вивід в циклі груп шкафчиків\n for row in range(len(group[line])-1, -1, -1):\n print(group[line][row])\n print(\"---\")\n\n\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"430746499","text":"from sklearn.preprocessing import LabelBinarizer\nfrom sklearn.metrics import classification_report\nfrom DLforCV.Starter.chap15_MiniVGGNet.minivggnet import MiniVGGNet\nfrom keras.callbacks import LearningRateScheduler\nfrom keras.optimizers import SGD\nfrom keras.datasets import cifar10\nimport matplotlib\nmatplotlib.use(\"Agg\")\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef step_decay(epoch):\n # 初始化初始学习率,衰减因子,衰减周期\n initAlpha = 0.01\n factor = 0.25\n dropEvery = 5\n\n # 计算当前周期的学习率\n # numpy.floor 对每个元素向下取整\n alpha = initAlpha * (factor ** np.floor((1 + epoch) / dropEvery))\n\n return float(alpha)\n\n# 加载图像并归一化\nprint('[INFO] 正在加载CIFAR10...')\n((trainX, trainY), (testX, testY)) = cifar10.load_data()\ntrainX = trainX.astype(\"float\") / 255.0\ntestX = testX.astype(\"float\") / 255.0\n\n# 类别转成向量形式\nlb = LabelBinarizer()\ntrainY = lb.fit_transform(trainY)\ntestY = lb.transform(testY)\n\n# initialize the label names for the CIFAR-10 dataset\nlabelNames = [\"airplane\", \"automobile\", \"bird\", \"cat\", \"deer\",\n \"dog\", \"frog\", \"horse\", \"ship\", \"truck\"]\n\n# 定义训练中传入模型的回调函数\ncallbacks = [LearningRateScheduler(step_decay)]\n\n# 初始化优化器和模型\nepoch = 40\nbatchsize = 64\nprint(\"[INFO] 正在编译模型...\")\n\nopt = SGD(lr=0.01, momentum=0.9, nesterov=True) # 参数decay是内置衰减控制 decay = init_lr / epoch\nmodel = MiniVGGNet.build(width=32, height=32, depth=3, classes=10)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\n\n# 训练网络\nprint(\"[INFO] 正在训练网络...\")\nH = model.fit(trainX, trainY, validation_data=(testX, testY),\n batch_size=batchsize, epochs=epoch, callbacks=callbacks, verbose=1)","sub_path":"Starter/chap16_learning_rate_decay/cifar10_lr_decay.py","file_name":"cifar10_lr_decay.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"620370826","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nfrom urllib.request import Request, urlopen\nfrom selenium import webdriver\n\n\n# In[2]:\n\n\nclass GetDataFromCitilink:\n def __init__(self, url):\n self.data = {}\n page = requests.get(url)\n self.soup = BeautifulSoup(page.content, 'html.parser')\n \n def get_data(self):\n title = self.soup.find_all('h1')[0].text.strip().split()\n name = ' '.join(title[2:])\n self.data['Название'] = name\n results = self.soup.find(id='content')\n if results is None:\n return {}\n full_specs = results.find_all('div', class_='SpecificationsFull')\n for specs in full_specs:\n spec = specs.find('div', class_='Specifications')\n if spec is None:\n continue\n for res in spec:\n x = res.find('div', class_ = 'Specifications__column Specifications__column_name')\n y = res.find('div', class_ = 'Specifications__column Specifications__column_value')\n if x is None or y is None:\n continue\n key, val = x.text.replace('\\n', '').strip(), y.text.replace('\\n', '').strip() \n self.data[key] = val\n return self.data\n\n\n# In[3]:\n\n\nclass GetDataFromDns:\n def __init__(self, url):\n self.data = {}\n chromedriver_path = 'C:\\\\Users\\\\dimas\\\\Downloads\\\\chromedriver_win32\\\\chromedriver.exe'\n options = webdriver.ChromeOptions()\n options.add_argument('headless') # для открытия headless-браузера\n driver = webdriver.Chrome(executable_path=chromedriver_path, chrome_options=options)\n driver.get(url)\n html = driver.page_source\n self.soup = BeautifulSoup(html, 'html.parser')\n driver.quit()\n \n def get_data(self):\n name = self.soup.find('div', class_ = 'price_item_description').text.split()\n name = ' '.join(name[2:])\n self.data['Название'] = name\n tabs = self.soup.find('div', class_ = 'product-card-tabs__contents')\n table = tabs.find('table')\n rows = table.find_all('tr')\n for row in rows:\n cols = row.find_all('td')\n cols = [ele.text.strip() for ele in cols]\n if len(cols) < 2:\n continue\n self.data[cols[0]] = cols[1]\n return self.data\n\n\n# In[21]:\n\n\ndef get_data_from_citilink(input_txt, output_json):\n urls, objs, features, output = [], [], [], []\n with open(input_txt, 'r') as file:\n lines = file.readlines()\n for line in lines:\n line = line.replace('\\n', '')\n urls.append(line)\n for url in urls:\n obj = GetDataFromCitilink(url)\n objs.append(obj.get_data())\n for obj in objs:\n features.append(set(obj.keys()))\n main_features = features[0]\n for feature in features:\n main_features &= feature\n for obj in objs:\n obj_copy = obj.copy()\n for obj_feature in obj:\n if obj_feature not in main_features:\n del obj_copy[obj_feature]\n output.append(obj_copy)\n with open(output_json, 'w') as out_file:\n for x in output:\n json_obj = json.dumps(x, ensure_ascii=False, indent=2)\n out_file.write(json_obj + '\\n')\n\n\n# In[4]:\n\n\ndef get_data_from_dns(input_txt, output_json):\n urls, objs, features, output = [], [], [], []\n with open(input_txt, 'r') as file:\n lines = file.readlines()\n for line in lines:\n line = line.replace('\\n', '')\n urls.append(line)\n for url in urls:\n obj = GetDataFromDns(url)\n objs.append(obj.get_data())\n with open(output_json, 'w') as out_file:\n for x in objs:\n json_obj = json.dumps(x, ensure_ascii=False, indent=2)\n out_file.write(json_obj + '\\n')\n\n\n# In[23]:\n\n\nget_data_from_citilink(input_txt='data_citilink.txt', output_json='citilink.json')\n\n\n# In[6]:\n\n\nget_data_from_dns(input_txt='data_dns.txt', output_json='dns.json')\n\n","sub_path":"big data/HW_1/src.py","file_name":"src.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"202000810","text":"# f(0)=1 f(1)=1 f(2)=1+1=2 f(3)=1+2=3 f(4)=2+3=5 f(5)=3+5=8 f(6)=5+8=13 f(7)=8+13=21 f(8)=13+21=34\n# f(n)=f(n-2)+f(n-1)\n\ndef fibo(n):\n if n == 0 or n == 1:\n return 1;\n else:\n prev1 = 1\n prev2 = 1\n result = 0;\n for i in range(n - 1):\n result = prev1 + prev2\n prev2 = prev1\n prev1 = result \n\n return result\n\ndef fibo2(n):\n ary = [1, 1]\n for i in range(2, n + 1):\n ary.insert(i, ary[i - 2] + ary[i - 1])\n return ary[n]\n\ndef fibo_recursive(n):\n if n == 0 or n == 1:\n return 1\n else:\n return fibo_recursive(n - 2) + fibo_recursive(n - 1)\n\n\n# print(fibo2(5))\n# print(fibo_recursive(5))\n# print(fibo_recursive(2))\n# print(fibo_recursive(6))","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"645712237","text":"import os\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport scipy.signal as sig\r\nfrom pulson440_formats import CONFIG_MSG_FORMAT\r\nfrom pulson440_constants import SPEED_OF_LIGHT, T_BIN, DN_BIN\r\nimport pandas\r\nimport timeit\r\nimport random\r\nfrom numpy import *\r\nfrom matplotlib.pyplot import *\r\n\r\nDT_0 = 10\r\npulse_data = 'day2_people'\r\nplatform_position_data = '5vertlineallen.csv'\r\nsize = 420\r\nmanual_adjust = 50\r\neyeballing_time_start = 40\r\n\r\ndef read_config_data(file_handle, legacy=False):\r\n \"\"\"\r\n Read in configuration data based on platform.\r\n \"\"\"\r\n config = dict.fromkeys(CONFIG_MSG_FORMAT.keys())\r\n \r\n if legacy:\r\n config_msg = file_handle.read(44)\r\n config['node_id'] = np.frombuffer(config_msg[4:8], dtype='>u4')[0]\r\n config['scan_start'] = np.frombuffer(config_msg[8:12], dtype='>i4')[0]\r\n config['scan_stop'] = np.frombuffer(config_msg[12:16], dtype='>i4')[0]\r\n config['scan_res'] = np.frombuffer(config_msg[16:18], dtype='>u2')[0]\r\n config['pii'] = np.frombuffer(config_msg[18:20], dtype='>u2')[0]\r\n config['ant_mode'] = np.uint16(config_msg[32])\r\n config['tx_gain_ind'] = np.uint16(config_msg[33])\r\n config['code_channel'] = np.uint16(config_msg[34])\r\n config['persist_flag'] = np.uint16(config_msg[35])\r\n \r\n else:\r\n config_msg = file_handle.read(32)\r\n byte_counter = 0\r\n for config_field in CONFIG_MSG_FORMAT.keys():\r\n num_bytes = CONFIG_MSG_FORMAT[config_field].itemsize\r\n config_data = config_msg[byte_counter:(byte_counter + num_bytes)]\r\n config[config_field] = np.frombuffer(config_data,\r\n dtype=CONFIG_MSG_FORMAT[config_field])[0]\r\n config[config_field] = config[config_field].byteswap()\r\n byte_counter += num_bytes\r\n \r\n return config\r\n\r\ndef unpack(file, legacy=False):\r\n \"\"\"\r\n Unpacks PulsOn 440 radar data from input file\r\n \"\"\"\r\n with open(file, 'rb') as f:\r\n config = read_config_data(f, legacy)\r\n \r\n scan_start_time = float(config['scan_start'])\r\n scan_end_time = float(config['scan_stop'])\r\n num_range_bins = DN_BIN * math.ceil((scan_end_time - scan_start_time) /\r\n (T_BIN * 1000 * DN_BIN))\r\n num_packets_per_scan = math.ceil(num_range_bins / 350)\r\n start_range = SPEED_OF_LIGHT * ((scan_start_time * 1e-12) - DT_0 * 1e-9) / 2\r\n drange_bins = SPEED_OF_LIGHT * T_BIN * 1e-9 / 2\r\n range_bins = start_range + drange_bins * np.arange(0, num_range_bins, 1)\r\n \r\n data = dict()\r\n data= {'scan_data': [],\r\n 'time_stamp': [],\r\n 'packet_ind': [],\r\n 'packet_pulse_ind': [],\r\n 'range_bins': range_bins}\r\n single_scan_data = []\r\n packet_count = 0\r\n pulse_count = 0\r\n \r\n while True:\r\n packet = f.read(1452)\r\n if len(packet) < 1452:\r\n break \r\n packet_count += 1\r\n \r\n data['packet_ind'].append(np.frombuffer(packet[48:50], dtype='u2'))\r\n \r\n if packet_count % num_packets_per_scan == 0:\r\n num_samples = num_range_bins % 350\r\n packet_data = np.frombuffer(packet[52:(52 + 4 * num_samples)], \r\n dtype='>i4')\r\n single_scan_data.append(packet_data)\r\n data['scan_data'].append(np.concatenate(single_scan_data))\r\n data['time_stamp'].append(np.frombuffer(packet[8:12], \r\n dtype='>u4'))\r\n single_scan_data = []\r\n pulse_count += 1\r\n else:\r\n num_samples = 350\r\n packet_data = np.frombuffer(packet[52:(52 + 4 * num_samples)], \r\n dtype='>i4')\r\n single_scan_data.append(packet_data)\r\n \r\n if single_scan_data:\r\n single_scan_data = np.concatenate(single_scan_data)\r\n num_pad = data['scan_data'][0].size - single_scan_data.size\r\n single_scan_data = np.pad(single_scan_data, (0, num_pad), \r\n 'constant', constant_values=0)\r\n data['scan_data'].append(single_scan_data)\r\n \r\n data['scan_data'] = np.stack(data['scan_data'])\r\n \r\n data['time_stamp']\r\n\r\n return data\r\n\r\ndef extract_complex_pulse():\r\n data = unpack(pulse_data)\r\n \r\n scan_data2 = data['scan_data']\r\n\r\n complex_pulse = sig.hilbert(scan_data2)\r\n return complex_pulse\r\n\r\ndef extract_time_stamp():\r\n data = unpack(pulse_data)\r\n\r\n time_stamp2 = data['time_stamp']\r\n return time_stamp2\r\n\r\ndef extract_range_bins():\r\n data = unpack(pulse_data)\r\n \r\n range_bins2 = data['range_bins']\r\n return range_bins2\r\n\r\ndef extract_platform_position():\r\n array = list()\r\n new_array = list()\r\n position_array = list()\r\n final_result = list()\r\n data = pandas.read_csv(platform_position_data, skiprows=2, low_memory = False)\r\n for elements in data:\r\n if \"Rigid Body\" in elements and \"Marker\" not in elements:\r\n array.append(elements)\r\n for contents in array:\r\n for col in data[contents]:\r\n if type(col) == str and \"Position\" in col:\r\n new_array.append(contents)\r\n for contents2 in new_array:\r\n position_array.append(data[contents2][4:].values)\r\n position_array = np.array(position_array).astype(np.float)\r\n for contents3 in range(len(position_array[0])):\r\n mini_array = list()\r\n for contents4 in range(len(position_array)):\r\n mini_array.append(position_array[contents4][contents3])\r\n final_result.append(np.array(mini_array))\r\n final_result = np.array(final_result)\r\n return final_result\r\n\r\ndef extract_time_stamp2():\r\n array = list()\r\n time_array = list()\r\n data = pandas.read_csv(platform_position_data, skiprows=6)\r\n for elements in data:\r\n if \"Time\" in elements:\r\n array.append(elements)\r\n for contents2 in array:\r\n time_array.append(data[contents2][0:].values)\r\n time_array = np.array(time_array).astype(np.float)\r\n return time_array\r\n\r\ndef get_start_time_platform():\r\n pltpos = extract_platform_position()\r\n mini = 2 ** 63 -1\r\n maxi = -2 ** 63 -1\r\n for n in range(1000):\r\n if pltpos[n][2] > maxi:\r\n maxi = pltpos[n][2] \r\n if pltpos[n][2] < mini:\r\n mini = pltpos[n][2]\r\n start_time = None\r\n n = 0\r\n while start_time == None:\r\n if abs(pltpos[n+100][2] - pltpos[n][2]) > abs(mini - maxi):\r\n start_time = n+100\r\n n += 1 \r\n return start_time\r\n\r\ndef get_parabola(): # dont use\r\n cxpls = extract_complex_pulse()\r\n abscxpls = abs(cxpls)\r\n distance = list()\r\n x = list()\r\n interm = get_start_time_highest_intensity()[1]\r\n adjust = get_start_time_highest_intensity()[0]\r\n for n in range(len(abscxpls)):\r\n distance.append((math.sqrt((interm) ** 2 + (len(abscxpls) / 2 - n) ** 2)))\r\n adjust_refine = adjust - len(abscxpls) /2\r\n for n in range(len(abscxpls)):\r\n x.append(n + adjust_refine-manual_adjust)\r\n return [x,distance]\r\n \r\ndef get_start_time_pulses(): #use to find start of line-->curve-->line\r\n cxpls = extract_complex_pulse()\r\n abscxpls = abs(cxpls)\r\n mini = 2 ** 63 -1\r\n maxi = -2 ** 63 -1\r\n for n in range(40):\r\n if abscxpls[n][0] > maxi:\r\n maxi = abscxpls[n][0] \r\n if abscxpls[n][0] < mini:\r\n mini = abscxpls[n][0]\r\n interm = None\r\n n = 0\r\n while interm == None:\r\n if abs(abscxpls[n+5][2] - abscxpls[n][2]) > abs(mini - maxi):\r\n interm = n+5\r\n n += 1\r\n return interm\r\n\r\ndef intersect(): #use to graph pulse data and parabola \r\n cxpls = extract_complex_pulse()\r\n abscxpls = abs(cxpls)\r\n plt.imshow(abscxpls)\r\n x = get_parabola()[0]\r\n distance = get_parabola()[1]\r\n plt.plot(distance,x,'r--')\r\n\r\ndef get_start_time_highest_intensity(): #dont use\r\n cxpls = extract_complex_pulse()\r\n abscxpls = abs(cxpls)\r\n maxi = -2 ** 63 -1\r\n for n in range(len(abscxpls[0])):\r\n for no in range(len(abscxpls)):\r\n if abscxpls[no][n] > maxi:\r\n maxi = abscxpls[no][n]\r\n for n in range(len(abscxpls[0])):\r\n for no in range(len(abscxpls)):\r\n if abscxpls[no][n] == maxi:\r\n return [no,n]\r\n \r\ndef average_5_pixels(x,y,abscxpls): #dont use\r\n return (abscxpls[x-2][y] + abscxpls[x-1][y] + abscxpls[x][y] + abscxpls[x+1][y] + abscxpls[x+2][y]) / 5.0\r\n\r\ndef get_range(radar_xpos, radar_ypos, radar_zpos, img_x, img_y, img_z):\r\n return math.sqrt((radar_xpos - img_x)**2 + (radar_ypos - img_y)**2 + (radar_zpos - img_z)**2)\r\n\r\ndef combine_all_arrays():\r\n pickle_file = list()\r\n x = time_align_interpolation()\r\n pickle_file.append(x[1])\r\n pickle_file.append(x[0])\r\n pickle_file.append(extract_range_bins())\r\n pickle_file = np.array(pickle_file)\r\n return pickle_file\r\n\r\ndef create_SAR_image(pickle_file):\r\n start = timeit.default_timer()\r\n\r\n radar_positions = pickle_file[0]\r\n pulses = pickle_file[1]\r\n range_bins = pickle_file[2]\r\n \r\n radar_x = []\r\n for position in radar_positions:\r\n radar_x.append(position[0])\r\n radar_y = []\r\n for position in radar_positions:\r\n radar_y.append(position[1])\r\n radar_z = []\r\n for position in radar_positions:\r\n radar_z.append(position[2])\r\n\r\n y = int(range_bins[len(range_bins)-1] - range_bins[0])/2\r\n x = -int(get_range(radar_x[0], radar_y[0], radar_z[0], radar_x[len(radar_x)-1], radar_y[len(radar_y)-1], radar_z[len(radar_z)-1]))/2\r\n print(x)\r\n print(y)\r\n size = abs(int(x*y*40))\r\n print(size)\r\n #pixel_values = list(list(0+0j for ii in np.arange(0, size*x/y)) for jj in np.arange(0, size))\r\n pixel_values = np.zeros((int(abs(size*x/y)),size))\r\n print(len(pixel_values))\r\n for ii in np.arange(0, size*x/y):\r\n x = -int(get_range(radar_x[0], radar_y[0], radar_z[0], radar_x[len(radar_x)-1], radar_y[len(radar_y)-1], radar_z[len(radar_z)-1]))/2\r\n for jj in np.arange(0, size):\r\n for kk in np.arange(0, len(radar_x)):\r\n z = 0\r\n distance = get_range(radar_x[kk], radar_y[kk], radar_z[kk], x, y, z)\r\n ratio = (distance % ((range_bins[1]-radar_bins[0])/2)) / ((range_bins[1]-radar_bins[0])/2)\r\n index = math.floor(((range_bins[1]-radar_bins[0])/2))\r\n pixel_values[ii][jj] += (pulses[kk][index]*(1-ratio) + pulses[kk][index+1]*(ratio))\r\n pixel_values[ii][jj] = np.abs(pixel_values[ii][jj])\r\n x = x + (abs(x)*2)/(size*x/y)\r\n y = y - (abs(y)*2)/size\r\n print(pixel_values)\r\n #plt.imshow(pixel_values)\r\n\r\n end = timeit.default_timer()\r\n print(end-start)\r\n \r\ndef show_image_determine_start_time():\r\n intersect()\r\n \r\ndef time_align_interpolation():\r\n cxpls = extract_complex_pulse()\r\n abscxpls = abs(cxpls)\r\n pltpos = extract_platform_position()\r\n strplat = get_start_time_platform()\r\n strrad = eyeballing_time_start\r\n stamprad = list(map(float,extract_time_stamp()))\r\n stamppla = extract_time_stamp2()\r\n r = np.array(stamprad).astype(float)\r\n p = np.array(stamppla).astype(float)\r\n cutcxpls = abscxpls[strrad:][:]\r\n cutpltpos = pltpos[strplat:][:]\r\n freqr = 1/(float(r[1]) - float(r[0])) * 1000\r\n freqp = 1/(p[0][1] - p[0][0]) \r\n divide = float(freqp / freqr)\r\n\r\n points = list()\r\n points.append(pltpos[strplat])\r\n n = 0\r\n index = None\r\n for elements in range(len(cutcxpls)):\r\n floor = math.floor(divide * elements)\r\n if floor + 1 < len(cutpltpos):\r\n slope = (cutpltpos[floor+1] - cutpltpos[floor]).reshape(3,1)\r\n vector_p = slope * (divide * elements) + cutpltpos[floor].reshape(3,1)\r\n points.append(vector_p.reshape(1,3)[0])\r\n else:\r\n if index == None:\r\n index = n\r\n n += 1\r\n \r\n cxpls = cxpls[strrad:][:]\r\n if index != None:\r\n cxpls = cxpls[:index+1][:]\r\n \r\n return [cxpls,points]\r\n\r\ncreate_SAR_image(combine_all_arrays())","sub_path":"scriptsave2.py","file_name":"scriptsave2.py","file_ext":"py","file_size_in_byte":12389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"502556006","text":"# euler 10\n\nimport time\nN = 2000000\n\ndef prime_sieve(n):\n\n primes = [False]*2 + [True for i in range(2,n+1)]\n p = 2\n\n while(p*p < n):\n\n for i in range(2*p,n + 1, p):\n primes[i] = False\n\n p = primes.index(True,p+1)\n\n\n result = []\n for i in range(n+1):\n if primes[i]:\n result.append(i)\n\n return sum(result)\n\ndef main():\n\n s = time.time()\n print(prime_sieve(N))\n print(\"Time taken: \" , time.time()-s, \"s\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"euler010.py","file_name":"euler010.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"68044980","text":"import json\n\nimport scipy.sparse as sp\n\nfrom . import libtsetlin\n\n\ndef _validate_params(params):\n rv = dict(params)\n\n for k, v in params.items():\n if k == \"s\":\n v = float(v)\n assert(v > 0.)\n elif k == \"boost_true_positive_feedback\":\n v = int(v)\n assert(v in [0, 1])\n elif k == \"n_jobs\":\n v = int(v)\n assert(v == -1 or v > 0)\n elif k == \"number_of_pos_neg_clauses_per_label\":\n v = int(v)\n assert(v > 0)\n elif k == \"number_of_states\":\n v = int(v)\n assert(v > 0)\n elif k == \"random_state\":\n if v is not None:\n v = int(v)\n elif k == \"threshold\":\n v = int(v)\n assert(v > 0)\n elif k == \"verbose\":\n v = bool(v)\n elif k == \"counting_type\":\n v = str(v)\n assert(v in [\"auto\", \"int8\", \"int16\", \"int32\"])\n elif k == \"clause_output_tile_size\":\n v = int(v)\n assert(v in [16, 32, 64, 128])\n\n rv[k] = v\n\n return rv\n\n\ndef _params_as_json_bytes(params):\n return json.dumps(params).encode('UTF-8')\n\n\ndef _classifier_fit(X, y, params, number_of_labels, n_iter):\n \"\"\"\n \"number_of_labels\" and \"number_of_features\" will be derived from X and y\n \"\"\"\n\n X_is_sparse = sp.issparse(X)\n y_is_sparse = sp.issparse(y)\n\n js_state = libtsetlin.classifier_fit(\n X, X_is_sparse,\n y, y_is_sparse,\n _params_as_json_bytes(params),\n number_of_labels,\n n_iter)\n\n return js_state\n\n\ndef _classifier_partial_fit(X, y, js_model, n_iter):\n \"\"\"\n \"number_of_labels\" and \"number_of_features\" will be derived from X and y\n \"\"\"\n\n X_is_sparse = sp.issparse(X)\n y_is_sparse = sp.issparse(y)\n\n js_state = libtsetlin.classifier_partial_fit(\n X, X_is_sparse,\n y, y_is_sparse,\n js_model,\n n_iter)\n\n return js_state\n\n\ndef _classifier_predict(X, js_model):\n\n X_is_sparse = sp.issparse(X)\n\n y_hat = libtsetlin.classifier_predict(X, X_is_sparse, js_model)\n\n return y_hat\n\n\ndef _classifier_predict_proba(X, js_model, threshold):\n X_is_sparse = sp.issparse(X)\n\n probas = libtsetlin.classifier_predict_proba(X, X_is_sparse, js_model, threshold)\n\n return probas\n","sub_path":"bindings/python/tsetlin_tk/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"503082254","text":"from dictionary import * \nfrom solutions import Solution\n\n#Ask for initial seed word\nseed_word = input('Enter a word: ')\nseed_word = seed_word.lower()\n\nrun = True\nwhile run == True:\n\n #Break the seed word into individual letters\n initials = list(seed_word)\n\n #Get the length for words that will fit the square\n length = len(seed_word)\n\n #Make a nested list of appropriate length words for each initial\n word_lists = []\n for x in range(length):\n word_list = get_dictionary(initials[x], length)\n word_lists.append(word_list)\n\n #make a list to hold the solution words\n square_words = []\n square_words.append(seed_word)\n\n #make a list to hold partially consumed word banks\n word_list_shelf = []\n word_list_shelf.append('null') #working_position[0] doesn't consume a list\n\n #make a list to hold solution objects\n solutions_list = []\n\n #make a list to hold solutions re-sorted by value\n sorted_solutions = []\n\n #initialize word value dictionary\n word_value = get_word_values()\n\n #initialize other variables\n working_position = 1\n test_strip = 'init'\n solutions = 0\n\n #get the first fixed letter\n fixed_letters = get_fixed_letters(working_position, square_words)\n\n #grab the first positon word bank to cycle through\n word_list = word_lists[working_position].copy()\n\n #Build word squares by recursively cycling through the word banks\n while working_position < length:\n try:\n #grab a word to check\n test_word = word_list.pop() \n #if there's no more words to grab,\n except IndexError: \n #if this isn't a final, fatal failure,\n if working_position > 1: \n #back up a row.\n working_position -= 1 \n #grab the partially consumed word list from earlier\n word_list = word_list_shelf[working_position] \n #get the fixed letters to check against\n fixed_letters = get_fixed_letters(\n working_position, square_words) \n #if this is a final failure\n #since working_position 0 is the seed word\n elif working_position == 1: \n #if this is a total failure (no solutions found)\n if solutions == 0: \n print('\\nNo valid word square exists.')\n #otherwise, report the action taken\n else:\n print('\\nOperation Complete.\\nCheck the solutions folder.')\n #break out of the recursive loop\n working_position = length + 1 \n #if there was a word to grab,\n else:\n #grab a slice the same length as current\n #fixed letters to check against\n test_strip = test_word[:working_position] \n #see if the slice matches the fixed letters\n if test_strip == fixed_letters: \n try: \n #maybe there's a solution word already in this spot\n #from last cycle\n square_words[working_position] = test_word\n except IndexError: \n #if not, make a new spot\n square_words.append(test_word)\n try:\n #put the partially consumed word bank on the shelf,\n #if a spot exists\n word_list_shelf[working_position] = word_list\n except IndexError:\n #if no spot exists, make a new one\n word_list_shelf.append(word_list)\n #move to the next row\n working_position += 1\n #if this is a total solution (a valid word in the final row)\n if working_position == length: \n #increment the solutions count\n solutions += 1\n #make a new solution object\n solution = Solution()\n #populate the new solution object word and score variables\n solution.get_scores(square_words, word_value)\n #add the new solution object to the solutions list\n solutions_list.append(solution)\n #give feedback in the command line to show progress\n print(str(solutions) + ' solutions found!!!')\n #drop back down so that remaining words in the word bank\n #can be checked\n working_position -= 1 \n #if this isn't a total solution\n else:\n #get new fixed letters to check against for this row\n fixed_letters = get_fixed_letters(\n working_position, square_words)\n #get a fresh word list to cycle through for this position \n word_list = word_lists[working_position].copy()\n\n \n #write the best solutions to a file\n if solutions > 0:\n create_solution_file(solutions_list, seed_word)\n\n #Ask to go again\n seed_word = input('\\nEnter a new word?\\n(Or \"q\" to quit): ')\n seed_word.lower()\n if seed_word == 'q':\n run = False","sub_path":"word_square.py","file_name":"word_square.py","file_ext":"py","file_size_in_byte":5250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"578415387","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nsd={\"王曉明\":50,\"李小美\":70,\"陳阿明\":65}\nwhile True:\n x=input(\"請輸入學生姓名或按enter結束:\")\n if x in sd:\n print(\"他的成績是\",sd[x])\n elif x ==\"\":\n print(\"輸入結束。\")\n break\n elif x not in sd and x!=\"\" :\n xx=int(input(\"請輸入{}的成績\".format(x)))\n sd[x]=xx\n\n\n# In[2]:\n\n\nprint(sd)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"W7_a1.py","file_name":"W7_a1.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"513268162","text":"import pygame\nimport sys\nimport os\nfrom robot import *\nfrom pygame.locals import *\nfrom action import *\n\ndef load_sprites():\n robot = Robot(\"robot.png\", 50, 50, 200, 200, screen)\n sprites.add(robot)\n objects['robot'] = robot\n\ndef main():\n # objects.get('robot').set_action_list([Action_move, Action_turn_left, Action_move, Action_turn_right, Action_move])\n\n running = True\n while(running):\n for event in pygame.event.get():\n if event.type == QUIT:\n running = False\n\n if event.type == KEYDOWN:\n if event.key == K_e:\n objects.get('robot').execute_action(sprites)\n if event.key == K_m:\n objects.get('robot').add_action(Action_move)\n if event.key == K_a:\n objects.get('robot').add_action(Action_turn_left)\n if event.key == K_d:\n objects.get('robot').add_action(Action_turn_right)\n\n objects.get('robot').baby_step()\n pygame.time.Clock().tick(fps)\n screen.blit(background, (0,0))\n sprites.draw(screen)\n pygame.display.flip()\n\npygame.init()\n\nfps = 30\nfps_clock = pygame.time.Clock()\n\nscreen = pygame.display.set_mode((900, 675))\nbackground = pygame.Surface(screen.get_size())\nbackground.fill((0,255,0))\nbackground = background.convert()\n\nsprites = pygame.sprite.Group()\nobjects = {}\nload_sprites()\n\nmain()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"377150128","text":"import pygame as p\r\nimport random\r\n\r\np.init()\r\np.mixer.init()\r\ndisplay=p.display.set_mode((300,400))\r\nclock = p.time.Clock()\r\nwhite=(255,255,255)\r\npipe_green=(61,175,80)\r\nalmost_white=(73,107,66)\r\ndisplay.fill(white)\r\nfont=p.font.SysFont(None, 30)\r\nscore=0\r\n\r\nbackground_image = p.image.load(\"flappy.png\")\r\nbird_img = p.image.load(\"bird.png\")\r\nbird_img=p.transform.scale(bird_img, (20,20))\r\n\r\nbird_x=10\r\nbird_y=100\r\n\r\nrun=True\r\noffset=120\r\npipe_lengthup=random.randint(3,21)\r\npipe_yd=pipe_lengthup*10+offset\r\n\r\npipe_yup=0\r\npipe_xup=100\r\n\r\nu=450\r\nd=450\r\n\r\npipe_xd=100\r\npipe_lengthlow=400\r\n\r\nbird = p.Surface((10, 10))\r\nbird.fill((255, 0, 0))\r\n\r\npipe_length_list=[]\r\nfor i in range(0,3):\r\n pipe_lengthup=random.randint(3,20)\r\n pipe_lengthlow=400\r\n pipe_length_list.append((pipe_lengthup*10,pipe_lengthlow,))\r\npipe_list=[]\r\nfor x,y in pipe_length_list:\r\n \r\n pipeup = p.Surface((20, x))\r\n pipeup.fill(pipe_green)\r\n \r\n piped = p.Surface((20, y))\r\n piped.fill(pipe_green)\r\n pipe_list.append((pipeup,piped,x+offset))\r\n \r\n \r\n \r\ndef score_board(text,color,x,y):\r\n score1=font.render(text,True,color)\r\n display.blit(score1,(x,y))\r\n \r\n \r\nwhile run:\r\n \r\n for event in p.event.get(eventtype=None):\r\n if event.type==p.QUIT:\r\n run=False\r\n \r\n if u<=-280 and d<=--280:\r\n pipe_length_list=[]\r\n for i in range(0,3):\r\n pipe_lengthup=random.randint(3,20)\r\n pipe_lengthlow=400\r\n pipe_length_list.append((pipe_lengthup*10,pipe_lengthlow))\r\n pipe_list=[]\r\n for x,y in pipe_length_list:\r\n \r\n pipeup = p.Surface((20, x))\r\n pipeup.fill(pipe_green)\r\n \r\n piped = p.Surface((20, y))\r\n piped.fill(pipe_green)\r\n pipe_list.append((pipeup,piped,x+offset))\r\n u=450\r\n d=450\r\n \r\n \r\n keys=p.key.get_pressed()\r\n if keys[p.K_SPACE]:\r\n p.mixer.music.load(\"sfx_wing.wav\")\r\n p.mixer.music.play()\r\n bird_y-=25\r\n \r\n \r\n display.blit(background_image, [0, 0])\r\n display.blit(bird,(20,bird_y))\r\n count=0\r\n pipe_xd=d\r\n pipe_yup=0\r\n pipe_xup=u\r\n for x,y,a in pipe_list: \r\n \r\n display.blit(x,(pipe_xup ,0))\r\n display.blit (y,(pipe_xd ,a))\r\n pipe_xd+=130 \r\n pipe_xup+=130\r\n \r\n if (((u+count*130)-bird_x)<=10 and (u+count*130)-bird_x >=0) and (bird_y-10<=(a-offset)) or ((((u+count*130)-bird_x)<=10 and (u+count*130)-bird_x >=0) and bird_y+10>=a):\r\n p.mixer.music.load(\"sfx_hit.wav\")\r\n p.mixer.music.play()\r\n run=False \r\n print((u+count*130)-bird_x,bird_y,a-offset,a,u,count*130)\r\n \r\n try:\r\n with open(\"highScore.txt\",\"r+\") as file:\r\n content=file.read()\r\n file.seek(0)\r\n if score>int(content):\r\n file.write(str(score))\r\n file.truncate()\r\n except:\r\n file = open(\"highScore.txt\", \"w\") \r\n file.write(\"0\") \r\n file.close() \r\n text=\"High Score : 0\"\r\n \r\n if bird_x-(u+count*130)==-20:\r\n score+=1\r\n \r\n# elif (u+count*130)-bird_x==0 and bird_y+10>=a:\r\n# p.mixer.music.load(\"sfx_hit.wav\")\r\n# p.mixer.music.play()\r\n# run=False\r\n# print(\"down\",(u+count*130)-bird_x,bird_y,a,u,count*130)\r\n \r\n #print(\"downnnnnn\",(u+count*130)-bird_x,bird_y,a,u,count*130,score)\r\n count+=1\r\n \r\n bird_y+=10 \r\n pipe_xd=d\r\n pipe_yup=0\r\n pipe_xup=u\r\n \r\n text=\"Current Score : \"+str(score)\r\n score_board(text, (99 ,50 ,88), 50, 350)\r\n try:\r\n with open(\"highScore.txt\",\"r+\") as file:\r\n content=file.read()\r\n text=\"High Score : \"+content\r\n except:\r\n file = open(\"highScore.txt\", \"w\") \r\n file.write(\"0\") \r\n file.close() \r\n text=\"High Score : 0\"\r\n \r\n score_board(text, (99 ,50 ,88), 50, 20)\r\n \r\n p.display.update()\r\n u-=5\r\n d-=5\r\n clock.tick(20)\r\n ","sub_path":"flappyBird/bird.py","file_name":"bird.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"116391324","text":"import logging.config\nfrom typing import List\nfrom settings import master\nfrom igraph import Graph\nimport random\nfrom igraph.clustering import VertexClustering\nfrom math import log\nfrom utils.timer import time_mark\nimport time\nimport matplotlib.pyplot as plt\n\nlogging.config.dictConfig(master.LOGGING_SETTINGS)\nlogger = logging.getLogger('normal')\n\n\nclass RadomCombine(object):\n def __init__(self, graph, edges_sum, detection_func, func_args, interval, partitions=None,\n path=None, index0=3, index1=0, **kwargs):\n self.__graph = graph\n self.__edges_sum = edges_sum\n self.__detection_func = detection_func\n self.__func_args = func_args\n self.__interval = interval\n self.__partitions = partitions\n self.__path = path\n\n self.__community_index_0 = index0\n self.__community_index_1 = index1\n self.__edge_set = None\n self.__degree_list = None\n self.__vertex_list = None\n self.__vertex_part = None\n self.__edge_added_list = None\n\n self.__partitions_expected = None\n self.__partitions_expected_degree: List[int] = list()\n self.__partitions_expected_volume: List[int] = list()\n self.__sorted_partitions_expected: List[List[int]] = list()\n self.__degree_distribute: List[int] = list()\n\n self.__start_time = time.time()\n self.__end_time = None\n\n def __start(self):\n\n logger.info(\"RadomCombine\")\n logger.info(f'Time : {time_mark(self.__start_time)}')\n logger.info(f'Graph: {self.__path}')\n logger.info(f'Info : {self.__graph.vcount()} {self.__graph.ecount()}')\n logger.info(f'Edges: {self.__edges_sum}')\n logger.info(f'Func : {self.__detection_func.__name__}')\n logger.info(f'Args : {self.__func_args}')\n logger.info(f'Gap : {self.__interval}')\n logger.info(f'Parts: {len(self.__partitions)}')\n logger.info(\"Community1\")\n\n subgraph0 = self.__partitions.subgraph(self.__community_index_0)\n logger.info(f'Community index: {self.__community_index_0}, '\n f'Info : {subgraph0.vcount()} {subgraph0.ecount()}')\n logger.info(\"Community2\")\n subgraph1 = self.__partitions.subgraph(self.__community_index_1)\n logger.info(f'Community index: {self.__community_index_1}, '\n f'Info : {subgraph1.vcount()} {subgraph1.ecount()}')\n logger.info(\"=\" * 60)\n\n def __quit(self):\n self.__end_time = time.time()\n logger.info(\"=\" * 60)\n logger.info(f'Time : {time_mark(self.__end_time)}')\n logger.info(f'Total: {(self.__end_time - self.__start_time):10.4f} s')\n logger.info(\"=\" * 60)\n logger.info(\"\\n\\n\")\n\n def __preprocess(self):\n self.__edge_set = set(self.__graph.get_edgelist())\n if not self.__partitions:\n self.__partitions = self.__detection_func(self.__graph, **self.__func_args)\n self.__set_necessary_info()\n\n def __set_necessary_info(self):\n v_degree = list()\n v_index = list()\n v_partation = list()\n memberships = self.__partitions._membership\n\n for index in range(len(memberships)):\n if memberships[index] == self.__community_index_0:\n v_index.append(index)\n v_degree.append(self.__graph.degree(index))\n v_partation.append(0)\n if memberships[index] == self.__community_index_1:\n v_index.append(index)\n v_degree.append(self.__graph.degree(index))\n v_partation.append(1)\n\n self.__degree_list = v_degree\n self.__vertex_list = v_index\n self.__vertex_part = v_partation\n\n # 最终合并的社区编号为self.__community_index_1\n partation_expected = VertexClustering(graph=self.__partitions._graph,\n membership=list(self.__partitions._membership))\n for i in range(len(partation_expected._membership)):\n if partation_expected._membership[i] == self.__community_index_0:\n partation_expected._membership[i] = self.__community_index_1\n for i in range(len(partation_expected._membership)):\n if partation_expected._membership[i] == partation_expected._len - 1:\n partation_expected._membership[i] = self.__community_index_0\n partation_expected._len -= 1\n # print(partation_expected._membership)\n self.__partitions_expected = partation_expected\n\n # for i in range(0, 11):\n # print(self.__partitions.subgraph(i).vcount())\n # for i in range(0, 10):\n # print(self.__partitions_expected.subgraph(i).vcount())\n\n def __combine(self):\n Max_vertex0 = self.__vertex_list[self.__degree_list.index(max(self.__degree_list))]\n Max_part0 = self.__vertex_part[self.__vertex_list.index(Max_vertex0)]\n vertex_part1 = Max_part0 ^ 1\n vertex_list0 = list() # ((degree,index))\n vertex_list1 = list()\n for index in range(len(self.__vertex_part)):\n if self.__vertex_part[index] == Max_part0:\n vertex_list0.append((self.__degree_list[index], self.__vertex_list[index]))\n if self.__vertex_part[index] == vertex_part1:\n vertex_list1.append((self.__degree_list[index], self.__vertex_list[index]))\n vertex_list0.sort(reverse=True, key=lambda x: x[0])\n vertex_list1.sort(reverse=True, key=lambda x: x[0])\n # print(vertex_list0)\n # print(vertex_list1)\n\n after_graph = self.__graph.copy()\n #eva = self.__evaluation_log(after_graph)\n #y_data = list()\n #y_data.append(eva)\n fname = master.GRAPH_SETTINGS['path'][8:len(master.GRAPH_SETTINGS['path'])]\n f = open('test/{}_{}_radomadd.txt'.format(fname, master.GRAPH_SETTINGS['edges_sum']), 'w')\n\n for i in range(0, self.__edges_sum):\n edgeadd = self.__random_add_edge(vertex_list0, vertex_list1)\n #print(edgeadd)\n if edgeadd not in self.__edge_set:\n after_graph.add_edge(edgeadd[0], edgeadd[1])\n self.__edge_set.add(edgeadd)\n s = '(' + str(edgeadd[0]) + ',' + str(edgeadd[1]) + ')' + '\\n'\n f.write(s)\n\n #y_data.append(eva)\n #x_data = [i for i in range(0, master.GRAPH_SETTINGS['edges_sum'] + 1)]\n #plt.plot(x_data, y_data)\n #plt.title('random add')\n #plt.show()\n f.close()\n\n def __random_add_edge(self, vertex_list0, vertex_list1):\n while True:\n a = random.randint(0, len(vertex_list0)-1)\n b = random.randint(0, len(vertex_list1)-1)\n if (vertex_list0[a][1], vertex_list1[b][1]) not in self.__edge_set and (vertex_list1[b][1], vertex_list0[a][1]) not in self.__edge_set:\n edgeadd = (vertex_list0[a][1], vertex_list1[b][1])\n return edgeadd\n\n def __evaluation_log(self, after_graph):\n temp_partitions = master.GRAPH_SETTINGS['detection_func'](after_graph, **master.GRAPH_SETTINGS['func_args'])\n # print(temp_partitions._membership)\n set_x = set(self.__vertex_list)\n # print(set_x)\n set_yi = set()\n ideal_evaluation = float(0)\n mem = temp_partitions._membership\n for i in range(0, temp_partitions._len):\n set_yi.clear()\n eva = float(0)\n for index in range(len(mem)):\n if mem[index] == i:\n set_yi.add(index)\n # print(set_yi)\n xx = len(set_x.intersection(set_yi))\n if xx != 0:\n eva = xx / len(set_x) * log(xx / len(set_x), 2)\n ideal_evaluation += eva\n\n return ideal_evaluation\n\n def run(self):\n self.__preprocess()\n self.__start()\n self.__combine()\n self.__quit()\n","sub_path":"anonymization/radon_combine.py","file_name":"radon_combine.py","file_ext":"py","file_size_in_byte":7900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"620877577","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 8 21:59:34 2020\n\n@author: amk170930\n\"\"\"\n\nimport numpy as np\nimport sys\nimport airsim\nfrom airsim import Vector3r\nimport time\n\nclass mpcTest1AK:\n \n # The points by which the trajectory is defined\n trajPts = [Vector3r(0,-10,0),\n Vector3r(0,-30,0),\n Vector3r(20,-30,0),\n Vector3r(40,-30,0),\n Vector3r(70,-30,0),\n Vector3r(70,-10,0),\n Vector3r(70,0,0)]\n \n def plotLine(startPos, endPos, color = \"red\",thickness = 3, VehicleClient = airsim.VehicleClient()):\n\n rgba = [1.0, 0.0, 0.0, 1.0]\n if color == \"blue\":\n rgba = [0.0, 0.0, 1.0, 1.0]\n \n #Plot blue line from specified start point to end point\n VehicleClient.simPlotArrows(points_start = startPos,\n points_end = endPos,\n color_rgba = rgba, arrow_size = 10, thickness = thickness, is_persistent = True)\n \n # Plots ellipse with given center\n # Assumption: Ellipses are only in X-Y plane ( Z is assumed constant)\n def plotEllipse(center,color = \"red\", a = 3,b = 1, nPoints = 20, VehicleClient = airsim.VehicleClient()):\n \n # a is semi major axis abd b is semi minor axis\n # nPoints is number of points you wish to define one half of ellipse with\n\n # Center\n h = center.x_val\n k = center.y_val\n \n # Coordinates at each step\n tailCoord = [0,0,center.z_val]\n headCoord = [0,0,center.z_val]\n \n #Create list of start and end points\n tailList = []\n headList = []\n \n # step is the difference in x value between each point plotted\n step = 2 * a / nPoints\n \n # Upper ellipse\n for i in range(nPoints):\n \n # Start position of the line\n tailCoord[0] = h - a + i * step\n tailCoord[1] = k + np.sqrt(b*b*(1-((tailCoord[0] - h)**2)/(a**2)))\n \n #End position of the line\n headCoord[0] = h - a + (i+1) * step\n headCoord[1] = k + np.sqrt(b*b*(1-((headCoord[0]-h)**2)/(a**2)))\n \n # Store the point\n tailList.append(Vector3r(tailCoord[0],tailCoord[1],tailCoord[2]))\n headList.append(Vector3r(headCoord[0],headCoord[1],headCoord[2]))\n \n # Lower ellipse\n for i in range(nPoints):\n # Start position of the line\n tailCoord[0] = h - a + i * step\n tailCoord[1] = k - np.sqrt(b*b*(1-((tailCoord[0] - h)**2)/(a**2)))\n \n # End position of the lineamsm\n headCoord[0] = h - a + (i+1) * step\n headCoord[1] = k - np.sqrt(b*b*(1-((headCoord[0] - h)**2)/(a**2)))\n \n # Store the point\n tailList.append(Vector3r(tailCoord[0],tailCoord[1],tailCoord[2]))\n headList.append(Vector3r(headCoord[0],headCoord[1],headCoord[2]))\n \n # Plot the ellipse\n mpcTest1AK.plotLine(tailList, headList, color)\n \n def main(self):\n \n #Setup airsim multirotor client\n client = airsim.MultirotorClient()\n client.confirmConnection()\n client.enableApiControl(True)\n \n # Arm the drone\n print(\"arming the drone...\")\n client.armDisarm(True)\n \n # Try taking off the multirotor to a deafult height of z = -3\n state = client.getMultirotorState()\n if state.landed_state == airsim.LandedState.Landed:\n print(\"taking off...\")\n client.takeoffAsync().join()\n else:\n client.hoverAsync().join()\n\n time.sleep(1)\n\n state = client.getMultirotorState()\n if state.landed_state == airsim.LandedState.Landed:\n print(\"take off failed...\")\n sys.exit(1)\n \n z = -5\n print(\"make sure we are hovering at %.1f meters...\" %(-z))\n client.moveToZAsync(z, 1).join()\n \n # Locate current position of the multirotor\n pos = state.kinematics_estimated.position\n \n while pos.z_val >-4.99:\n state = client.getMultirotorState()\n pos = state.kinematics_estimated.position\n \n print(\"Height of %.2f meters reached\"%(-z))\n # Initialize first point of trajectory with current position\n self.trajPts[0] = pos\n \n # Initialize all the z coordinates with current z coordinate\n for i in range(len(self.trajPts)):\n mpcTest1AK.trajPts[i].z_val = pos.z_val\n \n # List to store start points of the trajectory path\n trajStart = []\n # List to store end points of the trajectory path\n trajEnd = []\n \n # Loop to store the points in the required format for the trajectory\n for i in range(len(mpcTest1AK.trajPts)-1):\n \n # store the points \n trajStart.append(mpcTest1AK.trajPts[i])\n trajEnd.append(mpcTest1AK.trajPts[i+1])\n \n # Plot the trajectory\n print(\"Plotting the trajectroy...\")\n mpcTest1AK.plotLine(trajStart,trajEnd,\"blue\")\n \n time.sleep(2)\n \n # Plot the ellipses\n print(\"Plotting the ellipses...\")\n for i in range(len(mpcTest1AK.trajPts)):\n mpcTest1AK.plotEllipse(mpcTest1AK.trajPts[i],\"red\")\n \n time.sleep(2)\n \n print(\"flying on path...\")\n result = client.moveOnPathAsync([mpcTest1AK.trajPts[i] for i in range(len(mpcTest1AK.trajPts))],\n 4, 1200,\n airsim.DrivetrainType.MaxDegreeOfFreedom, airsim.YawMode(False,0), -1, 1).join()\n \n finalPt = mpcTest1AK.trajPts[len(mpcTest1AK.trajPts)-1]\n client.moveToPositionAsync(finalPt.x_val,finalPt.y_val,finalPt.z_val,1).join()\n time.sleep(10)\n \n print(\"landing...\")\n client.landAsync().join()\n \n\n print(\"disarming...\")\n client.armDisarm(False)\n \n client.enableApiControl(False)\n print(\"done.\")\n\nrun = mpcTest1AK()\nrun.main()\n \n \n ","sub_path":"PythonClient/multirotor/AK testing/mpcTest1AK.py","file_name":"mpcTest1AK.py","file_ext":"py","file_size_in_byte":6272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"335785611","text":"\n\ndef paginated_response(self, func, result_key=''):\n \"\\n Returns expanded response for paginated operations.\\n The 'result_key' is used to define the concatenated results that are combined from each paginated response.\\n \"\n args = dict()\n results = dict()\n loop = True\n while loop:\n response = func(**args)\n if (result_key == ''):\n result = response\n result.pop('ResponseMetadata', None)\n else:\n result = response.get(result_key)\n results.update(result)\n args['NextToken'] = response.get('NextToken')\n loop = (args['NextToken'] is not None)\n return results\n","sub_path":"Data Set/bug-fixing-2/12057de1c6972542fa5e838588b66667f98a8e68--bug.py","file_name":"12057de1c6972542fa5e838588b66667f98a8e68--bug.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"590990988","text":"def solution(nums):\n factors = {}\n n = len(nums)\n lcond, rcond = [False] * n, [False] * n\n nums.sort()\n for i, item in enumerate(nums):\n if i > 0 and nums[i-1] == nums[i]:\n lcond[i] = True\n if i < n-1 and nums[i+1] == nums[i]:\n rcond[i] = True\n j = 1\n while j * j < item:\n if item % j != 0:\n j += 1\n continue\n if j in factors:\n pos = factors[j]\n rcond[pos] = True\n lcond[i] = True\n if item//j in factors:\n pos = factors[item//j]\n rcond[pos] = True\n lcond[i] = True\n j += 1\n factors[item] = i\n for i in reversed(range(n)):\n if lcond[i] and rcond[i]:\n return nums[i]\n return -1\n\n\nnums = [1, 2, 6, 4, 107, 109, 1024]\nprint(solution(nums))\n\nnums = [1, 2, 6, 4, 128, 109, 1024]\nprint(solution(nums))\n\nnums = [1, 3, 107, 109, 1024]\nprint(solution(nums))\n","sub_path":"Amazon/FindMiddleMaximumCapcity.py","file_name":"FindMiddleMaximumCapcity.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"178580725","text":"\"\"\"\nCore\n====\n\"\"\"\nimport os\nimport logging\nimport time\nimport weakref\nimport pathlib\n\nimport grpc\n\nfrom ansys.grpc.dpf import base_pb2, base_pb2_grpc\nfrom ansys.dpf.core.errors import protect_grpc\nfrom ansys.dpf.core import server as serverlib\nfrom ansys.dpf.core.misc import DEFAULT_FILE_CHUNK_SIZE\nfrom ansys.dpf.core.common import _common_progress_bar\n\nLOG = logging.getLogger(__name__)\nLOG.setLevel(\"DEBUG\")\n\nif \"DPF_CONFIGURATION\" in os.environ:\n CONFIGURATION = os.environ[\"DPF_CONFIGURATION\"]\nelse:\n CONFIGURATION = \"release\"\n\n\ndef load_library(filename, name=\"\", symbol=\"LoadOperators\", server=None):\n \"\"\"Dynamically load an operators library for dpf.core.\n Code containing this library's operators is generated in\n ansys.dpf.core.operators\n\n Parameters\n ----------\n filename : str\n Filename of the operator library.\n\n name : str, optional\n Library name. Probably optional\n\n server : server.DPFServer, optional\n Server with channel connected to the remote or local instance. When\n ``None``, attempts to use the the global server.\n\n Examples\n --------\n Load the mesh operators for Windows (for Linux, just use\n 'libmeshOperatorsCore.so' instead of 'meshOperatorsCore.dll')\n\n >>> from ansys.dpf import core as dpf\n >>> # dpf.load_library('meshOperatorsCore.dll', 'mesh_operators')\n\n \"\"\"\n base = BaseService(server, load_operators=False)\n base.load_library(filename, name, symbol)\n return name + \" successfully loaded\"\n\n\ndef upload_file_in_tmp_folder(file_path, new_file_name=None, server=None):\n \"\"\"Upload a file from the client to the server in a temporary folder\n deleted when the server is shutdown\n\n Parameters\n ----------\n file_path : str\n file path on the client side to upload\n\n new_file_name : str, optional\n name to give to the file server side,\n if no name is specified, the same name as the input file is given\n\n server : server.DPFServer, optional\n Server with channel connected to the remote or local instance. When\n ``None``, attempts to use the the global server.\n\n Notes\n -----\n Print a progress bar\n\n Returns\n -------\n server_file_path : str\n path generated server side\n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n >>> from ansys.dpf.core import examples\n >>> file_path = dpf.upload_file_in_tmp_folder(examples.static_rst)\n\n \"\"\"\n base = BaseService(server, load_operators=False)\n return base.upload_file_in_tmp_folder(file_path, new_file_name)\n\n\ndef upload_files_in_folder(\n to_server_folder_path, client_folder_path, specific_extension=None, server=None\n):\n \"\"\"Upload all the files from a folder of the client\n to the target server folder path.\n\n Parameters\n ----------\n to_server_folder_path : str\n folder path target where will be uploaded files on the server side\n\n client_folder_path: str\n folder path where the files that must be uploaded are located\n on client side\n\n specific_extension (optional) : str\n copies only the files with the given extension\n\n server : server.DPFServer, optional\n Server with channel connected to the remote or local instance. When\n ``None``, attempts to use the the global server.\n\n Returns\n -------\n paths : list of str\n new file paths server side\n \"\"\"\n base = BaseService(server, load_operators=False)\n return base.upload_files_in_folder(\n to_server_folder_path, client_folder_path, specific_extension\n )\n\n\ndef download_file(server_file_path, to_client_file_path, server=None):\n \"\"\"Download a file from the server to the target client file path\n\n Parameters\n ----------\n server_file_path : str\n file path to download on the server side\n\n to_client_file_path: str\n file path target where the file will be located client side\n\n server : server.DPFServer, optional\n Server with channel connected to the remote or local instance. When\n ``None``, attempts to use the the global server.\n\n Notes\n -----\n Print a progress bar\n\n Examples\n --------\n >>> from ansys.dpf import core as dpf\n >>> from ansys.dpf.core import examples\n >>> import os\n >>> file_path = dpf.upload_file_in_tmp_folder(examples.static_rst)\n >>> dpf.download_file(file_path, examples.static_rst)\n\n \"\"\"\n base = BaseService(server, load_operators=False)\n return base.download_file(server_file_path, to_client_file_path)\n\n\ndef download_files_in_folder(\n server_folder_path, to_client_folder_path, specific_extension=None, server=None\n):\n \"\"\"Download all the files from a folder of the server\n to the target client folder path\n\n Parameters\n ----------\n server_folder_path : str\n folder path to download on the server side\n\n to_client_folder_path: str\n folder path target where the files will be located client side\n\n specific_extension (optional) : str\n copies only the files with the given extension\n\n server : server.DPFServer, optional\n Server with channel connected to the remote or local instance. When\n ``None``, attempts to use the the global server.\n\n Notes\n -----\n Print a progress bar\n\n Returns\n -------\n paths : list of str\n new file paths client side\n \"\"\"\n base = BaseService(server, load_operators=False)\n return base.download_files_in_folder(\n server_folder_path, to_client_folder_path, specific_extension\n )\n\n\ndef upload_file(file_path, to_server_file_path, server=None):\n \"\"\"Upload a file from the client to the target server file path\n\n Parameters\n ----------\n file_path : str\n file path on the client side to upload\n\n to_server_file_path: str\n file path target where the file will be located server side\n\n server : server.DPFServer, optional\n Server with channel connected to the remote or local instance. When\n ``None``, attempts to use the the global server.\n\n Notes\n -----\n Print a progress bar\n\n Returns\n -------\n server_file_path : str\n path generated server side\n \"\"\"\n base = BaseService(server, load_operators=False)\n return base.upload_file(file_path, to_server_file_path)\n\n\ndef make_tmp_dir_server(server=None):\n \"\"\"Create a temporary folder server side. Only one temporary folder can be created\n by server instance.\n The folder will be deleted when the server is stopped.\n\n Parameters\n ----------\n server : server.DPFServer, optional\n Server with channel connected to the remote or local instance. When\n ``None``, attempts to use the the global server.\n\n Returns\n -------\n path : str\n path to the temporary dir\n \"\"\"\n base = BaseService(server, load_operators=False)\n return base.make_tmp_dir_server()\n\n\ndef _description(dpf_entity_message, server=None):\n \"\"\"Ask the server to describe the entity in input\n\n Parameters\n ----------\n dpf_entity_message : core.Operator._message, core.Workflow._message,\n core.Scoping._message, core.Field._message,\n core.FieldContainer._message, core.MeshedRegion._message\n\n server : server.DPFServer, optional\n Server with channel connected to the remote or local instance. When\n ``None``, attempts to use the the global server.\n\n Returns\n -------\n description : str\n \"\"\"\n return BaseService(server, load_operators=False)._description(dpf_entity_message)\n\n\nclass BaseService:\n \"\"\"The Base Service class allows to make generic requests to dpf's server.\n For example, information about the server can be requested,\n uploading/downloading file from and to the server can be done,\n new operators plugins can be loaded...\n Most of the request done by the BaseService class are wrapped by\n functions.\n\n Parameters\n ----------\n server : server.DPFServer, optional\n Server with channel connected to the remote or local instance. When\n ``None``, attempts to use the the global server.\n\n timeout : float, optional\n Fails when a connection takes longer than ``timeout`` seconds\n to initialize.\n\n load_operators : bool, optional\n Automatically load the math operators\n\n Examples\n --------\n Connect to an existing DPF server\n >>> from ansys.dpf import core as dpf\n >>> #server = dpf.connect_to_server(ip='127.0.0.1', port = 50054, as_global=False)\n >>> #base = dpf.BaseService(server=server)\n\n \"\"\"\n\n def __init__(self, server=None, load_operators=True, timeout=5):\n \"\"\"Initialize base service\"\"\"\n\n if server is None:\n server = serverlib._global_server()\n\n self._server = weakref.ref(server)\n self._stub = self._connect(timeout)\n\n def _connect(self, timeout=5):\n \"\"\"Connect to dpf service within a given timeout\"\"\"\n stub = base_pb2_grpc.BaseServiceStub(self._server().channel)\n\n # verify connected\n if timeout is not None:\n state = grpc.channel_ready_future(self._server().channel)\n tstart = time.time()\n while (time.time() - tstart) < timeout and not state._matured:\n time.sleep(0.01)\n\n if not state._matured:\n raise IOError(\n f\"Unable to connect to DPF instance at {self._server()._input_ip} \"\n f\"{self._server()._input_port}\"\n )\n\n return stub\n\n def make_tmp_dir_server(self):\n \"\"\"Create a temporary folder server side. Only one temporary folder can be created\n by server instance.\n The folder will be deleted when the server is stopped.\n\n Returns\n -------\n path : str\n path to the temporary dir\n \"\"\"\n request = base_pb2.Empty()\n return self._stub.CreateTmpDir(request).server_file_path\n\n def load_library(self, filename, name=\"\", symbol=\"LoadOperators\"):\n \"\"\"Dynamically load an operators library for dpf.core.\n Code containing this library's operators is generated in\n ansys.dpf.core.operators\n\n Parameters\n ----------\n filename : str\n Filename of the operator library.\n\n name : str, optional\n Library name. Probably optional\n\n Examples\n --------\n Load the mesh operators for Windows (for Linux, just use\n 'libmeshOperatorsCore.so' instead of 'meshOperatorsCore.dll')\n\n >>> from ansys.dpf import core as dpf\n >>> base = dpf.BaseService()\n >>> # base.load_library('meshOperatorsCore.dll', 'mesh_operators')\n\n \"\"\"\n request = base_pb2.PluginRequest()\n request.name = name\n request.dllPath = filename\n request.symbol = symbol\n try:\n self._stub.Load(request)\n except Exception as e:\n raise IOError(\n f'Unable to load library \"{filename}\". File may not exist or'\n f\" is missing dependencies:\\n{str(e)}\"\n )\n\n # TODO: fix code generation upload posix\n import os\n\n if os.name != \"posix\":\n local_dir = os.path.dirname(os.path.abspath(__file__))\n LOCAL_PATH = os.path.join(local_dir, \"operators\")\n\n # send local generated code\n TARGET_PATH = self.make_tmp_dir_server()\n self.upload_files_in_folder(TARGET_PATH, LOCAL_PATH, \"py\")\n\n # generate code\n from ansys.dpf.core.dpf_operator import Operator\n\n code_gen = Operator(\"python_generator\")\n code_gen.connect(1, TARGET_PATH)\n code_gen.connect(0, filename)\n code_gen.connect(2, False)\n code_gen.run()\n\n self.download_files_in_folder(TARGET_PATH, LOCAL_PATH, \"py\")\n\n @property\n def server_info(self):\n \"\"\"Send the request for server information and keep\n the info into a dictionary\n\n Returns\n -------\n info : dictionary\n dictionary with \"server_ip\", \"server_port\", \"server_process_id\"\n \"server_version\" keys\n \"\"\"\n request = base_pb2.ServerInfoRequest()\n try:\n response = self._stub.GetServerInfo(request)\n except Exception as e:\n raise IOError(f\"Unable to recover information from the server:\\n{str(e)}\")\n out = {\n \"server_ip\": response.ip,\n \"server_port\": response.port,\n \"server_process_id\": response.processId,\n \"server_version\": str(response.majorVersion)\n + \".\"\n + str(response.minorVersion),\n }\n return out\n\n def _description(self, dpf_entity_message):\n \"\"\"Ask the server to describe the entity in input\n\n Parameters\n ----------\n dpf_entity_message : core.Operator._message, core.Workflow._message,\n core.Scoping._message, core.Field._message,\n core.FieldContainer._message, core.MeshedRegion._message...\n\n Returns\n -------\n description : str\n \"\"\"\n request = base_pb2.DescribeRequest()\n request.dpf_type_id = dpf_entity_message.id\n return self._stub.Describe(request).description\n\n def _get_separator(self, path):\n s1 = len(path.split(\"\\\\\"))\n s2 = len(path.split(\"/\"))\n if s2 > s1:\n # Linux case\n separator = \"/\"\n elif s1 > s2:\n # Windows case\n separator = \"\\\\\"\n return separator\n\n @protect_grpc\n def download_file(self, server_file_path, to_client_file_path):\n \"\"\"Download a file from the server to the target client file path\n\n Notes\n -----\n Print a progress bar\n\n Parameters\n ----------\n server_file_path : str\n file path to dowload on the server side\n\n to_client_file_path: str\n file path target where the file will be located client side\n \"\"\"\n request = base_pb2.DownloadFileRequest()\n request.server_file_path = server_file_path\n chunks = self._stub.DownloadFile(request)\n bar = _common_progress_bar(\"Downloading...\", unit=\"KB\")\n bar.start()\n i = 0\n with open(to_client_file_path, \"wb\") as f:\n for chunk in chunks:\n f.write(chunk.data.data)\n i += len(chunk.data.data) * 1e-3\n bar.update(i)\n bar.finish()\n\n @protect_grpc\n def download_files_in_folder(\n self, server_folder_path, to_client_folder_path, specific_extension=None\n ):\n \"\"\"Download all the files from a folder of the server\n to the target client folder path\n\n Parameters\n ----------\n server_folder_path : str\n folder path to download on the server side\n\n to_client_folder_path: str\n folder path target where the files will be located client side\n\n specific_extension (optional) : str\n copies only the files with the given extension\n\n Notes\n -----\n Print a progress bar\n\n\n Returns\n -------\n paths : list of str\n new file paths client side\n \"\"\"\n request = base_pb2.DownloadFileRequest()\n request.server_file_path = server_folder_path\n chunks = self._stub.DownloadFile(request)\n\n num_files = 1\n if chunks.initial_metadata()[0].key == \"num_files\":\n num_files = int(chunks.initial_metadata()[0].value)\n\n bar = _common_progress_bar(\"Downloading...\", unit=\"files\", tot_size=num_files)\n bar.start()\n\n server_path = \"\"\n\n import ntpath\n\n client_paths = []\n f = None\n for chunk in chunks:\n if chunk.data.server_file_path != server_path:\n server_path = chunk.data.server_file_path\n if (\n specific_extension == None\n or pathlib.Path(server_path).suffix == \".\" + specific_extension\n ):\n separator = self._get_separator(server_path)\n server_subpath = server_path.replace(\n server_folder_path + separator, \"\"\n )\n subdir = \"\"\n split = server_subpath.split(separator)\n n = len(split)\n i = 0\n to_client_folder_path_copy = to_client_folder_path\n if n > 1:\n while i < (n - 1):\n subdir = split[i]\n subdir_path = os.path.join(\n to_client_folder_path_copy, subdir\n )\n if not os.path.exists(subdir_path):\n os.mkdir(subdir_path)\n to_client_folder_path_copy = subdir_path\n i += 1\n cient_path = os.path.join(\n to_client_folder_path_copy, ntpath.basename(server_path)\n )\n client_paths.append(cient_path)\n f = open(cient_path, \"wb\")\n try:\n bar.update(len(client_paths))\n except:\n pass\n else:\n f = None\n if f is not None:\n f.write(chunk.data.data)\n try:\n bar.finish()\n except:\n pass\n return client_paths\n\n @protect_grpc\n def upload_files_in_folder(\n self, to_server_folder_path, client_folder_path, specific_extension=None\n ):\n \"\"\"Upload all the files from a folder of the client\n to the target server folder path.\n\n Parameters\n ----------\n to_server_folder_path : str\n folder path target where will be uploaded files on the server side\n\n client_folder_path: str\n folder path where the files that must be uploaded are located\n on client side\n\n specific_extension (optional) : str\n copies only the files with the given extension\n\n Returns\n -------\n paths : list of str\n new file paths server side\n \"\"\"\n server_paths = []\n for root, subdirectories, files in os.walk(client_folder_path):\n for subdirectory in subdirectories:\n subdir = os.path.join(root, subdirectory)\n for filename in os.listdir(subdir):\n f = os.path.join(subdir, filename)\n server_paths = self._upload_and_get_server_path(\n specific_extension,\n f,\n filename,\n server_paths,\n to_server_folder_path,\n subdirectory,\n )\n for file in files:\n f = os.path.join(root, file)\n server_paths = self._upload_and_get_server_path(\n specific_extension, f, file, server_paths, to_server_folder_path\n )\n break\n return server_paths\n\n def _upload_and_get_server_path(\n self,\n specific_extension,\n f,\n filename,\n server_paths,\n to_server_folder_path,\n subdirectory=None,\n ):\n separator = self._get_separator(to_server_folder_path)\n\n if subdirectory is not None:\n to_server_file_path = (\n to_server_folder_path + separator + subdirectory + separator + filename\n )\n else:\n to_server_file_path = to_server_folder_path + separator + filename\n if ((specific_extension is not None) and (f.endswith(specific_extension))) or (\n specific_extension is None\n ):\n server_path = self._stub.UploadFile(\n self.__file_chunk_yielder(\n file_path=f, to_server_file_path=to_server_file_path\n )\n ).server_file_path\n server_paths.append(server_path)\n return server_paths\n\n @protect_grpc\n def upload_file(self, file_path, to_server_file_path):\n \"\"\"Upload a file from the client to the target server file path\n\n Parameters\n ----------\n file_path : str\n file path on the client side to upload\n\n to_server_file_path: str\n file path target where the file will be located server side\n\n Notes\n -----\n Print a progress bar\n\n Returns\n -------\n server_file_path : str\n path generated server side\n \"\"\"\n if os.stat(file_path).st_size == 0:\n raise ValueError(file_path + \" is empty\")\n return self._stub.UploadFile(\n self.__file_chunk_yielder(file_path, to_server_file_path)\n ).server_file_path\n\n @protect_grpc\n def upload_file_in_tmp_folder(self, file_path, new_file_name=None):\n \"\"\"Upload a file from the client to the server in a temporary folder\n deleted when the server is shutdown\n\n Parameters\n ----------\n file_path : str\n file path on the client side to upload\n\n new_file_name : str, optional\n name to give to the file server side,\n if no name is specified, the same name as the input file is given\n\n Notes\n -----\n Print a progress bar\n\n Returns\n -------\n server_file_path : str\n path generated server side\n \"\"\"\n if new_file_name:\n file_name = new_file_name\n else:\n file_name = os.path.basename(file_path)\n if os.stat(file_path).st_size == 0:\n raise ValueError(file_path + \" is empty\")\n return self._stub.UploadFile(\n self.__file_chunk_yielder(\n file_path=file_path, to_server_file_path=file_name, use_tmp_dir=True\n )\n ).server_file_path\n\n def _prepare_shutdown(self):\n self._stub.PrepareShutdown(base_pb2.Empty())\n\n def __file_chunk_yielder(self, file_path, to_server_file_path, use_tmp_dir=False):\n request = base_pb2.UploadFileRequest()\n request.server_file_path = to_server_file_path\n request.use_temp_dir = use_tmp_dir\n\n tot_size = os.path.getsize(file_path) * 1e-3\n\n need_progress_bar = tot_size > 10000\n if need_progress_bar:\n bar = _common_progress_bar(\"Uploading...\", \"KB\", tot_size)\n bar.start()\n i = 0\n with open(file_path, \"rb\") as f:\n while True:\n piece = f.read(DEFAULT_FILE_CHUNK_SIZE)\n if len(piece) == 0:\n break\n request.data.data = piece\n yield request\n i += len(piece) * 1e-3\n if need_progress_bar:\n try:\n bar.update(min(i, tot_size))\n except:\n pass\n\n if need_progress_bar:\n try:\n bar.finish()\n except:\n pass\n","sub_path":"ansys/dpf/core/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":23285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"180903559","text":"__author__ = 'ian'\ndef the_101():\n length_and_cases = input()\n widths = input()\n length_and_cases = length_and_cases.split()\n widths = widths.split()\n number_of_cases = int(length_and_cases[1])\n mapped_road = []\n counter = 0\n for i in widths:\n segment = [int(i), counter]\n mapped_road.append(segment)\n counter += 1\n for i in range(0, number_of_cases):\n test_case = input()\n test_case = [int(x) for x in test_case.split()]\n min_val = 3\n for s in range(test_case[0], test_case[1]+1):\n if mapped_road[s][0] <= min_val:\n min_val = mapped_road[s][0]\n print(min_val)\nthe_101()\n","sub_path":"CarSqueeze.py","file_name":"CarSqueeze.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"577599778","text":"import cv2\nfrom face_detection import face\nfrom keras.models import load_model\nimport numpy as np\nfrom embedding import emb\nfrom tkinter import *\nfrom tkinter import Button \nfrom tkinter import messagebox \nimport pandas as pd\nimport re\nfrom datetime import datetime\nfrom fb import markEnd\n\n\n'''\nName of Programmer: Satinder (Open Source Code)\nJob: This Script runs constantly to detect and predict employees and marks their exit attendence\nPossible Failure : As Image quality is important images with low resolution may not get \n\t\t predicted accurately and wrong prediction is a high possibility in that case\n'''\n\n\n\n\nlabel=None\npeople={1:\"sabir\",2:\"tahir\",3:\"hassan\"}\n\ne=emb()\nfd=face()\n\nf = open(\"attendanceDict.txt\", \"r\");\nlinesList = [];\nif f.mode == 'r':\n linesList = f.readlines();\nf.close();\n\nattendanceDict={}\n\nfor line in linesList:\n tokens = re.split(\"\\t\", line);\n attendanceDict[int(tokens[0])]= int(tokens[1])\n\n\n\n\nmodel=load_model('face_reco2.MODEL')\n\n\ndef saveToFile():\n f = open(\"attendanceDict.txt\", \"w\");\n for x in attendanceDict:\n f.write(str(x) + \"\\t\" + str(attendanceDict[x])+ \"\\n\")\n f.close();\n\n\ndef test():\n test_run=cv2.imread('1.jpg',1)\n test_run=cv2.resize(test_run,(160,160))\n \n test_run=test_run.astype('float')/255.0\n test_run=np.expand_dims(test_run,axis=0)\n test_run=e.calculate(test_run)\n test_run=np.expand_dims(test_run,axis=0)\n test_run=model.predict(test_run)[0]\n\n\ncap=cv2.VideoCapture(0)\nret=True\n#test()\nwhile ret:\n ret,frame=cap.read()\n frame=cv2.flip(frame,1)\n det,coor=fd.detectFace(frame)\n\n if(det is not None):\n for i in range(len(det)):\n detected=det[i]\n k=coor[i]\n f=detected\n detected=cv2.resize(detected,(160,160))\n \n detected=detected.astype('float')/255.0\n detected=np.expand_dims(detected,axis=0)\n feed=e.calculate(detected)\n feed=np.expand_dims(feed,axis=0)\n prediction=model.predict(feed)[0]\n\n result=int(np.argmax(prediction))\n \n if(np.max(prediction)>.70):\n for j in people:\n if(result==j):\n label=people[j]\n if(attendanceDict[j]==1):\n print(\"Exit marked of:\" + label)\n now = datetime.now()\n hour=now.hour\n minute=now.minute\n day=now.day\n month=now.month\n year=now.year\n markEnd(j,day,month,year,minute,hour)\n attendanceDict[j]=0\n saveToFile()\n message_window = Tk()\n message_window.geometry(\"200x200\")\n \n messagebox.showinfo(\"Notification\",\"Attendance Exit has been Marked \"+label) \n \n message_window.withdraw() \n\n \n \n \n else:\n label='unknown'\n \n \n cv2.putText(frame,label,(k[0],k[1]),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)\n \n cv2.rectangle(frame,(k[0],k[1]),(k[0]+k[2],k[1]+k[3]),(252,160,39),3)\n #cv2.imshow('onlyFace',f)\n cv2.imshow('frame',frame)\n if(cv2.waitKey(1) & 0XFF==ord('q')):\n break\ncap.release()\ncv2.destroyAllWindows()\n\n","sub_path":"Project/Source Code/Attendance-using-Face/recognizerexit.py","file_name":"recognizerexit.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"551892136","text":"from common.T_websocket import WsSingle\nfrom common import Traversing_path\nfrom common.conf import Conf\nfrom common.m_process import mprocess\nimport Project_path\nimport ssl,json\nfrom common.read_xls_news import Read_xls\nfrom common.changeChineseNumToArab import changeChineseNumToArab\n\nxls=\"D:\\\\Users\\\\lijq36\\\\Desktop\\\\8009.xls\"\nxls_new=\"E:\\\\AITEST\\\\TestResult\\\\8009.xls\"\nr = Read_xls(xls)\nw=r.copy_book()\n\nssl._create_default_https_context = ssl._create_unverified_context\nconf_path= Project_path.conf_path\nurl = Conf(conf_path + \"/ws.ini\").get_value(\"WS\", \"url\")\nws=WsSingle(url)\nwav_path=\"E:\\\\8009项目\\\\test\"\nwav_list=Traversing_path.file_all_path(wav_path,file_type=\"wav\")\nprint(wav_list)\n\ndef tt(wav):\n wav_name = wav.split('.')[0].split('\\\\')[-1]\n wav_id = wav_name.split('_')[-1]\n a=ws.runsingle(wav)\n txt=json.loads(a)['text'].replace(' ',\"\")\n r.write_onlydata(w, int(wav_id), 5,txt,sheetname='019M41_02_020M24_13_021F30_1')\n r.write_onlydata(w, int(wav_id), 6, wav_name,sheetname='019M41_02_020M24_13_021F30_1')\n print(wav_name,txt)\n\n\nif __name__ == '__main__':\n mprocess(tt,wav_list)\n r.save_write(w, xls_new)\n ws.close()\n\n\n# for each in wav_list:\n# wav_name=each.split('.')[0].split('\\\\')[-redis_case]\n# wav_id=wav_name.split('_')[-redis_case]\n# a=ws.runsingle(each)\n# txt=json.loads(a)['text'].replace(' ',\"\")\n# r.write_onlydata(w, int(wav_id), 5,txt,sheetname='019M41_02_020M24_13_021F30_1')\n# r.write_onlydata(w, int(wav_id), 6, wav_name,sheetname='019M41_02_020M24_13_021F30_1')\n# print(wav_name,txt)\n# r.save_write(w,xls_new)\n# ws.close()\n\n\n\n","sub_path":"AITEST/testcase/WS_Test/80091.py","file_name":"80091.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"297815311","text":"from urllib.request import urlopen\nfrom urllib.error import HTTPError\nfrom urllib.error import URLError\n\n\ndef test_page(url):\n \"\"\"\n Function which test if pg found\n :return: html read\n \"\"\"\n try:\n html = urlopen(url)\n print(html.read())\n except HTTPError as e:\n print('HTTP error: ', e)\n raise\n except URLError as e:\n print('Server not found: ', e)\n raise\n else:\n return html\n\n\nif __name__ == '__main__':\n test_page('https://www.google.com')\n","sub_path":"scrapping/ex001_test_page.py","file_name":"ex001_test_page.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"505487961","text":"from tkinter import *\nimport tkinter as tk\nimport tkinter.scrolledtext as tkst\nimport tkinter.messagebox as tkmb\nimport socket\nimport threading\nfrom threading import Thread\nimport _thread\nimport pickle\nimport time\nimport select\nimport SimpleServer\n\ndef refresh_frame(frame, canvas):\n frame.destroy()\n frame=Frame(canvas)\n canvas.create_window((0,0),window=frame,anchor='nw')\n frame.bind(\"\",myfunction)\n return frame\n\ndef display_players(frame, canvas, clients):\n while True:\n frame = refresh_frame(frame, canvas)\n print(\"Number of clients: \" + str(len(clients)))\n for i in clients:\n c = Canvas(frame, width=300, height = 25)\n c.pack(side=\"top\")\n l = Label(c,text=i[1])\n c.create_window (0,0, anchor=NW, window = l)\n bootButton = tk.Button(c, anchor=NW)\n bootButton[\"text\"] = \"Boot\"\n c.create_window (250, 0, anchor=NW, window=bootButton)\n time.sleep(3)\n\ndef start_game(clients, host):\n for client in clients:\n client[0].sendto(host.encode(\"ascii\"), client[2])\n SimpleServer.serve(len(clients))\n \n \ndef myfunction(event):\n canvas.configure(scrollregion=canvas.bbox(\"all\"),width=300,height=200)\n \ndef broadcast():\n while True:\n print(\"Listening\")\n recv_data, addr = server_socket.recvfrom(8192)\n #host = socket.gethostbyname(socket.gethostname() + \".studentnet.int\")\n print(host)\n print(socket.gethostname())\n print(addr)\n print(recv_data)\n print(server_name)\n #packet = pickle.dumps((host, addr[1], server_name))\n packet = pickle.dumps((host, server_name))\n server_socket.sendto(packet, addr)\n #server_socket.sendto(server_name.encode(), addr)\n print(\"Sent\")\n\ndef listener(client, client_address, clients, serversocket, player_name):\n print(\"Accepted connection from: \", client_address)\n with clients_lock:\n l_temp = (client, player_name, client_address)\n clients.add(l_temp)#Array of clients\n \n print(str(len(clients)))\n try:\n while True:\n ready_to_read, ready_to_write, in_error = \\\n select.select([serversocket,], [serversocket,], [], 5)\n \n except select.error:\n print(\"connection error\")\n \n finally:\n with clients_lock:\n clients.remove(client)\n client.close()\n \ndef acceptPlayers():\n serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #host = socket.gethostbyname(socket.gethostname() + \".studentnet.int\")\n #print(host)\n #print(socket.gethostname())\n port = 9999 \n addr = (host, port)\n serversocket.bind((host, port))\n serversocket.listen(5)\n while True:\n client, client_address = serversocket.accept()\n player_name = client.recv(4096).decode()\n th.append(Thread(target=listener, args = (client, client_address, clients, serversocket, player_name)).start())\n\nth = []\nclients = set()\nclients_lock = threading.Lock()\n\ntemp = socket.gethostbyname_ex(socket.gethostname())[-1]\nhost = temp[1]\n#host = socket.getfqdn(socket.gethostname() + \".studentnet.int\")\nbroadcast_address = ('', 8080)\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\nserver_socket.bind(broadcast_address)\nserver_name = input(\"The name of the server is: \")\n\nt_broadcast = threading.Thread(target=broadcast)\nt_broadcast.daemon = True\nt_broadcast.start()\n\nt_accept_players = threading.Thread(target=acceptPlayers)\nt_accept_players.daemon = True\nt_accept_players.start()\n\nroot=Tk()\nsizex = 425\nsizey = 350\nposx = 100\nposy = 100\nroot.wm_geometry(\"%dx%d+%d+%d\" % (sizex, sizey, posx, posy))\n\nmyframe=Frame(root,relief=GROOVE,width=100,height=150,bd=1)\nmyframe.place(x=10,y=40)\nplayers_label = Label(root, text=\"Players\")\nplayers_label.place(x=10, y=10)\npassword_label = Label(root, text=\"Password:\")\npassword_label.place(x=10, y=320)\npassword_entry = Entry(root)\npassword_entry.place(x=70, y=320)\nplay_button = tk.Button(root, text=\"Play\", command = lambda: start_game(clients, host))\nplay_button.place(x=360, y=320)\ncanvas=Canvas(myframe)\nframe=Frame(canvas)\nmyscrollbar=Scrollbar(myframe,orient=\"vertical\",command=canvas.yview)\ncanvas.configure(yscrollcommand=myscrollbar.set)\n\nmyscrollbar.pack(side=\"right\",fill=\"y\")\ncanvas.pack(side=\"left\")\ncanvas.create_window((0,0),window=frame,anchor='nw')\nframe.bind(\"\",myfunction)\nt_display_players = threading.Thread(target=display_players, args=(frame, canvas, clients))\nt_display_players.daemon = True\nt_display_players.start()\nroot.wm_title(server_name)\nroot.resizable(width=FALSE, height=FALSE)\nroot.mainloop()","sub_path":"GameforPC/working versions/serverSetup.py","file_name":"serverSetup.py","file_ext":"py","file_size_in_byte":4771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"913260","text":"from pathlib import Path\n\nBASE_DIR = Path(__file__).resolve().parent\n\ncleaned = lambda x: [i.strip() for i in x]\n\ndef file_to_list(filename, test=False, sep=None, cast=None):\n if test:\n filepath = BASE_DIR / 'test_inputs' / filename\n else:\n filepath = BASE_DIR / 'inputs' / filename\n \n with open(filepath, 'r') as f:\n if not sep:\n lines = f.readlines()\n else:\n lines = f.read()\n lines = lines.split(sep)\n lines = cleaned(lines)\n \n if cast:\n return list(map(cast, lines))\n else:\n return lines\n","sub_path":"2020/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"17280616","text":"\nimport pandas as pd\n\ndados = pd.read_excel(\"Vendas.xlsx\", parse_dates=['DataEmissao'])\n\ndados2 = dados.groupby([\"DataEmissao\", 'cdProduto'], as_index=False)['ValorVenda'].sum()\ndados2.head()\n\ndados2['Dia_do_mes'] = dados2['DataEmissao'].dt.day\ndados2['Mes'] = dados2['DataEmissao'].dt.month\ndados2['Ano'] = dados2['DataEmissao'].dt.year\ndados2['Dia_da_semana'] = dados2['DataEmissao'].dt.weekday\ndados3 = dados2.drop(\"DataEmissao\", axis=1)\n\n\nfrom sklearn.tree import DecisionTreeRegressor\n\nmodelo = DecisionTreeRegressor()\nmodelo.fit(dados3[['Dia_do_mes','Mes', 'Ano', 'Dia_da_semana', 'cdProduto']], dados3['ValorVenda'])\n\n\nfuturo = pd.date_range(\"2019-03-14\", \"2019-03-31\", freq='D')\n\nfuturo_todos = []\n\nfor cdProduto in dados3['cdProduto'].unique():\n futuro_df = pd.DataFrame()\n futuro_df['Dia_do_mes'] = futuro.day\n futuro_df['Mes'] = futuro.month\n futuro_df['Ano'] = futuro.year\n futuro_df['Dia_da_semana'] = futuro.weekday\n futuro_df['cdProduto'] = cdProduto\n \n p = modelo.predict(futuro_df)\n \n futuro_df['ValorVenda'] = p\n \n futuro_todos.append(futuro_df)\n \nfuturo_todos_df = pd.concat(futuro_todos, ignore_index=True)","sub_path":"Prediction.py","file_name":"Prediction.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"288947931","text":"#Kata Basic Python\n\n\"\"\"\nEjercicio 17\nEscribe un programa que permita al usuario introducir \nuna frase y luego un caracter y muestre la frase\nintroducida, pero con todas las ocurrencias del \ncaracter indicado por el usuario reemplazadas por \n\"-\".\n\"\"\"\n\nfrase = input(\"Introduzca una frase: \")\ncar = input(\"Introduzca un caracter: \")\n\n\nfinal = frase.replace(car,\"-\")\n\nprint(final)","sub_path":"17Kata.py","file_name":"17Kata.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"577895946","text":"import matplotlib as mpl\nmpl.rcParams['font.size'] = 9.0\nimport matplotlib.pyplot as plt\nfrom mtspec import mtspec\nfrom mtspec.util import load_mtdata\n\ndata = load_mtdata('v22_174_series.dat.gz')\nspec, freq, jackknife, fstatistics, _ = mtspec(data, 4930., 3.5,\n number_of_tapers=5, nfft=312, statistics=True, rshape=0,\n fcrit=0.9)\n\nfig = plt.figure()\nax1 = fig.add_subplot(2, 1, 1)\nax1.plot(freq, fstatistics, color='black')\nax1.set_xlim(freq[0], freq[-1])\n\nax2 = fig.add_subplot(2, 1, 2)\nax2.set_yscale('log')\nax2.plot(freq, spec, color='black')\nax2.set_xlim(freq[0], freq[-1])","sub_path":"doc/html_doc/tutorial-2.py","file_name":"tutorial-2.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"402874890","text":"import pygame\nfrom Logger import Logger\n\nclass Drawable:\n\n def __init__(self, image, imagerect, position):\n \"\"\"\n :param image: shape or image to be drawn\n :param position: position on screen (of type Point)\n :param imagerect: rectangle of image to be displayed\n \"\"\"\n Logger.debug(\"DRAWABLE: init(position=(%s)\", str(position))\n self._image = image\n self._pos = position\n\n def draw(self, screen):\n \"\"\"\n Override if in need\n\n :param screen: pygame screen instance\n \"\"\"\n # http://stackoverflow.com/questions/8873219/what-is-a-good-way-to-draw-images-using-pygame\n # if object has radius - set origin to object's center\n if hasattr(self, 'radius'):\n pos = self._pos.state[0]-self.radius, self._pos.state[1]-self.radius\n screen.blit(self._image, pos)\n else:\n screen.blit(self._image, self._pos.state)\n","sub_path":"data/DrawableInterface.py","file_name":"DrawableInterface.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"103604302","text":"import pygame\nimport time\n\ndef checkmousebox(box,mouse):\n if (box[0]+box[2]>mouse[0]>box[0] \n and box[1]+box[3]>mouse[1]>box[1]):\n return True\n return False\n\nclass abilitybar:\n def __init__(self,world):\n self.world=world\n self.num_abilities=5\n self.abilitycooldowns=[0]*self.num_abilities\n self.cooldowns=[2,3,4,5,6]\n self.GCD=0\n \n self.x=0\n self.y=100\n self.abilitysize=20\n \n self.keybinds=[ord(\"1\"),ord(\"2\"),ord(\"3\"),ord(\"4\"),ord(\"5\")]\n self.abilitydescriptions=[(\"Poop\", \"deal 1 damage\"),\n (\"Poop2\", \"deal 2 damage\"),\n (\"Poop3\", \"deal 3 damage\"),\n (\"Poop4\", \"deal 4 damage\"),\n (\"Poop5\", \"deal 5 damage\")]\n def triggerCD(self,x):\n self.abilitycooldowns[x]=time.time()+self.cooldowns[x]\n def triggerGCD(self):\n self.GCD=time.time()+1.3\n \n def draw(self):\n mouse=(self.world.mouse_x,self.world.mouse_y)\n for x in range(self.num_abilities):\n xx=self.x+x*self.abilitysize\n yy=self.y\n box=[xx,yy,self.abilitysize,self.abilitysize]\n \n pygame.draw.rect(self.world.screen, (150,150,150),\n (box[0]+1,box[1]+1,\n box[2]-1,box[3]-1), 0)\n pygame.draw.rect(self.world.screen, (0,0,0),\n (box[0],box[1],\n box[2],box[3]), 1)\n if self.GCD-time.time()>0 or self.abilitycooldowns[x]-time.time()>0:\n if self.abilitycooldowns[x]-time.time()>0:\n progress=(1-(self.abilitycooldowns[x]-time.time())/self.cooldowns[x])\n #print(progress)\n else:\n progress=(1-(self.GCD-time.time())/1.3)\n points=[]\n #if progress<1/8:\n points = [(xx+self.abilitysize/2,yy+self.abilitysize/2),(xx+self.abilitysize/2,yy),\n (xx+self.abilitysize/2+min(self.abilitysize/2,(8)*progress*self.abilitysize/2),yy)]\n if progress>1/8:\n points.append((xx+self.abilitysize,yy+min(self.abilitysize,max((8*(progress-1/8))*self.abilitysize/2,0))))\n if progress>3/8:\n points.append((xx+self.abilitysize-min(self.abilitysize,max((8*(progress-3/8))*self.abilitysize/2,0)),yy+self.abilitysize))\n if progress>5/8:\n points.append((xx,yy+self.abilitysize-min(self.abilitysize,max((8*(progress-5/8))*self.abilitysize/2,0))))\n if progress>7/8:\n points.append((xx+min(self.abilitysize/2,max((8*(progress-7/8))*self.abilitysize/2,0)),yy))\n \n \n pygame.draw.polygon(self.world.surface, (0,0,0,100), points)\n self.world.screen.blit(self.world.fontobject.render(chr(self.keybinds[x]), 1, (0,0,0)),(box[0]+4,box[1]+2)) \n \n #ability description \n for x in range(self.num_abilities):\n xx=self.x+x*self.abilitysize\n yy=self.y\n box=[xx,yy,self.abilitysize,self.abilitysize]\n if checkmousebox(box,mouse):\n descriptionbox=[mouse[0],mouse[1]-55,150,55]\n pygame.draw.rect(self.world.screen, (150,150,150),\n (descriptionbox[0]+1,descriptionbox[1]+1,\n descriptionbox[2]-1,descriptionbox[3]-1), 0)\n pygame.draw.rect(self.world.screen, (0,0,0),\n (descriptionbox[0],descriptionbox[1],\n descriptionbox[2],descriptionbox[3]), 1)\n self.world.screen.blit(self.world.fontobject.render(self.abilitydescriptions[x][0]+\":\", 1, (0,0,0)),(descriptionbox[0]+5,descriptionbox[1]+5)) \n self.world.screen.blit(self.world.fontobject.render(self.abilitydescriptions[x][1], 1, (0,0,0)),(descriptionbox[0]+5,descriptionbox[1]+20)) \n self.world.screen.blit(self.world.fontobject.render(\"cooldown: \"+str(self.cooldowns[x])+\" seconds\", 1, (255,255,255)),(descriptionbox[0]+5,descriptionbox[1]+descriptionbox[3]-15)) \n \n \n\nclass statusbars:\n def __init__(self,world):\n self.world=world\n self.hpmax=1\n self.hp=0\n self.manamax=1\n self.mana=0\n self.staminamax=1\n self.stamina=0\n \n #displaying enemy info\n self.target=None\n def startbars(self, hpmax, hp, manamax, mana, staminamax, stamina):\n self.hpmax=int(hpmax)\n self.hp=int(hp)\n self.manamax=int(manamax)\n self.mana=int(mana)\n self.staminamax=int(staminamax)\n self.stamina=int(stamina)\n \n def draw(self):\n if not self.target==None:\n box=[100, 45, 150, 50]\n pygame.draw.rect(self.world.screen, (200,200,200),(box[0],box[1],\n box[2],box[3]), 0)\n self.world.screen.blit(self.world.fontobject.render(str(self.target.name), 1, (0,0,0)),(box[0]+box[2]/2-(len(self.target.name))*4,box[1]+5))\n \n hpmaxbox=[110,70,130,12]\n pygame.draw.rect(self.world.screen, (255,50,50),(hpmaxbox[0],hpmaxbox[1],\n hpmaxbox[2],hpmaxbox[3]), 1)\n pygame.draw.rect(self.world.screen, (255,0,0),(hpmaxbox[0]+1,hpmaxbox[1]+1,\n (self.target.hp/self.target.hpmax)*(hpmaxbox[2]-1),hpmaxbox[3]-1), 0)\n hpstring=str(self.target.hp)+\"/\"+str(self.target.hpmax)\n self.world.screen.blit(self.world.fontobject.render(hpstring, 1, (0,0,0)),(hpmaxbox[0]+hpmaxbox[2]/2-(len(hpstring))*3,hpmaxbox[1]))\n \n hpmaxbox=[125,1,150,12]\n pygame.draw.rect(self.world.screen, (255,50,50),(hpmaxbox[0],hpmaxbox[1],\n hpmaxbox[2],hpmaxbox[3]), 1)\n pygame.draw.rect(self.world.screen, (255,0,0),(hpmaxbox[0]+1,hpmaxbox[1]+1,\n (self.hp/self.hpmax)*(hpmaxbox[2]-1),hpmaxbox[3]-1), 0)\n self.world.screen.blit(self.world.fontobject.render(str(self.hp)+\"/\"+str(self.hpmax), 1, (0,0,0)),(hpmaxbox[0]+hpmaxbox[2]/3,hpmaxbox[1]))\n \n manamaxbox=[125,15,150,12]\n pygame.draw.rect(self.world.screen, (50,50,255),(manamaxbox[0],manamaxbox[1],\n manamaxbox[2],manamaxbox[3]), 1)\n pygame.draw.rect(self.world.screen, (0,0,255),(manamaxbox[0]+1,manamaxbox[1]+1,\n (self.mana/self.manamax)*(manamaxbox[2]-1),manamaxbox[3]-1), 0)\n self.world.screen.blit(self.world.fontobject.render(str(self.mana)+\"/\"+str(self.manamax), 1, (0,0,0)),(manamaxbox[0]+manamaxbox[2]/3,manamaxbox[1]))\n \n staminamaxbox=[125,29,150,12]\n pygame.draw.rect(self.world.screen, (50,255,50),(staminamaxbox[0],staminamaxbox[1],\n staminamaxbox[2],staminamaxbox[3]), 1)\n pygame.draw.rect(self.world.screen, (0,255,0),(staminamaxbox[0]+1,staminamaxbox[1]+1,\n (self.stamina/self.staminamax)*(staminamaxbox[2]-1),staminamaxbox[3]-1), 0)\n self.world.screen.blit(self.world.fontobject.render(str(self.stamina)+\"/\"+str(self.staminamax), 1, (0,0,0)),(staminamaxbox[0]+staminamaxbox[2]/3,staminamaxbox[1]))\n ","sub_path":"client/combatinterfaces.py","file_name":"combatinterfaces.py","file_ext":"py","file_size_in_byte":7677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"521281623","text":"import argparse\nimport json\nimport gzip\nfrom pathlib import Path\nfrom loguru import logger\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--category', type=str, default='car')\n parser.add_argument('--list_path', type=Path, default='/home/wangyuang/dev/pytorch3d/projects/implicitron_trainer/scripts/filter_sequences/filter_seq_lists/car.txt')\n parser.add_argument('--dataset_root', type=Path, default='/raid/yuang/Data/CO3D_ALL/')\n parser.add_argument('--save_root', type=Path, default='/home/wangyuang/dev/pytorch3d/projects/implicitron_trainer/scripts/filter_sequences/filtered_annos')\n parser.add_argument('--save_name_base', type=str, default='{cat}_filtered_frame_annotations.jgz')\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n \n logger.info(f'Filtering category [{args.category}] w/ [{args.list_path}]')\n # read seq-list-file\n with open(args.list_path, 'r') as f:\n seq_ids = [e.strip() for e in f.readlines()]\n logger.info(f'#seqs: {len(seq_ids)}')\n\n # read co3d annotation file \n with gzip.open(args.dataset_root / args.category / 'frame_annotations.jgz', 'rt', encoding='utf8') as zipfile:\n frame_annos = json.load(zipfile)\n \n # filter seqs & save a new annotation file\n frame_annos_dict = {e['sequence_name']: e for e in frame_annos}\n frame_annos_filtered = [frame_annos_dict[seq_id] for seq_id in seq_ids]\n dump_path = args.save_root / args.save_name_base.format(cat=args.category)\n # with gzip.GzipFile(args.dataset_root / args.category / args.save_name, 'wb') as zipfile:\n with gzip.GzipFile(dump_path, 'wb') as zipfile:\n # json.dumps(frame_annos_filtered, zipfile)\n zipfile.write(json.dumps(frame_annos_filtered).encode(\"utf8\"))\n logger.info(f'Filtered annotations dumped: {dump_path}')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"projects/implicitron_trainer/scripts/filter_sequences/filter_sequences.py","file_name":"filter_sequences.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"632405069","text":"#!/usr/bin/python3\n# Needs sh module\n# pip install --user sh\n\nfrom sh import fc_match\nfrom itertools import chain\n\nfonts = ['IBM Plex Mono', 'Noto Sans Mono', 'Noto Sans Mono CJK TC', 'Symbola', 'Material Icons']\nfont_offset = [0, 0, -2, 2, 2]\nfont_size=8\n\nranges = []\n\ndef getSymbols(font):\n result = []\n ranges = fc_match(font, format='%{charset}').split(' ')\n\n for r in ranges:\n if '-' in r:\n start, end = map(lambda x: int(x, 16), r.split('-'))\n result.append(range(start, end))\n else:\n result.append([int(r, 16)])\n\n return set(chain(*result))\n\nfor font in fonts:\n ranges.append(getSymbols(font))\n\nlastfont = -1\n\nwhile True:\n for char in input():\n for i, font in enumerate(fonts):\n if ord(char) in ranges[i]: \n if i == lastfont or lastfont == -1:\n print(char, end=\"\")\n lastfont=i\n break\n else:\n print(\"^fn()\", sep=\"\", end=\"\")\n if font_offset[lastfont] != 0:\n print(\"^p(;\", -font_offset[lastfont], ')', sep=\"\", end=\"\")\n\n if i == 0:\n print(char, end=\"\")\n else:\n if font_offset[i] != 0:\n print(\"^p(;\", font_offset[i], ')', sep=\"\", end=\"\")\n\n print(\"^fn(\", font, \":size=\", str(font_size), \")\", char, sep=\"\", end=\"\")\n lastfont=i\n break\n print(flush=True)\n","sub_path":".config/herbstluftwm/symbols.py","file_name":"symbols.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"39840955","text":"import os\nimport json\nimport re\nimport string\nimport random\n\nfrom rpitts import say\n\nfrom gmusicapi import Mobileclient\n\nimport pafy\n\nfrom random import shuffle\n\nfrom settings import readsettings, writesettings\nfrom db import (create_db_connection, close_db_connection,\n commit_db_connection, create_db_table,\n insert_db_table, drop_db_table, read_db_table)\n\nfrom mpvplayer import mpvplayergetvolume, mpvplayer, mpvplayerstop, mpvplayercycle, mpvplayergetskip, mpvplayersetskip\n\n#Read settings from gmusicplayer.json\ngoogleuserid=readsettings('gmusicplayer','googleuserid')\ngooglepasswd=readsettings('gmusicplayer','googlepasswd')\n\n#YouTube API Constants\nDEVELOPER_KEY = readsettings('youtubeplayer','apikey')\nYOUTUBE_API_SERVICE_NAME = 'youtube'\nYOUTUBE_API_VERSION = 'v3'\n\n#API settings\ngmapi = Mobileclient()\nlogged_in = gmapi.login(googleuserid, googlepasswd, Mobileclient.FROM_MAC_ADDRESS)\n\npafy.set_api_key(DEVELOPER_KEY)\n\nglobal musicplaylisttype\nmusicplaylisttype='gmusic'\n\n#To remove punctuations from query string.\nremovepunct = str.maketrans('', '', string.punctuation)\n\n#Random id generation for station generator\ndef id_generator(size=6, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n#Clear current playlist\ndef clearplaylists():\n if os.path.isfile(\"gmusicplaylist.json\"):\n os.remove('gmusicplaylist.json')\n\n#Get songs from google music library and save to database\ndef getsongsfromlibraryandsavetodb(tablename):\n songs_library = gmapi.get_all_songs()\n for i in range(0,len(songs_library)):\n song_items=[]\n columns = sorted(songs_library[i].keys())\n requiredcolumns = ('album','albumArtist', 'id', 'title')\n dbcolumns=list(filter(lambda x: x in requiredcolumns, columns))\n for j in dbcolumns:\n song_row = songs_library[i][j]\n if (j == 'id'):\n song_items.append(song_row)\n else:\n song_items.append(song_row.lower().translate(removepunct))\n query = \"insert into {0} (album, albumArtist, id, title) values (?{1})\"\n query = query.format(tablename, \",?\" * (len(requiredcolumns)-1))\n insert_db_table(tablename,query,song_items)\n\n#Get songs from playlists in google music library and save to database\ndef getsongsfromplaylistandsavetodb(tablename):\n playlists_library = gmapi.get_all_user_playlist_contents()\n for playlistitem in playlists_library:\n playlistname = playlistitem['name'].lower()\n tracks_library=playlistitem['tracks']\n for i in range(0,len(tracks_library)):\n songs_library=tracks_library[i]['track']\n song_id=tracks_library[i]['trackId']\n song_items=[]\n song_items.append(playlistname.lower().translate(removepunct))\n song_items.append(song_id)\n columns = sorted(songs_library.keys())\n requiredcolumns = ('name','trackId','album','albumArtist','title')\n dbcolumns=list(filter(lambda x: x in requiredcolumns, columns))\n for j in dbcolumns:\n song_row = songs_library[j]\n song_items.append(song_row.lower().translate(removepunct))\n query = \"insert into {0} (name, id, album, albumArtist, title) values (?{1})\"\n query = query.format(tablename, \",?\" * (len(requiredcolumns)-1))\n insert_db_table(tablename,query,song_items)\n\n#Function to save stations data to table in database\ndef getstationsandsavetodb(tablename):\n stations_library = gmapi.get_all_stations()\n for stationitem in stations_library:\n station_items=[]\n station_name = stationitem['name'].lower().translate(removepunct)\n station_id = stationitem['id']\n station_items.append(station_name)\n station_items.append(station_id)\n query = \"insert into {0} (name, id) values (?{1})\"\n query = query.format(tablename, \",?\")\n insert_db_table(tablename,query,station_items)\n\n#Save genres data to database\ndef getgenresandsavetodb(tablename):\n genres_library=gmapi.get_genres()\n for genresitem in genres_library:\n genres_items=[]\n genres_name = genresitem['name'].lower().translate(removepunct)\n genres_id = genresitem['id']\n genres_items.append(genres_name)\n genres_items.append(genres_id)\n query = \"insert into {0} (name, id) values (?{1})\"\n query = query.format(tablename, \",?\")\n insert_db_table(tablename,query,genres_items)\n\n#Save podcast data to database\ndef getpodcastsandsavetodb(tablename):\n podcast_library=gmapi.get_all_podcast_episodes(incremental=False, include_deleted=None, updated_after=None)\n for i in range(0,len(podcast_library)):\n podcast_items=[]\n podcast_name=podcast_library[i]['seriesTitle']\n podcast_episode=podcast_library[i]['episodeId']\n podcast_time=podcast_library[i]['publicationTimestampMillis']\n podcast_items=[podcast_name,podcast_episode,podcast_time]\n query = \"insert into {0} (name, id, time) values (?{1})\"\n query = query.format(tablename, \",?,?\")\n insert_db_table(tablename,query,podcast_items)\n\n\n#Update songs list json from your Google Play Music Library\n#https://play.google.com/music/listen?authuser&u=0#/albums\ndef updategmusiclibrary():\n try:\n create_db_connection('gmusiclibrary.db')\n drop_db_table('gmusicsongs')\n drop_db_table('gmusicplaylists')\n drop_db_table('gmusicstations')\n drop_db_table('gmusicgenres')\n drop_db_table('gmusicpodcasts')\n create_db_table('gmusicsongs',['album','albumArtist','id','title'])\n getsongsfromlibraryandsavetodb('gmusicsongs')\n create_db_table('gmusicplaylists',['name','id','album','albumArtist','title'])\n getsongsfromplaylistandsavetodb('gmusicplaylists')\n create_db_table('gmusicstations',['name','id'])\n getstationsandsavetodb('gmusicstations')\n create_db_table('gmusicgenres',['name','id'])\n getgenresandsavetodb('gmusicgenres')\n create_db_table('gmusicpodcasts',['name','id', 'time'])\n getpodcastsandsavetodb('gmusicpodcasts')\n commit_db_connection()\n close_db_connection()\n return True\n except Exception:\n return False\n\n#creates playlist from db\ndef creategmusicplaylist(**kwargs):\n clearplaylists()\n global musicplaylisttype\n musicplaylisttype='gmusic'\n song = kwargs.get('song', None)\n artist = kwargs.get('artist', None)\n album = kwargs.get('album', None)\n playlist = kwargs.get('playlist', None)\n podcast = kwargs.get('podcast', None)\n if 'playlist' in kwargs and playlist is not None:\n dbtable = kwargs.get('dbtable', 'gmusicplaylists')\n elif 'podcast' in kwargs and podcast is not None:\n dbtable = kwargs.get('dbtable', 'gmusicpodcasts')\n else:\n dbtable = kwargs.get('dbtable', 'gmusicsongs')\n create_db_connection('gmusiclibrary.db')\n querystring = \"SELECT id FROM \"+dbtable\n if (artist is not None) or (album is not None) or (song is not None) or (playlist is not None) or (podcast is not None):\n querystring = querystring + \" WHERE\"\n if (artist is not None):\n querystring = querystring + \" albumArtist LIKE '%\"+artist.lower().translate(removepunct).strip()+\"%' AND\"\n if (album is not None):\n querystring = querystring + \" album LIKE '%\"+album.lower().translate(removepunct).strip()+\"%' AND\"\n if (song is not None):\n querystring = querystring + \" title LIKE '%\"+song.lower().translate(removepunct).strip()+\"%' AND\"\n if (playlist is not None):\n querystring = querystring + \" name LIKE '%\"+playlist.lower().translate(removepunct).strip()+\"%' AND\"\n if (podcast is not None):\n querystring = querystring + \" name LIKE '%\"+podcast.lower().translate(removepunct).strip()+\"%' AND\"\n querystring = querystring + \" id IS NOT NULL\"\n if (podcast is not None):\n querystring = querystring + \" ORDER BY time DESC\"\n querystring = querystring + \";\"\n songs_ids = read_db_table(querystring)\n playlist=[]\n for song in songs_ids:\n playlist.append(song[0])\n close_db_connection()\n if playlist:\n with open('gmusicplaylist.json', 'w') as output_file:\n json.dump(playlist, output_file)\n\n#Create a playlist from station\ndef generateplaylistfromstation(station_id):\n clearplaylists()\n global musicplaylisttype\n musicplaylisttype='gmusic'\n station_tracks = gmapi.get_station_tracks(station_id, num_tracks=25, recently_played_ids=None)\n song_items = []\n for i in range(0,len(station_tracks)):\n song_id=station_tracks[i]['storeId']\n song_items.append(song_id)\n with open('gmusicplaylist.json', 'w') as output_file:\n json.dump(song_items, output_file)\n\n#Create a playlist from genre\ndef generateplaylistfromgenre(genreid):\n station_name = genreid + id_generator()\n station_id = gmapi.create_station(station_name,genre_id=genreid)\n generateplaylistfromstation(station_id)\n\n#Genreates playlist from google music\ndef generategmusicplaylist(**kwargs):\n station = kwargs.get('station', None)\n genre = kwargs.get('genre', None)\n if 'station' in kwargs:\n dbtable = kwargs.get('dbtable', 'gmusicstations')\n else:\n dbtable = kwargs.get('dbtable', 'gmusicgenres')\n create_db_connection('gmusiclibrary.db')\n querystring = \"SELECT id FROM \"+dbtable\n if (station is not None) or (genre is not None):\n querystring = querystring + \" WHERE\"\n if (station is not None):\n querystring = querystring + \" name LIKE '%\"+station.lower().translate(removepunct).strip()+\"%' AND\"\n if (genre is not None):\n querystring = querystring + \" name LIKE '%\"+genre.lower().translate(removepunct).strip()+\"%' AND\"\n querystring = querystring + \" id IS NOT NULL;\"\n item_ids = read_db_table(querystring)\n for item in item_ids:\n if (station is not None):\n generateplaylistfromstation(item[0])\n else:\n generateplaylistfromgenre(item[0])\n close_db_connection()\n\n#Search google music if no match found in database\ndef searchgmusic(**kwargs):\n clearplaylists()\n global musicplaylisttype\n musicplaylisttype='gmusic'\n song = kwargs.get('song', None)\n artist = kwargs.get('artist', None)\n album = kwargs.get('album', None)\n playlist = kwargs.get('playlist', None)\n station = kwargs.get('station', None)\n podcast = kwargs.get('podcast', None)\n situation = kwargs.get('sitaution', None)\n video = kwargs.get('video', None)\n searchquery=''\n if (song is not None):\n searchquery=searchquery+\" \"+song\n if (artist is not None):\n searchquery=searchquery+\" \"+artist\n if (album is not None):\n searchquery=searchquery+\" \"+album\n if (playlist is not None):\n searchquery=searchquery+\" \"+playlist\n if (station is not None):\n searchquery=searchquery+\" \"+station\n if (podcast is not None):\n searchquery=searchquery+\" \"+podcast\n searchquery=searchquery.strip()\n search_results=gmapi.search(searchquery,max_results=10)\n song_hits = search_results['song_hits']\n album_hits = search_results['album_hits']\n artist_hits = search_results['artist_hits']\n playlist_hits = search_results['playlist_hits']\n podcast_hits = search_results['podcast_hits']\n station_hits = search_results['station_hits']\n situation_hits = search_results['situation_hits']\n video_hits = search_results['video_hits']\n if (song is not None and not(len(song_hits) == 0)):\n song_ids=[]\n for i in range(0,len(song_hits)):\n songs_list=song_hits[i]['track']\n song_ids.append(songs_list['storeId'])\n if song_ids:\n with open('gmusicplaylist.json', 'w') as output_file:\n json.dump(song_ids, output_file)\n elif (album is not None and not(len(album_hits) == 0)):\n album_id=album_hits[0]['album']['albumId']\n album_item=gmapi.get_album_info(album_id, include_tracks=True)\n album_tracks=album_item['tracks']\n song_ids=[]\n for i in range(0,len(album_tracks)):\n song_id=album_tracks[i]['nid']\n song_ids.append(song_id)\n if song_ids:\n with open('gmusicplaylist.json', 'w') as output_file:\n json.dump(song_ids, output_file)\n elif (artist is not None and not(len(artist_hits) == 0)):\n artist_id=artist_hits[0]['artist']['artistId']\n artist_item=gmapi.get_artist_info(artist_id, max_top_tracks=50)\n artist_tracks=artist_item['topTracks']\n song_ids=[]\n for i in range(0,len(artist_tracks)):\n song_id=artist_tracks[i]['nid']\n song_ids.append(song_id)\n if song_ids:\n with open('gmusicplaylist.json', 'w') as output_file:\n json.dump(song_ids, output_file)\n elif (station is not None and not(len(station_hits) == 0)):\n station_seed = station_hits[0]['station']['seed']\n song_ids=[]\n for key, value in station_seed.items():\n if key.lower().endswith('id'):\n seed_id = value\n if (key == 'trackId'):\n song_ids.append(seed_id)\n if song_ids:\n with open('gmusicplaylist.json', 'w') as output_file:\n json.dump(song_ids, output_file)\n station_id = None\n elif (key == 'artistId'):\n station_id = gmapi.create_station(searchquery,artist_id=seed_id)\n elif (key == 'albumId'):\n station_id = gmapi.create_station(searchquery,album_id=seed_id)\n else:\n station_id = None\n if ( station_id is not None ):\n station_tracks = gmapi.get_station_tracks(station_id, num_tracks=25)\n for i in range(0,len(station_tracks)):\n song_ids.append(station_tracks[i]['storeId'])\n if song_ids:\n with open('gmusicplaylist.json', 'w') as output_file:\n json.dump(song_ids, output_file)\n elif (not(len(video_hits) == 0)):\n musicplaylisttype='youtube'\n video_ids=[]\n for i in range(0,len(video_hits)):\n video_ids.append(video_hits[i]['youtube_video']['id'])\n if video_ids:\n with open('gmusicplaylist.json', 'w') as output_file:\n json.dump(video_ids, output_file)\n else:\n say('No results found')\n\n#Generate song url from song_id\ndef getgmusicsongurl(song_id):\n if gmapi.is_subscribed:\n try:\n if song_id.startswith('D'):\n song_url = gmapi.get_podcast_episode_stream_url(song_id)\n else:\n song_url = gmapi.get_stream_url(song_id)\n except Exception:\n song_url = None\n else:\n station_name = id_generator()\n station_id = gmapi.create_station(station_name,track_id=song_id)\n station_info = gmapi.get_station_info(station_id, num_tracks=25)\n session_token = station_info['sessionToken']\n station_tracks = station_info['tracks']\n for i in range(0,len(station_tracks)):\n if (station_tracks[i]['storeId'] == song_id):\n wentry_id = station_tracks[i]['wentryid']\n try:\n song_url=gmapi.get_station_track_stream_url(song_id, wentry_id, session_token)\n except Exception:\n song_url = None\n return song_url\n\n#Get url from youtube from video_id\ndef getyoutubesongurl(video_id):\n youtube_url=\"http://www.youtube.com/watch?v=\" + video_id\n try:\n youtube_video = pafy.new(youtube_url)\n bestaudio = youtube_video.getbestaudio()\n song_url=bestaudio.url\n return song_url\n except Exception:\n return None\n\n#Identify youtube playlist type (Youtbue/GMusic\ndef getgmusicplaylisttype():\n if 'musicplaylisttype' in globals():\n return musicplaylisttype\n else:\n return None\n\n#Get streaming url from id\ndef getgmusicstreamurl(music_id):\n musicplaylisttype=getgmusicplaylisttype()\n if (musicplaylisttype == \"youtube\"):\n song_url=getyoutubesongurl(music_id)\n else:\n song_url=getgmusicsongurl(music_id)\n return song_url\n\n\n#Play music\ndef playgmusicplaylist(**kwargs):\n if os.path.isfile(\"gmusicplaylist.json\"):\n loop = kwargs.get('loop', False)\n playlistshuffle = kwargs.get('shuffle', False)\n while True:\n with open('gmusicplaylist.json','r') as input_file:\n songs_list=json.load(input_file)\n playlistlength=len(songs_list)\n if (playlistshuffle and playlistlength > 1):\n say('Shuffling playlist')\n shuffle(songs_list)\n tracknum = 0\n while tracknum < playlistlength:\n streamurl=getgmusicstreamurl(songs_list[tracknum])\n mpvplayer(mpvplayergetvolume(),streamurl)\n if (mpvplayergetskip() == 0):\n tracknum = tracknum + 1\n else:\n tracknum = tracknum + mpvplayergetskip()\n mpvplayersetskip(0)\n if (tracknum < 0 or tracknum >= playlistlength):\n say('End of playlist')\n if not gmusicplayercontinueplayback():\n break\n if loop == False:\n if os.path.isfile(\"gmusicplaylist.json\"):\n os.remove(\"gmusicplaylist.json\")\n break\n else:\n if not gmusicplayercontinueplayback():\n break\n else:\n say('Loop playing current playlist')\n else:\n say('Your playlist is empty')\n\n#Stop media player\ndef stopgmusicplayer():\n mpvplayerstop()\n clearplaylists()\n\n#Check if to continue playing current playlist.\ndef gmusicplayercontinueplayback():\n if os.path.isfile(\"gmusicplaylist.json\"):\n return True\n else:\n return False\n\n","sub_path":"gmusicplayer.py","file_name":"gmusicplayer.py","file_ext":"py","file_size_in_byte":18052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"224728535","text":"import matplotlib.pyplot as plt\nimport matplotlib\nfrom matplotlib.patches import Polygon\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n\n\ndef plot_one(x, y, name, name_x, name_y):\n \"\"\"\n Функция построения графиков\n :param x:\n :param y:\n :param name: Название графика\n :param name_x: Название оси X\n :param name_y: Название оси Y\n :return:\n \"\"\"\n plt.figure()\n plt.plot(x, y, color='red')\n plt.title(name)\n plt.xlabel(name_x)\n plt.ylabel(name_y)\n plt.grid(True)\n plt.show()\n\n\ndef plot_two(x, y1, y2, name, legend1, legend2):\n \"\"\"\n\n :param x:\n :param y1:\n :param y2:\n :param name:\n :return:\n \"\"\"\n plt.figure()\n plt.title(name)\n plt.plot(x, y1, label=legend1, color='red')\n plt.plot(x, y2, label=legend2, color='blue')\n plt.legend()\n plt.grid(True)\n plt.show()\n\n\ndef plot_contours(X, x, y, Z, name, name_x, name_y):\n plt.figure()\n x, Y = np.meshgrid(x, y)\n cp = plt.contourf(X, Y, Z, 100)\n plt.colorbar(cp)\n plt.title(name)\n plt.xlabel(name_x)\n plt.ylabel(name_y)\n plt.show()\n\n\ndef plot_3d(X, x, y, Z, name, name_x, name_y):\n fig = plt.figure()\n ax = Axes3D(fig)\n x, Y = np.meshgrid(x, y)\n surf = ax.plot_surface(X, Y, Z)\n # fig.colorbar(surf, shrink=0.75, aspect=15)\n plt.title(name)\n ax.set_xlabel(name_x)\n ax.set_ylabel(name_y)\n plt.show()\n\n # ax.title(name)\n\n\ndef plot_muzzle(layers):\n ax = plt.axes()\n tube = layers[0].tube\n xs, ys = tube.d.x, tube.d.y / 2\n line = plt.Line2D(xs, ys, marker='.', label='ствол')\n ax.add_line(line)\n line2 = plt.Line2D([xs[0], xs[-1]], [0, 0], linestyle='-.', linewidth=1)\n ax.add_line(line2)\n line3 = plt.Line2D([xs[0], xs[0]], [0, ys[0]], marker='.')\n ax.add_line(line3)\n line4 = plt.Line2D([xs[-1], xs[-1]], [0, ys[-1]], marker='.')\n ax.add_line(line4)\n ax.legend()\n plt.xlim((xs[0]-0.1, xs[-1]+0.1))\n plt.ylim((-0.05, max(ys)+0.05))\n plt.grid(True)\n plt.show()\n\n\ndef plot_layers_values(layers, attr_name, ax):\n lines = []\n cmap = matplotlib.pyplot.get_cmap('Set1')\n norm = matplotlib.colors.Normalize(vmin=0.,vmax=len(layers))\n for i, l in enumerate(layers):\n ys = getattr(l, attr_name)\n xs = l.x_c\n line = plt.Line2D(xs, ys, marker='.', label=f\"сетка {i}\", color=cmap(i))\n lines.append(ax.add_line(line))\n plt.legend()\n return lines\n","sub_path":"PB11/Invariants/Plot.py","file_name":"Plot.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"449772952","text":"from django.forms import ModelForm, Form, CharField, HiddenInput\nfrom courses.models import Submission\n\n\nclass SubmissionForm(ModelForm):\n class Meta:\n model = Submission\n fields = [\"title\", \"description\", \"data\"]\n\n\nclass SubscribeForm(Form):\n sender = CharField(label=\"Sender\", widget=HiddenInput())\n run_slug = CharField(label=\"Run\", widget=HiddenInput())\n","sub_path":"courses/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"548260107","text":"import re\n\ndict = {}\nlist1 = []\n\n\ndef counting(text):\n count = 0\n for letter in text:\n #print(letter)\n if letter in dict:\n dict[letter] += 1\n else:\n dict[letter] = 1\n\n list1 = list(dict.keys())\n list1.sort()\n #print(list1)\n for letter in list1:\n if not re.search(\"\\s\", letter):\n print(letter, dict[letter])\n\n\n\nprint(counting('hiS is String with Upper and lower case Letters'))","sub_path":"pythonwork/dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"630767287","text":"\"\"\"added metadata to files\n\nRevision ID: 9fc955710ef2\nRevises: c95e2380782e\nCreate Date: 2020-12-26 19:09:00.780640\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9fc955710ef2'\ndown_revision = 'c95e2380782e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.add_column('file', sa.Column('metadata', sa.Text(), nullable=True))\n\n\ndef downgrade():\n op.drop_column('file', 'metadata')","sub_path":"alembic/versions/9fc955710ef2_added_metadata_to_files.py","file_name":"9fc955710ef2_added_metadata_to_files.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"327282470","text":"import unittest\nfrom circularqueue import CircularQueue, QStack, digit_swap\n\nclass TestProject1(unittest.TestCase):\n\n def test_accessors(self):\n queue = CircularQueue()\n\n # manually set queue variables to test accessors\n queue.data = [5, 10, 15, None]\n queue.head = 0\n queue.tail = 3\n queue.size = 3\n\n assert queue.is_empty() == False\n assert len(queue) == 3\n assert queue.head_element() == 5\n\n def test_grow(self):\n queue = CircularQueue(5)\n queue.data = [0, 1, 2, 3, 4]\n queue.head = 0\n queue.tail = 0\n queue.size = 5\n\n queue.grow()\n\n assert queue.data == [0, 1, 2, 3, 4, None, None, None, None, None]\n # print(queue.data)\n # print(queue.tail)\n # print(queue.head)\n # print(queue.capacity)\n\n queue2 = CircularQueue(5)\n queue2.data = [10,20,30,40]\n queue2.head = 1\n queue2.tail = 1\n queue2.capacity = 4\n queue2.size = 4\n\n queue2.grow()\n\n # print(queue2.data)\n # print(queue2.tail)\n # print(queue2.head)\n # print(queue2.capacity)\n\n queue3 = CircularQueue(5)\n queue3.data = [10, 20, 30, 40, 50]\n queue3.head = 1\n queue3.tail = 0\n queue3.size = 5\n\n queue3.grow()\n\n # print(queue3.data)\n # print(queue3.tail)\n # print(queue3.head)\n # print(queue3.capacity)\n\n def test_shrink(self):\n queue = CircularQueue(8)\n queue.data = [0, 1, None, None, None, None, None, None]\n queue.size = 2\n queue.head = 0\n queue.tail = 2\n\n queue.shrink()\n\n assert queue.data == [0, 1, None, None]\n assert queue.size == 2\n assert queue.capacity == 4\n assert queue.head == 0\n assert queue.tail == 2\n\n # print(queue.data)\n # print(queue.tail)\n # print(queue.head)\n # print(queue.capacity)\n\n queue2 = CircularQueue(5)\n queue2.data = [10, 20, 30, 40, None, None, None, None, None, None, None, None, None, None, None, None]\n queue2.head = 1\n queue2.tail = 0\n queue2.size = 4\n queue2.capacity = 16\n\n queue2.shrink()\n\n # print(queue2.data)\n # print(queue2.tail)\n # print(queue2.head)\n # print(queue2.capacity)\n\n queue3 = CircularQueue(5)\n queue3.data = [4, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 6, 5]\n queue3.head = 16\n queue3.tail = 1\n queue3.size = 3\n queue3.capacity = 18\n\n queue3.shrink()\n\n # print(queue3.data)\n # print(\"tail: \", queue3.tail)\n # print(\"head: \", queue3.head)\n # print(\"size: \", queue3.size)\n # print(\"capacity: \", queue3.capacity)\n\n def test_enqueue(self):\n queue = CircularQueue(4)\n queue.data = [1, None]\n queue.size = 1\n queue.head = 0\n queue.tail = 0\n queue.capacity = 1\n\n queue.enqueue(1)\n queue.enqueue(2)\n queue.enqueue(3)\n\n ########\n\n queue = CircularQueue()\n\n queue.enqueue(10)\n queue.enqueue(20)\n queue.enqueue(30)\n\n assert queue.data == [10, 20, 30, None]\n assert queue.size == 3\n assert queue.head == 0\n assert queue.tail == 3\n assert queue.capacity == 4\n\n ##############\n\n queue = CircularQueue(4)\n queue.data = [3, None, 1, 2]\n queue.size = 3\n queue.head = 2\n queue.tail = 1\n\n queue.enqueue(4)\n\n # print(queue.data)\n # print(\"tail: \", queue.tail)\n # print(\"head: \", queue.head)\n # print(\"size: \", queue.size)\n # print(\"capacity: \", queue.capacity)\n\n def test_dequeue(self):\n queue = CircularQueue(6)\n\n for i in range(0, 5):\n queue.enqueue(i * 5)\n\n assert queue.data == [0, 5, 10, 15, 20, None]\n assert queue.size == 5\n assert queue.capacity == 6\n assert queue.head == 0\n assert queue.tail == 5\n\n queue.dequeue()\n\n assert queue.data == [None,5,10,15,20,None]\n assert queue.size == 4\n assert queue.capacity == 6\n assert queue.head == 1\n assert queue.tail == 5\n\n ###############\n\n queue = CircularQueue(0)\n queue.data = []\n queue.size = 0\n queue.head = 0\n queue.tail = 0\n\n queue.dequeue()\n queue.dequeue()\n queue.dequeue()\n\n # print(queue.data)\n # print(\"tail: \", queue.tail)\n # print(\"head: \", queue.head)\n # print(\"size: \", queue.size)\n # print(\"capacity: \", queue.capacity)\n\n def test_qstack_top(self):\n stack = QStack()\n\n #manually enqueue to test top accessor function\n stack.cq.enqueue(10)\n stack.size = 1\n\n assert stack.top() == 10\n\n stack.cq.enqueue(20)\n stack.size += 1\n\n assert stack.top() == 10\n\n def test_qstack_push(self):\n stack = QStack()\n stack.push(10)\n\n assert stack.top() == 10\n assert stack.size == 1\n\n stack.push(20)\n\n assert stack.top() == 20\n assert stack.size == 2\n\n # print(stack)\n\n def test_qstack_pop(self):\n stack = QStack()\n\n stack.push(1)\n stack.push(2)\n stack.push(3)\n\n assert stack.pop() == 3\n assert stack.top() == 2\n assert stack.size == 2\n\n def test_digit_swap(self):\n nums = \"5656\"\n replacements = 2\n assert digit_swap(nums, replacements) == 4 # example input 1\n\n nums = \"56787776646\"\n replacements = 1\n assert digit_swap(nums, replacements) == 5 # example input 2\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"(2) Algorithms and Data Structures (CSE 331)/Project 4 - Circular Queues/mimir_testcases.py","file_name":"mimir_testcases.py","file_ext":"py","file_size_in_byte":5798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"288976577","text":"import math as m\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import root_scalar,minimize\nimport scipy.integrate as integrate\nimport matplotlib.gridspec as gridspec\nimport pyswarm\n\n#All this stuff is dimensionless (See Sam's Thesis)\n\ndef SurfaceEnergy(Gamma,R):\n\treturn 2*Gamma/R\n\ndef ConstantFrankDensity(r,beta,K24,K33):\n\treturn FrankSwitch*(1/2)*(1-(np.sin(2*beta)/(2*r)))**2 + (K33/2)*(np.sin(beta)**4)/(r**2)\n\ndef ConstantFrankEnergy(beta,R,Rhat,K24,K33): \n\tE = (2/R**2) * integrate.quad(ConstantFrankDensity,0,Rhat,args=(0,K24,K33))[0]\n\tE += (2/R**2) * integrate.quad(ConstantFrankDensity,Rhat,R,args=(beta,K24,K33))[0]\n\tE -= (1+K24)*(np.sin(beta)**2)/(R**2)\n\n\treturn FrankSwitch*E\n\ndef LinearFrankDensity(r,alpha,K24,K33):\n\treturn FrankSwitch*(1/2)*(1-alpha-(np.sin(2*alpha*r)/(2*r)))**2 + (K33/2)*(np.sin(alpha*r)**4)/(r**2)\n\ndef LinearFrankEnergy(alpha,R,K24,K33): \n\tE = (2/R**2) * integrate.quad(LinearFrankDensity,0,R,args=(alpha,K24,K33))[0]\n\tE -= (1+K24)*(np.sin(alpha*R)**2)/(R**2)\n\n\treturn FrankSwitch*E\n\n##########\n\ndef ConstantPFCDensity(r,beta,eta):\n\treturn r*(4*np.pi**2 - (eta**2)*np.cos(beta)**2)**2\n\ndef ConstantPFCEnergy(R,Rhat,beta,Lambda,delta,eta,omega):\n\tE = (Lambda*delta**2)/(2*R**2) * integrate.quad(ConstantPFCDensity,0,Rhat,args=(0,eta))[0]\n\tE += (Lambda*delta**2)/(2*R**2) * integrate.quad(ConstantPFCDensity,Rhat,R,args=(beta,eta))[0]\n\tE += (omega*delta**2)/2 * ((delta**2)/2 -1)\n\n\treturn E\n\ndef LinearPFCDensity(r,alpha,eta):\n\treturn r*(4*np.pi**2 - (eta**2)*np.cos(alpha*r)**2)**2\n\ndef LinearPFCEnergy(R,alpha,Lambda,delta,eta,omega):\n\tE = (Lambda*delta**2)/(2*R**2) * integrate.quad(LinearPFCDensity,0,R,args=(alpha,eta))[0]\n\tE += (omega*delta**2)/2 * ((delta**2)/2 -1)\n\n\treturn E\n\n##########\n\ndef ConstantTotalFreeEnergy(x,R,Rhat,K24,K33,Gamma,Lambda,eta,omega):\n\tbeta=x[0]\n\tdelta=x[1]\n\treturn SurfaceEnergy(Gamma,R) + ConstantFrankEnergy(beta,R,Rhat,K24,K33) + ConstantPFCEnergy(R,Rhat,beta,Lambda,delta,eta,omega)\n\ndef LinearTotalFreeEnergy(x,R,K24,K33,Gamma,Lambda,eta,omega):\n\talpha=x[0]\n\tdelta=x[1]\n\treturn SurfaceEnergy(Gamma,R) + LinearFrankEnergy(alpha,R,K24,K33) + LinearPFCEnergy(R,alpha,Lambda,delta,eta,omega)\n\n\n\n\nbeta=0.3\nR0 = 100 * 10**(-9)\nRhat0 = 0.1*R0\n\nalpha=0.0027\n\nFrankSwitch=1\nK22_q_squared = 10 * 10**(-12) * (np.pi/(10**(-6)))**2\nq=np.pi/(10**(-6))\nK24 = 0.5\nK33 = 30\nmu = 30 * 10**6 / K22_q_squared\nGamma = 0.04\nLambda = 100#600\ndelta = 0.998\neta = 2*np.pi/0.985\nomega = 100#20\nLdelta=0.975\nLeta=2*np.pi/0.996\n\n\n\nRlist=np.linspace(10,250,num=100)\nRlist*=10**(-9)*q\nBetalist=[]\nCEList=[]\nAlphalist=[]\nLEList=[]\nCdeltalist=[]\nLdeltalist=[]\n\nfor R in Rlist:\n\tRhat=0.1*R\n\tx0=beta\n\t#x=minimize(ConstantTotalFreeEnergy,[x0,delta],args=(R,Rhat,K24,K33,Gamma,Lambda,eta,omega)).x\n\tx=pyswarm.pso(ConstantTotalFreeEnergy,[0,0],[1,1],args=(R,Rhat,K24,K33,Gamma,Lambda,eta,omega))[0]\n\tBetalist.append(x[0]*0.9)\n\tE=ConstantTotalFreeEnergy(x,R,Rhat,K24,K33,Gamma,Lambda,eta,omega)\n\tCEList.append(E)\n\tCdeltalist.append(x[1])\n\ty0=beta/(R*q)\n\t#y=minimize(LinearTotalFreeEnergy,x0,args=(R,K24,K33,Gamma,Lambda,Ldelta,Leta,omega)).x[0]\n\ty=pyswarm.pso(LinearTotalFreeEnergy,[0,0],[2,2],args=(R,K24,K33,Gamma,Lambda,Leta,omega))[0]\n\tE=LinearTotalFreeEnergy(y,R,K24,K33,Gamma,Lambda,Leta,omega)\n\tAlphalist.append(y[0]*R/2)\n\tLEList.append(E)\n\tLdeltalist.append(y[1])\n\nRlist/= (10**(-9)*q)\n\nfig,ax1 = plt.subplots()\nax2=ax1.twinx()\n\nax1.plot(Rlist,Betalist,color='grey',label='Constant Twist Phase')\nax1.plot(Rlist,Alphalist,color='black',label='Linear Twist Phase')\n#ax2.plot(Rlist,CEList,color='grey',linestyle='--',label='Free Energy')\n#ax2.plot(Rlist,LEList,color='black',linestyle='--',label='Free Energy')\nax2.plot(Rlist,Cdeltalist,color='grey',linestyle='--',label='D-Band Amplitude')\nax2.plot(Rlist,Ldeltalist,color='black',linestyle='--',label='D-Band Amplitude')\n#ax2.set_yscale('log')\n\nax1.set_xlabel('Fibril Radius (nm)')\nax1.set_ylabel(r'$\\langle \\psi^*(r) \\rangle$ (Average Twist Angle) (rad)')\n#ax2.set_ylabel('Equilibrium Free Energy (Dimensionless)')\nax2.set_ylabel('D-Band Amplitude (Dimensionless)')\n#ax1.legend(loc='best')\n#ax2.legend(loc='best')\nfig.legend(loc='best')\n\nplt.show()\n\n\n\n","sub_path":"Scripts/AlsoOldbutNewer/EquilibriumTwists.py","file_name":"EquilibriumTwists.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"23546780","text":"import deck\r\nimport loops\r\n\r\nclass Player:\r\n def __init__(self,name):\r\n self.name = name\r\n self.hand = []\r\n def starting_hand(self,decker,defuse):\r\n self.hand.append(defuse)\r\n for i in range(4):\r\n self.hand.append(decker.draw_top())\r\n def len_hand(self):\r\n return len(self.hand)\r\n def print_name(self):\r\n return(self.name)\r\n def show_hand(self):\r\n for i,k in enumerate(self.hand):\r\n print(str(i)+\"-\"+k.type)\r\n def draw(self,decker):\r\n self.hand.append(decker.draw_top())\r\n def play_card(self,decker,hand,pick,cards,attack,arr_players,turn_order):\r\n self.show_hand()\r\n print(\"Select a card\")\r\n played_card = loops.choose_loop(self.hand)\r\n if played_card.cat:\r\n x = 0\r\n for i in hand:\r\n if i.type == played_card.type:\r\n x += 1\r\n if x >= 1:\r\n if played_card.nope(arr_players,cards,turn_order):\r\n hand.remove(played_card)\r\n return True,False\r\n return played_card.steal(hand,self,arr_players,played_card)\r\n elif x == 0:\r\n print(\"You do not have two of those\")\r\n self.hand.append(played_card)\r\n return True,False\r\n else:\r\n if played_card == cards[2]:\r\n if played_card.nope(arr_players,cards,turn_order):\r\n return True,False\r\n return played_card.skip(attack,pick)\r\n elif played_card == cards[3]:\r\n if played_card.nope(arr_players,cards,turn_order):\r\n return True,False\r\n return played_card.attack(attack,pick)\r\n elif played_card == cards[4]:\r\n if played_card.nope(arr_players,cards,turn_order):\r\n return True,False\r\n return played.card.favor(hand,self,arr_players,played_card)\r\n elif played_card == cards[5]:\r\n if played_card.nope(arr_players,cards,turn_order):\r\n return True,False\r\n decker.shuffle()\r\n return True,False\r\n elif played_card == cards[12]:\r\n if played_card.nope(arr_players,cards,turn_order):\r\n return True,False\r\n played_card.see_future(decker)\r\n return pick,attack\r\n else:\r\n pick = True\r\n return pick,attack\r\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"34410676","text":"#Support Chinese\nimport jieba\n#Support Janpanese\nimport MeCab\n#Support Thai\nimport pythainlp\n#Support VietNamese\nfrom pyvi import ViTokenizer\n#Support Araby\nimport pyarabic.araby as araby\n#Support Korean \nfrom twkorean import TwitterKoreanProcessor\n\nimport chardet \nfrom config import *\n\nko_tokenizer = TwitterKoreanProcessor()\nja_tagger = MeCab.Tagger() # no additional dict, for local debug purpose\n\ndef tokenize(text, language):\n \"\"\" Tokenize text based on language \"\"\"\n\n if language in SPACE_SEPARATED_LANGUAGES:\n return text.split()\n elif language == 'vi':\n temp = ViTokenizer.tokenize(text)\n temp = temp.split()\n return temp\n elif language == 'th':\n return pythainlp.tokenize.word_tokenize(text)\n elif language == 'zh_tw' or language == 'zh_cn':\n return list(jieba.cut(text, HMM=False))\n elif language == 'ja':\n token = []\n string_ = ja_tagger.parse(text)\n for line in string_.split(\"\\n\"):\n if line.split()[0] == \"EOS\":\n break\n token.append(line.split()[0])\n token = [x for x in token]\n return token\n elif language == 'ar':\n return araby.tokenize(text)\n elif language == 'ko':\n result_temp = ko_tokenizer.tokenize_to_strings(text)\n result = []\n for word in result_temp:\n result.append(str(word))\n return result\n return None\n\ndef tokenize_join(text, language):\n tokenize_list = tokenize(text,language)\n result = ' '.join(tokenize_list)\n if type(result) is bytes:\n if chardet.detect(result)['encoding'] == 'UTF-16':\n result = result.decode('utf-16')\n elif chardet.detect(result)['encoding'] == 'cp1252':\n result = result.decode('cp1252')\n else:\n result = result.decode('utf-8')\n return result \n","sub_path":"Tokenize.py","file_name":"Tokenize.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"295992059","text":"def main(line_lists):\n flag = 0\n tmp_str = \"\"\n for line in line_lists:\n tmp_list = []\n splits = line.split(\",\")\n for num in range(0, len(splits)):\n if flag == 1:\n if splits[num].count('\"') == 1:\n tmp_str += \",\" + str(splits[num])\n tmp_list.append(tmp_str)\n tmp_str = \"\"\n flag = 0\n else:\n tmp_str += \",\" + str(splits[num])\n elif splits[num].count('\"') == 1:\n tmp_str = str(splits[num])\n flag = 1\n else:\n tmp_list.append(splits[num])\n print(\"\\t\".join(tmp_list).replace('\"',''))\n \n \n\nif __name__ == '__main__':\n fasta_list = []\n while True:\n try:\n fasta_list.append(str(input()).rstrip()) \n except EOFError:\n break\n main(fasta_list)\n","sub_path":"biodataprograming/interm/csv_to_tsv.py","file_name":"csv_to_tsv.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"425914989","text":"# class file read from other python source code.\n\nimport subprocess\nimport os\n\nclass CurrentUser:\n\n # attributes\n __currentUser = []\n __currentUserNum = 0\n \n # constractor, make current user list\n def __init__(self, FLEX_PATH, FLEX_CMD):\n \n # get console info\n os.chdir(FLEX_PATH)\n outputOfFlexnet = subprocess.Popen(FLEX_CMD, stdout=subprocess.PIPE,shell=True).communicate()[0].decode('Shift_JIS').split(\"\\r\\n\")\n \n # make current user list\n lastIndex = len(outputOfFlexnet) - 1\n for i, name in enumerate(outputOfFlexnet):\n if name.find(\"Device Name\") > -1: \n for j in range(i+2,lastIndex):\n if outputOfFlexnet[j].find(\"====\") > -1:\n break\n else: \n self.__currentUser.append(outputOfFlexnet[j])\n \n # define User Num\n self.__currentUserNum = len(self.__currentUser)\n \n # getter, No setter for this class\n def getCurrentUser(self):\n return self.__currentUser\n def getCurrentUserNum(self):\n return self.__currentUserNum","sub_path":"20190724/toybox_20190724_3.py","file_name":"toybox_20190724_3.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"383407654","text":"'''\nCreated on 2015.9.21\n\n@author: milo\n'''\n\ndef head(file,out):\n fin = open(file)\n fout = open(out,'w')\n count = 0\n for i in range(5):\n eachline = fin.readline()\n fout.write(eachline)\n fin.close()\n fout.close()\n\ntrf = \"train.csv\"\ntef = \"test.csv\"\n\nhead(trf,\"train_5.csv\")\nhead(tef,\"test_5.csv\")\n","sub_path":"springleaf/headcsv.py","file_name":"headcsv.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"368311716","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@author: changxin\n@mail: PyCharm\n@file: graph_bfs.py\n@time: 2018/5/13 20:18\n\"\"\"\nfrom collections import deque\nimport sys\n\nfrom basic.graph.graph import Graph, Node, State\n\n\nclass GraphBfs(Graph):\n\n def __init__(self, ):\n super(GraphBfs, self).__init__()\n self.pred = {} # 记录每个顶点的前驱顶点\n self.dist = {} # 记录起始顶点到当前顶点的最短路径\n self.queue = deque()\n\n def bfs(self, root, visit_fun):\n for node in self.nodes.values():\n self.pred[node.key] = -1\n self.dist[node.key] = sys.maxsize\n self.nodes[root].visit_state = State.visiting\n self.dist[root] = 0\n self.queue.append(self.nodes[root])\n\n while self.queue:\n node = self.queue.popleft()\n visit_fun(node)\n\n def bfs_visit(self, current_node):\n\n for node in current_node.adj_nodes.values():\n if node.visit_state == State.unvisited:\n self.pred[node.key] = current_node.key\n node.visit_state = State.visiting # 迭代的是字典的视图,修改会反映到字典实体上\n self.dist[node.key] = self.dist[current_node.key] + 1\n self.queue.append(node)\n current_node.visit_state = State.visited\n\n\nif __name__ == '__main__':\n graph = GraphBfs()\n graph.add_edge(0, 1)\n graph.add_edge(0, 2)\n graph.add_edge(1, 3)\n graph.add_edge(3, 4)\n graph.add_edge(4, 5)\n graph.add_edge(4, 6)\n graph.bfs(0, graph.bfs_visit)\n print(graph.pred)\n print(graph.dist)\n","sub_path":"algorithm/basic/graph/graph_bfs.py","file_name":"graph_bfs.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"10233254","text":"from django.shortcuts import render,get_object_or_404\nfrom django.http import HttpResponse\nfrom .models import Post,Category #导入对应模型\nimport markdown #用于内容页markdown\nfrom django.views.generic import ListView #用于类视图\nfrom django.db.models import Q #用于搜索\nfrom django.views import View\n\n\n\n#首页类视图\nclass IndexView(ListView):\n model = Post\n template_name = 'blog/index.html'\n context_object_name = 'post_list'\n #该值表示一页多少篇文章\n paginate_by = 7\n\n# 主页(以下为函数视图,改用上方的类视图,改后需要改urls.py)\n#def index(request):\n# post_list = Post.objects.all()\n# return render(request,'blog/index.html',context={\n# 'post_list': post_list\n# })\n# \n\n#文章详细页\ndef detail(request,pk):\n post = get_object_or_404(Post,pk=pk)\n # tag_list = Tag.objects.filter(pk=post)\n\n #阅读量+1\n post.increase_views()\n \n post.body = markdown.markdown(post.body,extensions=[\n 'markdown.extensions.extra', # 包含 缩写、表格等常用扩展\n 'markdown.extensions.codehilite', # 语法高亮扩展\n 'markdown.extensions.toc', #目录扩展\n ])\n # post.body = md.convert(post.body)\n # post.toc = md.toc\n return render(request,'blog/detail.html',context={\n 'post':post,\n })\n\n#分类页\n# class CategoryView(ListView):\n# model = Post\n# template_name = 'blog/list.html'\n# context_object_name = 'post_list'\n# paginate_by = 5\n\n# def get_queryset(self):\n# cate = get_object_or_404(Category,pk=self.kwargs.get('pk'))\n# return super(CategoryView,self).get_queryset().filter(category=cate)\n\n#上方为类视图,下面为普通,功能类似\ndef category(request,pk):\n cate = get_object_or_404(Category,pk=pk)\n post_list = Post.objects.filter(category=cate)\n paginate_by = 5\n return render(request,'blog/list.html',context={\n 'post_list':post_list,\n 'cate':cate #类目名称\n })\n \n\n\n#标签页\n# def tag(request,pk):\n# t = get_object_or_404(Tag,pk=pk)\n# post_list = Post.objects.filter(tags=t)\n# return render(request,'blog/list.html',context={\n# 'post_list':post_list,\n# 'cate':\"标签项\" \n# })\ndef tag(request):\n t = request.GET.get('tag')\n post_list = Post.objects.filter(tag__name__in=[t])\n return render(request,'blog/list.html',{'post_list':post_list,\n 'cate':\"标签项\"})\n\n\n#搜索\ndef search(request):\n q = request.GET.get('keyboard')\n error_msg = ''\n\n if not q:\n error_msg = \"请输入关键词\"\n return render(request,'blog/list.html',{'error_msg':error_msg})\n\n post_list = Post.objects.filter(Q(title__icontains=q) | Q(body__icontains=q))\n return render(request,'blog/list.html',{'error_msg':error_msg,\n 'post_list':post_list,\n 'cate':\"搜索结果\"})\n\n# 特别推荐页\ndef recommend(request):\n post_list = Post.objects.filter(recommend=1)\n paginate_by = 18\n return render(request,'blog/recommend.html',context={\n 'post_list':post_list,\n })\n \n\n#点赞功能+1\nclass IncreaseLikesView(View):\n def post(self,request,*args,**kwargs):\n post = Post.objects.get(id=kwargs.get('id'))\n post.likes += 1\n post.save()\n return HttpResponse('success') \n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"271789480","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 11 23:29:38 2019\r\n\r\n@author: lenovo\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n#import matplotlib.pyplot as graph\r\n#import tensorflow as tf\r\n\r\n#from sklearn import datasets\r\n#from sklearn import metrics\r\n#from sklearn.svm import SVC\r\n\r\nsharefile = pd.read_csv('Sharefile.txt', sep=',')\r\narr= np.array(sharefile)\r\n#sharefile = pd.read_csv('Sharefile.txt',sep =',')\r\n#Output = sharefile.head(5)\r\n#graph.plot(Output,Output,label='linear')\r\n#print (Output)\r\n#DataShape = sharefile.columns\r\n#print(DataShape)\r\nYearHighSort = sharefile.sort_values(['Growth(%)','PriceDiff'], ascending = False)\r\nprint(YearHighSort)\r\nf = open(\"SortedSharefile.txt\", \"w\")\r\nf.write(str(YearHighSort))\r\nf.close()\r\nprint('--------------------------------------------')\r\nprint(arr)\r\nprint(arr[2,2])\r\n#print(arr.sum(axis=1))\r\n\r\n#ds = datasets.load_iris()\r\n#model = SVC()\r\n#model.fit(ds.data,ds.target)\r\n#print(model)\r\n#print(\"/n\")\r\n\r\n#expected = ds.target\r\n#predicted = model.predict(ds.data)\r\n#print(metrics.classification_report (expected,predicted))","sub_path":"PandaProgram (withSortingMultiple&Filefuction).py","file_name":"PandaProgram (withSortingMultiple&Filefuction).py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"278840089","text":"from django.shortcuts import render\nfrom webapp_basic.settings import EMAIL_HOST_USER\nfrom . import forms\nfrom django.core.mail import send_mail\n#from subscribe.forms import SubscribeForm\nfrom .models import Subscribe6\n# Create your views here.\n#DataFlair #Send Email\ndef subscribe6(request):\n form = forms.Subscribe6()\n if request.method == 'POST':\n form = forms.Subscribe6(request.POST)\n print(\"table: \",request.POST)\n if form.is_valid():\n form.save()\n\n subject = 'Thư mời dự tiệc đám cưới'\n message = 'Kính mời ' + str(form['name'].value()) +' đến dự buổi tiệc đám cưới vào lúc ' + str(form['time'].value()) + ' ngày ' + str(form['day'].value()) + ' tháng ' + str(form['month'].value()) + ' năm ' + str(form['year'].value()) + '. Rất mong ' + str(form['name'].value()) + ' sẽ đến góp vui.'\n recepient = str(form['email'].value())\n send_mail(subject,\n message, EMAIL_HOST_USER, [recepient], fail_silently = False)\n return render(request, 'subscribe6/success.html', {'recepient': recepient})\n return render(request, 'subscribe6/index.html', {'form':form})\n","sub_path":"subscribe6/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"390134399","text":"\"\"\"!\n\n@brief CCORE Wrapper for ant colony based algorithm for travelling salesman problem.\n\n@authors Andrei Novikov, Alexey Kukushkin (pyclustering@yandex.ru)\n@date 2014-2016\n@copyright GNU Public License\n\n@cond GNU_PUBLIC_LICENSE\n PyClustering is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n PyClustering is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n@endcond\n\n\"\"\"\n\nfrom pyclustering.core.wrapper import *;\n\nimport types;\n\n\nCITIES_DISTANCE_SET_BY_MATRIX = True\nCITIES_DISTANCE_SET_BY_LIST_OF_COORDINATES = False\n\n\nclass c_antcolony_tsp_parameters(Structure):\n \"\"\"\n double q;\n double ro;\n double alpha;\n double beta;\n double gamma;\n double initial_pheramone;\n unsigned int iterations;\n unsigned int ants_per_iteration;\n \n \"\"\"\n _fields_ = [(\"q\" , c_double),\n (\"ro\" , c_double),\n (\"alpha\" , c_double),\n (\"beta\" , c_double),\n (\"gamma\" , c_double),\n (\"qinit_pheramone\" , c_double),\n (\"iterations\" , c_uint),\n (\"ants_per_iteration\" , c_uint) ];\n\n\nclass c_antcolony_tsp_objects(Structure):\n \"\"\"\n unsigned int size;\n unsigned int dimension;\n double *data;\n \n \"\"\"\n _fields_ = [(\"size\" , c_uint),\n (\"dimension\" , c_uint),\n (\"data\" , POINTER(c_double)) ];\n\n\nclass c_antcolony_tsp_matrix(Structure):\n \"\"\"\n unsigned int size;\n double **data;\n \n \"\"\"\n _fields_ = [(\"size\" , c_uint),\n (\"data\" , POINTER(POINTER(c_double))) ];\n \n\nclass c_antcolony_tsp_result(Structure):\n \"\"\"\n unsigned int size;\n double path_length;\n unsigned int *cities_num;\n \n \"\"\"\n _fields_ = [(\"size\" , c_uint),\n (\"path_length\" , c_double),\n (\"object_sequence\" , POINTER(c_uint)) ];\n\n\n\ndef get_algo_params(params):\n \n algorithm_params = c_antcolony_tsp_parameters();\n algorithm_params.q = c_double(params.q);\n algorithm_params.ro = c_double(params.ro);\n algorithm_params.alpha = c_double(params.alpha);\n algorithm_params.beta = c_double(params.beta);\n algorithm_params.gamma = c_double(params.gamma);\n algorithm_params.qinit_pheramone = c_double(params.qinit_pheramone);\n algorithm_params.iterations = c_uint(params.iterations);\n algorithm_params.ants_per_iteration = c_uint(params.ants_per_iteration);\n \n algorithm_params = pointer(algorithm_params);\n \n return algorithm_params\n\n\ndef antcolony_tsp_prepare_matrix(matrix):\n dist_matrix = c_antcolony_tsp_matrix()\n \n dist_matrix.size = len(matrix)\n \n p_dist = (POINTER(c_double) * dist_matrix.size)();\n \n for i in range(dist_matrix.size):\n tmp_p_dist = (c_double * dist_matrix.size)();\n for j in range(dist_matrix.size):\n tmp_p_dist[j] = matrix[i][j];\n \n p_dist[i] = cast(tmp_p_dist, POINTER(c_double));\n \n dist_matrix.data = cast(p_dist, POINTER(POINTER(c_double)));\n dist_matrix = pointer(dist_matrix)\n \n return dist_matrix\n \n \ndef antcolony_tsp_prepare_cities_list(cities):\n dimension = len(cities[0]);\n \n cities_coord = c_antcolony_tsp_objects();\n cities_coord.size = c_uint(len(cities) * dimension);\n cities_coord.dimension = c_uint(dimension);\n \n cities_coord.data = (c_double * cities_coord.size)();\n \n for i in range(0, cities_coord.size):\n cities_coord.data[i] = cities[i // dimension][i % dimension];\n \n cities_coord = pointer(cities_coord);\n \n return cities_coord\n\n\ndef antcolony_tsp_process(cities, params, citiesDistRepresent = CITIES_DISTANCE_SET_BY_LIST_OF_COORDINATES):\n algorithm_params = get_algo_params(params)\n \n ccore = cdll.LoadLibrary(PATH_DLL_CCORE_64);\n \n if citiesDistRepresent == CITIES_DISTANCE_SET_BY_MATRIX:\n cities_coord = antcolony_tsp_prepare_matrix(cities)\n result_pointer = ccore.ant_colony_tsp_process_by_matrix(cities_coord, algorithm_params);\n else:\n cities_coord = antcolony_tsp_prepare_cities_list(cities)\n result_pointer = ccore.ant_colony_tsp_process(cities_coord, algorithm_params);\n \n result = cast(result_pointer, POINTER(c_antcolony_tsp_result))[0];\n \n return (result_pointer, result);\n\n\ndef antcolony_tsp_destroy(tsp_result_pointer):\n ccore = cdll.LoadLibrary(PATH_DLL_CCORE_64);\n ccore.ant_colony_tsp_destroy(tsp_result_pointer);\n","sub_path":"pyclustering/core/antcolony_tsp_wrapper.py","file_name":"antcolony_tsp_wrapper.py","file_ext":"py","file_size_in_byte":5355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"115981913","text":"import argparse\ndef km(clean_data):\n import joblib\n from sklearn import metrics\n import pandas as pd\n from numpy.random import seed\n seed(1)\n import tensorflow as tf\n tf.random.set_seed(221)\n from tensorflow import keras\n from tensorflow.keras.models import Sequential\n from tensorflow.keras.layers import Dense, Dropout, BatchNormalization\n data = joblib.load(clean_data)\n x_train = data['X_train']\n y_train = data['Y_train']\n x_test = data['X_test']\n y_test = data['Y_test']\n\n keras_model = Sequential()\n keras_model.add(Dense(100, activation='relu', input_dim=13))\n keras_model.add(BatchNormalization())\n keras_model.add(Dense(40, activation='relu'))\n keras_model.add(Dropout(0.2))\n keras_model.add(Dense(1, activation='sigmoid'))\n\n keras_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n keras_model.fit(x_train, y_train, epochs=100)\n\n y_pred=keras_model.predict_classes(x_test)\n \n eval_results = keras_model.evaluate(x_test,y_test, verbose=0) \n loss = round(eval_results[0],4)\n accuracy = round((eval_results[1]), 2)\n print(\"\\nLoss, accuracy on test data: \")\n print(\"%0.4f %0.2f%%\" % (eval_results[0], \\\n eval_results[1]*100))\n model_json = keras_model.to_json()\n weights = keras_model.save_weights('km.h5')\n report = metrics.classification_report(y_test, y_pred, output_dict=True)\n df_classification_report = pd.DataFrame(report).transpose()\n print(df_classification_report)\n\n keras_metrics = {'loss':loss, 'test':accuracy, 'report':df_classification_report, 'model': [model_json, weights]}\n joblib.dump(keras_metrics,'keras_metrics')\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--clean_data')\n args = parser.parse_args()\n km(args.clean_data)\n","sub_path":"heart disease/pipeline components/keras_model/km.py","file_name":"km.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"454779152","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 24 11:16:49 2017\r\n\r\n@author: costa\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\na=4.25*2*np.pi/360 # angle alpha en rd\r\nb=5.885*2*np.pi/360 # angle béta en rd\r\nrf=0.270 # rayon sur plate forme fixe\r\nrm=0.195 # rayon sur plate forme mobile\r\nh=0.276 # hauteur de référence (hauteur lorsque les vérins sont rentrés)\r\n\r\ndef longueurs(x,y,z,theta1,theta2,theta3):\r\n xf=np.zeros(6)\r\n yf=np.zeros(6)\r\n zf=np.zeros(6)\r\n xm=np.zeros(6)\r\n ym=np.zeros(6)\r\n zm=np.zeros(6)\r\n alpha=np.zeros(6)\r\n beta=np.zeros(6)\r\n\r\n u=0\r\n v=1\r\n \r\n #Calcul des angles alpha\r\n for i in range(1,7):\r\n if i%2!=0:\r\n alpha[i-1]=u*2*np.pi/3+a\r\n u=u+1\r\n else:\r\n alpha[i-1]=v*2*np.pi/3-a\r\n v=v+1\r\n\r\n #Calcul des angles beta\r\n for i in range(1,7):\r\n if i%2!=0:\r\n beta[i-1]=(u+1)*2*np.pi/3-b\r\n u=u+1\r\n else:\r\n beta[i-1]=v*2*np.pi/3+b\r\n v=v+1\r\n\r\n #Coordonnées de OFBi\r\n xf=rf*np.cos(beta)\r\n yf=rf*np.sin(beta)\r\n zf=0*np.cos(beta)\r\n \r\n #Coordonnées de OMAi dans le repère RM\r\n xm=rm*np.cos(alpha)\r\n ym=rm*np.sin(alpha)\r\n\r\n #Coordonnées de OMAi dans le repère RF\r\n xmf=(-np.sin(theta1)*np.sin(theta2)*np.sin(theta3)+np.cos(theta1)*np.cos(theta3))*xm-np.sin(theta1)*np.cos(theta2)*ym+(np.sin(theta1)*np.sin(theta2)*np.cos(theta3)+np.cos(theta1)*np.sin(theta3))*zm\r\n ymf=(np.cos(theta1)*np.sin(theta2)*np.sin(theta3)+np.sin(theta1)*np.cos(theta3))*xm+np.cos(theta1)*np.cos(theta2)*ym +(-np.cos(theta1)*np.sin(theta2)*np.cos(theta3)+np.sin(theta1)*np.sin(theta3))*zm\r\n zmf=-(np.sin(theta3)*np.cos(theta2))*xm+np.sin(theta2)*ym+(np.cos(theta3)*np.cos(theta2))*zm\r\n\r\n #plt.plot(xf,yf)\r\n #plt.plot(xmf,ymf)\r\n #plt.axis('equal')\r\n\r\n #Coordonnées de BiAi dans le repère RF\r\n xt=xmf+x-xf\r\n yt=ymf+y-yf\r\n zt=zmf+z+h-zf\r\n \r\n #Normes des longueurs\r\n return np.sqrt(xt**2+yt**2+zt**2),xf,yf,zf,xmf,ymf,zmf\r\n\r\n# Exemple, rotation autour de z\r\n\r\ntemps=np.arange(0,5,0.01)\r\namplitude_z=0.2\r\namplitude_thetaz=np.pi/4\r\npulsation=5\r\n\r\nlong=[[]]\r\n\r\nx=0\r\ny=0\r\nz=0\r\ntheta1=np.pi/3\r\ntheta2=0\r\ntheta3=0\r\n\r\nfor t in temps:\r\n theta1=amplitude_thetaz*np.sin(pulsation*t)+np.pi/3\r\n if t==0:\r\n long=[longueurs(x,y,z,theta1,theta2,theta3)[0]]\r\n else:\r\n long=np.append(long,[longueurs(x,y,z,theta1,theta2,theta3)[0]],axis=0)\r\n\r\nfig = plt.figure(1)\r\nplt.plot(temps,long[:,0],temps,long[:,1],temps,long[:,2],temps,long[:,3],temps,long[:,4],temps,long[:,5])\r\n\r\n# Tracé d'une position en 3D\r\nlong_t=longueurs(0,0,0,np.pi/3,0,0) #position initiale\r\nxf,yf,zf,xmf,ymf,zmf=long_t[1],long_t[2],long_t[3],long_t[4],long_t[5],long_t[6]+h\r\nfig = plt.figure()\r\nax = plt.axes(projection='3d')\r\nax.plot(xf, yf, zf, '-b')\r\nax.plot(xmf, ymf, zmf, '-g')","sub_path":"S06 Cinématique du point/TP01 La cinématique des mécanismes/Ilot_04 Plateforme/06-TP01-I04.py","file_name":"06-TP01-I04.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"247497929","text":"# Create your views here.\nimport csv\n\nfrom beancounter.report_utils import departments,allocations\nfrom beancounter.report_utils import dept_report_csv,allocation_report_csv\n\nfrom django.http import HttpResponse,Http404\n\ndef report(request,report_type):\n # Create the response object with the appropriate CSV header\n response = HttpResponse(mimetype='text/csv')\n response['Content-Disposition'] = 'attachment; filename=util_report_by%s.csv'%report_type\n writer = csv.writer(response)\n header_values=None\n\n if report_type == 'department':\n header_values=departments()\n body=dept_report_csv(header_values)\n elif report_type=='allocation':\n header_values=allocations()\n body=allocation_report_csv(header_values)\n \n if header_values:\n headers=[ x for x in header_values ]\n headers.insert(0,\"Month\")\n writer.writerow(headers)\n for line in body:\n writer.writerow(line)\n else:\n raise Http404\n\n return response\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"500635066","text":"'''\r\n\r\nA hangman game by Justin Brown\r\nrex handled the drawing, I wrote the logic\r\n'''\r\nimport drawHangman\r\nimport turtle\r\nimport random\r\n\r\n\r\n\r\n\r\ndef main():\r\n \r\n #Do not change or remove code from here\r\n window = turtle.Screen()\r\n window.setup(400, 400, 200, 200)\r\n HG = turtle.Turtle()\r\n drawHangman.default(HG)\r\n #To here\r\n \r\n #Start your program below here You may still need other imports\r\n wordList = []\r\n guessNum = int(6)\r\n wordBank = open(\"data/wordbank.text\", \"w\")\r\n wordBank.write(\"python\\nwater\\nmonkey\\nsnake\\npumpkin\\nzebra\\nghost\\nzombie\\ndracula\")\r\n wordBank.close()\r\n \r\n wordBank = open(\"data/wordbank.text\", \"r\")\r\n for line in wordBank:\r\n if line == \"\":\r\n break\r\n else:\r\n wordList.append(line.strip(\"\\n\"))\r\n wordBank.close()\r\n \r\n play = True\r\n while play == True:\r\n print(\"Try to guess the word!\\nGuesses remaining:\", guessNum)\r\n gameWord = random.choice(wordList)\r\n hiddenString = [\"?\"] * len(gameWord)\r\n \r\n \r\n #print(wordList)\r\n #print(gameWord)\r\n print(\"\".join(hiddenString))\r\n \r\n while guessNum > 0:\r\n guess = input(\"Enter guess: \")\r\n guess.lower()\r\n \r\n for char in gameWord:\r\n if char == guess:\r\n print(\"Congratulations! You guessed a correct letter!\")\r\n index = gameWord.index(char)\r\n hiddenString[index] = guess\r\n if guess not in gameWord:\r\n guessNum = guessNum - 1\r\n print(\"Sorry that letter is not in the word! Guesses remaining:\", guessNum)\r\n if guessNum == 5:\r\n drawHangman.drawHead(HG)\r\n elif guessNum == 4:\r\n drawHangman.drawBody(HG)\r\n elif guessNum == 3:\r\n drawHangman.drawRightArm(HG)\r\n elif guessNum == 2:\r\n drawHangman.drawLeftArm(HG)\r\n elif guessNum == 1:\r\n drawHangman.drawLeftLeg(HG)\r\n elif guessNum == 0:\r\n drawHangman.drawRightLeg(HG)\r\n \r\n \r\n newString = \"\".join(hiddenString) \r\n print(newString)\r\n if newString == gameWord:\r\n print(\"Congratulations you won!\") \r\n break \r\n if guessNum <= 0:\r\n print(\"I'm sorry you have run out of guesses, the word was:\", gameWord)\r\n again = input(\"Would you like to play again? Yes or No: \") \r\n again.lower()\r\n if again == \"yes\":\r\n guessNum = 6\r\n hiddenString = \"\"\r\n \r\n print(\"\\n\\n\")\r\n drawHangman.reset(HG)\r\n \r\n #main()\r\n else:\r\n play = False\r\n print(\"Thank you for playing!\")\r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n #End of the main function\r\nmain()","sub_path":"hangManStudent/src/hangMan.py","file_name":"hangMan.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"35144601","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\ndef knap_sack(N, K):\r\n dp = {0: 0}\r\n for _ in range(N):\r\n W, V = map(int, input().split())\r\n temp = {}\r\n for k,v in dp.items():\r\n # 기존 item의 무게 (k) 와 새로운 item의 무게(W)의 합이 전체 무게(K)보다 작거나 같은 경우\r\n # 그리고, ? \r\n if k + W <= K and v + V > dp.get(k+W,0): # get(key가 없는경우, 'default'값 반환)\r\n temp[k + W] = v + V\r\n dp.update(temp)\r\n \r\n return max(dp.values())\r\n\r\n\r\nN, K = map(int, input().split())\r\nprint(knap_sack(N, K))\r\n\r\n","sub_path":"yoonhee/BOJ/20210329_12865_평범한배낭_OOO.py","file_name":"20210329_12865_평범한배낭_OOO.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"372764169","text":"import os\n#python script.py vima traces_microbenchmarks.txt configuration_files/sandy_vima.cfg _outro\n\nimport sys\nfilepath = sys.argv[2]\npath = '~/Experiment/benchmarks/traces/'\nbenchmark = sys.argv[1]\nconfig = sys.argv[3]\noutput = \"\"\nfolder = \"resultados\"\nsuffix = \"\"\n\nif os.path.exists(folder) == False: os.mkdir (folder)\n#if os.path.exists(folder+\"/\"+benchmark) == False: os.mkdir (folder+\"/\"+benchmark)\nif len(sys.argv) > 4: \n suffix = sys.argv[4]\n if os.path.exists(folder+\"/\"+benchmark+suffix) == False: os.mkdir (folder+\"/\"+benchmark+suffix)\nelse:\n\tif os.path.exists(folder+\"/\"+benchmark) == False: os.mkdir (folder+\"/\"+benchmark)\n\n\nwith open(filepath) as fp:\n for cnt, line in enumerate(fp):\n output += (\"./orcs -t {}{}/{} -c {} > {}/{}{}/{}.txt; \".format (path, benchmark, line.rstrip(), config, folder, benchmark, suffix, line.rstrip()))\n\nprint (output)\nos.system (output)\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"546181819","text":"\"\"\"\r\nQuestão A. O que o seguinte programa (dado na forma de pseucódigo) imprime?\r\nx = 2\r\ny = 5\r\nse y > 8 então\r\n y = y * 2\r\ncaso contrário,\r\n x = x * 2\r\nimprime (x + y)\r\nResposta: 9\r\n\"\"\"\r\n__author__ = 'Leonardo Vinicius Maciel aka Sephyros'\r\n\r\nx = 2\r\ny = 5\r\nif y > 8:\r\n y *= 2\r\nelse:\r\n x *= 2\r\nprint(\"Resposta: %d\" % (x + y))","sub_path":"PingMind/Python para Zumbis/Lista V/questao01.py","file_name":"questao01.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"44129886","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"logfile\")\n\n args = parser.parse_args()\n\n with open(args.logfile, \"r\") as logfile:\n steps = [[]]\n buffer_pos = [[]]\n buffer_neg = [[]]\n model_names = []\n for line in logfile:\n if \"pos_loss\" in line:\n buffer_pos[-1].append(float(line.split(\"pos_loss: \")[-1]))\n steps[-1].append(float(line.split(\"(\")[-1].split(\"/\")[0]))\n elif \"neg_loss\" in line:\n buffer_neg[-1].append(float(line.split(\"neg_loss: \")[-1]))\n elif \"Save model\" in line:\n model_names.append(line.split(\"/\")[-2])\n buffer_pos.append([])\n buffer_neg.append([])\n steps.append([])\n\n for s, v in zip(steps, buffer_pos):\n plt.plot(np.log10(s), np.log10(v))\n plt.xlabel(\"Step\")\n plt.ylabel(\"Loss\")\n plt.legend(model_names)\n plt.savefig(\"positive_loss.png\")\n plt.close()\n\n for s, v in zip(steps, buffer_neg):\n plt.plot(np.log10(s), np.log10(v))\n plt.xlabel(\"Step\")\n plt.ylabel(\"Loss\")\n plt.legend(model_names)\n plt.savefig(\"negative_loss.png\")\n plt.close()\n\n for s, v, n in zip(steps, buffer_pos, buffer_neg):\n plt.plot(np.log10(s), np.log10(np.array(v) + np.array(n)))\n plt.xlabel(\"Step\")\n plt.ylabel(\"Loss\")\n plt.legend(model_names)\n plt.savefig(\"overall_loss.png\")\n plt.close()\n\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"scripts/training/dglke_log_parser.py","file_name":"dglke_log_parser.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"397843167","text":"import numpy as np\nfrom enum import Enum\n\ndef IsInt(s):\n if isinstance(s, np.int32) or \\\n isinstance(s, np.int64) or \\\n isinstance(s, int):\n return True\n return False\n\ndef IsIntInString(s):\n if not isinstance(s, str):\n return 0\n try:\n int(s)\n return True\n except ValueError:\n return False\n\nclass InstTypes(Enum):\n DATA_HEADER = -1\n DATA_NAME_VAL = 0\n FUNC_HEADER = 1\n FUNC_RET = 2\n FUNC_COMMON = 3\n FUNC_NAME = 4\n START_HEADER = 5\n START_LABEL= 6\n START_NORMAL = 8\n START_ASSIGN = 9\n\nclass SectionType(Enum):\n DATA_HEADER = 0\n DATA = 1\n FUNCTION = 2\n START = 3\n\ndef IsTheHeaderOfDataSection():\n if section_type[0] == SectionType.DATA_HEADER:\n if len(line_items) != 2:\n return 0\n elif line_items[0] != 'section' or line_items[1] != '.data:':\n return 0\n else:\n section_type[0] = SectionType.DATA\n return 1\n return 0\n\ndef DetectDataInstruction():\n c = 20\n if len(line_items) == 2 and line_items[0] == 'section' and line_items[1] == '.functions:':\n section_type[0] = SectionType.FUNCTION\n instr_type[0] = InstTypes.FUNC_HEADER\n return 1\n elif len(line_items) == 2:\n if IsIntInString(line_items[1]):\n if IsIntInString(line_items[1]) <= 65536:\n instr_type[0] = InstTypes.DATA_NAME_VAL\n return 1\n else:\n return 0\n else:\n return 0\n else:\n return 0\n\ndef DetectFuncInstruction():\n if len(line_items) == 1:\n # Строка с именем ф-ции\n if len(line_items[0]) > 1 and line_items[0][-1] == ':':\n instr_type[0] = InstTypes.FUNC_NAME\n return 1\n elif line_items[0] == 'ret':\n instr_type[0] = InstTypes.FUNC_RET\n return 1\n else:\n return 0\n if len(line_items) == 2:\n if line_items[0] == 'section' and line_items[1] == '.start:':\n section_type[0] = SectionType.START\n instr_type[0] = InstTypes.START_HEADER\n return 1\n else:\n return 0\n elif len(line_items) == 5:\n instr_type[0] = InstTypes.FUNC_COMMON\n return 1\n\ndef IsAssignment():\n if(len(line_items) >= 3):\n sign = line_items[1]\n if sign == '=':\n return 1\n return 0\n\ndef DetectStartInstruction():\n # Метка\n if len(line_items) == 1:\n if line_items[0][-1] == ':':\n instr_type[0] = InstTypes.START_LABEL\n else:\n instr_type[0] = InstTypes.START_NORMAL\n return 1\n # Присвоение\n elif IsAssignment():\n instr_type[0] = InstTypes.START_ASSIGN\n return 1\n # Обычная операция\n elif len(line_items) >= 2:\n instr_type[0] = InstTypes.START_NORMAL\n return 1\n return 0\n\ndef IsDataSection():\n return section_type[0] == SectionType.DATA\n\ndef IsFuncSection():\n return section_type[0] == SectionType.FUNCTION\n\ndef IsStartSection():\n return section_type[0] == SectionType.START\n\n# Проверяет формат строки из ассемблерного кода\ndef LineIsCorrect():\n # Header\n if IsTheHeaderOfDataSection():\n return 1\n # Секция : .data\n elif IsDataSection():\n return DetectDataInstruction()\n # Секция : .functions\n elif IsFuncSection():\n return DetectFuncInstruction()\n # Секция : .start\n elif IsStartSection():\n return DetectStartInstruction()\n return 0\n\n# Возвращает: VM команду, приняв решение по формату ассемблерной инструкции\n# Типы инструкций:\n# - \"<имя_переменной><число>\"\n# - \"<имя_регистра><число>\"\n\ndef DecimalToHex(value):\n return [int(value) // 256, int(value) % 256]\n\ndef DataCommand():\n cmd = []\n if instr_type[0] == InstTypes.DATA_HEADER:\n return []\n elif instr_type[0] == InstTypes.DATA_NAME_VAL:\n names.setdefault(line_items[0], num_registers[0])\n var_idx_in_mem = names[line_items[0]]\n num_variables[0] += 1\n num_occupied_cells[0] += 1\n cmd.append(10)\n cmd.extend(DecimalToHex(var_idx_in_mem))\n cmd.extend(DecimalToHex(int(line_items[1])))\n return [cmd]\n\n# Возвращает: VM команду, приняв решение по формату ассемблерной инструкции\n# Типы инструкций:\n# - \"<имя_функции>\"\n# - \"<имя_функции>\"\n# - \"<имя_функции>\"\ndef FunctionCommand():\n if instr_type[0] == InstTypes.FUNC_HEADER:\n return [[]]\n\ndef MakeNormalCmd(operation):\n cmd = [operation_names[operation]]\n if operation == 'MOV' or operation == 'ADD':\n var1 = line_items[1]\n cmd.extend(DecimalToHex(names[var1]))\n var2 = line_items[3]\n if IsIntInString(var2):\n cmd.extend(DecimalToHex(var2))\n elif var2 in names:\n cmd.extend(DecimalToHex(names[var2]))\n elif operation == 'STOP':\n cmd.extend([0,0,0,0])\n elif operation == 'INPUT':\n var = line_items[1]\n cmd.extend(DecimalToHex(names[var]))\n cmd.extend([0, 0])\n elif operation == 'OUTPUT':\n var = line_items[1]\n cmd.extend([0, 0])\n cmd.extend(DecimalToHex(names[var]))\n elif operation == 'POP':\n print(\"TODO:POP\")\n elif operation == 'PUSH':\n print(\"TODO:PUSH\")\n elif operation == 'CALL':\n print(\"TODO:CALL\")\n elif operation == 'CMP':\n left_var = line_items[1]\n right_var = line_items[2]\n cmd.extend(DecimalToHex(names[left_var]))\n cmd.extend(DecimalToHex(names[right_var]))\n elif operation == 'JMP' or operation == 'INV_JMP':\n cmd.extend([0,0])\n label_name = line_items[1]\n # Имя метки нет => добавить \n if labels.get(label_name) == None:\n # Индекс инструкции jmp в массиве инструкций\n jmp_instr_pos = len(cmd_list)\n labels.setdefault(label_name, jmp_instr_pos)\n # Ставим флаги, что ячейки необходимо заполнить\n cmd.extend([-1,-1])\n # В labels уже есть имя метки => добавить номер в инструкцию с jmp\n else:\n instr_after_label = labels[label_name]\n cmd.extend(DecimalToHex(instr_after_label))\n else:\n print('Error:MakeNormalCmd: illegal op')\n exit(1)\n return [cmd]\n\ndef IsStringInQoutes(value):\n num_quoutes = 0\n if len(value) >= 1:\n if value[0] == '\\\"':\n num_quoutes += 1\n elif value[0][0] == '\\\"':\n num_quoutes += 1\n if value[-1] == '\\\"':\n num_quoutes += 1\n elif value[-1][-1] == '\\\"':\n num_quoutes += 1\n return num_quoutes == 2\n return 0\n\ndef IntToCmd(var_name, value):\n cmd = []\n cmd.append(10)\n pos_to_write = []\n value = value[0]\n names.setdefault(var_name, num_occupied_cells[0])\n num_occupied_cells[0] += 1\n num_variables[0] += 1\n\n if var_name in names:\n pos_to_write.append(0)\n pos_to_write.append(names[var_name])\n elif var_name in names:\n pos_to_write = DecimalToHex(names[var_name])\n elif IsIntInString(var_name):\n pos_to_write = DecimalToHex(var_name)\n cmd.extend(pos_to_write)\n cmd.extend(DecimalToHex(value))\n return [cmd]\n\ndef StringToCmd(var_name, value):\n cmd_list = []\n body_substr = (\" \").join(value)\n names.setdefault(var_name, num_occupied_cells[0])\n for idx, symbol in enumerate(body_substr):\n dest = DecimalToHex(num_occupied_cells[0])\n hex_symbol = DecimalToHex(ord(symbol))\n\n cmd = []\n cmd.append(11)\n cmd.extend(dest)\n cmd.extend(hex_symbol)\n cmd_list.append(cmd)\n num_occupied_cells[0] += 1\n # Последний элемент массива:\n cmd_list.append([11] + DecimalToHex(num_occupied_cells[0]) + [0, 0])\n num_variables[0] += 1\n num_occupied_cells[0] += 1\n return cmd_list\n\ndef IsIntInList(array):\n el1 = IsIntInString(array[0])\n el2 = len(array) == 1\n\n return len(array) == 1 and IsIntInString(array[0])\n\n# Возвращает: VM команду, приняв решение по формату ассемблерной инструкции\n# Типы инструкций:\n# - \"<имя_переменной><число>\"\n# - \"<имя_переменной><имя_переменной>\"\n# - \"<имя_переменной><имя_регистра>\"\ndef StartCommand():\n if instr_type[0] == InstTypes.START_HEADER:\n return [[]]\n elif instr_type[0] == InstTypes.START_ASSIGN:\n var_name = line_items[0]\n value = line_items[2:]\n if IsIntInList(value):\n return IntToCmd(var_name, value)\n elif IsStringInQoutes(value):\n return StringToCmd(var_name, value)\n else:\n print('Error:StartCommand: wrong value')\n exit(1)\n return cmd\n elif instr_type[0] == InstTypes.START_LABEL:\n label_name = line_items[0][:-1]\n # Метки в set нет => заносим (key= имя метки, value= номер след инструкции)\n if labels.get(label_name) == None:\n labels.setdefault(label_name, len(cmd_list))\n # Метка в set есть => в соответствующий JMP занести номер след инструкции\n else:\n value = labels.get(label_name)\n # В последние 2-е позиции соответствующей jump инструкции вносим номер след инструкции\n cmd_list[value][-2:] = DecimalToHex(len(cmd_list))\n return []\n elif instr_type[0] == InstTypes.START_NORMAL:\n return MakeNormalCmd(line_items[0])\n print('Error:StartCommand: wrong instr_type')\n exit(1)\n\n# Возвращает: пачку команд\n# Пример: [[0,0,1,2,0]] или [[0,0,1,2,0], [3, 3, 1, 0, 2]]\ndef MakeVmCommand():\n if IsDataSection():\n return DataCommand()\n elif IsFuncSection():\n return FunctionCommand()\n elif IsStartSection():\n return StartCommand()\n else:\n print('Error: MakeVmCommand: wring section_type')\n exit(1)\n\noperation_names = {'MOV': 1, 'ADD': 2, 'STOP': 3,\n 'INPUT': 4, 'OUTPUT': 5, 'POP': 6,\n 'PUSH': 7, 'CALL': 8, 'IP': 9,\n 'JMP': 12, 'CMP': 13 , 'INV_JMP': 14 }\n\nnames = {'EBP': 0, 'EAX': 1, 'ESI': 2, 'EDI': 3, 'ESP': 4, 'FLAGS': 5 }\n# Сет : (имя_переменной из .data, [№ ячейки,№ ячейки])\nsection_type = [SectionType.DATA_HEADER]\ninstr_type = [InstTypes.DATA_HEADER]\nline_items = []\nnum_registers = [len(names)]\nnum_variables = [0]\nnum_occupied_cells = [len(names)]\ncmd_list = []\nlabels = {}\n\ndef SetBasePointer():\n cmd = []\n cmd.append(0)\n cmd.extend(DecimalToHex(num_occupied_cells[0]))\n cmd.extend([0,0])\n return cmd\n\ndef WriteCommands():\n memory = []\n # Назначаем Base Pointer\n memory.append(SetBasePointer())\n for i in range(num_occupied_cells[0] - 1):\n memory.append([0,0,0,0,0])\n memory.extend(cmd_list)\n memory = np.asanyarray(memory)\n file = open(\"data.bin\", \"wb\")\n memory.tofile(file=\"data.bin\")\n file.close()\n\n\nwith open('code.txt') as file:\n for idx, line in enumerate(file):\n line_items = line.split()\n if len(line_items):\n if LineIsCorrect():\n cmd = MakeVmCommand()\n if(cmd != [[]]):\n cmd_list.extend(cmd)\n else:\n print('open:Error: code.txt illegal format')\n break\n\nWriteCommands()\n","sub_path":"Languages/HW1/asl.py","file_name":"asl.py","file_ext":"py","file_size_in_byte":12086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"480686336","text":"import sys\nfrom PyQt5.QtWidgets import QWidget, QLabel, QPushButton, QLineEdit, QMessageBox\nfrom PyQt5.QtGui import QPixmap\nfrom daig.api.rest import login_req\nfrom daig.api.auth import set_auth_header\nfrom component.constants import setLabelStyle, setButtonStyle, setLoginButtonStyle, setEditStandard\n\nclass LoginWidget(QWidget):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n # Daig 이미지\n daig_img = QPixmap('./local_data/daig_img.png') # 비율 10:4\n self.img_container = QLabel(self)\n self.img_container.setPixmap(QPixmap(daig_img))\n self.img_container.setScaledContents(True)\n self.img_container.setMaximumSize(300, 120)\n self.img_container.move(70, 20)\n\n # 로그인 버튼\n self.login = QPushButton('Login', self)\n self.login.resize(80, 80)\n self.login.move(300, 170)\n\n setLoginButtonStyle(self.login)\n\n # 회원가입 버튼\n self.sign_up = QPushButton('회원가입', self)\n self.sign_up.move(30, 265)\n setButtonStyle(self.sign_up)\n self.sign_up.setFixedWidth(340)\n\n # 아이디 찾기 버튼\n self.find_id = QPushButton('아이디 찾기', self)\n self.find_id.move(30, 305)\n setButtonStyle(self.find_id)\n self.find_id.setFixedWidth(340)\n\n # 비밀번호 찾기 버튼\n self.find_pwd = QPushButton('비밀번호 찾기', self)\n self.find_pwd.move(30, 345)\n setButtonStyle(self.find_pwd)\n self.find_pwd.setFixedWidth(340)\n\n # 아이디, 비밀번호 알리기\n self.label_id = QLabel('ID ', self)\n self.label_id.move(20, 185)\n font_id = self.label_id.font()\n font_id.setBold(True)\n font_id.setPointSize(20)\n setLabelStyle(self.label_id)\n\n self.label_pwd = QLabel('Password ', self)\n self.label_pwd.move(20, 225)\n font_pwd = self.label_pwd.font()\n font_pwd.setBold(True)\n font_pwd.setPointSize(20)\n setLabelStyle(self.label_pwd)\n\n # 아이디, 비밀번호 작성\n self.id = QLineEdit(self)\n self.id.move(100, 180)\n setEditStandard(self.id, 100, 180, '아이디')\n self.id.setFixedWidth(185)\n\n self.pwd = QLineEdit(self)\n self.pwd.setEchoMode(QLineEdit.Password)\n self.pwd.move(100, 220)\n self.pwd.setFixedWidth(185)\n setEditStandard(self.pwd, 100, 220, '비밀번호')\n\n # 아이디, 비밀번호 창\n def onChanged(self, text):\n self.id.setText(text)\n self.id.adjustSize()\n self.pwd.setText(text)\n self.pwd.adjustSize()\n\n def onClickLogin(self):\n sender_data = {\n \"username\" : self.id.text(),\n \"password\" : self.pwd.text()\n }\n print(sender_data)\n res = login_req(sender_data)\n print(res)\n if(res[\"is_successful\"] == True):\n set_auth_header(res[\"auth\"])\n print('set auth')\n return res[\"auth\"]\n else:\n QMessageBox.about(self, 'DAIG', res[\"message\"])\n return False\n","sub_path":"ui/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"489986417","text":"from django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.utils.translation import ugettext as _\nfrom django.views.generic.edit import BaseFormView, FormMixin\nfrom django.views.generic.base import TemplateResponseMixin, View\n\nfrom avatar.forms import PrimaryAvatarForm, DeleteAvatarForm, UploadAvatarForm\nfrom avatar.models import Avatar\nfrom avatar.settings import AVATAR_MAX_AVATARS_PER_USER, AVATAR_DEFAULT_SIZE\nfrom avatar.signals import avatar_updated\nfrom avatar.util import get_default_avatar_url\n\n\ndef _get_next(request):\n \"\"\"\n The part that's the least straightforward about views in this module is how\n they determine their redirects after they have finished computation.\n\n In short, they will try and determine the next place to go in the following\n order:\n\n 1. If there is a variable named ``next`` in the *POST* parameters, the view\n will redirect to that variable's value.\n 2. If there is a variable named ``next`` in the *GET* parameters, the view\n will redirect to that variable's value.\n 3. If Django can determine the previous page from the HTTP headers, the view\n will redirect to that previous page.\n \"\"\"\n next = request.POST.get('next', request.GET.get('next',\n request.META.get('HTTP_REFERER', None)))\n if not next:\n next = request.path\n return next\n\ndef _get_avatars(target):\n # Default set. Needs to be sliced, but that's it. Keep the natural order.\n avatars = Avatar.objects.avatars_for_object(target)\n\n # Current avatar\n primary_avatar = avatars.order_by('-primary')[:1]\n if primary_avatar:\n avatar = primary_avatar[0]\n else:\n avatar = None\n\n if AVATAR_MAX_AVATARS_PER_USER == 1:\n avatars = primary_avatar\n else:\n # Slice the default set now that we used the queryset for the primary\n # avatar\n avatars = avatars[:AVATAR_MAX_AVATARS_PER_USER]\n return (avatar, avatars)\n\nclass LoginRequiredMixin(object):\n @method_decorator(login_required)\n def dispatch(self, request, *args, **kwargs):\n return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)\n\nclass AvatarMixin(object):\n def get_target(self):\n return self.request.user\n\n def get_avatars(self, target):\n return _get_avatars(target)\n\n def create_avatar(self, target, avatar_file):\n avatar = Avatar(\n content_object=target,\n primary=True,\n )\n avatar.avatar.save(avatar_file.name, avatar_file)\n avatar.save()\n return avatar\n\n def get_success_url(self):\n return self.kwargs.get('next_override', None) or _get_next(self.request)\n\n def render_to_response(self, context):\n if self.request.is_ajax() or self.request.REQUEST.get('async', None) == 'true':\n return self.render_ajax_response(context)\n else:\n return TemplateResponseMixin.render_to_response(self, context)\n\n def render_ajax_response(self, context):\n return TemplateResponseMixin.render_to_response(self, context)\n\n def ajax_form_valid(self, new_avatar):\n if not new_avatar:\n return HttpResponse()\n return HttpResponse(new_avatar.avatar_url(AVATAR_DEFAULT_SIZE))\n\n def get_form_kwargs(self):\n kwargs = FormMixin.get_form_kwargs(self)\n kwargs['target'] = self.target\n kwargs['size'] = self.request.REQUEST.get('size', AVATAR_DEFAULT_SIZE)\n return kwargs\n\n def post(self, request, *args, **kwargs):\n self.target = self.get_target()\n self.avatar, self.avatars = self.get_avatars(self.target)\n return super(AvatarMixin, self).post(request, *args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n self.target = self.get_target()\n self.avatar, self.avatars = self.get_avatars(self.target)\n return super(AvatarMixin, self).get(request, *args, **kwargs)\n\nclass AddAvatarView(LoginRequiredMixin, AvatarMixin, TemplateResponseMixin, BaseFormView):\n form_class = UploadAvatarForm\n template_name = \"avatar/add.html\"\n\n def form_valid(self, form):\n new_avatar = self.create_avatar(self.target, self.request.FILES['avatar'])\n if new_avatar:\n self.request.user.message_set.create(\n message=_(\"Successfully uploaded a new avatar.\"))\n avatar_updated.send(sender=Avatar, target=self.target,\n avatar=new_avatar)\n if self.request.is_ajax() or self.request.REQUEST.get('async', None) == 'true':\n return self.ajax_form_valid(new_avatar)\n else:\n return FormMixin.form_valid(self, form)\n\n def get_context_data(self, **kwargs):\n kwargs['avatar'] = self.avatar\n kwargs['avatars'] = self.avatars\n kwargs['upload_avatar_form'] = kwargs['form']\n kwargs['next'] = self.get_success_url()\n return kwargs\n\nclass ChangeAvatarView(LoginRequiredMixin, AvatarMixin, TemplateResponseMixin, BaseFormView):\n form_class = PrimaryAvatarForm\n upload_form_class = UploadAvatarForm\n template_name = \"avatar/change.html\"\n\n def form_valid(self, form):\n new_avatar = Avatar.objects.get(id=form.cleaned_data['choice'])\n new_avatar.primary = True\n new_avatar.save()\n self.request.user.message_set.create(\n message=_(\"Avatar successfully updated.\"))\n avatar_updated.send(sender=Avatar, target=self.target, avatar=new_avatar)\n\n if self.request.is_ajax() or self.request.REQUEST.get('async', None) == 'true':\n return self.ajax_form_valid(new_avatar)\n else:\n return FormMixin.form_valid(self, form)\n\n def get_context_data(self, **kwargs):\n upload_form = self.upload_form_class(**self.get_form_kwargs())\n kwargs['avatar'] = self.avatar\n kwargs['avatars'] = self.avatars\n kwargs['target'] = self.target\n kwargs['primary_avatar_form'] = kwargs['form']\n kwargs['upload_avatar_form'] = upload_form\n kwargs['next'] = self.get_success_url()\n return kwargs\n\n def get_initial(self):\n initial = {}\n if self.avatar:\n initial['choice'] = self.avatar.id\n return initial\n else:\n return self.initial\n\nclass DeleteAvatarView(LoginRequiredMixin, AvatarMixin, TemplateResponseMixin, BaseFormView):\n form_class = DeleteAvatarForm\n template_name = \"avatar/confirm_delete.html\"\n\n def form_valid(self, form):\n ids = form.cleaned_data['choices']\n new_avatar = None\n if unicode(self.avatar.id) in ids and self.avatars.count() > len(ids):\n # Find the next best avatar, and set it as the new primary\n for a in self.avatars:\n if unicode(a.id) not in ids:\n a.primary = True\n a.save()\n new_avatar = a\n avatar_updated.send(sender=Avatar, target=self.target,\n avatar=a)\n break\n Avatar.objects.filter(id__in=ids).delete()\n self.request.user.message_set.create(\n message=_(\"Successfully deleted the requested avatars.\"))\n if self.request.is_ajax() or self.request.REQUEST.get('async', None) == 'true':\n return self.ajax_form_valid(new_avatar)\n else:\n return FormMixin.form_valid(self, form)\n\n def get_context_data(self, **kwargs):\n kwargs['avatar'] = self.avatar\n kwargs['avatars'] = self.avatars\n kwargs['delete_avatar_form'] = kwargs['form']\n kwargs['next'] = self.get_success_url()\n return kwargs\n\nclass PrimaryAvatarView(AvatarMixin, View):\n def render_primary(self):\n size = self.kwargs.get('size', AVATAR_DEFAULT_SIZE)\n if self.avatar:\n # FIXME: later, add an option to render the resized avatar dynamically\n # instead of redirecting to an already created static file. This could\n # be useful in certain situations, particularly if there is a CDN and\n # we want to minimize the storage usage on our static server, letting\n # the CDN store those files instead\n return HttpResponseRedirect(self.avatar.avatar_url(size))\n else:\n url = get_default_avatar_url(self.target, size)\n return HttpResponseRedirect(url)\n\n def post(self, request, *args, **kwargs):\n super(self.__class__, self).post(request, *args, **kwargs)\n return self.render_primary()\n\n def get(self, request, *args, **kwargs):\n super(self.__class__, self).get(request, *args, **kwargs)\n return self.render_primary()\n","sub_path":"avatar/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"311095881","text":"from lesson10_ass_arr import NativeDictionary\n\n\nclass NativeCache(NativeDictionary):\n def __init__(self, sz):\n NativeDictionary.__init__(self, sz)\n self.hits = [0] * self.size\n\n def put(self, key, value):\n index = self.find(key)\n if index is not None:\n if self.slots[index] == key:\n self.values[index] = value\n self.hits[index] += 1\n return True\n\n index = self.seek_slot(key)\n if index is None:\n old = self.hits.index(min(self.hits))\n self.slots[old] = key\n self.values[old] = value\n self.hits[old] = 1\n else:\n self.slots[index] = key\n self.values[index] = value\n self.hits[index] += 1\n return True\n\n def get(self, key):\n key = self.find(key)\n if key is None:\n return None\n else:\n self.hits[key] += 1\n return self.values[key]\n","sub_path":"lesson12_cache.py","file_name":"lesson12_cache.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"233428118","text":"from pathlib import Path\n\nimport pytest\n\nfrom docs_translate.exceptions import ObjectNotFoundException, DocsFileNotFoundError\nfrom docs_translate.files_worker import FilesWorker\n\nTEST_FIRST_FILE = Path.cwd() / 'tests/test_data/md_files_folder/first_file.md'\nTEST_SECOND_FILE = Path.cwd() / 'tests/test_data/md_files_folder/second_file.md'\n\n\nclass SettingsMock:\n def __init__(self, path):\n self.path = Path.cwd() / Path('test_data/').joinpath(path)\n\n\nclass TestFilesWorker:\n @pytest.mark.parametrize('path, err', [\n ['not existing folder', ObjectNotFoundException],\n ['folder_without_docs_files', DocsFileNotFoundError],\n ['not_a_folder', DocsFileNotFoundError],\n ['not_markdown_file.txt', DocsFileNotFoundError],\n ])\n def test_folder_errors(self, path, err):\n with pytest.raises(err):\n FilesWorker(SettingsMock(path)).get_files()\n","sub_path":"tests/test_filesworker.py","file_name":"test_filesworker.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"602049171","text":"#charange7\n\n#Q1\nwith open(\"st.txt\", \"w\") as f:\n f.write(\"fruits = [apple, banana, orange]\")\n\nwith open(\"st.txt\", \"r\") as f:\n print(f.read())\n\n#Q2\nquestion = \"what are you name?\"\nwith open(\"st.txt\", \"w\") as f:\n f.write(question)\n\n#Q3\nimport csv\n\nwith open(\"im.csv\", \"w\", newline='') as p:\n w = csv.writer(p, delimiter=\",\")\n w.writerow([\"Top Gun\",\"Risky Business\"])\n w.writerow([\"Tintail\",\"Obama\",\"Choco\"])\n w.writerow([\"Man on Fire\",\"level 5\"])\n\n#Q4\nimport csv\n\nwith open(\"im.csv1\", \"w\", encoding=\"utf-8\") as f:\n w = csv.writer(f, delimiter=\",\")\n w.writerow([\"トップガン\", \"リスキービジネス\"])\n w.writerow([\"チンタル\",\"オバマ\",\"チョコ\"])\n w.writerow([\"マンオンファイア\",\"レヴェル5\"])\n\nimport csv\n\nmovies = [[\"Top Gun\", \"Risky Business\", \"Minority Report\"], [\"Titanic\", \"The Revenant\", \"Inception\"], [\"Training Day\", \"Man on Fire\", \"Flight\"]]\nwith open(\"movies.csv\", \"w\") as csvfile:\n spamwriter = csv.writer(csvfile, delimiter=\",\")\n for movie_list in movies:\n spamwriter.writerow(movie_list)\n","sub_path":"Charange7.py","file_name":"Charange7.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"476857206","text":"import numpy as np\nimport pandas as pd\nfrom scipy import interpolate\n\nfrom .Constants import *\nfrom .AtomicData import *\nfrom .Conversions import *\n\n\n##########################\n# Taken from: https://stackoverflow.com/questions/779495/python-access-data-in-package-subdirectory\nimport os\nthis_dir, this_filename = os.path.split(__file__)\nDATA_PATH = os.path.join(this_dir, \"PREM500.csv\")\n##########################\n\n\n\n##########################\n# Read in Earth Data\n##########################\ndata = pd.read_csv(DATA_PATH)\n\n\nradiusTemp1 = data['Radius[m]'] # Radius in Meters\ndensityTemp1 = data[['Density[kg/m^3]']] # Density in kg/m^3\n\n# # The interpolation function doesn't like these objects, so they need to be massaged into 1-D numpy arrays\nradiusListBadUnits = np.asarray(radiusTemp1).squeeze()\ndensityListBadUnits = np.asarray(densityTemp1).squeeze()\n\n# Convert Units and trim off the zero-index value\nradiusList = radiusListBadUnits[1:] * 100 # cm\ndensityList = densityListBadUnits[1:] * (100)**-3 * 1000 # in g/cm^3\n\n\n\n\n##########################\n# Shell Thickness\n##########################\n# We define lenRadiusListm1 in order to give a deltaRList which has the same length as radiusList\nlenRadiusListm1 = radiusList[0:len(radiusList)-1]\ns = [0]\nfor i in lenRadiusListm1:\n s.append(i)\n\ndeltaRList = radiusList[0:len(radiusList)] - s[0:len(s)]\n\n\n\n##########################\n# Shell Mass\n##########################\nshellMassList = []\nlenRadiusList = range(0,len(radiusList))\nfor i in lenRadiusList:\n shellMassList.append(4 * np.pi * radiusList[i]**2 * densityList[i] * deltaRList[i])\n\n\n\n##########################\n# Enclosed Mass\n##########################\nenclosedMassList = []\ntempSum = 0\nfor i in shellMassList:\n tempSum = tempSum + i\n enclosedMassList.append(tempSum)\n\n\n##########################\n# Escape Velocity\n##########################\n\ndef accumulate(index):\n '''\n accumulate(index)\n\n This is the exact same function as in Mathematica\n \n returns the escape velocity at the specified index\n '''\n factor = 2.*G/c**2\n constant = max(enclosedMassList) / max(radiusList)\n \n if (index == 0):\n tempSum = 0\n \n elif (index != 0):\n tempSum = 0 \n for i in range(index, len(radiusList)):\n summand = enclosedMassList[i] * deltaRList[i] / (radiusList[i])**2\n tempSum += summand\n \n return factor * (tempSum + constant)\n\nescVel2List = []\nfor i in lenRadiusList:\n escVel2List.append(accumulate(i))\n \nescVel2List[0] = escVel2List[1]\n\n\n\n\n##########################\n# Number Density\n##########################\nmf = 0\n\ndef numDensityList(element):\n '''\n numDensityList(element)\n\n See ElementList in AtomicData.py for valid elements\n\n Returns: the number density array of element\n '''\n numDensityList = []\n for i in lenRadiusList:\n \n if radiusList[i] < RCrit:\n mf = coreMassFrac[element]\n \n elif RCrit <= radiusList[i] <= RCross:\n mf = mantleMassFrac[element]\n \n elif radiusList[i] > RCross:\n mf = 0\n\n ##########################################################\n # [mf] = mass fraction = dimensionless\n # [densityList] = g/cm^3\n # [atomicNumbers] = dimensionless\n # To make life easy, we convert everything into GeV\n # => densityList -> g2GeV(densitylist)\n # => atomicNumbers -> amu2GeV(atomicNumbers)\n \n n_i = mf * g2GeV(densityList[i]) /(amu2GeV(atomicNumbers[element]))\n\n numDensityList.append(n_i)\n \n return numDensityList\n\n\n\n##########################\n# Interpolate\n##########################\nenclosedMassInterp = interpolate.interp1d(radiusList,enclosedMassList,kind='linear') # g\nescVel2Interp = interpolate.interp1d(radiusList,escVel2List,kind='linear') # Dimensionless\ndensityInterp = interpolate.interp1d(radiusList,densityList,kind='linear') # g/cm^3","sub_path":"DarkCapPy/Configure/PlanetData.py","file_name":"PlanetData.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"63227285","text":"#!/usr/bin/python3\n\nimport re\n\nline = input(\"Enter text: \")\nnames = re.findall(\"(\\w+_\\w+)\", line)\nnew_names = []\n\nfor name in names:\n new_names.append(name[:name.find('_')].capitalize() + name[name.find('_') + 1:].capitalize())\n\nfor new_name in new_names:\n print(new_name)\n\nfor i in range(0,len(new_names) - 1):\n line = line.replace(names[i],new_names[i])\n\nprint(line)","sub_path":"lab7_7.py","file_name":"lab7_7.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"541024963","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.OUT)\n\n# Define Basics\ndot = 0.4\ndash = 3 * dot\npost_d = dot\nspace_l = dash - post_d\nspace_w = 7 * dot - post_d\n\n# Define Letters\nA = a =[dot, dash]\nB = b =[dash, dot, dot, dot]\nC = c =[dash, dot, dash, dot]\nD = d =[dash, dot, dot]\nE = e =[dot]\nF = f =[dot, dot, dash, dot]\nG = g =[dash, dash, dot]\nH = h =[dot, dot, dot, dot]\nI = i =[dot, dot]\nJ = j =[dot, dash, dash, dash]\nK = k =[dash, dot, dash]\nL = l =[dot, dash, dot, dot]\nM = m =[dash, dash]\nN = n =[dash, dot]\nO = o =[dash, dash, dash]\nP = p =[dot, dash, dash, dot]\nQ = q =[dash, dash, dot, dash]\nR = r =[dot, dash, dot]\nS = s =[dot, dot, dot]\nT = t =[dash]\nU = u =[dot, dot, dash]\nV = v =[dot, dot, dot, dash]\nW = w =[dot, dash, dash]\nX = x =[dash, dot, dot, dash]\nY = y =[dash, dot, dash, dash]\nZ = z =[dash, dash, dot, dot]\n\n# Message letters only #NO SPACES#\nm1 = 'HAMRADIOISFORLOSERS'\n\nwhile True:\n i0 = 0\n x0 = 0\n for val1 in m1:\n x0 = globals()[val1]\n print (x0)\n j0 = 0\n \n #while j0 < len(x0):\n for val2 in x0: \n GPIO.output(18, True)\n time.sleep(val2)\n GPIO.output(18, False)\n time.sleep(post_d)\n \n GPIO.output(18, False)\n time.sleep(space_l)\n \n GPIO.output(18, False)\n time.sleep(space_)","sub_path":"morse2.py","file_name":"morse2.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"619702513","text":"## adapted from https://matplotlib.org/examples/api/radar_chart.html\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nfrom matplotlib.spines import Spine\nfrom matplotlib.projections.polar import PolarAxes\nfrom matplotlib.projections import register_projection\n\n\ndef radar_factory(num_vars, frame='circle'):\n theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)\n theta += np.pi/2\n def draw_poly_patch(self):\n verts = unit_poly_verts(theta)\n return plt.Polygon(verts, closed=True, edgecolor='k')\n def draw_circle_patch(self):\n return plt.Circle((0.5, 0.5), 0.5)\n patch_dict = {'polygon': draw_poly_patch, 'circle': draw_circle_patch}\n if frame not in patch_dict:\n raise ValueError('unknown value for `frame`: %s' % frame)\n class RadarAxes(PolarAxes):\n name = 'radar'\n RESOLUTION = 1\n draw_patch = patch_dict[frame]\n def fill(self, *args, **kwargs):\n closed = kwargs.pop('closed', True)\n return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)\n def plot(self, *args, **kwargs):\n lines = super(RadarAxes, self).plot(*args, **kwargs)\n for line in lines:\n self._close_line(line)\n def _close_line(self, line):\n x, y = line.get_data()\n if x[0] != x[-1]:\n x = np.concatenate((x, [x[0]]))\n y = np.concatenate((y, [y[0]]))\n line.set_data(x, y)\n def set_varlabels(self, labels):\n self.set_thetagrids(np.degrees(theta), labels)\n def _gen_axes_patch(self):\n return self.draw_patch()\n def _gen_axes_spines(self):\n if frame == 'circle':\n return PolarAxes._gen_axes_spines(self)\n spine_type = 'circle'\n verts = unit_poly_verts(theta)\n verts.append(verts[0])\n path = Path(verts)\n spine = Spine(self, spine_type, path)\n spine.set_transform(self.transAxes)\n return {'polar': spine}\n register_projection(RadarAxes)\n return theta\n\n\ndef unit_poly_verts(theta):\n x0, y0, r = [0.5] * 3\n verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]\n return verts\n\ndef labels_to_colors(labels):\n cmap = plt.get_cmap('viridis')\n color_dict = {}\n unique_labels = np.unique(labels)\n for i, v in enumerate(unique_labels):\n color_dict[v] = cmap(i / len(unique_labels))\n colors = [color_dict[l] for l in labels]\n return colors\n\ndef radar_chart(data, labels, show_axis=False, fill_polygon=False):\n theta = radar_factory(len(data[0]), frame='circle')\n colors = labels_to_colors(labels)\n fig, ax = plt.subplots(figsize=(5,5), subplot_kw=dict(projection='radar'), facecolor='white')\n ax.axis('on' if show_axis else 'off')\n fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)\n for record, color in zip(data, colors):\n ax.plot(theta, record, color=color)\n if fill_polygon:\n ax.fill(theta, record, facecolor=color, alpha=0.25)\n return fig, ax\n","sub_path":"plotting/radar_chart.py","file_name":"radar_chart.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"646563745","text":"# Functions\ndef display(board):\n\tprint(' | | ')\n\tprint(\" \" + board[0] + \" | \" + board[1] + \" | \" + board[2])\n\tprint('---|---|---')\n\tprint(\" \" + board[3] + \" | \" + board[4] + \" | \" + board[5])\n\tprint('---|---|---')\n\tprint(\" \" + board[6] + \" | \" + board[7] + \" | \" + board[8])\n\tprint(' | | ')\n\ndef place_move_if_valid(board, player, position):\n\tif (board[position] == ' '):\n\t\tboard[position] = player\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef board_is_full(board):\n\tfor square in board:\n\t\tif (square == \" \"):\n\t\t\treturn False\n\telse:\n\t\treturn True\n\ndef check_for_winner(board):\n\tif (board[0] == board[1] == board[2] != \" \" or board[3] == board[4] == board[5] != \" \" or board[6] == board[7] == board[8] != \" \"\n\t\tor board[0] == board[3] == board[6] != \" \" or board[1] == board[4] == board[7] != \" \" or board[2] == board[5] == board[8] != \" \"\n\t\tor board[0] == board[4] == board[8] != \" \" or board[2] == board[4] == board[6] != \" \"):\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef game():\n\tturn = 0\n\tplayers = (\"X\", \"O\")\n\tboard = [\" \"] * 9\n\n\tdisplay(board)\n\twhile(not board_is_full(board)):\n\n\t\t# Next turn\n\t\tposition = int(input(f\"(Player {players[turn]}) Enter the number of your chosen position: \"))\n\t\tresult = place_move_if_valid(board, players[turn], position - 1)\n\n\t\t# Display changes\n\t\tdisplay(board)\n\n\t\t# Check board\n\t\tif (check_for_winner(board)):\n\t\t\tbreak\n\n\t\t# Move forward\n\t\tif (result):\n\t\t\tturn = (turn + 1) % 2\n\t\telse:\n\t\t\tprint(\"That position has already been taken! Try again.\")\n\t\t\tcontinue\n\n\tif (check_for_winner(board)):\n\t\tprint(f\"############ Congratulations Player {players[turn]} ############\")\n\telse:\n\t\tprint(\"############ DRAW ############\")\n\n# Start\nprint(\"Welcome at TicTacToe!\")\nprint(\"This game uses a numeric keypad.\")\n\nplaying = True\nwhile (playing):\n\tprint(\" \")\n\tgame()\n\n\tresult = input('Replay? [Y/N]: ')\n\tif (result == 'N'):\n\t\tplaying = False\n\n\n\n","sub_path":"games/02-tictactoe.py","file_name":"02-tictactoe.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"506333136","text":"import hlt\nfrom hlt import constants\nfrom hlt.bot_utils import Utils, SummaryWriter\nfrom hlt.positionals import Direction\nimport numpy as np\nimport sys\nimport os\nimport logging\nstderr = sys.stderr\nsys.stderr = open(os.devnull, 'w')\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nfrom algorithms.supervised_model import SupervisedModel\n\n\nclass MLBot:\n def __init__(self, episode=0, deposit_halite_amount=800, radius=16, summary_name=None, model_name='supervised_cnn_phase2'):\n self.radius = radius\n self.model = SupervisedModel(radius=self.radius, output_number=5, model_name=model_name)\n self.deposit_halite_amount = deposit_halite_amount\n self.summary_name = summary_name\n self.episode = episode\n if summary_name is not None:\n self.summary_writer = SummaryWriter()\n sys.stderr = stderr\n\n self.game = hlt.Game()\n self.max_halite, self.min_halite = Utils.get_max_min_map_halite(self.game.game_map)\n self.config = Utils.MAP_CONFIG[len(self.game.players)][self.game.game_map.height]\n for dropout in self.config['dropouts']:\n dropout.center.x = dropout.center.x * Utils.DROPOUT_MOD[len(self.game.players)][self.game.my_id]['x']\n dropout.center.y = dropout.center.y * Utils.DROPOUT_MOD[len(self.game.players)][self.game.my_id]['y']\n dropout.center = self.game.game_map.normalize(dropout.center + self.game.me.shipyard.position)\n\n self.game.ready(\"SupervisedBot\")\n\n def run(self):\n # F - finish, S - search, D - deposit, B - build dropout\n data = {'structures': [], 'ships': [], 'states': {}, 'dropout': None}\n ships_created = 0\n turn_limit = constants.MAX_TURNS\n ship_building_dropout = None\n\n while True:\n self.game.update_frame()\n game_map = self.game.game_map\n turn_number = self.game.turn_number\n me = self.game.me\n command_queue = []\n data['structures'] = [d.position for d in list([me.shipyard] + me.get_dropoffs())]\n data = Utils.update_ship_states(me.get_ships(), data)\n data, config = Utils.make_dropout(game_map, me.get_ships(), data, self.config, turn_number)\n\n for ship in me.get_ships():\n if data['states'][ship.id] == 'F' or turn_limit - turn_number - self.config['finish'] < \\\n game_map.calculate_distance(ship.position, me.shipyard.position):\n data['states'][ship.id] = 'F'\n elif ship.position in data['structures'] and data['states'][ship.id] != 'B':\n data['states'][ship.id] = 'S'\n elif ship.halite_amount > self.deposit_halite_amount and data['states'][ship.id] != 'B':\n data['states'][ship.id] = 'D'\n\n if data['states'][ship.id] == 'F':\n move = Utils.navigate_to_finish_game(data['structures'], game_map, ship, Utils.find_closest_structure(game_map, ship, data['structures']))\n elif data['states'][ship.id] == 'B':\n if ship.position == data['dropout']['dropout_position'] and Utils.has_halite_to_make_dropout(self.game, ship):\n command_queue.append(ship.make_dropoff())\n data['states'][ship.id] = 'S'\n data['dropout'] = None\n del config['dropouts'][0]\n ship_building_dropout = ship\n continue\n else:\n move = Utils.navigate(game_map, ship, data['dropout']['dropout_position'], data)\n elif data['states'][ship.id] == 'S':\n surroundings = Utils.get_surroundings(data, ship, game_map, self.radius, self.max_halite, self.min_halite)\n predicted_actions = self.model.predict_choice_actions(np.array([surroundings]))\n move = Utils.get_best_move(predicted_actions, game_map, ship)\n else:\n move = Utils.navigate(game_map, ship, Utils.find_closest_structure(game_map, ship, data['structures']), data)\n\n command_queue.append(ship.move(move))\n\n if ship_building_dropout is not None:\n if me.halite_amount >= constants.SHIP_COST + Utils.get_cost_to_make_dropout(self.game, ship_building_dropout):\n command_queue.append(me.shipyard.spawn())\n ships_created += 1\n ship_building_dropout = None\n elif (data['dropout'] is None and Utils.can_make_ship(turn_number, me, game_map, config)) or \\\n (data['dropout'] is not None and me.halite_amount >= constants.SHIP_COST + constants.DROPOFF_COST):\n command_queue.append(me.shipyard.spawn())\n ships_created += 1\n\n if self.summary_name is not None and turn_number == turn_limit:\n self.summary_writer.add_summary(len(me.get_ships()),\n me.halite_amount / 1000.0,\n self.episode,\n game_map.height,\n ships_created,\n self.summary_name)\n\n self.game.end_turn(command_queue)\n","sub_path":"MLBot.py","file_name":"MLBot.py","file_ext":"py","file_size_in_byte":5376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"354524522","text":"import sys\nimport numpy as np\nimport re\n\nbad_chars = [\"*\", '\"', \"+\", \"/\", \"%\"]\n\ndef check_if_doi(x):\n x = x.replace(\"DOI\", \"\\n\").split(\"\\n\")\n if len(x)==1:\n x = \"\".join([e.strip() for e in x[-1].lower().split(\",\")])\n return \"\".join(e for e in x if e.isalnum())\n else:\n return x[-1].strip()\n# Article object that contains info about one article\nclass Article:\n def __init__(self,info):\n self.doctype = None\n self.title = None\n self.authors = None\n self.journal = None\n self.abstract = None\n self.year = None\n self.month = None\n self.doi = None\n self.ncitations = None\n self.topic = None\n self.keywords = []\n self.references = []\n self.authors = []\n self.add_basics(info)\n self.add_id(info)\n self.add_references_id(info)\n self.link_from = dict()\n self.link_to = dict()\n self.raw = info\n def add_basics(self, info):\n if \"AB\" in info:\n self.abstract = re.sub(r'\\d+', \"\", info[\"AB\"].replace(\"\\n\", \".\").replace(\"*\", \" \").replace(\"%\", \" \").replace(\"/\",\" \").replace(\"+\", \" \").replace(\"-\", \" \").replace(\" )\", \" \").replace(\"( \", \" \").replace(\"()\", \" \").replace(\"( )\", \" \").strip())\n self.abstract = re.sub(\" +\", \" \", self.abstract)\n self.abstract = \". \".join([e.strip() for e in filter(None, self.abstract.split(\".\")) if not e.strip().isdigit()])\n if \"JI\" in info:\n self.journal = \"\".join(e for e in info[\"JI\"].replace(\"\\n\", \" \").strip() if e.isalnum())\n if \"PD\" in info:\n self.month = info[\"PD\"].lower().replace(\"\\n\", \" \").strip()\n if \"PY\" in info:\n self.year = int(info[\"PY\"].replace(\"\\n\", \" \").strip())\n if \"DI\" in info:\n self.doi = info[\"DI\"].replace(\"\\n\", \" \").strip()\n if \"TI\" in info:\n self.title = info[\"TI\"].replace(\"\\n\", \" \").strip()\n if \"PT\" in info:\n self.doctype = info[\"PT\"].replace(\"\\n\", \" \").strip()\n if \"Z9\" in info:\n self.ncitations = int(info[\"Z9\"].replace(\"\\n\", \" \").strip())\n if \"AU\" in info:\n self.authors = filter(None, info[\"AU\"].split(\"\\n\"))\n if \"WC\" in info:\n self.topic = \"\".join(f for f in \";\".join([e.strip() for e in filter(None, info[\"WC\"].lower().split(\";\"))]) if f.isalnum())\n if \"DE\" in info:\n self.keywords = filter(None, info[\"DE\"].lower().replace(\"\\n\", \" \").strip().split(\";\"))\n if \"ID\" in info:\n self.keywords = filter(None, self.keywords + info[\"ID\"].lower().replace(\"\\n\", \" \").strip().split(\";\"))\n if self.keywords:\n self.keywords = np.unique([\"\".join(k for k in e if k.isalnum()) for e in self.keywords])\n def add_id(self, info):\n # This function could be improved. Ideally, I would use the first word in the title of the paper but this information would not be reflected in the references of each article\n if self.doi:\n self.id = self.doi\n else:\n self.id = \"\".join(e for e in self.authors[0] if e.isalnum()) + str(self.year) + \"\".join(e for e in self.journal.lower() if e.isalnum())\n def add_references_id(self, info):\n if \"CR\" in info:\n self.references = filter(None,[check_if_doi(e.strip()) for e in info[\"CR\"].split(\"\\n\")])\n def __str__(self):\n output = \"\"\n output += \"title = \" + self.title\n output += \"\\ndocument type = \" + self.doctype\n output += \"\\njournal name = \" + self.journal\n output += \"\\nDOI = \" + self.doi\n output += \"\\nyear = \" + self.year\n output += \"\\n----------\\nabstract:\\n\" + self.abstract\n output += \"\\n----------\\nauthors:\\n\" + \";\".join(self.authors)\n output += \"\\n----------\\nreferences:\\n\" + \"\\n\".join(self.references)\n output += \"\\n\"\n return output\n\n# Object characterizing the network of articles\nclass Network:\n def __init__(self):\n self.nodes = dict()\n self.outnodes = set([])\n def add_article(self, info):\n x = Article(info)\n self.nodes[x.id] = x\n def generate_links(self, x):\n for y in x.references:\n if type(y)==type(\"str\"):\n if y in self.nodes.keys():\n try:\n z = x.link_from[y]\n except:\n x.link_from[y] = self.nodes[y]\n else:\n try:\n z = self.outnodes[y]\n except:\n self.outnodes.add(y)\n","sub_path":"code/process_data/datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"57564324","text":"import numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport time\nimport ot\nfrom scipy import linalg\nfrom scipy import sparse\nimport gromovWassersteinAveraging as gwa\nimport spectralGW as sgw\nfrom geodesicVisualization import *\nimport json\n\n# Load the S-GWL code\nimport DataIO as DataIO\nimport EvaluationMeasure as Eval\nimport GromovWassersteinGraphToolkit as GwGt\nimport pickle\nimport warnings\n\n# Load modules for network partitioning experiments\nimport community\nfrom networkx.algorithms.community import greedy_modularity_communities\nfrom networkx.algorithms.community.asyn_fluid import asyn_fluidc\nfrom sklearn import metrics\nfrom infomap import Infomap\n\nwarnings.filterwarnings(\"ignore\")\n\n# dictionaries for holding results\nscores = {}\nruntimes = {}\navetimes = {}\n\n# load data\nf = open('data/amazon.p', 'rb')\ndatabase = pickle.load(f)\nf.close()\nG = database['G']\nlabels = database['labels']\n\nnum_nodes = G.number_of_nodes()\nnum_partitions = len(np.unique(labels))\n\nidx2node = {}\nfor n in G.nodes:\n idx2node[n] = n\n\n# create noisy version\nnG = nx.Graph()\n\nfor n in G.nodes:\n nG.add_node(n)\n\nfor e in G.edges:\n nG.add_edge(e[0],e[1])\n \nstart_edges = nx.number_of_edges(nG)\n \n# add noise\nfor j in range(int( 0.1*G.number_of_edges() )):\n x1 = int(num_nodes * np.random.rand())\n x2 = int(num_nodes * np.random.rand())\n if database['labels'][x1] != database['labels'][x2]:\n nG.add_edge(x1, x2)\n\nprint('---{:3d} edges in raw version \\n'.format(G.number_of_edges())) \nprint('---Added {:d} edges to create noisy version \\n'.format(nx.number_of_edges(nG)-start_edges))\n\n \nprint('---Data files loaded. Computing...\\n')\n\n\ndef process_sgwl_amazon(cost_s,database,num_nodes,num_partitions,verbose=False):\n p_s = np.zeros((num_nodes, 1))\n p_s[:, 0] = np.sum(cost_s, axis=1) ** 0.001\n p_s /= np.sum(p_s)\n p_t = GwGt.estimate_target_distribution({0: p_s}, dim_t=num_partitions)\n\n ot_dict = {'loss_type': 'L2', # the key hyperparameters of GW distance\n 'ot_method': 'proximal',\n 'beta': 2e-7,\n 'outer_iteration': 300,\n # outer, inner iteration, error bound of optimal transport\n 'iter_bound': 1e-30,\n 'inner_iteration': 1,\n 'sk_bound': 1e-30,\n 'node_prior': 0,\n 'max_iter': 200, # iteration and error bound for calcuating barycenter\n 'cost_bound': 1e-16,\n 'update_p': False, # optional updates of source distribution\n 'lr': 0,\n 'alpha': 0}\n\n time_s = time.time()\n sub_costs, sub_probs, sub_idx2nodes, trans = GwGt.graph_partition_gd(cost_s,\n p_s,\n p_t,\n idx2node,\n ot_dict)\n est_idx = np.argmax(trans, axis=1)\n\n mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)\n \n if verbose:\n print('---Mutual information score = {:3.5f}'.format(mutual_info))\n\n return mutual_info\n\n###########################################################\n###########################################################\n# Method: Fluid communities\n###########################################################\n# Raw data\nif not nx.is_connected(G):\n #print('---Fluid community requires connected graph, skipping raw version---')\n scores['fluid-raw'] = 'failed'\n runtimes['fluid-raw'] = 'failed'\nelse:\n time_s = time.time()\n comp = asyn_fluidc(G.to_undirected(), k=num_partitions)\n list_nodes = [frozenset(c) for c in comp]\n est_idx = np.zeros((num_nodes,))\n for i in range(len(list_nodes)):\n for idx in list_nodes[i]:\n est_idx[idx] = i\n runtime = time.time() - time_s\n mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)\n scores['fluid-raw'] = mutual_info\n runtimes['fluid-raw'] = runtime\n\n# Noisy data\nif not nx.is_connected(nG):\n print('---Fluid community requires connected graph, skipping noisy version---')\n scores['fluid-noisy'] = 'failed'\n runtimes['fluid-noisy'] = 'failed' \nelse:\n time_s = time.time()\n comp = asyn_fluidc(nG.to_undirected(), k=num_partitions)\n list_nodes = [frozenset(c) for c in comp]\n est_idx = np.zeros((num_nodes,))\n for i in range(len(list_nodes)):\n for idx in list_nodes[i]:\n est_idx[idx] = i\n runtime = time.time() - time_s\n mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)\n scores['fluid-noisy'] = mutual_info\n runtimes['fluid-noisy'] = runtime \n\n\n \n###########################################################\n###########################################################\n# Method: FastGreedy\n###########################################################\n# Raw\ntime_s = time.time()\nlist_nodes = list(greedy_modularity_communities(G))\nest_idx = np.zeros((num_nodes,))\nfor i in range(len(list_nodes)):\n for idx in list_nodes[i]:\n est_idx[idx] = i\nruntime = time.time() - time_s\nmutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)\nscores['fastgreedy-raw'] = mutual_info\nruntimes['fastgreedy-raw'] = runtime \n\n\n# Noisy\ntime_s = time.time()\nlist_nodes = list(greedy_modularity_communities(nG))\nest_idx = np.zeros((num_nodes,))\nfor i in range(len(list_nodes)):\n for idx in list_nodes[i]:\n est_idx[idx] = i\nruntime = time.time() - time_s\nmutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)\nscores['fastgreedy-noisy'] = mutual_info\nruntimes['fastgreedy-noisy'] = runtime \n\n\n\n\n###########################################################\n###########################################################\n# Method: Louvain\n###########################################################\n# Raw\ntime_s = time.time()\npartition = community.best_partition(G)\nest_idx = np.zeros((num_nodes,))\nfor com in set(partition.values()):\n list_nodes = [nodes for nodes in partition.keys()\n if partition[nodes] == com]\n for idx in list_nodes:\n est_idx[idx] = com\nruntime = time.time() - time_s\nmutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)\nscores['louvain-raw'] = mutual_info\nruntimes['louvain-raw'] = runtime \n\n# Noisy\ntime_s = time.time()\npartition = community.best_partition(nG)\nest_idx = np.zeros((num_nodes,))\nfor com in set(partition.values()):\n list_nodes = [nodes for nodes in partition.keys()\n if partition[nodes] == com]\n for idx in list_nodes:\n est_idx[idx] = com\nruntime = time.time() - time_s\nmutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)\nscores['louvain-noisy'] = mutual_info\nruntimes['louvain-noisy'] = runtime \n\n\n\n\n###########################################################\n###########################################################\n# Method: Infomap\n########################################################### \n# Raw\ntime_s = time.time()\nim = Infomap()\nfor node in G.nodes:\n im.add_node(node)\nfor edge in G.edges:\n im.add_link(edge[0], edge[1])\n im.add_link(edge[1],edge[0])\n# Run the Infomap search algorithm to find optimal modules\nim.run()\n# print(f\"Found {im.num_top_modules} modules with Infomap\")\nest_idx = np.zeros((num_nodes,))\nfor node in im.tree:\n if node.is_leaf:\n est_idx[node.node_id] = node.module_id\n\nruntime = time.time() - time_s\nmutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)\nscores['infomap-raw'] = mutual_info\nruntimes['infomap-raw'] = runtime \n\n# Noisy\nprint('---Running Infomap with noisy data---\\n')\ntime_s = time.time()\nim = Infomap()\nfor node in nG.nodes:\n im.add_node(node)\nfor edge in nG.edges:\n im.add_link(edge[0], edge[1])\n im.add_link(edge[1],edge[0])\n# Run the Infomap search algorithm to find optimal modules\nim.run()\n# print(f\"Found {im.num_top_modules} modules with Infomap\")\nest_idx = np.zeros((num_nodes,))\nfor node in im.tree:\n if node.is_leaf:\n est_idx[node.node_id] = node.module_id\n\nruntime = time.time() - time_s\nmutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)\nscores['infomap-noisy'] = mutual_info\nruntimes['infomap-noisy'] = runtime \n\n\n###########################################################\n###########################################################\n# Method: GWL\n########################################################### \n# Raw\nstart = time.time()\ncost = nx.adjacency_matrix(G).toarray()\nmutual_info = process_sgwl_amazon(cost,database,num_nodes,num_partitions);\nend = time.time()\nscores['gwl-raw'] = mutual_info\nruntimes['gwl-raw'] = end-start \n\n\n# adjacency, undirected, noisy\nstart = time.time()\ncost = nx.adjacency_matrix(nG).toarray()\nmutual_info = process_sgwl_amazon(cost,database,num_nodes,num_partitions);\nend = time.time()\nscores['gwl-noisy'] = mutual_info\nruntimes['gwl-noisy'] = end-start\n\n\n###########################################################\n###########################################################\n# Proposed method: SpecGWL\n########################################################### \n# Raw\nmis = []\nrt = []\nts = [85+5/9]#np.linspace(80,90,10)\nfor t in ts:\n start = time.time()\n cost = sgw.undirected_normalized_heat_kernel(G,t)\n mutual_info = process_sgwl_amazon(cost,database,num_nodes,num_partitions);\n mis.append(mutual_info)\n end = time.time()\n rt.append(end-start)\n\n# print('--- Raw data | SpecGWL | Best mutual information score: {:3.3f} | @t = {:3.3f} | average runtime per iteration = {:3.3f}'.format(max(mis), ts[np.argmax(mis)], np.mean(rt)))\nscores['specgwl-raw'] = max(mis)\nruntimes['specgwl-raw'] = sum(rt)\n# avetimes['specgwl-raw'] = np.mean(rt)\n\n# Noisy\nmis = []\nrt = []\nts = [7.0555556]#np.linspace(6.5,7.5,10)\nfor t in ts:\n start = time.time()\n cost = sgw.undirected_normalized_heat_kernel(nG,t)\n mi = process_sgwl_amazon(cost,database,num_nodes,num_partitions);\n mis.append(mi)\n end = time.time()\n rt.append(end-start)\n \n# print('--- Noisy data | SpecGWL | Best mutual information score: {:3.3f} | @t = {:3.3f} | average runtime per iteration = {:3.3f}'.format(max(mis), ts[np.argmax(mis)], np.mean(rt)))\nscores['specgwl-noisy'] = max(mis)\nruntimes['specgwl-noisy'] = sum(rt)\n# avetimes['specgwl-noisy'] = np.mean(rt)\n\nprint('Mutual information scores')\nprint(json.dumps(scores,indent=1))\nprint('Runtimes')\nprint(json.dumps(runtimes,indent=1))\n# print('Average runtime of SpecGWL')\n# print(json.dumps(avetimes,indent=1))\n\nwith open('res_benchmark_amazon.txt', 'w') as outfile:\n json.dump(['Adjusted mutual information scores',\n scores,\n 'Runtimes',\n runtimes], outfile,indent=1)\n","sub_path":"benchmark_amazon.py","file_name":"benchmark_amazon.py","file_ext":"py","file_size_in_byte":10852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"71038265","text":"import csv\r\nimport scipy.stats as st\r\nimport statistics\r\nimport math\r\nimport os\r\nimport argparse\r\nfrom random import sample\r\n\r\n\r\nclass causal_cell():\r\n def __init__(self, Feature, value, z_score, probability_do, probability_not_do, p_value, support, condition_list):\r\n self.Feature = Feature\r\n self.value = value\r\n self.z_score = z_score\r\n self.probability_do = probability_do\r\n self.probability_not_do = probability_not_do\r\n self.probability_difference = probability_do - probability_not_do\r\n self.p_value = p_value\r\n self.support = support\r\n self.condition_list = condition_list\r\n\r\n def set_condition_list(condition_list):\r\n self.condition_list = condition_list\r\n\r\n def get_variable_list1(self):\r\n variable_list = [self.Feature, self.value, self.z_score, self.probability_do, self.probability_not_do,\r\n self.probability_difference, self.p_value, self.support]\r\n return variable_list\r\n\r\n def get_variable_list2(self):\r\n variable_list = [self.Feature, self.value, self.z_score, self.probability_do, self.probability_not_do,\r\n self.probability_difference, self.p_value, self.support, self.condition_list]\r\n return variable_list\r\n\r\n\r\ndef causal_tree(feature_file, probability_file, threshold, condition_list):\r\n gender_dict = {}\r\n gender_not_empty_dict = {}\r\n age_dict = {}\r\n age_not_empty_dict = {}\r\n ade_dict = {}\r\n ade_not_empty_dict = {}\r\n location_dict = {}\r\n location_not_empty_dict = {}\r\n psd_dict = {}\r\n psd_not_empty_dict = {}\r\n dose_dict = {}\r\n dose_not_empty_dict = {}\r\n indication_dict = {}\r\n indication_not_empty_dict = {}\r\n outcome_dict = {}\r\n outcome_not_empty_dict = {}\r\n filter_list = []\r\n probability_dict = {}\r\n\r\n def condition(condition_list, line):\r\n\r\n all_term_in = True\r\n if condition_list == []:\r\n return False\r\n for term in condition_list:\r\n if not term in line:\r\n all_term_in = False\r\n if all_term_in:\r\n return False\r\n else:\r\n return True\r\n\r\n def put_in_dict(index, str, dict):\r\n a = str.split(', ')\r\n for item in a:\r\n if not item in dict:\r\n dict[item] = [index]\r\n else:\r\n dict[item].append(index)\r\n return dict\r\n\r\n def put_in_dict_psd(index, str, dict):\r\n a = str.split('; ')\r\n for item in a:\r\n if not item in dict:\r\n dict[item] = [index]\r\n else:\r\n dict[item].append(index)\r\n return dict\r\n\r\n with open(feature_file) as tsvfile:\r\n tsvreader = csv.reader(tsvfile, delimiter=\"\\t\")\r\n for index, line in enumerate(tsvreader):\r\n if index == 0:\r\n continue\r\n else:\r\n\r\n age, ade, dose, psd, gender, indication, outcome = line\r\n if condition(condition_list, line):\r\n continue\r\n if dose != ' ':\r\n dose_not_empty_dict[index] = True\r\n if age != ' ':\r\n age_not_empty_dict[index] = True\r\n if ade != ' ':\r\n ade_not_empty_dict[index] = True\r\n if psd != ' ':\r\n psd_not_empty_dict[index] = True\r\n if gender != ' ':\r\n gender_not_empty_dict[index] = True\r\n if indication != ' ':\r\n indication_not_empty_dict[index] = True\r\n if outcome != ' ':\r\n outcome_not_empty_dict[index] = True\r\n gender_dict = put_in_dict(index, gender, gender_dict)\r\n age_dict = put_in_dict(index, age, age_dict)\r\n psd_dict = put_in_dict(index, psd, psd_dict)\r\n dose_dict = put_in_dict(index, dose, dose_dict)\r\n indication_dict = put_in_dict(index, indication, indication_dict)\r\n ade_dict = put_in_dict(index, ade, ade_dict)\r\n outcome_dict = put_in_dict(index, outcome, outcome_dict)\r\n with open(probability_file) as tsvfile:\r\n tsvreader = csv.reader(tsvfile, delimiter=\"\\t\")\r\n for line in enumerate(tsvreader):\r\n probability_dict[line[0] + 1] = line[1]\r\n\r\n def compute_gap(feature_dict, p_dict, not_empty_dict):\r\n dict = {}\r\n dict_in = {}\r\n dict_out = {}\r\n\r\n def compute_Z_score(in_list, out_list):\r\n L1 = []\r\n for term in in_list:\r\n L1.append(float(term[1]))\r\n L2 = []\r\n for term in out_list:\r\n L2.append(float(term[1]))\r\n s1 = statistics.variance(L1)\r\n l1 = s1 / len(L1)\r\n s2 = statistics.variance(L2)\r\n l2 = s2 / len(L2)\r\n l = l1 + l2\r\n m = math.sqrt(l)\r\n m1 = statistics.mean(L1)\r\n m2 = statistics.mean(L2)\r\n return (m1 - m2) / m\r\n\r\n def compute_expecation(list):\r\n L = []\r\n for term in list:\r\n L.append(float(term[1]))\r\n if not len(L) == 0:\r\n return sum(L) / len(L)\r\n else:\r\n return 0\r\n\r\n for key in feature_dict.keys():\r\n l1 = feature_dict[key]\r\n In = []\r\n Out = []\r\n for index in p_dict.keys():\r\n if index in not_empty_dict:\r\n if index in l1:\r\n In.append(p_dict[index])\r\n else:\r\n Out.append(p_dict[index])\r\n\r\n if len(In) >= threshold and len(Out) >= threshold:\r\n dict[key] = compute_Z_score(In, Out)\r\n dict_in[key] = compute_expecation(In)\r\n dict_out[key] = compute_expecation(Out)\r\n\r\n return dict, dict_in, dict_out\r\n\r\n gender_gap_dict, gender_in_dict, gender_out_dict = compute_gap(gender_dict, probability_dict, gender_not_empty_dict)\r\n age_gap_dict, age_in_dict, age_out_dict = compute_gap(age_dict, probability_dict, age_not_empty_dict)\r\n psd_gap_dict, psd_in_dict, psd_out_dict = compute_gap(psd_dict, probability_dict, psd_not_empty_dict)\r\n dose_gap_dict, dose_in_dict, dose_out_dict = compute_gap(dose_dict, probability_dict, dose_not_empty_dict)\r\n indication_gap_dict, indication_in_dict, indication_out_dict = compute_gap(indication_dict, probability_dict,\r\n indication_not_empty_dict)\r\n outcome_gap_dict, outcome_in_dict, outcome_out_dict = compute_gap(outcome_dict, probability_dict,\r\n outcome_not_empty_dict)\r\n\r\n total_dict = {**gender_gap_dict,\r\n **age_gap_dict,\r\n **psd_gap_dict,\r\n **dose_gap_dict,\r\n **indication_gap_dict,\r\n **outcome_gap_dict,\r\n }\r\n cell_list = []\r\n for key in total_dict:\r\n\r\n z_score = total_dict[key]\r\n p_values = 1 - st.norm.cdf(z_score)\r\n if not p_values <= 0.05:\r\n continue\r\n\r\n if key in gender_gap_dict:\r\n cell = causal_cell('gender', key, total_dict[key], gender_in_dict[key], gender_out_dict[key], p_values,\r\n len(gender_dict[key]), condition_list)\r\n if key in age_gap_dict:\r\n cell = causal_cell('age', key, total_dict[key], age_in_dict[key], age_out_dict[key], p_values,\r\n len(age_dict[key]), condition_list)\r\n if key in psd_gap_dict:\r\n cell = causal_cell('psd', key, total_dict[key], psd_in_dict[key], psd_out_dict[key], p_values,\r\n len(psd_dict[key]), condition_list)\r\n if key in dose_gap_dict:\r\n cell = causal_cell('dose', key, total_dict[key], dose_in_dict[key], dose_out_dict[key], p_values,\r\n len(dose_dict[key]), condition_list)\r\n if key in indication_gap_dict:\r\n cell = causal_cell('indication', key, total_dict[key], indication_in_dict[key], indication_out_dict[key],\r\n p_values, len(indication_dict[key]), condition_list)\r\n if key in outcome_gap_dict:\r\n cell = causal_cell('outcome', key, total_dict[key], outcome_in_dict[key], outcome_out_dict[key], p_values,\r\n len(outcome_dict[key]), condition_list)\r\n cell_list.append(cell)\r\n return cell_list\r\n\r\n\r\ndef causal_inference(probability_file, feature_file, out_dir, threshold=100):\r\n condition_list = []\r\n cell_list = causal_tree(feature_file, probability_file, threshold, condition_list)\r\n\r\n def myFunc(e):\r\n return e.get_variable_list1()[2]\r\n\r\n cell_list.sort(reverse=True, key=myFunc)\r\n # write csv file\r\n if not os.path.exists(out_dir):\r\n os.mkdir(out_dir)\r\n title = ['Feature', 'value', 'z score', 'probability of do value', 'probability of not do value',\r\n 'probability difference', 'p value', 'support']\r\n with open(out_dir + '/root' + '.csv', 'w', newline='') as csvfile:\r\n spamwriter = csv.writer(csvfile, delimiter=',',\r\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\r\n spamwriter.writerow(title)\r\n for cell in cell_list:\r\n a_list = cell.get_variable_list1()\r\n spamwriter.writerow(a_list)\r\n\r\n\r\ndef generate_causal_tree(probability_file, feature_file, out_dir, threshold=100):\r\n def myFunc(e):\r\n return e.get_variable_list1()[2]\r\n\r\n condition_list = []\r\n cell_list = causal_tree(feature_file, probability_file, threshold, condition_list)\r\n cell_list.sort(reverse=True, key=myFunc)\r\n stack = cell_list\r\n total_cell_list = []\r\n\r\n while not stack == []:\r\n one_cell = stack[0]\r\n condition_term = one_cell.get_variable_list2()[1]\r\n condition_list = one_cell.get_variable_list2()[8].copy()\r\n if one_cell.get_variable_list2()[3] >= 0.5:\r\n condition_list.append(condition_term)\r\n if len(condition_list) > 3:\r\n stack.pop(0)\r\n continue\r\n cell_list = causal_tree(feature_file, probability_file, threshold, condition_list)\r\n cell_list.sort(reverse=True, key=myFunc)\r\n total_cell_list.append(one_cell)\r\n stack.pop(0)\r\n stack = stack + cell_list\r\n else:\r\n stack.pop(0)\r\n\r\n title = ['level', 'route', 'Feature', 'value', 'z score', 'probability of do value', 'probability of not do value',\r\n 'probability difference', 'p value', 'support']\r\n if not os.path.exists(out_dir):\r\n os.mkdir(out_dir)\r\n with open(out_dir + '/causal_tree.csv', 'w', newline='') as csvfile:\r\n spamwriter = csv.writer(csvfile, delimiter=',',\r\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\r\n spamwriter.writerow(title)\r\n current_level = 0\r\n for cell in total_cell_list:\r\n a_list = cell.get_variable_list2()\r\n route = '->'.join(a_list[-1])\r\n line = []\r\n line.append(len(a_list[-1]))\r\n line.append(route)\r\n line = line + cell.get_variable_list1()\r\n if current_level < len(a_list[-1]):\r\n current_level = len(a_list[-1])\r\n spamwriter.writerow([])\r\n spamwriter.writerow(line)\r\n\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser()\r\n\r\n parser.add_argument('--probability-file', type=str, default='./')\r\n parser.add_argument('--feature-file', type=str, default='../../dat/Analgesics-induced_acute_liver_failure/feature.tsv')\r\n parser.add_argument('--out-dir', type=str, default='../output')\r\n\r\n args = parser.parse_args()\r\n causal_inference(args.probability_file, args.feature_file, args.out_dir)\r\n generate_causal_tree(args.probability_file, args.feature_file, args.out_dir)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"src/Analgesics-induced_acute_liver_failure/causal_inference.py","file_name":"causal_inference.py","file_ext":"py","file_size_in_byte":12141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"454755099","text":"import collections\nimport functools\nimport random\n\n\nclass Kdtree(collections.namedtuple('Kdtree', ['point', 'left', 'right'])):\n __slots__ = ()\n\n def nearest(self, point, axis=0, best=None):\n newdist = dist(point, self.point)\n if (not best) or newdist < best[1]:\n best = self.point, newdist\n\n next_axis = (axis + 1) % len(point)\n\n if point[axis] < self.point[axis]:\n first, second = self.left, self.right\n else:\n first, second = self.right, self.left\n\n if first:\n best = first.nearest(point, next_axis, best)\n\n if second and (self.point[axis] - point[axis])**2 < best[1]:\n best = second.nearest(point, next_axis, best)\n\n return best\n\n def nearest_point(self, point):\n return self.nearest(point)[0]\n\n def points(self):\n yield self.point\n if self.left:\n yield from self.left.points()\n if self.right:\n yield from self.right.points()\n\n\ndef dist(p1, p2):\n return sum((c1 - c2)**2 for (c1, c2) in zip(p1, p2))\n\ndef insert_point(kdtree, point, axis=0):\n if kdtree:\n next_axis = (axis + 1) % len(point)\n if point[axis] < kdtree.point[axis]:\n return Kdtree(point=kdtree.point,\n left=insert_point(kdtree.left, point, next_axis),\n right=kdtree.right)\n else:\n return Kdtree(point=kdtree.point,\n left=kdtree.left,\n right=insert_point(kdtree.right, point, next_axis))\n else:\n return Kdtree(point=point, left=None, right=None)\n\ndef remove_point(kdtree, point, axis=0):\n if kdtree:\n next_axis = (axis + 1) % len(point)\n if kdtree.point == point:\n stree = None\n for spoint in kdtree.points():\n if spoint != point:\n stree = insert_point(stree, spoint, axis)\n return stree\n elif point[axis] < kdtree.point[axis]:\n return Kdtree(point=kdtree.point,\n left=remove_point(kdtree.left, point, next_axis),\n right=kdtree.right)\n else:\n return Kdtree(point=kdtree.point,\n left=kdtree.left,\n right=remove_point(kdtree.right, point, next_axis))\n else:\n return None\n\ndef test(point_count=1000, test_count=100):\n def random_point():\n return (random.uniform(0, 100), random.uniform(0, 100))\n\n points = [random_point() for _ in range(point_count)]\n kdtree = None\n for point in points:\n kdtree = insert_point(kdtree, point)\n\n def nearest_fix(qpoint):\n bpoint = min(points, key=functools.partial(dist, qpoint))\n bdist = dist(bpoint, qpoint)\n return (bpoint, bdist)\n\n def nearest_tree(qpoint):\n return kdtree.nearest(qpoint)\n\n for _ in range(test_count):\n qpoint = random_point()\n nf = nearest_fix(qpoint)\n nt = nearest_tree(qpoint)\n assert(nf[1] == nt[1])\n #\n # remove too\n #\n rp = random.choice(points)\n points.remove(rp)\n kdtree = remove_point(kdtree, rp)\n\n\ntest()\n","sub_path":"kdtree.py","file_name":"kdtree.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"595141032","text":"import re\nimport json\nfrom collections import namedtuple\nfrom types import InstanceType, ClassType\n\ndef merge_dict(a, b, path=None):\n \"\"\"\n Merge two dictionaries together. Do not overwrite duplicate keys.\n\n :param a: The first dictionary\n :type a: dict\n :param b: The second dictionary\n :type b: dict\n :param path: Not really sure what this does, using re-purposed code here\n :type path: list\n \"\"\"\n if path is None: path = []\n for key in b:\n if key in a:\n if isinstance(a[key], dict) and isinstance(b[key], dict):\n merge_dict(a[key], b[key], path + [str(key)])\n elif a[key] == b[key]:\n pass\n else:\n raise Exception('Conflict at {0}'.format('.'.join(path + [str(key)])))\n else:\n a[key] = b[key]\n return a\n\nclass PowerConsul_Collection(object):\n \"\"\"\n Construct an immutable collection from a dictionary.\n \"\"\"\n def __init__(self, init_data=None):\n \"\"\"\n Initialize a new collection object.\n\n :param init_data: An optional dictionary used to initialize the collection\n :type init_data: dict\n \"\"\"\n self.class_name = self.__class__.__name__\n if init_data:\n if isinstance(init_data, dict):\n\n # Check if creating a collection from a Django QueryDict\n if re.match(r'^]*>$', str(obj))):\n return True\n\n # Test for a new style class\n if ((hasattr(obj, '__class__')) and (re.match(r'^$'.format(cls), repr(obj.__class__)))):\n return True\n return False\n\n def get(self):\n \"\"\"\n Retrieve the constructed collection objects. Converts the internal\n dictionary collection to a named tuple.\n\n :rtype: namedtuple\n \"\"\"\n def obj_mapper(d):\n \"\"\"\n Map a dictionary to a named tuple object based on dictionary keys\n\n :param d: The dictionary to map\n :type d: dict\n :rtype: namedtuple\n \"\"\"\n return namedtuple(self.class_name, d.keys())(*d.values())\n\n # Check if creating a collection of classes\n class_collection = False\n for key, obj in self.collection.iteritems():\n if self.isclass(self.collection[key], key):\n class_collection = True\n break\n\n # Map the data to an object and return\n if class_collection:\n return namedtuple(self.class_name, self.collection.keys())(*self.collection.values())\n else:\n data = json.dumps(self.collection)\n return json.loads(data, object_hook=obj_mapper)\n\n @classmethod\n def create(cls, data):\n \"\"\"\n Create a new collection.\n\n :param data: The source dictionary\n :type data: dict\n :rtype: namedtuple\n \"\"\"\n return cls(data).get()\n","sub_path":"powerconsul/common/collection.py","file_name":"collection.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"605796648","text":"import email\nimport json\nimport logging\nimport os\nimport sys\nfrom datetime import date, datetime, timedelta\nfrom getpass import getpass\nfrom imaplib import IMAP4\nfrom time import sleep\n\nimport requests\nfrom dateutil import parser\nfrom dateutil.tz import tzutc\nfrom imbox import Imbox\nfrom imbox.parser import parse_email\n\nlogging.basicConfig()\n\n\nclass MailCrawler(object):\n parser_urls = None\n indexer_url = os.environ['INDEXER_URL']\n indexer_token = os.environ.get('INDEXER_TOKEN')\n\n def __init__(self):\n self.imap_url = os.environ.get('IMAP_URL')\n self.imap_user = os.environ.get('IMAP_USER')\n self.imap_pass = os.environ.get('IMAP_PASS')\n self.imap_folder = os.environ.get('IMAP_FOLDER', False)\n\n def get_parsers(self):\n \"\"\"Retrieves a list of parser hosts\"\"\"\n if self.parser_urls is None:\n self.parser_urls = os.environ.get('PARSERS', '').split(',')\n return self.parser_urls\n\n def parse_message(self, message):\n \"\"\"Parses tokens from an email message\"\"\"\n body = self.get_email_body(message)\n if not body:\n print('No email text returned')\n return []\n\n results = []\n for parser_url in self.get_parsers():\n # print('Parsing email text... ', text)\n response = requests.post(\n parser_url+'/parse',\n json={\n 'from': message.sent_from,\n 'subject': message.subject,\n 'message': body,\n },\n )\n response.raise_for_status()\n print('Got response', response.text)\n results += response.json()\n return results\n\n def get_server(self):\n \"\"\"Returns an active IMAP server\"\"\"\n return Imbox(\n self.imap_url,\n username=self.imap_user,\n password=self.imap_pass,\n ssl=True,\n )\n\n def get_email_body(self, message):\n \"\"\"Get the body from the message\"\"\"\n has_body = message.body.get('html') or message.body.get('plain')\n if not has_body:\n return None\n # Concat all known body content together since it doesn't really matter\n return {\n 'html': ''.join([text\n for text in message.body.get('html')\n if isinstance(text, str)]),\n 'plain': ''.join([text\n for text in message.body.get('plain')\n if isinstance(text, str)])\n }\n\n def index_token(self, message):\n \"\"\"Sends a token from the parser to the indexer\"\"\"\n headers = {}\n if self.indexer_token:\n headers['Authorization'] = 'Bearer %s' % self.indexer_token\n\n response = requests.post(\n self.indexer_url+'/token',\n json=message,\n headers=headers,\n )\n response.raise_for_status()\n return response.json()\n\n def process_message(self, message):\n \"\"\"Process a single email message\"\"\"\n for result in self.parse_message(message):\n result.update({\n 'subject': message.subject,\n })\n print('Parsed result: ', result)\n print('Indexed result: ', self.index_token(result))\n\n\n def process_messages(self, server, since_date, last_message=0):\n for uid, message in server.messages(date__gt=since_date,\n folder=self.imap_folder):\n uid = int(uid)\n if uid <= last_message:\n print('DDB Already seen message with uid {}. Skipping'.format(uid))\n continue\n\n print(\n 'Processing message uid {} message_id {} '\n 'with subject \"{}\"'.format(\n uid, getattr(message, 'message_id', '?'), message.subject\n )\n )\n try:\n self.process_message(message)\n except Exception as e:\n logging.error(\n 'An error occured while processing message %s%s: %s.',\n uid,\n ((' (%s)' % message.subject)\n if hasattr(message, 'subject') else ''),\n str(e)\n )\n\n # Update since_date\n try:\n message_date = parser.parse(message.date, fuzzy=True)\n print(\n 'DDB Processed message. Message date: %s Old date: %s' %\n (message_date, since_date)\n )\n if since_date:\n since_date = max(since_date, message_date)\n else:\n since_date = message_date\n except ValueError:\n logging.warning('Invalid date encountered: %s.', message.date)\n print('DDB Since date is now ', since_date)\n last_message = max(uid, last_message)\n\n return since_date, last_message\n\n\n def run_against_imap(self):\n print('Starting crawler')\n # TODO: Put server into some kind of context manager and property\n with self.get_server() as server:\n # TODO: parameterize startup date, maybe relative\n since_date = False # Start back from origin\n last_message = 0\n while True:\n print('Lets process')\n since_date, last_message = self.process_messages(\n server,\n since_date,\n last_message=last_message\n )\n print('DDB Processed all. New since_date', since_date)\n # TODO: parameterize sleep\n # Sleep for 10 min\n sleep(10 * 60)\n\n def run_against_stdin(self):\n print('Running crawler on stdin')\n message = parse_email(sys.stdin.read())\n self.process_message(message)\n print('Done')\n\n def run(self):\n if self.imap_url and self.imap_user and self.imap_pass:\n while True:\n try:\n self.run_against_imap()\n except IMAP4.abort:\n print('Imap abort. We will try to reconnect')\n pass\n else:\n self.run_against_stdin()\n\n\nif __name__ == '__main__':\n MailCrawler().run()\n","sub_path":"crawlers/imap-crawler/imapCrawler/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"353468267","text":"import time\nfrom datetime import datetime\n\nfrom data_pretreatment.data_handle.update_all_count import updateAllCount\nfrom data_pretreatment.logConfig import logger,errorMessage\nfrom data_pretreatment.common_func.deal_data_by_redis import getFlagValue,saveData\n\ndef updateMysql():\n try:\n nowdate=datetime.today().date()\n while True:\n if nowdate!=datetime.today().date(): #到了新的一天了\n if int(time.strftime(\"%H%M%S\"))>63000: #凌晨两点半开始更新\n updateAllCount()\n nowdate=datetime.today().date() #日期更新为今天\n restartFlag=getFlagValue('restartFlag') #重新统计标识为1时,也要重新更新\n if restartFlag=='1':\n updateAllCount()\n saveData('restartFlag',0)\n time.sleep(1800) #每次循环间隔半小时\n except Exception as e:\n # _, reason, exc_tb = sys.exc_info()\n # error = traceback.extract_tb(exc_tb)\n # result = error[len(error) - 1]\n # message = (\"file: %s--line: %s--errorfunc: %s()--reason: %s\" % (result[0], result[1], result[2], reason))\n logger.critical(errorMessage(e))\n","sub_path":"systemServe/data_pretreatment/update_mysql.py","file_name":"update_mysql.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"186682446","text":"from django.test import TestCase\nfrom django.test import Client\nfrom django.urls import reverse\nfrom aliss.tests.fixtures import Fixtures\nfrom aliss.models import Organisation, ALISSUser, Service, Location\nimport mock\nimport geopy\n\nclass LocationViewTestCase(TestCase):\n def setUp(self):\n self.service = Fixtures.create()\n self.organisation = self.service.organisation\n self.location = self.organisation.locations.first()\n self.client.login(username=\"claimant@user.org\", password=\"passwurd\")\n\n\n def test_location_edit(self):\n path=reverse('location_edit', kwargs={'pk':self.location.pk})\n self.assertEqual(self.client.get(path).status_code, 200)\n self.client.login(username=\"updater@aliss.org\", password='passwurd') #editor\n self.assertEqual(self.client.get(path).status_code, 302)\n\n\n def test_location_update(self):\n with mock.patch('aliss.forms.LocationForm.geocode_address') as mock_geocode_address:\n mock_geocode_address.return_value = geopy.location.Location(\n \"Newkirkgate, Leith, Edinburgh, City of Edinburgh, Scotland, EH6 6AB, United Kingdom\",\n (55.9714304, -3.1715182)\n )\n path=reverse('location_edit', kwargs={'pk':self.location.pk})\n response = self.client.post(path,\n { 'name': 'Leith Community Education Centre', 'street_address': '12A Newkirkgate',\n 'locality': 'Edinburgh', 'postal_code': 'EH6 6AD' })\n\n self.location.refresh_from_db()\n self.assertEqual(self.location.name, 'Leith Community Education Centre')\n self.assertTrue(mock_geocode_address.called)\n self.assertEqual(self.location.latitude, 55.9714304)\n self.assertEqual(self.location.longitude, -3.1715182)\n self.assertEqual(response.status_code, 302)\n\n\n def test_location_create(self):\n x=reverse('location_create', kwargs={'pk':self.organisation.pk})\n response = self.client.get(x)\n self.assertEqual(response.status_code, 200)\n\n\n def test_logout_location_create(self):\n self.client.logout()\n response = self.client.get(reverse('location_create', kwargs={'pk':self.organisation.pk}))\n self.assertEqual(response.status_code, 302)\n\n\n def tearDown(self):\n Fixtures.organisation_teardown()\n","sub_path":"aliss/tests/views/test_location_view.py","file_name":"test_location_view.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"653659948","text":"# login code modified from https://gist.github.com/guillaumevincent/4771570\nimport tornado.auth\nimport tornado.escape\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nimport tornado.websocket\nfrom tornado.options import define, options\nfrom os.path import dirname, join\nfrom base64 import b64encode\nfrom uuid import uuid4\n\nfrom qiita_core.qiita_settings import qiita_config\nfrom qiita_pet.handlers.base_handlers import (MainHandler, NoPageHandler)\nfrom qiita_pet.handlers.auth_handlers import (\n AuthCreateHandler, AuthLoginHandler, AuthLogoutHandler, AuthVerifyHandler)\nfrom qiita_pet.handlers.user_handlers import (\n ChangeForgotPasswordHandler, ForgotPasswordHandler, UserProfileHandler)\nfrom qiita_pet.handlers.analysis_handlers import (\n SelectCommandsHandler, AnalysisWaitHandler, AnalysisResultsHandler,\n ShowAnalysesHandler, SearchStudiesHandler)\nfrom qiita_pet.handlers.study_handlers import (\n CreateStudyHandler, PrivateStudiesHandler, PublicStudiesHandler,\n StudyDescriptionHandler, MetadataSummaryHandler, EBISubmitHandler,\n CreateStudyAJAX)\nfrom qiita_pet.handlers.logger_handlers import LogEntryViewerHandler\nfrom qiita_pet.handlers.websocket_handlers import MessageHandler\nfrom qiita_pet.handlers.upload import UploadFileHandler\nfrom qiita_pet.handlers.compute import ComputeCompleteHandler\nfrom qiita_pet.handlers.preprocessing_handlers import PreprocessHandler\nfrom qiita_db.util import get_db_files_base_dir\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\n\nDIRNAME = dirname(__file__)\nSTATIC_PATH = join(DIRNAME, \"static\")\nTEMPLATE_PATH = join(DIRNAME, \"templates\") # base folder for webpages\nRES_PATH = get_db_files_base_dir()\nCOOKIE_SECRET = b64encode(uuid4().bytes + uuid4().bytes)\nDEBUG = qiita_config.test_environment\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/\", MainHandler),\n (r\"/auth/login/\", AuthLoginHandler),\n (r\"/auth/logout/\", AuthLogoutHandler),\n (r\"/auth/create/\", AuthCreateHandler),\n (r\"/auth/verify/(.*)\", AuthVerifyHandler),\n (r\"/auth/forgot/\", ForgotPasswordHandler),\n (r\"/auth/reset/(.*)\", ChangeForgotPasswordHandler),\n (r\"/profile/\", UserProfileHandler),\n (r\"/results/(.*)\", tornado.web.StaticFileHandler,\n {\"path\": RES_PATH}),\n (r\"/static/(.*)\", tornado.web.StaticFileHandler,\n {\"path\": STATIC_PATH}),\n (r\"/analysis/2\", SearchStudiesHandler),\n (r\"/analysis/3\", SelectCommandsHandler),\n (r\"/analysis/wait/(.*)\", AnalysisWaitHandler),\n (r\"/analysis/results/(.*)\", AnalysisResultsHandler),\n (r\"/analysis/show/\", ShowAnalysesHandler),\n (r\"/consumer/\", MessageHandler),\n (r\"/error/\", LogEntryViewerHandler),\n (r\"/metadata_summary/(.*)\", MetadataSummaryHandler),\n (r\"/ebi_submission/(.*)\", EBISubmitHandler),\n (r\"/compute_complete/(.*)\", ComputeCompleteHandler),\n (r\"/study/create/\", CreateStudyHandler),\n (r\"/study/private/\", PrivateStudiesHandler),\n (r\"/study/public/\", PublicStudiesHandler),\n (r\"/study/preprocess\", PreprocessHandler),\n (r\"/study/description/(.*)\", StudyDescriptionHandler),\n (r\"/upload/\", UploadFileHandler),\n (r\"/check_study/\", CreateStudyAJAX),\n # 404 PAGE MUST BE LAST IN THIS LIST!\n (r\".*\", NoPageHandler)\n ]\n settings = {\n \"template_path\": TEMPLATE_PATH,\n \"debug\": DEBUG,\n \"cookie_secret\": COOKIE_SECRET,\n \"login_url\": \"/auth/login/\"\n }\n tornado.web.Application.__init__(self, handlers, **settings)\n\n\ndef main():\n tornado.options.parse_command_line()\n http_server = tornado.httpserver.HTTPServer(Application())\n http_server.listen(options.port)\n print(\"Tornado started on port\", options.port)\n tornado.ioloop.IOLoop.instance().start()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"qiita_pet/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"28764534","text":"import logging\nfrom typing import Dict\n\nimport pyudev\nimport rx\nfrom rx import Observable\nfrom rx.core.typing import Observer\nfrom rx.subjects import Subject\nfrom serial import Serial\n\nfrom bus import Bus, ModBus, CanBus\nfrom config import portconfig\nfrom enums.protocol import Protocol\nfrom ttyscanner import TtyScanner\n\n\nclass NoPortConfigException(Exception):\n\n def __init__(self, device: pyudev.Device):\n super().__init__(f\"No port config found for {device}\")\n\n\nclass BusManager(object):\n\n def __init__(self) -> None:\n\n self.__bus_subject = Subject()\n self.__bus_map: Dict[str, Bus] = dict()\n self.__scanner = TtyScanner()\n\n x = Observer()\n\n\n self.__scanner.added_devices.s\n self.__scanner.added_devices.subscribe(lambda device: self.__tty_opened(device))\n self.__scanner.removed_devices.subscribe(self.__tty_closed)\n self.__scanner.removed_devices.subscribe(Observer())\n self.__scanner.scan()\n\n def __tty_opened(self, device: pyudev.Device) -> None:\n\n try:\n bus = self.__create_bus(device)\n self.__bus_map[device.device_node] = bus\n self.__bus_subject.on_next(bus)\n\n except NoPortConfigException as e:\n logging.warning(e)\n\n def __tty_closed(self, device: pyudev.Device) -> None:\n\n if device.device_node not in self.__bus_map:\n return\n\n bus = self.__bus_map.pop(device.device_node)\n bus.close(f\"Port {bus.serial.port} disconnected\")\n\n def get_buses(self) -> Observable:\n\n return rx.concat(\n rx.from_list(self.__bus_map.values()),\n self.__bus_subject\n )\n\n def dispose(self) -> None:\n\n self.__scanner.stop()\n\n for bus in self.__bus_map.values():\n bus.close()\n\n self.__bus_subject.dispose()\n\n @staticmethod\n def __create_bus(device: pyudev.Device) -> Bus:\n\n protocol = portconfig.get_protocol(device)\n\n serial = Serial(\n port=device.device_node,\n baudrate=9600\n )\n\n if protocol is Protocol.MODBUS:\n return ModBus(serial)\n\n if protocol is Protocol.CANBUS:\n return CanBus(serial)\n\n raise NoPortConfigException(device)\n","sub_path":"busmanager.py","file_name":"busmanager.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"82893097","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom apifortune.lib.Twilio.twilio_lib import TWILIO_SID\nfrom apifortune.models.fortune_user import FortuneUser\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass Twilio(APIView):\n\tauthentication_classes = ()\n\tpermission_classes = ()\n\n\tdef post(self, request, format=None):\n\t\tdata = request.data\n\t\tif data['AccountSid'][0] != TWILIO_SID:\n\t\t\tlogger.info(\"Invalid Post Request Attempted\")\n\t\t\treturn\n\t\tfrom_number = data['From'][0]\n\t\tbody = data['BODY'][0]\n\t\tuser = FortuneUser.objects.get(phone_number=from_number)\n\t\tif user and body in ['STOP', 'stop']:\n\t\t\tuser.is_subscribed = False\n\t\t\ttry:\n\t\t\t\tuser.save()\n\t\t\t\tlogger.info(\"User Unsubscribed %s\", from_number)\n\t\t\texcept:\n\t\t\t\tlogger.info(\"Unable to Unsubscribe User %s\", from_number)\n\t\treturn Response(\n\t\t\tdata,\n\t\t\tstatus=status.HTTP_200_OK\n\t\t)\n","sub_path":"fortunecookie/apifortune/views/twilio_reply.py","file_name":"twilio_reply.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"417261903","text":"import keras, os\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Activation, Flatten, MaxPool2D, Dropout\nfrom keras.datasets import cifar10\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\n\nbatch_size = 32\nnum_classes = 10\nepochs = 5\ndata_augmentation = False\nsave_dir = os.path.join(os.getcwd(), 'log')\nmodel_name = 'cifar10_trained_model.h5'\n\n# load cifar10 dateset\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\nprint('x_train shape:', x_train.shape)\nprint('x_test shape:', x_test.shape)\nprint(x_train.shape[0], 'train examples')\nprint(x_test.shape[0], 'test examples')\n\ny_train = to_categorical(y_train, num_classes)\ny_test = to_categorical(y_test, num_classes)\n\n# Model\nmodel = Sequential()\n\n# add some layers\nmodel.add(Conv2D(32, (3, 3), padding='same',\n input_shape=x_train.shape[1:]))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(32, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPool2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes))\nmodel.add(Activation('softmax'))\n\n# configure learning process\nopt = keras.optimizers.adam()\nmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\n\nif not data_augmentation:\n print('Not using data augmentation.')\n model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n validation_data=(x_test, y_test),\n shuffle=True)\nelse:\n print('Using real-time data augmentation.')\n # This will do preprocessing and realtime data augmentation:\n datagen = ImageDataGenerator(\n featurewise_center=False, # set input mean to 0 over the dataset\n samplewise_center=False, # set each sample mean to 0\n featurewise_std_normalization=False, # divide inputs by std of the dataset\n samplewise_std_normalization=False, # divide each input by its std\n zca_whitening=False, # apply ZCA whitening\n rotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)\n width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)\n height_shift_range=0.1, # randomly shift images vertically (fraction of total height)\n horizontal_flip=True, # randomly flip images\n vertical_flip=False) # randomly flip images\n\n # Compute quantities required for feature-wise normalization\n # (std, mean, and principal components if ZCA whitening is applied).\n datagen.fit(x_train)\n\n # Fit the model on the batches generated by datagen.flow().\n model.fit_generator(datagen.flow(x_train, y_train,\n batch_size=batch_size),\n epochs=epochs,\n validation_data=(x_test, y_test),\n workers=4)\n\n# Save model and weights\nif not os.path.isdir(save_dir):\n os.makedirs(save_dir)\nmodel_path = os.path.join(save_dir, model_name)\nmodel.save(model_path)\nprint('Saved trained model at %s ' % model_path)\n\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\n","sub_path":"cifar10_cnn.py","file_name":"cifar10_cnn.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"373634826","text":"#problema2\n\nsuc=open('sucursales.txt','r')\nmens1=[]\ni=0\nfor line in suc:\n\tmens1.append(line.split(\",\"))\n\tmens1[i].pop(2)\n\tmens1[i][0]=int(mens1[i][0])\n\ti=i+1 \nprint (mens1)\n#mens=(f.readline().split(\",\"))\n#mens.pop(2)\n#print (mens)\nart=open('articulos.txt','r')\nmens2=[]\ni=0\nfor line in art:\n\tmens2.append(line.split(\",\"))\n\tmens2[i].pop(3)\n\tmens2[i][0]=int(mens2[i][0])\n\tmens2[i][2]=float(mens2[i][2])\n\ti=i+1 \nprint (mens2)\n\naxs=open('articulosXsucursal.txt','r')\nmens3=[]\ni=0\naux=[]\nfor line in axs:\n\tmens3.append(line.split(\",\"))\n\tmens3[i].pop(4)\n\tmens3[i][0]=int(mens3[i][0])\n\tmens3[i][1]=int(mens3[i][1])\n\tmens3[i][2]=int(mens3[i][2])\n\tmens3[i][3]=int(mens3[i][3])\n\ti=i+1 \n\taux.append([0,0])\nprint (mens3)\n\nsal=[]\nnaxs=len(mens3)\nfor i in range (0,naxs):\n\tcodart=mens3[i][1]\n\tcodsuc=mens3[i][2]\n\tcant=mens3[i][3]\n\tcantaux=aux[codart][1]\n\tsucaux=aux[codart][0]\n\tif cant==0:\n\t\tif cantaux>5:\n\t\t\tsal.append([codsuc,codart,mens2[codart-1][1]])\n\t\t\tcantaux=None\t\t\n\t\telse:\n\t\t\taux[codart]=[codsuc,cant]\n\telif cant>5:\n\t\tif cantaux==0 and sucaux!=0:\n\t\t\tsal.append([sucaux,codart,mens2[codart-1][1]])\n\t\t\tcantaux=None\n\t\telse:\n\t\t\taux[codart]=[codsuc,cant]\nprint ('auxiliar')\nprint (aux)\nprint ('salida')\nprint (sal)\n","sub_path":"problema2.py","file_name":"problema2.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"604566881","text":"import requests as s\nfrom bs4 import BeautifulSoup\n\nreq_headers = {\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'en-US,en;q=0.8',\n 'upgrade-insecure-requests': '1',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'\n}\n\nall_data = []\n\nurl = 'https://www.zillow.com/austin-tx/home-values/:formatted/'\nr = s.get(url, headers=req_headers)\nsoup = BeautifulSoup(r.content, 'html.parser')\nprint(soup.prettify())\nprint(soup.find('li.legend-value'))\n\nfor ul in soup.find_all('ul'):\n lis=ul.find_all('li')\n for elem in lis:\n all_data.append(elem.text.strip())\n\nprint(all_data)\n","sub_path":"scrapy_file/b_soup_zellow.py","file_name":"b_soup_zellow.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"387610847","text":"import sys\nsys.path.insert(0, '../../../')\nimport numpy as np\nfrom bokeh.themes import Theme\nimport mut.viz\nimport mut.thermo\nimport bokeh.io\nimport bokeh.plotting\nfrom bokeh import events\nfrom bokeh.models import ColumnDataSource, Div, CustomJS, CDSView, IndexFilter\nfrom bokeh.layouts import layout, widgetbox\nfrom bokeh.models.widgets import Select, Slider, RadioButtonGroup, Button, RangeSlider\npboc = mut.viz.color_selector('pboc')\nbokeh.plotting.output_file(\"sensitivity.html\")\n\n# Define python functions for computing the WT parameter sensitivities\ndef deriv_epai(ep_value, c, ka, ki, n):\n allo_ratio = ((ka * (ki + c))/ (ki * (ka + c)))**n\n return allo_ratio / (allo_ratio + np.exp(ep_value))\n\ndef deriv_c(ep, c_value, ka, ki, n):\n numer = -n * ((ka * (ki + c_value)) / (ki * (ka + c_value)))**n * (ka - ki)\n denom_a = (ka + c_value) * (ki + c_value)\n denom_b = ((ka * (ki + c_value) / (ki * (ka + c_value))))**n + np.exp(ep)\n return numer / (denom_a * denom_b)\n\ndef deriv_ka(ep, c, ka_value, ki, n):\n numer = -c * n * (ka_value * (ki + c) / (ki * (ka_value + c)))**n\n denom_a = ka_value * (ka_value + c) \n denom_b = ((ka_value * (ki + c)) / (ki * (ka_value + c)))**n + np.exp(ep)\n return numer / (denom_a * denom_b)\n\ndef deriv_ki(ep, c, ka, ki_value, n):\n numer = c * n * ((ka * (ki_value + c)) / (ki_value * (ka + c)))**n\n denom_a = ki_value * (ki_value + c) \n denom_b = ((ka * (ki_value + c)) / (ki_value * (ka + c)))**n + np.exp(ep)\n return numer / (denom_a * denom_b)\n\n# Don't permit adjustable ranges\nn_points = 300\nlog_ka_range = np.linspace(-4, 4, n_points)\nlog_ki_range = np.linspace(-4, 4, n_points)\nepAI_range = np.linspace(-8, 8, n_points)\nlog_c_range = np.linspace(-4, 4, n_points)\n\n# Define the sliders\nka_slider = Slider(title='log10(Ka / 1 µM)', value=np.log10(139), start=log_ka_range[0], \n end=log_ka_range[-1], step=0.01, \n bar_color=pboc['light_red'])\nki_slider = Slider(title='log10(Ki / 1µM)', value=np.log10(0.53), start=log_ki_range[0], \n end=log_ki_range[-1], step=0.01, bar_color=pboc['light_red'])\nepAI_slider = Slider(title='allosteric energy difference [kT]', value=4.5, \n start=-10, end=10, step=0.1, bar_color=pboc['light_red'])\nc_slider = Slider(title='log10(IPTG / 1µM)', value=np.log10(50), start=log_c_range[0], \n end=log_c_range[-1], step=0.01, bar_color=pboc['light_red'])\n\n# # Define the source data \nsource = ColumnDataSource(data={'ka':10**log_ka_range, 'ki':10**log_ki_range,\n 'epAI':epAI_range, 'c':10**log_c_range,\n 'dF_depAI':deriv_epai(epAI_range, 50, 139, 0.53, 2), \n 'dF_dka': deriv_ka(4.5, 50, 10**log_ka_range, 0.53, 2),\n 'dF_dki':deriv_ki(4.5, 50, 139, 10**log_ki_range, 2), \n 'dF_dc':deriv_c(4.5, 10**log_c_range, 139, 0.53, 2)})\n\n# Instantiate the figures \np_epAI = bokeh.plotting.figure(width=425, height=300, \n x_axis_label='allosteric energy difference [kT]',\n y_axis_label='∂∆F / ∂∆ε_AI',\n y_range=[-0.1, 1.1])\np_Ka = bokeh.plotting.figure(width=425, height=300, \n x_axis_type='log',\n x_axis_label = 'Ka [µM]',\n y_axis_label='∂∆F / ∂Ka' )\np_Ki = bokeh.plotting.figure(width=425, height=300, \n x_axis_type='log',\n x_axis_label = 'Ki [µM]',\n y_axis_label='∂∆F / ∂Ki')\np_c = bokeh.plotting.figure(width=425, height=300, \n x_axis_type='log',\n x_axis_label = 'IPTG [µM]',\n y_axis_label='∂∆F / ∂c')\n \n\n# Add initial glyphs. \np_epAI.line(x='epAI', y='dF_depAI', source=source, color=pboc['red'], line_width=2)\np_Ka.line(x='ka', y='dF_dka', source=source, color=pboc['red'], line_width=2)\np_Ki.line(x='ki', y='dF_dki', source=source, color=pboc['red'], line_width=2)\np_c.line(x='c', y='dF_dc', source=source, color=pboc['red'], line_width=2)\n\n# Define callback arguments\ncallback_args = {'source':source, 'Ka':ka_slider, 'Ki':ki_slider,\n 'EpAI':epAI_slider, 'C':c_slider, 'nSites':2,\n 'nPoints':n_points}\n\n# Load the callback files\nwith open(\"sensitivity.js\") as f:\n sensitivity = f.read()\n\ngeneral_callback = CustomJS(args=callback_args, code=sensitivity)\n_reset_callback = CustomJS(args=callback_args, code=\"\"\"\n var ka = 139; \n var ki = 0.53;\n var c = 50;\n var epAI = 4.5;\n var n = 2;\n Ka.value = Math.log10(ka);\n Ki.value = Math.log10(ki);\n EpAI.value = epAI;\n C.value = Math.log10(c);\n \"\"\")\n\n# Define the reset button\nreset = Button(label='Reset to default', callback=_reset_callback)\nreset.js_on_click(general_callback)\n\n# Trigger callbacks\nsliders = [epAI_slider, ka_slider, ki_slider, c_slider]\nfor s in sliders:\n s.callback = general_callback\n\n# Generate the layout\nparams = [epAI_slider, ka_slider, ki_slider, c_slider]\nlayout = bokeh.layouts.layout([[reset], [params[:2], params[2:]], \n [p_Ka, p_Ki], [p_epAI, p_c]])\n\n# #############################\n# THEME DETAILS\n# ############################\ntheme_json = {'attrs':\n {'Figure': {\n 'background_fill_color': '#E3DCD0',\n 'outline_line_color': '#FFFFFF',\n },\n 'Axis': {\n 'axis_line_color': \"white\",\n 'major_tick_in': 7,\n 'major_tick_line_width': 2.5,\n 'major_tick_line_color': \"white\",\n 'minor_tick_line_color': \"white\",\n 'axis_label_text_font': 'Helvetica',\n 'axis_label_text_font_style': 'normal'\n },\n 'Grid': {\n 'grid_line_color': None,\n },\n 'Legend': {\n 'background_fill_color': '#E3DCD0',\n 'border_line_color': '#FFFFFF',\n 'border_line_width': 1.5,\n 'background_fill_alpha': 0.5\n },\n 'Text': {\n 'text_font_style': 'normal',\n 'text_font': 'Helvetica'\n },\n 'Title': {\n 'background_fill_color': '#FFEDC0',\n 'text_font_style': 'normal',\n 'align': 'center',\n 'text_font': 'Helvetica',\n 'offset': 2,\n }}}\n\ntheme = Theme(json=theme_json)\nbokeh.io.curdoc().theme = theme\nbokeh.io.save(layout)\n","sub_path":"code/figures/js/sensitivity.py","file_name":"sensitivity.py","file_ext":"py","file_size_in_byte":6742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"581422071","text":"# Ked potrebujes nejaky help tak social medias mam na samuelmikula.com\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport time\nimport json\nimport datetime\n\n\ndelay = 1\nproxySupport = False\n\n# Staci zmenit Discord webhook na vlastny\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\nwebhook_url = 'https://discordapp.com/api/webhooks/XXXXXXXXXXXXXXXXXX/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\nlinks = {\n '16' : 'https://goout.net/cs/parties/addict-16-nobodylisten+cyber69+dalsi/oqkfe/+sjafm/',\n# 'kviff54' : 'https://goout.net/cs/parties/addict-kviff54-opening-rave-nobodylisten+dalsi/upeie/+kyljm/',\n}\n\n\nin_stock = {\n\t\"username\": \"Addict Monitor\",\n\t\"avatar_url\": \"https://i.imgur.com/1bxvsuI.png\",\n \"embeds\": [{\n \"author\": {\n \"name\": \"Addict\",\n \"icon_url\": \"https://i.imgur.com/6tzQCit.png\"\n },\n \"thumbnail\": {\n \"url\": \"https://goout.net/i/077/776867-800.jpg\"\n },\n \"description\": \"Restockli vstupenky na Addict #16.\",\n \"color\": 4634359,\n \"fields\":[\n {\n \"name\": \"Stav\",\n \"value\": \"Dostupné | [Koupit](https://goout.net/cs/listky/addict-16-nobodylisten+cyber69+dalsi/bmme/)\"\n }\n ],\n \"footer\": {\n \"text\": \"Addict Monitor\"\n }\n }]\n}\n\nrunning = {\n\t\"username\": \"Addict Monitor\",\n\t\"avatar_url\": \"https://i.imgur.com/1bxvsuI.png\",\n \"embeds\": [{\n \"author\": {\n \"name\": \"Addict\",\n \"icon_url\": \"https://i.imgur.com/6tzQCit.png\"\n },\n \"description\": \"Monitor byl právě spuštěn. :white_check_mark:\",\n \"color\": 4634359,\n \"footer\": {\n \"text\": \"Addict Monitor\"\n }\n }]\n}\n\nprint(\" ___ __ ___ __ \")\nprint(\" / _ |___/ /__/ (_)___/ /_\")\nprint(\" / __ / _ / _ / / __/ __/\")\nprint(\"/_/ |_\\_,_/\\_,_/_/\\__/\\__/ \")\nprint(\"\")\nprint(\"Addict Monitor by @samoinsecure\")\nresponse = requests.post(\nwebhook_url, data=json.dumps(running),\nheaders={'Content-Type': 'application/json'})\ntime.sleep(2)\nprint(\"\")\nprint(\"\")\n\n\ndef GetTime():\n a = datetime.datetime.now()\n currentTime = (\"[%s:%s:%s:%s] \" % (a.hour, a.minute, a.second, str(a.microsecond)[:-3]))\n return str(currentTime)\n\ndef monitorLocalhost():\n while True:\n for name in links:\n\n print(GetTime() + \"Monitoruju restocky na Addict listky.\")\n\n url = links[name]\n\n response = requests.get(url, headers=headers)\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n \n\n addictrestock = soup.findAll(\"a\", {\"class\": \"eventCard-button eventCard-button--buy eventCard-button--big\"})\n\n\n if addictrestock:\n print(GetTime() + \"Listky prave restocknuli!\")\n response = requests.post(\n webhook_url, data=json.dumps(in_stock),\n headers={'Content-Type': 'application/json'})\n else:\n print(GetTime() + \"Listky nerestocknuli.\")\n\n time.sleep(delay)\n\n\nif proxySupport:\n monitorProxy()\n\nelse:\n monitorLocalhost()\n","sub_path":"addict.py","file_name":"addict.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"72523992","text":"try:\r\n\tif (user < 2000000000):\r\n\t\tsend(user, 'Команда работает только в беседах!')\r\n\telse:\r\n\t\trandid = -1\r\n\t\ttext = text[text.index(word)+1]\r\n\t\tparam = (('v', '5.92'), ('peer_id', user), ('group_id', group_id), ('access_token', token))\r\n\t\tres = requests.post('https://api.vk.com/method/messages.getConversationMembers', data=param)\r\n\t\tres = json.loads(res.text)\r\n\t\twhile randid < 0:\r\n\t\t\trand = random.randint(0, (res['response']['count'])-1)\r\n\t\t\trandid = res['response']['items'][rand]['member_id']\r\n\t\t\treq[0][field]\r\n\t\treq = vk.users.get(user_ids = res['response']['items'][rand]['member_id'])\r\n\t\tname = req[0]['first_name']+' '+req[0]['last_name']\r\n\t\tif (random.randint(0,1)==0):\r\n\t\t\tsend(user, 'Возможно, что это - '+name)\r\n\t\telse:\r\n\t\t\tsend(user, 'Мне кажется, что это у нас '+name)\r\nexcept KeyError:\r\n\tsend(user, 'Для выполнение данной функции, необходимы права администратора.')\r\nexcept:\r\n\tsend(user, '⚠ Семпай! Произошла ошибка! Проверьте свой запрос.')","sub_path":"modules/default/who.py","file_name":"who.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"160304132","text":"#Import libraries\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n#Import Dataset\r\ndataset = pd.read_csv(\"Salary_data-TG.csv\")\r\nX = dataset.iloc[:,:-1].values\r\ny = dataset.iloc[:,1].values\r\n\r\n\r\n#Split the dataset for Training and Test\r\nfrom sklearn.model_selection import train_test_split\r\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.1,random_state=0)\r\nprint (X_test)\r\nprint (y_test)\r\n\r\n#Buidling Linear Regression Model\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor = LinearRegression()\r\n#Training the regressor object\r\nregressor.fit(X_train, y_train)\r\n\r\n#Predict the model\r\ny_pred = regressor.predict(X_test)\r\n\r\n#Visualize the train set results\r\nplt.scatter(X_train, y_train, color = 'red' )\r\nplt.plot(X_train,regressor.predict(X_train),color = 'blue')\r\nplt.title('Experience Vs Title (training set)')\r\nplt.xlabel('Years of Exp')\r\nplt.ylabel('Salary')\r\nplt.show()\r\n\r\n#Visualize the test set results\r\nplt.scatter(X_test, y_test, color = 'red' )\r\nplt.plot(X_test,regressor.predict(X_test),color = 'blue')\r\nplt.title('Experience Vs Title (Test set)')\r\nplt.xlabel('Years of Exp')\r\nplt.ylabel('Salary')\r\nplt.show()\r\n\r\n","sub_path":"3rd Day NOtes/LinearRegression-UPDATED.py","file_name":"LinearRegression-UPDATED.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"546190282","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n################################################################################\n#\n#\tRMG Website - A Django-powered website for Reaction Mechanism Generator\n#\n#\tCopyright (c) 2011 Prof. William H. Green (whgreen@mit.edu) and the\n#\tRMG Team (rmg_dev@mit.edu)\n#\n#\tPermission is hereby granted, free of charge, to any person obtaining a\n#\tcopy of this software and associated documentation files (the 'Software'),\n#\tto deal in the Software without restriction, including without limitation\n#\tthe rights to use, copy, modify, merge, publish, distribute, sublicense,\n#\tand/or sell copies of the Software, and to permit persons to whom the\n#\tSoftware is furnished to do so, subject to the following conditions:\n#\n#\tThe above copyright notice and this permission notice shall be included in\n#\tall copies or substantial portions of the Software.\n#\n#\tTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n#\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n#\tDEALINGS IN THE SOFTWARE.\n#\n################################################################################\n\nimport os\nimport os.path\nimport re\nimport socket\nimport StringIO # cStringIO is faster, but can't do Unicode\nimport copy\nimport time\nimport subprocess\n\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.http import Http404, HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nimport settings\n\nfrom rmgpy.molecule import Molecule\nfrom rmgpy.group import Group\nfrom rmgpy.thermo import *\nfrom rmgpy.kinetics import *\nfrom rmgpy.reaction import Reaction\n\nimport rmgpy\nfrom rmgpy.data.base import Entry, LogicNode\nfrom rmgpy.data.thermo import ThermoDatabase\nfrom rmgpy.data.kinetics import KineticsDatabase, TemplateReaction, DepositoryReaction, LibraryReaction, KineticsGroups\nfrom rmgpy.data.rmg import RMGDatabase\n\nfrom forms import *\nfrom tools import *\nfrom rmgweb.main.tools import *\n\n#from rmgweb.main.tools import moleculeToURL, moleculeFromURL\n\n################################################################################\n\ndef load(request):\n \"\"\"\n Load the RMG database and redirect to the database homepage.\n \"\"\"\n loadDatabase()\n return HttpResponseRedirect(reverse(index))\n \ndef index(request):\n \"\"\"\n The RMG database homepage.\n \"\"\"\n return render_to_response('database.html', context_instance=RequestContext(request))\n\ndef thermo(request, section='', subsection=''):\n \"\"\"\n The RMG database homepage.\n \"\"\"\n # Make sure section has an allowed value\n if section not in ['depository', 'libraries', 'groups', '']:\n raise Http404\n\n # Load the thermo database if necessary\n database = loadDatabase('thermo', section)\n\n if subsection != '':\n\n # A subsection was specified, so render a table of the entries in\n # that part of the database\n \n # Determine which subsection we wish to view\n try:\n database = getThermoDatabase(section, subsection)\n except ValueError:\n raise Http404\n\n # Sort entries by index\n entries0 = database.entries.values()\n entries0.sort(key=lambda entry: entry.index)\n\n entries = []\n for entry in entries0:\n\n structure = getStructureMarkup(entry.item)\n\n if isinstance(entry.data, ThermoData): dataFormat = 'Group additivity'\n elif isinstance(entry.data, Wilhoit): dataFormat = 'Wilhoit'\n elif isinstance(entry.data, MultiNASA): dataFormat = 'NASA'\n elif isinstance(entry.data, str): dataFormat = 'Link'\n \n if entry.data is None:\n dataFormat = 'None'\n entry.index = 0\n \n entries.append((entry.index,entry.label,structure,dataFormat))\n\n return render_to_response('thermoTable.html', {'section': section, 'subsection': subsection, 'databaseName': database.name, 'entries': entries}, context_instance=RequestContext(request))\n\n else:\n # No subsection was specified, so render an outline of the thermo\n # database components\n thermoDepository = [(label, depository) for label, depository in database.thermo.depository.iteritems()]\n thermoDepository.sort()\n thermoLibraries = [(label, database.thermo.libraries[label]) for label in database.thermo.libraryOrder]\n #If they weren't already sorted in our preferred order, we'd call thermoLibraries.sort()\n thermoGroups = [(label, groups) for label, groups in database.thermo.groups.iteritems()]\n thermoGroups.sort()\n return render_to_response('thermo.html', {'section': section, 'subsection': subsection, 'thermoDepository': thermoDepository, 'thermoLibraries': thermoLibraries, 'thermoGroups': thermoGroups}, context_instance=RequestContext(request))\n\ndef thermoEntry(request, section, subsection, index):\n \"\"\"\n A view for showing an entry in a thermodynamics database.\n \"\"\"\n\n # Load the thermo database if necessary\n loadDatabase('thermo', section)\n\n # Determine the entry we wish to view\n try:\n database = getThermoDatabase(section, subsection)\n except ValueError:\n raise Http404\n index = int(index)\n for entry in database.entries.values():\n if entry.index == index:\n break\n else:\n raise Http404\n\n # Get the structure of the item we are viewing\n structure = getStructureMarkup(entry.item)\n\n # Prepare the thermo data for passing to the template\n # This includes all string formatting, since we can't do that in the template\n if isinstance(entry.data, str):\n thermo = ['Link', database.entries[entry.data].index]\n else:\n thermo = entry.data\n \n referenceType = ''\n reference = entry.reference\n return render_to_response('thermoEntry.html', {'section': section, 'subsection': subsection, 'databaseName': database.name, 'entry': entry, 'structure': structure, 'reference': reference, 'referenceType': referenceType, 'thermo': thermo}, context_instance=RequestContext(request))\n\ndef thermoSearch(request):\n \"\"\"\n A view of a form for specifying a molecule to search the database for\n thermodynamics properties.\n \"\"\"\n\n # Load the thermo database if necessary\n loadDatabase('thermo')\n\n if request.method == 'POST':\n form = ThermoSearchForm(request.POST, error_class=DivErrorList)\n if form.is_valid():\n adjlist = form.cleaned_data['species']\n adjlist = adjlist.replace('\\n', ';')\n adjlist = re.sub('\\s+', '%20', adjlist)\n return HttpResponseRedirect(reverse(thermoData, kwargs={'adjlist': adjlist}))\n else:\n form = ThermoSearchForm()\n \n return render_to_response('thermoSearch.html', {'form': form}, context_instance=RequestContext(request))\n\ndef thermoData(request, adjlist):\n \"\"\"\n Returns an image of the provided adjacency list `adjlist` for a molecule.\n Note that the newline character cannot be represented in a URL;\n semicolons should be used instead.\n \"\"\"\n \n # Load the thermo database if necessary\n loadDatabase('thermo')\n from tools import database\n\n adjlist = str(adjlist.replace(';', '\\n'))\n molecule = Molecule().fromAdjacencyList(adjlist)\n species = Species(molecule=[molecule])\n species.generateResonanceIsomers()\n \n # Get the thermo data for the molecule\n thermoDataList = []\n for data, library, entry in database.thermo.getAllThermoData(species):\n if library is None:\n source = 'Group additivity'\n href = ''\n #data = convertThermoData(data, molecule, Wilhoit)\n #data = convertThermoData(data, molecule, MultiNASA)\n entry = Entry(data=data)\n elif library in database.thermo.depository.values():\n source = 'Depository'\n href = reverse(thermoEntry, kwargs={'section': 'depository', 'subsection': library.label, 'index': entry.index})\n elif library in database.thermo.libraries.values():\n source = library.name\n href = reverse(thermoEntry, kwargs={'section': 'libraries', 'subsection': library.label, 'index': entry.index})\n thermoDataList.append((\n entry,\n entry.data,\n source,\n href,\n ))\n \n # Get the structure of the item we are viewing\n structure = getStructureMarkup(molecule)\n\n return render_to_response('thermoData.html', {'structure': structure, 'thermoDataList': thermoDataList, 'plotWidth': 500, 'plotHeight': 400 + 15 * len(thermoDataList)}, context_instance=RequestContext(request))\n\n################################################################################\n\ndef getDatabaseTreeAsList(database, entries):\n \"\"\"\n Return a list of entries in a given database, sorted by the order they\n appear in the tree (as determined via a depth-first search).\n \"\"\"\n tree = []\n for entry in entries:\n # Write current node\n tree.append(entry)\n # Recursively descend children (depth-first)\n tree.extend(getDatabaseTreeAsList(database, entry.children))\n return tree\n\ndef getKineticsTreeHTML(database, section, subsection, entries):\n \"\"\"\n Return a string of HTML markup used for displaying information about\n kinetics entries in a given `database` as a tree of unordered lists.\n \"\"\"\n html = ''\n for entry in entries:\n # Write current node\n url = reverse(kineticsEntry, kwargs={'section': section, 'subsection': subsection, 'index': entry.index})\n html += '
  • \\n'\n html += '
    '\n if len(entry.children) > 0:\n html += ''.format(entry.index)\n else:\n html += ''\n html += '{1}. {2}\\n'.format(url, entry.index, entry.label)\n html += '
    \\n'\n if entry.data is not None:\n for T in [300,400,500,600,800,1000,1500,2000]:\n html += '{0:.2f} '.format(math.log10(entry.data.getRateCoefficient(T, P=1e5)))\n html += '
    \\n'\n # Recursively descend children (depth-first)\n if len(entry.children) > 0:\n html += '
      \\n'.format(entry.index)\n html += getKineticsTreeHTML(database, section, subsection, entry.children)\n html += '
    \\n'\n html += '
  • \\n'\n return html\n\ndef kinetics(request, section='', subsection=''):\n \"\"\"\n The RMG database homepage.\n \"\"\"\n # Make sure section has an allowed value\n if section not in ['libraries', 'families', '']:\n raise Http404\n\n # Load the kinetics database, if necessary\n rmgDatabase = loadDatabase('kinetics', section)\n\n # Determine which subsection we wish to view\n database = None\n try:\n database = getKineticsDatabase(section, subsection)\n except ValueError:\n pass\n\n if database is not None:\n\n # A subsection was specified, so render a table of the entries in\n # that part of the database\n\n isGroupDatabase = False\n\n # Sort entries by index\n if database.top is not None and len(database.top) > 0:\n # If there is a tree in this database, only consider the entries\n # that are in the tree\n entries0 = getDatabaseTreeAsList(database, database.top)\n tree = '
      \\n{0}\\n
    \\n'.format(getKineticsTreeHTML(database, section, subsection, database.top))\n else:\n # If there is not a tree, consider all entries\n entries0 = database.entries.values()\n # Sort the entries by index and label\n entries0.sort(key=lambda entry: (entry.index, entry.label))\n tree = ''\n \n entries = []\n\n for entry0 in entries0:\n\n dataFormat = ''\n\n if isinstance(entry0.data, KineticsData): dataFormat = 'KineticsData'\n elif isinstance(entry0.data, Arrhenius): dataFormat = 'Arrhenius'\n elif isinstance(entry0.data, str): dataFormat = 'Link'\n elif isinstance(entry0.data, ArrheniusEP): dataFormat = 'ArrheniusEP'\n elif isinstance(entry0.data, MultiKinetics): dataFormat = 'MultiKinetics'\n elif isinstance(entry0.data, PDepArrhenius): dataFormat = 'PDepArrhenius'\n elif isinstance(entry0.data, Chebyshev): dataFormat = 'Chebyshev'\n elif isinstance(entry0.data, Troe): dataFormat = 'Troe'\n elif isinstance(entry0.data, Lindemann): dataFormat = 'Lindemann'\n elif isinstance(entry0.data, ThirdBody): dataFormat = 'ThirdBody'\n\n entry = {\n 'index': entry0.index,\n 'label': entry0.label,\n 'dataFormat': dataFormat,\n }\n if isinstance(database, KineticsGroups):\n isGroupDatabase = True\n entry['structure'] = getStructureMarkup(entry0.item)\n entry['parent'] = entry0.parent\n entry['children'] = entry0.children\n elif 'rules' in subsection:\n entry['reactants'] = ' + '.join([getStructureMarkup(reactant) for reactant in entry0.item.reactants])\n entry['products'] = ' + '.join([getStructureMarkup(reactant) for reactant in entry0.item.products])\n entry['arrow'] = '⇔' if entry0.item.reversible else '→'\n else:\n entry['reactants'] = ' + '.join([moleculeToInfo(reactant) for reactant in entry0.item.reactants])\n entry['products'] = ' + '.join([moleculeToInfo(reactant) for reactant in entry0.item.products])\n entry['arrow'] = '⇔' if entry0.item.reversible else '→'\n \n entries.append(entry)\n \n return render_to_response('kineticsTable.html', {'section': section, 'subsection': subsection, 'databaseName': database.name, 'entries': entries, 'tree': tree, 'isGroupDatabase': isGroupDatabase}, context_instance=RequestContext(request))\n\n else:\n # No subsection was specified, so render an outline of the kinetics\n # database components\n kineticsLibraries = [(label, library) for label, library in rmgDatabase.kinetics.libraries.iteritems() if subsection in label]\n kineticsLibraries.sort()\n kineticsFamilies = [(label, family) for label, family in rmgDatabase.kinetics.families.iteritems() if subsection in label]\n kineticsFamilies.sort()\n return render_to_response('kinetics.html', {'section': section, 'subsection': subsection, 'kineticsLibraries': kineticsLibraries, 'kineticsFamilies': kineticsFamilies}, context_instance=RequestContext(request))\n\ndef getReactionUrl(reaction, family=None):\n \"\"\"\n Get the URL (for kinetics data) of a reaction.\n \n Returns '' if the reaction contains functional Groups or LogicNodes instead\n of real Species or Molecules.\"\"\"\n kwargs = dict()\n for index, reactant in enumerate(reaction.reactants):\n if isinstance(reactant, Group) or isinstance(reactant, LogicNode):\n return ''\n \n mol = reactant if isinstance(reactant,Molecule) else reactant.molecule[0]\n kwargs['reactant{0:d}'.format(index+1)] = moleculeToURL(mol)\n for index, product in enumerate(reaction.products):\n mol = product if isinstance(product,Molecule) else product.molecule[0]\n kwargs['product{0:d}'.format(index+1)] = moleculeToURL(mol)\n if family:\n kwargs['family']=family\n reactionUrl = reverse(kineticsGroupEstimateEntry, kwargs=kwargs)\n else:\n reactionUrl = reverse(kineticsData, kwargs=kwargs)\n return reactionUrl\n \n\n@login_required\ndef kineticsEntryNewTraining(request, family):\n \"\"\"\n A view for creating a new entry in a kinetics family training depository.\n \"\"\"\n # Load the kinetics database, if necessary\n loadDatabase('kinetics', 'families')\n try:\n database = getKineticsDatabase('families', family+'/training')\n except ValueError:\n raise Http404\n \n entry = None\n if request.method == 'POST':\n form = KineticsEntryEditForm(request.POST, error_class=DivErrorList)\n if form.is_valid():\n new_entry = form.cleaned_data['entry']\n \n # determine index for new entry (1 higher than highest)\n max_index = max(database.entries.keys() or [0])\n index = max_index + 1\n \n # check it's not already there\n for entry in database.entries.values():\n if entry.item.isIsomorphic(new_entry.item):\n kwargs = { 'section': 'families',\n 'subsection': family+'/training',\n 'index': entry.index,\n }\n forward_url = reverse(kineticsEntry, kwargs=kwargs)\n message = \"\"\"\n This reaction is already in the {0} training set.\n View or edit it at {1}.\n \"\"\".format(family, forward_url)\n return render_to_response('simple.html', { \n 'title': 'Reaction already in training set.',\n 'body': message,\n },\n context_instance=RequestContext(request))\n new_entry.index = index\n new_history = (time.strftime('%Y-%m-%d'),\n \"{0.first_name} {0.last_name} <{0.email}>\".format(request.user),\n 'action',\n \"New entry. \"+form.cleaned_data['change']\n )\n new_entry.history = [new_history]\n \n # Get the entry as a entry_string\n entry_buffer = StringIO.StringIO(u'')\n rmgpy.data.kinetics.saveEntry(entry_buffer, new_entry)\n entry_string = entry_buffer.getvalue()\n entry_buffer.close()\n \n # redirect when done\n kwargs = { 'section': 'families',\n 'subsection': family+'/training',\n 'index': index,\n }\n forward_url = reverse(kineticsEntry, kwargs=kwargs)\n \n if False:\n # Just return the text.\n return HttpResponse(entry_string, mimetype=\"text/plain\")\n if True:\n # save it\n database.entries[index] = new_entry\n path = os.path.join(settings.DATABASE_PATH, 'kinetics', 'families', family, 'training.py' )\n database.save(path)\n commit_author = \"{0.first_name} {0.last_name} <{0.email}>\".format(request.user)\n commit_message = \"New {family}/training/{index} reaction: {msg}\\n\\nNew kinetics/families/{family}/training entry number {index} submitted through RMG website:\\n{msg}\\n{author}\".format(family=family, index=index, msg=form.cleaned_data['change'], author=commit_author)\n commit_result = subprocess.check_output(['git', 'commit',\n '-m', commit_message,\n '--author', commit_author,\n path\n ], cwd=settings.DATABASE_PATH, stderr=subprocess.STDOUT)\n \n \n message = \"\"\"\n New training reaction saved succesfully:
    \n
    {0}

    \n See result at {1}.\n \"\"\".format(commit_result, forward_url)\n return render_to_response('simple.html', { \n 'title': 'New rate saved successfully.',\n 'body': message,\n },\n context_instance=RequestContext(request))\n \n else: # not POST\n form = KineticsEntryEditForm()\n \n return render_to_response('kineticsEntryEdit.html', {'section': 'families',\n 'subsection': family+'/training',\n 'databaseName': family,\n 'entry': entry,\n 'form': form,\n },\n context_instance=RequestContext(request))\n \n@login_required\ndef kineticsEntryEdit(request, section, subsection, index):\n \"\"\"\n A view for editing an entry in a kinetics database.\n \"\"\"\n\n # Load the kinetics database, if necessary\n loadDatabase('kinetics', section)\n\n # Determine the entry we wish to view\n try:\n database = getKineticsDatabase(section, subsection)\n except ValueError:\n raise Http404\n index = int(index)\n for entry in database.entries.values():\n if entry.index == index:\n break\n else:\n raise Http404\n \n if request.method == 'POST':\n form = KineticsEntryEditForm(request.POST, error_class=DivErrorList)\n if form.is_valid():\n new_entry = form.cleaned_data['entry']\n new_entry.index = index\n new_entry.history = copy.copy(entry.history)\n new_history = (time.strftime('%Y-%m-%d'),\n \"{0.first_name} {0.last_name} <{0.email}>\".format(request.user),\n 'action',\n form.cleaned_data['change']\n )\n new_entry.history.append(new_history)\n \n # Get the entry as a entry_string\n entry_buffer = StringIO.StringIO(u'')\n rmgpy.data.kinetics.saveEntry(entry_buffer, new_entry)\n entry_string = entry_buffer.getvalue()\n entry_buffer.close()\n \n if False:\n # Just return the text.\n return HttpResponse(entry_string, mimetype=\"text/plain\")\n if False:\n # Render it as if it were saved.\n return render_to_response('kineticsEntry.html', {'section': section,\n 'subsection': subsection,\n 'databaseName': database.name,\n 'entry': new_entry,\n 'reference': entry.reference,\n 'kinetics': entry.data,\n },\n context_instance=RequestContext(request))\n if True:\n # save it\n database.entries[index] = new_entry\n path = os.path.join(settings.DATABASE_PATH, 'kinetics', section, subsection + '.py' )\n database.save(path)\n commit_author = \"{0.first_name} {0.last_name} <{0.email}>\".format(request.user)\n commit_message = \"{1}:{2} {3}\\n\\nChange to kinetics/{0}/{1} entry {2} submitted through RMG website:\\n{3}\\n{4}\".format(section,subsection,index, form.cleaned_data['change'], commit_author)\n commit_result = subprocess.check_output(['git', 'commit',\n '-m', commit_message,\n '--author', commit_author,\n path\n ], cwd=settings.DATABASE_PATH, stderr=subprocess.STDOUT)\n \n \n #return HttpResponse(commit_result, mimetype=\"text/plain\")\n \n kwargs = { 'section': section,\n 'subsection': subsection,\n 'index': index,\n }\n forward_url = reverse(kineticsEntry, kwargs=kwargs)\n message = \"\"\"\n Changes saved succesfully:
    \n
    {0}

    \n See result at {1}.\n \"\"\".format(commit_result, forward_url)\n return render_to_response('simple.html', { \n 'title': 'Change saved successfully.',\n 'body': message,\n },\n context_instance=RequestContext(request))\n \n # redirect\n return HttpResponseRedirect(forward_url)\n \n else: # not POST\n # Get the entry as a entry_string\n entry_buffer = StringIO.StringIO(u'')\n rmgpy.data.kinetics.saveEntry(entry_buffer, entry)\n entry_string = entry_buffer.getvalue()\n entry_buffer.close()\n \n #entry_string = entry.item.reactants[0].toAdjacencyList()\n # remove leading 'entry('\n entry_string = re.sub('^entry\\(\\n','',entry_string)\n # remove the 'index = 23,' line\n entry_string = re.sub('\\s*index = \\d+,\\n','',entry_string)\n # remove the history and everything after it (including the final ')' )\n entry_string = re.sub('\\s+history = \\[.*','',entry_string, flags=re.DOTALL)\n \n form = KineticsEntryEditForm(initial={'entry':entry_string })\n \n return render_to_response('kineticsEntryEdit.html', {'section': section,\n 'subsection': subsection,\n 'databaseName': database.name,\n 'entry': entry,\n 'form': form,\n },\n context_instance=RequestContext(request))\n\ndef gitHistory(request,dbtype='',section='',subsection=''):\n \"\"\"\n A view for seeing the history of the given part of the database.\n dbtype = thermo / kinetics\n section = libraries / families\n subsection = 'Glarborg/C3', etc.\n \"\"\"\n \n path = os.path.join(settings.DATABASE_PATH, dbtype, section, subsection + '*' )\n history_result = subprocess.check_output(['git', 'log',\n '--', os.path.split(path)[0],\n ], cwd=settings.DATABASE_PATH, stderr=subprocess.STDOUT)\n\n history = []\n re_commit = re.compile('commit ([a-f0-9]{40})')\n re_author = re.compile('Author: (.*) \\<(\\w+\\@[^> ]+)\\>')\n re_date = re.compile('Date:\\s+(.*)')\n re_message = re.compile(' (.*)$')\n for line in history_result.split('\\n'):\n # print line\n m = re_commit.match(line)\n if m:\n commit = {}\n commit['hash'] = m.group(1)\n commit['message'] = ''\n history.append(commit)\n continue\n m = re_author.match(line)\n if m:\n commit['author_name'] = m.group(1)\n commit['author_email'] = m.group(2)\n commit['author_name_email'] = \"{0} <{1}>\".format(m.group(1),m.group(2))\n continue\n m = re_date.match(line)\n if m:\n commit['date'] = m.group(1)\n continue\n m = re_message.match(line)\n if m:\n commit['message'] += m.group(1) + '\\n'\n continue\n \n return render_to_response('history.html', { 'dbtype': dbtype,\n 'section': section,\n 'subsection': subsection,\n 'history': history,\n }, context_instance=RequestContext(request))\n\n\ndef kineticsEntry(request, section, subsection, index):\n \"\"\"\n A view for showing an entry in a kinetics database.\n \"\"\"\n\n # Load the kinetics database, if necessary\n loadDatabase('kinetics', section)\n\n # Determine the entry we wish to view\n try:\n database = getKineticsDatabase(section, subsection)\n except ValueError:\n raise Http404\n index = int(index)\n for entry in database.entries.values():\n if entry.index == index:\n break\n else:\n raise Http404\n \n reference = entry.reference\n referenceType = ''\n\n numReactants = 0; degeneracy = 1\n if isinstance(database, KineticsGroups):\n numReactants = database.numReactants\n else:\n numReactants = len(entry.item.reactants)\n degeneracy = entry.item.degeneracy\n \n if isinstance(database, KineticsGroups):\n structure = getStructureMarkup(entry.item)\n return render_to_response('kineticsEntry.html', {'section': section,\n 'subsection': subsection,\n 'databaseName': database.name,\n 'entry': entry,\n 'structure': structure,\n 'reference': reference,\n 'referenceType': referenceType,\n 'kinetics': entry.data,\n },\n context_instance=RequestContext(request))\n else:\n if 'rules' in subsection:\n reactants = ' + '.join([getStructureMarkup(reactant) for reactant in entry.item.reactants])\n products = ' + '.join([getStructureMarkup(reactant) for reactant in entry.item.products])\n arrow = '⇔' if entry.item.reversible else '→'\n else:\n reactants = ' + '.join([moleculeToInfo(reactant) for reactant in entry.item.reactants])\n products = ' + '.join([moleculeToInfo(reactant) for reactant in entry.item.products])\n arrow = '⇔' if entry.item.reversible else '→'\n\n # Searching for other instances of the reaction only valid for real reactions, not groups\n # If a Group or LogicNode shows up in the reaction, getReactionUrl will return ''\n reactionUrl = getReactionUrl(entry.item)\n\n \n return render_to_response('kineticsEntry.html', {'section': section,\n 'subsection': subsection,\n 'databaseName': database.name,\n 'entry': entry,\n 'reactants': reactants,\n 'arrow': arrow,\n 'products': products,\n 'reference': reference,\n 'referenceType': referenceType,\n 'kinetics': entry.data,\n 'reactionUrl': reactionUrl },\n context_instance=RequestContext(request))\n\n\ndef kineticsGroupEstimateEntry(request, family, reactant1, product1, reactant2='', reactant3='', product2='', product3=''):\n \"\"\"\n View a kinetics group estimate as an entry.\n \"\"\"\n # Load the kinetics database if necessary\n loadDatabase('kinetics','families')\n # Also load the thermo database so we can generate reverse kinetics if necessary\n loadDatabase('thermo')\n \n # we need 'database' to reference the top level object that we pass to generateReactions\n from tools import database\n \n # check the family exists\n try:\n getKineticsDatabase('families', family+'/groups')\n except ValueError:\n raise Http404\n\n reactantList = []\n reactantList.append(moleculeFromURL(reactant1))\n if reactant2 != '':\n reactantList.append(moleculeFromURL(reactant2))\n if reactant3 != '':\n reactantList.append(moleculeFromURL(reactant3))\n\n productList = []\n productList.append(moleculeFromURL(product1))\n if product2 != '':\n productList.append(moleculeFromURL(product2))\n if product3 != '':\n productList.append(moleculeFromURL(product3)) \n \n # Search for the corresponding reaction(s)\n reactionList, empty_list = generateReactions(database, reactantList, productList, only_families=[family])\n \n kineticsDataList = []\n \n # discard all the rates from depositories and rules\n reactionList = [reaction for reaction in reactionList if isinstance(reaction, TemplateReaction)]\n \n # if there are still two, only keep the forward direction\n if len(reactionList)==2:\n reactionList = [reaction for reaction in reactionList if reactionHasReactants(reaction, reactantList)]\n \n assert len(reactionList)==1, \"Was expecting one group estimate rate, not {0}\".format(len(reactionList))\n reaction = reactionList[0]\n \n # Generate the thermo data for the species involved\n for reactant in reaction.reactants:\n generateSpeciesThermo(reactant, database)\n for product in reaction.products:\n generateSpeciesThermo(product, database)\n \n # If the kinetics are ArrheniusEP, replace them with Arrhenius\n if isinstance(reaction.kinetics, ArrheniusEP):\n reaction.kinetics = reaction.kinetics.toArrhenius(reaction.getEnthalpyOfReaction(298))\n \n reactants = ' + '.join([moleculeToInfo(reactant) for reactant in reaction.reactants])\n arrow = '⇔' if reaction.reversible else '→'\n products = ' + '.join([moleculeToInfo(reactant) for reactant in reaction.products])\n assert isinstance(reaction, TemplateReaction), \"Expected group additive kinetics to be a TemplateReaction\"\n \n source = '%s (RMG-Py Group additivity)' % (reaction.family.name)\n entry = Entry(\n item=reaction,\n data=reaction.kinetics,\n longDesc=reaction.kinetics.comment,\n shortDesc=\"Estimated by RMG-Py Group Additivity\",\n )\n \n # Get the entry as a entry_string, to populate the New Entry form\n # first, replace the kinetics with a fitted arrhenius form with no comment\n entry.data = reaction.kinetics.toArrhenius()\n entry.data.comment = ''\n entry_buffer = StringIO.StringIO(u'')\n rmgpy.data.kinetics.saveEntry(entry_buffer, entry)\n entry_string = entry_buffer.getvalue()\n entry_buffer.close()\n # replace the kinetics with the original ones\n entry.data = reaction.kinetics\n entry_string = re.sub('^entry\\(\\n','',entry_string) # remove leading entry(\n entry_string = re.sub('\\s*index = -?\\d+,\\n','',entry_string) # remove the 'index = 23,' (or -1)line\n entry_string = re.sub('\\s+history = \\[.*','',entry_string, flags=re.DOTALL) # remove the history and everything after it (including the final ')' )\n new_entry_form = KineticsEntryEditForm(initial={'entry':entry_string })\n\n forwardKinetics = reaction.kinetics\n reverseKinetics = reaction.generateReverseRateCoefficient()\n \n forward = reactionHasReactants(reaction, reactantList) # boolean: true if template reaction in forward direction\n \n reactants = ' + '.join([moleculeToInfo(reactant) for reactant in reaction.reactants])\n products = ' + '.join([moleculeToInfo(reactant) for reactant in reaction.products])\n reference = rmgpy.data.reference.Reference(\n url=request.build_absolute_uri(reverse(kinetics,kwargs={'section':'families','subsection':family+'/groups'})),\n )\n referenceType = ''\n entry.index=-1\n\n reactionUrl = getReactionUrl(reaction)\n\n return render_to_response('kineticsEntry.html', {'section': 'families',\n 'subsection': family,\n 'databaseName': family,\n 'entry': entry,\n 'reactants': reactants,\n 'arrow': arrow,\n 'products': products,\n 'reference': reference,\n 'referenceType': referenceType,\n 'kinetics': reaction.kinetics,\n 'reactionUrl': reactionUrl,\n 'reaction': reaction,\n 'new_entry_form': new_entry_form},\n context_instance=RequestContext(request))\n \n\ndef kineticsJavaEntry(request, entry, reactants_fig, products_fig, kineticsParameters, kineticsModel):\n section = ''\n subsection = ''\n databaseName = 'RMG-Java Database'\n reference = ''\n referenceType = ''\n arrow = '⇔'\n return render_to_response('kineticsEntry.html', {'section': section, 'subsection': subsection, 'databaseName': databaseName, 'entry': entry, 'reactants': reactants_fig, 'arrow': arrow, 'products': products_fig, 'reference': reference, 'referenceType': referenceType, 'kinetics': entry.data}, context_instance=RequestContext(request))\n\ndef kineticsSearch(request):\n \"\"\"\n A view of a form for specifying a set of reactants to search the database\n for reactions. Redirects to kineticsResults to view the results of the search.\n \"\"\"\n\n # Load the kinetics database if necessary\n loadDatabase('kinetics')\n\n if request.method == 'POST':\n form = KineticsSearchForm(request.POST, error_class=DivErrorList)\n if form.is_valid():\n kwargs = {}\n\n reactant1 = form.cleaned_data['reactant1']\n kwargs['reactant1'] = re.sub('\\s+', '%20', reactant1.replace('\\n', ';'))\n\n reactant2 = form.cleaned_data['reactant2']\n if reactant2 != '':\n kwargs['reactant2'] = re.sub('\\s+', '%20', reactant2.replace('\\n', ';'))\n\n product1 = form.cleaned_data['product1']\n if product1 != '':\n kwargs['product1'] = re.sub('\\s+', '%20', product1.replace('\\n', ';'))\n\n product2 = form.cleaned_data['product2']\n if product2 != '':\n kwargs['product2'] = re.sub('\\s+', '%20', product2.replace('\\n', ';'))\n\n return HttpResponseRedirect(reverse(kineticsResults, kwargs=kwargs))\n else:\n form = KineticsSearchForm()\n\n return render_to_response('kineticsSearch.html', {'form': form}, context_instance=RequestContext(request))\n\ndef kineticsResults(request, reactant1, reactant2='', reactant3='', product1='', product2='', product3=''):\n \"\"\"\n A view used to present a list of unique reactions that result from a\n valid kinetics search.\n \"\"\"\n \n # Load the kinetics database if necessary\n loadDatabase('kinetics')\n from tools import database # the global one with both thermo and kinetics\n \n reactantList = []\n reactantList.append(moleculeFromURL(reactant1))\n if reactant2 != '':\n reactantList.append(moleculeFromURL(reactant2))\n if reactant3 != '':\n reactantList.append(moleculeFromURL(reactant3))\n\n if product1 != '' or product2 != '' or product3 != '':\n productList = []\n if product1 != '':\n productList.append(moleculeFromURL(product1))\n if product2 != '':\n productList.append(moleculeFromURL(product2))\n if product3 != '':\n productList.append(moleculeFromURL(product3))\n else:\n productList = None\n \n # Search for the corresponding reaction(s)\n reactionList, rmgJavaReactionList = generateReactions(database, reactantList, productList)\n reactionList.extend(rmgJavaReactionList)\n \n # Remove duplicates from the list and count the number of results\n uniqueReactionList = []\n uniqueReactionCount = []\n for reaction in reactionList:\n for i, rxn in enumerate(uniqueReactionList):\n if reaction.isIsomorphic(rxn):\n uniqueReactionCount[i] += 1\n break\n else:\n uniqueReactionList.append(reaction)\n uniqueReactionCount.append(1)\n \n reactionDataList = []\n for reaction, count in zip(uniqueReactionList, uniqueReactionCount):\n reactants = ' + '.join([moleculeToInfo(reactant) for reactant in reaction.reactants])\n arrow = '⇔' if reaction.reversible else '→'\n products = ' + '.join([moleculeToInfo(reactant) for reactant in reaction.products])\n reactionUrl = getReactionUrl(reaction)\n \n forward = reactionHasReactants(reaction, reactantList)\n if forward:\n reactionDataList.append([reactants, arrow, products, count, reactionUrl])\n else:\n reactionDataList.append([products, arrow, reactants, count, reactionUrl])\n \n return render_to_response('kineticsResults.html', {'reactionDataList': reactionDataList}, context_instance=RequestContext(request))\n\ndef kineticsData(request, reactant1, reactant2='', reactant3='', product1='', product2='', product3=''):\n \"\"\"\n A view used to present a list of reactions and the associated kinetics\n for each.\n \"\"\"\n \n # Load the kinetics database if necessary\n loadDatabase('kinetics')\n # Also load the thermo database so we can generate reverse kinetics if necessary\n loadDatabase('thermo')\n from tools import database # the global one with both thermo and kinetics\n\n reactantList = []\n reactantList.append(moleculeFromURL(reactant1))\n if reactant2 != '':\n reactantList.append(moleculeFromURL(reactant2))\n if reactant3 != '':\n reactantList.append(moleculeFromURL(reactant3))\n\n if product1 != '' or product2 != '' or product3 != '':\n productList = []\n if product1 != '':\n productList.append(moleculeFromURL(product1))\n if product2 != '':\n productList.append(moleculeFromURL(product2))\n if product3 != '':\n productList.append(moleculeFromURL(product3))\n \n reverseReaction = Reaction(reactants = productList, products = reactantList)\n reverseReactionURL = getReactionUrl(reverseReaction)\n else:\n productList = None\n\n # Search for the corresponding reaction(s)\n reactionList, rmgJavaReactionList = generateReactions(database, reactantList, productList)\n reactionList.extend(rmgJavaReactionList)\n \n kineticsDataList = []\n \n # Go through database and group additivity kinetics entries\n for reaction in reactionList:\n # Generate the thermo data for the species involved\n for reactant in reaction.reactants:\n generateSpeciesThermo(reactant, database)\n for product in reaction.products:\n generateSpeciesThermo(product, database)\n \n # If the kinetics are ArrheniusEP, replace them with Arrhenius\n if isinstance(reaction.kinetics, ArrheniusEP):\n reaction.kinetics = reaction.kinetics.toArrhenius(reaction.getEnthalpyOfReaction(298))\n\n #reactants = [getStructureMarkup(reactant) for reactant in reaction.reactants]\n reactants = ' + '.join([moleculeToInfo(reactant) for reactant in reaction.reactants])\n arrow = '⇔' if reaction.reversible else '→'\n products = ' + '.join([moleculeToInfo(reactant) for reactant in reaction.products])\n if isinstance(reaction, TemplateReaction):\n source = '%s (RMG-Py Group additivity)' % (reaction.family.name)\n href = getReactionUrl(reaction, family=reaction.family.name)\n entry = Entry(data=reaction.kinetics)\n elif reaction in rmgJavaReactionList:\n source = 'RMG-Java'\n href = ''\n entry = reaction.entry\n elif isinstance(reaction, DepositoryReaction):\n source = '%s' % (reaction.depository.name)\n href = reverse(kineticsEntry, kwargs={'section': 'families', 'subsection': reaction.depository.label, 'index': reaction.entry.index})\n entry = reaction.entry\n elif isinstance(reaction, LibraryReaction):\n source = reaction.library.name\n href = reverse(kineticsEntry, kwargs={'section': 'libraries', 'subsection': reaction.library.label, 'index': reaction.entry.index})\n entry = reaction.entry\n \n forwardKinetics = reaction.kinetics\n \n forward = reactionHasReactants(reaction, reactantList)\n if forward:\n kineticsDataList.append([reactants, arrow, products, entry, forwardKinetics, source, href, forward])\n else:\n reverseKinetics = reaction.generateReverseRateCoefficient()\n kineticsDataList.append([products, arrow, reactants, entry, reverseKinetics, source, href, forward])\n\n\n form = TemperatureForm()\n temperature = ''\n if request.method == 'POST':\n form = TemperatureForm(request.POST, error_class=DivErrorList)\n initial = request.POST.copy()\n if form.is_valid():\n temperature = form.cleaned_data['temperature']\n\n return render_to_response('kineticsData.html', {'kineticsDataList': kineticsDataList,\n 'plotWidth': 500,\n 'plotHeight': 400 + 15 * len(kineticsDataList),\n 'reactantList': reactantList,\n 'productList': productList,\n 'reverseReactionURL':reverseReactionURL,\n 'form':form,\n 'temperature':temperature,\n },\n context_instance=RequestContext(request))\n\ndef moleculeSearch(request):\n \"\"\"\n Creates webpage form to display molecule chemgraph upon entering adjacency list, smiles, or inchi, as well as searches for thermochemistry data.\n \"\"\"\n form = MoleculeSearchForm()\n structure_markup = ''\n molecule = Molecule()\n if request.method == 'POST':\n posted = MoleculeSearchForm(request.POST, error_class=DivErrorList)\n initial = request.POST.copy()\n\n if posted.is_valid():\n adjlist = posted.cleaned_data['species']\n if adjlist != '':\n molecule.fromAdjacencyList(adjlist)\n structure_markup = getStructureMarkup(molecule)\n \n form = MoleculeSearchForm(initial, error_class=DivErrorList)\n \n if 'thermo' in request.POST:\n return HttpResponseRedirect(reverse(thermoData, kwargs={'adjlist': adjlist}))\n \n if 'reset' in request.POST:\n form = MoleculeSearchForm()\n structure_markup = ''\n molecule = Molecule()\n \n return render_to_response('moleculeSearch.html', {'structure_markup':structure_markup,'molecule':molecule,'form': form}, context_instance=RequestContext(request))\n\ndef EniSearch(request):\n \"\"\"\n Creates webpage form to display detergent and deposit structures upon entering smiles as well as returns binding constants\n between the detergent and deposit\n \"\"\"\n from tools import getAbrahamAB\n if request.method == 'POST':\n form = EniSearchForm(request.POST, error_class=DivErrorList)\n if form.is_valid():\n detergent_adjlist = form.cleaned_data['detergent']\n deposit_adjlist = form.cleaned_data['deposit']\n\n detergent = Molecule()\n detergent.fromAdjacencyList(detergent_adjlist)\n detergent_smiles = detergent.toSMILES()\n detergent_structure = getStructureMarkup(detergent)\n\n deposit = Molecule()\n deposit.fromAdjacencyList(deposit_adjlist)\n deposit_smiles = deposit.toSMILES()\n deposit_structure = getStructureMarkup(deposit)\n \n detergentA, detergentB = getAbrahamAB(detergent_smiles)\n depositA, depositB = getAbrahamAB(deposit_smiles)\n \n # Estimating the binding strength assuming the the detergent to be the donor and dirt to be acceptor \n logK_AB = 7.354*detergentA*depositB\n # Estimating the binding strength assuming the the detergent to be the acceptor and dirt to be donor\n logK_BA = 7.354*detergentB*depositA\n \n else:\n detergentA = 0\n detergentB = 0\n depositA = 0\n depositB = 0\n logK_AB = 0\n logK_BA = 0 \n form = EniSearchForm() \n \n return render_to_response('EniSearch.html', {'detergentA': detergentA, 'detergentB': detergentB, 'depositA': depositA, 'depositB': depositB, 'logKAB': logK_AB, 'logKBA': logK_BA, 'form': form}, context_instance=RequestContext(request))\n\n\ndef moleculeEntry(request,adjlist):\n \"\"\"\n Returns an html page which includes the image of the molecule\n and its corresponding adjacency list/SMILES/InChI, as well\n as molecular weight info and a button to retrieve thermo data.\n\n Basically works as an equivalent of the molecule search function.\n \"\"\"\n\n adjlist = str(adjlist.replace(';', '\\n'))\n molecule = Molecule().fromAdjacencyList(adjlist)\n structure = getStructureMarkup(molecule)\n\n return render_to_response('moleculeEntry.html',{'structure':structure,'molecule':molecule}, context_instance=RequestContext(request))\n","sub_path":"rmgweb/database/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":50211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"80890559","text":"\"\"\"\nAuthor: Francesco Peri \n\ntrain performs traning on signal and backgrounds\n\"\"\"\n\n\nfrom __future__ import print_function\nimport numpy as np\n\n# Keras imports\nfrom keras.utils import np_utils\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Reshape\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras import backend as K\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.constraints import maxnorm\nfrom keras.callbacks import LearningRateScheduler\n#other\nimport matplotlib.pyplot as plt\nimport glob, os\nimport numpy as np\nfrom ROOT import *\nfrom ROOT import TChain,TH1F,TMVA,TLorentzVector,TCanvas\nimport random\n\n\n# Sklearn imports\nfrom sklearn import preprocessing\nfrom sklearn.metrics import roc_curve,roc_auc_score\nfrom sklearn.externals import joblib\n\nfrom generator import Generator\nfrom pgenerator import Generator as tGen\nfrom model import make_models\nfrom gsize import getsize\nfrom scaler import Scaler\n\ndef training_odd(mass,region,folder1,folder2,batch_size):\n\n f1size=int(getsize(mass,region,folder1)/float(batch_size))\n f2size=int(getsize(mass,region,folder2)/float(batch_size))\n print(f1size)\n print(f2size)\n\n scal = joblib.load(\"../model_\"+mass+\"/\"+region+\"/scaler.pkl\")\n\n model=make_models()\n\n g1=tGen(mass,region,folder1,folder2,0,1000)\n\n gen=next(g1)\n dset2 = np.asarray(gen).reshape(int(len(gen)/37), 37)\n X = dset2[:,:35]\n Y = dset2[:,35]\n W = dset2[:,36]\n newX = scal.transform(X)\n encoder = preprocessing.LabelEncoder()\n encoder.fit(Y)\n newY = encoder.transform(Y)\n X_test0=newX\n Y_test0=newY\n W_test0=W\n tup=dset2[:,:37]\n tup[:,:35]=X_test0\n\n for j in range(1):\n for i in range(1):\n g=Generator(mass,region,folder1,folder2,1,scal,batch_size)\n model.fit_generator(g,validation_data=(X_test0,Y_test0,W_test0),samples_per_epoch=min(f1size,f2size)*int(batch_size), nb_epoch = max(6,f1size/f2size+1,f2size/f1size+1),verbose=0)\n #del g1\n del g\n\n\n # serialize model to JSON\n model_json = model.to_json()\n with open(\"../model_\"+mass+\"/\"+region+\"/model\"+folder2+\"_odd.json\", \"w\") as json_file:\n \tjson_file.write(model_json)\n\n # serialize weights to HDF5\n model.save_weights(\"../model_\"+mass+\"/\"+region+\"/model\"+folder2+\"_odd.h5\")\n print(\"Saved model to disk\")\n\ndef training(mass,region,folder1,folder2,batch_size):\n\n f1size=int(getsize(mass,region,folder1)/float(batch_size))\n f2size=int(getsize(mass,region,folder2)/float(batch_size))\n print(f1size)\n print(f2size)\n\n g1=tGen(mass,region,folder1,folder2,1,1000)\n \n model=make_models()\n\n scal = joblib.load(\"../model_\"+mass+\"/\"+region+\"/scaler.pkl\")\n\n gen=next(g1)\n dset2 = np.asarray(gen).reshape(int(len(gen)/37), 37)\n X = dset2[:,:35]\n Y = dset2[:,35]\n W = dset2[:,36]\n newX = scal.transform(X)\n encoder = preprocessing.LabelEncoder()\n encoder.fit(Y)\n newY = encoder.transform(Y)\n X_test0=newX\n Y_test0=newY\n W_test0=W\n tup=dset2[:,:37]\n tup[:,:35]=X_test0\n\n for j in range(1):\n for i in range(1):\n g=Generator(mass,region,folder1,folder2,0,scal,batch_size)\n model.fit_generator(g,validation_data=(X_test0,Y_test0,W_test0),samples_per_epoch=min(f1size,f2size)*int(batch_size), nb_epoch = max(6,f1size/f2size+1,f2size/f1size+1),verbose=1)\n #del g1\n del g\n\n\n # serialize model to JSON\n model_json = model.to_json()\n with open(\"../model_\"+mass+\"/\"+region+\"/model\"+folder2+\".json\", \"w\") as json_file:\n \tjson_file.write(model_json)\n\n # serialize weights to HDF5\n model.save_weights(\"../model_\"+mass+\"/\"+region+\"/model\"+folder2+\".h5\")\n print(\"Saved model to disk\")\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"246691732","text":"from tkinter import *\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom metodos import *\n\nclass MyApp(Frame,Metodos):\n def __init__(self, master=None):\n Metodos.__init__(self)\n Frame.__init__(self, master)\n\n #CONTAINER TITULO\n self.primeiroContainer = Frame(master)\n self.primeiroContainer[\"padx\"] = 20\n self.primeiroContainer[\"pady\"] = 80\n self.primeiroContainer.pack()\n self.titulo = Label(self.primeiroContainer, text=\"Acesso do Mesário\")\n self.titulo[\"font\"] = (\"Times New Roman Baltic\", \"26\", \"bold\")\n self.titulo.pack()\n self.fontePadrao = (\"Times New Roman\", \"15\")\n\n #CONTAINER PRA COLOCAR O LOGIN\n self.segundoContainer = Frame(master)\n self.segundoContainer[\"padx\"] = 50\n self.segundoContainer[\"pady\"] = 10\n self.segundoContainer.pack()\n self.nomeLabel = Label(self.segundoContainer,\n text=\"Login\", font=self.fontePadrao)\n self.nomeLabel[\"padx\"]=30\n self.nomeLabel.pack(side=LEFT)\n self.nome = Entry(self.segundoContainer)\n self.nome[\"width\"] = 30\n self.nome[\"font\"] = self.fontePadrao\n self.nome.pack(side=LEFT)\n\n #CONTAINER PRA COLOCAR SENHA\n self.terceiroContainer = Frame(master)\n self.terceiroContainer[\"padx\"] = 20\n self.terceiroContainer[\"pady\"] = 10\n self.terceiroContainer.pack()\n self.senhaLabel = Label(self.terceiroContainer,\n text=\"Senha\", font=self.fontePadrao)\n self.senhaLabel[\"padx\"]=30\n self.senhaLabel.pack(side=LEFT)\n self.senha = Entry(self.terceiroContainer)\n self.senha[\"width\"] = 30\n self.senha[\"font\"] = self.fontePadrao\n self.senha[\"show\"] = \"*\"\n self.senha.pack(side=LEFT)\n\n #CONTAINER BOTÃO DE ENTRAR\n self.quartoContainer = Frame(master)\n self.quartoContainer[\"padx\"] = 80\n self.quartoContainer[\"pady\"] = 60\n self.quartoContainer.pack()\n self.autenticar = Button(self.quartoContainer)\n self.autenticar[\"text\"] = \"Entrar\"\n self.autenticar[\"font\"] = (\"Verdana\", \"13\")\n self.autenticar[\"width\"] = 12\n self.autenticar[\"command\"] = self.verifica_senha\n self.autenticar.pack(side=LEFT)\n\n \n def janelaProsseguir(self):\n self.prosseguir = Toplevel()\n self.prosseguir.geometry(\"%dx%d+0+0\" % (w-16, h))\n self.prosseguir.title('Prosseguir')\n self.prosseguir.focus_force()#Quando abrir foco nela\n self.prosseguir.resizable(width=False, height=False)\n\n \n\n #CONTAINER COM A PERGUNTA\n self.primeiroContainer = Frame(self.prosseguir)\n self.primeiroContainer[\"padx\"] = 20\n self.primeiroContainer[\"pady\"] = 80\n self.primeiroContainer.pack()\n self.titulo = Label(self.primeiroContainer, text=\"O que deseja fazer?\")\n self.titulo[\"font\"] = (\"Times New Roman Baltic\", \"26\", \"bold\")\n self.titulo.pack()\n\n #CONTAINER COM DOIS BOTOES\n self.segundoContainer = Frame(self.prosseguir)\n self.segundoContainer.pack()\n self.bt = Button(self.segundoContainer)\n self.bt[\"text\"] = \"Votar\"\n self.bt[\"font\"] = (\"Verdana\", \"13\")\n self.bt[\"width\"] = 20\n self.bt[\"command\"] = self.dadosJanela\n self.bt.pack(side=LEFT)\n self.bt2 = Button(self.segundoContainer)\n self.bt2[\"text\"] = \"Encerrar Eleição\"\n self.bt2[\"font\"] = (\"Verdana\", \"13\")\n self.bt2[\"width\"] = 20\n self.bt2[\"command\"] = self.encerrar\n self.bt2.pack()\n self.prosseguir.deiconify()\n\n self.terceiroContainer = Frame(self.prosseguir)\n self.terceiroContainer[\"padx\"] = 20\n self.terceiroContainer[\"pady\"] = 50\n self.terceiroContainer.pack()\n self.bt = Button(self.terceiroContainer)\n self.bt[\"text\"] = \"Sair\"\n self.bt[\"font\"] = (\"Verdana\", \"13\")\n self.bt[\"width\"] = 20\n self.bt[\"command\"] = self.sair\n self.bt.pack()\n \n\n def dadosJanela(self):\n self.prosseguir.withdraw()\n self.janelaDados= Toplevel() \n\n self.janelaDados.update()\n self.janelaDados.geometry(\"%dx%d+0+0\" % (w-16, h))\n self.janelaDados.title('Confirmação de Dados')\n self.janelaDados.resizable(width=False, height=False)\n self.janelaDados.focus_force()\n\n self.primeiroContainer = Frame(self.janelaDados)\n self.primeiroContainer[\"padx\"] = 20\n self.primeiroContainer[\"pady\"] = 80\n self.primeiroContainer.pack()\n self.nomeLabel = Label(self.primeiroContainer,\n text=\"Confirmação\", font=(\"Times New Roman Baltic\", \"27\", \"bold\"))\n self.nomeLabel[\"padx\"]=30\n self.nomeLabel.pack(side=LEFT)\n\n self.segundoContainer = Frame(self.janelaDados)\n self.segundoContainer[\"padx\"] = 60\n self.segundoContainer[\"pady\"] = 60\n self.segundoContainer.pack()\n self.cpfLabel = Label(self.segundoContainer,\n text=\"CPF: \", font=self.fontePadrao)\n self.cpfLabel[\"padx\"]=30\n self.cpfLabel.pack(side=LEFT)\n self.cpf = Entry(self.segundoContainer)\n self.cpf[\"width\"] = 30\n self.cpf[\"font\"] = (\"Arial\", \"13\")\n self.cpf.focus()\n self.cpf.pack(side=LEFT)\n\n self.terceiroContainer = Frame(self.janelaDados)\n self.terceiroContainer[\"padx\"] = 20\n self.terceiroContainer[\"pady\"] = 20\n self.terceiroContainer.pack()\n self.bt = Button(self.terceiroContainer)\n self.bt[\"text\"] = \"Validar\"\n self.bt[\"font\"] = (\"Verdana\", \"13\")\n self.bt[\"width\"] = 20\n self.bt[\"command\"] = self.validar\n self.bt.pack()\n\n self.quartoContainer = Frame(self.janelaDados)\n self.quartoContainer[\"padx\"] = 20\n self.quartoContainer[\"pady\"] = 0\n self.quartoContainer.pack()\n self.bt3 = Button(self.quartoContainer)\n self.bt3[\"text\"] = \"Voltar\"\n self.bt3[\"font\"] = (\"Verdana\", \"13\")\n self.bt3[\"width\"] = 20\n self.bt3[\"command\"] = self.voltar\n self.bt3.pack()\n\n def votoJanela(self):\n global w,h, caminho\n self.janela_voto = Toplevel()\n #self.janela_voto.geometry(\"600x500+1500+50\")#########\n self.janela_voto.geometry(\"1275x985+%d+0\" % (w))\n #self.janela_voto.geometry(\"%dx%d+%d+0\" % (w, h, w))\n mixer.init()\n self.janela_voto.title(\"Voto\")\n self.janela_voto.grab_set()\n self.janela_voto.transient()\n #self.janela_voto.attributes('-fullscreen',True)\n self.janela_voto.resizable(width=False, height=False)\n\n var = tk.StringVar()\n max_len = 2\n\n vcmd = (self.master.register(self.validate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')\n\n self.janela_voto.bind(\"\", self.key1)\n self.janela_voto.bind(\"<,>\", self.key2)\n #self.janela_voto.bind(\"<*>\", self.key3)\n\n Numero = tk.StringVar()\n Nome = tk.StringVar()\n Partido = tk.StringVar()\n caminho = \"padrao.png\"\n Numero.set(\"?\")\n Nome.set(\"?\")\n Partido.set(\"?\")\n\n self.imagem = PhotoImage(file = caminho)\n \n #CONTAINER FOTO DO CANDIDATO\n self.container1 = Frame(self.janela_voto)\n self.container1[\"width\"] = 200\n self.container1.pack()\n self.foto = Label(self.container1, image=self.imagem)\n self.foto.imagem = self.imagem\n self.foto.imagem[\"width\"] = 200\n self.foto.imagem[\"height\"] = 200\n self.foto.pack()\n\n\n \n \n #CONTAINER INFORMAÇÃO DO CANDIDATO\n self.container2 = Frame(self.janela_voto)\n self.container2[\"pady\"] = 20\n self.container2.pack()\n self.lb1 = Label(self.container2)\n self.lb1[\"text\"] = \"SEU VOTO PARA GOVERNADOR\"\n self.lb1[\"font\"] = (\"Verdana\", \"30\")\n self.lb1.pack()\n\n self.container3 = Frame(self.janela_voto)\n self.container3[\"pady\"] = 15\n self.container3.pack()\n self.lb2 = Label(self.container3)\n self.lb2[\"text\"] = \"Número:\"\n self.lb2[\"font\"] = (\"Verdana\", \"20\")\n self.lb2.pack(side=LEFT)\n self.lb3 = Label(self.container3, textvariable = Numero)\n self.lb3[\"font\"] = (\"Verdana\", \"20\")\n self.lb3.pack(side=BOTTOM)\n\n self.container4 = Frame(self.janela_voto)\n self.container4[\"pady\"] = 15\n self.container4.pack()\n self.lb4 = Label(self.container4)\n self.lb4[\"text\"] = \"Nome:\"\n self.lb4[\"font\"] = (\"Verdana\", \"20\")\n self.lb4.pack(side=LEFT)\n self.lb5 = Label(self.container4, textvariable = Nome)\n self.lb5[\"font\"] = (\"Verdana\", \"20\")\n self.lb5.pack(side = BOTTOM)\n\n self.container5 = Frame(self.janela_voto)\n self.container5[\"pady\"] = 15\n self.container5.pack()\n self.lb6 = Label(self.container5)\n self.lb6[\"text\"] = \"Partido:\"\n self.lb6[\"font\"] = (\"Verdana\", \"20\")\n self.lb6.pack(side=LEFT)\n self.lb7 = Label(self.container5, textvariable = Partido)\n self.lb7[\"font\"] = (\"Verdana\", \"20\")\n self.lb7.pack(side = BOTTOM)\n\n #CONTAINER ENTRY DO NUMERO DE VOTO\n self.container6 = Frame(self.janela_voto)\n self.container6[\"pady\"] = 25\n self.container6.pack()\n self.et1 = Entry(self.container6, validate = 'key', validatecommand = vcmd, textvariable = var)\n self.et1[\"width\"] = 5\n self.et1[\"font\"] = (\"Verdana\", \"28\")\n self.et1[\"justify\"] = \"center\"\n self.et1.focus()\n self.et1.pack()\n\n #CONTAINER CONFIRMA E BRANCO\n self.container4 = Frame(self.janela_voto)\n self.container4[\"width\"] = 25\n self.container4.pack()\n self.lb8 = Label(self.container4)\n self.lb8[\"text\"] = \"Aperte Enter duas vezes para votar\"\n self.lb8[\"font\"] = (\"Verdana\", \"11\")\n self.lb8.pack()\n \n \n \n def on_write(self, *args):\n global cont\n global cont1\n s = var.get()\n cont1 = 0\n if len(s) > max_len:\n var.set(s[:max_len])\n \n elif len(s) == 0 or len(s) > 0:\n global cont\n global cpfRelativo\n global caminho\n global app\n num = s\n \n if s == '':\n Numero.set(\"?\")\n Nome.set(\"?\")\n Partido.set(\"?\")\n app.imagem[\"file\"]=\"padrao.png\"\n cont=num\n\n elif len(s)==1:\n Numero.set(\"?\")\n Nome.set(\"?\")\n Partido.set(\"?\")\n app.imagem[\"file\"]=\"padrao.png\"\n cont=num\n\n elif s == '00':\n Numero.set(\"Branco\")\n Nome.set(\"Branco\")\n Partido.set(\"Branco\")\n caminho=\"candidatos/\" + num + \"/\" + num + \".png\" \n cont = num\n \n \n elif len(s)==2:\n arq = \"candidatos/\" + num + \"/info.txt\"\n try:\n abre = open(arq, \"r\")\n linhas = abre.readlines()\n except IOError:\n Numero.set(\"Nulo\")\n Nome.set(\"Nulo\")\n Partido.set(\"Nulo\")\n app.imagem[\"file\"]=\"padrao.png\"\n cont=num\n \n\n except Exception as erro:\n\n messagebox.showerror(\"Erro Inesperado\", erro)\n\n else:\n Numero.set(linhas[0].strip(\"\\n\"))\n Nome.set(linhas[1].strip(\"\\n\"))\n Partido.set(linhas[2].strip(\"\\n\"))\n caminho=\"candidatos/\" + num + \"/\" + num + \".png\"\n app.imagem[\"file\"]=\"candidatos/\" + num + \"/\" + num + \".png\"\n #self.imagem = self.imagem.zoom(20)\n #self.imagem = self.imagem.subsample(50)\n abre.close()\n cont = s\n \n \n \n \n\n var.trace_variable(\"w\",on_write)\n\n def telafim(self):\n self.fim = Toplevel()\n self.fim.geometry(\"1275x985+%d+0\" % (w))\n self.fim.title(\"Fim\")\n self.fim.grab_set()\n self.fim.transient()\n self.fim.resizable(width=False, height=False)\n\n self.container1 = Frame(self.fim)\n self.container1[\"pady\"] = 300\n self.container1.pack()\n self.lb1 = Label(self.container1)\n self.lb1[\"text\"] = \"FIM!\"\n self.lb1[\"font\"] = (\"Verdana\", \"80\")\n self.lb1.pack()\n\n self.lb2 = Label(self.container1)\n self.lb2[\"text\"] = \"\\n\\n\\n\\n\\n\\n\\n\\nDesenvolvido por:\\nAderson Januario\\nPedro Vicente\\nAlessandra Medeiros\"\n self.lb2[\"font\"] = (\"Verdana\", \"12\")\n self.lb2.pack()\n\n \n\n \n \n\n \n\napp = MyApp()\napp.master.title(\"Tela de Login do Mesário\")\nw, h = app.master.winfo_screenwidth(), app.master.winfo_screenheight()\napp.master.geometry(\"%dx%d+0+0\" % (w-16, h))\nmainloop()\n\n\n#self.jan.transient(root)#Sempre aberta\n#self.jan.focus_force()#Quando abrir foco nela\n#self.jan.grab_set()#Não usar botoes da outra\n#messagebox.showinfo(\"Informação\", \"Dados do \"+ Clube +\":\" +\"\\n\\nNome do clube: \"+ Lista[0]+\"\\nAno de fundação: \"+Lista[1]+\"\\nSérie Atual: Série \"+Lista[2]+\"\\nQuantidade de títulos: \"+Lista[3])\n#messagebox.showerror(\"Erro\", \"Um erro foi encontrado!\\nO clube \"+Clube+\" não foi encontrado!\")\n\n","sub_path":"mesario_tela.py","file_name":"mesario_tela.py","file_ext":"py","file_size_in_byte":13832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"433592443","text":"\nimport numpy as np\nfrom scipy.misc import imread,imresize\n\n#import matplotlib\n#matplotlib.use('QT4Agg')\n#import matplotlib.pyplot as plt\n\nimport tensorflow as tf\n\nfrom inception import inception_model as inception\n\nimport glob\n\nimage_size = 299\nnum_class = 1001\n\ndef main() :\n jpg_files = glob.glob('./images/*.jpg')\n images = None\n file_names = []\n for file_index,file_name in enumerate(jpg_files) :\n img_src = imread(file_name)\n img = imresize(img_src,(image_size,image_size))\n resized_image = tf.cast(tf.constant(img,shape = [image_size,image_size,3]),tf.float32)\n image = tf.ones([1,image_size,image_size,3]) * tf.image.per_image_whitening(resized_image)\n #image = tf.ones([1,image_size,image_size,3]) * tf.image.per_image_standardization(resized_image)\n if images is None :\n images = image\n else :\n images = tf.concat(0,[images,image])\n file_names.append(file_name)\n\n logits = inception.inference(images,num_class)[0]\n labels = tf.nn.top_k(logits,k = 5)\n\n variable_averages = tf.train.ExponentialMovingAverage(\n inception.MOVING_AVERAGE_DECAY)\n variables_to_restore = variable_averages.variables_to_restore()\n saver = tf.train.Saver(variables_to_restore)\n\n init = tf.initialize_all_variables()\n #init = tf.global_variables_initializer()\n predict_tag = None\n with tf.Session() as session :\n session.run(init)\n\n ckpt = tf.train.get_checkpoint_state('/opt/workspace/imagenet/inception/train_train_700000/')\n if ckpt and ckpt.model_checkpoint_path :\n saver.restore(session,ckpt.model_checkpoint_path)\n else :\n print('No checkpoint file found')\n return\n raw = session.run(labels)\n for i in range(0,len(file_names)) :\n print('%s ---- %s ---- %s' % (file_names[i],raw[0][i],raw[1][i]))\n\n #coord.request_stop()\n #coord.join(threads)\n\n #plt.imshow(img_src)\n #plt.title('it\\'s a %s' % predict_tag)\n #plt.show()\n\nif __name__ == '__main__' :\n main()\n\n","sub_path":"python/00..deep_learning/tensorflow_demos/inception_validation_test.py","file_name":"inception_validation_test.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"315526953","text":"import theano\nimport theano.tensor as T\nfrom theano.tensor.fourier import fft, Fourier\nfrom theano import Apply, tensor\n\n\nclass FFTAbs(Fourier):\n def make_node(self, frames, n, axis):\n ret = super(FFTAbs, self).make_node(frames, n, axis)\n return Apply(self, ret.inputs,\n [tensor.TensorType(dtype='float64',\n broadcastable=ret.outputs[0].broadcastable)()])\n\n def perform(self, node, inp, out):\n super(FFTAbs, self).perform(node, inp, out[0])\n out[0] = numpy.abs(out[0])\n\n def grad(self, inp, out):\n assert type(self) == FFTAbs\n abs_gz = out[0]\n abs_x = fft(*inp)\n fft_gz = abs_gz * abs_x / abs(abs_x)\n import pdb;pdb.set_trace()\n ret = super(FFTAbs, self).grad(inp, [fft_gz])\n return ret\n\n\nx = T.vector('x')\ny = FFTAbs()(x, 10, 0)[1].mean()\ntheano.printing.debugprint(y, print_type=True)\ngy = T.grad(y, x)\n#fun = theano.function([x], [gy])\n","sub_path":"experiments/convae/ver/fftabs.py","file_name":"fftabs.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"85333375","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\ndef extract_news(soup):\n \"\"\" Extract news from a given web page \"\"\"\n\n news_list = []\n try:\n table = soup.table.findAll('table')[1]\n except AttributeError:\n return\n\n for i in range(0, 89, 3):\n try:\n tr0 = table.findAll('tr')[i]\n tr1 = table.findAll('tr')[i + 1]\n\n td_for0 = tr0.findAll('td')[2]\n url = td_for0.a['href']\n # print(url)\n title = td_for0.a.text\n # print(title)\n\n td_for1 = tr1.findAll('td')[1]\n points = td_for1.find('span', {\"class\": \"score\"}).text\n if points:\n points = points.rsplit(' ', 1)[0]\n else:\n points = 0\n # print(points)\n\n author_ = td_for1.find('a', {\"class\": \"hnuser\"}).text\n if author_:\n author = author_\n else:\n author = None\n # print(author)\n\n comments = \"0\"\n comment = td_for1.findAll('a')[-1].text\n if 'discuss' == comment:\n comments = 'discuss'\n else:\n comments = comment\n\n # print(comments)\n\n news = {'author': author,\n 'title': title,\n 'comments': comments,\n 'points': points,\n 'url': url}\n news_list.append(news)\n except AttributeError:\n\n pass\n # print(news_list)\n return news_list\n\n\ndef extract_next_page(soup):\n \"\"\" Extract next page URL \"\"\"\n next = soup.find('a', {\"class\": \"morelink\"})\n return next['href']\n\n\ndef get_news(url, n_pages=1):\n \"\"\" Collect news from a given web page \"\"\"\n news = []\n while n_pages:\n print(\"Collecting data from page: {}\".format(url))\n response = requests.get(url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n news_list = extract_news(soup)\n next_page = extract_next_page(soup)\n url = \"https://news.ycombinator.com/\" + next_page\n news.extend(news_list)\n n_pages -= 1\n return news\n","sub_path":"homework06/scraputils.py","file_name":"scraputils.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"370213932","text":"#!/usr/bin/env python3\n\n# Copyright 2018 IBM Corp. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Unit tests for the zhmc_prometheus_exporter\"\"\"\n\nimport time\nimport datetime\nimport hashlib\nimport os\nimport stat\n\nfrom io import StringIO\nimport unittest\nfrom unittest.mock import patch\n\nimport zhmcclient\nimport zhmcclient_mock\n\nimport prometheus_client\n\nimport zhmc_prometheus_exporter\n\n\nclass TestParseArgs(unittest.TestCase):\n \"\"\"Tests parse_args.\"\"\"\n\n def test_args_store(self):\n \"\"\"Tests generic input.\"\"\"\n args = (zhmc_prometheus_exporter.\n parse_args([\"-p\", \"1\", \"-c\", \"2\", \"-m\", \"3\"]))\n self.assertEqual(args.p, \"1\")\n self.assertEqual(args.c, \"2\")\n self.assertEqual(args.m, \"3\")\n\n def test_default_args(self):\n \"\"\"Tests for all defaults.\"\"\"\n args = zhmc_prometheus_exporter.zhmc_prometheus_exporter.parse_args([])\n self.assertEqual(args.p, \"9291\")\n self.assertEqual(args.c, \"/etc/zhmc-prometheus-exporter/hmccreds.yaml\")\n self.assertEqual(args.m, \"/etc/zhmc-prometheus-exporter/metrics.yaml\")\n\n\nclass TestParseYaml(unittest.TestCase):\n \"\"\"Tests parse_yaml_file.\"\"\"\n\n def test_normal_input(self):\n \"\"\"Tests if some generic file is correctly parsed.\"\"\"\n # Get a SHA256 of Unixtime to create a filename that does not exist\n filename = str(hashlib.sha256(str(time.time()).encode(\"utf-8\")).\n hexdigest())\n with open(filename, \"w+\") as testfile:\n testfile.write(\"\"\"metrics:\n hmc: 127.0.0.1\n userid: user\n password: pwd\n\"\"\")\n expected_dict = {\"metrics\": {\"hmc\": \"127.0.0.1\",\n \"userid\": \"user\",\n \"password\": \"pwd\"}}\n self.assertEqual(zhmc_prometheus_exporter.parse_yaml_file(filename),\n expected_dict)\n os.remove(filename)\n\n def test_permission_error(self):\n \"\"\"Tests if permission denied is correctly handled.\"\"\"\n filename = str(hashlib.sha256(str(time.time()).encode(\"utf-8\")).\n hexdigest())\n with open(filename, \"w+\"):\n pass\n # Make it unreadable (mode 000)\n os.chmod(filename, not stat.S_IRWXU)\n with self.assertRaises(PermissionError):\n (zhmc_prometheus_exporter.\n parse_yaml_file(filename))\n os.remove(filename)\n\n def test_not_found_error(self):\n \"\"\"Tests if file not found is correctly handled.\"\"\"\n filename = str(hashlib.sha256(str(time.time()).encode(\"utf-8\")).\n hexdigest())\n with self.assertRaises(FileNotFoundError):\n zhmc_prometheus_exporter.parse_yaml_file(filename)\n\n\nclass TestParseSections(unittest.TestCase):\n \"\"\"Tests parse_yaml_sections.\"\"\"\n\n def test_normal_input(self):\n \"\"\"Tests with some generic input.\"\"\"\n sample_dict = {\"hmc\": \"127.0.0.1\", \"userid\": \"user\", \"password\": \"pwd\"}\n sample_dict_wrap = {\"metrics\": sample_dict}\n cred_dict = (zhmc_prometheus_exporter.\n parse_yaml_sections(sample_dict_wrap,\n (\"metrics\",),\n \"filename\")[0])\n self.assertEqual(cred_dict, sample_dict)\n\n def test_section_error(self):\n \"\"\"Tests for a missing section.\"\"\"\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n (zhmc_prometheus_exporter.\n parse_yaml_sections({}, (\"metrics\",), \"filename\"))\n\n def test_attribute_error(self):\n \"\"\"Tests for something that is not YAML.\"\"\"\n with self.assertRaises(AttributeError):\n (zhmc_prometheus_exporter.\n parse_yaml_sections(\"notyaml\", (\"metrics\",), \"filename\"))\n\n\nclass TestCheckCreds(unittest.TestCase):\n \"\"\"Tests check_creds_yaml.\"\"\"\n\n def test_check_creds_yaml(self):\n \"\"\"Tests all sorts of missing, incorrect, and correct information.\"\"\"\n missing_hmc = {\"userid\": \"user\", \"password\": \"pwd\"}\n incorrect_ip = {\"hmc\": \"256.0.0.1\",\n \"userid\": \"user\",\n \"password\": \"pwd\"}\n missing_user = {\"hmc\": \"127.0.0.1\", \"password\": \"pwd\"}\n missing_pwd = {\"hmc\": \"127.0.0.1\", \"userid\": \"user\"}\n correct = {\"hmc\": \"127.0.0.1\", \"userid\": \"user\", \"password\": \"pwd\"}\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n zhmc_prometheus_exporter.check_creds_yaml(missing_hmc, \"filename\")\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n zhmc_prometheus_exporter.check_creds_yaml(incorrect_ip, \"filename\")\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n zhmc_prometheus_exporter.check_creds_yaml(missing_user, \"filename\")\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n zhmc_prometheus_exporter.check_creds_yaml(missing_pwd, \"filename\")\n zhmc_prometheus_exporter.check_creds_yaml(correct, \"filename\")\n\n\nclass TestCheckMetrics(unittest.TestCase):\n \"\"\"Tests check_metrics_yaml.\"\"\"\n\n def test_check_metrics_yaml(self):\n \"\"\"Tests all sorts of missing, incorrect, and correct information.\"\"\"\n bad_prefix = {\"metric_group\": {\"fetch\": True}}\n bad_fetch = {\"metric_group\": {\"prefix\": \"pre\"}}\n bad_fetch_format = {\"metric_group\": {\"prefix\": \"pre\",\n \"fetch\": \"none\"}}\n correct_groups = {\"metric_group\": {\"prefix\": \"pre\", \"fetch\": True}}\n bad_percent = {\"metric_group\": {\"metric\": {\"exporter_name\": \"name\",\n \"exporter_desc\": \"desc\"}}}\n bad_percent_format = {\"metric_group\": {\"metric\": {\n \"percent\": \"none\",\n \"exporter_name\": \"name\",\n \"exporter_desc\": \"desc\"}}}\n bad_name = {\"metric_group\": {\"metric\": {\"percent\": True,\n \"exporter_desc\": \"desc\"}}}\n bad_desc = {\"metric_group\": {\"metric\": {\"percent\": True,\n \"exporter_name\": \"name\"}}}\n correct_metric = {\"metric_group\": {\"metric\": {\n \"percent\": True,\n \"exporter_name\": \"name\",\n \"exporter_desc\": \"desc\"}}}\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n (zhmc_prometheus_exporter.\n check_metrics_yaml(bad_prefix, correct_metric, \"filename\"))\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n (zhmc_prometheus_exporter.\n check_metrics_yaml(bad_fetch, correct_metric, \"filename\"))\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n (zhmc_prometheus_exporter.\n check_metrics_yaml(bad_fetch_format, correct_metric, \"filename\"))\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n (zhmc_prometheus_exporter.\n check_metrics_yaml({}, correct_metric, \"filename\"))\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n (zhmc_prometheus_exporter.\n check_metrics_yaml(correct_groups, bad_percent, \"filename\"))\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n zhmc_prometheus_exporter.check_metrics_yaml(correct_groups,\n bad_percent_format,\n \"filename\")\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n (zhmc_prometheus_exporter.\n check_metrics_yaml(correct_groups, bad_name, \"filename\"))\n with self.assertRaises(zhmc_prometheus_exporter.YAMLInfoNotFoundError):\n (zhmc_prometheus_exporter.\n check_metrics_yaml(correct_groups, bad_desc, \"filename\"))\n (zhmc_prometheus_exporter.\n check_metrics_yaml(correct_groups, correct_metric, \"filename\"))\n\n\n# Fake HMC derived from\n# github.com/zhmcclient/python-zhmcclient/zhmcclient_mock/_hmc.py\nclass TestCreateContext(unittest.TestCase):\n \"\"\"Tests create_metrics_context with a fake HMC.\"\"\"\n\n def test_normal_input(self):\n \"\"\"Tests normal input with a generic metric group.\"\"\"\n session = zhmcclient_mock.FakedSession(\"fake-host\", \"fake-hmc\",\n \"2.13.1\", \"1.8\")\n context = (zhmc_prometheus_exporter.\n create_metrics_context(session,\n {\"metric-group\": {\"prefix\": \"pre\",\n \"fetch\": True}},\n \"filename\"))\n self.assertEqual(type(context), zhmcclient._metrics.MetricsContext)\n context.delete()\n session.logoff()\n\n def test_timeout(self):\n \"\"\"Tests a timeout with an IP where no HMC is sitting.\n Omitting this test improves test time by three orders of magnitude.\n \"\"\"\n cred_dict = {\"hmc\": \"192.168.0.0\", \"userid\": \"user\", \"password\": \"pwd\"}\n session = zhmc_prometheus_exporter.create_session(cred_dict)\n with self.assertRaises(zhmc_prometheus_exporter.ConnectTimeout):\n (zhmc_prometheus_exporter.\n create_metrics_context(session, {}, \"filename\"))\n\n\nclass TestDeleteContext(unittest.TestCase):\n \"\"\"Tests delete_metrics_context.\"\"\"\n\n def test_delete_context(self):\n \"\"\"Tests normal input, just needs to know no errors happen.\"\"\"\n session = zhmcclient_mock.FakedSession(\"fake-host\", \"fake-hmc\",\n \"2.13.1\", \"1.8\")\n client = zhmcclient.Client(session)\n context = client.metrics_contexts.create(\n {\"anticipated-frequency-seconds\": 15,\n \"metric-groups\": [\"metric-group\"]})\n zhmc_prometheus_exporter.delete_metrics_context(session, context)\n\n\nclass TestRetrieveMetrics(unittest.TestCase):\n \"\"\"Tests retrieve_metrics.\"\"\"\n\n def test_retrieve_metrics(self):\n \"\"\"Tests metrics retrieval with a fake CPC and fake metrics.\"\"\"\n session = zhmcclient_mock.FakedSession(\"fake-host\", \"fake-hmc\",\n \"2.13.1\", \"1.8\")\n session.hmc.add_resources({\"cpcs\": [{\"properties\": {\n \"name\": \"cpc_1\", \"object-uri\": \"cpc_1\"}}]})\n session.hmc.metrics_contexts.add_metric_group_definition(\n zhmcclient_mock.FakedMetricGroupDefinition(\n name=\"dpm-system-usage-overview\",\n types=[(\"metric\", \"integer-metric\")]))\n session.hmc.metrics_contexts.add_metric_values(\n zhmcclient_mock.FakedMetricObjectValues(\n group_name=\"dpm-system-usage-overview\",\n resource_uri=\"cpc_1\",\n timestamp=datetime.datetime.now(),\n values=[(\"metric\", 1)]))\n client = zhmcclient.Client(session)\n context = client.metrics_contexts.create(\n {\"anticipated-frequency-seconds\": 15,\n \"metric-groups\": [\"dpm-system-usage-overview\"]})\n expected_output = {\"dpm-system-usage-\"\n \"overview\": {\"cpc_1\": {\"metric\": 1}}}\n actual_output = zhmc_prometheus_exporter.retrieve_metrics(context)\n self.assertEqual(expected_output, actual_output)\n context.delete()\n session.logoff()\n\n\nclass TestFormatUnknown(unittest.TestCase):\n \"\"\"Tests format_unknown_metrics.\"\"\"\n\n def test_non_percent(self):\n \"\"\"Tests one with a non-percent value.\"\"\"\n expected_output = {\"percent\": False,\n \"exporter_name\": \"my_metric\",\n \"exporter_desc\": \"my metric\"}\n actual_output = (zhmc_prometheus_exporter.\n format_unknown_metric(\"my-metric\"))\n self.assertEqual(expected_output, actual_output)\n\n def test_percent(self):\n \"\"\"Tests one with a percent value.\"\"\"\n expected_output = {\"percent\": True,\n \"exporter_name\": \"my_metric_usage_ratio\",\n \"exporter_desc\": \"my metric usage\"}\n actual_output = (zhmc_prometheus_exporter.\n format_unknown_metric(\"my-metric-usage\"))\n self.assertEqual(expected_output, actual_output)\n\n\nclass TestIdentifyIncoming(unittest.TestCase):\n \"\"\"Tests identify_incoming_metrics.\"\"\"\n\n def test_unexpected_metric(self):\n \"\"\"Tests with some metric that is not known.\"\"\"\n # Verify a known metric does not get modified\n incoming_metrics = {\"metric-group\": {\"resource\": {\n \"known-metric\": 0, \"unknown-metric\": 0}}}\n yaml_metrics = {\"metric-group\": {\"known-metric\": {\n \"percent\": False,\n \"exporter_name\": \"known_metric\",\n \"exporter_desc\": \"known metric\"}}}\n expected_output = {\"metric-group\": {\n \"known-metric\": {\n \"percent\": False,\n \"exporter_name\": \"known_metric\",\n \"exporter_desc\": \"known metric\"},\n \"unknown-metric\": {\n \"percent\": False,\n \"exporter_name\": \"unknown_metric\",\n \"exporter_desc\": \"unknown metric\"}}}\n # Ignore warning\n with patch(\"sys.stderr\", new=StringIO()):\n actual_output = (zhmc_prometheus_exporter.\n identify_incoming_metrics(incoming_metrics,\n yaml_metrics,\n \"filename\"))\n self.assertEqual(expected_output, actual_output)\n\n\nclass TestAddFamilies(unittest.TestCase):\n \"\"\"Tests add_families.\"\"\"\n\n def test_add_families(self):\n \"\"\"Tests with some generic input.\"\"\"\n yaml_metric_groups = {\"metric-group\": {\"prefix\": \"pre\",\n \"fetch\": True}}\n input_metrics = {\"metric-group\": {\"metric\": {\n \"percent\": True,\n \"exporter_name\": \"metric\",\n \"exporter_desc\": \"metric\"}}}\n output = (zhmc_prometheus_exporter.\n add_families(yaml_metric_groups, input_metrics))\n families = output[\"metric-group\"][\"metric\"]\n self.assertIsInstance(families,\n prometheus_client.core.GaugeMetricFamily)\n self.assertEqual(families.name, \"zhmc_pre_metric\")\n self.assertEqual(families.documentation, \"metric\")\n self.assertEqual(families.type, \"gauge\")\n self.assertEqual(families.samples, [])\n self.assertEqual(families._labelnames, (\"resource\",))\n\n\nclass TestStoreMetrics(unittest.TestCase):\n \"\"\"Tests store_metrics.\"\"\"\n\n def test_store_metrics(self):\n \"\"\"Tests with some generic input.\"\"\"\n yaml_metric_groups = {\"metric-group\": {\"prefix\": \"pre\",\n \"fetch\": True}}\n yaml_metrics = {\"metric-group\": {\"metric\": {\n \"percent\": True,\n \"exporter_name\": \"metric\",\n \"exporter_desc\": \"metric\"}}}\n yaml_metrics_dict = {\"metric-group\": {\"resource\": {\"metric\": 0}}}\n family_objects = (zhmc_prometheus_exporter.\n add_families(yaml_metric_groups, yaml_metrics))\n output = zhmc_prometheus_exporter.store_metrics(yaml_metrics_dict,\n yaml_metrics,\n family_objects)\n stored = output[\"metric-group\"][\"metric\"]\n self.assertIsInstance(stored, prometheus_client.core.GaugeMetricFamily)\n self.assertEqual(stored.name, \"zhmc_pre_metric\")\n self.assertEqual(stored.documentation, \"metric\")\n self.assertEqual(stored.type, \"gauge\")\n# self.assertEqual(stored.samples, [(\"zhmc_pre_metric\",\n# {\"resource\": \"resource\"},\n# 0)])\n self.assertEqual(stored._labelnames, (\"resource\",))\n\n\nclass TestInitZHMCUsageCollector(unittest.TestCase):\n \"\"\"Tests ZHMCUsageCollector.\"\"\"\n\n def test_init(self):\n \"\"\"Tests ZHMCUsageCollector.__init__.\"\"\"\n cred_dict = {\"hmc\": \"192.168.0.0\", \"userid\": \"user\", \"password\": \"pwd\"}\n session = zhmcclient_mock.FakedSession(\"fake-host\", \"fake-hmc\",\n \"2.13.1\", \"1.8\")\n yaml_metric_groups = {\"metric-group\": {\"prefix\": \"pre\",\n \"fetch\": True}}\n context = (zhmc_prometheus_exporter.\n create_metrics_context(session,\n yaml_metric_groups,\n \"filename\"))\n yaml_metrics = {\"metric-group\": {\"metric\": {\n \"percent\": True,\n \"exporter_name\": \"metric\",\n \"exporter_desc\": \"metric\"}}}\n my_zhmc_usage_collector = (zhmc_prometheus_exporter.\n ZHMCUsageCollector(cred_dict,\n session,\n context,\n yaml_metric_groups,\n yaml_metrics,\n \"filename\",\n \"filename\"))\n self.assertEqual(my_zhmc_usage_collector.yaml_creds, cred_dict)\n self.assertEqual(my_zhmc_usage_collector.session, session)\n self.assertEqual(my_zhmc_usage_collector.context, context)\n self.assertEqual(my_zhmc_usage_collector.yaml_metric_groups,\n yaml_metric_groups)\n self.assertEqual(my_zhmc_usage_collector.yaml_metrics, yaml_metrics)\n self.assertEqual(my_zhmc_usage_collector.filename_metrics, \"filename\")\n self.assertEqual(my_zhmc_usage_collector.filename_creds, \"filename\")\n\n def test_collect(self):\n \"\"\"Test ZHMCUsageCollector.collect\"\"\"\n cred_dict = {\"hmc\": \"192.168.0.0\", \"userid\": \"user\", \"password\": \"pwd\"}\n session = zhmcclient_mock.FakedSession(\"fake-host\", \"fake-hmc\",\n \"2.13.1\", \"1.8\")\n yaml_metric_groups = {\"metric-group\": {\"prefix\": \"pre\",\n \"fetch\": True}}\n context = (zhmc_prometheus_exporter.\n create_metrics_context(session,\n yaml_metric_groups,\n \"filename\"))\n yaml_metrics = {\"metric-group\": {\"metric\": {\n \"percent\": True,\n \"exporter_name\": \"metric\",\n \"exporter_desc\": \"metric\"}}}\n my_zhmc_usage_collector = (zhmc_prometheus_exporter.\n ZHMCUsageCollector(cred_dict,\n session,\n context,\n yaml_metric_groups,\n yaml_metrics,\n \"filename\",\n \"filename\"))\n collected = list(my_zhmc_usage_collector.collect())\n self.assertEqual(len(collected), 1)\n self.assertEqual(type(collected[0]),\n prometheus_client.core.GaugeMetricFamily)\n self.assertEqual(collected[0].name, \"zhmc_pre_metric\")\n self.assertEqual(collected[0].documentation, \"metric\")\n self.assertEqual(collected[0].type, \"gauge\")\n self.assertEqual(collected[0].samples, [])\n self.assertEqual(collected[0]._labelnames, (\"resource\",))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"zhmc_prometheus_exporter/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":20509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"298719777","text":"\"\"\"\n AVM SmartHome Actor\n ~~~~~~~~~~~~~~~~~~~\n\"\"\"\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nclass Actor(object):\n \"\"\"\n Represents a single SmartHome actor.\n You usally don't create that class yourself, use FritzBox.get_actors\n instead.\n \"\"\"\n def __init__(self, device_xml):\n self.actor_id = device_xml.attrib['identifier']\n self.device_id = device_xml.attrib['id']\n self.name = device_xml.find('name').text\n self.fwversion = device_xml.attrib['fwversion']\n self.productname = device_xml.attrib['productname']\n self.manufacturer = device_xml.attrib['manufacturer']\n\n self.functionbitmask = int(device_xml.attrib['functionbitmask'])\n self.has_hkr = self.functionbitmask & (1 << 6) > 0\n self.has_powermeter = self.functionbitmask & (1 << 7) > 0\n self.has_temperature = self.functionbitmask & (1 << 8) > 0\n self.has_switch = self.functionbitmask & (1 << 9) > 0\n self.hast_dect_repeater = self.functionbitmask & (1 << 10) > 0\n\n self.temperature = 0.0\n if self.has_temperature:\n if device_xml.find(\"temperature\").find(\"celsius\").text is not None:\n self.temperature = float(device_xml.find(\"temperature\").find(\"celsius\").text) / 10.0\n else:\n logger.warn(\"Actor \" + self.name + \" seems offline. Returning None as temperature.\")\n self.temperature=None\n\n def __repr__(self):\n return u''.format(repr(self.name))\n","sub_path":"fritzhome/actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"419792190","text":"# -*- coding: utf-8 -*-\n\"\"\"\n# Shake.cli.globals\n\n\"\"\"\nimport os\nimport re\n\nfrom pyceo import Manager, format_title\nimport voodoo\n\n\nmanager = Manager()\n\n\nROOTDIR = os.path.realpath(os.path.join(os.path.dirname(__file__),\n '..', 'skeletons'))\n\nENV_OPTIONS = {\n 'autoescape': False,\n 'block_start_string': '[%',\n 'block_end_string': '%]',\n 'variable_start_string': '[[',\n 'variable_end_string': ']]',\n}\n\nFILTER = ('.pyc', '.DS_Store', '.pyo')\n\n","sub_path":"shake/cli/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"291927462","text":"import inspect\nfrom typing import Callable\n\nimport pytest\nfrom kfp import Client\n\nfrom .pipelines.cowsay import cowsay_pipeline\nfrom .pipelines.jupyter import jupyter_pipeline\nfrom .pipelines.katib import katib_pipeline\nfrom .pipelines.mnist import mnist_pipeline\nfrom .pipelines.object_detection import object_detection_pipeline\n\n\ndef get_params(func):\n return {name: value.default for name, value in inspect.signature(func).parameters.items()}\n\n\n@pytest.mark.parametrize(\n 'name,fn',\n [\n pytest.param(\n 'mnist',\n mnist_pipeline,\n marks=[pytest.mark.full, pytest.mark.lite, pytest.mark.edge],\n ),\n pytest.param(\n 'cowsay',\n cowsay_pipeline,\n marks=[pytest.mark.full, pytest.mark.lite, pytest.mark.edge],\n ),\n pytest.param(\n 'katib',\n katib_pipeline,\n marks=[pytest.mark.full],\n ),\n # pytest.param(\n # 'jupyter',\n # jupyter_pipeline,\n # marks=[pytest.mark.full, pytest.mark.lite],\n # ),\n pytest.param(\n 'object_detection',\n object_detection_pipeline,\n marks=pytest.mark.gpu,\n ),\n ],\n)\ndef test_pipelines(name: str, fn: Callable):\n \"\"\"Runs each pipeline that it's been parameterized for, and waits for it to succeed.\"\"\"\n\n client = Client('127.0.0.1:8888')\n run = client.create_run_from_pipeline_func(fn, arguments=get_params(fn))\n completed = client.wait_for_run_completion(run.run_id, timeout=3600)\n status = completed.to_dict()['run']['status']\n assert status == 'Succeeded', f'Pipeline {name} status is {status}'\n","sub_path":"tests/test_pipelines.py","file_name":"test_pipelines.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"194355468","text":"from rest_framework.test import APILiveServerTestCase, RequestsClient\nfrom rest_framework import status\nfrom football_api.tournaments.models import Tournament, Team, Match, Goal\n\n\nclass MarsCupTest(APILiveServerTestCase):\n\n def setUp(self):\n self.client = RequestsClient()\n self.tournament_data = {'name': 'Mars2100',\n 'host_countries': 'Tomorrowland',\n 'start_date': '2100-01-01',\n 'end_date': '2100-01-02',\n 'teams_number': 100,\n 'champion': 'Some Marvel hero',\n 'description': 'Mars world cup 2100'\n }\n self.tournament = Tournament.objects.create(**self.tournament_data)\n self.team1_data = {'country': 'aaa', 'name': 'dreamteam1', 'coach': 'coach1', 'year': '2100'}\n self.team2_data = {'country': 'bbb', 'name': 'dreamteam2', 'coach': 'coach2', 'year': '2100'}\n self.team1 = Team.objects.create(**self.team1_data)\n self.team2 = Team.objects.create(**self.team2_data)\n\n self.match_data = {'date': '2012-07-01',\n 'stadium': 'Warsaw',\n 'team1': self.team1,\n 'team2': self.team2,\n 'tournament': self.tournament}\n self.match = Match.objects.create(**self.match_data)\n\n self.goal_data = {'player': 'IronMan',\n 'time': 10,\n 'match': self.match,\n 'team': self.team1,\n 'tournament': self.tournament}\n self.goal = Goal.objects.create(**self.goal_data)\n\n def test_teams_retrieve(self):\n response = self.client.get(self.live_server_url + '/tournaments/teams/' + str(self.team1.id))\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.json(), self.team1_data)\n\n def test_matches_list(self):\n response = self.client.get(self.live_server_url + '/tournaments/matches')\n resp_data = response.json()[0]\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(resp_data['stadium'], self.match.stadium)\n\n def test_goals_retrieve(self):\n response = self.client.get(self.live_server_url + '/tournaments/Mars2100/goals/' + str(self.goal.id))\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.json()['player'], self.goal.player)\n","sub_path":"football_api/tournaments/tests/tests_liveserver.py","file_name":"tests_liveserver.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"350102486","text":"import json\nimport urllib2\ntry:\n from markdown import markdown\nexcept ImportError:\n print('WARNING: failed to import markdown')\n markdown = lambda x: x\n\ndef load_dataset(datapackage_url):\n print('Processing: %s' % datapackage_url)\n base = datapackage_url.rstrip('datapackage.json')\n # TODO: deal with 404s gracefully\n try:\n datapackage = json.load(urllib2.urlopen(datapackage_url))\n except:\n print('Failed to load %s' % datapackage_url)\n return None\n\n # ensure certain fields exist\n if not 'description' in datapackage:\n datapackage['description'] = ''\n\n # get the readme\n readme_url = base + 'README.md'\n try:\n readmefo = urllib2.urlopen(readme_url)\n datapackage['readme'] = readmefo.read().replace('\\r\\n', '\\n')\n except:\n datapackage['readme'] = datapackage['description']\n pass\n # set description as first paragraph of readme if we no description\n if not datapackage['description'] and 'readme' in datapackage:\n # first extract plain text ...\n html = markdown(unicode(datapackage['readme'], 'utf8'))\n plain = strip_tags(html).split('\\n\\n')[0].replace(' \\n', '').replace('\\n', ' ')\n datapackage['description'] = plain.encode('utf8')\n\n for info in datapackage['resources']:\n if (not info.get('url') and info.get('path')):\n info['url'] = base + info.get('path')\n\n return datapackage\n\nfrom HTMLParser import HTMLParser\n\nclass MLStripper(HTMLParser):\n def __init__(self):\n self.reset()\n self.fed = []\n def handle_endtag(self, tag):\n if tag == 'p':\n self.fed.append('\\n\\n')\n def handle_data(self, d):\n self.fed.append(d)\n def get_data(self):\n return ''.join(self.fed)\n\ndef strip_tags(html):\n s = MLStripper()\n s.feed(html)\n return s.get_data()\n\ndef load(dataset_names):\n out = [ load_dataset(name) for name in dataset_names if name ]\n # if failed loads returned dp is None\n out = [ x for x in out if x ]\n out = dict([ (x['name'], x) for x in out ])\n return out\n\n\ndef build_index(dataset_list_url, outpath='datapackage-index.json'):\n dataset_list = open(dataset_list_url).read().split('\\n')\n # strip out blank lines or similar which can creep in\n dataset_list = [_to_dp_url(ds) for ds in dataset_list if ds]\n index = load(dataset_list)\n with open(outpath, 'w') as dest:\n json.dump(index, dest, indent=2, sort_keys=True)\n\ndef _to_dp_url(nameOrUrl):\n if '/' not in nameOrUrl:\n url = 'https://raw.github.com/senegalouvert/data/master/' + nameOrUrl + '/'\n else:\n url = nameOrUrl\n\n if not url.endswith('datapackage.json'):\n url = url.rstrip('/')\n url += '/datapackage.json'\n\n return url\n \n\n\nimport sys\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n listpath = sys.argv[1]\n else:\n listpath = 'datapackage-list.txt'\n if len(sys.argv) > 2:\n outpath = sys.argv[2]\n else:\n outpath = 'datapackage-index.json'\n build_index(listpath, outpath)\n\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"288139978","text":"import pyautogui\nimport time \n\nimport random\nimport game.browser_control\n\ncurrentGrid = [[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]]\n\nUP = 100\nLEFT = 101\nDOWN = 102\nRIGHT = 103\nSCALE_FACTOR = 2\nSPEED = 9\n\nSPEED_LIST = list(reversed([0.00001,0.00005,0.0005,0.005,0.01,0.05,0.1,0.5,1,2]))\nWAIT = SPEED_LIST[SPEED]\n\n\ndef moves_map(move_id):\n # 0, 1, 2, 3 are up, right, down, left\n # moves_map = {0:UP,1:DOWN,2:LEFT,3:RIGHT}\n moves_map = {0:UP,1:RIGHT,2:DOWN,3:LEFT}\n return moves_map[move_id]\n\ndef getGrid():\n currentGrid = game.browser_control.get_grid()\n return currentGrid\n \ndef printGrid(grid):\n for t in range(len(grid)):\n print(grid[t])\n\ndef performMove(action):\n move = moves_map(action)\n pyautogui.click(x=65,y=266)\n if move == UP:\n pyautogui.keyDown('up')\n # time.sleep(0.05)\n pyautogui.keyUp('up')\n elif move == DOWN:\n pyautogui.keyDown('down')\n # time.sleep(0.05)\n pyautogui.keyUp('down')\n elif move == LEFT:\n pyautogui.keyDown('left')\n # time.sleep(0.05)\n pyautogui.keyUp('left')\n else:\n pyautogui.keyDown('right')\n # time.sleep(0.05)\n pyautogui.keyUp('right')\n # pyautogui.click(x=1200*2,y=850*2)\n pyautogui.PAUSE = WAIT\n # time.sleep(0.3)\n \ndef restart_game():\n print(\"STARTING NEW GAME\")\n # time.sleep(0.5)\n pyautogui.moveTo(x=530,y=265)\n pyautogui.click(x=530,y=265)\n pyautogui.click(x=530,y=265)\n # time.sleep(0.5)\n pyautogui.click(x=1120,y=500)\n # time.sleep(0.5)\n\ndef getScore():\n score = game.browser_control.get_score() \n return score\n\ndef getBestScore():\n bestScore = game.browser_control.get_best_score()\n return bestScore\n\ndef isOver():\n isOver = game.browser_control.is_over()\n return isOver\n ","sub_path":"game/game_control.py","file_name":"game_control.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"432566095","text":"import socket\r\nimport TCPUtils\r\n\r\nclass CorkProxy(object):\r\n\r\n def __init__(self, address, port):\r\n self.address = address\r\n self.port = port\r\n \r\n def postMessage(self, message):\r\n sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) \r\n sock.connect( (self.address, self.port))\r\n TCPUtils.sendObject(sock,\"postMessage\")\r\n TCPUtils.sendObject(sock,message)\r\n sock.close() \r\n \r\n def getMessages(self):\r\n sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) \r\n sock.connect( (self.address, self.port))\r\n TCPUtils.sendObject(sock,\"getMessages\")\r\n messages = TCPUtils.readObject(sock)\r\n sock.close()\r\n return messages \r\n \r\n def clearMessages(self):\r\n sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) \r\n sock.connect( (self.address, self.port))\r\n TCPUtils.sendObject(sock,\"clearMessages\")\r\n sock.close() ","sub_path":"Topics/03_NetworkProgramming/EX3_NetworkHiLo/pyro/CorkProxy.py","file_name":"CorkProxy.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"55670035","text":"# black 3x3 image form\nimport numpy\nimport cv2\n\nimg = numpy.zeros((1024, 1024), dtype=numpy.uint8) # 1024, 1024 --> dimensoin and uint8 --> 8 bits of 1 pixel\nimg = cv2.resize(img, (700, 500))\nprint(img) # print image value\ncv2.imwrite('Img_Black_background.jpg', img) # write image\ncv2.imshow('Img_Black_background', img) # image display\ncv2.waitKey(0) # wait till u enter any key\ncv2.destroyAllWindows() # close all windows","sub_path":"Img_Black_background.py","file_name":"Img_Black_background.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"427074536","text":"# File: statements.py\n# Template file for Informatics 2A Assignment 2:\n# 'A Natural Language Query System in Python/NLTK'\n\n# John Longley, November 2012\n# Revised November 2013 and November 2014 with help from Nikolay Bogoychev\n# Revised November 2015 by Toms Bergmanis and Shay Cohen\n\n\n# PART A: Processing statements\n\ndef add(lst,item):\n if (item not in lst):\n lst.insert(len(lst),item)\n\nclass Lexicon:\n \"\"\"stores known word stems of various part-of-speech categories\"\"\"\n def __init__ (self):\n self.tupleList = []\n def add (self, stem, cat):\n self.tupleList.append((stem, cat))\n def getAll (self, cat):\n lst = []\n for t in self.tupleList:\n if (t[1] == cat):\n add (lst, t[0])\n return lst\n\n#lx = Lexicon()\n#lx.add(\"fly\", \"I\")\n#lx.add(\"swim\", \"I\")\n#lx.add(\"John\", \"P\")\n#lx.add(\"Mary\", \"P\")\n#lx.add(\"duck\", \"N\")\n#lx.add(\"student\", \"N\")\n#lx.add(\"hit\", \"T\")\n#lx.add(\"like\", \"T\")\n#lx.add(\"purple\", \"A\")\n#lx.add(\"old\", \"A\")\n#print lx.getAll(\"I\")\n\nclass FactBase:\n def __init__ (self):\n self.unary = []\n self.binary = []\n def addUnary (self, pred, e1):\n self.unary.append((pred, e1))\n def addBinary (self, pred, e1, e2):\n self.binary.append((pred, e1, e2))\n def queryUnary (self, pred, e1):\n for u in self.unary:\n if (u == (pred, e1)):\n return True\n break\n return False\n def queryBinary (self, pred, e1, e2):\n if ((pred, e1, e2) in self.binary):\n return True\n else:\n return False\n\n#fb = FactBase()\n#fb.addUnary(\"duck\",\"John\")\n#fb.addBinary(\"love\",\"John\",\"Mary\")\n#print fb.queryUnary(\"duck\",\"John\")\n#print fb.queryBinary(\"love\",\"Mary\",\"John\")\n\nimport re\nfrom nltk.corpus import brown\ndef verb_stem(s):\n \"\"\"extracts the stem from the 3sg form of a verb, or returns empty string\"\"\"\n ok = 0\n\n if (re.match(\"\\w*([^aeiousxyzh]|[^cs]h)s$\", s)):\n stem = s[:-1]\n elif (re.match(\"(\\w*)[aeiou]ys$\", s)):\n stem = s[:-1]\n elif (re.match(\"\\w+[^aeiou]ies$\", s)):\n stem = s[:-3]+'y'\n elif (re.match(\"[^aeiou]ies$\", s)):\n stem = s[:-1]\n elif (re.match(\"\\w*([ox]|ch|sh|ss|zz)es$\", s)):\n stem = s[:-2]\n elif (re.match(\"\\w*(([^s]se)|([^z]ze))s$\", s)):\n stem = s[:-1]\n elif (re.match(\"has\", s)):\n stem = \"have\"\n elif (re.match(\"\\w*([^iosxzh]|[^cs]h)es$\", s)):\n stem = s[:-1]\n else:\n stem = \"\"\n\n if (stem != \"\" and ok != 1):\n for (word, tag) in brown.tagged_words():\n if word == stem and tag in ('VB', 'VBZ'):\n return stem\n ok = 1\n break\n\n if (ok == 0):\n return \"\"\n\n#print verb_stem(\"boxes\")\n#print verb_stem(\"bathes\")\n#print verb_stem(\"ties\")\n#print verb_stem(\"unties\")\n#print verb_stem(\"unifies\")\n#print verb_stem(\"eat\")\n#print verb_stem(\"cats\")\n#print verb_stem(\"pays\")\n#print verb_stem(\"flies\")\n#print verb_stem(\"dies\")\n#print verb_stem(\"washes\")\n#print verb_stem(\"dresses\")\n#print verb_stem(\"loses\")\n#print verb_stem(\"has\")\n#print verb_stem(\"likes\")\n#print verb_stem(\"flys\")\n#print verb_stem(\"goes\")\n#print verb_stem(\"fizzes\")\n\ndef add_proper_name (w,lx):\n \"\"\"adds a name to a lexicon, checking if first letter is uppercase\"\"\"\n if ('A' <= w[0] and w[0] <= 'Z'):\n lx.add(w,'P')\n return ''\n else:\n return (w + \" isn't a proper name\")\n\ndef process_statement (lx,wlist,fb):\n \"\"\"analyses a statement and updates lexicon and fact base accordingly;\n returns '' if successful, or error message if not.\"\"\"\n # Grammar for the statement language is:\n # S -> P is AR Ns | P is A | P Is | P Ts P\n # AR -> a | an\n # We parse this in an ad hoc way.\n msg = add_proper_name (wlist[0],lx)\n if (msg == ''):\n if (wlist[1] == 'is'):\n if (wlist[2] in ['a','an']):\n lx.add (wlist[3],'N')\n fb.addUnary ('N_'+wlist[3],wlist[0])\n else:\n lx.add (wlist[2],'A')\n fb.addUnary ('A_'+wlist[2],wlist[0])\n else:\n stem = verb_stem(wlist[1])\n if (len(wlist) == 2):\n lx.add (stem,'I')\n fb.addUnary ('I_'+stem,wlist[0])\n else:\n msg = add_proper_name (wlist[2],lx)\n if (msg == ''):\n lx.add (stem,'T')\n fb.addBinary ('T_'+stem,wlist[0],wlist[2])\n return msg\n\n# End of PART A.\n","sub_path":"UI/statements.py","file_name":"statements.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"34236391","text":"import os\nimport hashlib\nimport requests\nimport shutil\nimport glob\nfrom tornado.web import RequestHandler, stream_request_body, StaticFileHandler\nfrom tornado.websocket import WebSocketHandler\nimport tornado.httpclient\nfrom tornado.ioloop import IOLoop\nfrom .multipart_streamer import MultiPartStreamer\nfrom tornado.concurrent import run_on_executor\nfrom concurrent.futures import ThreadPoolExecutor\nfrom logzero import logger\n\n\nclass IndexHandler(RequestHandler):\n async def get(self):\n self.render(\"index.html\")\n\n\nclass WebSocketForwardHandler(WebSocketHandler):\n def initialize(self, forward_uri, binary=True):\n self.forward_uri = forward_uri\n self.binary = binary\n\n def check_origin(self, origin):\n return True\n\n async def forward(self):\n while True:\n msg = await self.ws.read_message()\n if msg is None:\n break\n await self.write_message(msg, binary=self.binary)\n\n async def open(self):\n self.ws = await tornado.websocket.websocket_connect(self.forward_uri)\n IOLoop.current().spawn_callback(self.forward)\n\n async def on_message(self, msg):\n await self.ws.write_message(msg, binary=self.binary)\n\n def on_close(self):\n pass\n\n\nclass HttpForwardHandler(RequestHandler):\n def initialize(self, forward_uri):\n self.forward_uri = forward_uri\n self.http_client = tornado.httpclient.AsyncHTTPClient()\n\n async def get(self):\n response = await self.http_client.fetch(\n self.forward_uri + self.request.uri, headers=self.request.headers\n )\n self.set_status(response.code)\n self._headers = response.headers\n self._headers.pop(\"Transfer-Encoding\", None)\n self.write(response.body)\n\n async def post(self):\n response = await self.http_client.fetch(\n self.forward_uri + self.request.uri,\n method=\"POST\",\n body=self.request.body,\n headers=self.request.headers,\n )\n self.set_status(response.code)\n self._headers = response.headers\n self._headers.pop(\"Transfer-Encoding\", None)\n self.write(response.body)\n\n\n@stream_request_body\nclass UploadListHandler(RequestHandler): # replace UploadListHandler\n async def prepare(self):\n if self.request.method.lower() == \"post\":\n self.request.connection.set_max_body_size(8 << 30) # 8G\n try:\n total = int(self.request.headers.get(\"Content-Length\", \"0\"))\n except KeyError:\n total = 0\n self.ps = MultiPartStreamer(total)\n\n def data_received(self, chunk):\n self.ps.data_received(chunk)\n\n async def post(self):\n try:\n self.ps.data_complete() # close the incoming stream.\n parts = self.ps.get_parts_by_name(\"file\")\n if len(parts) == 0:\n self.write(\n {\n \"success\": False,\n \"description\": 'no form \"file\" providered',\n }\n )\n return\n\n filepart = parts[0]\n filepart.f_out.seek(0)\n\n # save file\n target_dir = os.path.join(\n \"uploads\", filepart.md5sum[:2], filepart.md5sum[2:]\n )\n os.makedirs(target_dir, exist_ok=True)\n _, ext = os.path.splitext(filepart.get_filename())\n target_path = os.path.join(target_dir, \"file\" + ext)\n if not os.path.isfile(target_path):\n filepart.move(target_path)\n\n # gen file info\n url = \"\".join(\n [\n self.request.protocol,\n \"://\",\n self.request.host,\n \"/\",\n target_path.replace(\"\\\\\", \"/\"),\n ]\n )\n data = dict(url=url, md5sum=filepart.md5sum)\n self.write(\n {\n \"success\": True,\n \"data\": data,\n }\n )\n finally:\n self.ps.release_parts()\n\n\nclass InstallHandler(RequestHandler):\n _install_executor = ThreadPoolExecutor(4)\n _download_executor = ThreadPoolExecutor(1)\n\n def cache_filepath(self, text: str) -> str:\n m = hashlib.md5()\n m.update(text.encode(\"utf-8\"))\n return \"cache-\" + m.hexdigest()\n\n @run_on_executor(executor=\"_download_executor\")\n def cache_download(self, url: str) -> str:\n \"\"\"download with local cache\"\"\"\n target_path = self.cache_filepath(url)\n logger.debug(\"Download %s to %s\", url, target_path)\n\n if os.path.exists(target_path):\n logger.debug(\"Cache hited\")\n return target_path\n\n # TODO: remove last\n for fname in glob.glob(\"cache-*\"):\n logger.debug(\"Remove old cache: %s\", fname)\n os.unlink(fname)\n\n tmp_path = target_path + \".tmp\"\n r = requests.get(url, stream=True)\n r.raise_for_status()\n\n with open(tmp_path, \"wb\") as tfile:\n content_length = int(r.headers.get(\"content-length\", 0))\n if content_length:\n for chunk in r.iter_content(chunk_size=40960):\n tfile.write(chunk)\n else:\n shutil.copyfileobj(r.raw, tfile)\n\n os.rename(tmp_path, target_path)\n return target_path\n\n @run_on_executor(executor=\"_install_executor\")\n def app_install_url(self, apk_path: str, **kwargs):\n return self.application.device.install(apk_path, **kwargs) \n\n async def post(self):\n url = self.get_argument(\"url\")\n launch = self.get_argument(\"launch\", \"false\") in [\"true\", \"True\", \"TRUE\", \"1\"]\n\n apk_path = await self.cache_download(url)\n pkg_name = await self.app_install_url(apk_path, launch=launch)\n self.write({\n \"success\": True,\n \"description\": \"Success\",\n \"packageName\": pkg_name,\n })\n\n\nclass UploadItemHandler(StaticFileHandler):\n async def get(self, path, include_body=True):\n filepath = self.get_absolute_path(self.root, path)\n if os.path.isfile(filepath):\n os.utime(filepath, None) # update modtime\n await super().get(path, include_body)\n","sub_path":"app/handlers/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":6296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"587546310","text":"class Garage():\n\n def __init__(self, spots, tickets):\n self.spots = spots\n self.tickets = tickets\n self.currentTicket = {\n 1: False,\n 2: False,\n 3: False,\n 4: False,\n 5: False,\n 6: False,\n 7: False,\n 8: False,\n 9: False,\n 10: False\n }\n\n # def showSpots(self):\n # pass\n\n def takeTicket(self):\n if self.spots and self.tickets:\n user_spot = self.spots.pop()\n user_tickets = self.tickets.pop()\n print(f\"Your parking spot is {user_spot}\\n\"\n + f\"Your ticket number is {user_tickets}.\")\n else:\n print(\"Sorry the parking lot is full.\")\n\n def payForParking(self):\n ticket_number = int(input(\"Scan your ticket: \"))\n if ticket_number in self.currentTicket:\n print(\"Valid Ticket\")\n if self.currentTicket[ticket_number] == False:\n input(\"Press any key to pay for your ticket\")\n self.currentTicket[ticket_number] = True\n print(\"Okay new you have paid\")\n else:\n print(\"Ticket has been paid, Thank you\")\n return ticket_number\n else:\n print(\"Invalid Ticket\")\n\n def leaveGarage(self):\n ticket_number = self.payForParking()\n # ticket_number = int(input(\"Scan your ticket: \"))\n # if ticket_number in self.currentTicket:\n # print(\"Valid Ticket\")\n # if self.currentTicket[ticket_number] == False:\n # print(\"Okay pay for your ticket\")\n # self.currentTicket[ticket_number] = True\n # print(\"Okay new you have paid\")\n # else:\n # print(\"Ticket has been paid, Thank you\")\n # else:\n # print(\"Invalid Ticket\")\n input(\"You have 15 minutes to leave \")\n print(\"Thank you, have a nice day!\")\n self.spots.append(ticket_number)\n self.tickets.append(ticket_number)\n\n def run():\n while True:\n response = input(\"What do you want to do? You can: pay or quit. Type only one!\")\n \n if response.lower() == 'park':\n self.takeTicket()\n \n if response.lower() == 'pay':\n self.payForParking()\n\n if response.lower() == 'leave':\n self.leaveGarage()\n \n if response.lower() == 'quit':\n self.payForParking()\n print(\"Thanks for using our Parking Garage!\")\n\n#Added comment for test \n\ngarage = Garage([1, 2, 3, 4,5, 6, 7, 8 , 9, 10], [1, 2, 3, 4,5, 6, 7, 8 , 9, 10])\n\ngarage.takeTicket()\n#garage.payForParking() \ngarage.leaveGarage()\n\n","sub_path":"parkingGarage.py","file_name":"parkingGarage.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"487894827","text":"\"\"\"\nCopyright (c) 2015 Red Hat, Inc\nAll rights reserved.\n\nThis software may be modified and distributed under the terms\nof the BSD license. See the LICENSE file for details.\n\"\"\"\n\nimport json\nimport argparse\nimport pkg_resources\nfrom base64 import b64encode\n\n\ndef generate_json(args):\n with open(args.cert, \"r\") as fpcer:\n with open(args.key, \"r\") as fpkey:\n pulpsecret = {\n 'apiVersion': 'v1beta3',\n 'kind': 'Secret',\n 'metadata': {\n 'name': args.name,\n 'namespace': args.namespace\n },\n 'data': {\n 'pulp.cer': b64encode(fpcer.read()),\n 'pulp.key': b64encode(fpkey.read())\n }\n }\n print(json.dumps(pulpsecret, indent=2))\n\n\nclass CLI(object):\n def __init__(self):\n self.parser = argparse.ArgumentParser(\n description=\"pulpsecret-gen, tool for creating secret resource\"\n )\n\n def set_arguments(self):\n try:\n version = pkg_resources.get_distribution(\"atomic_reactor\").version\n except pkg_resources.DistributionNotFound:\n version = \"GIT\"\n\n exclusive_group = self.parser.add_mutually_exclusive_group()\n exclusive_group.add_argument(\"-V\", \"--version\", action=\"version\", version=version)\n self.parser.add_argument('-C', '--cert', default=False, required=True,\n help='specify a certificate file')\n self.parser.add_argument('-K', '--key', default=False, required=True,\n help='specify a key file')\n self.parser.add_argument('--name', default='pulpsecret',\n help='resource name')\n self.parser.add_argument('--namespace', default='default',\n help='namespace')\n\n def run(self):\n self.set_arguments()\n args = self.parser.parse_args()\n try:\n generate_json(args)\n except KeyboardInterrupt:\n pass\n\n\ndef run():\n cli = CLI()\n cli.run()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"atomic_reactor/cli/secret.py","file_name":"secret.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"357136195","text":"\"\"\"\nLimpieza del corpus.\n\nElementos útiles:\n
    : title, contenido\n

    : contenido\n : contenido\n : href, contenido\n\nDudas y comentarios:\n * ¿Mezclar todos los contenidos o separarlos en arreglos distintos?\n * Problema. Se reconocen algunos caracteres especiales de HTML como parte del XML (por ejemplo: & ).\n https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined%5Fentities%5Fin%5FXML\n\"\"\"\n\nimport re\nimport time\nimport xml.etree.ElementTree as ET\n\ntraining_path = '../../data/articles-training-20180831.xml/articles-training-20180831.xml'\ntraining_labels_path = '../../data/ground-truth-training-20180831.xml/ground-truth-training-20180831.xml'\n\nvalidation_path = '../../data/articles-validation-20180831.xml/articles-validation-20180831.xml'\nvalidation_labels_path = '../../data/ground-truth-validation-20180831.xml/ground-truth-validation-20180831.xml'\n\n\n####### CONFIGURA DATASET #######\n\ndataset = 'validation' # 'train' o 'validation'\nLIMIT = 100\n\n##################################\n\nif dataset == 'train':\n articles_path = training_path\n labels_path = training_labels_path\nelif dataset == 'validation':\n articles_path = validation_path\n labels_path = validation_labels_path\n\noutput_path = 'dataset/{}_{}.txt'.format(dataset, LIMIT)\nprint('Dataset:', output_path)\n\n##################################\n\ndef clean_data(text):\n \"\"\" Limpia el texto recibido. \"\"\"\n text = re.sub(r'\\?[a-zA-Z]\\b', ' ', text) # Cambia (?) seguido de una letra por espacio.\n # text = re.sub(r'&', '', text) # Quita & No es necesario ya que XML lo convierte al símbolo (&).\n text = re.sub(r'#160;', '', text) # Quita #160;\n text = re.sub(r'[^0-9a-zA-Z\\. ]', '', text) # Quita símbolos especiales. Los puntos pueden utilizarse obtener sentencias.\n text = re.sub(r' {2,}', ' ', text) # Quita espacios en blanco repetidos.\n return text.strip()\n\n\nstart_time = time.time()\n\n\narticles_xml = iter(ET.iterparse(articles_path, events=['start','end']))\nlabels_xml = iter(ET.iterparse(labels_path, events=['start']))\n\n_, root_articles = next(articles_xml)\n_, _ = next(labels_xml) # lee el primer elemento (lo omite).\n\ncnt = 0\nwith open(output_path, 'w', encoding='UTF-8') as output_file:\n\n article = ''\n for event, elem in articles_xml:\n # Etiqueta

    .\n if elem.tag == 'article':\n\n if event == 'start': # Apertura de un artículo.\n cnt = cnt+1\n article = elem.attrib['title'] + ' '\n idx = elem.attrib['id']\n else: # Cierre de un artículo.\n _, label = next(labels_xml)\n\n if idx != label.attrib['id']:\n raise ValueError('Los IDs no coinciden: {}, {}'.format(idx, label.attrib['id']))\n\n val = 1 if 'true' == label.attrib['hyperpartisan'] else 0\n output_file.write('{},{},{}\\n'.format(idx, clean_data(article), val))\n\n # Cierre de etiquetas (excepto article).\n elif event == 'end':\n pass\n\n # Apertura de etiquetas

    , o .\n elif elem.tag == 'p' or elem.tag == 'q' or elem.tag == 'a':\n if elem.text != None:\n article = article + elem.text + ' '\n\n root_articles.clear()\n\n if cnt > LIMIT:\n break\n\nprint('Total time: %.3f s' % (time.time() - start_time))\n","sub_path":"embeddingsLSTM/build_dataset.py","file_name":"build_dataset.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"382959450","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport codecs\nimport os.path\nimport re\nimport sys\n\nfrom cStringIO import StringIO\nfrom pkg_resources import resource_listdir, resource_string\n\nfrom trac.loader import load_components\nfrom trac.test import EnvironmentStub, Mock, MockPerm\nfrom trac.util.text import printerr, printout\nfrom trac.web.chrome import web_context\nfrom trac.web.href import Href\nfrom trac.wiki.formatter import format_to_html\nfrom trac.wiki.model import WikiPage\n\ntry:\n import html2rest\nexcept ImportError:\n printerr(\"The html2rest package must be installed.\")\n sys.exit(1)\n\n\nclass Parser(html2rest.Parser):\n\n def __init__(self, writer=sys.stdout, encoding='utf8', relroot=None,\n relpath=None):\n html2rest.Parser.__init__(self, writer, encoding, relroot, relpath)\n self.links = {}\n\n def end_a(self):\n if '#pending' in self.hrefs:\n href = self.hrefs['#pending']\n label = self.hrefs[href]\n key = label.lower()\n if key not in self.links:\n self.links[key] = (label, href)\n elif href != self.links[key][1]:\n alt = label\n while True:\n alt += '*'\n if alt not in self.links:\n break\n continue\n self.data(alt[len(label):])\n self.hrefs[href] = alt\n self.links[alt] = (alt, href)\n self.data('`_')\n del self.hrefs['#pending']\n\n def end_body(self):\n self.end_p()\n for label, href in self.links.itervalues():\n if href[0] != '#':\n self.writeline('.. _%s: %s' % (label, href))\n self.end_p()\n\n\ndef wiki2rest(env, context, wiki):\n text = re.sub('\\r?\\n', '\\n', wiki.text)\n text = re.sub(r'\\[\\[TracGuideToc\\]\\]\\r?\\n?', '', text)\n text = re.sub(r'\\[\\[PageOutline\\([^\\)]*\\)\\]\\]\\r?\\n?', '', text)\n html = format_to_html(env, context, text)\n html = html.replace(u'\\u200b', '')\n html = re.sub(r'\\s*([^<]*?)\\s*', r'\\1', html)\n html = '%s' % html\n writer = StringIO()\n parser = Parser(writer, 'utf-8', None, None)\n parser.feed(html)\n parser.close()\n rst = writer.getvalue().strip('\\n')\n rst = re.sub('\\n{4,}', '\\n\\n\\n', rst)\n # sort links\n rst = re.sub(r'(?:\\n\\.\\. _[^\\n]*)+\\Z',\n lambda m: '\\n'.join(sorted(m.group(0).split('\\n'),\n key=lambda v: v.lower())),\n rst)\n if any(ord(c) > 0x7f for c in rst):\n # Trac detects utf-8 using BOM\n rst = '%s.. charset=utf-8\\n\\n%s' % (codecs.BOM_UTF8, rst)\n return rst + '\\n'\n\n\ndef main():\n names = sorted(name for name in resource_listdir('trac.wiki',\n 'default-pages')\n if not name.startswith('.'))\n\n env = EnvironmentStub()\n load_components(env)\n with env.db_transaction:\n for name in names:\n wiki = WikiPage(env, name)\n wiki.text = resource_string('trac.wiki', 'default-pages/' +\n name).decode('utf-8')\n if wiki.text:\n wiki.save('trac', '')\n else:\n printout('%s: Skipped empty page' % name)\n\n req = Mock(href=Href('/'), abs_href=Href('http://trac.edgewall.org/'),\n perm=MockPerm(), chrome={})\n for name in sys.argv[1:]:\n name = os.path.basename(name)\n wiki = WikiPage(env, name)\n if not wiki.exists:\n continue\n context = web_context(req, wiki.resource, absurls=True)\n rst = wiki2rest(env, context, wiki)\n sys.stdout.write(rst)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"contrib/wiki2rst.py","file_name":"wiki2rst.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"564814729","text":"import json\n\nimport cherrypy\nimport redis\nimport os\n\nimport cherrypy\nimport time\nfrom jinja2 import Environment, FileSystemLoader\n\nfrom download_bhav_script import getBhav\n\nCUR_DIR = os.path.dirname(os.path.abspath(__file__))\nenv=Environment(loader=FileSystemLoader(CUR_DIR),\ntrim_blocks=True)\nfrom controllers.base import BaseController\n\n\nclass HomeController(BaseController):\n\n @cherrypy.expose()\n def index(self):\n redis_server = getBhav()\n bseobjs = redis_server.get('bhavcopy')\n bseobjtop = redis_server.get('bsetop')\n bsedatestr = redis_server.get('datestr')\n bseobjs = json.loads(bseobjs)\n bseobjtop = json.loads(bseobjtop)\n bsedatestr = time.strftime(\"%d %b %Y\",time.strptime(\n bsedatestr, \"%Y-%m-%d %H:%M:%S.%f\"\n )\n )\n return self.render_template(\n 'home/index.html',\n {\n 'list_header' : bsedatestr,\n 'bseobjs' : bseobjs,\n 'bseobjtop' : bseobjtop,\n 'site_title' : \"Stock list\"\n }\n )\n\n","sub_path":"controllers/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"528100901","text":"########\n# Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# * See the License for the specific language governing permissions and\n# * limitations under the License.\n\nfrom contextlib import contextmanager\nimport subprocess\nimport json\nimport os\nimport shutil\nimport tempfile\nimport time\nimport urllib2\n\nimport fabric\nfrom influxdb import InfluxDBClient\nfrom pkg_resources import parse_version\n\nfrom cloudify_cli import constants as cli_constants\nfrom cloudify.workflows import local\n\nfrom cosmo_tester.framework.testenv import TestCase\nfrom cosmo_tester.framework.git_helper import clone\nfrom cosmo_tester.framework.util import create_rest_client, \\\n YamlPatcher, get_cfy\n\n\nBOOTSTRAP_REPO_URL = 'https://github.com/cloudify-cosmo/' \\\n 'cloudify-manager-blueprints.git'\n\nBOOTSTRAP_BRANCH = '3.4rc1'\n\nUPGRADE_REPO_URL = 'https://github.com/cloudify-cosmo/' \\\n 'cloudify-manager-blueprints.git'\nUPGRADE_BRANCH = 'master'\n\n\nclass BaseManagerUpgradeTest(TestCase):\n \"\"\"Base for manager upgrade tests, with methods for bootstrap/upgrade.\n\n When writing a manager upgrade test, inherit from this, and use the\n .prepare_manager, .upgrade_manager, .rollback_manager, etc. methods -\n but note that upgrade, rollback and other methods rely on state stored\n during the .prepare_manager method.\n\n For debugging purposes, we can skip bootstrapping the manager that will\n be used in the test, and use a pre-existing one: see the\n ._use_external_manager method\n \"\"\"\n\n @property\n def _use_external_manager(self):\n \"\"\"Check if the handler config has a valid upgrade_manager setting.\n\n To use a pre-bootstrapped manager for this test, handler configuration\n needs to contain a \"upgrade_manager\" key, referencing an object\n with the following keys: manager_key, agents_key (filepaths to the ssh\n keys), public_ip, private_ip.\n\n Only use this when working on the test itself.\n \"\"\"\n return 'upgrade_manager' in self.env.handler_configuration\n\n @contextmanager\n def _manager_fabric_env(self, **kwargs):\n \"\"\"Push a fabric context connecting to the manager.\n\n Inside this contextmanager, use fabric's methods to interact with\n the manager that was bootstrapped during the test.\n \"\"\"\n # Note that bootstrapping the manager is part of the test, so we can't\n # use the testenv manager - we can't use the self.manager_env_fabric\n # method.\n if self.upgrade_manager_ip is None:\n raise RuntimeError(\"Can't SSH to the manager before bootstrapping\")\n\n inputs = self.manager_inputs\n settings = {\n 'host_string': self.upgrade_manager_ip,\n 'user': inputs['ssh_user'],\n 'key_filename': inputs['ssh_key_filename'],\n # use keepalive to make sure fabric doesn't hang, when a connection\n # dies after a long period of inactivity (eg. running an upgrade)\n 'keepalive': 30,\n }\n settings.update(kwargs)\n with fabric.context_managers.settings(**settings):\n yield fabric.api\n\n def _bootstrap_local_env(self, workdir):\n storage = local.FileStorage(\n os.path.join(workdir, '.cloudify', 'bootstrap'))\n return local.load_env('manager', storage=storage)\n\n def _blueprint_rpm_versions(self, blueprint_path, inputs):\n \"\"\"RPM filenames that should be installed on the manager.\n\n Currently, only amqpinflux, restservice and mgmtworker are installed\n from RPMs during the bootstrap.\n \"\"\"\n env = local.init_env(\n blueprint_path,\n inputs=inputs,\n ignored_modules=cli_constants.IGNORED_LOCAL_WORKFLOW_MODULES)\n\n storage = env.storage\n\n amqp_influx_rpm = storage.get_node('amqp_influx')['properties'][\n 'amqpinflux_rpm_source_url']\n restservice_rpm = storage.get_node('rest_service')['properties'][\n 'rest_service_rpm_source_url']\n mgmtworker_rpm = storage.get_node('mgmt_worker')['properties'][\n 'management_worker_rpm_source_url']\n return {\n 'cloudify-amqp-influx': amqp_influx_rpm,\n 'cloudify-rest-service': restservice_rpm,\n 'cloudify-management-worker': mgmtworker_rpm\n }\n\n def _cloudify_rpm_versions(self):\n with self._manager_fabric_env() as fabric:\n return fabric.sudo('rpm -qa | grep cloudify')\n\n def check_rpm_versions(self, blueprint_path, inputs):\n \"\"\"Check if installed RPMs are the versions declared in the blueprint.\n\n Parse the blueprint to retrieve package RPM filenames, and verify\n that `rpm -qa` on the manager reports these exact versions.\n \"\"\"\n blueprint_rpms = self._blueprint_rpm_versions(blueprint_path, inputs)\n installed_rpms = self._cloudify_rpm_versions()\n for service_name, rpm_filename in blueprint_rpms.items():\n for line in installed_rpms.split('\\n'):\n line = line.strip()\n if line.startswith(service_name):\n self.assertIn(line.strip(), rpm_filename)\n\n def get_curr_version(self):\n version = self.rest_client.manager.get_version()['version']\n # Parse version does not handle 'm' version well.\n version = version.replace('m', 'a')\n return parse_version(version)\n\n def prepare_manager(self):\n # note that we're using a separate manager checkout, so we need to\n # create our own utils like cfy and the rest client, rather than use\n # the testenv ones\n self.cfy_workdir = tempfile.mkdtemp(prefix='manager-upgrade-')\n self.addCleanup(shutil.rmtree, self.cfy_workdir)\n self.manager_cfy = get_cfy()\n self.manager_inputs = self._get_bootstrap_inputs()\n\n if self._use_external_manager:\n upgrade_config = self.env.handler_configuration['upgrade_manager']\n self.upgrade_manager_ip = upgrade_config['public_ip']\n self.manager_private_ip = upgrade_config['private_ip']\n self.manager_cfy.use(self.upgrade_manager_ip)\n else:\n self.bootstrap_manager()\n\n self.rest_client = create_rest_client(self.upgrade_manager_ip)\n\n self.bootstrap_manager_version = self.get_curr_version()\n\n def _get_keys(self, prefix):\n if self._use_external_manager:\n upgrade_config = self.env.handler_configuration['upgrade_manager']\n return upgrade_config['manager_key'], upgrade_config['agents_key']\n else:\n ssh_key_filename = os.path.join(self.workdir, 'manager.key')\n self.addCleanup(self.env.handler.remove_keypair,\n prefix + '-manager-key')\n\n agent_key_path = os.path.join(self.workdir, 'agents.key')\n self.addCleanup(self.env.handler.remove_keypair,\n prefix + '-agents-key')\n return ssh_key_filename, agent_key_path\n\n def _get_bootstrap_inputs(self):\n prefix = self.test_id\n\n ssh_key_filename, agent_key_path = self._get_keys(prefix)\n\n return {\n 'keystone_username': self.env.keystone_username,\n 'keystone_password': self.env.keystone_password,\n 'keystone_tenant_name': self.env.keystone_tenant_name,\n 'keystone_url': self.env.keystone_url,\n 'region': self.env.region,\n 'flavor_id': self.env.medium_flavor_id,\n 'image_id': self.env.centos_7_image_id,\n\n 'ssh_user': self.env.centos_7_image_user,\n 'external_network_name': self.env.external_network_name,\n 'resources_prefix': 'test-upgrade-',\n\n 'manager_server_name': prefix + '-manager',\n\n # shared settings\n 'manager_public_key_name': prefix + '-manager-key',\n 'agent_public_key_name': prefix + '-agents-key',\n 'ssh_key_filename': ssh_key_filename,\n 'agent_private_key_path': agent_key_path,\n\n 'management_network_name': prefix + '-network',\n 'management_subnet_name': prefix + '-subnet',\n 'management_router': prefix + '-router',\n\n 'agents_user': '',\n\n # private settings\n 'manager_security_group_name': prefix + '-m-sg',\n 'agents_security_group_name': prefix + '-a-sg',\n 'manager_port_name': prefix + '-port',\n 'management_subnet_dns_nameservers': ['8.8.8.8', '8.8.4.4'],\n\n # we'll be using the openstack plugin to install a deployment.\n # We need to either upload the plugin (using the CLI or the REST\n # client), or install a compiler so that the plugin can be\n # installed from source on the manager.\n 'install_python_compilers': True\n }\n\n def get_bootstrap_blueprint(self):\n manager_repo_dir = tempfile.mkdtemp(prefix='manager-upgrade-')\n self.addCleanup(shutil.rmtree, manager_repo_dir)\n manager_repo = clone(BOOTSTRAP_REPO_URL,\n manager_repo_dir,\n branch=BOOTSTRAP_BRANCH)\n yaml_path = manager_repo / 'openstack-manager-blueprint.yaml'\n\n # allow the ports that we're going to connect to from the tests,\n # when doing checks\n for port in [8086, 9200, 9900]:\n secgroup_cfg = [{\n 'port_range_min': port,\n 'port_range_max': port,\n 'remote_ip_prefix': '0.0.0.0/0'\n }]\n secgroup_cfg_path = 'node_templates.management_security_group' \\\n '.properties.rules'\n with YamlPatcher(yaml_path) as patch:\n patch.append_value(secgroup_cfg_path, secgroup_cfg)\n\n return yaml_path\n\n def _load_private_ip_from_env(self, workdir):\n env = self._bootstrap_local_env(workdir)\n return env.outputs()['private_ip']\n\n def _load_public_ip_from_env(self, workdir):\n env = self._bootstrap_local_env(workdir)\n return env.outputs()['manager_ip']\n\n def bootstrap_manager(self):\n self.bootstrap_blueprint = self.get_bootstrap_blueprint()\n inputs_path = self.get_inputs_in_temp_file(\n self.manager_inputs, self._testMethodName)\n\n try:\n bootstrap_cli_env = tempfile.mkdtemp()\n # create bootstrap venv\n create_venv_cmd = 'virtualenv {0}'.format(bootstrap_cli_env)\n self._execute_command(create_venv_cmd.split())\n # install cli matching the bootstrap manager version\n py_bin_path = os.path.join(bootstrap_cli_env, 'bin')\n install_cli_cmd = '{0}/pip install cloudify=={1}' \\\n .format(py_bin_path, BOOTSTRAP_BRANCH)\n self._execute_command(install_cli_cmd.split())\n # init temp workdir\n cfy_init_cmd = '{0}/cfy init -r'.format(py_bin_path)\n\n self._execute_command(cfy_init_cmd.split(), cwd=self.cfy_workdir)\n # execute bootstrap\n bootstrap_cmd = '{0}/cfy bootstrap {1} -i {2} --install-plugins'\\\n .format(py_bin_path, self.bootstrap_blueprint, inputs_path)\n self._execute_command(bootstrap_cmd.split(), cwd=self.cfy_workdir)\n\n self.upgrade_manager_ip = self._load_public_ip_from_env(\n self.cfy_workdir)\n self.manager_private_ip = self._load_private_ip_from_env(\n self.cfy_workdir)\n self.manager_cfy.use(self.upgrade_manager_ip)\n finally:\n if os.path.isdir(bootstrap_cli_env):\n shutil.rmtree(bootstrap_cli_env, ignore_errors=True)\n\n def _execute_command(self, command, cwd=None):\n process = subprocess.Popen(command, cwd=cwd, stdout=subprocess.PIPE)\n\n while process.poll() is None:\n line = process.stdout.readline()\n self.logger.info(line)\n self.logger.info(process.stdout.read())\n\n def deploy_hello_world(self, prefix=''):\n \"\"\"Install the hello world app.\"\"\"\n blueprint_id = prefix + self.test_id\n deployment_id = prefix + self.test_id\n hello_repo_dir = tempfile.mkdtemp(prefix='manager-upgrade-')\n hello_repo_path = clone(\n 'https://github.com/cloudify-cosmo/'\n 'cloudify-hello-world-example.git',\n hello_repo_dir\n )\n self.addCleanup(shutil.rmtree, hello_repo_dir)\n hello_blueprint_path = hello_repo_path / 'blueprint.yaml'\n self.cfy.blueprints.upload(\n hello_blueprint_path,\n blueprint_id=blueprint_id\n )\n\n inputs = {\n 'agent_user': self.env.ubuntu_image_user,\n 'image': self.env.ubuntu_trusty_image_name,\n 'flavor': self.env.flavor_name\n }\n inputs = self.get_inputs_in_temp_file(inputs, deployment_id)\n self.manager_cfy.deployments.create(\n deployment_id,\n blueprint_id=blueprint_id,\n inputs=inputs\n )\n\n self.manager_cfy.executions.start(\n 'install',\n deployment_id=deployment_id\n )\n return deployment_id\n\n def get_upgrade_blueprint(self):\n \"\"\"Path to the blueprint using for upgrading the manager.\n\n Note that upgrade uses a simple blueprint, even though the manager\n was installed using the openstack blueprint. Upgrade does not need to\n use the same blueprint.\n \"\"\"\n repo_dir = tempfile.mkdtemp(prefix='manager-upgrade-')\n self.addCleanup(shutil.rmtree, repo_dir)\n upgrade_blueprint_path = clone(UPGRADE_REPO_URL,\n repo_dir,\n branch=UPGRADE_BRANCH)\n\n return upgrade_blueprint_path / 'simple-manager-blueprint.yaml'\n\n def upgrade_manager(self, blueprint=None, inputs=None):\n self.upgrade_blueprint = blueprint or self.get_upgrade_blueprint()\n if not blueprint:\n # we're changing one of the ES inputs -\n # make sure we also re-install ES\n with YamlPatcher(self.upgrade_blueprint) as patch:\n patch.set_value(\n ('node_templates.elasticsearch.properties'\n '.use_existing_on_upgrade'),\n False)\n\n self.upgrade_inputs = inputs or {\n 'private_ip': self.manager_private_ip,\n 'public_ip': self.upgrade_manager_ip,\n 'ssh_key_filename': self.manager_inputs['ssh_key_filename'],\n 'ssh_user': self.manager_inputs['ssh_user'],\n 'ssh_port': 22,\n 'elasticsearch_endpoint_port': 9900\n }\n upgrade_inputs_file = self.get_inputs_in_temp_file(\n self.upgrade_inputs,\n self._testMethodName\n )\n\n with self.maintenance_mode():\n self.manager_cfy.upgrade(\n self.upgrade_blueprint,\n inputs=upgrade_inputs_file,\n install_plugins=self.env.install_plugins\n )\n\n def post_upgrade_checks(self, preupgrade_deployment_id):\n \"\"\"To check if the upgrade succeeded:\n - fire a request to the REST service\n - check that elasticsearch is listening on the changed port\n - check that the pre-existing deployment still reports to influxdb\n - install a new deployment, check that it reports to influxdb,\n and uninstall it: to check that the manager still allows\n creating, installing and uninstalling deployments correctly\n \"\"\"\n upgrade_manager_version = self.get_curr_version()\n self.assertGreaterEqual(upgrade_manager_version,\n self.bootstrap_manager_version)\n self.check_rpm_versions(self.upgrade_blueprint, self.upgrade_inputs)\n\n self.rest_client.blueprints.list()\n self.check_elasticsearch(self.upgrade_manager_ip, 9900)\n self.check_influx(preupgrade_deployment_id)\n\n postupgrade_deployment_id = self.deploy_hello_world('post-')\n self.check_influx(postupgrade_deployment_id)\n self.uninstall_deployment(postupgrade_deployment_id)\n\n def check_influx(self, deployment_id):\n \"\"\"Check that the deployment_id continues to report metrics.\n\n Look at the last 5 seconds worth of metrics. To avoid race conditions\n (running this check before the deployment even had a chance to report\n any metrics), first wait 5 seconds to allow some metrics to be\n gathered.\n \"\"\"\n # TODO influx config should be pulled from props?\n time.sleep(5)\n influx_client = InfluxDBClient(self.upgrade_manager_ip, 8086,\n 'root', 'root', 'cloudify')\n try:\n result = influx_client.query('select * from /^{0}\\./i '\n 'where time > now() - 5s'\n .format(deployment_id))\n except NameError as e:\n self.fail('monitoring events list for deployment with ID {0} were'\n ' not found on influxDB. error is: {1}'\n .format(deployment_id, e))\n\n self.assertTrue(len(result) > 0)\n\n def check_elasticsearch(self, host, port):\n \"\"\"Check that elasticsearch is listening on the given host:port.\n\n This is used for checking if the ES port changed correctly during\n the upgrade.\n \"\"\"\n try:\n response = urllib2.urlopen('http://{0}:{1}'.format(\n self.upgrade_manager_ip, port))\n response = json.load(response)\n if response['status'] != 200:\n raise ValueError('Incorrect status {0}'.format(\n response['status']))\n except (ValueError, urllib2.URLError):\n self.fail('elasticsearch isnt listening on the changed port')\n\n def uninstall_deployment(self, deployment_id):\n self.manager_cfy.executions.start(\n 'uninstall',\n deployment_id=deployment_id\n )\n\n def rollback_manager(self, blueprint=None, inputs=None):\n blueprint = blueprint or self.upgrade_blueprint\n rollback_inputs = inputs or {\n 'private_ip': self.manager_private_ip,\n 'public_ip': self.upgrade_manager_ip,\n 'ssh_key_filename': self.manager_inputs['ssh_key_filename'],\n 'ssh_port': 22,\n 'ssh_user': self.manager_inputs['ssh_user']\n }\n rollback_inputs_file = self.get_inputs_in_temp_file(\n rollback_inputs,\n self._testMethodName\n )\n\n with self.maintenance_mode():\n self.manager_cfy.rollback(blueprint, inputs=rollback_inputs_file)\n\n def post_rollback_checks(self, preupgrade_deployment_id):\n rollback_manager_version = self.get_curr_version()\n self.assertEqual(rollback_manager_version,\n self.bootstrap_manager_version)\n self.check_rpm_versions(self.bootstrap_blueprint, self.manager_inputs)\n\n self.rest_client.blueprints.list()\n self.check_elasticsearch(self.upgrade_manager_ip, 9200)\n self.check_influx(preupgrade_deployment_id)\n\n def teardown_manager(self):\n if not self._use_external_manager:\n self.manager_cfy.teardown(ignore_deployments=True)\n\n # a failed copy command on centos outputs an error with illegal chars.\n # replacing them in order to be able to print the output, and find\n # a required string in the error message.\n def replace_illegal_chars(self, s):\n return s.replace(u'\\u2019', \"'\").replace(u'\\u2018', \"'\")\n","sub_path":"cosmo_tester/test_suites/test_manager_upgrade/manager_upgrade_base.py","file_name":"manager_upgrade_base.py","file_ext":"py","file_size_in_byte":20190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"370472287","text":"import odoo\nfrom odoo import http\nfrom odoo import fields\nfrom odoo.http import request\nfrom odoo.addons.clarico_shop.controllers.main import claricoShop\n\n\nclass claricoPriceFilter(claricoShop):\n \n def _get_search_domain(self, search, category, attrib_values, price_vals = {}): \n domain = request.website.sale_product_domain()\n if search:\n for srch in search.split(\" \"):\n domain += [\n '|', '|', '|','|', ('name', 'ilike', srch), ('description', 'ilike', srch),\n ('description_sale', 'ilike', srch), ('product_variant_ids.default_code', 'ilike', srch),\n ('brand_ept_id.name','ilike', srch)]\n if category:\n domain += [('public_categ_ids', 'child_of', int(category))]\n \n if price_vals :\n domain += [('list_price','>=',price_vals.get('min_val')),('list_price','<=',price_vals.get('max_val'))]\n \n if attrib_values:\n attrib = None\n ids = []\n for value in attrib_values:\n if value[0] == 0 :\n ids.append(value[1])\n domain += [('brand_ept_id.id', 'in', ids)]\n elif not attrib:\n attrib = value[0]\n ids.append(value[1])\n elif value[0] == attrib:\n ids.append(value[1])\n else:\n domain += [('attribute_line_ids.value_ids', 'in', ids)]\n attrib = value[0]\n ids = [value[1]]\n if attrib:\n domain += [('attribute_line_ids.value_ids', 'in', ids)]\n return domain\n \n @http.route([\n '/shop',\n '/shop/page/',\n '/shop/category/',\n '/shop/category//page/'\n ], type='http', auth=\"public\", website=True)\n def shop(self, page=0, category=None, search='', ppg=False, **post):\n request.cr.execute( 'select min(list_price),max(list_price) from product_template where sale_ok=True and active=True and website_published=True')\n min_max_vals = request.cr.fetchall()\n min_val = min_max_vals[0][0] or 0\n if int(min_val) == 0:\n min_val = 1\n max_val = min_max_vals[0][1] or 1\n \n custom_min_val = custom_max_val = 0\n product_price_search_vals = {}\n if request.httprequest.args.getlist('min_val') and request.httprequest.args.getlist('max_val'):\n custom_min_val = float(request.httprequest.args.getlist('min_val')[0])\n custom_max_val = float(request.httprequest.args.getlist('max_val')[0])\n if custom_min_val > custom_max_val:\n tmp = custom_max_val\n custom_max_val = custom_min_val\n custom_min_val = tmp\n product_price_search_vals.update({'min_val':custom_min_val,'max_val':custom_max_val})\n post.update({'attrib_price':'%s-%s'%(custom_min_val,custom_max_val)})\n \n else :\n post.update({'attrib_price':'%s-%s'%(min_val,max_val)})\n \n \n \n response = super(claricoPriceFilter, self).shop(page=page, category=category, search=search,ppg=ppg, **post)\n response.qcontext['custom_min_val'] = custom_min_val\n response.qcontext['custom_max_val'] = custom_max_val\n response.qcontext['min_val'] = min_val\n response.qcontext['max_val'] = max_val\n return response \n \n \n \n \n","sub_path":"clarico_pricefilter/controller/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"276229582","text":"\"\"\"Utils functions that might be used into any module.\"\"\"\n\n# stdlib\nfrom functools import lru_cache\nimport operator\nfrom typing import Any\nfrom typing import Dict\nfrom typing import Tuple\nfrom typing import cast\n\n# third party\nimport numpy as np\n\nRING_SIZE_TO_TYPE: Dict[int, np.dtype] = {\n 2 ** 32: np.dtype(\"int32\"),\n 2: np.dtype(\"bool\"), # Special case: need to do reconstruct and share with XOR\n}\n\nTYPE_TO_RING_SIZE: Dict[np.dtype, int] = {v: k for k, v in RING_SIZE_TO_TYPE.items()}\n\n\ndef ispointer(obj: Any) -> bool:\n \"\"\"Check if a given obj is a pointer (is a remote object).\n Args:\n obj (Any): Object.\n Returns:\n bool: True (if pointer) or False (if not).\n \"\"\"\n if type(obj).__name__.endswith(\"Pointer\") and hasattr(obj, \"id_at_location\"):\n return True\n return False\n\n\n@lru_cache()\ndef get_nr_bits(ring_size: int) -> int:\n \"\"\"Get number of bits.\n\n Args:\n ring_size (int): Ring Size.\n\n Returns:\n int: Bit length.\n \"\"\"\n return (ring_size - 1).bit_length()\n\n\n@lru_cache(maxsize=128)\ndef get_shape(\n op_str: str,\n x_shape: Tuple[int],\n y_shape: Tuple[int],\n) -> Tuple[int]:\n \"\"\"Get the shape of apply an operation on two values\n\n Args:\n op_str (str): the operation to be applied\n x_shape (Tuple[int]): the shape of op1\n y_shape (Tuple[int]): the shape of op2\n\n Returns:\n The shape of the result\n \"\"\"\n op = getattr(operator, op_str)\n res = op(np.empty(x_shape), np.empty(y_shape)).shape\n res = cast(Tuple[int], res)\n return tuple(res) # type: ignore\n\n\n@lru_cache(maxsize=128)\ndef get_ring_size(\n x_ring_size: int,\n y_ring_size: int,\n) -> int:\n \"\"\"Get the ring_size of apply an operation on two values\n\n Args:\n x_ring_size (int): the ring size of op1\n y_ring_size (int): the ring size of op2\n\n Returns:\n The ring size of the result\n \"\"\"\n if x_ring_size != y_ring_size:\n raise ValueError(\n \"Expected the same ring size for x and y ({x_ring_size} vs {y_ring_size})\"\n )\n\n return x_ring_size\n","sub_path":"packages/syft/src/syft/core/tensor/smpc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"509780382","text":"# Copyright 2018 Regents of the University of Colorado. All Rights Reserved.\n# Released under the MIT license.\n# This software was developed at the University of Colorado's Laboratory for Atmospheric and Space Physics.\n# Verify current version before use at: https://github.com/MAVENSDC/Pytplot\n\nimport pytplot\n\ndef interp_nan(tvar, new_tvar='tvar_interp_nan', s_limit=0):\n \"\"\"\n Interpolates the tplot variable through NaNs in the data.\n\n .. note::\n This analysis routine assumes the data is no more than 2 dimensions. If there are more, they may become flattened!\n\n Parameters:\n tvar : str\n Name of tplot variable.\n s_limit : int or float, optional\n The maximum size of the gap in seconds to not interpolate over. I.e. if there are too many NaNs in a row, leave them there.\n new_tvar : str\n Name of new tvar for added data. If not set, then a name is made up.\n\n Returns:\n None\n\n Examples:\n >>> # Interpolate through the np.NaN values\n >>> pytplot.store_data('e', data={'x':[2,5,8,11,14,17,21], 'y':[[np.nan,1,1],[np.nan,2,3],[4,np.nan,47],[4,np.nan,5],[5,5,99],[6,6,25],[7,np.nan,-5]]})\n >>> pytplot.interp_nan('e','e_nonan',s_limit=5)\n >>> print(pytplot.data_quants['e_nonan'].values)\n \"\"\"\n\n if new_tvar=='tvar_interp_nan':\n newtvar = tvar +\"_interp_nan\"\n\n if 'spec_bins' in pytplot.data_quants[tvar].coords:\n d, s = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(tvar)\n else:\n d = pytplot.tplot_utilities.convert_tplotxarray_to_pandas_dataframe(tvar)\n s = None\n tv1 = d.values.copy()\n tv1 = tv1.astype(float)\n cadence = tv1.index[1] - tv1.index[0]\n n_nans = int(round(s_limit/cadence))\n if s_limit == 0:\n tv1 = tv1.interpolate(method='linear')\n else:\n tv1 = tv1.interpolate(method='linear',limit=n_nans,limit_direction='both') \n tv1 = tv1.astype(object)\n\n if s is not None:\n pytplot.store_data(newtvar,data = {'x':tv1.index,'y':tv1, 'v': pytplot.data_quants[tvar].coords['spec_bins'].values})\n else:\n pytplot.store_data(newtvar, data={'x': tv1.index, 'y': tv1})\n return","sub_path":"pytplot/tplot_math/interp_nan.py","file_name":"interp_nan.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"118181846","text":"\"\"\"CompMusic Hindustani Rhythm Dataset Loader\n\n.. admonition:: Dataset Info\n :class: dropdown\n\n CompMusic Hindustani Rhythm Dataset is a rhythm annotated test corpus for automatic rhythm analysis tasks in Hindustani Music. \n The collection consists of audio excerpts from the CompMusic Hindustani research corpus, manually annotated time aligned markers \n indicating the progression through the taal cycle, and the associated taal related metadata. A brief description of the dataset\n is provided below.\n\n For a brief overview and audio examples of taals in Hindustani music, please see: http://compmusic.upf.edu/examples-taal-hindustani\n\n The dataset contains the following data:\n\n **AUDIO:** The pieces are chosen from the CompMusic Hindustani music collection. The pieces were chosen in four popular taals of Hindustani music,\n which encompasses a majority of Hindustani khyal music. The pieces were chosen include a mix of vocal and instrumental recordings, new and old\n recordings, and to span three lays. For each taal, there are pieces in dhrut (fast), madhya (medium) and vilambit (slow) lays (tempo class). All\n pieces have Tabla as the percussion accompaniment. The excerpts are two minutes long. Each piece is uniquely identified using the MBID of the recording.\n The pieces are stereo, 160 kbps, mp3 files sampled at 44.1 kHz. The audio is also available as wav files for experiments.\n\n **SAM, VIBHAAG AND THE MAATRAS:** The primary annotations are audio synchronized time-stamps indicating the different metrical positions in the taal cycle.\n The sam and matras of the cycle are annotated. The annotations were created using Sonic Visualizer by tapping to music and manually correcting the taps. \n Each annotation has a time-stamp and an associated numeric label that indicates the position of the beat marker in the taala cycle. The annotations and the\n associated metadata have been verified for correctness and completeness by a professional Hindustani musician and musicologist. The long thick lines show \n vibhaag boundaries. The numerals indicate the matra number in cycle. In each case, the sam (the start of the cycle, analogous to the downbeat) are indicated\n using the numeral 1.\n\n **METADATA:** For each excerpt, the taal and the lay of the piece are recorded. Each excerpt can be uniquely identified and located with the MBID of the\n recording, and the relative start and end times of the excerpt within the whole recording. A separate 5 digit taal based unique ID is also provided for each\n excerpt as a double check. The artist, release, the lead instrument, and the raag of the piece are additional editorial metadata obtained from the release.\n There are optional comments on audio quality and annotation specifics.\n\n The dataset consists of excerpts with a wide tempo range from 10 MPM (matras per minute) to 370 MPM. To study any effects of the tempo class, the full dataset\n (HMDf) is also divided into two other subsets - the long cycle subset (HMDl) consisting of vilambit (slow) pieces with a median tempo between 10-60 MPM, and the\n short cycle subset (HMDs) with madhyalay (medium, 60-150 MPM) and the drut lay (fast, 150+ MPM).\n\n **Possible uses of the dataset:** Possible tasks where the dataset can be used include taal, sama and beat tracking, tempo estimation and tracking, taal recognition,\n rhythm based segmentation of musical audio, audio to score/lyrics alignment, and rhythmic pattern discovery.\n\n **Dataset organization:** The dataset consists of audio, annotations, an accompanying spreadsheet providing additional metadata, a MAT-file that has identical\n information as the spreadsheet, and a dataset description document.\n\n The annotations files of this dataset are shared with the following license: Creative Commons Attribution Non Commercial Share Alike 4.0 International\n\n\"\"\"\n\nimport os\nimport csv\nimport logging\nimport librosa\nimport numpy as np\n\nfrom mirdata import annotations, core, io, jams_utils\nfrom smart_open import open\n\n\ntry:\n from openpyxl import load_workbook as get_xlxs\nexcept ImportError:\n logging.error(\n \"In order to use CompMusic Hindustani Music Rhythm you must have openpyxl installed. \"\n \"Please reinstall mirdata using `pip install 'mirdata[compmusic_hindustani_rhythm]'\"\n )\n raise\n\nBIBTEX = \"\"\"\n@inproceedings{Srinivasamurthy2016,\n author = {Srinivasamurthy, Ajay and Holzapfel, Andre and Cemgil, Ali and Serra, Xavier},\n year = {2016},\n month = {03},\n pages = {76-80},\n title = {A generalized Bayesian model for tracking long metrical cycles in acoustic music signals},\n doi = {10.1109/ICASSP.2016.7471640}\n}\n\"\"\"\n\nINDEXES = {\n \"default\": \"1.0\",\n \"test\": \"1.0\",\n \"1.0\": core.Index(filename=\"compmusic_hindustani_rhythm_full_index_1.0.json\"),\n}\n\nREMOTES = None\n\nLICENSE_INFO = (\n \"Creative Commons Attribution Non Commercial Share Alike 4.0 International.\"\n)\n\nDOWNLOAD_INFO = \"\"\"The files of this dataset are shared under request. Please go to: https://zenodo.org/record/1264742 and request access, stating\n the research-related use you will give to the dataset. Once the access is granted (it may take, at most, one day or two), please download \n the dataset with the provided Zenodo link and uncompress and store the datasets to a desired location, and use such location to initialize the \n dataset as follows: compmusic_hindustani_rhythm = mirdata.initialize(\"compmusic_hindustani_rhythm\", data_home=\"/path/to/home/folder/of/dataset\").\n \"\"\"\n\n\nclass Track(core.Track):\n \"\"\"CompMusic Hindustani Music Rhythm class\n\n Args:\n track_id (str): track id of the track\n data_home (str): Local path where the dataset is stored. default=None\n If `None`, looks for the data in the default directory, `~/mir_datasets`\n\n Attributes:\n audio_path (str): path to audio file\n beats_path (srt): path to beats file\n meter_path (srt): path to meter file\n\n Cached Properties:\n beats (BeatData): beats annotation\n meter (string): meter annotation\n mbid (string): MusicBrainz ID\n name (string): name of the recording in the dataset\n artist (string): artists name\n release (string): release name\n lead_instrument_code (string): code for the load instrument\n taala (string): taala annotation\n raaga (string): raaga annotation\n laya (string): laya annotation\n num_of_beats (int): number of beats in annotation\n num_of_samas (int): number of samas in annotation\n median_matra_period (float): median matra per period\n median_matras_per_min (float): median matras per minute\n median_ISI (float): median ISI\n median_avarts_per_min (float): median avarts per minute\n \"\"\"\n\n def __init__(\n self,\n track_id,\n data_home,\n dataset_name,\n index,\n metadata,\n ):\n super().__init__(\n track_id,\n data_home,\n dataset_name,\n index,\n metadata,\n )\n\n # Audio path\n self.audio_path = self.get_path(\"audio\")\n\n # Annotations paths\n self.beats_path = self.get_path(\"beats\")\n self.meter_path = self.get_path(\"meter\")\n\n @core.cached_property\n def beats(self):\n return load_beats(self.beats_path)\n\n @core.cached_property\n def meter(self):\n return load_meter(self.meter_path)\n\n @core.cached_property\n def mbid(self):\n return self._track_metadata.get(\"mbid\")\n\n @core.cached_property\n def name(self):\n return self._track_metadata.get(\"name\")\n\n @core.cached_property\n def artist(self):\n return self._track_metadata.get(\"artist\")\n\n @core.cached_property\n def release(self):\n return self._track_metadata.get(\"release\")\n\n @core.cached_property\n def lead_instrument_code(self):\n return self._track_metadata.get(\"lead_instrument_code\")\n\n @core.cached_property\n def taala(self):\n return self._track_metadata.get(\"taala\")\n\n @core.cached_property\n def raaga(self):\n return self._track_metadata.get(\"raaga\")\n\n @core.cached_property\n def laya(self):\n return self._track_metadata.get(\"laya\")\n\n @core.cached_property\n def num_of_beats(self):\n return self._track_metadata.get(\"num_of_beats\")\n\n @core.cached_property\n def num_of_samas(self):\n return self._track_metadata.get(\"num_of_samas\")\n\n @core.cached_property\n def median_matra_period(self):\n return self._track_metadata.get(\"median_matra_period\")\n\n @core.cached_property\n def median_matras_per_min(self):\n return self._track_metadata.get(\"median_matras_per_min\")\n\n @core.cached_property\n def median_ISI(self):\n return self._track_metadata.get(\"median_ISI\")\n\n @core.cached_property\n def median_avarts_per_min(self):\n return self._track_metadata.get(\"median_avarts_per_min\")\n\n @property\n def audio(self):\n \"\"\"The track's audio\n\n Returns:\n * np.ndarray - audio signal\n * float - sample rate\n\n \"\"\"\n return load_audio(self.audio_path)\n\n def to_jams(self):\n \"\"\"Get the track's data in jams format\n\n Returns:\n jams.JAMS: the track's data in jams format\n\n \"\"\"\n return jams_utils.jams_converter(\n audio_path=self.audio_path,\n beat_data=[(self.beats, \"beats\")],\n metadata={\n \"meter\": self.meter,\n \"mbid\": self.mbid,\n \"name\": self.name,\n \"artist\": self.artist,\n \"release\": self.release,\n \"lead_instrument_code\": self.lead_instrument_code,\n \"taala\": self.taala,\n \"raaga\": self.raaga,\n \"laya\": self.laya,\n \"num_of_beats\": self.num_of_beats,\n \"num_of_samas\": self.num_of_samas,\n \"median_matra_period\": self.median_matra_period,\n \"median_matras_per_min\": self.median_matras_per_min,\n \"median_ISI\": self.median_ISI,\n \"median_avarts_per_min\": self.median_avarts_per_min,\n },\n )\n\n\n# no decorator here because of https://github.com/librosa/librosa/issues/1267\ndef load_audio(audio_path):\n \"\"\"Load an audio file.\n\n Args:\n audio_path (str): path to audio file\n\n Returns:\n * np.ndarray - the mono audio signal\n * float - The sample rate of the audio file\n\n \"\"\"\n if audio_path is None:\n return None\n return librosa.load(audio_path, sr=44100, mono=False)\n\n\n@io.coerce_to_string_io\ndef load_beats(fhandle):\n \"\"\"Load beats\n\n Args:\n fhandle (str or file-like): Local path where the beats annotation is stored.\n\n Returns:\n BeatData: beat annotations\n\n \"\"\"\n beat_times = []\n beat_positions = []\n\n reader = csv.reader(fhandle, delimiter=\",\")\n for line in reader:\n beat_times.append(float(line[0]))\n beat_positions.append(int(line[1]))\n\n if not beat_times or beat_times[0] == -1.0:\n return None\n\n return annotations.BeatData(\n np.array(beat_times), \"s\", np.array(beat_positions), \"bar_index\"\n )\n\n\n@io.coerce_to_string_io\ndef load_meter(fhandle):\n \"\"\"Load meter\n\n Args:\n fhandle (str or file-like): Local path where the meter annotation is stored.\n\n Returns:\n float: meter annotation\n\n \"\"\"\n reader = csv.reader(fhandle, delimiter=\",\")\n return next(reader)[0]\n\n\n@core.docstring_inherit(core.Dataset)\nclass Dataset(core.Dataset):\n \"\"\"\n The compmusic_hindustani_rhythm dataset\n\n \"\"\"\n\n def __init__(self, data_home=None, version=\"default\"):\n super().__init__(\n data_home,\n version,\n name=\"compmusic_hindustani_rhythm\",\n track_class=Track,\n bibtex=BIBTEX,\n indexes=INDEXES,\n remotes=REMOTES,\n license_info=LICENSE_INFO,\n download_info=DOWNLOAD_INFO,\n )\n\n @core.cached_property\n def _metadata(self):\n metadata_path = os.path.join(self.data_home, \"HMR_1.0\", \"HMDf.xlsx\")\n\n metadata = {}\n try:\n with open(metadata_path, \"rb\") as fhandle:\n reader = get_xlxs(fhandle)\n reade = reader[\"HMDf\"]\n rows = 0\n\n # Get actual number of rows\n for _, row in enumerate(reade, 1):\n if not all(col.value is None for col in row):\n rows += 1\n\n # Get actual columns\n columns = []\n for cell in reade[1]:\n if cell.value:\n columns.append(cell.value)\n\n for row in range(2, rows + 1):\n metadata[str(reade.cell(row, 1).value)] = {\n \"mbid\": reade.cell(row, 3).value,\n \"name\": reade.cell(row, 4).value,\n \"artist\": reade.cell(row, 5).value,\n \"release\": reade.cell(row, 6).value,\n \"lead_instrument_code\": reade.cell(row, 7).value,\n \"raaga\": reade.cell(row, 8).value,\n \"taala\": reade.cell(row, 9).value,\n \"laya\": reade.cell(row, 10).value,\n \"num_of_beats\": int(reade.cell(row, 13).value),\n \"num_of_samas\": int(reade.cell(row, 14).value),\n \"median_matra_period\": float(reade.cell(row, 16).value),\n \"median_matras_per_min\": round(\n 60 / float(reade.cell(row, 16).value), 2\n ),\n \"median_ISI\": float(reade.cell(row, 16).value) * 16,\n \"median_avarts_per_min\": round(\n 60 / (float(reade.cell(row, 16).value) * 16), 2\n ),\n }\n\n except FileNotFoundError:\n raise FileNotFoundError(\"Metadata not found. Did you run .download()?\")\n\n return metadata\n","sub_path":"mirdata/datasets/compmusic_hindustani_rhythm.py","file_name":"compmusic_hindustani_rhythm.py","file_ext":"py","file_size_in_byte":14215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"335104774","text":"import json\r\nimport random\r\nimport re\r\n\r\nimport jsonpath\r\nimport jieba\r\nfrom zhon.hanzi import punctuation\r\nimport jieba.analyse\r\n\r\ndef stopwordslist(filepath):\r\n stopwords = [line.strip() for line in open(\r\n filepath, 'r', encoding='utf-8').readlines()]\r\n return stopwords\r\nstopwords = stopwordslist('./resources/stop.txt')\r\njieba.load_userdict(\"./resources/userdict.txt\")\r\n\r\nfou=open('./resources/xjpnews_fasttext.txt','w',encoding='utf-8')\r\n\r\nf=open('./resources/data.txt',encoding='utf-8')\r\njs=json.load(f)\r\nf.close()\r\njsonp=jsonpath.jsonpath(js,\"$..news.*\")\r\nrandom.shuffle(jsonp)\r\n\r\n\r\n\r\nfor el in jsonp:\r\n print(el['cat'],el['title'])\r\n # 标题\r\n line = el['title'].strip() + \" \" + el['detail'].strip()\r\n line = re.sub('[a-zA-Z0-9]', '', line)\r\n line = re.sub('\\n', '', line)\r\n linelist = jieba.cut(re.sub(r\"[%s]+\" % punctuation, \"\", line), cut_all=False)\r\n # linelist = jieba.analyse.extract_tags(re.sub(r\"[%s]+\" % punctuation, \"\", line)) #不应该 用这个,有ngram,有局部顺序\r\n outline = \"\"\r\n for word in linelist:\r\n if word not in stopwords:\r\n if word != '\\t' or word != '\\n':\r\n outline += word\r\n outline += \" \"\r\n outline = \"\\t__label__\" + el['cat'] + \" \" + outline + \"\\t\\n\"\r\n fou.write(outline)\r\nfou.close()","sub_path":"jsonParser.py","file_name":"jsonParser.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"37531676","text":"#-*-coding:utf8;-*-\n#qpy:3\n#qpy:console\n\ntry:\n import androidhelper as android\nexcept ImportError:\n import android\n\ndroid = android.Android()\n\nimport signal\nfrom math import ceil\n\ndef stt(*args, **kwargs):\n #t = kwargs.get(\"timeout\", 5.5)\n #if t is not None:\n # signal.signal(signal.SIGALRM, _handle_timeout)\n # signal.alarm(ceil(t))\n try: r = droid.recognizeSpeech(NAME).result\n except TimeoutError: return\n \n #signal.alarm(0)\n droid.makeToast(\"Du: \"+(r if r is not None else \"Nichts.\"))\n return r\n\ndef tts(*text, **kwargs):\n delay = kwargs.get(\"delay\",1)\n for phrase in text:\n droid.ttsSpeak(phrase)\n droid.makeToast(\"%s: %s\" % (NAME, phrase))\n time.sleep(delay)\n\nimport time\n\n\nNAME = \"S.E.A.S\"\nNAME_DESCRIPTION = \"die Spracherkennungs- und Automatisierungssoftware\"\n\nVERSION = \"0.1\"\n\nLOCALE_POINT_VERSION = \" Punkt \"\n\nNAME_FULL = \"%s, %s Version %s\" % (NAME, NAME_DESCRIPTION, VERSION.replace(\".\", LOCALE_POINT_VERSION))\n\ndef _handle_timeout(signum, frame):\n raise TimeoutError('')\n\nclass TimeoutError(Exception):\n pass","sub_path":"SEAS/speech.py","file_name":"speech.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"603620337","text":"\nfrom tkinter import *\nfrom sys import *\n\ndef almacenar():\n \"\"\"Almacena los datos ingresados\"\"\"\n #messageBox.showinfo(\"Mensaje de comprobacion\", \"Exportacion completada\")\n a = open('C:\\\\Windows\\\\CCM\\\\Inventory\\\\noidmifs\\\\archivo.txt', 'w')\n a.write(nombre_entry.get() + '\\n' + last_str.get() + '\\n' + id_entry.get())\n nombre_entry.delete(0, END)\n last_str.delete(0, END)\n id_entry.delete(0, END)\n a.close\n##############################\n\n\nroot = Tk()\nroot.title('Datos Fijos')\nroot.geometry(\"320x100\") #Tamaño de la ventana\n\n# row 1 : Placa\nnombre_label = Label(root,text=\"Placa Equipo :\")\nnombre_label.grid(row=1,column=1,sticky=N, padx=5)\nnombre_str = StringVar()\nnombre_entry = Entry(root,textvariable=nombre_str)\nnombre_entry.grid(row=1,column=2,sticky=N, padx=5)\n#Parametros de configuración\n#nombre_entry.place(x=150, y=10)\n\n#row 2 : Serial\nlast_label= Label(root,text=\"Serial Monitor : \")\nlast_label.grid(row=2,column=1)\nlast_str = StringVar()\nlast_entry = Entry(root,textvariable=last_str)\nlast_entry.grid(row=2,column=2)\n\n#row 3 : Identificación\nid_label = Label(root,text=\"Identificación de Responsable: \")\nid_label.grid(row=3,column=1)\nid_str = StringVar()\nid_entry = Entry(root,textvariable=id_str)\nid_entry.grid(row=3,column=2)\n\n#row 4 : end\nfinish = Button(root,text=\"Guardar\",command=almacenar) #relief=RAISED\nfinish.grid(row=5,column=2)\n\nroot.mainloop()\n","sub_path":"DatosFijos.py","file_name":"DatosFijos.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"490210974","text":"'''Write a python program to find if the given number is a perfect'''\n#cube or not\n# using guess and check algorithm\n\n# testcase 1\n# Input: 24389\n# Output: 24389 is a perfect cube\n\n# testcase 2\n# Input: 21950\n# Output: 21950 is not a perfect cube\ndef main():\n '''Enter a input this will displays is it perfect cube or not'''\n number = int(input())\n itr = 0\n while itr <= number:\n if itr**3 == number:\n flag = 0\n print(str(number) + \" is a perfect cube\")\n break\n else:\n flag = 1\n itr += 1\n if flag == 1:\n print(str(number)+\" is not a perfect cube\")\nif __name__ == \"__main__\":\n main()\n","sub_path":"Module 5/p1/perfect_cube.py","file_name":"perfect_cube.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"387402965","text":"\"\"\"Capture for variant counts.\"\"\"\nimport argparse, pandas\nfrom collections import defaultdict\nimport wxs_tools, capture_samples\nfrom enrich_tools import *\n\ndef main(args):\n \"\"\"When using WT, wt_status==wt\n else wt_status==nwt\n Only applies to the every test.\n \"\"\"\n only_naz_flag = args.just_naz == 'True'\n tgt_sample_count, use_samples = capture_samples.load_capture_sample_count(args.sampleFile, args.hist, args.pop, args.wt_status == 'wt')\n wxs_tools.dump_wxs(args.varFile, use_samples, args.var_or_sample_counting, args.used_tgt_vars,\n only_naz_flag, args.var_type, args.pop == 'every',\n args.out_file, args.out_pickle_pos, args.full_support_out)\n\nif __name__ == \"__main__\":\n desc = 'Cgi vs exac, var counts.'\n parser = argparse.ArgumentParser(description=desc)\n argLs = ('wt_status', 'just_naz', 'var_type', 'var_or_sample_counting',\n 'pop', 'hist', 'varFile', 'sampleFile',\n 'used_tgt_vars', 'out_file', 'out_pickle_pos',\n 'full_support_out')\n for param in argLs:\n parser.add_argument(param)\n args = parser.parse_args()\n main(args)\n","sub_path":"code/scripts/dump_capture.py","file_name":"dump_capture.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"421327010","text":"book = {}\nbook['tom'] = {\n 'name': 'tom',\n 'address': '1 red street, NY',\n 'phone': 98989898\n}\nbook['bob'] = {\n 'name': 'bob',\n 'address': '1 green street, NY',\n 'phone': 23424234\n}\n\nimport json\ns_obj=json.dumps(book)\nwith open(\"data.json\",\"w\") as f:\n f.write(s_obj)\nf.close()\n","sub_path":"Misc/json_objects_python/json_formatting.py","file_name":"json_formatting.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"503640813","text":"a=int(input())\r\nb=a\r\nrev=0\r\nrem=0\r\nwhile(a!=0):\r\n rem=a%10\r\n rev=rev*10+rem\r\n a=a//10\r\nprint(rev)\r\nc=str(b)\r\nprint(c[::-1])\r\n","sub_path":"reverse_num.py","file_name":"reverse_num.py","file_ext":"py","file_size_in_byte":134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"223029085","text":"#factors\n#Code by Shreyank #Github-https://github.com/Shreyankkarjigi\n#problem: Wap to display factors of a number\n#factors of number show all the numbers by which the number can be divided.\n\n\nn=int(input(\"enter number:\\n\"))\n\nfor i in range(1,n+1):\n if n%i==0:\n print(i)\n\n\n'''\noutput\nenter number:\n320\n1\n2\n4\n5\n8\n10\n16\n20\n32\n40\n64\n80\n160\n320\n'''","sub_path":"Basic programs/Factors of a number.py","file_name":"Factors of a number.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"601964168","text":"# -*- coding:utf-8 -*-\n__author__ = '张全亮'\nimport re\nimport random\nimport urllib3\nimport urllib.parse\nimport time\nimport asyncio\nimport aiohttp\n\nurllib3.disable_warnings()\nimport pymysql\nfrom logger import Logger\nfrom bs4 import BeautifulSoup\n\npymysql.install_as_MySQLdb()\n\n# TODO 需要提供goods_url(商品地址), pdduid(拼多多用户ID,可为手机号), accesstoken(websocket加载的token)\n\n\"\"\"\ngoods_url = 商品地址\ngoods_id = 商品ID\ngroup_id = 分组排序ID\nsku_id = 商品的属性ID,如衣服的尺码,颜色\ncookie = 需要登陆状态下的Cookie\naccesstoken = 支付认证的token\npdduid = 拼多多用户ID\norder_sn = 订单编号\n\"\"\"\n\nlogger = Logger()\n\n\"\"\"\ninput = 分组排序ID(group_id), 商品ID(goods_id), 商品属性ID(sku_id), 用户ID(pdduid), \n支付宝登陆成功认证的token(accesstoken), 地址ID(address_id)\noutput = 付款地址(pay_url)\n\"\"\"\n\n\nasync def pay(alipay, address_id, pdduid, accesstoken, sku_id, group_id, goods_id, order_number, session, headers):\n url = 'https://api.pinduoduo.com/order?pdduid={}'.format(pdduid)\n headers['Referer'] = 'https://mobile.yangkeduo.com/order_checkout.html?sku_id={}&group_id={}&goods_id={}&' \\\n 'goods_number={}'.format(sku_id, group_id, goods_id, order_number)\n headers['accesstoken'] = accesstoken\n json_str = {\n \"address_id\": address_id,\n \"goods\": [{\"sku_id\": sku_id, \"sku_number\": order_number, \"goods_id\": goods_id}],\n \"group_id\": group_id,\n \"duoduo_type\": 0,\n \"biz_type\": 0,\n \"source_channel\": -1,\n \"source_type\": 0,\n \"pay_app_id\": 38,\n \"app_id\": 9,\n \"is_app\": \"0\",\n \"version\": 1\n }\n\n # 循环请求,3次请求仍获取不到,则判断token失效\n order_sn = ''\n for i in range(3):\n response = await session.get(url, headers=headers, json=json_str)\n res_json = await response.json()\n if 'order_sn' in res_json:\n order_sn = res_json['order_sn']\n break\n elif 'error_code' in res_json and i == 2:\n return False, 'access_token错误, 请更新.'\n else:\n time.sleep(1)\n continue\n\n if alipay:\n logger.log('INFO', '订单:[{}]支付方式: 支付宝支付'.format(order_sn), 'pdd_spider', pdduid)\n url2 = 'https://api.pinduoduo.com/order/prepay?pdduid={}'.format(pdduid)\n t_data = {\n \"order_sn\": order_sn,\n \"app_id\": 9,\n \"return_url\": \"https://mobile.yangkeduo.com/alipay_callback.html?order_sn={}\".format(order_sn),\n \"version\": 2,\n \"attribute_fields\": {\"paid_times\": 0}\n }\n response2 = await session.get(url2, headers=headers, json=t_data)\n xiadan_json = await response2.json()\n gateway_url = xiadan_json['gateway_url']\n query = xiadan_json['query']\n a = urllib.parse.urlencode(query)\n dingdan_url = gateway_url + '?' + a\n response = await session.get(dingdan_url, headers=headers)\n pay_url = response.url\n else:\n logger.log('INFO', '订单:[{}]支付方式: 微信支付'.format(order_sn), 'pdd_spider', pdduid)\n url2 = 'https://api.pinduoduo.com/order/prepay?pdduid={}'.format(pdduid)\n t_data = {\n \"order_sn\": order_sn,\n \"app_id\": 38,\n \"pap_pay\": 1,\n \"version\": 1,\n # \"attribute_fields\": {\"paid_times\": 0}\n }\n response2 = await session.post(url2, headers=headers, json=t_data)\n xiadan_json = await response2.json()\n nweb_url = xiadan_json['mweb_url']\n headers['Referer'] = 'https://mobile.yangkeduo.com/wechat_h5_pay_callback.html?order_sn={}'.format(order_sn)\n response3 = await session.get(nweb_url, headers=headers)\n html = await response3.text()\n pay_url = re.findall('var url=\"(.*?)\";', html, re.I | re.S)[0]\n return order_sn, pay_url\n\n\n\"\"\"\n获取需要的地址ID\ninput = 分组排序ID(group_id), 商品ID(goods_id), 商品的属性ID(sku_id)如衣服的尺码,颜色 购买数量(goods_number)\noutput = 地址ID(addressId)\n\"\"\"\n\n\nasync def get_address_id(sku_id, group_id, goods_id, amount, pdduid, goods_number, session, headers):\n url = 'https://mobile.yangkeduo.com/order_checkout.html?sku_id={}&group_id={}&goods_id={}&goods_number={}'.format(\n sku_id, group_id, goods_id, goods_number)\n response = await session.get(url, headers=headers)\n html = await response.text()\n if 'window.isUseHttps= false' in html or 'window.isUseHttps' not in html:\n return '获取地区ID错误, access_token错误, 请更新'\n\n addressId = re.findall('\"addressId\":(.*?),', html)[0]\n soup = BeautifulSoup(html, 'html.parser')\n price = soup.find('span', class_='oc-final-amount').get_text().replace('¥', '').strip()\n if float(price) == float(amount):\n return addressId\n else:\n logger.log('DEBUG', '订单金额不一致, 给定金额:{},实际支付金额:{}'.format(amount, price), 'pdd_spider', pdduid)\n return '订单金额不一致, 给定金额:{},实际支付金额:{}'.format(amount, price)\n\n\n\"\"\"\n获取商品需要的参数\ninput = 商品地址(goods_url), 登陆状态下的Cookie(cookie)\noutput = 分组排序ID(group_id), 商品ID(goods_id), 商品的属性ID(sku_id)如衣服的尺码,颜色\n\"\"\"\n\n\nasync def get_goods_id(url, session, cookie, headers):\n response = await session.get(url, headers=headers)\n html = await response.text()\n if '该商品已下架' in html:\n return '该商品已下架', None, None\n if cookie is not None:\n headers['Cookie'] = cookie\n if 'skuID' in html and 'groupID' in html and 'goodsID' in html:\n sku_id = re.findall('\"skuID\":(.*?),', html)[0]\n group_id = re.findall('\"groupID\":(.*?),', html)[0]\n goods_id = re.findall('\"goodsID\":\"(.*?)\",', html)[0]\n else:\n return '获取商品信息错误', None, None\n return sku_id, group_id, goods_id\n\n\n\"\"\"获取增加收货地址\"\"\"\n\n\nasync def get_shipping_address(pdduid, accesstoken, session, headers):\n headers['accesstoken'] = accesstoken\n addresses_url = 'https://api.pinduoduo.com/addresses?pdduid={}'.format(pdduid)\n response = await session.get(addresses_url, headers=headers)\n result = await response.json()\n if len(result) == 0:\n url = 'https://api.pinduoduo.com/address?pdduid={}'.format(pdduid)\n f = open('pdd用户地址.csv', 'r', encoding='utf-8')\n b = f.readlines()[random.randint(0, 56145)]\n name = str(b.split(',')[0]).replace('\"', '').replace(\"'\", '')\n phone = str(b.split(',')[1]).replace('\"', '').replace(\"'\", '')\n address = str(b.split(',')[2:-3]).replace('\"', '').replace(\"'\", '').replace(\"[\", '').replace(\"]\", '').replace(\n \",\", '')\n province_id = str(b.split(',')[-3]).replace('\"', '').replace(\"'\", '')\n city_id = str(b.split(',')[-2]).replace('\"', '').replace(\"'\", '')\n district_id = str(b.split(',')[-1].replace('\\n', '')).replace('\"', '').replace(\"'\", '')\n f.close()\n add_data = {\n \"address\": address,\n \"city_id\": city_id, # 城市标识\n \"district_id\": district_id, # 地区识别码\n \"mobile\": phone,\n \"name\": name,\n \"province_id\": province_id # 省标识\n }\n add_response = await session.post(url, headers=headers, json=add_data)\n add_response_json = await add_response.json()\n\n if 'server_time' in add_response_json:\n logger.log('INFO', '新增收货地址成功', 'pdd_spider', pdduid)\n return True, '新增收货地址成功'\n else:\n logger.log('ERROR', '新增收货地址失败', 'pdd_spider', pdduid)\n return False, '新增收货地址失败'\n else:\n if 'error_code' in result:\n logger.log('ERROR', 'access_token错误,请更新.', 'pdd_spider', pdduid)\n return False, 'access_token错误,请更新.'\n return True, '已存在收货地址'\n\n\n\"\"\"拼多多下单入口函数\"\"\"\n\n\nasync def pdd_main(pdduid, accesstoken, goods_url, amount, order_number):\n headers = {\n 'Accept': 'text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{}.{}.{}.{} Safari/537.36'\n .format(random.randint(0, 1000), random.randint(0, 1000), random.randint(0, 1000), random.randint(0, 1000)),\n }\n session = aiohttp.ClientSession()\n order_number = int(order_number)\n # TODO goods_url, accesstoken, pdduid\n # 是否支付宝支付, True为是\n alipay = False\n cookie = 'pdd_user_id={}; PDDAccessToken={};'.format(pdduid, accesstoken)\n\n \"\"\"判断收货地址,没有则增加\"\"\"\n is_add, msg = await get_shipping_address(pdduid, accesstoken, session, headers)\n if is_add is False:\n session.close()\n return {'code': 0, 'pay_url': '', 'order_sn': '', 'msg': msg}\n \"\"\"获取商品信息\"\"\"\n sku_id, group_id, goods_id = await get_goods_id(goods_url, session, cookie, headers)\n\n if '该商品已下架' == sku_id or '错误' in sku_id:\n session.close()\n return {'code': 0, 'pay_url': '', 'order_sn': '', 'msg': sku_id, 'goods_id': 0}\n\n \"\"\"获取地区ID\"\"\"\n address_id = await get_address_id(sku_id, group_id, goods_id, amount, pdduid, order_number, session, headers)\n if '错误' not in address_id and '订单金额' not in address_id:\n order_sn, pay_url = await pay(alipay, address_id, pdduid, accesstoken, sku_id, group_id, goods_id, order_number,\n session, headers)\n if '错误' in pay_url:\n session.close()\n return {'code': 0, 'pay_url': '', 'order_sn': '', 'msg': pay_url, 'goods_id': 0}\n session.close()\n logger.log('INFO', '订单:[{}]支付链接:[{}]'.format(order_sn, pay_url), 'pdd_spider', pdduid)\n return {'code': 1, 'pay_url': pay_url, 'order_sn': order_sn, 'msg': '', 'goods_id': goods_id}\n elif '订单金额不一致' in address_id:\n session.close()\n return {'code': 0, 'pay_url': '', 'order_sn': '', 'msg': address_id, 'goods_id': 0}\n else:\n session.close()\n logger.log('ERROR', '未获取到地区ID, 更新accesstoken后重试', 'pdd_spider', pdduid)\n return {'code': 0, 'pay_url': '', 'order_sn': '', 'msg': address_id, 'goods_id': 0}\n\n\nif __name__ == '__main__':\n start = time.time()\n goods_url = 'https://mobile.yangkeduo.com/goods.html?goods_id=3127645572'\n pdduid = 17083602650\n accesstoken = 'GWWQLINXTMP67SMBE7QXN242U2FHD72OPMHFV2CYBHJ27KVCQDNQ101a825'\n amount = 10\n order_number = 1\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n tasks = asyncio.ensure_future(pdd_main(pdduid, accesstoken, goods_url, amount, order_number))\n taskNone = loop.run_until_complete(tasks)\n result = {}\n for k, v in taskNone.items():\n result[k] = v\n loop.close()\n print(result)\n ('Cost time:', time.time() - start)\n","sub_path":"pinduoduo/pdd_spider.py","file_name":"pdd_spider.py","file_ext":"py","file_size_in_byte":11147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"556843000","text":"import requests\nimport arrow\nimport _strptime\nfrom colorama import Fore, Back, Style, init\ninit()\n\ndef getCurrentBtcPrice():\n response = requests.get(\n 'https://api.coindesk.com/v1/bpi/currentprice.json',\n headers={'ACCEPT': 'application/json'}\n )\n return response.json()\n\ndef main(): \n print('BITCOIN TICKER')\n\n selection = ''\n previousPrice = '0'\n \n while(selection.lower() != 'exit'):\n print('')\n dayResult = getCurrentBtcPrice()\n\n #Moment library for time manipulation\n currentTime = arrow.utcnow().to('local').format('MM/DD/YYYY hh:mm')\n currentPrice = dayResult['bpi']['USD']['rate']\n\n #Prints Green if value increased since last check\n #Prints Red if value decreased\n #Prints White if no change has occured\n if (float(currentPrice.replace(',', '')) > float(previousPrice.replace(',', ''))):\n print(Fore.GREEN + '{0} : ${1} dollars'.format(currentTime, currentPrice))\n elif(float(currentPrice.replace(',', '')) < float(previousPrice.replace(',', ''))): \n print(Fore.RED + '{0} : ${1} dollars'.format(currentTime, currentPrice))\n else: \n print(Fore.WHITE + '{0} : ${1} dollars'.format(currentTime, currentPrice))\n\n\n #Set comparison value for next loop\n previousPrice = currentPrice\n\n #Reset color to white\n print(Fore.WHITE)\n\n selection = input('Press enter to update price or type EXIT: ')\n\nmain()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"477083745","text":"#!/usr/bin/env python2\n\nimport rospy\nimport numpy as np\nimport math\n\n# structure of the nearest neighbor \nclass NeighBor:\n def __init__(self):\n self.distances = None\n self.src_indices = None\n self.tar_indices = None\n\nclass ICP:\n def __init__(self):\n # max iterations\n self.max_iter = 50\n # distance threshold for filter the matching points\n self.dis_th = 0.02 # 0.02\n # tolerance to stop icp\n self.tolerance = 7e-18\n # min match\n # self.min_match = rospy.get_param('/icp/min_match',2)\n \n # ICP process function\n # return: T = (R, t), where T is 2*3, R is 2*2 and t is 2*1\n def process(self,tar_pc,src_pc):\n # tar_pc: last_time [3,n], src_pc: this_time [3,n]\n Transform_acc = np.eye(3)\n prev_error = 0.0\n iter_cnt = 0\n for _ in range(self.max_iter):\n neigh = self.findNearest(src_pc.T, tar_pc.T)\n # filter\n src_pc_xy = ((src_pc.T)[neigh.src_indices]).T\n tar_chorder = ((tar_pc.T)[neigh.tar_indices]).T\n Transform = self.getTransform(src_pc_xy.T, tar_chorder.T)\n Transform_acc = Transform.dot(Transform_acc)\n src_pc = Transform.dot(src_pc)\n mean_error = np.mean(neigh.distances)\n # print(\"Toletance : \", abs(prev_error - mean_error))\n if abs(prev_error - mean_error) < self.tolerance:\n break\n prev_error = mean_error\n iter_cnt = iter_cnt + 1\n print(\"total_iter: {:d}\".format(iter_cnt))\n return Transform_acc[:2,:]\n\n # find the nearest points & filter\n # return: neighbors of src and tar\n def findNearest(self,src,tar):\n neigh = NeighBor()\n src = np.expand_dims(src, axis=1)\n tar = np.expand_dims(tar, axis=0)\n diff = src[...,:2] - tar[...,:2]\n tmp_dist = np.hypot(diff[...,0], diff[...,1])\n min_dist = np.min(tmp_dist, axis=1)\n mask = min_dist < self.dis_th\n min_index = np.argmin(tmp_dist[mask,:], axis=1)\n src_index = np.arange(src.shape[0])[mask]\n neigh.src_indices = src_index\n neigh.tar_indices = min_index\n neigh.distances = min_dist[mask]\n return neigh \n\n # Waiting for Implementation \n # return: T = (R, t), where T is 2*3, R is 2*2 and t is 2*1\n def getTransform(self,src,tar):\n # return 3*3 (last line [0,0,1])\n centroid_src = np.mean(src, axis=0)\n centroid_tar = np.mean(tar, axis=0)\n src_ = (src - centroid_src)[...,:2]\n tar_ = (tar - centroid_tar)[...,:2]\n\n W = np.dot(src_.T, tar_) # H\n U, S, Vt = np.linalg.svd(W) # Vt = V.T\n V = Vt.T\n R = V.dot(U.T)\n t = centroid_tar[:2,np.newaxis] - R.dot(centroid_src[:2,np.newaxis])\n transform = np.hstack([R, t])\n transform = np.vstack((transform, [0,0,1]))\n return transform\n\n # def calcDist(self,a,b):\n # dx = a[0] - b[0]\n # dy = a[1] - b[1]\n # return math.hypot(dx,dy)\n\n","sub_path":"Nano_project/rplidar_ros/src/icp.py","file_name":"icp.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"589271998","text":"\"\"\"users table\n\nRevision ID: 46b3f6358910\nRevises:\nCreate Date: 2019-08-25 13:07:12.847343\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '46b3f6358910'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('is_active', sa.Boolean(), server_default='1', nullable=False),\n sa.Column('username', sa.String(length=100), nullable=False),\n sa.Column('password', sa.String(length=255), server_default='', nullable=False),\n sa.Column('email_confirmed_at', sa.DateTime(), nullable=True),\n sa.Column('first_name', sa.String(length=100), server_default='', nullable=False),\n sa.Column('last_name', sa.String(length=100), server_default='', nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('username')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('users')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/46b3f6358910_.py","file_name":"46b3f6358910_.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"525371845","text":"class BasicUserModel(object):\n POSITIVE = 40\n NEGATIVE = -40\n\n def __init__(self, tweet_classifier):\n\n self.tweet_classifier = tweet_classifier\n self.time_constant = 5.0\n self.partisan = None\n self.score = 0.0\n self.scaler = 1.0\n\n def said(self, status):\n\n score = self.tweet_classifier.predict(status).score\n\n if score > 0:\n self.add_positive(score)\n elif score < 0:\n self.add_negative(score)\n\n return score\n\n\n def add_positive(self, score):\n\n if self.partisan is None or self.partisan == \"Negative\":\n if self.partisan == \"Negative\":\n self.scaler = 2.0\n self.partisan = \"Positive\"\n\n self.score += self.scaler * score * (self.POSITIVE - self.score) / 100\n\n def add_negative(self, score):\n\n if self.partisan is None or self.partisan == \"Positive\":\n if self.partisan == \"Positive\":\n self.scaler = 2.0\n self.partisan = \"Negative\"\n\n self.score += self.scaler * abs(score) * (self.NEGATIVE - self.score) / 100\n\n def get_classification(self):\n return self.score","sub_path":"server/src/AnalyticsService/Graphing/Classification/User/Basic.py","file_name":"Basic.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"419900946","text":"import string\nimport logging\nimport logging.handlers\n\n\nclass BufferingSMTPHandler(logging.handlers.BufferingHandler):\n \"\"\" \n Child class of logging.BufferingHandler to send records via mail\n\n\n \"\"\"\n\n def __init__(self, mailhost, fromaddr, toaddrs, subject, capacity):\n logging.handlers.BufferingHandler.__init__(self, capacity)\n self.mailhost = mailhost\n self.mailport = None\n self.fromaddr = fromaddr\n self.toaddrs = toaddrs\n self.subject = subject\n self.setFormatter(logging.Formatter(\n \"%(asctime)s %(levelname)-5s %(message)s\"))\n\n def flush(self):\n if len(self.buffer) > 0:\n try:\n import smtplib\n port = self.mailport\n if not port:\n port = smtplib.SMTP_PORT\n smtp = smtplib.SMTP(self.mailhost, port)\n msg = \"From: %s\\r\\nTo: %s\\r\\nSubject: %s\\r\\n\\r\\n\" % (\n self.fromaddr,\n string.join(self.toaddrs, \",\"),\n self.subject)\n for record in self.buffer:\n s = self.format(record)\n #print s\n msg = msg + s + \"\\r\\n\"\n smtp.sendmail(self.fromaddr, self.toaddrs, msg)\n smtp.quit()\n except:\n self.handleError(None) # no particular record\n self.buffer = []\n","sub_path":"classes/BufferingSMTPHandler.py","file_name":"BufferingSMTPHandler.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"652389059","text":"import torch\nimport os\nimport numpy as np\nimport pandas as pd\nimport models\nimport pickle \n\n\nfrom utilities import Adult_dataset\nfrom utilities import medical_dataset\nfrom utilities import german_dataset_age\nfrom utilities import german_dataset_sex\nfrom utilities import Readmission_dataset\n\nfrom utilities import format_datasets\nfrom utilities import Dataset_format\nfrom utilities import test\n\n\nfrom torch.utils.data import Dataset, DataLoader\n\n\nfrom sklearn.preprocessing import StandardScaler\nfrom aif360.metrics import ClassificationMetric\nfrom aif360.datasets import BinaryLabelDataset\nfrom sklearn.metrics import roc_auc_score\nfrom xlwt import Workbook \n\nif __name__ == \"__main__\":\n\n\n \"\"\" INPUT DATA \"\"\"\n epochs = 3000\n threshold = 0.5\n model_AIF = [0, 1, 2, 3 ,4]\n alpha = [0, 1e-3, 1e-2, 1e-1, 1, 10, 100, 1000]\n eta = [0, 1e-3, 1e-2, 1e-1, 1, 10, 100, 1000]\n\n saver_dir_models = r'Trained_models/Start_ger_sex' \n saver_dir_results= r'Results/Ger_sex.xls' \n\n\n data, atribute, sensitive, output, pr_gr, un_gr = german_dataset_sex()\n prot = list(pr_gr[0].keys())[0]\n\n data_train, data_test, data_val, atribute_train, atribute_val, atribute_test, sensitive_train, sensitive_val, sensitive_test, output_train, output_val, output_test = format_datasets(data, atribute, sensitive, output, sens_name=prot)\n\n dataset_train = Dataset_format(atribute_train, sensitive_train, output_train)\n dataset_val = Dataset_format(atribute_val, sensitive_val, output_val)\n dataset_test = Dataset_format(atribute_test, sensitive_test, output_test)\n\n dataloader_train = DataLoader(dataset_train, batch_size=len(dataset_train), shuffle=True)\n dataloader_val = DataLoader(dataset_val, batch_size=len(dataset_val), shuffle=True)\n dataloader_test = DataLoader(dataset_test, batch_size=len(dataset_test), shuffle=True)\n\n inp = dataset_train[0][0].shape[0]\n\n iteracija = 0\n\n wb = Workbook()\n\n columns = [\"model\",\"AUC_y_val\", \"Accuracy_y_val\", \"AUC_A_val\", 'bal_acc_val', 'avg_odds_diff_val', \n 'disp_imp_val','stat_par_diff_val', 'eq_opp_diff_val', \n \"AUC_y_test\", \"Accuracy_y_test\", \"AUC_A_test\", 'bal_acc_test', 'avg_odds_diff_test', \n 'disp_imp_test','stat_par_diff_test', 'eq_opp_diff_test', \"alpha\"]\n\n sheets = wb.add_sheet('{}'.format(\"sheet_1\"))\n\n k = 0\n for i in columns:\n sheets.write(0,k,i)\n k+=1 \n\n row = 1\n\n for a in alpha:\n\n ind = eta[iteracija]\n iteracija +=1\n\n lst = [\n # models.Fair_PR(sensitive = prot, class_attr = 'labels', eta = ind),\n # models.Fair_DI_NN(sensitive = prot, inp_size = inp, num_layers_y = 3, step_y = 1.5, repair_level = ind),\n # models.Fair_DI_RF(sensitive = prot, repair_level = ind),\n # models.Fair_rew_NN(un_gr, pr_gr, inp_size = inp, num_layers_y = 3, step_y = 1.5),\n # models.Fair_rew_RF(un_gr, pr_gr),\n\n models.FAD_class(input_size = inp, num_layers_z = 3, num_layers_y = 3, \n step_z = 1.5, step_y = 1.5, name = f\"FAD_{a}\"),\n # models.FAIR_scalar_class(input_size = inp, num_layers_w = 3, step_w = 1.5, \n # num_layers_A = 2, step_A = 1.5, num_layers_y = 4, step_y = 1.5),\n # models.FAIR_betaSF_class(input_size = inp, num_layers_w = 3, step_w = 1.5, \n # num_layers_A = 2, step_A = 1.5, num_layers_y = 4, step_y = 1.5),\n # models.FAIR_Bernoulli_class(input_size = inp, num_layers_w = 3, step_w = 1.5, \n # num_layers_A = 2, step_A = 1.5, num_layers_y = 4, step_y = 1.5),\n # models.FAIR_betaREP_class(input_size = inp, num_layers_w = 3, step_w = 1.5, \n # num_layers_A = 2, step_A = 1.5, num_layers_y = 4, step_y = 1.5),\n # models.FAD_prob_class(flow_length = 2, no_sample = 1,\n # input_size = inp, num_layers_y = 2, \n # step_y = 2, step_z = 2)\n models.CLFR_class(input_size = inp, num_layers_z = 3, num_layers_y = 3, \n step_z = 1.5, step_y = 1.5, name = f\"CLFR_{a}\"),\n models.LURMI_class(input_size = inp, num_layers_z = 3, num_layers_y = 3, \n step_z = 1.5, step_y = 1.5, name = f\"LURMI_{a}\")] \n\n k = 0\n for i in lst: \n \n if np.isin(k ,model_AIF):\n i.fit(data_train, ['labels'], [prot])\n saver_path = os.path.join(saver_dir_models, 'checkpoint_{}_epochs_{}_eta_{}'.format(type(i).__name__, epochs, ind))\n else:\n i.fit(dataloader_train, dataloader_val, max_epoch= epochs, log = 1, alpha = a, log_epoch = 2, early_stopping_no= 1)\n saver_path = os.path.join(saver_dir_models, 'checkpoint_{}_epochs_{}_alpha_{}'.format(type(i).__name__, epochs, a))\n\n torch.cuda.empty_cache()\n\n f = open(saver_path,\"wb\")\n pickle.dump(i,f)\n f.close\n\n metric_val, metric_test = test(data_val, data_test, i, output_val, output_test, \n sensitive_val, sensitive_test, threshold,\n model_AIF, k, dataloader_val, dataloader_test, prot, un_gr, pr_gr)\n \n for column, _ in enumerate(columns):\n if column == 0:\n name = type(i).__name__\n sheets.write(row, column, name)\n elif column > 0 and column < 9:\n sheets.write(row, column , metric_val[column-1])\n elif column == len(columns) - 1:\n sheets.write(row, column, a)\n else:\n sheets.write(row, column , metric_test[column-9])\n \n wb.save(saver_dir_results) \n \n row += 1\n k += 1","sub_path":"Start_ger_sex.py","file_name":"Start_ger_sex.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"9172084","text":"import numpy as np\nimport gym\n\nfrom multiagent.environment import MultiAgentEnv\nimport multiagent.scenarios as scenarios\n\nfrom shiva.envs.Environment import Environment\n\nclass MultiAgentParticleEnv(Environment):\n _GYM_VERSION_ = '0.10.5'\n def __init__(self, config):\n assert gym.__version__ == self._GYM_VERSION_, \"MultiAgentParticleEnv requires Gym {}. Run 'pip uninstall gym' and 'pip install gym==0.10.5' \".format(self._GYM_VERSION_)\n super(MultiAgentParticleEnv, self).__init__(config)\n self._connect()\n self.set_initial_values()\n\n def _connect(self):\n # load scenario from script\n _load_name = self.env_name\n if '.py' not in _load_name:\n _load_name += '.py'\n self.scenario = scenarios.load(_load_name).Scenario()\n # create world\n self.world = self.scenario.make_world()\n # create multiagent environment\n self.env = MultiAgentEnv(self.world, self.scenario.reset_world, self.scenario.reward, self.scenario.observation, info_callback=None, shared_viewer=self.share_viewer)\n # render call to create viewer window (necessary only for interactive policies)\n self.display()\n self.step_data = self.env.reset()\n\n def set_initial_values(self):\n '''Unique Agent Behaviours'''\n self.num_instances_per_env = 1\n self.num_agents = self.env.n\n self.roles = [a.name for a in self.env.agents]\n\n self.action_space = {role:self.get_action_space_from_env(self.env.action_space[ix]) for ix, role in enumerate(self.roles)}\n self.observation_space = {role:self.get_observation_space_from_env(self.env.observation_space[ix]) for ix, role in enumerate(self.roles)}\n\n self.num_instances_per_role = {role:1 for role in self.roles}\n self.num_instances_per_env = 1\n\n '''Init session cumulative metrics'''\n self.reward_total = {role:0 for role in self.roles}\n self.step_count = 0\n self.done_count = 0\n\n # reward function\n self.rewards_wrap = lambda x: x\n if hasattr(self, 'normalize_reward') and self.normalize:\n self.rewards_wrap = self.normalize_reward\n\n '''Reset Metrics'''\n self.reset()\n\n def reset(self, *args, **kwargs):\n '''\n To be called by Shiva Learner\n It's just to reinitialize our metrics. Unity resets the environment on its own.\n '''\n self.steps_per_episode = 0\n self.temp_done_counter = 0\n self.reward_per_step = {role:0 for role in self.roles}\n self.reward_per_episode = {role:0 for role in self.roles}\n\n obs = self.env.reset()\n self.observations = {role:obs[ix] for ix, role in enumerate(self.roles)}\n\n def step(self, actions):\n self.actions = {role:self._clean_actions(role, actions[ix]) for ix, role in enumerate(self.roles)}\n obs, rew, don, _ = self.env.step(list(self.actions.values()))\n self.observations = {role:obs[ix] for ix, role in enumerate(self.roles)}\n self.rewards = {role:self.rewards_wrap(rew[ix]) for ix, role in enumerate(self.roles)}\n\n # maybe overwrite the done - not sure if env tells when is Done\n self.dones = {role:don[ix] for ix, role in enumerate(self.roles)}\n\n '''\n Metrics collection\n Episodic # of steps self.steps_per_episode --> is equal to the amount of instances on Unity, 1 Shiva step could be a couple of Unity steps\n Cumulative # of steps self.step_count\n Temporary episode count self.temp_done_counter --> used for the is_done() call. Zeroed on reset().\n Cumulative # of episodes self.done_count\n Step Reward self.reward_per_step\n Episodic Reward self.reward_per_episode\n Cumulative Reward self.reward_total\n '''\n self.steps_per_episode += self.num_instances_per_env\n self.step_count += self.num_instances_per_env\n self.temp_done_counter += int(self.dones[self.roles[0]]) #sum(self.dones[role] for role in self.roles)\n self.done_count += int(self.dones[self.roles[0]]) #sum([self.dones[role] for role in self.roles])\n for role in self.roles:\n # in case there's asymetric environment\n self.reward_per_step[role] += self.rewards[role]\n self.reward_per_episode[role] += self.rewards[role]\n self.reward_total[role] += self.reward_per_episode[role]\n\n self.display()\n return list(self.observations.values()), list(self.rewards.values()), list(self.dones.values()), {}\n\n def get_metrics(self, episodic=True):\n '''MultiAgent Metrics'''\n metrics = {role:self.get_role_metrics(role, episodic) for ix, role in enumerate(self.roles)}\n return list(metrics.values())\n\n def get_role_metrics(self, role=None, episodic=True):\n if not episodic:\n metrics = [\n ('Reward/Per_Step', self.reward_per_step[role])\n ]\n else:\n metrics = [\n ('Reward/Per_Episode', self.reward_per_episode[role]),\n ('Agent/Steps_Per_Episode', self.steps_per_episode)\n ]\n return metrics\n\n def is_done(self):\n return self.steps_per_episode >= self.episode_max_length\n\n def _clean_actions(self, role, role_actions):\n '''\n Keep Discrete Actions as a One-Hot encode\n '''\n if self.env.discrete_action_space:\n # actions = np.array([ [np.argmax(_act)] for _act in role_actions ])\n actions = np.array(role_actions)\n elif type(role_actions) != np.ndarray:\n actions = np.array(role_actions)\n return actions\n\n def get_action_space_from_env(self, agent_action_space):\n '''All Action Spaces are Discrete - unless new environment is created by us'''\n if self.env.discrete_action_space:\n action_space = {\n 'discrete': agent_action_space.n,\n 'continuous': 0,\n 'param': 0,\n 'acs_space': agent_action_space.n\n }\n else:\n assert \"Continuous Action Space for the Particle Environment is not implemented\"\n # all scenarios have discrete action space\n # action_space = {\n # 'discrete': agent_action_space.n,\n # 'continuous': 0,\n # 'param': 0,\n # 'acs_space': agent_action_space.n\n # }\n return action_space\n\n def get_observation_space_from_env(self, agent_obs_space):\n '''All Obs Spaces are Continuous - unless new environment is implemented'''\n observation_space = 1\n if agent_obs_space.shape != ():\n for i in range(len(agent_obs_space.shape)):\n observation_space *= agent_obs_space.shape[i]\n else:\n observation_space = agent_obs_space.n\n assert observation_space > 1, \"Error processing Obs space? got {}\".format(agent_obs_space)\n return observation_space\n\n def get_observations(self):\n return list(self.observations.values())\n\n def get_actions(self):\n return list(self.actions.values())\n\n def get_rewards(self):\n return list(self.rewards.values())\n\n def get_reward_episode(self, roles=True):\n return self.reward_per_episode\n\n def display(self):\n if self.render:\n self.env.render()\n\n def close(self):\n self.env.close()\n delattr(self, 'env')\n\n def debug(self):\n pass\n","sub_path":"shiva/shiva/envs/MultiAgentParticleEnv.py","file_name":"MultiAgentParticleEnv.py","file_ext":"py","file_size_in_byte":7634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"220890729","text":"from app.tasks import query_page\nfrom django.core.management.base import BaseCommand\nimport sys\nimport pika\nfrom django.conf import settings\n\n\n\nclass Command(BaseCommand):\n def add_arguments(self, parser):\n parser.add_argument('access_token', nargs='+', )\n\n def handle(self, **options):\n parameters = pika.connection.URLParameters(settings.RABBITMQ_URL)\n connection = pika.BlockingConnection(parameters=parameters)\n channel = connection.channel()\n channel.queue_declare(queue='access_token_queue')\n access_token = str(options['access_token'][0])\n\n channel.basic_publish(exchange='',\n routing_key='access_token_queue',\n body=access_token,\n properties=pika.BasicProperties(\n delivery_mode=2, # make message persistent\n ))\n connection.close()\n","sub_path":"app/management/commands/push_to_queue.py","file_name":"push_to_queue.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"145909863","text":"import ROOT\nimport pandas as pd\nimport os\nimport multiprocessing as mp\nimport sys\nsys.path.append('.')\nfrom Bs2PhiJpsi2KKMuMuAnalyzer import Bs2PhiJpsi2KKMuMuAnalyzer\n\n\nROOT.gROOT.SetBatch()\n\ndef exec_me(command, dryRun=False):\n print(command)\n if not dryRun:\n os.system(command)\n\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n n = max(1, n)\n for i in xrange(0, len(l), n):\n yield l[i:i + n]\n\ndef analyze(inputfile, output_file, hist=False, isMC=False):\n analyzer = Bs2PhiJpsi2KKMuMuAnalyzer(inputfile, output_file, isMC)\n analyzer.run()\n\ndef analyzeParallel(enumfChunk):\n ich, fChunk = enumfChunk\n print(\"Processing chunk number %i\"%(ich))\n output_file = outpath+'/'+args.output_file.replace('.root','').replace('.h5','')+'_subset'+str(ich)+'.root'\n analyze(fChunk, output_file, args.hist, args.isMC)\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description=\"Run the Bs analyzer\")\n parser.add_argument(\"-i\", \"--in_txt\", dest=\"in_txt\", default=\"files_BsToPhiJpsi_ToKKMuMu.txt\", help=\"Path to file containing list of input skim files\")\n parser.add_argument(\"-o\", \"--output_file\", dest=\"output_file\", default=\"Bs_hists.root\", help=\"Output file containing plots\")\n parser.add_argument(\"-n\", \"--nevents\", dest=\"nevents\", type=int, default=-1, help=\"Maximum number events to loop over\")\n parser.add_argument(\"-r\", \"--runparallel\", dest=\"runparallel\", action='store_true', help=\"Enable parallel run\")\n args = parser.parse_args()\n\n input_files = []\n with open(args.in_txt) as f:\n for line in f:\n input_files.append(line.strip())\n\n if not args.runparallel:\n output_file = args.output_file.replace('.root','').replace('.h5','')+'.root'\n analyzer = Bs2PhiJpsi2KKMuMuAnalyzer(input_files, output_file, True)\n analyzer.start()\n analyzer.run()\n analyzer.finish()\n\n else:\n #outputBase = \"/eos/uscms/store/user/klau/BsPhiLL_output/LowPtElectronSculpting\"\n #outputFolder = \"BsPhiEE_CutBasedEvaluation\"\n global outpath\n #outpath = \"%s/%s\"%(outputBase,outputFolder)\n outpath = '.'\n if not os.path.exists(outpath):\n exec_me(\"mkdir -p %s\"%(outpath), False)\n\n with open(args.inputfiles) as filenames:\n fileList = [f.rstrip('\\n') for f in filenames]\n group = 6\n # stplie files in to n(group) of chunks\n fChunks= list(chunks(fileList,group))\n print (\"writing %s jobs\"%(len(fChunks)))\n\n pool = mp.Pool(processes = 4)\n input_parallel = list(enumerate(fChunks))\n #print(input_parallel)\n pool.map(analyzeParallel, input_parallel)\n pool.close()\n pool.join()\n\n output_file = args.output_file.replace('.root','').replace('.h5','')\n #if args.hist:\n exec_me(\"hadd -k -f %s/%s %s/%s\"%(outpath,output_file+'.root',outpath,output_file+'_subset*.root'))\n exec_me(\"rm %s/%s\"%(outpath,output_file+'_subset*.root'))\n \n '''\n else:\n if os.path.isfile('{}/{}.h5'.format(outpath, output_file)): os.system('rm {}/{}.h5'.format(outpath, output_file))\n #allHDF = [pd.read_hdf(f, 'branches') for f in ['{}/{}'.format(outpath, output_file+'_subset{}.h5'.format(i)) for i in range(len(fChunks))]]\n allHDF = []\n for f in ['{}/{}'.format(outpath, output_file+'_subset{}.h5'.format(i)) for i in range(len(fChunks))]:\n try:\n allHDF.append(pd.read_hdf(f))\n except ValueError:\n print('Empty HDF file')\n if len(allHDF) != 0:\n outputHDF = pd.concat(allHDF, ignore_index=True)\n else:\n outputHDF = pd.DataFrame()\n outputHDF.to_hdf('{}/{}.h5'.format(outpath, output_file), 'branches', mode='a', format='table', append=True)\n exec_me(\"rm %s/%s\"%(outpath,output_file+'_subset*.h5'))\n '''\n\n\n\n\n","sub_path":"BParkingNANOAnalyzer/analysis/run_bs_mc.py","file_name":"run_bs_mc.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"232969158","text":"import crimjustsimpy as cj\nfrom crimjustsimpy import Visualization\n\n# Setup parameters for the experiment.\n\nAVG_CASES_PER_INTERVAL = 100\nMAX_CASES_PER_INTERVAL = 300\nMIN_PROB_CONVICT = 0.05\nMEAN_PROB_CONVICT = 0.4\nMAX_PROB_CONVICT = 0.95\nPROB_PLEA=0.8\nITERATIONS = 240\n\n# Configure the case factory.\nconvict_gen = cj.RandomScaledBetaProb(shape=10.0,\n lower=MIN_PROB_CONVICT,middle=MEAN_PROB_CONVICT,upper=MAX_PROB_CONVICT)\ncase_factory = cj.CaseFactory(convict_gen=convict_gen)\n\n# Configure the docket factory.\narrival_gen = cj.RandomPoissonBounded(mean=AVG_CASES_PER_INTERVAL, upper=MAX_CASES_PER_INTERVAL)\ndocket_factory = cj.DocketFactory(case_factory=case_factory, arrival_gen=arrival_gen)\n\n# Configure the plea bargaining logic.\nplea_bargaining = cj.PleaBargainingAtRandom(prob_plea=PROB_PLEA)\n\n# Configure the trial logic.\ntrial = cj.Trial()\n\n# Configure the experiment.\nexperiment = cj.Experiment(docket_factory=docket_factory, trial=trial, plea_bargaining=plea_bargaining)\n\n# Run it.\nexperiment.run(ITERATIONS)\nprint(\"Simulation ran for {0} seconds.\".format(experiment.run_time))\ndf = experiment.to_cases_data_frame()\n\n# Plot docket sizes histogram.\nVisualization.plot_docket_sizes_hist(df)\n\n# Plot case probability of conviction histogram.\nVisualization.plot_prob_guilt_hist(df)\n\n# Pie chart of pleas vs trials.\nVisualization.plot_pleas_vs_trials_pie(df)\n\n# Pie chart of trial results.\nVisualization.plot_trial_results_pie(df)\n\n# Pie chart of guilty/not guilty.\nVisualization.plot_guilt_summary_pie(df)\n\n# Pie chart of case results.\nVisualization.plot_case_results_pie(df)\n\n# Plot sentencing histogram.\nVisualization.plot_sentences_hist(df)\n","sub_path":"samples/s20_run_experiment.py","file_name":"s20_run_experiment.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"181236353","text":"#!/usr/bin/env python3\n#\n# mod_.planning_tsa.py\n\nimport glob\nimport os, shutil\nimport pandas as pd\nimport datetime\nimport numpy as np\n\nimport myoutput as out\n\nEXPORTFOLDER = os.path.dirname(os.path.realpath(__file__)) + '/selenium/download/backup/' \nFOLDER_PLANNING = os.path.dirname(os.path.realpath(__file__)) + '/documents/planningsfiles/'\nFILE_PLANNING = FOLDER_PLANNING + 'planningsfiles.csv'\nEXPORT_FILE_PR = EXPORTFOLDER + 'export_back.csv'\nFOLDER_IMPORT_PR = FOLDER_PLANNING + 'tsa_import_pr/'\n\nTAB = 'Surveyor Rapport'\nCOLUMN_TSA_SIGNED = 'Datum TSA Getekend'\nCOLUMN_LAMKEY = 'Opdrachtnummer'\n\n\n\ndef make_tsa_projectindex(project,file_planning):\n\n out.info_file(\"Reading Planrrr data\", EXPORT_FILE_PR)\n df_pr = pd.read_csv(EXPORT_FILE_PR, delimiter=',', encoding = \"ISO-8859-1\", parse_dates=['TSA SIGNED'],keep_default_na=False,dtype={'Opdrachtnummer': str})\n df_pr.columns = df_pr.columns.str.replace(' ','_')\n\n\n pl_file = file_planning\n pl_project = project\n\n out.info_file(\"Planningsfile\",pl_file)\n xls = pd.ExcelFile(pl_file)\n df_pl = pd.read_excel(xls, TAB ,header=3, dtype={'Opdrachtnummer': str, 'BG Name': str })\n df_pl.columns = df_pl.columns.str.replace(' ','_')\n\n df_pr_project=df_pr[df_pr['Projectnummer']==pl_project]\n\n df_pl['BG_KEY'] = df_pl.apply(\n lambda row: row['Opdrachtnummer'] if pd.isnull(row['BG_Name']) else row['BG_Name'],\n axis=1\n )\n df_pr_project['BG_KEY'] = df_pr_project.apply(\n lambda row: row['Opdrachtnummer'] if (row['BG_Name']=='') else row['BG_Name'],\n axis=1\n )\n\n df_pl['VCA'] = df_pl['Datum_TSA_Definitief_Geweigerd'].astype(object)\n df_pl['VCA'] = np.where(pd.isna(df_pl['VCA'])==False, 'NOK', '')\n \n \n df_pr_project_signed = df_pr_project[(df_pr_project['TSA_SIGNED']>pd.to_datetime('1900-1-1'))|(df_pr_project['VCA_Status']=='NOK')]\n df_pr_project_signed = df_pr_project_signed.drop_duplicates(subset=['BG_KEY'])\n\n print('TSA signed in Planrrr:')\n print(df_pr_project_signed['BG_KEY'].count())\n\n df_pl_signed = df_pl[(df_pl['Datum_TSA_Getekend']>pd.to_datetime('1900-1-1'))|(df_pl['VCA']=='NOK')] \n df_pl_signed = df_pl_signed.drop_duplicates(subset=['BG_KEY'])\n print('TSA signed in Planning:')\n print(df_pl_signed['BG_KEY'].count())\n\n\n\n df_pl_pr = df_pr_project_signed.merge(df_pl_signed, how='outer', left_on='BG_KEY', right_on='BG_KEY',suffixes=('', '_PL'))\n\n df_pl_pr['TSA_DELTA'] = np.where((df_pl_pr['TSA_SIGNED']!=df_pl_pr['Datum_TSA_Getekend'])|(df_pl_pr['VCA']!=df_pl_pr['VCA_Status']), 'yes', 'no')\n df_pl_pr_delta=df_pl_pr[df_pl_pr['TSA_DELTA']=='yes']\n\n\n\n# print(df_pl['VCA'])\n\n df_pl_pr_delta_full = df_pr_project.merge(df_pl_pr_delta, how='right', left_on='BG_KEY', right_on='BG_KEY',suffixes=('_PR', ''))\n\n\n\n df_pl_pr_delta = df_pl_pr_delta_full.rename(columns={\"Opdrachtnummer_PR\": \"BUILDING KEY\", \"TSA_SIGNED\": \"TSA SIGNED Planrrr\", \"Datum_TSA_Getekend\": \"TSA SIGNED\", \"VCA\" : \"VCA Status\", \"VCA_Status\" : \"VCA Planrrr\"})\n\n \n df_pl_pr_delta = df_pl_pr_delta[['BUILDING KEY','BG_KEY','Straat','Huisnummer','Huisnummer_Toevoeging','Quadrant','TSA SIGNED', 'TSA SIGNED Planrrr', 'VCA Status', 'VCA Planrrr']]\n\n\n\n df_pl_pr_delta['TSA SIGNED'] = pd.to_datetime(df_pl_pr_delta['TSA SIGNED'], format='%Y-%m-%d')\n\n\n csv = df_pl_pr_delta.to_csv(FOLDER_IMPORT_PR + 'tsa_'+ pl_project +'.csv', sep=';', index=False, date_format='%Y-%m-%d')\n out.info_file(\"tsa data\", df_pl_pr_delta)\n\n\nout.info_file(\"Reading Planning data\", FILE_PLANNING)\ndf_planning = pd.read_csv(FILE_PLANNING, delimiter=';', encoding = \"ISO-8859-1\")\n\n\nfor index,row in df_planning.iterrows():\n print(index, '\\t', row['projectnummer'])\n\nindex = input(\"Enter projectnumber:]\")\n\nproject = df_planning.loc[int(index),'projectnummer']\nfile_planning = df_planning.loc[int(index),'file']\n\nmake_tsa_projectindex(project,file_planning)\n\n\n\n","sub_path":"survey/mod_planning_tsa.py","file_name":"mod_planning_tsa.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"325334810","text":"#! /usr/bin/env python\n\n\"\"\"\nFile: centered_diff.py\nCopyright (c) 2016 Chinmai Raman\nLicense: MIT\n\nCourse: PHYS227\nAssignment: 1.3\nDate: Feb 12, 2016\nEmail: raman105@mail.chapman.edu\nName: Chinmai Raman\nDescription: Function for numberical differentiation and errors in approximation\n\"\"\"\n\nimport numpy as np\n\ndef diff(f, x, h = 1e-5):\n \"\"\"\n Approximates the derivative of a function at a given value of x.\n \"\"\"\n return ((f(x + h) - f(x - h)) / (2.0 * h))\n\ndef test_diff():\n \"\"\"\n Tests the diff function above.\n \"\"\"\n f = lambda x: float(x**2)\n assert(abs(diff(f, 3) - 6.0) < 1e-10), \"Failure.\"\n \ndef application():\n \"\"\"\n Prints the errors of the approximations of the derivatives of given functions.\n \"\"\"\n ex = lambda x: np.exp(x)\n ex2 = lambda x: np.exp(-2.0 * (x**2))\n cos = lambda x: np.cos(x)\n ln = lambda x: np.log(x)\n \n print(\"f(x)\\t\\tx\\tf'(x)\\tapproximation of f'(x)\\terror\")\n print(\"e^x\\t\\t0\\t1\\t\" + str(diff(ex, 0, 0.01)) + \"\\t\\t\" + str(abs(diff(ex, 0, 0.01) - 1)))\n print(\"e^(-2x^2)\\t0\\t0\\t\" + str(diff(ex2, 0, 0.01)) + \"\\t\\t\\t\" + str(abs(diff(ex2, 0, 0.01) - 0)))\n print(\"cos(x)\\t\\t2pi\\t0\\t\" + str(diff(cos, 2 * np.pi, 0.01)) + \"\\t\\t\\t\" + str(abs(diff(cos, 2 * np.pi, 0.01) - 0)))\n print(\"ln(x)\\t\\t1\\t1\\t\" + str(diff(ln, 1, 0.01)) + \"\\t\\t\" + str(abs(diff(ln, 1, 0.01) - 1)))","sub_path":"centered_diff.py","file_name":"centered_diff.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"158345723","text":"import discord\nfrom discord.ext import commands\nimport datetime\nimport descriptions\nimport functions\n\nbot = commands.Bot(command_prefix='>', description=\"I will eat your kneecaps!\")\n\n\n# Commands\nclass KneecapsStuff(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.KneecapHolder = 'KneecapBot'\n self.HolderMember = bot\n self.next_steal = datetime.datetime.now()\n\n @commands.command(brief=descriptions.holder_brief, description=descriptions.holder)\n async def holder(self, ctx):\n await ctx.send(\"Current kneecap owner is: **{}**\".format(self.KneecapHolder))\n\n @commands.command(brief=descriptions.steal_brief, description=descriptions.steal)\n async def steal(self, ctx):\n if datetime.datetime.now() < self.next_steal:\n await ctx.send(\n \"You need to wait {}\".format(functions.chop_microseconds(self.next_steal - datetime.datetime.now())))\n elif ctx.message.author.name == self.KneecapHolder:\n await ctx.send(\"You are the friking holder. bruh\")\n else:\n self.KneecapHolder = ctx.message.author.name\n self.next_steal = datetime.datetime.now() + datetime.timedelta(days=1)\n role = discord.utils.get(ctx.message.guild.roles, name=\"KneecapHolder\")\n for m in role.members:\n await m.remove_roles(role)\n await ctx.send(\"Current kneecap owner is: **{}**\".format(self.KneecapHolder))\n await ctx.message.guild.get_member_named(self.KneecapHolder).add_roles(role)\n\n @commands.command(brief=descriptions.give_brief, description=descriptions.give)\n async def give(self, ctx, member: discord.Member = None):\n if not member:\n await ctx.send(\"I don't know this crackhead\")\n if self.KneecapHolder != ctx.message.author.name:\n await ctx.send(\"You don't have the kneecaps\")\n elif ctx.message.author.name == member.name:\n await ctx.send(\"You are the friking holder. bruh\")\n else:\n self.KneecapHolder = member.name\n role = discord.utils.get(ctx.message.guild.roles, name=\"KneecapHolder\")\n for m in role.members:\n await m.remove_roles(role)\n await ctx.send(\"Current kneecap owner is: **{}**\".format(self.KneecapHolder))\n await ctx.message.guild.get_member_named(self.KneecapHolder).add_roles(role)\n\n @give.error\n async def give_error(self, ctx, error):\n if isinstance(error, commands.BadArgument):\n await ctx.send('I don\\'t know this crackhead')\n\n\nclass OnlyForServerOwner(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(brief=descriptions.setprefix_brief, description=descriptions.setprefix)\n async def setprefix(self, ctx, *, nprefix):\n if ctx.message.author != ctx.message.guild.owner:\n await ctx.send(\"You are not the owner bruh\")\n else:\n nprefix = nprefix.strip()\n if nprefix != \"\":\n try:\n prefix = nprefix\n bot.command_prefix = prefix\n await ctx.send(\"k it worked: **{}**\".format(prefix))\n await self.bot.change_presence(\n activity=discord.Game(name=\"Prefix is {}\".format(self.bot.command_prefix)))\n except:\n await ctx.send(\"Bruh it didn't work (prefix its {})\".format(self.bot.command_prefix))\n\n\nclass Epic(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(hidden=True)\n async def role(self, ctx):\n try:\n if not discord.utils.get(ctx.message.guild.roles, name=\"KneecapHolder\"):\n await ctx.message.guild.create_role(name=\"KneecapHolder\", hoist=True, colour=discord.Colour(0x0000ff))\n role = discord.utils.get(ctx.message.guild.roles, name=\"KneecapHolder\")\n await ctx.message.guild.get_member_named('KneecapBot').add_roles(role)\n except:\n print(ctx.message.guild.name)\n channel = discord.utils.get(ctx.message.guild.channels, name=\"general\", type=discord.ChannelType.text)\n await channel.send(\n \"@everyone Pls deti dajte mi permission aby so vedel vytvarat a spravovat roles aby sme mohli kradnut kneecaps\")\n\n\n# Events\n@bot.event\nasync def on_ready():\n await bot.change_presence(activity=discord.Game(name=\"Prefix is {}\".format(bot.command_prefix)))\n for server in bot.guilds:\n try:\n if not discord.utils.get(server.roles, name=\"KneecapHolder\"):\n await server.create_role(name=\"KneecapHolder\", hoist=True, colour=discord.Colour(0x00ffff))\n role = discord.utils.get(server.roles, name=\"KneecapHolder\")\n await server.get_member_named('KneecapBot').add_roles(role)\n except:\n print(server.name)\n channel = discord.utils.get(server.channels, name=\"general\", type=discord.ChannelType.text)\n await channel.send(\n \"@everyone Pls deti dajte mi permission aby so vedel vytvarat a spravovat roles aby sme mohli kradnut kneecaps\")\n\n print('READY!')\n\n\nbot.add_cog(KneecapsStuff(bot))\nbot.add_cog(OnlyForServerOwner(bot))\nbot.add_cog(Epic(bot))\nbot.run('')\n#NzIyMTgxODQ1MTcyNjE3Mjk5.Xuku\n#Kw.7b6vlaCpnzHSNA7zVPlne1gz_ZE\n","sub_path":"bots/Discord/KneecapBot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"48176943","text":"'''\nCreated on Oct 14, 2015 @author: vkholin\nTHIS FILES CONTAINS:\n1)in this class all major methods are be written, (like:click, sendKey, dropdown, waitExpl, ...)\nThis methods can be reused by simply calling it and sending parametrs\n \n'''\nfrom selenium.webdriver.remote.webelement import WebElement\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException\nimport sys, time, unittest, os\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.support.select import Select\nimport selenium.webdriver.support.ui as ui\nfrom selenium.common.exceptions import TimeoutException\nimport selenium.webdriver.support.expected_conditions as EC\n\nfrom report_path import path_report\nfrom allElements import Locators_Class\nfrom pyvirtualdisplay import Display\n\nf = open(os.path.join(path_report, \"highLevel.log\"), 'w')\n#display = Display(visible=0, size=(1024, 768))\n#display.start()\n\nclass Common_Methods_Class():\n\n driver = None\n \n def launchDriver(self):\n global driver \n \n driver = webdriver.Firefox()\n driver.set_page_load_timeout(30)\n driver.implicitly_wait(30)\n driver.delete_all_cookies()\n return driver\n \n \n def quitDriver(self):\n global driver \n driver.quit()\n# display.stop()\n \n def clearCookies(self):\n global driver \n driver.delete_all_cookies()\n\n \n\n def getURL(self, url):\n global driver \n\n locat = Locators_Class();\n if(url == ''):\n url = 'https://instructorled.training/access/login'\n if(url!= ''):\n url \n\n print(\"This is your URL for this test: \" + url)\n driver.delete_all_cookies()\n driver.get(url)\n try:\n time.sleep(0.5)\n print(\"wait\")\n finally:\n return driver\n return driver\n\n def sendK(self, inputData, locator):\n global driver \n \n print(locator + \"your locator at sendK\")\n \n try:\n fl = Common_Methods_Class();\n fl.findElementBy(locator).clear() \n fl.findElementBy(locator).send_keys(inputData) \n print(\"sendK for \" + locator)\n except:\n f.write(\"\\n____ERROR____cannot sendK: \" + inputData + \" at locator:\" + locator)\n print(\"\\n____ERROR____cannot sendK: \" + inputData + \" at locator:\" + locator)\n return driver\n \n \n def clickElement(self, locator):\n global driver \n try:\n fl = Common_Methods_Class();\n fl.findElementBy(locator).click()\n print(\"clickElement \" + locator)\n except:\n f.write(\"\\n____ERROR____cannot clickElement: \" + locator)\n print(\"\\n____ERROR____cannot clickElement: \" + locator)\n return driver\n \n# nice to create one more method verify without exception handling \n def verifyElementPresent(self, locator):\n global driver \n wait = ui.WebDriverWait(driver,10)\n fl = Common_Methods_Class();\n try: \n \n element = fl.findElementBy(locator)\n print(element.text)\n\n wait.until(lambda driver: element.isVisible())\n \n # ui.WebDriverWait(driver, timeout=2).until(EC.visibility_of_element_located(element))\n \n # driver.find_element(By.XPATH, fl.locatorMeth(locator))\n print(\"verifyElementPresent for \" + locator)\n return True\n except NoSuchElementException as e: \n f.write(\"\\n____ERROR____cannot verifyElementPresent: \" + locator)\n print(\"\\n____ERROR____cannot verifyElementPresent: \" + locator)\n return False\n \n \n def selectElementFromDropdown(self, locator, element):\n global driver \n fl = Common_Methods_Class();\n try:\n# dropDownElement = WebDriverWait(driver, 3).until(lambda driver: driver.find_element(fl.findElementBy(locator)))\n# Select(dropDownElement).select_by_visible_text(element)\n\n Select(driver.find_element(By.XPATH, fl.locatorMeth(locator))).select_by_visible_text(element)\n \n print(\"selectElementFromDropdown \" + locator) \n except:\n f.write(\"\\n____ERROR____cannot selectElementFromDropdown: \" + element)\n print(\"\\n____ERROR____cannot selectElementFromDropdown: \" + element) \n \n#for this method use XPATH ONLY, since with other locators there are some issues. \n def compareTextElementFromDropdown(self, locator, expected):\n global driver \n fl = Common_Methods_Class();\n try:\n selected_option = Select(driver.find_element(By.XPATH, fl.locatorMeth(locator))).first_selected_option\n\n print(selected_option.text == expected) \n print(selected_option.text + \" \" + expected) \n\n if(selected_option.text == expected):\n print(\"compareTextElementFromDropdown. Default viewer is: \" + expected + \" \" + locator) \n except:\n f.write(\"\\n____ERROR____cannot compareTextElementFromDropdown: \" + expected + \" \" + locator) \n print(\"\\n____ERROR____cannot compareTextElementFromDropdown: \" + expected + \" \" + locator) \n\n#actual then expected \n def compare(self, locator, expected):\n fl = Common_Methods_Class();\n actual = fl.findElementBy(locator).text\n print(actual == expected) \n print(actual + \" 1 \" + expected)\n \n try:\n if(actual == expected):\n print(\"+++Compare passed\") \n except:\n f.write(\"\\n____ERROR____cannot compare: \" + locator)\n print(\"\\n____ERROR____cannot compare: \" + locator) \n return driver\n \n \n def findElementBy(self, locator):\n locat = Common_Methods_Class();\n l = locat.locatorMeth(locator)\n \n findBy = locator[:2]\n if(findBy == \"ID\"):\n print(findBy + \" is your locator\" + l)\n return driver.find_element(By.ID, l)\n \n if(findBy == \"XP\"):\n print(\"XPATH is your locator\" + l)\n return driver.find_element(By.XPATH, l)\n \n if(findBy == \"NM\"):\n print(\"NAME is your locator\" + l)\n return driver.find_element(By.NAME, l)\n \n if(findBy == \"LT\"):\n print(\"LinkText is your locator\" + l)\n return driver.find_element(By.LINK_TEXT, l)\n \n if(findBy == \"CN\"):\n print(\"ClassName is your locator\" + l)\n return driver.find_element(By.CLASS_NAME, l)\n \n if(findBy == \"CS\"):\n print(\"CSS_Selector is your locator\" + l)\n return driver.find_element(By.CSS_SELECTOR, l)\n \n if(findBy == \"PL\"):\n print(\"PartialLinkText is your locator\" + l)\n return driver.find_element(By.PARTIAL_LINK_TEXT, l)\n \n if(findBy == \"TN\"):\n# print(\"TagName is your locator\")\n return driver.find_element(By.TAG_NAME, l)\n \n \n def locatorMeth(self, locator):\n loc = locator[3:]\n return loc\n \n def log(self, text):\n print(text)\n \n \n ","sub_path":"RT_Projects/ILP_PY/MAT_acceptance_test/commonMethods.py","file_name":"commonMethods.py","file_ext":"py","file_size_in_byte":7520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"571512792","text":"from tkinter.ttk import Combobox\nfrom pymongo import MongoClient\nfrom tkinter import *\nfrom tkinter import messagebox\nimport mongoDB as db\nimport Main as graph\nfrom PIL import Image,ImageTk\n\n\ndef createLoginFrame(prevFrame,currentFrame):\n forgetFrame=currentFrame\n forgetFrame.forget()\n loginFrame = Frame(loginScrren) ################### we can use loginframe=prevframe#########\n loginFrame.pack()\n labelUserID = Label(loginFrame, text=\"Enter user ID\").pack()\n spaceLabel = Label(loginFrame, text=\"\").pack()\n textBox = Text(loginFrame, height=2, width=11)\n textBox.pack()\n spaceLabel = Label(loginFrame, text=\"\").pack()\n nextButton = Button(loginFrame, height=1, width=10, text=\"Login\",\n command=lambda: GetUserID(textBox, loginFrame)).pack()\ndef presentPrevScreen(prevFrame, userType, currentFrame):\n removeFrame=currentFrame\n removeFrame.forget()\ndef GetUserID(textBox,loginFrame):\n prevFrame=loginFrame\n userType=\"\"\n id=\"\"\n username=textBox.get(\"1.0\", \"end-1c\")\n if not username:\n print('Your username invalid')\n return 0\n print(\"the user name is: \"+username)\n\n db = client['setstudy'].get_collection('users').find({'username': username})\n\n if db.count() == 0:\n messagebox.showinfo(\"ERROR\",'Username do not exist')\n return 0\n\n for document in db:\n id=document['_id']\n flagType=str(document['type'])\n print(\"The user id is: \"+str(id))\n\n if flagType=='1':\n userType=\"Admin\"\n print(userType)\n WelcomePage(userType,prevFrame)\n if flagType=='2':\n userType=\"Lecturer\"\n print(userType)\n WelcomePage(userType,prevFrame)\n if flagType=='0':\n userType=\"Student\"\n print(\"the user type is: \"+userType)\n WelcomePage(userType,prevFrame)\ndef getSelectedGraph(graphSelection,clusterSelection,usersToCluster,username,userRound,dominateFlag,analysisFlag):\n if(graphSelection==\"Heat map\"):\n graph.HeatMapFunction(username, userRound, dominateFlag, analysisFlag)\n if (graphSelection == \"Eye movment speed\"):\n graph.SpeedUpEyes(username,userRound)\n #graph.HeatMapFunction(username, userRound, dominateFlag,analysisFlag)\n if (graphSelection == \"Point drawing\"):\n graph.PointDrawing(username, userRound, dominateFlag)\n #graph.HeatMapFunction(username, userRound, dominateFlag,analysisFlag)\n #Speed var\",\"Speed of eye movement\",\"Speed var with speed of eye movement\n if(clusterSelection==\"Speed var\"):\n graph.ClusterDataBySpeedVar(usersToCluster)\n if (clusterSelection == \"Speed of eye movement\"):\n graph.ClusterDataBySpeedFastMovments(usersToCluster)\n #graph.HeatMapFunction(username, userRound, dominateFlag,analysisFlag)\n if (clusterSelection == \"Speed var with speed of eye movement\"):\n graph.ClusterDataBySpeedAndFastMovmentAVG(usersToCluster)\n\n #graph.HeatMapFunction(username, userRound, dominateFlag,analysisFlag)\n\n #if (graphSelection == \"Eye movment speed\"):\n #if (graphSelection == \"Point drawing\"):\ndef CheckLecturerSelection(graphSelection,roundSelection,clusterSelection,usersToCluster,username,domFlag,analysisFlag):\n if graphSelection ==\"\":\n messagebox.showinfo(\"ERROR\", \"Please select graph type\")\n if roundSelection ==\"\":\n messagebox.showinfo(\"ERROR\", \"Please select round to present\")\n if clusterSelection==\"\":\n messagebox.showinfo(\"ERROR\", \"Please select cluster attributes\")\n if(graphSelection!=\"\" and roundSelection!=\"\" and clusterSelection!=\"\"):\n getSelectedGraph(graphSelection, clusterSelection, usersToCluster, username,roundSelection, domFlag, analysisFlag)\ndef GetViewDetailsByRequestedID(texbox, prevFrame, getIDButton):\n forgetFrame = prevFrame\n forgetFrame.forget()\n currentFrame = Frame(loginScrren) ################### we can use loginframe=prevframe#########\n currentFrame.pack()\n spaceLabel = Label(currentFrame, text=\"\").pack()\n\n instructionLabel = Label(currentFrame,text=\"Select values to present\",font='Arial 14 bold')\n instructionLabel.pack()\n spaceLabel = Label(currentFrame, text=\"\").pack()\n #(currentFrame, text=\"\").pack()\n username = texbox.get(\"1.0\", \"end-1c\")\n usersToCluster = ['user1', 'user2', 'user4', 'user5', 'user7', 'user8']\n print(\"the reqursted id is: \" + username)\n #getIDButton.pack_forget()\n numberOfRounds = db.GetNumberOfRoundByUsername(username)\n numberOfRoundArray = []\n for i in range(numberOfRounds):\n numberOfRoundArray.append(i+1)\n\n roundsLabel = Label(currentFrame, text=username+\" rounds\").pack()\n var = IntVar()\n var2 = IntVar()\n roundsComboBox = Combobox(currentFrame, values = numberOfRoundArray)\n roundsComboBox.pack()\n # spaceLabel = Label(currentFrame, text=\"\").pack()\n graphSelectionLabel = Label(currentFrame, text=\"Choose your graph type\").pack()\n graphSelectionComboBox = Combobox(currentFrame,\n values=[\"Heat map\", \"Eye movment speed\", \"Point drawing\"])\n graphSelectionComboBox.pack()\n #spaceLabel = Label(currentFrame, text=\"\").pack()\n clusterSelectionLabel = Label(currentFrame, text=\"Choose clustering attributes\").pack()\n clusterSelectionComboBox = Combobox(currentFrame,\n values=[\"Speed var\",\"Speed of eye movement\",\"Speed var with speed of eye movement\"])\n clusterSelectionComboBox.pack()\n spaceLabel = Label(currentFrame, text=\"\").pack()\n checkBoxButton=Checkbutton(currentFrame,text=\"Show dominate cards\",variable=var)\n checkBoxButton.pack()\n checkBoxButton2=Checkbutton(currentFrame,text=\"Show analysis \",variable=var2)\n #checkBoxButton2.pack()\n spaceLabel = Label(currentFrame, text=\"\").pack()\n next=Button(currentFrame,text=\"Get graph\",\n command=lambda: CheckLecturerSelection(\n graphSelectionComboBox.get(),(int(roundsComboBox.get())-1),clusterSelectionComboBox.get(),usersToCluster,\n username,var.get(),var2.get()))\n next.pack()\n spaceLabel = Label(currentFrame, text=\"\").pack()\n\n prevButton = Button(currentFrame, text=\" Back \",\n command=lambda: CreateViewFrame(currentFrame))\n prevButton.pack()\ndef createAdminsFrame(userType,prevFrame):\n welcomeAdminFrame = Frame(loginScrren)\n currentFrame = welcomeAdminFrame\n welcomeAdminFrame.pack()\n labelUserID = Label(welcomeAdminFrame, text=\"Enter requested id: \" + userType).pack()\n spaceLabel = Label(welcomeAdminFrame, text=\"\").pack()\n texbox = Text(welcomeAdminFrame, height=2, width=11).pack()\n spaceLabel = Label(text=\"\")\n signOutButton = Button(welcomeAdminFrame, height=1, width=10, text=\"Sign-out\",\n command=lambda: createLoginFrame(prevFrame,currentFrame)).pack()\ndef CreateViewFrame(prevFrame):\n forgetFrame=prevFrame\n forgetFrame.forget()\n viewFrame=Frame(loginScrren)\n viewFrame.pack()\n currentFrame=viewFrame\n spaceLabelgert = Label(viewFrame, text=\"\").pack()\n spaceLabelgert = Label(viewFrame, text=\"\").pack()\n labelUserID = Label(viewFrame, fg=\"black\", text=\"Enter candidates name\",font='bold').pack()\n spaceLabelgert = Label(viewFrame, text=\"\").pack()\n texbox = Text(viewFrame, height=2, width=11)\n texbox.pack()\n spaceLabelgert = Label(viewFrame, text=\"\").pack()\n getIDButton = Button(viewFrame, height=1, width=10, text=\"Get details\",\n command=lambda: GetViewDetailsByRequestedID(texbox,viewFrame,getIDButton))\n getIDButton.pack()\n\ndef createLecturerFrame(userType,prevFrame):\n welcomeLecturerFrame = Frame(loginScrren)\n currentFrame = welcomeLecturerFrame\n welcomeLecturerFrame.pack()\n spaceLabel = Label(welcomeLecturerFrame, text=\"\").pack()\n spaceLabel = Label(welcomeLecturerFrame, text=\"\").pack()\n spaceLabel = Label(welcomeLecturerFrame, text=\"\").pack()\n labelUserID = Label(welcomeLecturerFrame,text=\"Welcome \" + userType,font='bold').pack()\n spaceLabel = Label(welcomeLecturerFrame, text=\"\").pack()\n viewButton = Button(welcomeLecturerFrame, height=1, width=20,\n text=\"View test results\",\n command=lambda: CreateViewFrame(currentFrame)).pack()\n spaceLabel = Label(welcomeLecturerFrame, text=\"\").pack()\n\n signOutButton = Button(welcomeLecturerFrame, height=1, width=10,\n text=\"Sign-out\",\n command=lambda: createLoginFrame(prevFrame,currentFrame)).pack()\ndef createStudentsFrame(userType,prevFrame):\n welcomeStudentFrame = Frame(loginScrren)\n currentFrame = welcomeStudentFrame\n welcomeStudentFrame.pack()\n labelUserID = Label(welcomeStudentFrame, bg=\"grey\", fg=\"White\", text=\"HI \" + userType).pack()\n spaceLabel = Label(welcomeStudentFrame, text=\"\").pack()\n texbox = Text(welcomeStudentFrame, height=2, width=11).pack()\n spaceLabel = Label(welcomeStudentFrame,text=\"\").pack()\n startTestButton = Button(welcomeStudentFrame, height=1, width=10, text=\"Start test\",).pack()\n spaceLabel = Label(welcomeStudentFrame,text=\"\").pack()\n signOutButton = Button(welcomeStudentFrame, height=1, width=10, text=\"Sign-out\",\n command=lambda: createLoginFrame(prevFrame,currentFrame)).pack()\n spaceLabel = Label(welcomeStudentFrame,text=\"\",).pack()\ndef WelcomePage(userType,prevFrame):\n forgetFrame=prevFrame\n forgetFrame.forget()\n\n if(userType==\"Admin\"):\n createAdminsFrame(userType,prevFrame)\n if (userType == \"Lecturer\"):\n createLecturerFrame(userType,prevFrame)\n if (userType == \"Student\"):\n createStudentsFrame(userType,prevFrame)\ndef StartPage():\n global loginScrren\n loginScrren=Tk()\n loginScrren.geometry(\"300x350\")\n loginScrren.title(\"Set game analyzer\")\n signOutFram=Frame(loginScrren)\n signOutFram.pack(side=BOTTOM)\n loginFrame=Frame(loginScrren)\n loginFrame.pack()\n spaceLabel = Label(loginFrame, text=\"\").pack()\n spaceLabel = Label(loginFrame, text=\"\").pack()\n spaceLabel = Label(loginFrame, text=\"\").pack()\n labelUserID=Label(loginFrame, text=\"Enter user ID\",font='bold').pack()\n spaceLabel=Label(loginFrame, text=\"\").pack()\n textBox=Text(loginFrame, height=2, width=11)\n textBox.pack()\n spaceLabel = Label(loginFrame, text=\"\").pack()\n nextButton=Button(loginFrame, height=1, width=10, text=\"Login\",\n command=lambda: GetUserID(textBox, loginFrame)).pack()\n loginScrren.mainloop()\nclient = MongoClient('mongodb://admin:matanman@ds031822.mongolab.com:31822/admin?authSource=setstudy')\nStartPage()\n","sub_path":"Gui.py","file_name":"Gui.py","file_ext":"py","file_size_in_byte":10657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"428836711","text":"import json\nimport re\n\nfrom util import listToJson\n\nif __name__ == '__main__':\n sections: list = json.load(open('_pawsSection.raw.json', 'r'))\n requirements: list = json.load(open('requirement.json', 'r'))\n tags: list = json.load(open('tag.json', 'r'))\n\n descriptions = set()\n for section in sections:\n description: str = section['title'][1]\n if description != '':\n descriptions.add(section['title'][1])\n\n descriptions = list(descriptions)\n\n tagPattern = r'\\((?:'\n tagPattern += '|'.join([tag['code'] for tag in tags])\n tagPattern += r'|/)+\\)'\n # print(tagPattern)\n # \\((?:CC|CL|COM|HON|HU|LA|Q|SS|/)+\\)\n tagPattern = re.compile(tagPattern, flags=re.IGNORECASE)\n\n prerequisitesPattern = re.compile(r'(\\(Prerequisites: .+?\\))')\n\n for index, description in enumerate(descriptions):\n try:\n startIndex = re.search(r'\\(Requirement[s]?: ', description).start()\n\n nestingLevel = 0\n for offset, char in enumerate(description[startIndex:]):\n if char == '(':\n nestingLevel += 1\n elif char == ')':\n nestingLevel -= 1\n\n if nestingLevel == 0:\n endIndex = startIndex + offset + 1\n break\n\n description = description[:startIndex] + description[endIndex:]\n except AttributeError:\n pass\n\n description = tagPattern.sub(repl='', string=description)\n description = prerequisitesPattern.sub(repl='', string=description)\n\n descriptions[index] = description.strip()\n\n listToJson(descriptions, 'description')\n","sub_path":"description.py","file_name":"description.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"54090039","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[16]:\n\n\nimport math\na = [2, 4, 9, 16, 25]\nfor i in range(len(a)):\n a[i] = math.sqrt(a[i])\na\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"dz3/new_list.py","file_name":"new_list.py","file_ext":"py","file_size_in_byte":154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"633378919","text":"\n\n#calss header\nclass _YAHOO():\n\tdef __init__(self,): \n\t\tself.name = \"YAHOO\"\n\t\tself.definitions = [u'a rude, loud, unpleasant person, especially one who has little education']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_yahoo.py","file_name":"_yahoo.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"527750765","text":"\"\"\"\n处理染色体数据\n得到染色体上每个基因的编号和起始结束位置\n\"\"\"\n\nimport csv\n\ndef remove_n(data):\n return data.strip(\"\\n\")\n\ndef get_mRNA():\n with open(\"hs_ref_GRCh38.p7_chr1.gbs\") as f:\n with open(\"output.txt\",\"a\") as result_file:\n while True:\n data = f.readline().strip(\" \")\n if data:\n if len(data) == 0:\n pass\n elif data.startswith(\"mRNA\"):\n every_mRNA_data = []\n every_mRNA_data.append(data)\n next_line = f.readline().strip(\" \")\n while next_line[0].isdigit() or next_line[0] == \"<\":\n every_mRNA_data.append(next_line)\n next_line = f.readline().strip(\" \") \n while True:\n data = f.readline().strip(\" \")\n if data.startswith('/db_xref=\"GeneID'): \n every_mRNA_data.append(\" \"+data) \n result_file.write(\"\".join(list(map(remove_n,every_mRNA_data))) +\"\\n\") \n break\n else:\n break\n\ndef get_id(string):\n return string[string.find(\"GeneID\"):].split(\":\")[-1].strip('\"')\n\ndef get_loc(string):\n string_list = string.split(\"..\")\n start = int(string_list[0].split(\"(\")[-1].strip(\">\").strip(\"<\")) #not find return -1\n end = int(string_list[-1].strip(\")\").strip(\"<\").strip(\">\"))\n return start,end\n\n\ndef get_id_loc():\n all_dataset = []\n with open(\"output.txt\",\"r\") as f:\n for line in f.readlines():\n data = [item.strip() for item in line.split(\" \") if len(item) != 0]\n all_dataset.append(data)\n\n gene_id = get_id(all_dataset[0][-1])\n start,end = get_loc(all_dataset[0][1])\n start_list=[start]\n end_list = [end]\n \n \"\"\"\n print(all_dataset[0])\n print(gene_id)\n print(start,end)\n \"\"\"\n\n output = open(\"ultimate_output.csv\",\"w\")\n writer = csv.writer(output)\n writer.writerow([\"GeneID\",\"startLoc\",\"endLoc\"])\n\n for mRNA in all_dataset[1:]:\n temp_gene_id = get_id(mRNA[-1])\n if temp_gene_id != gene_id:\n writer.writerow([gene_id,min(start_list),max(end_list)])\n gene_id = temp_gene_id\n start_list = []\n end_list = []\n start_list.append(get_loc(mRNA[1])[0])\n end_list.append(get_loc(mRNA[1])[1])\n else:\n start_list.append(get_loc(mRNA[1])[0])\n end_list.append(get_loc(mRNA[1])[1])\n \n output.close() \n \n\n\nif __name__ == '__main__':\n get_id_loc()\n","sub_path":"RIFS/methylation/得到染色体上每个基因的位置/get_gene_start_end.py","file_name":"get_gene_start_end.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"619968391","text":"#! /usr/bin/python3\n\nT = int(input())\n\nfor n in range(1, T+1):\n print(\"Case #%d:\" % n)\n (R, C, M) = (int(x) for x in input().split())\n dots = R*C - M\n if M == 0:\n print(\"\\n\".join([\"c\"+(C-1)*\".\"] + (R-1)*[C*\".\"]))\n elif dots == 0:\n print(\"Impossible\")\n elif R == 1:\n assert C - M > 0\n print(\"c\"+(C-M-1)*\".\"+M*\"*\")\n elif C == 1:\n assert R - M > 0\n print(\"c\\n\"+(R-M-1)*\".\\n\"+M*\"*\\n\", end='')\n elif dots == 1:\n print(\"\\n\".join([\"c\"+ (C-1)*\"*\"] + (R-1)*[C*\"*\"]))\n elif dots > 3:\n if (dots == 5) or (dots == 7):\n print(\"Impossible\")\n continue\n if (R == 2) or (C == 2):\n if dots%2 != 0 :\n print(\"Impossible\")\n continue\n elif R == 2:\n l = int(dots/2)\n print(\"c\"+(l-1)*\".\"+(C-l)*\"*\")\n print(l*\".\"+(C-l)*\"*\")\n continue\n elif C == 2:\n l = int(dots/2)\n print(\"c.\")\n print((l-1)*\"..\\n\", end='')\n print(int(M/2)*\"**\\n\", end='')\n continue\n (lines, extra) = divmod(dots, C)\n temp = []\n if (lines >= 2) and (extra != 1):\n temp.append(\"c\"+(C-1)*\".\")\n temp.extend((lines-1)*[C*\".\"])\n temp.append(extra*\".\"+(C-extra)*\"*\")\n temp.extend((R-lines-1)*[C*\"*\"])\n print(\"\\n\".join(temp))\n continue\n elif (lines > 2) and (extra == 1):\n temp.append(\"c\"+(C-1)*\".\")\n temp.extend((lines-2)*[C*\".\"])\n temp.append((C-1)*\".\"+\"*\")\n temp.append(\"..\"+ (C-2)*\"*\")\n temp.extend((R-lines-1)*[C*\"*\"])\n print(\"\\n\".join(temp))\n continue\n elif (lines == 2) and (extra == 1):\n temp.append(\"c\"+(C-2)*\".\"+\"*\")\n temp.append((C-1)*\".\"+\"*\")\n temp.append(3*\".\"+(C-3)*\"*\")\n temp.extend((R-3)*[C*\"*\"])\n print(\"\\n\".join(temp))\n continue\n elif lines < 2:\n (l, rem) = divmod(dots, 2)\n if rem == 1:\n l -= 1\n rem += 2\n temp.append(\"c\"+(l-1)*\".\"+(C-l)*\"*\")\n temp.append(l*\".\"+(C-l)*\"*\")\n temp.append(rem*\".\"+(C-rem)*\"*\")\n temp.extend( (R-3)*[ C*\"*\" ])\n print(\"\\n\".join(temp))\n continue\n else:\n print(\"Impossible\")\n\n","sub_path":"solutions_5690574640250880_0/Python/fractal/minesweep.py","file_name":"minesweep.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"591459454","text":"\"\"\"A simple HTTP web-server implementation.\"\"\"\nimport traceback\nimport mimetypes\nimport socket\nimport select\nimport queue\nimport time\nimport sys\nimport os\n\n\nclass FriPlugin:\n \"\"\"\n Base class for plug-ins for the FriServer.\n\n Plug-ins are a way to extends the capabilities of the FriServer. A plug-in\n may generate a document on-the-fly as an example.\n Another use-case would be the connection to a database.\n \"\"\"\n\n def load(self):\n \"\"\"\n Load the plug-in (abstract method).\n\n This method is called during the initialization of the server. If the\n plug-in raises an exception in this method it will be removed from the\n active plug-in list.\n \"\"\"\n raise NotImplementedError('Implement this method in the derived class')\n \n def end(self):\n \"\"\"\n End the plug-in execution (abstract method).\n\n This method is called during the shutdown of the server. Exceptions\n from the plug-in are caught, but nothing is done except for a message.\n \"\"\"\n raise NotImplementedError('Implement this method in the derived class')\n\n def on_get_request(self, request):\n \"\"\"\n Change the handling of a GET request.\n\n Plug-ins are able to change the behavior of the GET response. If any\n work is done, the method has to return the generated request, else\n None.\n :param request: The request message from the client.\n :return: The response to the client, if the plug-in generated it or\n None, if not.\n :rtype: UTF-8 encoded bytes\n \"\"\"\n raise NotImplementedError('Implement this method in the derived class')\n\n def on_post_request(self, request):\n \"\"\"\n Change the handling of a POST request.\n\n Plug-ins are able to change the behavior of the POST response. If any\n work is done, the method has to return the generated request, else\n None.\n :param request: The request message from the client.\n :return: The response to the client, if the plug-in generated it or\n None, if not.\n :rtype: UTF-8 encoded bytes\n \"\"\"\n raise NotImplementedError('Implement this method in the derived class')\n\n\nclass FriServer:\n r\"\"\"\n A simple HTTP web-server.\n\n It manages all client connections using raw sockets. The connections aren't\n encrypted (for the encrypted version see the class SecuredFriServer).\n Currently it accepts and manages HTTP GET and POST requests only. Note that\n POST requests are currently not responded correctly. The response is the\n content of the requested file if it exists or the correct Page-Not-\n Found response (404).\n It also allows to limit the use of resources by setting the maximum number\n of concurrently open connections.\n\n This method is no test, but all other tests call that function. It creates\n the server object\n >>> def server_create(port_used):\n ... import threading\n ...\n ... server = FriServer(port=port_used, max_connections=5, verbose=False)\n ... server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n ... server_thread = threading.Thread(target=server.serve)\n ... server_thread.start()\n ... return server\n\n A test, if a server can successfully created. The variable is used in later\n tests as well. There is also a test, if the exception is caught, when a\n port couldn't be bound due to insufficient privileges.\n >>> server = server_create(80)\n >>> server._running\n False\n >>> server = server_create(1997)\n >>> server._running\n True\n\n A test, if the server responds with the HTTP 200 and the page content, if\n an existing page is requested:\n >>> def test_200_ok():\n ... '''Creates a file and request it from the server.'''\n ... test_file = open('test.page', 'w')\n ... _ = test_file.write('This is a test.')\n ... test_file.close()\n ...\n ... client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n ... client.connect(('0.0.0.0', 1997))\n ... client.sendall(b'GET /test.page HTTP/1.1\\r\\n\\r\\n')\n ... response = client.recv(1024)\n ... client.close()\n ...\n ... os.remove('test.page')\n ...\n ... http_code = response.splitlines()[0]\n ... content = response.split(b'\\r\\n\\r\\n')[1]\n ... return [http_code, content]\n >>> test_200_ok()\n [b'HTTP/1.1 200 OK', b'This is a test.']\n\n A test, if the server responds to a non-existing page with the error 404.\n >>> def test_404_not_found():\n ... client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n ... client.connect(('0.0.0.0', 1997))\n ... client.sendall(b'GET /non-existing.page HTTP/1.1\\r\\n\\r\\n')\n ... response = client.recv(1024)\n ... client.close()\n ... return response.splitlines()[0]\n >>> test_404_not_found()\n b'HTTP/1.1 404 Not Found'\n\n A test, if the server supports a custom 404 page (has to be called \n 'error_404.html'). This page may only be sent, if the requested page was a\n .html file. Other file should indeed report 404.\n >>> def test_custom_404_page(requested_page):\n ... page= open('error_404.html', 'w')\n ... _ = page.write('Custom 404 page.')\n ... page.close()\n ...\n ... client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n ... client.connect(('0.0.0.0', 1997))\n ... client.sendall(b'GET /' + requested_page + b' HTTP/1.1\\r\\n\\r\\n')\n ... response = client.recv(1024)\n ... client.close()\n ...\n ... os.remove('error_404.html')\n ...\n ... http_code = response.splitlines()[0]\n ... content = response.split(b'\\r\\n\\r\\n')[1]\n ... return [http_code, content]\n >>> test_custom_404_page(b'non-existing-page.html')\n [b'HTTP/1.1 200 OK', b'Custom 404 page.']\n >>> test_custom_404_page(b'non-existing-page.non-html')\n [b'HTTP/1.1 404 Not Found', b'']\n\n A test, if the connection limiting works (Note that this test takes time to\n complete (~5-10s)):\n >>> def test_max_connetions():\n ... '''\n ... Test, whether the parameter max_connections is respected.\n ...\n ... The function creates a server at the port 1997 and a set of 10 clients\n ... which are connecting (nearly) at the same time to the server. The\n ... requested page is this file (works since the server's root directory is\n ... set to the directory '.'). The number of maximum concurrent connections\n ... is set to 5, so at least one of the clients should receive a 503, if\n ... the connection limiting works.\n ... :return: True, if at least one client receives a 503 response code.\n ... :rtype: boolean\n ... '''\n ...\n ... port_used = 1997\n ...\n ... server = server_create(port_used)\n ...\n ... clients = []\n ... request = b'GET /FriServer.py HTTP/1.1\\r\\n\\r\\n'\n ... for _ in range(10):\n ... clients.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM))\n ... for client in clients:\n ... client.connect(('0.0.0.0', port_used))\n ... for client in clients:\n ... client.sendall(request)\n ... \n ... responses = [client.recv(4096) for client in clients]\n ... server.shutdown()\n ...\n ... responses = [r.splitlines()[0].split()[1] for r in responses]\n ... responses = [str(response, 'utf8') for response in responses]\n ... responses = [int(response) for response in responses]\n ...\n ... return 503 in responses\n >>> test_max_connetions()\n True\n\n Close the server created for the tests.\n >>> server.shutdown()\n \"\"\"\n\n def __init__(\n self,\n port=80,\n max_connections=50,\n file_base_path='.',\n verbose=True\n ):\n \"\"\"\n Construct the class.\n\n It initializes all private variables and tries to bind the the server\n to the selected interface (which defaults to port 80 on all available\n interfaces).\n :param port: The port under which the server can be accessed. Defaults\n to port 80, which is the default port for HTTP connections.\n :param max_connections: The maximum number of simultaneously open\n connections. This number has to be greater than zero.\n Note that this number is not the number of client connections, since\n one client is able to send multiple requests simultaneously (e.g. a\n HTTP file as well as the CSS-script and the JavaScript used). Example:\n If you limit the maximum connections to 1, the client may get a broken\n site, because only the HTML page is transmitted and all other files are\n not sent (503 is returned).\n :param file_base_path: The directory that contains all server files.\n It's also called the server's 'root' directory. It must not end with\n a slash and must not be empty. If the current folder should be used,\n pass the string '.'.\n :param verbose: Enable/disable verbose mode. In verbose mode (which is\n on by default) the server messages are printed to sys.stdout.\n \"\"\"\n self._verbose = verbose\n self._print('Server is starting...')\n\n if max_connections < 1:\n raise ValueError('There has to be at least one connection allowed')\n self._max_connections = max_connections\n self._open_connections = 0\n\n self._running = True\n\n if file_base_path == '':\n file_base_path = '.'\n elif file_base_path[-1:] == '/':\n file_base_path = file_base_path.rstrip('/')\n self.file_base_path = bytes(file_base_path, 'utf8')\n\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self._bind_socket(port)\n self._read_queues = {}\n self._write_queues = {}\n\n self.plugins = []\n\n def serve(self):\n \"\"\"\n Handle all connections.\n\n TODO: describe the work done.\n\n This is done by setting up all needed local variables and calling the\n private method _serve_once() on a while loop. If the member variable\n _running is set to false (this has to be done asynchronously) the loop\n ends and all open sockets are closed.\n \"\"\"\n if not self._running:\n self._print('Server is not running!')\n\n inputs = [self.socket]\n outputs = []\n while self._running:\n self._serve_once(inputs, outputs)\n\n for plugin in self.plugins:\n try:\n plugin.end()\n except:\n print('Plug-in exception: stracktrace follows')\n traceback.print_exc(file=sys.stdout)\n\n for sock in inputs:\n sock.close()\n for sock in outputs:\n sock.close()\n self.socket.close()\n self._print('Server closed.')\n\n def add_plugin(self, plugin):\n \"\"\"\n Add a plug-in to the server.\n\n This plug-in is appended to the list of plug-ins if the load()-method\n didn't throw an exception.\n \"\"\"\n if not isinstance(plugin, FriPlugin):\n raise TypeError('The plug-in has to be derived from FriPlugin.')\n try:\n plugin.load()\n self.plugins.append(plugin)\n except:\n self._print('Could not load plug-in', line_feed=False)\n self._print(plugin)\n traceback.print_exc(file=sys.stdout)\n\n def _serve_once(self, inputs, outputs):\n \"\"\"\n Do exactly one serving iteration.\n\n This includes the checking for sockets that are not blocked, i.e. they\n provide data, take data or are faulting. Using select() there are three\n lists that are each processed in separate methods. See their\n descriptions for more information. This method may block for one second\n (this is the timeout for select()).\n :param inputs: The list of all connections to read from.\n :param outputs: The list of all connections to write to.\n \"\"\"\n readable, writable, exceptional = select.select(\n inputs,\n outputs,\n inputs,\n 1\n )\n self._handle_readable_connections(readable, inputs, outputs)\n self._handle_writeable_connections(writable, inputs, outputs)\n self._handle_exceptional_connections(exceptional, inputs, outputs)\n\n def _handle_readable_connections(self, readable, inputs, outputs):\n \"\"\"\n Handle connections that have data available.\n\n The handler for a list of sockets that can be read from. This list may\n include sockets that are closed in the time between select() and the\n one to this method, so an check if the current socket is still open is\n necessary.\n There are two types of readable sockets: the main server socket and an\n ordinary connection.\n In the first case a new client connection is available and should be\n accepted. This connection is either accepted (if the maximum number of\n connections is not reached) or discarded.\n In the second case the current connection has data to read available.\n This data is read in 1KiB chunks and stored in/appended to the receive\n message buffer. If the read call returns nothing the socket has no more\n data and the transmission is done. In that case the connection is\n closed.\n :param writable: A list of all writable sockets. This list should be\n obtained by select().\n :param inputs: The list of all sockets to read from. Used in every\n access to the connection.\n :param outputs: The list of all sockets to write to. Used in every\n access to the connection.\n \"\"\"\n for sock in readable:\n if sock not in inputs:\n break\n if sock is self.socket:\n if self._open_connections < self._max_connections:\n self._open_new_connection(sock, inputs, outputs)\n else:\n self._discard_new_connection(sock)\n else:\n data = self._receive_bytes(sock, inputs, outputs)\n if data:\n if sock in self._read_queues:\n self._read_queues[sock].put(data)\n else:\n self._read_queues[sock] = queue.Queue()\n self._read_queues[sock].put(data)\n\n if sock not in outputs:\n outputs.append(sock)\n else:\n self._close_connection(sock, inputs, outputs)\n\n def _handle_writeable_connections(self, writable, inputs, outputs):\n \"\"\"\n Handle connections that request data.\n\n The handler for a list of sockets that can be written to. The lists may\n include sockets that are closed in the time between select() and the\n one to this method (i.e. in in _handle_readable_connections()), so an\n check if the current socket is still open is necessary.\n An writable socket can have two states: the response is already\n generated and can be sent (parts of it even may be sent already) or the\n message has to be generated now.\n In the first case the message was already written to the write message\n buffer and now the rest of the message has to be transmitted to the\n client. If the message was not fully sent, the remaining bytes are\n stored in the message buffer again. If the message was sent completely\n the connection is closed.\n In the second case the response is not ready to be sent and has to be\n created. The generation is based on the read message buffer (this\n implies that there has to be a valid message in there. Currently there\n is no check for that!) and is done by the private method\n _generate_response(). See its description for details.\n :param writable: A list of all writable sockets. This list should be\n obtained by select().\n :param inputs: The list of all sockets to read from. Passed on to\n _close_connection().\n :param outputs: The list of all sockets to write to. Passed on to\n _close_connection().\n \"\"\"\n for sock in writable:\n if sock not in outputs:\n break\n if sock in self._write_queues:\n message = self._write_queues[sock]\n bytes_sent = self._send_bytes(sock, message)\n if bytes_sent < len(message):\n self._write_queues[sock] = message[bytes_sent:]\n else:\n self._close_connection(sock, inputs, outputs)\n else:\n request = b''\n for msg in list(self._read_queues[sock].queue):\n request += msg\n self._write_queues[sock] = self._generate_response(request)\n\n def _handle_exceptional_connections(self, exceptional, inputs, outputs):\n \"\"\"\n Handle exceptional connections.\n\n The handler for a list of exceptional connections. Those connections\n are closed and removed from the input and output list. An error is only\n printed if the verbose mode is activated.\n :param exceptional: A list of all faulting sockets. This list should be\n obtained by select().\n :param inputs: The list of all sockets to read from. Passed on to\n _close_connection().\n :param outputs: The list of all sockets to write to. Passed on to\n _close_connection().\n \"\"\"\n for sock in exceptional:\n self._print('Error in socket, closing it...')\n if sock in inputs:\n inputs.remove(sock)\n if sock in outputs:\n outputs.remove(sock)\n self._close_connection(sock, inputs, outputs)\n\n def shutdown(self):\n \"\"\"\n End the server.\n\n This method has to be called asynchronously (either by an interrupt or\n using threads). It sets the private variable _running to False. This\n causes the server to end after the current call of _serve_once()\n returns and the loop can end.\n A message will be printed if the server is in verbose mode.\n \"\"\"\n self._running = False\n self._print('Server is shutting down...')\n\n def _print(self, msg, line_feed=True):\n \"\"\"\n Print a string if the verbose mode is enabled.\n\n :param msg: The message to print.\n :param line_feed: (line feed) Controls the newline. A newline is only printed\n if this parameter is True (default).\n \"\"\"\n if self._verbose:\n if line_feed:\n print(msg)\n else:\n print(msg, end='')\n\n def _bind_socket(self, port):\n \"\"\"\n Bind the server socket to the specified port.\n\n The server listens on all available interfaces (e.g. 127.0.0.1,\n 0.0.0.0, ::1, one of the assigned IPs, etc.). The binding may fail for\n two reasons: either the port is already in use or the user has not\n enough privileges for binding to the specified port. Ports with a\n number less than 1024 are reserved for root.\n :param port: The port of any interface to bind to.\n \"\"\"\n try:\n self.socket.bind(('', port))\n self.socket.setblocking(False)\n self._print('Listening on %s:%d' % (self.socket.getsockname()))\n self.socket.listen(0)\n self._running = True\n except PermissionError:\n sys.stderr.write('Not enough permissions to take port %d' % port)\n sys.stderr.write('ports < 1024 are reserved for root)\\r\\n')\n self.shutdown()\n except OSError:\n sys.stderr.write('Invalid value.')\n sys.stderr.write('Is port %d already in use?\\r\\n' % port)\n self.shutdown()\n\n def _open_new_connection(self, sock, inputs, outputs):\n \"\"\"\n Accept a new connection to the socket.\n\n This method calls socket.accept() and configures the socket.\n It also appends it to the 'inputs'-array and increments the number of\n open connections.\n Note that the 'sock' parameter should be the main socket that is opened\n in self.__init__() respectively self.socket.\n :TODO: check for HTTPS and ignore it\n :param sock: the socket from which the new connection should be\n accepted. Note that this parameter should be the main socket that is\n opened in self.__init__() respectively self.socket.\n :param inputs: the list of all sockets to read from. The new connection\n will be appended to that list.\n :param outputs: This parameter is currently unused, but it is required,\n because the sub-class overridden method needs it.\n \"\"\"\n del outputs\n connection, _ = sock.accept()\n connection.setblocking(False)\n inputs.append(connection)\n self._open_connections += 1\n\n def _discard_new_connection(self, sock):\n \"\"\"\n Discard a new connection on the socket.\n\n The connection is accepted in the first place, but only to send a\n response. This response is the HTTP status code 503 (Service\n Unavailable) and tells the client that the server currently cannot\n handle the request. After it was sent the connection is closed.\n :param sock: the socket from which the new connection should be\n accepted. Note that this parameter should be the main socket that is\n opened in self.__init__() respectively self.socket.\n \"\"\"\n connection, _ = sock.accept()\n response = self._http_response_code(503)\n connection.sendall(response)\n connection.close()\n\n def _close_connection(self, sock, inputs, outputs):\n \"\"\"\n Close a connection.\n\n Closes a socket an removes it from the input and output lists. It also\n decrements the number of open connections.\n :param sock: The connection to remove.\n :param inputs: The list of all sockets to read from. The connection\n will be removed from that list if it is contained.\n :param outputs: The list of all sockets to write to. The connection\n will be removed from that list if it is contained.\n \"\"\"\n if sock in outputs:\n outputs.remove(sock)\n if sock in inputs:\n inputs.remove(sock)\n if sock in self._read_queues:\n del self._read_queues[sock]\n if sock in self._write_queues:\n del self._write_queues[sock]\n sock.close()\n self._open_connections -= 1\n\n def _send_bytes(self, sock, message):\n \"\"\"\n Send some bytes and returns the number of bytes sent.\n\n Has to be in a method, because SecuredFriServer has to override it.\n :param sock: The connection to send the bytes to.\n :param message: The message to send.\n :return: Then number of bytes sent.\n :rtype: integer with a value greater or equal to zero\n \"\"\"\n return sock.send(message)\n\n def _receive_bytes(self, sock, inputs, outputs):\n \"\"\"\n Receives some bytes.\n\n Has to be in a method, because SecuredFriServer has to override it.\n :param sock: The connection to read the bytes from.\n :param inputs: unused. Required, because sub-classes may need it.\n :param outputs: unused. Required, because sub-classes may need it.\n :return: The received bytes.\n :rtype: bytes with a length of up to 1KiB\n \"\"\"\n del inputs\n del outputs\n return sock.recv(1024)\n\n def _generate_response(self, request):\n r\"\"\"\n Generate the HTTP response.\n\n This method checks, if the request_header method used is GET or POST\n and calls the appropriate handler for it. If any other request method\n is used the method returns the 501 Not Implemented header.\n \n Test for PUT request (which should return 501):\n >>> request = b'''PUT /send.php HTTP/1.1\n ... Host: example.com\n ... Connection: close\n ... '''\n >>> FriServer(port=1994, verbose=False)._generate_response(request)\n b'HTTP/1.1 501 Not Implemented\\r\\n\\r\\n'\n\n :param request: The request that the client sent.\n :return: The response from the server to the client.\n :rtype: UTF-8 encoded bytes\n \"\"\"\n request_header = request.splitlines()[0]\n if request_header.startswith(b'GET '):\n return self._generate_get_response(request)\n elif request_header.startswith(b'POST '):\n return self._generate_post_response(request)\n return self._http_response_code(501) + b'\\r\\n'\n\n def _generate_get_response(self, request):\n \"\"\"\n Handle a GET request.\n\n The requested file will be sent. If the requested file is the server's\n root, the file content of index.html is sent instead. All other header\n informations are not respected.\n All plug-ins are executed and if any generates a response that one is\n returned instead of the response of the server (that is not even\n generated then).\n\n Note that the arguments after '?' (and separated by '&') are discarded.\n :param request: The request that the client has sent.\n :return: The generated response that the server sends to the client.\n :rtype: UTF-8 encoded bytes\n \"\"\"\n for plugin in self.plugins:\n try:\n response = plugin.on_get_request(request)\n if response:\n return response\n except:\n print('Plug-in exception: stracktrace follows')\n traceback.print_exc(file=sys.stdout)\n\n request_lines = request.splitlines()\n request_method_fields = request_lines[0].split()\n assert request_method_fields[0] == b'GET'\n assert request_method_fields[2].startswith(b'HTTP')\n\n filename = request_method_fields[1]\n filename = filename.split(b'?')[0]\n if filename == b'/':\n filename = b'/index.html'\n\n return self._generate_file_content_response(filename)\n\n def _generate_post_response(self, request):\n \"\"\"\n Handle a POST request.\n\n The requested file will be sent. If the requested file is the server's\n root, the file content of index.html is sent instead. All other header\n informations are not respected.\n All plug-ins are executed and if any generates a response that one is\n returned instead of the response of the server (that is not even\n generated then).\n :param request: The request that the client has sent.\n :return: The generated response that the server sends to the client.\n :rtype: UTF-8 encoded bytes\n \"\"\"\n for plugin in self.plugins:\n try:\n response = plugin.on_post_request(request)\n if response:\n return response\n except:\n print('Plug-in exception: stracktrace follows')\n traceback.print_exc(file=sys.stdout)\n\n request_lines = request.splitlines()\n request_method_fields = request_lines[0].split()\n assert request_method_fields[0] == b'POST'\n assert request_method_fields[2].startswith(b'HTTP')\n\n return self._http_response_code(510) + b'\\r\\n\\r\\n'\n\n def _http_response_code(self, status_code):\n r\"\"\"\n Generate a HTTP response code header line.\n\n The content of this line is the following:\n b'HTTP/1.1 \\\\r\\\\n'\n No more header content (like Content-Type, Date, etc.) is generated.\n Unknown codes return the code of '501 Not Implemented'.\n\n Some examples:\n >>> server = FriServer(port=1996, verbose=False)\n >>> server._http_response_code(200)\n b'HTTP/1.1 200 OK\\r\\n'\n >>> server._http_response_code(404)\n b'HTTP/1.1 404 Not Found\\r\\n'\n >>> server._http_response_code(501)\n b'HTTP/1.1 501 Not Implemented\\r\\n'\n >>> server._http_response_code(1997)\n b'HTTP/1.1 501 Not Implemented\\r\\n'\n\n :param status_code: The requested HTTP status code.\n :return: The HTTP response header line with the status code.\n :rtype: UTF-8 encoded bytes\n \"\"\"\n status_codes = {\n 200: b'200 OK',\n 301: b'301 Moved Permanently',\n 303: b'303 See Other',\n 400: b'400 Bad Request',\n 404: b'404 Not Found',\n 500: b'500 Internal Server Error',\n 501: b'501 Not Implemented',\n 503: b'503 Service Unavailable'\n }\n\n response = b'HTTP/1.1 '\n response += status_codes.get(status_code, status_codes[501])\n response += b'\\r\\n'\n return response\n\n def _generate_file_content_response(self, path):\n \"\"\"\n Generate the HTTP response for sensing a whole file.\n\n It generates the right HTTP response code, the content-type (MIME-type)\n and appends the file content. This way limits the file size (files with\n a size of more than approximately 5MiB should not delivered this way)!\n If the file could not be found there are two options. If a file with\n the name 'error_404.html' exists then the content of that file is\n returned. If not the 404 status code is returned.\n :param path: The path to the file that is requested.\n :return: The HTTP response: the 200 OK header and file content or the\n 404 header of the file was not found.\n :rtype: UTF-8 encoded bytes\n \"\"\"\n path = self.file_base_path + path\n if os.path.isfile(path):\n file = open(path, 'rb')\n content = file.read()\n response = self._http_response_code(200)\n response += b'Content-Type: '\n response += self._get_mime_type(path)\n response += b'\\r\\n'\n response += b'Content-Length: '\n response += bytes(str(len(content)), 'utf-8')\n response += b'\\r\\n'\n response += b'Date: '\n response += self._get_date()\n response += b'\\r\\n'\n response += b'Last-Modified: '\n response += self._get_modification_time(path)\n response += b'\\r\\n\\r\\n'\n response += content\n return response\n _, extension = os.path.splitext(path)\n if extension == b'.html':\n path = b'/error_404.html'\n path_404 = self.file_base_path + path\n if os.path.isfile(path_404):\n return self._generate_file_content_response(path)\n return self._http_response_code(404) + b'Connection: close\\r\\n\\r\\n'\n\n def _get_modification_time(self, path):\n \"\"\"Return the modification date of a file.\"\"\"\n modification_time = os.path.getmtime(path)\n tm = time.localtime(modification_time)\n return self._http_date_format(tm)\n\n def _get_date(self):\n \"\"\"Return the current date and time. Required for origin servers.\"\"\"\n tm = time.localtime()\n return self._http_date_format(tm)\n\n def _http_date_format(self, tm):\n \"\"\"\n Generate a valid HTTP date.\n\n The date has to have the following format:\n , :: GMT\n \"\"\"\n weekdays = {\n 0: b'Sun',\n 1: b'Mon',\n 2: b'Tue',\n 3: b'Wed',\n 4: b'Thu',\n 5: b'Fri',\n 6: b'Sat'\n }\n months = {\n 1: b'Jan',\n 2: b'Feb',\n 3: b'Mar',\n 4: b'Apr',\n 5: b'May',\n 6: b'Jun',\n 7: b'Jul',\n 8: b'Aug',\n 9: b'Sep',\n 10: b'Oct',\n 11: b'Nov',\n 12: b'Dec'\n }\n return b'%s, %02d %s %4d %02d:%02d:%02d GMT' % (\n weekdays[tm.tm_wday],\n tm.tm_mday,\n months[tm.tm_mon],\n tm.tm_year,\n tm.tm_hour,\n tm.tm_min,\n tm.tm_sec\n )\n\n def _get_mime_type(self, filename):\n \"\"\"\n Return the MIME-type of a file.\n\n The python module mimetypes is used. Note that the map type_map\n requires a string as its key element and returns a string itself, so\n two conversions are necessary.\n\n Some examples:\n >>> server = FriServer(port=1995, verbose=False)\n >>> server._get_mime_type(b'page.html')\n b'text/html'\n >>> server._get_mime_type(b'image.png')\n b'image/png'\n >>> server._get_mime_type(b'unknown-mime.asdf')\n b'application/octet-stream'\n\n :param filename: The path to the file\n :return: The MIME-type of the file if the extension is known or\n 'application/octet-stream' if there is no MIME-type that matches\n :rtype: UTF-8 encoded bytes\n \"\"\"\n _, extension = os.path.splitext(filename)\n try:\n return bytes(mimetypes.types_map[str(extension, 'utf8')], 'utf8')\n except KeyError:\n return b'application/octet-stream'\n","sub_path":"FriServer.py","file_name":"FriServer.py","file_ext":"py","file_size_in_byte":33566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"329590036","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n\n\n@Date : Fri Nov 14 13:20:38 2014 \\n\n@Author : Erwan Ledoux \\n\\n\n\n\n\nThe Rower helps to set rowed lines in a Databaser from pointed attributes,\nready then to be inserted in a table.\n\n\"\"\"\n\n#\nimport ShareYourSystem as SYS\nBaseModuleStr=\"ShareYourSystem.Standards.Modelers.Modeler\"\nDecorationModuleStr=\"ShareYourSystem.Standards.Classors.Classer\"\nSYS.setSubModule(globals())\n#\n\n#\nimport collections\nimport copy\nfrom ShareYourSystem.Standards.Itemizers import Getter\nfrom ShareYourSystem.Standards.Controllers import Controller\n#\n\n#\ndef getRowedDictsListWithTable(_Table):\n\treturn map(\n\t\t\tlambda __Row:\n\t\t\tdict(\n\t\t\t\tzip(\n\t\t\t\t\t_Table.colnames,\n\t\t\t\t\tmap(\n\t\t\t\t\t\tlambda __ColumnStr:\n\t\t\t\t\t\t__Row[__ColumnStr],\n\t\t\t\t\t\t_Table.colnames\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t),\n\t\t\t_Table.iterrows()\n\t\t)\n#\n\n\n#\n@DecorationClass(\n\t**{'ClassingSwitchMethodStrsList':[\"row\"]}\n)\nclass RowerClass(\n\t\t\t\t\tBaseClass\n\t\t\t\t):\n\t\n\tdef default_init(\n\t\t\t\t\tself,\n\t\t\t\t\t_RowKeyStrToColumnStrOrderedDict=None,\n\t\t\t\t\t_RowHdfColumnStrsList=None,\n\t\t\t\t\t_RowingKeyStrsList=None,\n\t\t\t\t\t_RowedMongoPickOrderedDict=None, \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t_RowedHdfPickOrderedDict=None,\n\t\t\t\t\t_RowedMongoIsBoolsList=None,\t \n\t\t\t\t\t_RowedHdfIsBoolsList=None,\t\n\t\t\t\t\t_RowedMongoIsBool=False,\n\t\t\t\t\t_RowedHdfIsBool=False,\n\t\t\t\t\t_RowedMongoIndexInt=-1,\n\t\t\t\t\t_RowedHdfIndexInt=-1,\n\t\t\t\t\t**_KwargVariablesDict\n\t\t\t\t):\n\n\t\t#Call the parent init method\n\t\tBaseClass.__init__(self,**_KwargVariablesDict)\n\t\t\n\tdef do_row(self):\n\t\t\"\"\"\"\"\"\n\t\t\n\t\t#debug\n\t\t'''\n\t\tself.debug(\n\t\t\t[\n\t\t\t\t'We row here'\n\t\t\t]\n\t\t)\n\t\t'''\n\n\t\t#Check\t\n\t\tif self.ModeledParentControllerDeriveModelerVariable!=None:\n\t\t\t\n\t\t\t#debug\n\t\t\t'''\n\t\t\tself.ModeledParentControllerDeriveModelerVariable.debug('ParentSpeaking...')\n\t\t\t'''\n\n\t\t\t#Check\n\t\t\tif self.ModelMongoBool:\n\n\t\t\t\t#Update\n\t\t\t\tself.RowedMongoPickOrderedDict.update(\n\t\t\t\t\tzip(\n\t\t\t\t\t\tself.RowingKeyStrsList,\n\t\t\t\t\t\t#self.ModeledParentControllerDeriveModelerVariable[Getter.GetMapStr](\n\t\t\t\t\t\t#\t*self.ModelKeyStrsList\n\t\t\t\t\t\t#).ItemizedMapValueVariablesList\n\t\t\t\t\t\tself.ModeledParentControllerDeriveModelerVariable.mapGet(\n\t\t\t\t\t\t\tself.ModelKeyStrsList\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t\t\t#debug\n\t\t\t\t'''\n\t\t\t\tself.debug(\n\t\t\t\t\t[\n\t\t\t\t\t\t('self.',self,[\n\t\t\t\t\t\t\t\t\t\t'RowedMongoPickOrderedDict',\n\t\t\t\t\t\t\t\t\t\t'ModeledMongoCollection'\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t),\n\t\t\t\t\t\t'list(self.ModeledMongoCollection.find()) is '+SYS._str(\n\t\t\t\t\t\t\tlist(self.ModeledMongoCollection.find()))\n\t\t\t\t\t]\n\t\t\t\t)\n\t\t\t\t'''\n\n\t\t\t\t#Check if it was already rowed\n\t\t\t\tself.RowedMongoIsBoolsList=map(\n\t\t\t\t\t\tlambda __Row:\n\t\t\t\t\t\tall(\n\t\t\t\t\t\t\tmap(\n\t\t\t\t\t\t\t\t\tlambda __RowedItemTuple:\n\t\t\t\t\t\t\t\t\tSYS.getIsEqualBool(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__Row[__RowedItemTuple[0]],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__RowedItemTuple[1]\n\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tself.RowedMongoPickOrderedDict.items()\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t),\n\t\t\t\t\t\tself.ModeledMongoCollection.find()\n\t\t\t\t\t)\n\n\t\t\t\t#debug\n\t\t\t\t'''\n\t\t\t\tself.debug(\n\t\t\t\t\t[\n\t\t\t\t\t\t('self.',self,[\n\t\t\t\t\t\t\t'RowedMongoIsBoolsList'\n\t\t\t\t\t\t]),\n\t\t\t\t\t\t'Maybe there is now row or no rowing Key str ...so it is false already',\n\t\t\t\t\t\t'len(self.RowedMongoIsBoolsList)==0 is ',\n\t\t\t\t\t\tstr(len(self.RowedMongoIsBoolsList)==0),\n\t\t\t\t\t\t'len(self.RowedMongoPickOrderedDict)==0 is',\n\t\t\t\t\t\tstr(len(self.RowedMongoPickOrderedDict))\n\t\t\t\t\t]\n\t\t\t\t)\n\t\t\t\t'''\n\n\t\t\t\t#set\n\t\t\t\tif len(self.RowedMongoIsBoolsList)==0 or len(self.RowedMongoPickOrderedDict)==0:\n\t\t\t\t\tself.RowedMongoIsBool=False\n\t\t\t\telse:\n\t\t\t\t\tself.RowedMongoIsBool=any(self.RowedMongoIsBoolsList)\n\n\t\t\t\t#Init to the len of the table\n\t\t\t\tself.RowedMongoIndexInt=len(self.RowedMongoIsBoolsList)\n\t\t\t\t\n\t\t\t\t#debug\n\t\t\t\t'''\n\t\t\t\tself.debug(('self.',self,[\n\t\t\t\t\t\t'RowedMongoIndexInt',\n\t\t\t\t\t\t'RowedMongoIsBool'\n\t\t\t\t\t]))\n\t\t\t\t'''\n\t\t\t\t\n\t\t\t\t#But maybe find a last index\n\t\t\t\tif self.RowedMongoIsBool: \n\t\t\t\t\tif len(self.RowedMongoIsBoolsList)>0:\n\t\t\t\t\t\tself.RowedMongoIndexInt=self.RowedMongoIsBoolsList.index(True)\n\n\t\t\t\t#debug\n\t\t\t\t'''\n\t\t\t\tself.debug(('self.',self,['RowedMongoIsBool','RowedMongoIndexInt']))\n\t\t\t\t'''\n\n\t\t\t#Check\n\t\t\tif self.ModelHdfBool:\n\n\t\t\t\t#debug\n\t\t\t\t'''\n\t\t\t\tself.debug('This is a hdf row here')\n\t\t\t\t'''\n\n\t\t\t\t#/##################/#\n\t\t\t\t# First check the good size\n\t\t\t\t#\n\n\t\t\t\tif self.RowKeyStrToColumnStrOrderedDict==None or len(\n\t\t\t\t\tself.ModelingDescriptionTuplesList)!=len(\n\t\t\t\t\tself.RowKeyStrToColumnStrOrderedDict):\n\n\t\t\t\t\t#Bind with RowGetStrToColumnStrOrderedDict setting\n\t\t\t\t\tself.RowKeyStrToColumnStrOrderedDict=collections.OrderedDict(\n\t\t\t\t\t\t\tmap(\n\t\t\t\t\t\t\t\tlambda _ModelingSealTuple:\n\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t_ModelingSealTuple[0],\n\t\t\t\t\t\t\t\t\t_ModelingSealTuple[1]\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tself._ModelingDescriptionTuplesList\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t)\n\n\t\t\t\t\t#Bind with \n\t\t\t\t\tself.RowHdfColumnStrsList=map(\n\t\t\t\t\t\t\tlambda __RowingKeyStr:\n\t\t\t\t\t\t\tself.RowKeyStrToColumnStrOrderedDict[__RowingKeyStr],\n\t\t\t\t\t\t\tself.RowingKeyStrsList\n\t\t\t\t\t\t)\n\n\t\t\t\t#/#################/#\n\t\t\t\t# Pick the values to be rowed in the hdf variables\n\t\t\t\t#\n\n\t\t\t\t#debug\n\t\t\t\t'''\n\t\t\t\tself.debug(\n\t\t\t\t\t('self.',self,[\n\t\t\t\t\t\t'RowingKeyStrsList',\n\t\t\t\t\t\t'RowHdfColumnStrsList'\n\t\t\t\t\t\t])\n\t\t\t\t)\n\t\t\t\t'''\n\t\t\t\t\n\t\t\t\t#Update\n\t\t\t\tself.RowedHdfPickOrderedDict.update(\n\t\t\t\t\tzip(\n\t\t\t\t\t\tself.RowHdfColumnStrsList,\n\t\t\t\t\t\t#self.ModeledParentControllerDeriveModelerVariable[Getter.GetMapStr](\n\t\t\t\t\t\t#\t*self.RowingKeyStrsList\n\t\t\t\t\t\t#).ItemizedMapValueVariablesList\n\t\t\t\t\t\tself.ModeledParentControllerDeriveModelerVariable.mapGet(\n\t\t\t\t\t\t\tself.RowingKeyStrsList\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t)\n\n\t\t\t\t#debug\n\t\t\t\t'''\n\t\t\t\tself.debug(\n\t\t\t\t\t[\n\t\t\t\t\t\t'Ok we have almost end the row',\n\t\t\t\t\t\t('self.',self,[\n\t\t\t\t\t\t\t\t\t'RowedHdfPickOrderedDict',\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t),\n\t\t\t\t\t\t'Check now if it is a new row'\n\t\t\t\t\t]\n\t\t\t\t)\n\t\t\t\t'''\n\n\t\t\t\t#/#################/#\n\t\t\t\t# Check if it is a new row\n\t\t\t\t#\n\n\t\t\t\t#Check if it was already rowed\n\t\t\t\tself.RowedHdfIsBoolsList=map(\n\t\t\t\t\t\tlambda __Row:\n\t\t\t\t\t\tall(\n\t\t\t\t\t\t\tmap(\n\t\t\t\t\t\t\t\t\tlambda __RowedItemTuple:\n\t\t\t\t\t\t\t\t\tSYS.getIsEqualBool(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__Row[__RowedItemTuple[0]],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__RowedItemTuple[1]\n\t\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\tself.RowedHdfPickOrderedDict.items()\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\tself.ModeledHdfTable.iterrows()\n\t\t\t\t\t)\n\n\t\t\t\t#debug\n\t\t\t\t'''\n\t\t\t\tself.debug(\n\t\t\t\t\t[\n\t\t\t\t\t\t'Is is a new row ?',\n\t\t\t\t\t\t('self.',self,['RowedHdfIsBoolsList']),\n\t\t\t\t\t\t'Maybe there is now row or no rowing Key str ...so it is false already',\n\t\t\t\t\t\t'len(self.RowedHdfIsBoolsList)==0 is ',\n\t\t\t\t\t\tstr(len(self.RowedHdfIsBoolsList)==0),\n\t\t\t\t\t\t'len(self.RowedHdfPickOrderedDict)==0 is',\n\t\t\t\t\t\tstr(len(self.RowedHdfPickOrderedDict))\n\t\t\t\t\t]\n\t\t\t\t)\t\n\t\t\t\t'''\n\n\t\t\t\t#set\n\t\t\t\tif len(self.RowedHdfIsBoolsList)==0 or len(self.RowedHdfPickOrderedDict)==0:\n\t\t\t\t\tself.RowedHdfIsBool=False\n\t\t\t\telse:\n\t\t\t\t\tself.RowedHdfIsBool=any(self.RowedHdfIsBoolsList)\n\n\t\t\t\t#Init to the len of the table\n\t\t\t\tself.RowedHdfIndexInt=self.ModeledHdfTable.nrows\n\n\t\t\t\t#But maybe find a last index\n\t\t\t\tif self.RowedHdfIsBool: \n\t\t\t\t\tif len(self.RowedHdfIsBoolsList)>0:\n\t\t\t\t\t\tself.RowedHdfIndexInt=self.RowedHdfIsBoolsList.index(True)\n\n\t\t\t\t#debug\n\t\t\t\t'''\n\t\t\t\tself.debug(\n\t\t\t\t\t[\n\t\t\t\t\t\t('self.',self,['RowedHdfIsBool','RowedHdfIndexInt'])\n\t\t\t\t\t]\n\t\t\t\t)\n\t\t\t\t'''\n#\n\n#\nController.ModelsClass.ManagingValueClass=RowerClass\n#\n\n#\nRowerClass.PrintingClassSkipKeyStrsList.extend(\n\t[\n\t\t'RowingKeyStrsList',\n\t\t'RowHdfColumnStrsList',\t\n\t\t'RowKeyStrToColumnStrOrderedDict',\n\t\t'RowedMongoPickOrderedDict',\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t'RowedHdfPickOrderedDict',\n\t\t'RowedMongoIsBoolsList',\n\t\t'RowedHdfIsBoolsList',\n\t\t'RowedMongoIsBool',\n\t\t'RowedHdfIsBool',\n\t\t'RowedMongoIndexInt',\n\t\t'RowedHdfIndexInt'\n\t]\n)\n#\n","sub_path":"Pythonlogy/build/lib/ShareYourSystem/Standards/Modelers/Rower/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"87676941","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nfrom sklearn.model_selection import RepeatedKFold\r\nfrom sklearn.metrics import r2_score\r\nfrom sklearn import linear_model\r\nfrom feature_selection_ga import FeatureSelectionGA\r\n\r\n\r\n# Creamos una función fitness personalizada\r\nclass CustomFitnessFunctionClass:\r\n def __init__(self,n_total_features,n_splits = 5, alpha=0.01, *args,**kwargs):\r\n \"\"\"\r\n Parameters\r\n -----------\r\n n_total_features :int\r\n \tTotal number of features N_t.\r\n n_splits :int, default = 5\r\n Number of splits for cv\r\n alpha :float, default = 0.01\r\n Tradeoff between the classifier performance P and size of \r\n feature subset N_f with respect to the total number of features\r\n N_t.\r\n \r\n verbose: 0 or 1\r\n \"\"\"\r\n self.n_splits = n_splits\r\n self.alpha = alpha\r\n self.n_total_features = n_total_features\r\n\r\n def calculate_fitness(self,model,x,y):\r\n alpha = self.alpha\r\n total_features = self.n_total_features\r\n\r\n cv_set = np.repeat(-1.,x.shape[0])\r\n skf = RepeatedKFold(n_splits = self.n_splits)\r\n for train_index,test_index in skf.split(x,y):\r\n x_train,x_test = x[train_index],x[test_index]\r\n y_train,y_test = y[train_index],y[test_index]\r\n if x_train.shape[0] != y_train.shape[0]:\r\n raise Exception()\r\n model.fit(x_train,y_train)\r\n predicted_y = model.predict(x_test)\r\n cv_set[test_index] = predicted_y\r\n \r\n # P = accuracy_score(y, cv_set)\r\n P = r2_score(y, cv_set)\r\n fitness = (alpha*(1.0 - P) + (1.0 - alpha)*(1.0 - (x.shape[1])/total_features))\r\n return fitness\r\n\r\n\r\n\r\ndef ga(target, firma, control):\r\n print(\"Ejecutando Genetic Algorithm...\")\r\n # Grupo control 2014 ###################################\r\n x = firma\r\n y = control.loc[:, target]\r\n model = linear_model.LinearRegression()\r\n ff = CustomFitnessFunctionClass(n_total_features=x.shape[1], \r\n n_splits=3,\r\n alpha=0.05)\r\n fsga = FeatureSelectionGA(model, x, y, ff_obj = ff)\r\n pop = fsga.generate(5000)\r\n print(pop)\r\n \r\n return\r\n\r\n\r\n","sub_path":"ga_old.py","file_name":"ga_old.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"148172438","text":" \nfrom django.urls import path, include\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name = 'index'),\n path('homepage/', views.homepage, name = 'homepage'),\n path('register/', views.registerUser, name = 'register'),\n path('login/', views.loginUser, name = 'login'),\n path('logout/', views.logoutUser, name = 'logout'),\n path('example/',views.example,name='example'),\n path('fileload/', views.fileload, name='fileload'),\n path('viewfile/', views.viewfile, name='viewfile'),\n path('search_file/',views.search_file, name='search_file'),\n path('contact/', views.contact,name='contact'),\n path('upload_file/', views.upload_file, name='upload_file'),\n path('viewfile/', views.delete_doc, name='delete_doc'),\n ]\n\n","sub_path":"file/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"239731944","text":"import time\ndef my_timer(f):\n def tmp(*args, **kwargs):\n start_time = time.time()\n result = f(*args, **kwargs)\n delta_time = time.time() - start_time\n print ('Время выполнения %f' % delta_time)\n return result\n return tmp\n#@my_timer\n#def my_sum(x, y):\n# return x + y\n#\n#print (my_sum(4, 5))\n\ndef logging(func):\n def wrapper(*args, **kwargs):\n result = func(*args, **kwargs)\n with open('my_file', 'a') as f:\n f.write(\n 'function name: {func_name} with result = {result}. Start at {start_time}\\n\\n'.format(func_name=func.__name__, result=result, start_time=time.ctime(time.time())\n )\n )\n f.close()\n return result \n return wrapper\n\n@my_timer\n@logging\ndef my_sum(x, y, z):\n return x + y + z\n\nprint (my_sum(4, 5, 7))\n","sub_path":"My_work/time_dec.py","file_name":"time_dec.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"640297868","text":"import pafy\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nfrom threading import Thread\r\nfrom tkinter import font\r\nfrom ttkthemes import ThemedStyle\r\n\r\n\r\nwin = tk.Tk()\r\nwin.title(\"Youtube Downloader\")\r\nwin.resizable(False, False)\r\nwin.iconbitmap(\"youtube.ico\")\r\n\r\nstyle = ThemedStyle(win)\r\nstyle.set_theme(\"equilux\")\r\n\r\n\r\nmyFont = font.Font(family=\"Comic Sans MS\")\r\n\r\nstyle_main = ttk.Style(win)\r\nfont = font.Font(family=\"Comic Sans MS\", size=10, weight=\"bold\")\r\nstyle_main.configure(\"TButton\", font=font)\r\n\r\n\r\nmain_frame = ttk.LabelFrame(win)\r\nmain_frame.grid(row=0, column=0, padx=10, pady=10)\r\nmain_frame[\"padding\"] = [20]\r\n# main_frame[\"font\"] = font\r\n\r\n\r\ndef startDownloadingThread(file_handler):\r\n run_thread = Thread(target=startDownloading, args=(file_handler,))\r\n run_thread.start()\r\n\r\n\r\ndef startDownloading(file_handler):\r\n radSel = radVar.get()\r\n if radSel == 0:\r\n abc = file_handler.getbest()\r\n elif radSel == 1:\r\n abc = file_handler.getbestvideo(preftype=\"mp4\", ftypestrict=False)\r\n elif radSel == 2:\r\n abc = file_handler.getbestaudio()\r\n abc.download()\r\n result_label.configure(\r\n text=f\"{file_handler.title}\\nDuration : {file_handler.duration}\\n\\n\\nDownloaded\"\r\n )\r\n\r\n\r\ndef SearchFor():\r\n url = entered_url.get()\r\n if url == \"\":\r\n result_label.configure(text=\"Seems like you haven't entered an link yet\")\r\n else:\r\n try:\r\n file_handler = pafy.new(url)\r\n video_title = file_handler.title\r\n video_duration = file_handler.duration\r\n startDownloadingThread(file_handler) # Download in a separate thread\r\n\r\n result_label.configure(\r\n text=f\"{video_title}\\nDuration : {video_duration}\\n\\n\\nDownload in progress\"\r\n )\r\n except:\r\n result_label.configure(text=\"Please enter a valid youtube link\")\r\n\r\n\r\ndef change_theme(a):\r\n theme = selected_theme.get()\r\n result_label.configure(text=\"Changed theme to \" + theme)\r\n style.set_theme(theme)\r\n if theme == \"scidpink\":\r\n win.configure(background=\"#F72D60\")\r\n elif theme == \"scidmint\":\r\n win.configure(background=\"#7EAF51\")\r\n elif theme == \"scidblue\":\r\n win.configure(background=\"#41A5E1\")\r\n elif theme == \"black\":\r\n win.configure(background=\"#323232\")\r\n elif theme == \"kroc\":\r\n win.configure(background=\"#FFA66A\")\r\n else:\r\n win.configure(background=\"#f05b5b\")\r\n\r\n\r\nurl_label = ttk.Label(\r\n main_frame,\r\n text=\"Enter youtube link here:\",\r\n font=(\"Comic Sans MS\", 10, \"bold italic\"),\r\n)\r\nurl_label.grid(row=0, column=0, padx=5, pady=10, sticky=\"W\")\r\n\r\n\r\nselected_theme = tk.StringVar()\r\nnumber_field = ttk.Combobox(\r\n main_frame,\r\n width=20,\r\n textvariable=selected_theme,\r\n state=\"readonly\",\r\n)\r\nnumber_field[\"values\"] = (\r\n \"xpnative\",\r\n \"kroc\",\r\n \"itft1\",\r\n \"blue\",\r\n \"equilux\",\r\n \"scidpink\",\r\n \"scidblue\",\r\n \"scidmint\",\r\n \"black\",\r\n)\r\nnumber_field.current(4)\r\nnumber_field.grid(row=0, column=2, pady=10, sticky=\"E\")\r\nnumber_field.bind(\"<>\", change_theme)\r\n\r\n\r\nentered_url = tk.StringVar()\r\nentry_box = ttk.Entry(main_frame, width=100, textvariable=entered_url)\r\nentry_box.grid(row=1, column=0, padx=5, pady=10, sticky=\"WE\", columnspan=3)\r\n\r\n\r\nradVar = tk.IntVar()\r\nrad0 = ttk.Radiobutton(\r\n main_frame,\r\n text=\"VIDEO\",\r\n variable=radVar,\r\n value=0,\r\n)\r\nrad1 = ttk.Radiobutton(\r\n main_frame,\r\n text=\"VIDEO ONLY\",\r\n variable=radVar,\r\n value=1,\r\n)\r\nrad2 = ttk.Radiobutton(\r\n main_frame,\r\n text=\"AUDIO ONLY\",\r\n variable=radVar,\r\n value=2,\r\n)\r\nrad0.grid(row=2, column=0, sticky=\"W\")\r\nrad1.grid(row=2, column=1, sticky=\"W\")\r\nrad2.grid(row=2, column=2, sticky=\"E\")\r\n\r\n\r\ndownload_button = ttk.Button(main_frame, text=\"Download\", command=SearchFor)\r\ndownload_button.grid(row=3, column=0, pady=10, columnspan=3)\r\n\r\nresult_label = ttk.Label(\r\n main_frame,\r\n text=\"Let's get started\",\r\n font=(\"Comic Sans MS\", 12, \"bold italic\"),\r\n)\r\nresult_label.grid(row=4, column=0, rowspan=10, columnspan=3)\r\nentry_box.focus()\r\nwin.configure(background=\"#f05b5b\")\r\n# win.attributes(\"-alpha\", 0.9) # transparency\r\n\r\n\r\nwin.mainloop()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"134609427","text":"# Compute MMD distance using pytorch\n\nimport torch\nimport torch.nn as nn\n\n\nclass MMD_loss(nn.Module):\n def __init__(self, kernel_type='rbf', kernel_mul=2.0, kernel_num=5):\n super(MMD_loss, self).__init__()\n self.kernel_num = kernel_num\n self.kernel_mul = kernel_mul\n self.fix_sigma = None\n self.kernel_type = kernel_type\n\n def guassian_kernel(self, source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None):\n n_samples = int(source.size()[0]) + int(target.size()[0])\n total = torch.cat([source, target], dim=0)\n total0 = total.unsqueeze(0).expand(\n int(total.size(0)), int(total.size(0)), int(total.size(1)))\n total1 = total.unsqueeze(1).expand(\n int(total.size(0)), int(total.size(0)), int(total.size(1)))\n L2_distance = ((total0-total1)**2).sum(2)\n if fix_sigma:\n bandwidth = fix_sigma\n else:\n bandwidth = torch.sum(L2_distance.data) / (n_samples**2-n_samples)\n bandwidth /= kernel_mul ** (kernel_num // 2)\n bandwidth_list = [bandwidth * (kernel_mul**i)\n for i in range(kernel_num)]\n kernel_val = [torch.exp(-L2_distance / bandwidth_temp)\n for bandwidth_temp in bandwidth_list]\n return sum(kernel_val)\n\n def linear_mmd2(self, f_of_X, f_of_Y):\n loss = 0.0\n delta = f_of_X.float().mean(0) - f_of_Y.float().mean(0)\n loss = delta.dot(delta.T)\n return loss\n\n def forward(self, source, target):\n if self.kernel_type == 'linear':\n return self.linear_mmd2(source, target)\n elif self.kernel_type == 'rbf':\n batch_size = int(source.size()[0])\n kernels = self.guassian_kernel(\n source, target, kernel_mul=self.kernel_mul, kernel_num=self.kernel_num, fix_sigma=self.fix_sigma)\n XX = torch.mean(kernels[:batch_size, :batch_size])\n YY = torch.mean(kernels[batch_size:, batch_size:])\n XY = torch.mean(kernels[:batch_size, batch_size:])\n YX = torch.mean(kernels[batch_size:, :batch_size])\n loss = torch.mean(XX + YY - XY - YX)\n return loss\n","sub_path":"code/distance/mmd_pytorch.py","file_name":"mmd_pytorch.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"202652864","text":"import sys\r\nimport random\r\n# random.seed(0)\r\n\r\ndef CSPGenerator(N, M, K, output_file_path):\r\n colors = range(K)\r\n variables = [(i, random.choice(colors)) for i in range(N)]\r\n\r\n variables_by_color = []\r\n for c in colors:\r\n vars = [v for v in variables if v[1] == c]\r\n variables_by_color.append(vars)\r\n\r\n valid_colors = [v[0][1] for v in variables_by_color if len(v) > 0]\r\n if len(valid_colors) <= 1 and M>0:\r\n return False\r\n\r\n valid_csps = []\r\n for c1 in valid_colors:\r\n for c2 in valid_colors:\r\n if c1>=c2:\r\n continue\r\n for var1 in variables_by_color[c1]:\r\n for var2 in variables_by_color[c2]:\r\n valid_csps.append([var1[0], var2[0]])\r\n\r\n if len(valid_csps) < M:\r\n return False\r\n csps = random.sample(valid_csps, M)\r\n with open(output_file_path, 'w') as f:\r\n f.write('{} {} {}'.format(N,M,K))\r\n if len(csps) > 0:\r\n for csp in csps:\r\n f.write('\\n{} {}'.format(csp[0], csp[1]))\r\n return True\r\n\r\nif __name__ == \"__main__\":\r\n N = int(sys.argv[1])\r\n M = int(sys.argv[2])\r\n K = int(sys.argv[3])\r\n output_file_path = sys.argv[4]\r\n solvable = 1\r\n\r\n if len(sys.argv) > 5:\r\n solvable = int(sys.argv[5])\r\n\r\n if solvable == 0:\r\n with open(output_file_path, 'w') as f:\r\n f.write('{} {} {}'.format(N, M, K))\r\n for m in range(M):\r\n csp = random.sample(range(N), 2)\r\n f.write('\\n{} {}'.format(csp[0], csp[1]))\r\n else:\r\n trial = 1000\r\n\r\n for t in range(trial):\r\n status = CSPGenerator(N, M, K, output_file_path)\r\n if status:\r\n break\r\n\r\n if not status:\r\n print(\"failed to create csp for input parameters\")","sub_path":"A2 (Given files)/CSPGenerator.py","file_name":"CSPGenerator.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"352874042","text":"# Copyright (c) 2018 European Organization for Nuclear Research.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport mock\n\nfrom oslo_utils import uuidutils\n\nfrom magnum.api.controllers.v1 import nodegroup as api_nodegroup\nimport magnum.conf\nfrom magnum import objects\nfrom magnum.tests import base\nfrom magnum.tests.unit.api import base as api_base\nfrom magnum.tests.unit.api import utils as apiutils\nfrom magnum.tests.unit.db import utils as db_utils\nfrom magnum.tests.unit.objects import utils as obj_utils\n\nCONF = magnum.conf.CONF\n\n\nclass TestNodegroupObject(base.TestCase):\n def test_nodegroup_init(self):\n nodegroup_dict = apiutils.nodegroup_post_data()\n del nodegroup_dict['node_count']\n del nodegroup_dict['min_node_count']\n del nodegroup_dict['max_node_count']\n nodegroup = api_nodegroup.NodeGroup(**nodegroup_dict)\n self.assertEqual(1, nodegroup.node_count)\n self.assertEqual(1, nodegroup.min_node_count)\n self.assertIsNone(nodegroup.max_node_count)\n\n\nclass TestListNodegroups(api_base.FunctionalTest):\n _expanded_attrs = [\"id\", \"project_id\", \"docker_volume_size\", \"labels\",\n \"node_addresses\", \"links\"]\n\n _nodegroup_attrs = [\"uuid\", \"name\", \"flavor_id\", \"node_count\", \"role\",\n \"is_default\", \"image_id\", \"min_node_count\",\n \"max_node_count\"]\n\n def setUp(self):\n super(TestListNodegroups, self).setUp()\n obj_utils.create_test_cluster_template(self.context)\n self.cluster_uuid = uuidutils.generate_uuid()\n obj_utils.create_test_cluster(\n self.context, uuid=self.cluster_uuid)\n self.cluster = objects.Cluster.get_by_uuid(self.context,\n self.cluster_uuid)\n\n def _test_list_nodegroups(self, cluster_id, filters=None, expected=None):\n url = '/clusters/%s/nodegroups' % cluster_id\n if filters is not None:\n filter_list = ['%s=%s' % (k, v) for k, v in filters.items()]\n url += '?' + '&'.join(f for f in filter_list)\n response = self.get_json(url)\n if expected is None:\n expected = []\n ng_uuids = [ng['uuid'] for ng in response['nodegroups']]\n self.assertEqual(expected, ng_uuids)\n for ng in response['nodegroups']:\n self._verify_attrs(self._nodegroup_attrs, ng)\n self._verify_attrs(self._expanded_attrs, ng, positive=False)\n\n def test_get_all(self):\n expected = [ng.uuid for ng in self.cluster.nodegroups]\n self._test_list_nodegroups(self.cluster_uuid, expected=expected)\n\n def test_get_all_by_name(self):\n expected = [ng.uuid for ng in self.cluster.nodegroups]\n self._test_list_nodegroups(self.cluster.name, expected=expected)\n\n def test_get_all_by_name_non_default_ngs(self):\n db_utils.create_test_nodegroup(cluster_id=self.cluster_uuid,\n name='non_default_ng')\n expected = [ng.uuid for ng in self.cluster.nodegroups]\n self._test_list_nodegroups(self.cluster.name, expected=expected)\n\n def test_get_all_by_role(self):\n filters = {'role': 'master'}\n expected = [self.cluster.default_ng_master.uuid]\n self._test_list_nodegroups(self.cluster.name, filters=filters,\n expected=expected)\n filters = {'role': 'worker'}\n expected = [self.cluster.default_ng_worker.uuid]\n self._test_list_nodegroups(self.cluster.name, filters=filters,\n expected=expected)\n\n def test_get_all_by_non_existent_role(self):\n filters = {'role': 'non-existent'}\n self._test_list_nodegroups(self.cluster.name, filters=filters)\n\n @mock.patch(\"magnum.common.policy.enforce\")\n @mock.patch(\"magnum.common.context.make_context\")\n def test_get_all_as_admin(self, mock_context, mock_policy):\n temp_uuid = uuidutils.generate_uuid()\n obj_utils.create_test_cluster(self.context, uuid=temp_uuid,\n project_id=temp_uuid)\n self.context.is_admin = True\n self.context.all_tenants = True\n cluster = objects.Cluster.get_by_uuid(self.context, temp_uuid)\n expected = [ng.uuid for ng in cluster.nodegroups]\n self._test_list_nodegroups(cluster.uuid, expected=expected)\n\n def test_get_all_non_existent_cluster(self):\n response = self.get_json('/clusters/not-here/nodegroups',\n expect_errors=True)\n self.assertEqual(404, response.status_code)\n\n def test_get_one(self):\n worker = self.cluster.default_ng_worker\n url = '/clusters/%s/nodegroups/%s' % (self.cluster.uuid, worker.uuid)\n response = self.get_json(url)\n self.assertEqual(worker.name, response['name'])\n self._verify_attrs(self._nodegroup_attrs, response)\n self._verify_attrs(self._expanded_attrs, response)\n\n def test_get_one_non_existent_ng(self):\n url = '/clusters/%s/nodegroups/not-here' % self.cluster.uuid\n response = self.get_json(url, expect_errors=True)\n self.assertEqual(404, response.status_code)\n\n @mock.patch(\"magnum.common.policy.enforce\")\n @mock.patch(\"magnum.common.context.make_context\")\n def test_get_one_as_admin(self, mock_context, mock_policy):\n temp_uuid = uuidutils.generate_uuid()\n obj_utils.create_test_cluster(self.context, uuid=temp_uuid,\n project_id=temp_uuid)\n self.context.is_admin = True\n self.context.all_tenants = True\n cluster = objects.Cluster.get_by_uuid(self.context, temp_uuid)\n worker = cluster.default_ng_worker\n url = '/clusters/%s/nodegroups/%s' % (cluster.uuid, worker.uuid)\n response = self.get_json(url)\n self.assertEqual(worker.name, response['name'])\n self._verify_attrs(self._nodegroup_attrs, response)\n self._verify_attrs(self._expanded_attrs, response)\n\n\nclass TestNodeGroupPolicyEnforcement(api_base.FunctionalTest):\n def setUp(self):\n super(TestNodeGroupPolicyEnforcement, self).setUp()\n obj_utils.create_test_cluster_template(self.context)\n self.cluster_uuid = uuidutils.generate_uuid()\n obj_utils.create_test_cluster(\n self.context, uuid=self.cluster_uuid)\n self.cluster = objects.Cluster.get_by_uuid(self.context,\n self.cluster_uuid)\n\n def _common_policy_check(self, rule, func, *arg, **kwarg):\n self.policy.set_rules({rule: \"project:non_fake\"})\n response = func(*arg, **kwarg)\n self.assertEqual(403, response.status_int)\n self.assertEqual('application/json', response.content_type)\n self.assertTrue(\n \"Policy doesn't allow %s to be performed.\" % rule,\n response.json['errors'][0]['detail'])\n\n def test_policy_disallow_get_all(self):\n self._common_policy_check(\n \"nodegroup:get_all\", self.get_json,\n '/clusters/%s/nodegroups' % self.cluster_uuid, expect_errors=True)\n\n def test_policy_disallow_get_one(self):\n worker = self.cluster.default_ng_worker\n self._common_policy_check(\n \"nodegroup:get\", self.get_json,\n '/clusters/%s/nodegroups/%s' % (self.cluster.uuid, worker.uuid),\n expect_errors=True)\n","sub_path":"magnum/tests/unit/api/controllers/v1/test_nodegroup.py","file_name":"test_nodegroup.py","file_ext":"py","file_size_in_byte":7949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"540452578","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns=[\n path(\"nuova_sezione\",views.CreaSezioneViewCB.as_view(),name=\"nuova_sezione\"),\n path(\"home\",views.SessionListViewCB.as_view(),name=\"home_forum\"),\n path(\"sezione/\",views.DettaglioSezioneView,name=\"dettaglio_sezione\"),\n path(\"sezione//nuova_discussione\",views.CreaDiscussioneView,name=\"nuova_discussione\"),\n path(\"discussione/\",views.DettagliDiscussioneView,name=\"dettaglio_discussione\"),\n path(\"discussione//rispondi\",views.NuovoPostView,name=\"rispondi_a_discussione\"),\n path('utente/', views.PostsUtenteView, name='posts_utente'),\n path(\"discussione//cancella_post/\",views.DeletePostView.as_view(),name=\"cancella_post\"),\n path(\"discussione//modifica_post/\",views.UpdatePostView.as_view(),name=\"modifica_post\"),\n]\n","sub_path":"GenericProject/appForum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"51520675","text":"from django.urls import path\nfrom django.views.generic.base import TemplateView\n\nfrom .views import (\n home,\n my_logout,\n HomePageView,\n MyView,\n)\n\nurlpatterns = [\n path('', home, name=\"home\"),\n path('logout/', my_logout, name=\"logout\"),\n\n # Não há necessidade de declarar uma view - Serve apenas para servir conteúdo html\n path('home2/', TemplateView.as_view(template_name='home2.html')),\n\n # Se quiser ler / injetar contexto é necessário criar sua própria view\n path('home3/', HomePageView.as_view(template_name='home3.html')),\n\n path('home3/', HomePageView.as_view(template_name='home3.html')),\n\n path('view/', MyView.as_view()),\n]","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"465417397","text":"import tensorflow as tf\nimport numpy as np \nimport random\nimport math\nfrom matplotlib import pyplot as plt\nimport os\nimport copy\nimport numpy as np \n#from tensorflow.contrib import rnn\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.framework import dtypes\nimport numpy as np \nimport pandas as pd\nimport dataset_2019_9_19 as data_helper\n\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG,#控制台打印的日志级别\n filename='./logs/order_system_web.log',\n filemode='a',##模式,有w和a,w就是写模式,每次都会重新写日志,覆盖之前的日志\n #a是追加模式,默认如果不写的话,就是追加模式\n format='%(asctime)s - %(pathname)s[line:%(lineno)d] -%(funcName)s: %(message)s'\n #日志格式\n )\n\n\ntest=True\n#test=False\nif test:\n train_x,train_y,val_x,val_y,predicts=data_helper.get_data(val_pct=0.2)\n ###train_x.shape=(7220, 60, 31) train_y.shape=(7220, 7, 1)\n val_x,val_y,predicts=np.array(val_x),np.array(val_y),np.array(predicts)\n index=[e for e in range(len(train_x))]\n np.random.shuffle(index)\n train_x=train_x[index,:]\n train_y=train_y[index,:]\n \n x_train_name_date=[]\n for e in range(len(train_x)):\n name_date=train_x[e][0][:2]\n x_train_name_date.append([name_date[0],name_date[1]])\n x_train_name_date=np.array(x_train_name_date)\n \n x_val_name_date=[]\n for e in range(len(val_x)):\n name_date=val_x[e][0][:2]\n x_val_name_date.append([name_date[0],name_date[1]])\n x_val_name_date=np.array(x_val_name_date)\n \n x_pred_name_date=[]\n for e in range(len(predicts)):\n name_date=predicts[e][0][:2]\n x_pred_name_date.append([name_date[0],name_date[1]])\n x_pred_name_date=np.array(x_pred_name_date)\n \n train_x=train_x[:,:,2:]\n if len(val_x)>0:\n val_x=val_x[:,:,2:]\n predicts=predicts[:,:,2:]\n \n \n\ndef generate_train_samples(batch_size):\n data_len=train_x.shape[0]\n for i in range(data_len//batch_size+1):\n x1 = train_x[i*batch_size:(i+1)*batch_size]\n y1 = train_y[i*batch_size:(i+1)*batch_size]\n# \n# batch_x = x1.transpose((1, 0, 2))\n# batch_y = y1.transpose((1, 0, 2))\n# yield batch_x, batch_y\n\n yield x1, y1\n\nbatch_size=1024\ninput_seq, output_seq = train_x.shape[2],train_y.shape[2]\n\n## Parameters\nlearning_rate = 0.01\nlambda_l2_reg = 0.001\nlambda_l2_reg = 0\n\n## Network Parameters\n# length of input signals\ninput_seq_len = train_x.shape[1]\noutput_seq_len = train_y.shape[1]\n\n# size of LSTM Cell\nhidden_dim = 128\n# num of input signals\ninput_dim = train_x.shape[2]\n# num of output signals\noutput_dim = train_y.shape[2]\n# num of stacked lstm layers \nnum_stacked_layers = 2 \n# gradient clipping - to avoid gradient exploding\nGRADIENT_CLIPPING = 2.5 \n\n\ndef build_graph(feed_previous = False):\n\n tf.reset_default_graph()\n\n global_step = tf.Variable(\n initial_value=0,\n name=\"global_step\",\n trainable=False,\n collections=[tf.GraphKeys.GLOBAL_STEP, tf.GraphKeys.GLOBAL_VARIABLES])\n\n weights = {\n 'out': tf.get_variable('Weights_out', \\\n shape = [hidden_dim, output_dim], \\\n dtype = tf.float32, \\\n initializer = tf.truncated_normal_initializer()),\n }\n biases = {\n 'out': tf.get_variable('Biases_out', \\\n shape = [output_dim], \\\n dtype = tf.float32, \\\n initializer = tf.constant_initializer(0.)),\n }\n\n with tf.variable_scope('Seq2seq'):\n # Encoder: inputs\n enc_inp = [\n tf.placeholder(tf.float32, shape=(None, input_dim), name=\"inp_{}\".format(t))\n for t in range(input_seq_len)\n ]\n\n # Decoder: target outputs\n target_seq = [\n tf.placeholder(tf.float32, shape=(None, output_dim), name=\"y\".format(t))\n for t in range(output_seq_len)\n ]\n\n # Give a \"GO\" token to the decoder. \n # If dec_inp are fed into decoder as inputs, this is 'guided' training; otherwise only the \n # first element will be fed as decoder input which is then 'un-guided'\n dec_inp = [ tf.zeros_like(target_seq[0], dtype=tf.float32, name=\"GO\") ] + target_seq[:-1]\n\n with tf.variable_scope('LSTMCell'): \n cells = []\n for i in range(num_stacked_layers):\n with tf.variable_scope('RNN_{}'.format(i)):\n cells.append(tf.contrib.rnn.LSTMCell(hidden_dim))\n cell = tf.contrib.rnn.MultiRNNCell(cells)\n\n def _rnn_decoder(decoder_inputs,\n initial_state,\n cell,\n loop_function=None,\n scope=None):\n \"\"\"RNN decoder for the sequence-to-sequence model.\n Args:\n decoder_inputs: A list of 2D Tensors [batch_size x input_size].\n initial_state: 2D Tensor with shape [batch_size x cell.state_size].\n cell: rnn_cell.RNNCell defining the cell function and size.\n loop_function: If not None, this function will be applied to the i-th output\n in order to generate the i+1-st input, and decoder_inputs will be ignored,\n except for the first element (\"GO\" symbol). This can be used for decoding,\n but also for training to emulate http://arxiv.org/abs/1506.03099.\n Signature -- loop_function(prev, i) = next\n * prev is a 2D Tensor of shape [batch_size x output_size],\n * i is an integer, the step number (when advanced control is needed),\n * next is a 2D Tensor of shape [batch_size x input_size].\n scope: VariableScope for the created subgraph; defaults to \"rnn_decoder\".\n Returns:\n A tuple of the form (outputs, state), where:\n outputs: A list of the same length as decoder_inputs of 2D Tensors with\n shape [batch_size x output_size] containing generated outputs.\n state: The state of each cell at the final time-step.\n It is a 2D Tensor of shape [batch_size x cell.state_size].\n (Note that in some cases, like basic RNN cell or GRU cell, outputs and\n states can be the same. They are different for LSTM cells though.)\n \"\"\"\n with variable_scope.variable_scope(scope or \"rnn_decoder\"):\n state = initial_state\n outputs = []\n prev = None\n for i, inp in enumerate(decoder_inputs):\n if loop_function is not None and prev is not None:\n with variable_scope.variable_scope(\"loop_function\", reuse=True):\n inp = loop_function(prev, i)\n if i > 0:\n variable_scope.get_variable_scope().reuse_variables()\n output, state = cell(inp, state)\n outputs.append(output)\n if loop_function is not None:\n prev = output\n return outputs, state\n\n def _basic_rnn_seq2seq(encoder_inputs,\n decoder_inputs,\n cell,\n feed_previous,\n dtype=dtypes.float32,\n scope=None):\n \"\"\"Basic RNN sequence-to-sequence model.\n This model first runs an RNN to encode encoder_inputs into a state vector,\n then runs decoder, initialized with the last encoder state, on decoder_inputs.\n Encoder and decoder use the same RNN cell type, but don't share parameters.\n Args:\n encoder_inputs: A list of 2D Tensors [batch_size x input_size].\n decoder_inputs: A list of 2D Tensors [batch_size x input_size].\n feed_previous: Boolean; if True, only the first of decoder_inputs will be\n used (the \"GO\" symbol), all other inputs will be generated by the previous \n decoder output using _loop_function below. If False, decoder_inputs are used \n as given (the standard decoder case).\n dtype: The dtype of the initial state of the RNN cell (default: tf.float32).\n scope: VariableScope for the created subgraph; default: \"basic_rnn_seq2seq\".\n Returns:\n A tuple of the form (outputs, state), where:\n outputs: A list of the same length as decoder_inputs of 2D Tensors with\n shape [batch_size x output_size] containing the generated outputs.\n state: The state of each decoder cell in the final time-step.\n It is a 2D Tensor of shape [batch_size x cell.state_size].\n \"\"\"\n with tf.variable_scope(scope or \"basic_rnn_seq2seq\"):\n enc_cell = copy.deepcopy(cell)\n _, enc_state = rnn.static_rnn(enc_cell, encoder_inputs, dtype=dtype)\n if feed_previous:\n return _rnn_decoder(decoder_inputs, enc_state, cell, _loop_function)\n else:\n return _rnn_decoder(decoder_inputs, enc_state, cell)\n\n def _loop_function(prev, _):\n '''Naive implementation of loop function for _rnn_decoder. Transform prev from \n dimension [batch_size x hidden_dim] to [batch_size x output_dim], which will be\n used as decoder input of next time step '''\n return tf.matmul(prev, weights['out']) + biases['out']\n\n dec_outputs, dec_memory = _basic_rnn_seq2seq(\n enc_inp, \n dec_inp, \n cell, \n feed_previous = feed_previous\n )\n\n reshaped_outputs = [tf.matmul(i, weights['out']) + biases['out'] for i in dec_outputs]\n\n # Training loss and optimizer\n with tf.variable_scope('Loss'):\n # L2 loss\n output_loss = 0\n for _y, _Y in zip(reshaped_outputs, target_seq):\n output_loss += tf.reduce_mean(tf.pow(_y - _Y, 2))\n\n # L2 regularization for weights and biases\n reg_loss = 0\n for tf_var in tf.trainable_variables():\n if 'Biases_' in tf_var.name or 'Weights_' in tf_var.name:\n reg_loss += tf.reduce_mean(tf.nn.l2_loss(tf_var))\n\n loss = output_loss + lambda_l2_reg * reg_loss\n\n with tf.variable_scope('Optimizer'):\n optimizer = tf.contrib.layers.optimize_loss(\n loss=loss,\n learning_rate=learning_rate,\n global_step=global_step,\n optimizer='Adam',\n clip_gradients=GRADIENT_CLIPPING)\n\n saver = tf.train.Saver\n\n return dict(\n enc_inp = enc_inp, \n target_seq = target_seq, \n train_op = optimizer, \n loss=loss,\n saver = saver, \n reshaped_outputs = reshaped_outputs,\n )\ntotal_iteractions =5000\nbatch_size = 1024\nKEEP_RATE = 0.8\ntrain_losses = []\nval_losses = []\nval_n=10\n\nmin_scope=None\nrun_echo=0\nearly_echo=50\n\n\n \n\nrnn_model = build_graph(feed_previous=False)\n\nsaver = tf.train.Saver()\nimport datetime \ninit = tf.global_variables_initializer()\nwith tf.Session() as sess:\n sess.run(init)\n for i in range(total_iteractions):\n loss_ts=[]\n now=datetime.datetime.now()\n for batch_input, batch_output in generate_train_samples(batch_size=batch_size):\n\n feed_dict = {rnn_model['enc_inp'][t]: batch_input[:,t].reshape(-1,input_dim) for t in range(input_seq_len)}\n feed_dict.update({rnn_model['target_seq'][t]: batch_output[:,t].reshape(-1,output_dim) for t in range(output_seq_len)})\n _, loss_t = sess.run([rnn_model['train_op'], rnn_model['loss']], feed_dict)\n loss_ts.append(loss_t)\n end=datetime.datetime.now()\n if i%val_n==0 and len(val_x)>0:\n print(\"-----------------------------------------------------------------------------\")\n feed_dict = {rnn_model['enc_inp'][t]: val_x[:,t].reshape(-1,input_dim) for t in range(input_seq_len)}\n feed_dict.update({rnn_model['target_seq'][t]: val_y[:,t].reshape(-1,output_dim) for t in range(output_seq_len)})\n loss_t_val = sess.run(rnn_model['loss'], feed_dict)\n print(\"Step {0}/{1}--timelenght:{2}, train loss: {3},val_loss: {4}\".format(i, total_iteractions,(end-now).total_seconds(), sum(loss_ts)/len(loss_ts),loss_t_val))\n print(\"Step {}/{}--timelenght:{}, train loss: {}\".format(i, total_iteractions,(end-now).total_seconds(), sum(loss_ts)/len(loss_ts)))\n loss=sum(loss_ts)/len(loss_ts)\n if min_scope is None:\n min_scope=loss\n else:\n if loss=early_echo:\n break\n \n \n \n\nprint(\"Checkpoint saved at: \", save_path)\n\n\ndef smape(y_true, y_pred):\n denominator = (np.abs(y_true) + np.abs(y_pred)) / 2.0\n diff = np.abs(y_true - y_pred) / denominator\n diff[denominator == 0] = 0.0\n return np.mean(diff)\n\nrnn_model = build_graph(feed_previous=True)\ninit = tf.global_variables_initializer()\n\ndef predict_feed_previous(X,Y,name):\n feed_dict = {rnn_model['enc_inp'][t]: X[:,t].reshape(-1,input_dim) for t in range(input_seq_len)}\n feed_dict.update({rnn_model['target_seq'][t]: np.zeros([X.shape[0],output_dim]) for t in range(output_seq_len)})\n final_preds = sess.run(rnn_model['reshaped_outputs'], feed_dict)\n final_preds = np.concatenate(final_preds, axis = 1)\n final_preds=np.array(final_preds).reshape(-1)\n Y_=Y.reshape(-1)\n final_preds=np.expm1(final_preds)\n Y_=np.expm1(Y_)\n smape_score=smape(Y_,final_preds)\n from sklearn.metrics import r2_score\n score = r2_score(Y_, final_preds)\n logging.info(\"%s得分:%s\"%(name,smape_score))\n logging.info(\"%sR^2得分:%s\"%(name,smape_score))\n print(\"%s smape得分:%s\"%(name,smape_score))\n print(\"%s smapeR^2得分:%s\"%(name,smape_score))\n return Y_,final_preds,smape_score,score\n \n#tf.reset_default_graph()\n# sess.close()\nsess = tf.InteractiveSession()\nwith tf.Session() as sess:\n sess.run(init)\n saver = rnn_model['saver']().restore(sess, os.path.join('./models/', 'univariate_ts_model0'))\n predict_feed_previous(train_x,train_y,\"训练集合\")\n \n if val_x.shape[0]>0:\n predict_feed_previous(val_x,val_y,\"测试集合\")\n ####预测\n feed_dict = {rnn_model['enc_inp'][t]: predicts[:,t].reshape(-1,input_dim) for t in range(input_seq_len)}\n feed_dict.update({rnn_model['target_seq'][t]: np.zeros([predicts.shape[0],output_dim]) for t in range(output_seq_len)})\n final_preds = sess.run(rnn_model['reshaped_outputs'], feed_dict)\n final_preds = np.concatenate(final_preds, axis = 1)\nfinal_preds=np.expm1(final_preds)\ndata=np.concatenate([x_pred_name_date,final_preds],axis=1)\ndf_predict=pd.DataFrame(data=data)\ncolmuns=[str(x_pred_name_date[0][1]+pd.Timedelta(days=5+i)) for i in range(7)]\ndf_predict.columns=['WAREHOUSE_NAME','maxdate']+colmuns\ndf_predict.to_excel(\"./xlsx/seq2seq_predicts.xlsx\",index=False)","sub_path":"seq2seq_text_model/seq2seq_train.py","file_name":"seq2seq_train.py","file_ext":"py","file_size_in_byte":15471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"255723036","text":"import datetime\nfrom sqlalchemy import func\nfrom model import User, Meal, mealMedia, mealType, connect_to_db, db\nfrom model import app\n\ndef load_users(user_filename):\n\n for i, row in enumerate(open(user_filename)):\n row = row.rstrip() \n\n user_id, first_name, last_name, email, password = row.split(\"|\") \n\n user = User(user_id=user_id, \n first_name=first_name, \n last_name=last_name,\n email=email, \n password=password)\n\n user_id = int(user_id)\n\n db.session.add(user)\n\n db.session.commit()\n\n\ndef load_meals(meal_filename):\n\n for i, row in enumerate(open(user_filename)):\n row = row.rstrip() \n\n meal_id, user_id, name, description, start_time, end_time, location,\n longitude, latitude, media_type_id= row.split(\"|\") \n\n meal = Meal(meal_id=meal_id, \n user_id=user_id, \n name=name, \n description=description, \n start_time=start_time, \n end_time=end_time, \n location=location, \n longitude=longitude, \n latitude=latitude, \n meal_type_id=meal_type_id)\n\n\n meal_id = int(meal_id)\n user_id = int(user_id)\n longitude = float(longitude)\n latitude = float(latitude)\n\n\n db.session.add(user)\n\n db.session.commit()\n\ndef load_meal_media(meal_media_filename):\n\n for i, row in enumerate(open(user_filename)):\n row = row.rstrip() \n\n meal_media_id, meal_id, media = row.split(\"|\") \n\n meal_media = mealMedia( meal_media_id=meal_media_id,\n meal_id=meal_id, \n media=media)\n\n meal_media_id = int(meal_media_id)\n meal_id = int(meal_id)\n \n\n\n db.session.add(user)\n db.session.commit()\n\ndef load_meal_type(meal_type_filename): \n\n for i, row in enumerate(open(user_filename)):\n row = row.rstrip() \n\n meal_type_id, title = row.split(\"|\") \n\n meal_type = mealType(meal_type_id=meal_type_id, title=title)\n meal_type_id = int(meal_type_id)\n\n\n db.session.add(meal_type)\n db.session.commit()\n\ndef set_val_user_id():\n \"\"\"Set value for the next user_id after seeding database\"\"\"\n\n # Get the Max user_id in the database\n result = db.session.query(func.max(User.user_id)).one()\n max_id = int(result[0])\n\n # Set the value for the next user_id to be max_id + 1\n query = \"SELECT setval('users_user_id_seq', :new_id)\"\n db.session.execute(query, {'new_id': max_id + 1})\n db.session.commit()\n\nif __name__ == \"__main__\":\n connect_to_db(app)\n db.create_all()\n\n user_filename = \"seed_data/user_data\"\n\n load_users(user_filename)\n set_val_user_id()\n load_meals(meal_filename)\n load_meal_media(meal_media_filename)\n load_meal_type(meal_type_filename)\n\n","sub_path":"seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"402575402","text":"from openpyxl import load_workbook\nfrom ru.textilstock.assortment.mixbox.MixBox import MixBox, MixBoxItem\n\n\ndef is_mix_box_start(row):\n val = row[0].value\n return val is not None and isinstance(val, str) and val.startswith('Поставщик: ')\n\n\ndef is_mix_box_end(row):\n val = row[2].value\n return val is not None and isinstance(val, str) and val == 'ИТОГО В КОРОБЕ'\n\n\ndef prepare_row_boxes(ws):\n row_boxes = []\n cur_rowboxes = None\n for row in ws.iter_rows():\n if is_mix_box_start(row):\n cur_rowboxes = []\n\n if is_mix_box_end(row):\n cur_rowboxes.append(row)\n row_boxes.append(cur_rowboxes)\n cur_rowboxes = None\n\n if cur_rowboxes is not None:\n cur_rowboxes.append(row)\n return row_boxes\n\n\ndef process_box(row_box):\n first_item_row_offset = 6\n supplier_name = row_box[0][0].value[11:]\n brand = row_box[1][0].value[7:]\n consignee = row_box[2][0].value[17:]\n cargo_number_str = row_box[3][0].value[12:]\n try:\n cargo_number = int(cargo_number_str)\n except ValueError:\n print('BAD CARGO NUM. SKIPPED')\n return None\n num_and_count = row_box[4][2].value.split()\n box_num = int(num_and_count[0])\n box_count = int(num_and_count[2])\n sum_items_count = int(row_box[len(row_box) - 1][4].value)\n\n item_rows = row_box[first_item_row_offset:len(row_box) - 1]\n\n items = []\n for item_row in item_rows:\n item = MixBoxItem(item_row[0].value,\n item_row[1].value,\n item_row[2].value,\n item_row[3].value,\n item_row[4].value)\n items.append(item)\n\n box = MixBox(supplier_name, brand, consignee, cargo_number,\n box_num, box_count, items, sum_items_count)\n print('Proeessed. cargo num: ' + str(box.cargo_number)\n + ', box num: ' + str(box_num))\n return box\n\n\n\"\"\"\nReturns MixBox array\n :rtype: :class:`MixBox`\n\"\"\"\n\n\ndef parse(mix_xlsx_file_name):\n workbook = load_workbook(filename=mix_xlsx_file_name, data_only=True)\n ws = workbook.active\n row_boxes = prepare_row_boxes(ws)\n result = []\n for rb in row_boxes:\n box = process_box(rb)\n if box is not None:\n result.append(box)\n return result\n\n","sub_path":"ru/textilstock/assortment/mixbox/MixBoxXlsParser.py","file_name":"MixBoxXlsParser.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"617047606","text":"import graphics as gr\nimport math\n\nwidth = 500 # int(input('Введите ширину поля... ')) * 10\nx0 = 250\ny0 = 250\n\nsensors = [[-45, 50], [-15, 50], [15, 50], [45, 50], [-30, 35], [0, 35],\n [30, 35], [-15, 20], [15, 20], [-45, 20], [45, 25],\n [-30, 5], [-5, 5], [-45, -10], [-15, -10], [25, -10], [45, -10],\n [-25, -20], [10, -30], [35, -30], [-45, -40], [-15, -50], [15, -50],\n [45, -50]]\n\n\nwindow = gr.GraphWin('Picture', width, width)\n\n\ndef drawRectangle(x1, y1, x2, y2, fill='red', outline='red'):\n my_rectangle = gr.Rectangle(gr.Point(x1, y1), gr.Point(x2, y2))\n my_rectangle.setFill(fill)\n my_rectangle.setOutline(outline)\n my_rectangle.draw(window)\n\n\ndef drawCircle(x, y, r, fill='white', outline='black'):\n my_circle = gr.Circle(gr.Point(x, y), r)\n my_circle.setFill(fill)\n my_circle.setOutline(outline)\n my_circle.draw(window)\n\n\ndef drawLine(x1, y1, x2, y2, width=1, fill='red', outline='red'):\n my_line = gr.Line(gr.Point(x1, y1), gr.Point(x2, y2))\n my_line.setFill(fill)\n my_line.setOutline(outline)\n my_line.setWidth(width)\n my_line.draw(window)\n\n\ndef drawSensorRadius(sensor):\n coordX = x0+sensor[0]*5\n coordY = (y0-sensor[1]*5)\n drawCircle(coordX, coordY, 75, 'white', 'white')\n\n\ndef drawErrorSensor(sensor):\n coordX = x0+sensor[0]*5\n coordY = (y0-sensor[1]*5)\n drawCircle(coordX, coordY, 10, 'red', 'red')\n\n\ndef drawSensorInfo(sensor):\n coordX = x0+sensor[0]*5\n coordY = (y0-sensor[1]*5)\n drawCircle(coordX, coordY, 5, 'yellow', 'yellow')\n\n txt = gr.Text(gr.Point(coordX+10, coordY+15), sensor)\n txt.setSize(10)\n txt.draw(window)\n\n\ndef showBlindSpots(sensors):\n errorSensors = []\n length = len(sensors)\n\n drawSensorRadius(sensors[0])\n for i in range(length):\n A = sensors[i]\n for j in range(i+1, length, 1):\n B = sensors[j]\n ABlength = math.sqrt((A[0]-B[0])**2+(A[1]-B[1])**2)\n if ABlength < 20:\n errorSensors.append([A, B])\n\n drawSensorRadius(sensors[i])\n\n for sensor in sensors:\n drawSensorInfo(sensor)\n\n for errorCouple in errorSensors:\n\n drawLine(x0+errorCouple[0][0]*5, y0-errorCouple[0][1]*5,\n x0+errorCouple[1][0]*5, y0-errorCouple[1][1]*5,\n 5, 'red', 'red')\n\n print(errorSensors)\n\n\ndrawRectangle(0, 0, width, width)\ndrawRectangle(0, width/2, width, width/2, 'blue', 'blue')\ndrawRectangle(width/2, 0, width/2, width, 'blue', 'blue')\nshowBlindSpots(sensors)\n\nwindow.getMouse()\nwindow.close()\n","sub_path":"Lesson-4/extra/ex-03-disable_nearest.py","file_name":"ex-03-disable_nearest.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"307910285","text":"import os\nfrom datetime import datetime\nfrom flask import current_app\n\ntimestamp_format = '%Y%m%dT%H%M%S.%f'\n\n\ndef get_rollout_ids():\n rollouts_path = os.path.join(current_app.log_dir, 'rollouts')\n return os.listdir(rollouts_path)\n\n\ndef get_latest_rollout_info():\n rollout_ids = get_rollout_ids()\n\n if len(rollout_ids) == 0:\n return None, None\n\n latest = datetime.strptime(rollout_ids[0], timestamp_format)\n for rollout_id in rollout_ids[1:]:\n now = datetime.strptime(rollout_id, timestamp_format)\n if now > latest:\n latest = now\n\n latest_rollout_id = latest.strftime(timestamp_format)\n\n return latest_rollout_id, os.path.join(current_app.log_dir, 'rollouts', latest_rollout_id)\n","sub_path":"chainerrl_visualizer/server_tasks/rollout_ids.py","file_name":"rollout_ids.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"331693755","text":"import traceback\n\nfrom django.contrib.auth.decorators import permission_required\nfrom django.http import JsonResponse\nfrom django.utils.decorators import method_decorator\nfrom rest_framework.decorators import permission_classes\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.views import APIView\n\nfrom monitor_web import models\nfrom monitor_web.serializers import DiagramSerializer, DiagramItemSerializer\nfrom web.common import constant\nfrom web.common.paging import paging_request\n\n\n@permission_classes((IsAuthenticated,))\nclass DiagramList(APIView):\n @method_decorator(permission_required('monitor_web.view_diagram', raise_exception=True))\n def get(self, request, pk=None, format=None):\n \"\"\"\n 【模板下的】获取图表列表\n \"\"\"\n from monitor_web import models\n if self.request.query_params.__contains__('templateId'):\n page_data, count = paging_request(request, models.Diagram, self,\n filter={'template__in': [request.query_params['templateId']]})\n elif self.request.query_params.__contains__('id'):\n page_data, count = paging_request(request, models.Diagram, self,\n filter={'id__in': [request.query_params['id']]})\n else:\n page_data, count = paging_request(request, models.Diagram, self)\n # 对数据进行序列化\n serializer = DiagramSerializer(instance=page_data, many=True)\n ret = {\n \"code\": constant.BACKEND_CODE_OK,\n \"data\": {\n \"count\": count,\n \"items\": serializer.data,\n \"page\": {\n \"currPage\": request.GET.get('page', constant.DEFAULT_CURRENT_PAGE),\n \"pageSize\": request.GET.get('size', constant.DEFAULT_PAGE_SIZE)\n }\n }\n }\n return JsonResponse(ret, safe=False)\n\n\n@permission_classes((IsAuthenticated,))\nclass DiagramInfo(APIView):\n @method_decorator(permission_required('monitor_web.view_diagram', raise_exception=True))\n def get(self, request, *args, **kwargs):\n \"\"\"\n 【模板下的】获取图表\n \"\"\"\n diagram = models.Diagram.objects.get(\n id=self.request.query_params['id']) if self.request.query_params.__contains__('id') else None\n\n di = models.DiagramItem.objects.filter(diagram__in=str(diagram.id)).all()\n serializer = DiagramItemSerializer(instance=di, many=True)\n ret = {\n \"code\": constant.BACKEND_CODE_OK,\n \"data\": {\n \"items\": serializer.data\n }\n }\n return JsonResponse(ret, safe=False)\n\n @method_decorator(permission_required('monitor_web.add_diagram', raise_exception=True))\n def post(self, request, *args, **kwargs):\n \"\"\"\n 【模板下的】创建图表\n \"\"\"\n data = JSONParser().parse(self.request)\n # 创建图表\n ret = {\n 'code': constant.BACKEND_CODE_OPT_FAIL,\n 'message': '创建图表失败'\n }\n try:\n t = models.Template.objects.filter(id=data['template_id'])\n if t.count() > 0:\n d = models.Diagram.objects.create(name=data['name'], width=data['width'], height=data['height'],\n template=t.get())\n # 创建图表项\n itemIds = data['item_ids'].split(\",\")\n for itemId in itemIds:\n models.DiagramItem.objects.create(diagram=d, item=models.MonitorItem.objects.filter(id=itemId).get())\n except:\n print(traceback.format_exc())\n return JsonResponse(ret, safe=False)\n\n ret = {\n 'code': constant.BACKEND_CODE_CREATED,\n 'message': '创建图表成功'\n }\n return JsonResponse(ret, safe=False)\n\n\n@permission_classes((IsAuthenticated,))\nclass ServerDiagramList(APIView):\n @method_decorator(permission_required('monitor_web.view_diagram', raise_exception=True))\n def get(self, request, *args, **kwargs):\n \"\"\"\n grafana图表\n \"\"\"\n server_id = self.request.query_params['id']\n now = self.request.query_params['now'] if 'now' in self.request.query_params else 'now-6h'\n server = models.Server.objects.filter(id=server_id).get()\n server_name = server.name.lower()\n dashboards = models.GrafanaDashboard.objects.filter(device_id=server_id, device_type=1).all()\n ret_iframes = ''\n if dashboards.count() > 0:\n for d in dashboards:\n # 图表id,暂时没用\n did = d.diagram_id\n ret_iframes = ret_iframes + '' % (\n d.dashboard_uid, server_name, d.diagram_id, now, d.diagram.width, d.diagram.height)\n ret = {\n \"code\": constant.BACKEND_CODE_OK,\n \"data\": {\n \"item\": ret_iframes\n }\n }\n return JsonResponse(ret, safe=False)\n","sub_path":"monitor_api2/monitor_web/views/diagram_view.py","file_name":"diagram_view.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"367342869","text":"import pandas as pd\r\nimport zipfile\r\nimport os\r\n\r\n#pass in excel file path, the key and the value for columns\r\ndic = pd.read_excel('./new_replacement.xlsx', engine='openpyxl').set_index('Key')['Value'].to_dict()\r\ncolor_change_needed = set()\r\ndef replace(old_path,new_path, dic):\r\n\r\n zin = zipfile.ZipFile (old_path, 'r')\r\n zout = zipfile.ZipFile (new_path, 'w')\r\n\r\n for i in zin.infolist():\r\n buffer = zin.read(i.filename)\r\n if (i.filename == 'word/document.xml'):\r\n result = buffer.decode(\"utf-8\")\r\n for key in dic:\r\n result = result.replace(key,dic[key])\r\n if '**' in result:\r\n color_change_needed.add(old_path)\r\n buffer = result.encode(\"utf-8\")\r\n zout.writestr(i, buffer)\r\n zout.close()\r\n zin.close()\r\n\r\n#input - pass location for directory containing the files that need to be replaced.\r\n#output - pass location for where the output folder\r\ndirectory_input = r'C:\\Users\\AnushPoudel\\Documents\\Input'\r\ndirectory_output = r'C:\\Users\\AnushPoudel\\Documents\\Output'\r\n\r\nfor entry in os.scandir(directory_input):\r\n if (entry.path.endswith(\".docx\") or entry.path.endswith(\".doc\")) and entry.is_file():\r\n replace(entry.path, directory_output + '\\\\' + entry.name, dic)\r\n\r\nprint(color_change_needed)\r\n","sub_path":"final_replace.py","file_name":"final_replace.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"30890883","text":"from django.conf.urls import patterns, url\n\n\nurlpatterns = patterns(\n 'fjord.analytics.views',\n\n # This covers / and /dashboard\n url(r'^(?:dashboard/?)?$', 'dashboard', name='dashboard'),\n\n # Show a specific response\n url(r'^dashboard/response/(?P\\d+)/?$',\n 'response_view', name='response_view'),\n\n)\n\n# These are analyzer-group only views.\nurlpatterns += patterns(\n 'fjord.analytics.analyzer_views',\n\n # Analytics dashboard\n url(r'^analytics/?$', 'analytics_dashboard',\n name='analytics_dashboard'),\n url(r'^analytics/occurrences/?$', 'analytics_occurrences',\n name='analytics_occurrences'),\n url(r'^analytics/products/?$', 'analytics_products',\n name='analytics_products'),\n url(r'^analytics/search/?$', 'analytics_search',\n name='analytics_search'),\n\n url(r'^analytics/duplicates/?$', 'analytics_duplicates', name='analytics_duplicates'),\n)\n","sub_path":"fjord/analytics/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"429917761","text":"\n'''IPOR'''\n'''Input: nums = [1,2,3]\nOutput: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\nINPUT:[1]\noutput=[[1]]'''\n\n\n\ndef permutation(arr):\n result =[]\n\n if len(arr)==1:\n return [arr[:]]\n\n for i in range(len(arr)):\n n = arr.pop(0)\n perms =permutation(arr)\n\n\n for perm in perms:\n perm.append(n)\n\n result.extend(perms)\n\n arr.append(n)\n\n return result\n\n\n\n\n\n\n\n\n\n\narr = [1,2,3]\nprint(permutation(arr))","sub_path":"RECURSION/GoodPermutations.py","file_name":"GoodPermutations.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"220711611","text":"import math\n\nwith open(\"f_libraries_of_the_world.txt\", \"r\") as f:\n lines = f.readlines()\n initial_data = lines[0].split(' ')\n B = int(initial_data[0]) # books, 10^5\n L = int(initial_data[1]) # libraries, 10^5\n D = int(initial_data[2]) # total time in days, 10^5\n book_scores = [int(val) for val in lines[1].split(' ')] # book scores\n\n libraries = []\n _index = 2\n for i in range(L):\n library_initial_data = lines[_index].split(' ')\n book_ids = [{'id': int(val), 'score': book_scores[int(val)]} for val in lines[_index + 1].split(' ')]\n N = int(library_initial_data[0]) # number of books\n T = int(library_initial_data[1]) # days to signup\n M = int(library_initial_data[2]) # books sending limit\n libraries.append({'id': i, 'N': N, 'T': T, 'M': M, 'book_ids': book_ids, 'weight': 0})\n _index += 2\n\n# print('B: ', str(B), ', L: ', str(L), ', D: ', str(D))\n# print(book_scores)\n\nalready_scanned_book_ids = [] # for many duplicates\n\nfor l in libraries:\n # deduplicate ids ---- no need\n # eliminim ce e deja scanat\n bkids = [book['id'] for book in l['book_ids']]\n aux = set(bkids) - set(already_scanned_book_ids)\n aux2 = [{'id': val, 'score': book_scores[val]} for val in aux]\n l['book_ids'] = aux2\n # actualizez numarul de carti ale librariei\n l['N'] = len(l['book_ids'])\n l['book_ids'].sort(key=lambda x:x['score'], reverse=True) # for diff scores\n already_scanned_book_ids += aux\n total = 0\n for book in l['book_ids']:\n total += book['score']\n l['weight'] = total/l['T']\n \nlibraries.sort(key=lambda x:x['weight'], reverse=True)\n\ncurrent_start_day = 0\ndays_left = D\nindex = 0\nno_libraries = L\nout_libraries = []\n\nwhile index < len(libraries) and days_left - libraries[index]['T'] > 0:\n if libraries[index]['N'] > 0:\n # print(libraries[index])\n current_start_day += libraries[index]['T']\n # print('start: ', current_start_day)\n days_left -= libraries[index]['T']\n # print('left: ', days_left)\n days = min(days_left + 1, math.ceil(libraries[index]['N']/libraries[index]['M']))\n throughput = days * libraries[index]['M']\n throughput = min(throughput, libraries[index]['N'])\n # print('days: ', days)\n # print('th: ', throughput)\n out_libraries.append({'id': libraries[index]['id'], 'no_books': throughput, 'book_ids': libraries[index]['book_ids'][:throughput]})\n no_libraries -= 1\n index += 1\n # print()\n\nwith open(\"output.txt\", \"w+\") as f:\n f.write(str(len(out_libraries)))\n f.write(\"\\n\")\n for l in out_libraries:\n f.write(str(l['id']))\n f.write(' ')\n f.write(str(l['no_books']))\n f.write('\\n')\n for book_id in l['book_ids']:\n f.write(str(book_id['id']))\n f.write(' ')\n f.write('\\n')\n","sub_path":"solutions/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"62649405","text":"#运用列表生成式,可以写出非常简洁的代码。例如,列出当前目录下的所有文件和目录名,可以通过一行代码实现:\nimport os # 导入os模块\nl=[ d for d in os.listdir('.')] # os.listdir列出文件目录\nprint(l)\n\nd = {'x': 'A', 'y': 'B', 'z': 'C' }\n\nm=[k + '=' + v for k, v in d.items()]\n\n# v.lower() 全部转换为小写\nm=[k + '=' + v.lower() for k, v in d.items()]\n\nprint(m)\n\n\nL=[\"Hello\",\"Ni\",\"Hao\"]\n\nprint([x.lower() for x in L])","sub_path":"day_3/List_comprehensions2.py","file_name":"List_comprehensions2.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"434609205","text":"# -*- coding: utf-8 -*-\n\nfrom completor import Completor\n\n\nclass Racer(Completor):\n filetype = 'rust'\n\n def format_cmd(self):\n line, col = self.cursor\n binary = self.get_option('completor_racer_binary') or 'racer'\n return [binary, 'complete', str(line), str(col), self.filename,\n self.tempname]\n\n def parse(self, items):\n completions = []\n for item in items:\n if not item.startswith('MATCH'):\n continue\n\n parts = item.split(',')\n name = parts[0][6:]\n spec = ', '.join(parts[5:])\n\n completions.append({\n 'word': name,\n 'menu': spec,\n 'dup': 0\n })\n return completions\n","sub_path":"pythonx/completers/rust.py","file_name":"rust.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"407603969","text":"# %%\nimport matplotlib.pyplot as plt\n#%matplotlib inline\nfrom numpy import *\nimport numpy as np\nimport h5py\nimport myfunc.util as util\nimport glob\nimport gzip\nfrom collections import deque\nfrom datetime import datetime, timedelta\nimport os, sys, socket\nfrom bisect import bisect_left\nimport time\n#iDTime = datetime(2018,3,1)\n#eDTime = datetime(2018,12,31)\n\niDTime = datetime(2018,4,1)\neDTime = datetime(2018,12,31)\n\n#iDTime = datetime(2018,1,23)\n#eDTime = datetime(2018,2,28)\n\n\ntstart = time.time()\n\n#----------------------------\ngmi = [\"GPM\",\"GMI\",\"1C\",\"1C\",\"V05\"]\namsr2 = [\"GCOMW1\",\"AMSR2\",\"1C\",\"1C\",\"V05\"]\nssmis_f16 = [\"F16\",\"SSMIS\",\"1C\",\"1C\",\"V05\"]\nssmis_f17 = [\"F17\",\"SSMIS\",\"1C\",\"1C\",\"V05\"] # 37V is missing after April 2016\nssmis_f18 = [\"F18\",\"SSMIS\",\"1C\",\"1C\",\"V05\"]\natms_npp = [\"NPP\",\"ATMS\",\"1C\",\"1C\",\"V05\"]\natms_noaa20= [\"NOAA20\",\"ATMS\",\"1C\",\"1C\",\"V05\"] # MRMS is not available\n\nmhs_metopa= [\"METOPA\",\"MHS\",\"1C\",\"1C\",\"V05\"]\nmhs_metopb= [\"METOPB\",\"MHS\",\"1C\",\"1C\",\"V05\"]\nmhs_noaa18= [\"NOAA18\",\"MHS\",\"1C\",\"1C\",\"V05\"] # Not available at arthurhou.pps after 2018/10/21\nmhs_noaa19= [\"NOAA19\",\"MHS\",\"1C\",\"1C\",\"V05\"]\n\n#lspec = [amsr2, ssmis_f16, ssmis_f17, ssmis_f18, atms_npp, atms_noaa20, mhs_metopa, mhs_metopb, mhs_noaa18, mhs_noaa19, gmi]\nlspec = [mhs_noaa18, mhs_noaa19,ssmis_f18, gmi]\n#lspec = [ssmis_f16, ssmis_f18, atms_npp, mhs_metopa, mhs_metopb, mhs_noaa18, mhs_noaa19, gmi]\n#lspec = [mhs_noaa18]\n#lspec = [gmi]\n\nscantype='epc'\n#scantype='gpr'\n\nny_mrms = 3500\nnx_mrms = 7000\n\n#*****************************************\ndef calc_km(lat1,lon1,lat2,lon2):\n RADEARTH = 6371\n DTR = 0.017453\n km= RADEARTH*np.arccos(np.cos(DTR*(lon1-lon2))*np.cos(DTR*lat1)*np.cos(DTR*lat2) + np.sin(DTR*lat1)*np.sin(DTR*lat2))\n return km\n\n#*****************************************\n# Start sate,sensor loop\n#-----------------------------------------\nfor spec in lspec:\n print('spec=',spec)\n print('')\n sate = spec[0]\n sensor = spec[1]\n prdName = spec[2]\n prj = spec[3]\n ver = spec[4]\n\n #*****************************************\n myhost = socket.gethostname()\n if myhost ==\"well\":\n workDir = '/home/utsumi/mnt/lab_work'\n tankDir = '/home/utsumi/mnt/lab_tank'\n tbbaseDir = '/home/utsumi/mnt/lab_work/hk02/PMM/NASA/%s.%s/1C/%s'%(sate,sensor,ver)\n mrmsbaseDir='/media/disk2/data/PMM/MRMS'\n else:\n workDir = '/work'\n tankDir = '/tank'\n tbbaseDir = '/work/hk02/PMM/NASA/%s.%s/1C/%s'%(sate,sensor,ver)\n mrmsbaseDir='/work/hk02/PMM/MRMS'\n\n #*****************************************\n # Make path list\n #-----------------------------------------\n iY,iM = iDTime.timetuple()[:2]\n eY,eM = eDTime.timetuple()[:2]\n lYM = util.ret_lYM([iY,iM],[eY,eM])\n\n ltbPathAll = []\n liescanAll = []\n for (Year,Mon) in lYM:\n\n if (sate=='NOAA18')&(datetime(Year,Mon,1,0)>=datetime(2018,10,21)):continue\n\n listPath = tankDir + '/utsumi/PMM/US/obtlist/overpass.%s.%s.%04d.%02d.csv'%(sensor,sate,Year,Mon)\n f=open(listPath,'r'); lines=f.readlines(); f.close()\n for line in lines:\n _,_,Day,oid,iscan,escan = list(map(int,line.strip().split(',')))\n\n #print(line)\n #if ('sate'=='AMSR2')&(datetime(2018,8,31) < datetime(Year,Mon,Day)): continue # No NOAA18 data after 2018/10/21\n\n #if (sate=='GCOMW1'): continue # test\n #if (sate=='NPP')&(Mon<3): continue # test\n #if (sate=='GPM')&(Mon<3): continue # test\n #if (sate=='METOPA')&(Mon<3): continue # test\n #if (sate=='METOPB')&(Mon<3): continue # test\n #if (sate=='NOAA18')&(Mon<3): continue # No NOAA18 data after 2018/10/21\n #if (sate=='NOAA19')&(Mon<3): continue # \n #if (sate=='F16'): continue # test\n #if (sate=='F18')&(Mon<3): continue # test\n #if (sate=='GPM')&(oid !=22370): continue # test\n\n if (iDTime<=datetime(Year,Mon,Day))&(datetime(Year,Mon,Day)<=eDTime):\n ltbPathTmp = sorted(glob.glob(tbbaseDir + '/%04d/%02d/%02d/*.%06d.????.HDF5'%(Year,Mon,Day,oid)))\n ltbPathAll = ltbPathAll + ltbPathTmp\n liescanAll.append([Year,Mon,Day,oid,iscan,escan])\n\n #print(tbbaseDir + '/%04d/%02d/%02d/*.%06d.????.HDF5'%(Year,Mon,Day,oid))\n #*****************\n # Start oid loop\n #*****************\n for (tbPath, iescan) in zip(ltbPathAll, liescanAll):\n\n Year,Mon,Day,oid,iscan,escan = iescan\n DTime = datetime(Year,Mon,Day)\n #if (sate=='F18')&(DTime datetime(2018,10,21)):continue # No NOAA18 data after 2018/10/21\n if (sate=='NOAA18')&(DTime 90, a2pixara[0]) # Representative for the entire granule\n\n #*****************\n # Determine the number of MRMS pixels\n #*****************\n ara_mrms = 1 # km2\n a1nrad = (np.sqrt(a1pixara/ara_mrms) /2).astype('int32') \n\n #*****************\n # Determine the corresponding MRMS location\n #*****************\n lat0_mrms = 20\n lon0_mrms = -130\n lat1_mrms = 55\n lon1_mrms = -60\n dlatlon_mrms = 0.01\n\n a2latpmw = ma.masked_outside(a2latpmw, lat0_mrms, lat1_mrms)\n a2lonpmw = ma.masked_outside(a2lonpmw, lon0_mrms, lon1_mrms)\n a2masklatlon = a2latpmw.mask + a2lonpmw.mask \n a2latpmw = ma.masked_where(a2masklatlon, a2latpmw)\n a2lonpmw = ma.masked_where(a2masklatlon, a2lonpmw)\n\n a2y_mrms = ((a2latpmw - lat0_mrms)/dlatlon_mrms).astype('int32')\n a2x_mrms = ((a2lonpmw - lon0_mrms)/dlatlon_mrms).astype('int32')\n \n #*****************\n # Make MRMS list\n #*****************\n mrmsDir = mrmsbaseDir + '/level2/%s/%04d/%02d'%(sate,Year,Mon)\n ssearch = mrmsDir + '/PRECIPRATE.GC.????????.??????.%05d.dat.gz'%(oid)\n lmrmsPath = sort(glob.glob(ssearch))\n if len(lmrmsPath)==0:\n print('No MRMS',Year,Mon,Day,oid)\n\n #*****************\n # Initialize output \n #*****************\n a2ave = np.full([nypmw,nxpmw], -9999., dtype='float32')\n a2num = np.full([nypmw,nxpmw], -9999., dtype='float32')\n a2qlt = np.full([nypmw,nxpmw], -9999., dtype='float32')\n\n #*****************\n # Read MRMS\n #*****************\n ''' first row = northern end '''\n ''' Header\n ncols 7000\n nrows 3500\n xllcenter -129.995000\n yllcenter 20.005000\n cellsize 0.010000\n '''\n\n a2ave_mrms = np.full([nypmw,nxpmw], -9999., 'float32')\n a2goodfrac = np.full([nypmw,nxpmw], -9999., 'float32')\n\n a2num_mrms = np.full([nypmw,nxpmw], -9999., 'int16')\n\n lptype = [0,1,2,3,4,6,7,10,91,96]\n d2vfc_type = {} # volume fraction\n d2num_type = {}\n for ptype in lptype:\n d2vfc_type[ptype] = np.full([nypmw,nxpmw], -9999., 'float32')\n d2num_type[ptype] = np.full([nypmw,nxpmw], -9999., 'int16')\n\n for mrmsPath in lmrmsPath: \n slabel = '.'.join(os.path.basename(mrmsPath).split('.')[2:5])\n rqiPath = mrmsDir + '/RQI.%s.asc.gz'%(slabel) \n typePath= mrmsDir + '/MASK.%s.asc.gz'%(slabel)\n\n yyyymmdd=os.path.basename(mrmsPath).split('.')[2]\n hhmnss = os.path.basename(mrmsPath).split('.')[3]\n dtimegv = datetime.strptime(yyyymmdd+hhmnss, '%Y%m%d%H%M%S')\n\n # MRMS file contains the backward 2-min average\n # Confirmed with Pierre.\n idtimegv= dtimegv - timedelta(seconds=60*2)\n edtimegv= dtimegv\n\n if (idtimegv > a1dtime[-1]): continue\n if (edtimegv < a1dtime[0]): continue\n print(slabel, dtimegv)\n print(mrmsPath)\n\n try:\n with gzip.open(mrmsPath, 'rt') as f:\n a2mrms=np.array(f.read().split()[12:], 'float64').reshape(ny_mrms,nx_mrms)\n \n with gzip.open(rqiPath, 'rt') as f:\n a2rqi =np.array(f.read().split()[12:], 'float32').reshape(ny_mrms,nx_mrms)\n\n with gzip.open(typePath, 'rt') as f:\n a2type =np.array(f.read().split()[12:], 'float32').reshape(ny_mrms,nx_mrms)\n\n except:\n print('')\n print('Error')\n print('Skip')\n print('')\n continue\n\n\n #iy=561\n #ix=719\n\n #plt.figure()\n #plt.imshow(ma.masked_less_equal(a2mrms[iy-10:iy+10,ix-10:ix+10],0))\n #plt.colorbar()\n #plt.show()\n\n #plt.figure()\n #plt.imshow(ma.masked_less_equal(a2type[iy-10:iy+10,ix-10:ix+10],0))\n #plt.colorbar()\n #plt.show()\n\n #if a2mrms.max()>0:\n # a = ma.masked_where(a2type<1,a2mrms)\n # a = ma.masked_where(a2rqi<1, a)\n # print a.min(), a.max()\n # sys.exit()\n ##--- test -------\n ##a1latmrms= np.arange(20+0.005, 55-0.005+0.001, 0.01)\n ##a1lonmrms= np.arange(-130+0.005, -60-0.005+0.001, 0.01)\n ##a2lonmrms, a2latmrms = np.meshgrid(a1lonmrms, a1latmrms)\n #a1lonmrms = np.linspace(0,10,7000)\n #a1latmrms = np.linspace(0,10,3500)\n #a2lonmrms, a2latmrms = np.meshgrid(a1lonmrms, a1latmrms)\n #a2mrms = a2lonmrms\n #a2rqi = ma.ones([ny_mrms,nx_mrms])\n\n ##----------------\n\n a2mrms = np.flipud(np.array(a2mrms))\n a2rqi = np.flipud(np.array(a2rqi ))\n a2type = np.flipud(np.array(a2type))\n\n #*****************\n # Padding outer area of MRMS\n #*****************\n dpad = a1nrad[0] + 1 # take the largest rad\n\n a2mrms_pad = np.full([ny_mrms+dpad*2,nx_mrms+dpad*2],-9999., dtype='float64')\n a2mrms_pad[dpad:dpad+ny_mrms, dpad:dpad+nx_mrms] = a2mrms \n\n #*****************\n # Partial extraction of PMW based on time\n #*****************\n iypart = bisect_left(a1dtime, idtimegv) \n eypart = bisect_left(a1dtime, edtimegv) \n nypart = eypart - iypart\n if nypart ==0: continue\n\n a2y_mrms_tmp = a2y_mrms[iypart:eypart] \n a2x_mrms_tmp = a2x_mrms[iypart:eypart] \n\n nypmw_tmp = eypart - iypart+1\n nxpmw_tmp = nxpmw\n\n #print 'iypart,eypart=',iypart,eypart\n ##*****************\n ## Process each angle bin\n ##*****************\n #for ix in range(nxpmw):\n # a1x_mrms = a2x_mrms_tmp[:,ix] # Keeps masks. Should be handled later.\n # a1y_mrms = a2y_mrms_tmp[:,ix]\n\n\n # nrad = a1nrad[ix]\n\n # a2offsetx, a2offsety = np.meshgrid(list(range(-nrad,nrad+1)), list(range(-nrad,nrad+1)))\n # a3collectx = np.array([a2offsetx + x for x in a1x_mrms], 'int32')\n # a3collecty = np.array([a2offsety + y for y in a1y_mrms], 'int32')\n # #a3collectx = np.apply_along_axis(add, 1, a1x_mrms[:,None], a2offsetx).astype('int32')\n # #a3collecty = np.apply_along_axis(add, 1, a1y_mrms[:,None], a2offsety).astype('int32')\n\n # #- If center MRMS pixel is out of boundary then replace ---\n # a1xy_mrms_mask = a1x_mrms.mask + a1y_mrms.mask\n # a3collectx[a1xy_mrms_mask,:,:] = -9999\n # a3collecty[a1xy_mrms_mask,:,:] = -9999\n # #----------------------------------------------------------\n # a1collectx = a3collectx.flatten()\n # a1collecty = a3collecty.flatten()\n\n # #- If MRMS pixel location is out of boundary, then mask and replace --\n # a3collectxy_mask = ma.masked_outside(a3collectx, 0, nx_mrms-1).mask + ma.masked_outside(a3collecty, 0, ny_mrms-1).mask # masks are kept with flatten\n # a1collectxy_mask = ma.masked_outside(a1collectx, 0, nx_mrms-1).mask + ma.masked_outside(a1collecty, 0, ny_mrms-1).mask # masks are kept with flatten\n\n # # temporarily replace with zero\n # a1collectx[a1collectxy_mask] = 0 \n # a1collecty[a1collectxy_mask] = 0\n\n # #- Extract MRMS data ----------------\n # a1collect_prec = a2mrms[a1collecty, a1collectx]\n # a1collect_rqi = a2rqi [a1collecty, a1collectx]\n # a1collect_type = a2type[a1collecty, a1collectx]\n\n # a3collect_prec = a1collect_prec.reshape(-1,nrad*2+1, nrad*2+1) \n # a3collect_rqi = a1collect_rqi .reshape(-1,nrad*2+1, nrad*2+1) \n # a3collect_type = a1collect_type.reshape(-1,nrad*2+1, nrad*2+1) \n\n # #- Mask of invalid MRMS data -----------\n # a3collect_mask = ma.masked_less(a3collect_rqi, 0.8).mask + ma.masked_less(a3collect_prec, 0).mask \n\n # #- Add mask of invalid pixel location --\n # a3collect_mask = a3collect_mask + a3collectxy_mask\n\n # if type(a3collect_mask) == np.bool_:\n # a3collect_mask = np.full(a3collect_prec.shape, a3collect_mask)\n\n # a1goodfrac = ((nrad*2+1)**2 - a3collect_mask.sum(axis=(1,2))) / float( (nrad*2+1)**2)\n\n # a3collect_prec = ma.masked_where(a3collect_mask, a3collect_prec)\n # a3collect_type = ma.masked_where(a3collect_mask, a3collect_type)\n\n # #a2ave_mrms[iypart:eypart,ix] = ma.masked_where(a3collect_mask, a3collect_prec).mean(axis=(1,2)).filled(-9999.)\n # a2ave_mrms[iypart:eypart,ix] = a3collect_prec.mean(axis=(1,2)).filled(-9999.)\n # a2goodfrac[iypart:eypart,ix] = a1goodfrac\n\n # #-- precipitation type info ---\n # a1sum_mrms = a3collect_prec.sum(axis=(1,2))\n\n # a2num_mrms[iypart:eypart,ix] = (2*nrad+1)*(2*nrad+1)\n\n # for ptype in lptype: \n # a3collect_type_mask = ma.masked_not_equal(a3collect_type, ptype).mask\n\n # if a3collect_type_mask is np.True_:\n # d2num_type[ptype][iypart:eypart,ix] = 0\n # d2vfc_type[ptype][iypart:eypart,ix] = 0.\n\n # elif a3collect_type_mask is np.False_:\n # d2num_type[ptype][iypart:eypart,ix] = (2*nrad+1)*(2*nrad+1)\n # d2vfc_type[ptype][iypart:eypart,ix] = 1.0\n\n # else:\n # d2num_type[ptype][iypart:eypart,ix] = (~a3collect_type_mask).sum(axis=(1,2))\n\n # if ptype !=0:\n # d2vfc_type[ptype][iypart:eypart,ix] = ma.masked_invalid( ma.masked_where(a3collect_type_mask, a3collect_prec).sum(axis=(1,2)) / a1sum_mrms ).filled(-9999.)\n\n #a2goodfrac = ma.masked_where(a2ave_mrms<0, a2goodfrac).filled(-9999.)\n tnow = time.time()\n elapsed_time = tnow - tstart \n print(Year,Mon,Day,oid,elapsed_time)\n ##*****************\n ## Save\n ##*****************\n #outDir= tankDir + '/utsumi/PMM/MRMS/level2-pixel-match/%s.%s.%s/%04d/%02d/%02d'%(scantype, sensor, sate, Year, Mon, Day)\n #util.mk_dir(outDir)\n #ave_mrms_path= outDir + '/mrms.%06d.%05d-%05d.npy'%(oid,iscan,escan)\n #goodfrac_path= outDir + '/goodfrac.%06d.%05d-%05d.npy'%(oid,iscan,escan)\n #np.save(ave_mrms_path, a2ave_mrms.astype('float32'))\n #np.save(goodfrac_path, a2goodfrac.astype('float32'))\n\n #num_mrms_path = outDir + '/num-all.%06d.%05d-%05d.npy'%(oid,iscan,escan)\n #np.save(num_mrms_path, a2num_mrms.astype('int16'))\n\n #for ptype in lptype:\n # ave_type_path= outDir + '/pr-%02d.%06d.%05d-%05d.npy'%(ptype, oid,iscan,escan)\n # num_type_path= outDir + '/num-%02d.%06d.%05d-%05d.npy'%(ptype, oid,iscan,escan)\n\n # np.save(num_type_path, d2num_type[ptype].astype('int16'))\n # \n # if ptype !=0:\n # np.save(ave_type_path, d2vfc_type[ptype].astype('float32'))\n\n\n #print(ave_mrms_path)\n \n \n\n\n# %%\n","sub_path":"multisensor/temp.mk.mrmr.orbit.nulti.py","file_name":"temp.mk.mrmr.orbit.nulti.py","file_ext":"py","file_size_in_byte":18517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"539777768","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport xml.etree.ElementTree # parse xml\nimport json # convert containers to json\nimport dateutil.parser # used to parse dates in cdot xml\nimport utils # utility functions to get urls and connect to database\n\ndef get_segments_poly(segments_xml):\n tree = xml.etree.ElementTree.parse(segments_xml)\n return {\"type\": \"FeatureCollection\",\n \"features\": [{\n \"type\": \"Feature\",\n \"properties\": {'Id': int(polyline.find('{http://www.cotrip.org/schema/spatial}Id').text),\n 'Name': polyline.find('{http://www.cotrip.org/schema/spatial}Name').text},\n \"geometry\": {\n \"type\": \"LineString\",\n 'coordinates': [[float(x) for x in item.split(',')] for item in polyline.find(\n '{http://www.cotrip.org/schema/spatial}Points').text.split(',0') if item != '']}}\n for polyline in tree.findall('{http://www.cotrip.org/schema/spatial}Polyline')]}\n\n\nif __name__ == \"__main__\":\n default_database = utils.default_database()\n cdot_segments_xml = utils.get_cdot_xml('Speed Segment Polylines')\n static = get_segments_poly(cdot_segments_xml)\n print(json.dumps(static))\n\n","sub_path":"bin/static_speed_poly.py","file_name":"static_speed_poly.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"343320925","text":"cof=10\r\n\r\nwhile cof!=0:\r\n mon=int(input(\"돈을 입력하세요:\"))\r\n g=mon//300\r\n if mon<300:\r\n print(\"돈을 다시 돌려줍니다.\")\r\n elif mon>=300:\r\n if g>cof:\r\n print(\"커피가 {}잔 밖에 없으므로 {}원을 돌려줍니다\".format(cof,mon-(cof*300)))\r\n break\r\n if mon%300==0:\r\n print(\"커피를 {}잔 줍니다.\".format(g))\r\n else:\r\n print(\"커피를 {}잔 주고 {}원을 돌려줍니다\".format(g,mon%300))\r\n cof-=g\r\n if cof!=0:\r\n print(\"남은 커피의 양은 %d개 입니다.\" % cof)\r\n\r\n\r\nprint(\"커피가 다 떨어졌습니다\")\r\n\r\n","sub_path":"Python/gwaze_3.py","file_name":"gwaze_3.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"142733026","text":"#\n# Copyright (C) 2014, Zebra Technologies\n# Authors: Matt Hooks \n# Zachary Lorusso \n# Modified by Ilya Etingof \n#\n# Redistribution and use in source and binary forms, with or without \n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the \n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF \n# THE POSSIBILITY OF SUCH DAMAGE.\n#\nfrom pysnmp.entity.rfc3413 import cmdgen\nfrom pyasn1.compat.octets import null\nfrom pysnmp.proto.api import v2c\ntry:\n import asyncio\nexcept ImportError:\n import trollius as asyncio\n\ngetNextVarBinds = cmdgen.getNextVarBinds\n\nclass AbstractCommandGenerator:\n commandGenerator = None\n\n def _cbFunWithFuture(self, snmpEngine, sendRequestHandle, errorIndication,\n errorStatus, errorIndex, varBinds, future):\n if future.cancelled():\n return\n future.set_result(\n (snmpEngine, errorIndication, errorStatus, errorIndex, varBinds)\n )\n\n def sendVarBinds(self, snmpEngine, targetName,\n contextEngineId, contextName, varBinds):\n future = asyncio.Future()\n self.commandGenerator.sendVarBinds(\n snmpEngine,\n targetName,\n contextEngineId,\n contextName,\n varBinds,\n self._cbFunWithFuture,\n future\n )\n return future\n \nclass GetCommandGenerator(AbstractCommandGenerator):\n commandGenerator = cmdgen.GetCommandGenerator()\n\nclass SetCommandGenerator(AbstractCommandGenerator):\n commandGenerator = cmdgen.SetCommandGenerator()\n\nclass NextCommandGenerator(AbstractCommandGenerator):\n commandGenerator = cmdgen.NextCommandGenerator()\n\nclass BulkCommandGenerator(AbstractCommandGenerator):\n commandGenerator = cmdgen.BulkCommandGenerator()\n\n def sendVarBinds(self, snmpEngine, targetName,\n contextEngineId, contextName,\n nonRepeaters, maxRepetitions, varBinds):\n future = asyncio.Future()\n self.commandGenerator.sendVarBinds(\n snmpEngine,\n targetName,\n contextEngineId,\n contextName,\n nonRepeaters,\n maxRepetitions,\n varBinds,\n self._cbFunWithFuture,\n future\n )\n return future\n","sub_path":"pysnmp/entity/rfc3413/asyncio/cmdgen.py","file_name":"cmdgen.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"653228069","text":"\"\"\"Project Euler Problem 5\nFind the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.\"\"\"\n\nsumSquare = []\nsquareSum = []\n\nfor i in range(1, 101):\n sumSquare.append(i ** 2)\n squareSum.append(i)\n\nprint((sum(squareSum) ** 2) - sum(sumSquare))\n","sub_path":"python/projectEuler/problem6.py","file_name":"problem6.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"350996661","text":"def numJewelsInStone1(J, S):\n return sum(map(S.count, J))\n\n\ndef numJewelsInStone(J, S):\n resl = set(J)\n count = 0\n for i in S:\n if i in resl:\n count += 1\n return count \n\n\n# hash slow\ndef numJewelsInStone2(J, S):\n resl = {}\n for i in J:\n resl[i] = 0\n for i in S:\n if i in resl:\n resl[i] += 1\n print(resl)\n return sum(resl.values())\n\n\nJ = 'aA'\nS = 'aAAbbbbb'\nprint(numJewelsInStone2(J, S))\n","sub_path":"leetcode/771.py","file_name":"771.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"582851290","text":"from datetime import datetime, timedelta\n\nimport isodate\n\nfrom jbox_util import unquote, CloudHelper\nfrom handlers.handler_base import JBoxHandler\nfrom jbox_container import JBoxContainer\nfrom handlers.auth import AuthHandler\nfrom db.user_v2 import JBoxUserV2\nfrom db.invites import JBoxInvite\nfrom db.accounting_v2 import JBoxAccountingV2\n\n\nclass AdminHandler(JBoxHandler):\n def get(self):\n sessname = unquote(self.get_cookie(\"sessname\"))\n jbox_cookie = AuthHandler.get_session_cookie(self)\n\n if (None == sessname) or (len(sessname) == 0) or (None == jbox_cookie):\n self.send_error()\n return\n\n user_id = jbox_cookie['u']\n cont = JBoxContainer.get_by_name(sessname)\n\n if cont is None:\n self.send_error()\n return\n\n juliaboxver, upgrade_available = self.get_upgrade_available(cont)\n if self.do_upgrade(cont, upgrade_available):\n response = {'code': 0, 'data': ''}\n self.write(response)\n return\n\n user = JBoxUserV2(user_id)\n\n is_admin = sessname in self.config(\"admin_sessnames\", [])\n manage_containers = is_admin or user.has_role(JBoxUserV2.ROLE_MANAGE_CONTAINERS)\n show_report = is_admin or user.has_role(JBoxUserV2.ROLE_ACCESS_STATS)\n invites_perm = is_admin or user.has_role(JBoxUserV2.ROLE_MANAGE_INVITES)\n\n sections = []\n loads = []\n report = {}\n report_span = 'day'\n invites_info = []\n\n action = self.get_argument(\"action\", None)\n #invite_code = self.request.get(\"invite_code\", None)\n if action == \"invites_report\" and invites_perm:\n self.write(dict(\n code=0,\n data=[obj for obj in JBoxInvite.table().scan()]))\n return\n\n if manage_containers:\n sections, loads = self.do_containers()\n\n if show_report:\n today = datetime.now()\n if self.get_argument('range', 'day') == 'week':\n dates = [today - timedelta(days=i) for i in range(6, -1, -1)]\n report_span = 'week'\n else:\n dates = [today]\n report = JBoxAccountingV2.get_stats(dates)\n\n d = dict(\n manage_containers=manage_containers,\n show_report=show_report,\n invites_perm=invites_perm,\n report_span=report_span,\n sessname=sessname,\n user_id=user_id,\n created=isodate.datetime_isoformat(cont.time_created()),\n started=isodate.datetime_isoformat(cont.time_started()),\n allowed_till=isodate.datetime_isoformat((cont.time_started() + timedelta(seconds=self.config('expire')))),\n mem=cont.get_memory_allocated(),\n cpu=cont.get_cpu_allocated(),\n disk=cont.get_disk_allocated(),\n expire=self.config('expire'),\n sections=sections,\n loads=loads,\n report=report,\n juliaboxver=juliaboxver,\n upgrade_available=upgrade_available\n )\n\n self.rendertpl(\"ipnbadmin.tpl\", d=d, cfg=self.config())\n\n def do_upgrade(self, cont, upgrade_available):\n upgrade_id = self.get_argument(\"upgrade_id\", '')\n if (upgrade_id == 'me') and (upgrade_available is not None):\n cont.stop()\n cont.backup()\n cont.delete()\n return True\n return False\n\n @staticmethod\n def get_upgrade_available(cont):\n cont_images = cont.get_image_names()\n juliaboxver = cont_images[0]\n if (JBoxContainer.DCKR_IMAGE in cont_images) or ((JBoxContainer.DCKR_IMAGE + ':latest') in cont_images):\n upgrade_available = None\n else:\n upgrade_available = JBoxContainer.DCKR_IMAGE\n if ':' not in upgrade_available:\n upgrade_available += ':latest'\n return juliaboxver, upgrade_available\n\n def do_containers(self):\n sections = []\n loads = []\n\n iac = []\n ac = []\n sections.append([\"Active\", ac])\n sections.append([\"Inactive\", iac])\n\n delete_id = self.get_argument(\"delete_id\", '')\n stop_id = self.get_argument(\"stop_id\", '')\n stop_all = (self.get_argument('stop_all', None) is not None)\n\n if stop_all:\n all_containers = JBoxContainer.DCKR.containers(all=False)\n for c in all_containers:\n cont = JBoxContainer(c['Id'])\n cname = cont.get_name()\n\n if None == cname:\n self.log_info(\"Admin: Not stopping unknown \" + cont.debug_str())\n elif cname not in self.config(\"protected_docknames\"):\n cont.stop()\n\n elif not (stop_id == ''):\n cont = JBoxContainer(stop_id)\n cont.stop()\n elif not (delete_id == ''):\n cont = JBoxContainer(delete_id)\n cont.delete()\n\n # get them all again (in case we deleted some)\n jsonobj = JBoxContainer.DCKR.containers(all=all)\n for c in jsonobj:\n o = dict()\n o[\"Id\"] = c[\"Id\"][0:12]\n o[\"Status\"] = c[\"Status\"]\n if (\"Names\" in c) and (c[\"Names\"] is not None):\n o[\"Name\"] = c[\"Names\"][0]\n else:\n o[\"Name\"] = \"/None\"\n\n if (c[\"Ports\"] is None) or (c[\"Ports\"] == []):\n iac.append(o)\n else:\n ac.append(o)\n\n # get cluster loads\n average_load = CloudHelper.get_cluster_average_stats('Load')\n if None != average_load:\n loads.append({'instance': 'Average', 'load': average_load})\n\n machine_loads = CloudHelper.get_cluster_stats('Load')\n if None != machine_loads:\n for n, v in machine_loads.iteritems():\n loads.append({'instance': n, 'load': v})\n\n return sections, loads\n","sub_path":"host/tornado/src/handlers/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"489984441","text":"\"\"\"\n[345] Reverse Vowels of a String\n\nhttps://leetcode.com/problems/reverse-vowels-of-a-string/description/\n\n* algorithms\n* Easy (39.90%)\n* Source Code: 345.reverse-vowels-of-a-string.python3.py\n* Total Accepted: 126.1K\n* Total Submissions: 315.6K\n* Testcase Example: '\"hello\"'\n\nWrite a function that takes a string as input and reverse only the vowels of a string.\n\nExample 1:\n\n\nInput: \"hello\"\nOutput: \"holle\"\n\n\n\nExample 2:\n\n\nInput: \"leetcode\"\nOutput: \"leotcede\"\n\n\nNote:\nThe vowels does not include the letter \"y\".\n\"\"\"\n\nclass Solution:\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n s = list(s)\n vowels = {'a', 'e', 'i', 'o', 'u'}\n l = len(s)\n if l <= 1:\n return \"\".join(s)\n b_p, e_p = 0, l-1\n b_f, e_f = False, False\n if s[b_p].lower() in vowels:\n b_f = True\n if s[e_p].lower() in vowels:\n e_f = True\n while b_p != e_p:\n if b_f and e_f:\n # swap\n s[b_p], s[e_p] = s[e_p], s[b_p]\n b_f, e_f = False, False\n elif not b_f:\n b_p += 1\n if s[b_p].lower() in vowels:\n b_f = True\n elif not e_f:\n e_p -= 1\n if s[e_p].lower() in vowels:\n e_f = True\n s = \"\".join(s)\n return s\n","sub_path":"345.reverse-vowels-of-a-string.python3.py","file_name":"345.reverse-vowels-of-a-string.python3.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"633785942","text":"import os\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\nWHERE = 'registrydt/' \nif os.path.exists(WHERE + \"res.csv\"):\n os.remove(WHERE + \"res.csv\")\n os.remove(WHERE + \"res_met.csv\")\n\n_, _, filenames = next(os.walk(WHERE))\n\n# find errors\nk = 0\nfor i in filenames:\n k = k + 1\n sys.stdout.write('\\r' + \"Loading\" + \".\" + str(k))\n if not \"times\" in i and not \"zeros\" in i:\n tmp = pd.read_csv(WHERE + i, delimiter = \",\", header = None)\n if len(tmp) != 145:\n print(i)\n print(len(tmp))\n\n# accuracy\n\n\ndef get_met_acc_increase(tmp_times):\n precdefault = tmp_times[tmp_times['alg'].isin(['testprec'])]['val'].iloc[0]\n data = []\n for i in range(0,len(tmp_times)):\n if 'acc' in tmp_times['alg'].iloc[i]:\n tmp_times['val'].iloc[i] = tmp_times['val'].iloc[i] - precdefault\n tmp_times['alg'].iloc[i] = tmp_times['alg'].iloc[i][:-3]\n data.append(pd.DataFrame([tmp_times.iloc[i]]))\n \n return pd.concat(data)\n\n\n#### calculate accuracy increase with respect to naive prediction\n#### for a single experiment, separately for each metamodel\n\ndef get_result(fname):\n tmp_times = pd.read_csv(WHERE + fname.split(\".\")[0] + '.csv',\\\n delimiter = \",\", header = None)\n tmp_times.columns = ['alg', 'val']\n tmp = get_met_acc_increase(tmp_times)\n \n extra = fname.split(\".\")[0].split(\"_\")\n tmp['dat'] = [extra[0]]*tmp.shape[0]\n tmp['itr'] = [extra[1]]*tmp.shape[0]\n tmp['npt'] = [extra[2]]*tmp.shape[0]\n return tmp\n\n#### read and process data from all experiments with decision trees\n\nres = []\nk = 0\nfor i in filenames:\n k = k + 1\n sys.stdout.write('\\r' + \"Loading\" + \".\" + str(k))\n try:\n if \"times\" in i:\n res.append(get_result(i))\n except:\n print(\"error at \" + i)\nres = pd.concat(res)\nres.to_csv(WHERE + 'res_met.csv')\n\n\n#### accuracy increase\n# res = pd.read_csv(WHERE + 'res.csv', delimiter = \",\")\n\na = res.copy() \na['npt'] = pd.to_numeric(a['npt']) \na = a[['alg', 'npt', 'val']].groupby(['alg', 'npt']).mean()\na.to_csv(WHERE + 'a.csv')\na = pd.read_csv(WHERE + 'a.csv', delimiter = \",\")\nos.remove(WHERE + \"a.csv\")\n\n","sub_path":"read_results_dt_new.py","file_name":"read_results_dt_new.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"499576275","text":"import matplotlib.pyplot as plt\n\n# Create figure, 5 inches by 5 inches\nplt.figure(figsize=(5,5))\n\nlabels = [\"USA\",\"China\",\"India\",\"Canada\",\"Turkey\"]\nvalues = [25,10,15,40,23]\n\n# Pop up section of the pie chart\nexplode = [0,0,0,0.05,0]\n\n# Change colors in the pie chart\n# You can use RGB and HEX values\ncolors = [\"c\",\"b\",\"g\",\"r\",\"y\"]\n\n# Create pie chart\nplt.pie(values, labels=labels, autopct=\"%.1f%%\", explode=explode, colors=colors)\n\nplt.show()\n","sub_path":"PieChart.py","file_name":"PieChart.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"515856367","text":"from flask import Flask, render_template\nfrom models.forms import LoginForm\n\napp = Flask(__name__)\n# A secret key is needed to make the form work\napp.secret_key = 'ERSD345qwRFwas4'\n\n\n@app.route('/')\ndef home():\n\treturn render_template('views/home.html')\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n\t# Assign the LoginForm class to a variable to be able to render the form\n\tform = LoginForm()\n\tif form.validate_on_submit():\n\t\treturn 'Successfully logged in'\n\treturn render_template('views/login.html', form=form)\n\n\nif __name__ == '__main__':\n\tapp.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"498067824","text":"from flake8.formatting import base\n\nfrom flake8_truveris import (\n trailing_commas,\n)\n\nerror_modules = {\n \"T812\": trailing_commas,\n}\n\n\nclass FormatTruveris(base.BaseFormatter):\n\n error_format = \"%(path)s:%(row)d:%(col)d: %(code)s %(text)s\"\n\n def format(self, error):\n return self.error_format % {\n \"code\": error.code,\n \"text\": error.text,\n \"path\": error.filename,\n \"row\": error.line_number,\n \"col\": error.column_number,\n }\n\n def handle(self, error):\n line = self.format(error)\n source = self.show_source(error)\n self.write(line, source)\n\n if error.code[0] == \"T\" and error.code[1:].isdigit():\n # error was generated by flake8-truveris\n with open(error.filename, 'r') as file:\n # read a list of lines into data\n data = file.readlines()\n\n data = error_modules[error.code].fix(data, error)\n\n with open(error.filename, 'w') as file:\n file.writelines(data)\n","sub_path":"flake8_truveris/format_truveris.py","file_name":"format_truveris.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"414176433","text":"#!/usr/bin/env python3\n\n# Copyright 2021, Autonomous Space Robotics Lab (ASRL)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport uuid\nimport time\nimport math\nfrom enum import Enum\n\nimport rclpy\nfrom rclpy.action import ActionClient\nfrom action_msgs.msg import GoalStatus\nfrom collections import OrderedDict\n\nfrom vtr_mission_planning.ros_manager import RosManager\nfrom vtr_mission_planning.mission_client import MissionClient\nfrom builtin_interfaces.msg import Duration\nfrom unique_identifier_msgs.msg import UUID\nfrom vtr_messages.action import Mission\nfrom vtr_messages.srv import MissionPause\nfrom vtr_messages.msg import MissionStatus\n\nif __name__ == \"__main__\":\n mc = MissionClient()\n mc.start()\n\n print(\"\\nStart\")\n mc.set_pause(False)\n\n print(\"\\nAdd an Idle goal, cancel after succeeded\")\n uuid = mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n time.sleep(2)\n time.sleep(1)\n mc.cancel_goal(uuid) # no goal to cancel as it has succeeded\n print(\"\\nAdd an Idle goal, cancel before it is accepted\")\n uuid = mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n mc.cancel_goal(uuid) # no goal to cancel as it has not been accepted\n time.sleep(2)\n time.sleep(1)\n print(\"\\nAdd an Idle goal, cancel before it is executed\")\n uuid = mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n time.sleep(0.5)\n mc.cancel_goal(uuid) # no goal to cancel as it has not been accepted\n time.sleep(1.5)\n time.sleep(1)\n print(\"\\nAdd an Idle goal, cancel after it is executed but before finished\")\n uuid = mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n time.sleep(1.5)\n mc.cancel_goal(uuid) # no goal to cancel as it has not been accepted\n time.sleep(0.5)\n time.sleep(1)\n\n print(\"\\nAdd two Idle goal, cancel after succeeded\")\n uuid0 = mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n time.sleep(0.5)\n uuid1 = mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n time.sleep(4)\n time.sleep(1)\n mc.cancel_all() # no goal to cancel as both have succeeded\n print(\"\\nAdd two Idle goal cancel the first before it is finished.\")\n uuid0 = mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n time.sleep(0.5)\n uuid1 = mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n time.sleep(0.5)\n mc.cancel_goal(uuid0) # first goal canceled\n time.sleep(3.5)\n time.sleep(1)\n print(\"\\nAdd two Idle goal cancel the first after it is finished\")\n uuid0 = mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n time.sleep(0.5)\n uuid1 = mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n time.sleep(1.5)\n mc.cancel_goal(uuid0) # no goal to cancel as it is finished\n time.sleep(1.5)\n time.sleep(1)\n\n print(\"\\nStop\")\n mc.set_pause(True)\n mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n mc.add_goal(Mission.Goal.IDLE, (), 1, 1)\n time.sleep(1)\n mc.cancel_all()\n\n # Shut down\n time.sleep(1)\n mc.shutdown()\n","sub_path":"main/src/vtr_mission_planning/test/mission_client_tests.py","file_name":"mission_client_tests.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"236978266","text":"from flask import Blueprint, request, session, redirect, url_for, render_template\nimport os\nimport datetime\nimport pandas as pd\nfrom src.common.flask_redirect import redirect_url\nfrom src.models.users.decorators import requires_login\nfrom src.models.users.user import User\nfrom src.models.data.data_item import DataItem\nfrom src.common.utils import Utils\n\ndata_blueprint = Blueprint('data', __name__)\n\nuploaddir = os.path.join(os.path.dirname(os.path.abspath(__file__)), \n os.path.normpath('../../../../uploaded'))\n\nlogger = Utils.get_logger(__name__)\n\n@data_blueprint.route('/upload', methods=['POST'])\n@requires_login\ndef handle_upload():\n\n ### Get file descriptions from form ###\n description = \"NA\" #request.form.get('dataUploadTextArea')\n\n\n ### Get user id ###\n userid = User.find_by_email(session[\"email\"])._id\n\n ### Create data folder ###\n datadir = os.path.join(uploaddir,os.path.normpath(\"{}/\".format(userid)))\n\n if not os.path.exists(datadir):\n os.mkdir(datadir)\n\n ### upload data ###\n h5_output_file = os.path.join(datadir,os.path.normpath(\"userdata.h5\"))\n\n ### Store compress data has hd5\n with pd.HDFStore(h5_output_file, mode='a', complevel=9) as store:\n\n for key, f in request.files.items():\n if key.startswith('file'):\n \n ### data to server ###\n file = os.path.join(datadir, f.filename)\n f.save(file)\n\n ### Store csvfile in h5 format ###\n df = DataItem.import_csv(file)\n dataname = DataItem.get_dataset_name(file)\n columnsstring = ','.join(list(df.columns))\n filesize = os.path.getsize(file)\n\n ctr,dataname0 = 0,dataname\n while '/'+dataname in store.keys():\n logger.warning(\"Dataset exists! Changing name in DB.\")\n dataname=dataname0+\"_\"+str(ctr)\n ctr+=1\n\n store.put(dataname, df) \n\n ### Create data object ###\n dataItem = DataItem(dataname, h5_output_file, userid, columnsstring, filesize, description=description).save_to_db()\n\n ### Delete csv file ###\n try:\n os.remove(file)\n except:\n logger.warning(\"Couldn't delete file: {}\".format(file))\n\n return '', 204\n\n\n@data_blueprint.route('/form', methods=['POST'])\ndef handle_form():\n description = request.form.get('dataUploadTextArea')\n return 'file uploaded and form submit
    title: %s
    description: %s' % (\"title\", description)\n\n\n@data_blueprint.route('/explorer')\n@requires_login\ndef explorer():\n return render_template(\"data/databrowser.html\", dataItems=DataItem.getDataItems())\n \n\n@data_blueprint.route('/remove')\n@requires_login\ndef remove():\n\n \n item = DataItem.find_by_id(request.args.get('dataid'))\n \n if not item is None: \n item.h5filepath\n item.dataname\n\n with pd.HDFStore(item.h5filepath) as store:\n store.remove(item.dataname)\n\n item.remove_from_DB()\n del item;\n return \"DataItem deleted successfully!\"\n\n\n return \"Couldn't delete DataItem\"","sub_path":"src/models/data/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"592549063","text":"\r\n\r\ndef print_pub(lis1, lis2):\r\n len1 = len(lis1)\r\n len2 = len(lis2)\r\n i = 0\r\n j = 0\r\n res = []\r\n while i < len1 and j < len2:\r\n if lis1[i] == lis2[j]:\r\n res.append(lis1[i])\r\n i += 1\r\n j += 1\r\n elif lis1[i] < lis2[j]:\r\n i += 1\r\n else:\r\n j += 1\r\n\r\n return res\r\n\r\n\r\n# 输出函数\r\n# 输出形式 1 2 3 4 5 !!第一种方法会有一个空格!!!\r\n# 为了避免最后一个空格,可以使用注释掉的语句\r\ndef output(res):\r\n for re in res:\r\n #print(re, end=' ')\r\n print(re, end=' 'if re != res[-1] else '')\r\n\r\n\r\nif __name__ == '__main__':\r\n n = input()\r\n lis1 = list(map(int, input().split()))\r\n n = input()\r\n lis2 = list(map(int, input().split()))\r\n res = print_pub(lis1, lis2)\r\n output(res)\r\n\r\n","sub_path":"sharepython/printpublic.py","file_name":"printpublic.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"126531410","text":"\"\"\"NVDM Tensorflow implementation by Yishu Miao\"\"\"\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nimport math\nimport os\nfrom nvdm import utils\nfrom sklearn.metrics import precision_recall_fscore_support\nfrom sklearn.metrics import accuracy_score\n#import model.utils as utils\n#from sklearn.preprocessing import MultiLabelBinarizer\n#import sklearn.metrics.pairwise as pw\n#from gensim.models import CoherenceModel\n#from gensim.corpora.dictionary import Dictionary\n#import model.evaluate as eval\n#import model.data_lstm as data\n\nseed = 42\ntf_op_seed = 1234\nnp.random.seed(seed)\ntf.set_random_seed(seed)\n\n#learning_rate = 5e-5\n#batch_size = 64\n#n_hidden = 256\n\n#fixed_topic_params \n\n#n_topic = 150\n#n_sample = 1\n#non_linearity = tf.nn.tanh\nnon_linearity = tf.nn.sigmoid\n######\n\nclass NVDM(object):\n\t\"\"\" Neural Variational Document Model -- BOW VAE.\n\t\"\"\"\n\t#def __init__(self, topic_params, prior_embeddings=None, initializer_nvdm=None):\n\tdef __init__(self, topic_params, x, mask , topic_vocab_size, label_ids, n_labels, prior_embeddings=None, initializer_nvdm=None):\n\n\t\t#self.vocab_size = topic_params.TM_vocab_length\n\t\tself.vocab_size = topic_vocab_size\n\t\tself.n_hidden = topic_params.hidden_size_TM\n\t\tself.n_topic = topic_params.n_topic\n\t\tself.n_sample = topic_params.n_sample\n\t\tself.non_linearity = non_linearity\n\t\tself.learning_rate = topic_params.nvdm_learning_rate\n\t\tself.batch_size = topic_params.nvdm_batch_size\n\t\tself.x = x\n\t\tself.mask = mask\n\t\tself.label_ids = label_ids\n\t\tself.n_labels = n_labels \n\n\n\t\t#self.x = tf.placeholder(tf.float32, [None, self.vocab_size], name='x')\n\t\t#self.mask = tf.placeholder(tf.float32, [None], name='mask') # mask paddings\n\n\t\t#if topic_params.use_sent_topic_rep:\n\t\t\t#self.x_sent = tf.placeholder(tf.float32, [None, None, self.vocab_size], name='x_sent')\n\n\t\t#if topic_params.use_topic_embedding:\n\t\t#\tself.x_doc_mask = tf.placeholder(tf.float32, [None, self.vocab_size], name='x_doc_mask')\n\n\t\t#self.input_batch_size = tf.placeholder(tf.int32, (), name='input_batch_size')\n\t\tself.input_batch_size = tf.shape(self.x)[0]\n\t\t#if topic_params.use_sent_topic_rep:\n\t\t#\tself.input_batch_size_sent = tf.shape(self.x_sent)[0]\n\t\t#\tself.input_batch_len_sent = tf.shape(self.x_sent)[1]\n\t\t#\tself.batch_size_sent = self.input_batch_size_sent * self.input_batch_len_sent\n\n\t\t# encoder\n\t\twith tf.variable_scope('TM_encoder', reuse=tf.AUTO_REUSE): \n\t\t\tself.enc_vec = utils.mlp(self.x, [self.n_hidden], self.non_linearity, initializer=initializer_nvdm[0])\n\t\t\t#self.enc_vec = utils.mlp(self.x, [self.n_hidden, self.n_hidden], self.non_linearity, initializer=initializer_nvdm[0])\n\t\t\t#self.enc_vec = utils.mlp(self.x, [self.n_hidden, self.n_hidden], self.non_linearity)\n\t\t\tself.mean = utils.nvdm_linear(self.enc_vec,\n\t\t\t\t\t\t\t\t\t\tself.n_topic,\n\t\t\t\t\t\t\t\t\t\tscope='mean',\n\t\t\t\t\t\t\t\t\t\tmatrix_initializer=initializer_nvdm[1][0],\n\t\t\t\t\t\t\t\t\t\tbias_initializer=initializer_nvdm[1][1])\n\t\t\tself.logsigm = utils.nvdm_linear(self.enc_vec, \n\t\t\t\t\t\t\t\t\tself.n_topic, \n\t\t\t\t\t\t\t\t\tbias_start_zero=True,\n\t\t\t\t\t\t\t\t\tmatrix_start_zero=True,\n\t\t\t\t\t\t\t\t\tscope='logsigm',\n\t\t\t\t\t\t\t\t\tmatrix_initializer=initializer_nvdm[2][0],\n\t\t\t\t\t\t\t\t\tbias_initializer=initializer_nvdm[2][1])\n\t\t\tself.kld = -0.5 * tf.reduce_sum(1 - tf.square(self.mean) + 2 * self.logsigm - tf.exp(2 * self.logsigm), 1)\n\t\t\t#self.kld = self.mask*self.kld # mask paddings\n\t\t\tself.kld = tf.multiply(self.mask, self.kld, name='kld') # mask paddings\n\n\t\t\t#if topic_params.use_sent_topic_rep:\n\t\t\t#\tself.x_sent_reshape = tf.reshape(self.x_sent, [-1, self.vocab_size])\n\t\t\t#\tself.enc_vec_sent = utils.mlp(self.x_sent_reshape, [self.n_hidden], self.non_linearity)\n\t\t\t#\t#self.enc_vec = utils.mlp(self.x, [self.n_hidden, self.n_hidden], self.non_linearity)\n\t\t\t#\tself.mean_sent = utils.nvdm_linear(self.enc_vec_sent, self.n_topic, scope='mean')\n\t\t\t#\tself.logsigm_sent = utils.nvdm_linear(self.enc_vec_sent, \n\t\t\t#\t\t\t\t\t\t\tself.n_topic, \n\t\t\t#\t\t\t\t\t\t\tbias_start_zero=True,\n\t\t\t#\t\t\t\t\t\t\tmatrix_start_zero=True,\n\t\t\t#\t\t\t\t\t\t\tscope='logsigm')\n\n\t\t\t#if topic_params.prior_emb_for_topics:\n\t\t\t#\tW_prior = tf.get_variable(\n\t\t\t#\t\t'embeddings_TM_prior',\n\t\t\t#\t\tdtype=tf.float32,\n\t\t\t#\t\tinitializer=prior_embeddings,\n\t\t\t#\t\ttrainable=False\n\t\t\t#\t)\n\t\t\t\"\"\"\n\t\t\tW_prior_proj = tf.get_variable(\n\t\t\t\t'embeddings_TM_prior_proj',\n\t\t\t\t[prior_embeddings.shape[1], self.n_topic],\n\t\t\t\tdtype=tf.float32,\n\t\t\t\ttrainable=False\n\t\t\t)\n\t\t\tW_prior = tf.matmul(W_prior, W_prior_proj, name='W_prior_projected')\n\t\t\t\"\"\"\n\t\t\t\t\n\n\t\t\n\t\twith tf.variable_scope('TM_decoder', reuse=tf.AUTO_REUSE):\n\t\t\tif self.n_sample == 1:\n\t\t\t\teps = tf.random_normal((self.input_batch_size, self.n_topic), mean=0.0, stddev=1.0, seed=seed)\n\t\t\t\t#doc_vec = tf.mul(tf.exp(self.logsigm), eps) + self.mean\n\n\t\t\t\t## Hidden representation to be used in BERT\n\t\t\t\tself.doc_vec = tf.add(tf.multiply(tf.exp(self.logsigm), eps), self.mean, name='doc_hidden')\n\n\t\t\t\t\n\t\t\t\tself.doc_vec = tf.nn.softmax(self.doc_vec, axis = 1)\n\t\t\t\t\n\t\t\t\tself.last_h = self.doc_vec\n\t\t\t\tlogits_projected, self.decoding_matrix = utils.nvdm_linear(self.doc_vec, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.vocab_size, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tscope='projection', \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tget_matrix=True,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmatrix_initializer=initializer_nvdm[3][0],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbias_initializer=initializer_nvdm[3][1])\n\t\t\t\tlogits = tf.nn.log_softmax(logits_projected)\n\t\t\t\tself.recons_loss = -tf.reduce_sum(tf.multiply(logits, self.x), 1)\n\n\t\t\t\tsup_logits = utils.nvdm_linear(self.doc_vec, self.n_labels, scope='supervised')\n\n\t\t\t\tif topic_params.multilabel:\n\t\t\t\t\tself.sup_prob = tf.nn.sigmoid(sup_logits)\n\t\t\t\t\tself.supervised_loss = tf.multiply(self.mask, tf.reduce_sum(tf.losses.sigmoid_cross_entropy(self.label_ids, sup_logits , reduction=\"none\"), axis=-1))\n\n\t\t\t\telse:\n\t\t\t\t\tself.sup_prob = tf.nn.softmax(sup_logits, axis=-1)\n\t\t\t\t\tlog_prob = tf.nn.log_softmax(sup_logits)\n\t\t\t\t\tself.one_hot_labels = tf.one_hot(self.label_ids, depth=n_labels, on_value = 1.0, off_value = 0.0, dtype=tf.float32)\n\t\t\t\t\tself.supervised_loss = -tf.reduce_sum(tf.multiply(log_prob, self.one_hot_labels), 1)\n\n\n\n\t\t\t\t\"\"\"\n\t\t\t\tif topic_params.use_topic_embedding:\n\t\t\t\t\t#self.last_h_topic_emb = utils.nvdm_linear(tf.nn.softmax(self.last_h, axis=1), self.vocab_size, scope='projection')\n\t\t\t\t\t#self.top_k = tf.nn.top_k(self.decoding_matrix, k=topic_params.use_k_topic_words, sorted=False)\n\t\t\t\t\ttopics_masked = tf.multiply(tf.expand_dims(self.x_doc_mask, axis=1), tf.expand_dims(self.decoding_matrix, axis=0), name='topics_masked')\n\t\t\t\t\tself.top_k = tf.nn.top_k(topics_masked, k=topic_params.use_k_topic_words, sorted=False)\n\t\t\t\t\tif topic_params.prior_emb_for_topics:\n\t\t\t\t\t\tself.top_k_embeddings = tf.nn.embedding_lookup(W_prior, self.top_k.indices)\n\t\t\t\t\t\tself.topic_emb_size = prior_embeddings.shape[1]\n\t\t\t\t\t\t#self.topic_emb_size = prior_embeddings.shape[1] * topic_params.use_k_topics\n\t\t\t\t\t\t#self.topic_emb_size = prior_embeddings.shape[1] + self.n_topic\n\t\t\t\t\t\t#self.topic_emb_size = self.n_topic\n\t\t\t\t\t\t#self.topic_emb_size = self.n_topic * 2\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.top_k_embeddings = tf.nn.embedding_lookup(tf.transpose(self.decoding_matrix), self.top_k.indices)\n\t\t\t\t\t\t#self.topic_emb_size = self.n_topic\n\t\t\t\t\t\tself.topic_emb_size = self.n_topic * 2\n\t\t\t\t\t#self.top_k_embeddings = tf.multiply(tf.expand_dims(tf.nn.softmax(self.top_k.values, axis=1), axis=2), self.top_k_embeddings)\n\t\t\t\t\t#self.temp_1 = tf.expand_dims(tf.nn.softmax(self.top_k.values, axis=2), axis=2)\n\t\t\t\t\t#self.topic_embeddings = tf.squeeze(tf.matmul(self.temp_1, self.top_k_embeddings), axis=2, name='topic_embeddings')\n\t\t\t\t\t#self.topic_embeddings = tf.reduce_sum(self.top_k_embeddings, axis=1, name='topic_embeddings')\n\t\t\t\t\t#self.topic_embeddings = tf.reduce_mean(self.top_k_embeddings, axis=1, name='topic_embeddings')\n\t\t\t\t\tself.topic_embeddings = tf.reduce_mean(self.top_k_embeddings, axis=2, name='topic_embeddings')\n\n\t\t\t\t\tif topic_params.use_k_topics > 0:\n\t\t\t\t\t\t# Masking document topic proportion vector\n\t\t\t\t\t\ttop_k_h_values, top_k_h_indices = tf.nn.top_k(self.last_h, k=topic_params.use_k_topics, sorted=False, name='top_k_h')\n\t\t\t\t\t\trow_numbers = tf.tile(tf.expand_dims(tf.range(0, self.input_batch_size), 1), [1, topic_params.use_k_topics], name='row_numbers')\n\t\t\t\t\t\tfull_indices = tf.concat([tf.expand_dims(row_numbers, -1), tf.expand_dims(top_k_h_indices, -1)], axis=2)\n\t\t\t\t\t\tfull_indices = tf.reshape(full_indices, [-1, 2], name='full_indices')\n\t\t\t\t\t\t#mask_updates = tf.ones([self.input_batch_size * topic_params.use_k_topics], dtype=tf.float32, name='mask_updates')\n\t\t\t\t\t\t#new_mask = tf.scatter_nd(full_indices, mask_updates, [self.input_batch_size, self.n_topic], name='new_mask')\n\t\t\t\t\t\t#last_h_softmax = tf.multiply(tf.nn.softmax(self.last_h, axis=1), new_mask, name='last_h_softmax')\n\t\t\t\t\t\tlast_h_softmax = tf.scatter_nd(\n\t\t\t\t\t\t\tfull_indices, \n\t\t\t\t\t\t\ttf.reshape(tf.nn.softmax(top_k_h_values, axis=1), [-1]), \n\t\t\t\t\t\t\t#tf.ones([self.input_batch_size * topic_params.use_k_topics], dtype=tf.float32), \n\t\t\t\t\t\t\t[self.input_batch_size, self.n_topic], \n\t\t\t\t\t\t\tname='last_h_softmax'\n\t\t\t\t\t\t)\n\t\t\t\t\telse:\n\t\t\t\t\t\tlast_h_softmax = tf.nn.softmax(self.last_h, axis=1, name='last_h_softmax')\n\t\t\t\t\t\t#last_h_softmax = self.last_h\n\t\t\t\t\t\t\n\t\t\t\t\t#self.last_h_topic_emb = tf.matmul(last_h_softmax, self.topic_embeddings, name='last_h_topic_emb')\n\t\t\t\t\tself.last_h_topic_emb = tf.squeeze(tf.matmul(tf.expand_dims(last_h_softmax, axis=1), self.topic_embeddings), axis=1, name='last_h_topic_emb')\n\t\t\t\t\t#temp = tf.nn.embedding_lookup(self.topic_embeddings, top_k_h_indices)\n\t\t\t\t\t#self.last_h_topic_emb = tf.reduce_sum(temp, axis=1, name='last_h_topic_emb')\n\t\t\t\t\t#self.last_h_topic_emb = tf.reshape(temp, [self.input_batch_size, self.topic_emb_size], name='last_h_topic_emb')\n\t\t\t\t\t#self.last_h_topic_emb = tf.concat([self.last_h_topic_emb, last_h_softmax], axis=1)\n\t\t\t\t\t#self.last_h_topic_emb = tf.concat([self.last_h_topic_emb, self.last_h], axis=1)\n\t\t\t\"\"\"\n\t\t\telse:\n\t\t\t\teps = tf.random_normal((self.n_sample*self.input_batch_size, self.n_topic), mean=0.0, stddev=1.0, seed=seed)\n\t\t\t\teps_list = tf.split(eps, self.n_sample, 0)\n\t\t\t\trecons_loss_list = []\n\t\t\t\tdoc_vec_list = []\n\t\t\t\tfor i in range(self.n_sample):\n\t\t\t\t\tif i > 0: tf.get_variable_scope().reuse_variables()\n\t\t\t\t\tcurr_eps = eps_list[i]\n\t\t\t\t\tdoc_vec = tf.add(tf.multiply(tf.exp(self.logsigm), curr_eps), self.mean)\n\t\t\t\t\t\n\t\t\t\t\tdoc_vec = tf.nn.softmax(doc_vec, axis=1)\n\t\t\t\t\tdoc_vec_list.append(doc_vec)\n\t\t\t\t\tlogits = tf.nn.log_softmax(utils.nvdm_linear(doc_vec, self.vocab_size, scope='projection'))\n\t\t\t\t\trecons_loss_list.append(-tf.reduce_sum(tf.multiply(logits, self.x), 1))\n\t\t\t\tself.recons_loss = tf.add_n(recons_loss_list) / self.n_sample\n\t\t\t\tself.doc_vec = tf.add_n(doc_vec_list) / self.n_sample\n\t\t\t\tself.last_h = self.doc_vec\n\n\t\t\t\tsup_logits = utils.nvdm_linear(self.doc_vec, self.n_labels, scope='supervised')\n\n\t\t\t\tif topic_params.multilabel:\n\t\t\t\t\tself.sup_prob = tf.nn.sigmoid(sup_logits)\n\t\t\t\t\tself.supervised_loss = tf.multiply(self.mask, tf.reduce_sum(tf.losses.sigmoid_cross_entropy(self.label_ids, sup_logits , reduction=\"none\"), axis=-1))\n\n\t\t\t\telse:\n\t\t\t\t\tself.sup_prob = tf.nn.softmax(sup_logits, axis=-1)\n\t\t\t\t\tlog_prob = tf.nn.log_softmax(sup_logits)\n\t\t\t\t\tself.one_hot_labels = tf.one_hot(self.label_ids, depth=n_labels, on_value = 1.0, off_value = 0.0, dtype=tf.float32)\n\t\t\t\t\tself.supervised_loss = -tf.reduce_sum(tf.multiply(log_prob, self.one_hot_labels), 1)\n\n\t\t\t\"\"\"\"\n\t\t\tif topic_params.use_sent_topic_rep:\n\t\t\t\tif self.n_sample == 1:\n\t\t\t\t\teps_sent = tf.random_normal((self.batch_size_sent, self.n_topic), mean=0.0, stddev=1.0, seed=seed)\n\t\t\t\t\tself.last_h_sent = tf.add(tf.multiply(tf.exp(self.logsigm_sent), eps_sent), self.mean_sent, name='sent_hidden')\n\t\t\t\t\tself.last_h_sent = tf.reshape(self.last_h_sent, [self.input_batch_size_sent, self.input_batch_len_sent, self.n_topic])\n\n\t\t\t\t\tif topic_params.use_topic_embedding:\n\t\t\t\t\t\t#self.last_h_topic_emb_sent = utils.nvdm_linear(tf.nn.softmax(self.last_h_sent, axis=1), self.vocab_size, scope='projection')\n\t\t\t\t\t\tif topic_params.use_k_topics > 0:\n\t\t\t\t\t\t\t# Masking sentence topic proportion vector\n\t\t\t\t\t\t\ttop_k_h_sent_values, top_k_h_sent_indices = tf.nn.top_k(self.last_h_sent, k=topic_params.use_k_topics, sorted=False, name='top_k_h_sent')\n\t\t\t\t\t\t\trow_numbers_sent = tf.tile(tf.expand_dims(tf.range(0, self.batch_size_sent), 1), [1, topic_params.use_k_topics], name='row_numbers_sent')\n\t\t\t\t\t\t\tfull_indices_sent = tf.concat([tf.expand_dims(row_numbers_sent, -1), tf.expand_dims(top_k_h_sent_indices, -1)], axis=2)\n\t\t\t\t\t\t\tfull_indices_sent = tf.reshape(full_indices_sent, [-1, 2], name='full_indices_sent')\n\t\t\t\t\t\t\t#mask_updates_sent = tf.ones([self.batch_size_sent * topic_params.use_k_topics], dtype=tf.float32, name='mask_updates_sent')\n\t\t\t\t\t\t\t#new_mask_sent = tf.scatter_nd(full_indices_sent, mask_updates_sent, [self.batch_size_sent, self.n_topic], name='new_mask_sent')\n\t\t\t\t\t\t\t#last_h_softmax_sent = tf.multiply(tf.nn.softmax(self.last_h_sent, axis=1), new_mask_sent, name='last_h_softmax_sent')\n\t\t\t\t\t\t\tlast_h_softmax_sent = tf.scatter_nd(full_indices_sent, tf.reshape(tf.nn.softmax(top_k_h_sent_values, axis=1), [-1]), [self.batch_size_sent, self.n_topic], name='last_h_softmax_sent')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tlast_h_softmax_sent = tf.nn.softmax(self.last_h_sent, axis=2, name='last_h_softmax_sent')\n\t\t\t\t\t\t\n\t\t\t\t\t\tself.last_h_topic_emb_sent = tf.matmul(last_h_softmax_sent, self.topic_embeddings, name='last_h_topic_emb_sent')\n\t\t\t\t\t\t#self.last_h_topic_emb_sent = tf.concat([self.last_h_topic_emb_sent, self.last_h_sent], axis=2, name='last_h_topic_emb_sent')\n\t\t\t\t\t\t#self.last_h_topic_emb_sent = tf.concat([self.last_h_topic_emb_sent, last_h_softmax_sent], axis=2, name='last_h_topic_emb_sent')\n\t\t\t\t\t\t#self.last_h_topic_emb_sent = tf.reshape(self.last_h_topic_emb_sent, [self.input_batch_size_sent, self.input_batch_len_sent, self.vocab_size])\n\t\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Error: model_NVDM.py - Decoder\")\n\t\t\t\t\tsys.exit()\n\t\t\t\"\"\"\n\n\t\t#self.objective_TM = self.recons_loss + self.kld\n\t\t#self.objective_TM = tf.add(self.recons_loss, self.kld, name='TM_loss_unnormed')\n\t\t#self.final_loss = tf.add(self.recons_loss, self.kld, name='TM_loss_unnormed')\n\n\t\tself.unsupervised_loss = tf.add(self.recons_loss, self.kld, name='TM_loss_unnormed')\n\t\tself.final_loss = tf.add((1-topic_params.beta)*self.unsupervised_loss, topic_params.beta*(self.supervised_loss), \"TM_combined_loss\")\n\n\t\tself.objective_TM = tf.reduce_mean(self.final_loss)\n\n\t\t\"\"\"\n\t\tif topic_params.TM_uniqueness_loss:\n\t\t\t## NVDM topic uniqueness loss\n\t\t\teye = tf.constant(np.eye(self.n_topic), dtype=tf.float32)\n\t\t\ttopicnorm = matrix / tf.sqrt(tf.reduce_sum(tf.square(self.decoding_matrix), 1, keepdims=True))\n\t\t\tuniqueness = tf.reduce_max(tf.square(tf.matmul(topicnorm, tf.transpose(topicnorm)) - eye))\n\t\t\tself.objective_TM += topic_params.alpha_uniqueness * uniqueness\n\t\t\"\"\"\n\n\t\n\t\t\n\t\toptimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)\n\t\t#fullvars = tf.trainable_variables()\n\n\t\t#enc_vars = utils.variable_parser(fullvars, 'TM_encoder')\n\t\tenc_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='TM_encoder')\n\t\t#dec_vars = utils.variable_parser(fullvars, 'TM_decoder')\n\t\tdec_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='TM_decoder')\n\t\tself.pretrain_saver = tf.train.Saver(enc_vars + dec_vars)\n\n\t\tenc_grads = tf.gradients(self.objective_TM, enc_vars)\n\t\tdec_grads = tf.gradients(self.objective_TM, dec_vars)\n\n\t\tself.optim_enc = optimizer.apply_gradients(zip(enc_grads, enc_vars))\n\t\tself.optim_dec = optimizer.apply_gradients(zip(dec_grads, dec_vars))\n\t\t\n\n\t## Pretraining of NVDM-TM\n\tdef pretrain(self, dataset, topic_params, nvdm_datadir , session,\n\t\t\t\t#training_epochs=1000, alternate_epochs=10):\n\t\t\t\t#training_epochs=100, alternate_epochs=10):\n\t\t\t\ttraining_epochs=20, alternate_epochs=10):\n\t\t\t\t#training_epochs=1, alternate_epochs=1):\n\n\t\t#log_dir = os.path.join(topic_params.model, 'logs_nvdm_pretrain')\n\t\t#model_dir_ir_nvdm = os.path.join(topic_params.model, 'model_ir_nvdm_pretrain')\n\t\t#model_dir_ppl_nvdm = os.path.join(topic_params.model, 'model_ppl_nvdm_pretrain')\n\t\tlog_dir = os.path.join(topic_params.output_dir, 'logs_nvdm_pretrain')\n\t\tmodel_dir_ir_nvdm = os.path.join(topic_params.output_dir, 'model_ir_nvdm_pretrain')\n\t\tmodel_dir_ppl_nvdm = os.path.join(topic_params.output_dir, 'model_ppl_nvdm_pretrain')\n\t\tmodel_dir_f1_nvdm = os.path.join(topic_params.output_dir, 'model_f1_nvdm_pretrain')\n\n\t\t#model_dir_supervised = os.path.join(topic_params.model, 'model_supervised_nvdm_pretrain')\n\n\t\tif not os.path.isdir(log_dir):\n\t\t\tos.mkdir(log_dir)\n\t\tif not os.path.isdir(model_dir_ir_nvdm):\n\t\t\tos.mkdir(model_dir_ir_nvdm)\n\t\tif not os.path.isdir(model_dir_ppl_nvdm):\n\t\t\tos.mkdir(model_dir_ppl_nvdm)\n\t\t#if not os.path.isdir(model_dir_supervised):\n\t\t#\tos.mkdir(model_dir_supervised)\n\n\t\t#train_url = os.path.join(topic_params.dataset, 'training_nvdm_docs_non_replicated.csv')\n\t\t#dev_url = os.path.join(topic_params.dataset, 'validation_nvdm_docs_non_replicated.csv')\n\t\t#test_url = os.path.join(topic_params.dataset, 'test_nvdm_docs_non_replicated.csv')\n\n\t\ttrain_url = os.path.join(nvdm_datadir, 'training_nvdm_docs_non_replicated.csv')\n\t\tdev_url = os.path.join(nvdm_datadir, 'validation_nvdm_docs_non_replicated.csv')\n\t\ttest_url = os.path.join(nvdm_datadir, 'test_nvdm_docs_non_replicated.csv')\n\n\t\ttrain_set, train_count, train_ids, train_doc_ids = utils.data_set(train_url, topic_params)\n\t\ttest_set, test_count, test_ids, test_doc_ids = utils.data_set(test_url, topic_params)\n\t\tdev_set, dev_count, dev_ids, dev_doc_ids = utils.data_set(dev_url, topic_params)\n\n\t\tdev_batches = utils.create_batches(len(dev_set), self.batch_size, shuffle=False)\n\t\t#dev_batches = utils.create_batches(len(dev_set), 512, shuffle=False)\n\t\ttest_batches = utils.create_batches(len(test_set), self.batch_size, shuffle=False)\n\t\t#test_batches = utils.create_batches(len(test_set), 512, shuffle=False)\n\t\t\n\t\t#training_labels = np.array(\n\t\t#\t[[y] for y, _ in dataset.rows('training_nvdm_docs_non_replicated', num_epochs=1)]\n\t\t#)\n\t\t#validation_labels = np.array(\n\t\t#\t[[y] for y, _ in dataset.rows('validation_nvdm_docs_non_replicated', num_epochs=1)]\n\t\t#)\n\t\t#test_labels = np.array(\n\t\t#\t[[y] for y, _ in dataset.rows('test_nvdm_docs_non_replicated', num_epochs=1)]\n\t\t#)\n\n\t\tpatience = topic_params.nvdm_patience\n\t\tpatience_count_ppl = 0\n\t\tpatience_count_f1 = 0\n\t\tbest_dev_ppl = np.inf\n\t\tbest_dev_f1 = -np.inf\n\t\tbest_val_nvdm_IR = -1.0\n\n\t\t\n\n\t\tppl_model = False\n\t\tir_model = False\n\t\tf1_model = False\n\t\t\n\t\tfor epoch in range(training_epochs):\n\t\t\tepoch_counter = epoch + 1\n\t\t\ttrain_batches = utils.create_batches(len(train_set), self.batch_size, shuffle=True)\n\t\t\t#train_batches = utils.create_batches(len(train_set), 512, shuffle=True)\n\t\t\t\n\t\t\t#-------------------------------\n\t\t\t# train\n\t\t\tfor switch in range(0, 2):\n\t\t\t\tif switch == 0:\n\t\t\t\t\toptim = self.optim_dec\n\t\t\t\t\tprint_mode = 'updating decoder'\n\t\t\t\telse:\n\t\t\t\t\toptim = self.optim_enc\n\t\t\t\t\tprint_mode = 'updating encoder'\n\t\t\t\tfor i in range(alternate_epochs):\n\t\t\t\t\tprint_ppx, print_ppx_perdoc, print_kld, print_sup_loss, print_macro_prec, print_macro_recall, print_macro_f1_score, print_acc = self.run_epoch(\n\t\t\t\t\t\ttrain_batches, \n\t\t\t\t\t\ttrain_set, \n\t\t\t\t\t\ttrain_count, \n\t\t\t\t\t\ttopic_params, \n\t\t\t\t\t\tsession,\n\t\t\t\t\t\tinput_labels = train_ids,\n\t\t\t\t\t\toptimizer=optim\n\t\t\t\t\t)\n\n\t\t\t\t\tprint('| Epoch train: {:d} |'.format(epoch_counter), \n\t\t\t\t\t\tprint_mode, '{:d}'.format(i),\n\t\t\t\t\t\t'| Corpus Perplexity: {:.5f}'.format(print_ppx), # perplexity for all docs\n\t\t\t\t\t\t'| Per doc Perplexity: {:.5f}'.format(print_ppx_perdoc), # perplexity for per doc\n\t\t\t\t\t\t'| KLD: {:.5}'.format(print_kld), \n\t\t\t\t\t\t'| Supervised loss: {:.5f}'.format(print_sup_loss))\n\t\t\t\n\t\t\tif epoch_counter >= 1 and epoch_counter % topic_params.nvdm_validation_ppl_freq == 0:\n\t\t\t\tppl_model = True\n\t\t\t\t\n\t\t\t\tprint_ppx, print_ppx_perdoc, print_kld, print_sup_loss, print_macro_prec, print_macro_recall, print_macro_f1_score, print_acc = self.run_epoch(\n\t\t\t\t\tdev_batches, \n\t\t\t\t\tdev_set, \n\t\t\t\t\tdev_count, \n\t\t\t\t\ttopic_params, \n\t\t\t\t\tsession,\n\t\t\t\t\tinput_labels = dev_ids\n\t\t\t\t)\n\n\t\t\t\tif print_ppx_perdoc < best_dev_ppl:\n\t\t\t\t#if print_ppx_perdoc <= best_dev_ppl:\n\t\t\t\t\tbest_dev_ppl = print_ppx_perdoc\n\t\t\t\t\tprint(\"Saving best model.\")\n\t\t\t\t\tself.pretrain_saver.save(session, model_dir_ppl_nvdm + '/model_ppl_nvdm_pretrain', global_step=1)\n\t\t\t\t\tself.save_to_s3_TM(topic_params)\n\n\t\t\t\t\tpatience_count_ppl = 0\n\t\t\t\telse:\n\t\t\t\t\tpatience_count_ppl += 1\n\n\t\t\t\tprint('| Epoch dev: {:d} |'.format(epoch_counter), \n\t\t\t\t\t'| Corpus Perplexity: {:.9f} |'.format(print_ppx),\n\t\t\t\t\t'| Per doc Perplexity: {:.5f} |'.format(print_ppx_perdoc),\n\t\t\t\t\t'| KLD: {:.5} |'.format(print_kld),\n\t\t\t\t\t'| Best dev PPL: {:.5} |'.format(best_dev_ppl))\n\t\t\t\t\n\t\t\t\twith open(log_dir + \"/logs_ppl_nvdm_pretrain.txt\", \"a\") as f:\n\t\t\t\t\tf.write('| Epoch Val: {:d} || Val Corpus PPL: {:.9f} || Val Per doc PPL: {:.5f} || Best Val PPL: {:.5} || KLD Val: {:.5} |\\n'.format(epoch+1, print_ppx, print_ppx_perdoc, best_dev_ppl, print_kld))\n\t\t\t\n\n\t\t\tif epoch_counter >= 1 and epoch_counter % topic_params.nvdm_validation_f1_freq == 0:\n\t\t\t\tf1_model = True\n\t\t\t\t\n\t\t\t\tprint_ppx, print_ppx_perdoc, print_kld, print_sup_loss, print_macro_prec, print_macro_recall, print_macro_f1_score, print_acc = self.run_epoch(\n\t\t\t\t\tdev_batches, \n\t\t\t\t\tdev_set, \n\t\t\t\t\tdev_count, \n\t\t\t\t\ttopic_params, \n\t\t\t\t\tsession,\n\t\t\t\t\tinput_labels = dev_ids\n\t\t\t\t)\n\t\t\t\tif print_macro_f1_score > best_dev_f1:\n\t\t\t\t\n\t\t\t\t\tbest_dev_f1 = print_macro_f1_score\n\t\t\t\t\tprint(\"Saving best model.\")\n\t\t\t\t\tself.pretrain_saver.save(session, model_dir_f1_nvdm + '/model_f1_nvdm_pretrain', global_step=1)\n\t\t\t\t\tself.save_to_s3_TM(topic_params)\n\t\t\t\t\tpatience_count_f1 = 0\n\t\t\t\telse:\n\t\t\t\t\tpatience_count_f1 += 1\n\n\t\t\t\tprint('| Epoch dev: {:d} |'.format(epoch_counter), \n\t\t\t\t\t'| Macro F1 : {:.9f} |'.format(print_macro_f1_score),\n\t\t\t\t\t'| Macro Prec: {:.5f} |'.format(print_macro_prec),\n\t\t\t\t\t'| Macro Recall: {:.5} |'.format(print_macro_recall),\n\t\t\t\t\t'| Best F1: {:.5} |'.format(best_dev_f1))\n\t\t\t\t\n\t\t\t\twith open(log_dir + \"/logs_f1_nvdm_pretrain.txt\", \"a\") as f:\n\t\t\t\t\tf.write('| Epoch Val: {:d} || Macro F1: {:.9f} || Macro Prec: {:.5f} || Macro Recall: {:.5} || Best Macro F1: {:.5} || Accuracy: {:.5} |\\n'.format(epoch+1, print_macro_f1_score, print_macro_prec, print_macro_recall, best_dev_f1 , print_acc))\n\n\n\t\t\tif epoch_counter >= 1 and epoch_counter % topic_params.nvdm_validation_ir_freq == 0:\n\t\t\t\tir_model = True\n\n\t\t\t\tvalidation_vectors_nvdm = self.hidden_vectors(\n\t\t\t\t\t#dataset.batches_nvdm_LM('validation_nvdm_docs_non_replicated', topic_params.nvdm_batch_size, topic_params.TM_vocab_length, num_epochs=1, multilabel=topic_params.multi_label),\n\t\t\t\t\tdataset.batches_nvdm_LM('validation_nvdm_docs_non_replicated', topic_params.nvdm_batch_size, self.vocab_size, num_epochs=1, multilabel=topic_params.multilabel),\n\t\t\t\t\ttopic_params,\n\t\t\t\t\tsession\n\t\t\t\t)\n\n\t\t\t\ttraining_vectors_nvdm = self.hidden_vectors(\n\t\t\t\t\t#dataset.batches_nvdm_LM('training_nvdm_docs_non_replicated', topic_params.nvdm_batch_size, topic_params.TM_vocab_length, num_epochs=1, multilabel=topic_params.multi_label),\n\t\t\t\t\tdataset.batches_nvdm_LM('training_nvdm_docs_non_replicated', topic_params.nvdm_batch_size, self.vocab_size, num_epochs=1, multilabel=topic_params.multilabel),\n\t\t\t\t\ttopic_params,\n\t\t\t\t\tsession\n\t\t\t\t)\n\n\t\t\t\tval_nvdm_ir, _ = eval.evaluate(\n\t\t\t\t\ttraining_vectors_nvdm,\n\t\t\t\t\tvalidation_vectors_nvdm,\n\t\t\t\t\ttraining_labels,\n\t\t\t\t\tvalidation_labels,\n\t\t\t\t\trecall=[0.02],\n\t\t\t\t\tnum_classes=topic_params.nvdm_num_classes,\n\t\t\t\t\tmulti_label=topic_params.multilabel\n\t\t\t\t)\n\t\t\t\tval_nvdm_ir = val_nvdm_ir[0]\n\t\t\t\t\n\t\t\t\t# Saving model and Early stopping on IR\n\t\t\t\tif val_nvdm_ir > best_val_nvdm_IR:\n\t\t\t\t\tbest_val_nvdm_IR = val_nvdm_ir\n\t\t\t\t\tprint('saving: {}'.format(model_dir_ir_nvdm))\n\t\t\t\t\tself.pretrain_saver.save(session, model_dir_ir_nvdm + '/model_ir_nvdm_pretrain', global_step=1)\n\t\t\t\t\tself.save_to_s3_TM(topic_params)\n\t\t\t\t#\tpatience_count = 0\n\t\t\t\t#else:\n\t\t\t\t#\tpatience_count += 1\n\n\t\t\t\tprint(\"Epoch: %i,\tVal NVDM IR: %s,\tbest val NVDM IR: %s\\n\" %\n\t\t\t\t\t\t(epoch_counter, val_nvdm_ir, best_val_nvdm_IR))\n\n\t\t\t\t# logging information\n\t\t\t\twith open(log_dir + \"/logs_ir_nvdm_pretrain.txt\", \"a\") as f:\n\t\t\t\t\tf.write(\"Epoch: %i,\tVal NVDM IR: %s,\tbest val NVDM IR: %s\\n\" %\n\t\t\t\t\t\t\t(epoch_counter, val_nvdm_ir, best_val_nvdm_IR))\n\n\t\t\tif topic_params.validate_supervised_TM == \"ppl\":\n\t\t\t\tif patience_count_ppl > patience:\n\t\t\t\t\tprint(\"Early stopping.\")\n\t\t\t\t\tbreak\n\n\t\t\telif topic_params.validate_supervised_TM == \"f1\":\n\t\t\t\tif patience_count_f1 > patience:\n\t\t\t\t\tprint(\"Early stopping.\")\n\t\t\t\t\tbreak\n\n\t\t\n\t\tif ppl_model:\n\t\t\tprint(\"Calculating Test PPL.\")\n\n\t\t\tself.pretrain_saver.restore(session, tf.train.latest_checkpoint(model_dir_ppl_nvdm))\n\n\t\t\tprint_ppx, print_ppx_perdoc, print_kld, print_sup_loss, print_macro_prec, print_macro_recall, print_macro_f1_score, print_acc= self.run_epoch(\n\t\t\t\ttest_batches, \n\t\t\t\ttest_set, \n\t\t\t\ttest_count, \n\t\t\t\ttopic_params, \n\t\t\t\tsession, \n\t\t\t\tinput_labels = test_ids\n\t\t\t)\n\n\t\t\tprint('| Corpus Perplexity: {:.9f}'.format(print_ppx),\n\t\t\t\t\t'| Per doc Perplexity: {:.5f}'.format(print_ppx_perdoc),\n\t\t\t\t\t'| KLD: {:.5}'.format(print_kld))\n\n\t\t\twith open(log_dir + \"/logs_ppl_nvdm_pretrain.txt\", \"a\") as f:\n\t\t\t\tf.write('\\n\\nTest Corpus PPL: {:.9f} || Test Per doc PPL: {:.5f} || KLD Test: {:.5} |\\n'.format(print_ppx, print_ppx_perdoc, print_kld))\n\n\n\t\tif f1_model:\n\t\t\tprint(\"Calculating Test F1.\")\n\n\t\t\tself.pretrain_saver.restore(session, tf.train.latest_checkpoint(model_dir_f1_nvdm))\n\n\t\t\tprint_ppx, print_ppx_perdoc, print_kld, print_sup_loss, print_macro_prec, print_macro_recall, print_macro_f1_score, print_acc = self.run_epoch(\n\t\t\t\ttest_batches, \n\t\t\t\ttest_set, \n\t\t\t\ttest_count, \n\t\t\t\ttopic_params, \n\t\t\t\tsession, \n\t\t\t\tinput_labels = test_ids\n\t\t\t)\n\n\t\t\tprint('| Macro F1: {:.9f}'.format(print_macro_f1_score),\n\t\t\t\t\t'| Macro prec: {:.5f}'.format(print_macro_prec),\n\t\t\t\t\t'| Macro recall : {:.5}'.format(print_macro_recall),\n\t\t\t\t\t'| Acc : {:.5}'.format(print_acc)\n\t\t\t\t\t)\n\n\t\t\twith open(log_dir + \"/logs_f1_nvdm_pretrain.txt\", \"a\") as f:\n\t\t\t\tf.write('\\n\\nTest Macro F1: {:.9f} || Test Macro prec : {:.5f} || Test Macro recall : {:.5} || Test Acc : {:.5} |\\n'.format(print_macro_f1_score, print_macro_prec, print_macro_recall, print_acc ))\n\n\n\t\tif ir_model:\n\t\t\tprint(\"Calculating Test IR.\")\n\n\t\t\tself.pretrain_saver.restore(session, tf.train.latest_checkpoint(model_dir_ir_nvdm))\n\n\t\t\ttest_vectors_nvdm = self.hidden_vectors(\n\t\t\t\t#dataset.batches_nvdm_LM('test_nvdm_docs_non_replicated', topic_params.nvdm_batch_size, topic_params.TM_vocab_length, num_epochs=1, multilabel=topic_params.multi_label),\n\t\t\t\tdataset.batches_nvdm_LM('test_nvdm_docs_non_replicated', topic_params.nvdm_batch_size, self.vocab_size, num_epochs=1, multilabel=topic_params.multilabel),\n\t\t\t\ttopic_params,\n\t\t\t\tsession\n\t\t\t)\n\n\t\t\ttest_nvdm_ir, _ = eval.evaluate(\n\t\t\t\ttraining_vectors_nvdm,\n\t\t\t\ttest_vectors_nvdm,\n\t\t\t\ttraining_labels,\n\t\t\t\ttest_labels,\n\t\t\t\trecall=[0.02],\n\t\t\t\tnum_classes=topic_params.nvdm_num_classes,\n\t\t\t\tmulti_label=topic_params.multilabel\n\t\t\t)\n\t\t\ttest_nvdm_ir = test_nvdm_ir[0]\n\n\t\t\tprint(\"Epoch: %i,\tTest NVDM IR: %s\\n\" %\n\t\t\t\t\t(epoch_counter, test_nvdm_ir))\n\n\t\t\t# logging information\n\t\t\twith open(log_dir + \"/logs_ir_nvdm_pretrain.txt\", \"a\") as f:\n\t\t\t\tf.write(\"Epoch: %i,\tTest NVDM IR: %s\\n\" %\n\t\t\t\t\t\t(epoch_counter, test_nvdm_ir))\n\n\n\tdef hidden_vectors(self, data, topic_params, session):\n\t\tvecs = []\n\t\tfor y, x, count, mask in data:\n\n\t\t\tfeed_dict = {\n\t\t\t\tself.x.name: x,\n\t\t\t\tself.mask.name: mask\n\t\t\t\t#self.input_batch_size: x.shape[0]\n\t\t\t}\n\t\t\t\n\t\t\tvecs.extend(\n\t\t\t\tsession.run([self.last_h], feed_dict=feed_dict)[0]\n\t\t\t)\n\t\t\n\t\treturn np.array(vecs)\n\n\tdef run_epoch(self, input_batches, input_set, input_count, topic_params, session, input_labels = None, optimizer=None):\n\t\tloss_sum = 0.0\n\t\tppx_sum = 0.0\n\t\tkld_sum = 0.0\n\t\tsupervised_loss_sum = 0.0\n\t\tword_count = 0\n\t\tdoc_count = 0\n\t\tdoc_pred = []\n\t\tdoc_labels = []\n\n\t\tfor idx_batch in input_batches:\n\t\t\tdata_batch, count_batch, mask, label_batch = utils.fetch_data(\n\t\t\tinput_set, input_count, idx_batch, self.vocab_size, topic_params, labels = input_labels)\n\t\t\t#import pdb; pdb.set_trace()\n\t\t\tinput_feed = {self.x.name: data_batch,\n\t\t\t\t\t\tself.mask.name: mask, \n\t\t\t\t\t\tself.label_ids.name: label_batch}\n\t\t\tif not optimizer is None:\n\t\t\t\t_, (loss, kld, supervised_loss, prob) = session.run((optimizer, \n\t\t\t\t\t\t\t\t\t\t\t[self.unsupervised_loss, self.kld, self.supervised_loss, self.sup_prob]),\n\t\t\t\t\t\t\t\t\t\t\tinput_feed)\n\t\t\telse:\n\t\t\t\tloss, kld, supervised_loss, prob = session.run([self.unsupervised_loss, self.kld, self.supervised_loss, self.sup_prob],\n\t\t\t\t\t\t\t\t\t\t\tinput_feed)\n\t\t\t\t\n\t\t\tif topic_params.multilabel:\n\t\t\t\tprob_arr = np.asarray(prob)\n\t\t\t\tmultilabel_pred = np.where(prob_arr >= 0.5, 1, 0)\n\t\t\t\tpred = np.ndarray.tolist(multilabel_pred)\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tpred = np.argmax(prob, axis = 1)\n\t\t\tassert len(pred) == len(label_batch) == len(mask)\n\n\t\t\tfor i in range(len(mask)):\n\t\t\t\tif mask[i] != 0.0:\n\t\t\t\t\tdoc_pred.append(pred[i])\n\t\t\t\t\tdoc_labels.append(label_batch[i])\n\n\t\t\tloss_sum += np.sum(loss)\n\t\t\tkld_sum += np.sum(kld) / np.sum(mask) \n\t\t\tsupervised_loss_sum += np.sum(supervised_loss) / np.sum(mask) \n\t\t\tword_count += np.sum(count_batch)\n\t\t\t# to avoid nan error\n\t\t\tcount_batch = np.add(count_batch, 1e-12)\n\t\t\t# per document loss\n\t\t\tppx_sum += np.sum(np.divide(loss, count_batch)) \n\t\t\tdoc_count += np.sum(mask)\n\n\t\tassert -1 not in doc_labels\n\n\t\tif topic_params.multilabel:\n\t\t\tdoc_labels = np.asarray(doc_labels)\n\t\t\tdoc_pred = np.asarray(doc_pred)\n\n\t\tprint_macro_prec, print_macro_recall, print_macro_f1_score, _ = precision_recall_fscore_support(doc_labels, doc_pred, average = \"macro\")\n\t\t#print_micro_prec, print_micro_recall, print_micro_f1_score, _ = precision_recall_fscore_support(doc_labels, doc_pred, average = \"micro\")\n\t\tprint_acc = accuracy_score(doc_labels, doc_pred)\n\t\tprint_sup_loss = supervised_loss_sum/len(input_batches)\n\n\t\tprint_ppx = np.exp(loss_sum / word_count)\n\t\tprint_ppx_perdoc = np.exp(ppx_sum / doc_count)\n\t\tprint_kld = kld_sum/len(input_batches)\n\n\t\treturn print_ppx, print_ppx_perdoc, print_kld, print_sup_loss, print_macro_prec, print_macro_recall, print_macro_f1_score, print_acc\n\n\t\"\"\"\n\tdef topic_dist(self, input_batches, input_set, input_count, topic_params, session):\n\t\ttopic_dist = []\n\t\tmask_list = []\n\t\tfor idx_batch in input_batches:\n\t\t\tdata_batch, count_batch, mask = utils.fetch_data(\n\t\t\tinput_set, input_count, idx_batch, self.vocab_size)\n\t\t\tinput_feed = {self.x.name: data_batch,\n\t\t\t\t\t\t\tself.mask.name: mask}\n\t\t\t\t\t\t\t\n\t\t\tdoc_vec = session.run([self.doc_vec], input_feed)\n\t\t\ttopic_dist.extend(list(doc_vec[0]))\n\t\t\tmask_list.extend(list(mask))\n\t\t\n\n\t\ttopic_dist_unique = []\n\t\tfor num, m in enumerate(mask_list):\n\t\t\tif m!= 0.0:\n\t\t\t\ttopic_dist_unique.append(topic_dist[num])\n\n\t\ttopic_dist_unique = np.asarray(topic_dist_unique)\n\t\treturn topic_dist_unique, mask_list\n\t\"\"\"\n\tdef topic_dist(self, input_batches, input_set, input_doc_ids , input_count, topic_params, session):\n\t\ttopic_dist = []\n\t\tmask_list = []\n\t\tdoc_id_list = []\n\t\tfor idx_batch in input_batches:\n\t\t\tdata_batch, count_batch, mask = utils.fetch_data(\n\t\t\tinput_set, input_count, idx_batch, self.vocab_size, topic_params)\n\t\t\tinput_feed = {self.x.name: data_batch,\n\t\t\t\t\t\t\tself.mask.name: mask}\n\t\t\t\t\t\t\t\n\t\t\tdoc_vec = session.run([self.doc_vec], input_feed)\n\t\t\ttopic_dist.extend(list(doc_vec[0]))\n\t\t\tmask_list.extend(list(mask))\n\n\t\t\tfor idx in idx_batch:\n\t\t\t\tif idx != -1: \n\t\t\t\t\tdoc_id_list.append(input_doc_ids[idx])\n\t\t\t\telse:\n\t\t\t\t\tdoc_id_list.append(-1)\n\n\n\t\tassert len(topic_dist) == len(doc_id_list)\n\t\ttopic_dist_unique = {}\n\n\t\tfor id, dist in zip(doc_id_list, topic_dist):\n\t\t\tif id != -1:\n\t\t\t\ttopic_dist_unique[str(id)] = dist\n\t\t\n\n\t\treturn topic_dist_unique, mask_list\n\n\tdef save_to_s3_TM(self, topic_params):\n\t\tpass\n\n\n\tdef run_epoch_v2(self, data, topic_params, session):\n\t\t# train_y, train_x, train_count, train_mask = dataset.batches_nvdm_LM(training_data_filename_TM, topic_params.batch_size, topic_params.TM_vocab_length, num_epochs=1, multilabel=topic_params.multi_label)\n\t\t# val_y, val_x, val_count, val_mask = dataset.batches_nvdm_LM(validation_data_filename_TM, topic_params.batch_size, topic_params.TM_vocab_length, num_epochs=1, multilabel=topic_params.multi_label)\n\t\t# test_y, test_x, test_count, test_mask = dataset.batches_nvdm_LM(test_data_filename_TM, topic_params.batch_size, topic_params.TM_vocab_length, num_epochs=1, multilabel=topic_params.multi_label)\n\t\t\n\t\tkld_sum = []\n\t\tthis_nvdm_loss_normed = []\n\t\tthis_nvdm_loss_unnormed = []\n\t\tthis_nvdm_words = []\n\t\tfor nvdm_y, nvdm_x, nvdm_count, nvdm_mask in data:\n\t\t\tnvdm_feed_dict = {\n\t\t\t\tmodel.topic_model.x.name: nvdm_x,\n\t\t\t\tmodel.topic_model.mask.name: nvdm_mask#,\n\t\t\t\t#model.topic_model.input_batch_size: nvdm_x.shape[0]\n\t\t\t}\n\t\t\n\t\t\tif topic_params.supervised:\n\t\t\t\tsys.exit()\n\t\t\telse:\n\t\t\t\tloss, kld = session.run([model.topic_model.final_loss, \n\t\t\t\t\t\t\t\t\t\tmodel.topic_model.kld], \n\t\t\t\t\t\t\t\t\t\tfeed_dict=nvdm_feed_dict)\n\t\t\t\tnvdm_count = np.add(nvdm_count, 1e-12)\n\t\t\t\tthis_nvdm_loss_normed.extend(np.divide(loss, nvdm_count))\n\t\t\t\tthis_nvdm_loss_unnormed.extend(loss)\n\t\t\t\tthis_nvdm_words.append(np.sum(nvdm_count))\n\t\t\t\tkld_sum.append(np.sum(kld) / np.sum(nvdm_mask))\n\n\t\ttotal_nvdm_nll = np.mean(this_nvdm_loss_unnormed)\n\t\t#total_nvdm_ppl = np.exp(np.sum(this_nvdm_loss_unnormed) / np.sum(this_val_nvdm_words))\n\t\ttotal_nvdm_ppl = np.exp(np.mean(this_nvdm_loss_normed))\n\t\tprint_kld = np.mean(kld_sum)\n\n\t\treturn total_nvdm_nll, total_nvdm_ppl, print_kld\n\n\t","sub_path":"TopicBERT/topic_bert/nvdm/model_GSM_supervised.py","file_name":"model_GSM_supervised.py","file_ext":"py","file_size_in_byte":33215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"398276382","text":"'''\nCreated on Oct 30, 2018\n\n@author: David Ariando\n'''\n\nimport os\nimport time\n\nfrom nmr_std_function.nmr_functions import compute_iterate\nfrom nmr_std_function.nmr_functions import compute_wobble\nfrom nmr_std_function.data_parser import parse_simple_info\nfrom nmr_std_function.nmr_class import tunable_nmr_system_2018\n\n# variables\ndata_parent_folder = \"/root/NMR_DATA\"\nen_remote_dbg = 0\nfig_num = 1\nen_fig = 1\n\n# instantiate nmr object\nnmrObj = tunable_nmr_system_2018(data_parent_folder)\n\n# remote debug setup\nif en_remote_dbg:\n from pydevd_file_utils import setup_client_server_paths\n PATH_TRANSLATION = [(nmrObj.client_path, nmrObj.server_path)]\n setup_client_server_paths(PATH_TRANSLATION)\n print(\"---server:%s---client:%s---\" % (nmrObj.server_ip, nmrObj.client_ip))\n pydevd.settrace(nmrObj.client_ip)\n\nwork_dir = os.getcwd()\nos.chdir(data_parent_folder)\n\n\n\n# system setup\nnmrObj.initNmrSystem() # necessary to set the GPIO initial setting\n# nmrObj.turnOnPower()\nnmrObj.assertControlSignal(nmrObj.PSU_5V_TX_N_EN_msk |\n nmrObj.PSU_5V_ADC_EN_msk | nmrObj.PSU_5V_ANA_P_EN_msk |\n nmrObj.PSU_5V_ANA_N_EN_msk)\n\nnmrObj.setMatchingNetwork(0,0)\n\nwhile True:\n nmrObj.assertControlSignal( nmrObj.RX_IN_SEL_1_msk | nmrObj.PAMP_IN_SEL_TEST_msk) \n nmrObj.assertControlSignal(nmrObj.AMP_HP_LT1210_EN_msk | nmrObj.PSU_15V_TX_P_EN_msk | nmrObj.PSU_15V_TX_N_EN_msk)\n time.sleep(0.1)\n \n sta_freq = 1\n sto_freq = 4\n spac_freq = 0.01\n samp_freq = 25\n nmrObj.wobble(sta_freq, sto_freq, spac_freq, samp_freq)\n\n nmrObj.deassertControlSignal(nmrObj.AMP_HP_LT1210_EN_msk | nmrObj.PSU_15V_TX_P_EN_msk | nmrObj.PSU_15V_TX_N_EN_msk)\n nmrObj.deassertControlSignal( nmrObj.RX_IN_SEL_1_msk | nmrObj.PAMP_IN_SEL_TEST_msk)\n \n S11_min = -10\n meas_folder = parse_simple_info(data_parent_folder, 'current_folder.txt')\n # meas_folder[0] = \"nmr_wobb_2018_06_25_12_44_48\"\n\n S11_fmin, S11_fmax, S11_bw, minS11, minS11_freq = compute_wobble(\n data_parent_folder, meas_folder[0], S11_min, en_fig, fig_num)\n print('fmin={0:0.3f} fmax={1:0.3f} bw={2:0.3f} minS11={3:0.2f} minS11_freq={4:0.2f}'.format(\n S11_fmin, S11_fmax, S11_bw, minS11, minS11_freq))\n\n \n","sub_path":"MAIN_nmr_code/obsolete/Z_OBSOLETE_nmr_pamp_gain.py","file_name":"Z_OBSOLETE_nmr_pamp_gain.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"505642893","text":"# https://adventofcode.com/2019/day/17\n\n\nimport re\nimport os\nimport sys\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..'))\nfrom lib.intcode import IntCodeComputer\n\n\ndef calibrate_cam(map_):\n ap_sum = 0\n for x, row in enumerate(map_[1:-1]):\n for y, tile in enumerate(row[1:-1]):\n if (\n tile == '#'\n and map_[x][y + 1] == '#'\n and map_[x + 1][y] == '#'\n and map_[x + 1][y + 2] == '#'\n and map_[x + 2][y + 1] == '#'\n ):\n ap_sum += (x + 1) * (y + 1)\n return ap_sum\n\n\ndef render_grid(grid, show=False):\n tiles = []\n for tile in grid:\n tiles.append(str(chr(tile)))\n output = \"\".join(tiles)\n if show:\n print(output)\n return [[c for c in line] for line in output.splitlines()]\n\n\ndef find_path(map_):\n x, y = 0, 0\n grid = [\"\".join(line) for line in map_]\n turn_r = {\n (0, 1): (1, 0),\n (1, 0): (0, -1),\n (0, -1): (-1, 0),\n (-1, 0): (0, 1),\n }\n turn_l = {\n (0, 1): (-1, 0),\n (-1, 0): (0, -1),\n (0, -1): (1, 0),\n (1, 0): (0, 1),\n }\n direction = 0, +1\n path = ['R', 0]\n while True:\n nx, ny = x + direction[0], y + direction[1]\n if 0 <= nx <= len(grid) - 1 and 0 <= ny <= len(grid[0]) - 1 and grid[nx][ny] == '#':\n x, y = nx, ny\n path[-1] += 1\n else:\n r = turn_r[direction]\n nx, ny = x + r[0], y + r[1]\n if 0 <= nx <= len(grid) - 1 and 0 <= ny <= len(grid[0]) - 1 and grid[nx][ny] == '#':\n x, y = nx, ny\n direction = r\n path.append('R')\n path.append(1)\n else:\n l = turn_l[direction]\n nx, ny = x + l[0], y + l[1]\n if 0 <= nx <= len(grid) - 1 and 0 <= ny <= len(grid[0]) - 1 and grid[nx][ny] == '#':\n x, y = nx, ny\n direction = l\n path.append('L')\n path.append(1)\n else:\n break\n return ','.join(str(s) for s in path)\n\n\ndef main():\n program = IntCodeComputer.load_intcode('input.txt')\n computer = IntCodeComputer(program)\n out = computer.start_program()\n map_ = render_grid(out)\n output_p1 = calibrate_cam(map_)\n path = find_path(map_)\n\n # manual path mapping + zipping\n # L,12,L,8,R,10,R,10,L,6,L,4,L,12,L,12,L,8,R,10,R,10,L,6,L,4,L,12,R,10,L,8,L,4,R,10,L,6,L,4,L,12,L,12,L,8,R,10,R,10,R,10,L,8,L,4,R,10,L,6,L,4,L,12,R,10,L,8,L,4,R,10\n\n # L, 12, L, 8, R, 10, R, 10, A\n # L, 6, L, 4, L, 12, B\n # L, 12, L, 8, R, 10, R, 10, A\n # L, 6, L, 4, L, 12, B\n # R, 10, L, 8, L, 4, R, 10, C\n # L, 6, L, 4, L, 12, B\n # L, 12, L, 8, R, 10, R, 10, A\n # R, 10, L, 8, L, 4, R, 10, C\n # L, 6, L, 4, L, 12, B\n # R, 10, L, 8, L, 4, R, 10, C\n\n a = \"L,12,L,8,R,10,R,10\"\n b = \"L,6,L,4,L,12\"\n c = \"R,10,L,8,L,4,R,10\"\n zipped = \"A,B,A,B,C,B,A,C,B,C\"\n routine = zipped + \"\\n\" + a + \"\\n\" + b + \"\\n\" + c + \"\\n\" + \"n\\n\"\n input_ = [ord(x) for x in routine]\n\n program[0] = 2\n computer = IntCodeComputer(program, input_)\n out = computer.start_program()\n map_ = render_grid(out, True)\n\n print(\"output: %d\" % output_p1)\n print(\"output p2: %d\" % out.pop())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"17_set-and-forget/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"109464635","text":"# encoding: utf-8\nfrom django.conf.urls import url\nfrom apps.core.views import base_page, index, menu, instrument, instrument_model, parsing, capture\n\nurlpatterns = [\n url(r'^base/$', base_page),\n url(r'^index/$', index),\n url(r'^system/menu/$', menu),\n url(r'^instrument/$', instrument),\n url(r'^instrument_model/$', instrument_model),\n url(r'^parsing/$', parsing),\n url(r'^data/capture/$', capture),\n]\n","sub_path":"apps/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"418369033","text":"class Lengths:\n m = 1\n dm = m/10\n cm = dm/10\n mm = cm/10\n\nclass Volume:\n m3 = 1\n dm3 = m3/(10**3)\n cm3 = dm3/(10**3)\n liter = dm3\n\nclass Pressure:\n kPa = 1e3\n MPa = 1e6\n bar = 100 * kPa\n\nclass Area:\n cm2 = Lengths.cm * Lengths.cm","sub_path":"src/tests/tankFill/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"584299875","text":"\"\"\"\nimport sqlite3\nconn = sqlite3.connect('test.db')\nprint(\"Opened database successfully\")\ncursor = conn.execute(\"SELECT id, name,age, address, salary from COMPANY\")\nprint(type(cursor))\nfor row in cursor:\n print(\"ID = \", row[0])\n print(\"NAME = \", row[1])\n print(\"AGE = \",row[2])\n print(\"ADDRESS = \", row[3])\n print(\"SALARY = \", row[4], \"\\n\")\nprint(\"Operation done successfully\")\nconn.close()\n\nFollowing Python program shows how to fetch and display records from the COMPANY table created in the above example.\n\"\"\"\nimport sqlite3\nconn=sqlite3.connect(\"test.db\")\nprint(\"Opened Database successfully\")\nage=32\ncursor=conn.execute(\"SELECT AGE FROM COMPANY WHERE ID=(?)\",(age,))\nfor row in cursor:\n print(row[0])\nconn.commit()\nprint(\"Operation perform Successfully\")\nconn.close()\n","sub_path":"Python/Python Database/selectoperation.py","file_name":"selectoperation.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"51419968","text":"import numpy as np\nimport math as m\nimport matplotlib.pyplot as plt\n#from scipy.ndimage.filters import convolve\n\n\nmatrix = np.zeros((1000, 1000))\n\n\n\n################################################\n\n# add draw function here\n\n\n\n# example drawing a square in the middle (from row 33 to row 67, column 33 to column 67)\n\n#matrix[33:67, 33:67] = 1\n\n#circle attempt 1\n\ndef make_crystal():\n arraysize =1000\n radius = 20\n dist = radius*4\n xpos = 200 - dist\n ypos = 200 - radius\n xpos1 = xpos\n ypos1 = ypos\n n1 = 8\n n2 = 8\n \n for i in range(n1):\n \n ypos1 = ypos\n\n xpos1 += dist\n \n if i % 2 == 0:\n ypos1 = ypos - dist/2\n n1 = n1+1\n \n else:\n ypos1 = ypos\n \n for j in range(n2):\n \n ypos1 +=dist\n \n x, y = np.mgrid[-xpos1:arraysize-xpos1, -ypos1:arraysize-ypos1]\n \n cir = x**2 + y**2 <= radius**2\n\n matrix[int(xpos):int(xpos1)+int(2*radius), int(ypos):int(ypos1)+int(2*radius)] = 1 \n matrix[cir] = 0 \n\n \n\n \n \n #xpos1 = xpos\n #ypos1 = ypos\n \n #for i in range(10):\n # ypos1 += 50\n # x, y = np.mgrid[-xpos1:arraysize-xpos1, -ypos1:arraysize-ypos1]\n # cir = x**2 + y**2 <= radius**2\n # matrix[cir] = 1\n #xpos2 = xpos+50\n #ypos2 = ypos+20\n #for i in range(10):\n # ypos2 += 50\n # x, y = np.mgrid[-xpos2:arraysize-xpos2, -ypos2:arraysize-ypos2]\n # cir = x**2 + y**2 <= radius**2\n # matrix[cir] = 1\n\n #xpos3 = xpos +100\n #ypos3 = ypos\n #for i in range(10):\n # ypos3 += 50\n # x, y = np.mgrid[-xpos3:arraysize-xpos3, -ypos3:arraysize-ypos3]\n # cir = x**2 + y**2 <= radius**2\n # matrix[cir] = 1\n \n \n \nmake_crystal()\n\n################################################\n\n\n\ndef main():\n\n fig, ax = plt.subplots()\n\n image = ax.imshow(matrix, vmax=1, vmin=0, aspect='auto')\n\n ax.set_aspect('equal', 'box')\n\n ax.set_title('Drawing')\n\n\n\n plt.show()\n\nmain()\n","sub_path":"draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"114847342","text":"#!/usr/bin/env\n# -*- coding: utf-8 -*-\n# filename = guess_regex\n# author=SluttyScience\n# date = 7/31/17\n\"\"\" filename = guess_regex\"\"\"\nfrom __future__ import absolute_import, unicode_literals\nfrom startups import *\nimport sys, os\nimport regex\nimport string\nimport re\nfrom startups.regular.util import get_has\nfrom startups.regular.const import get_attr\n\n\ncategory_letters = 'CLMNPSZcdefiklmnopstu'\nre_repetition = regex.compile('\\{\\[\\^\\{\\}\\]\\*\\}')\nre_Q = regex.compile(r'((?:[*+?])\\?|[*+?])')\nre_comment = regex.compile(r'\\(\\?#[^)]*\\)')\nre_define =regex.compile(r'\\(\\?\\(DEFINE\\)(.+)\\)\\)')\nre_short_property = regex.compile(r'\\\\p\\{([CLMNPSZ][cdefiklmnopstu]?)\\}')\nre_property = regex.compile(r'\\\\p\\{([A-za-z]+)\\}')\nre_meta = regex.compile(r'(\\\\)(\\^|\\*|\\]|\\[|\\#|\\}|\\?|\\(|\\||\\{|\\+|\\.|\\&|\\-|\\)|\\~|\\$|\\\\)')\nre_double_slash = regex.compile(r'(\\\\)(1|[^\\\\]+?)')\n\n#cat:regex #cat:pattern\ndef unescape(pattern, special_only = False):\n\t\"\"\"\n\t:param pattern: The regular expression pattern to unescape\n\t:param special_only: True if just to unescape special-characters\n\t:return: An unescaped pattern as string\n\t\"\"\"\n\t\n\t_METACHARS = get_attr('_METACHARS')\n\tMETA = regex.compile('(\\\\\\\\)(\\\\^|\\\\*|\\\\]|\\\\[|\\\\#|\\\\}|\\\\?|\\\\(|\\\\||\\\\{|\\\\+|\\\\.|\\\\&|\\\\-|\\\\)|\\\\~|\\\\$|\\\\\\\\)')\n\tif special_only:\n\t\treturn META.sub(r'\\2', pattern)\n\treturn regex.sub(r\"\\\\\", '', pattern)\n\ndef __get_quantifier(self, as_character=True): # TODO LazyRepeat, GreedyRepeat\n\tmin_count = get_has('min_count')\n\tmax_count = get_has('max_count')\n\tbottom = min_count(self)\n\ttop = max_count(self)\n\tif not as_character:\n\t\treturn (bottom, top)\n\t\n\tif as_character:\n\t\tif bottom == 0 and top is None:\n\t\t\treturn '*'\n\t\telif bottom == 0 and top == 1:\n\t\t\treturn '?'\n\t\telif bottom == 1 and top is None:\n\t\t\treturn '+'\n\t\telse:\n\t\t\treturn (bottom, top)\n\treturn (bottom, top)\n\n\n\nFL = '(V0|V1|a|b|e|f|i|L|m|p|r|s|u|w|x)*'\nFLAG = regex.compile(r'(?<=\\?)(?PV(?:[01])|[Labefimprsuwx]+)', regex.VERBOSE)\n #r'((?<=\\-)(?&flags))',\n #regex.VERBOSE)\n\n\n#class Strings(object):\n#\tdef __init__(self, limit=10):\n#\t\tself._limit = limit\n#\t\tself._cache = dict()\n#\n#\t\tself._alphabets = {\n#\t\t\t'printable': string.printable,\n#\t\t\t'letters': string.ascii_letters,\n#\t\t\t'uppercase': string.ascii_uppercase,\n#\t\t\t'lowercase': string.ascii_lowercase,\n#\t\t\t'digits': string.digits,\n#\t\t\t'punctuation': string.punctuation,\n#\t\t\t'nondigits': string.ascii_letters + string.punctuation,\n#\t\t\t'nonletters': string.digits + string.punctuation,\n#\t\t\t'whitespace': string.whitespace,\n#\t\t\t'nonwhitespace': string.printable.strip(),\n#\t\t\t'normal': string.ascii_letters + string.digits + ' ',\n#\t\t\t'word': string.ascii_letters + string.digits + '_',\n#\t\t\t'nonword': ''.join(set(string.printable)\n#\t\t\t .difference(string.ascii_letters +\n#\t\t\t string.digits + '_')),\n#\t\t\t'postalsafe': string.ascii_letters + string.digits + ' .-#/',\n#\t\t\t'urlsafe': string.ascii_letters + string.digits + '-._~',\n#\t\t\t'domainsafe': string.ascii_letters + string.digits + '-'\n#\t\t}\n#\n#\t\tself._categories = {\n#\t\t\t\"category_digit\": lambda: self._alphabets['digits'],\n#\t\t\t\"category_not_digit\": lambda: self._alphabets['nondigits'],\n#\t\t\t'CATEGORY_SPACE': lambda: self._alphabets['whitespace'],\n#\t\t\t\"category_not_space\": lambda: self._alphabets['nonwhitespace'],\n#\t\t\t\"category_word\": lambda: self._alphabets['word'],\n#\t\t\t\"category_not_word\": lambda: self._alphabets['nonword'],\n#\t\t}\n#\n#\t\tself._cases = {\n#\t\t\t\"literal\": lambda x: chr(x),\n#\t\t}\n#\n\n#NEXT = 36\n#BRANCH = 10\n#END = 20\n#GROUP_EXISTS = 32\n#GROUP = 30\n#STRING = 74 #pos/neg, number, chars\n#CONDITIONAL = 16 #LookAroundConditional #[(OP.CONDITIONAL, int(self.positive), int(not self.behind))]\n#OR = \"branch\"\n\n#tab = regex.Regex(r'\\s{4}', flags=regex.F | regex.V1)\n\n#_INDENT = regex.compile(r'\\A(\\s{4})*', regex.M) #\\W, \\S\n\n#s = regex.compile(r'\\A((?\\s{4})+)')\n#len(m.captures('indent'))]\n#hexcode = '\\xXX'\n#hexcode = '\\uXXXX'\n\ncn = lambda x: x.__class__.__name__\n\nfrom treelib import Tree, Node\n\ndef make_node(parsed):\n\tCN = cn(parsed)\n\tID = str(id(parsed))\n\tdata = parsed.__dict__\n\treturn Node(identifier = CN+ID, data = data)\n\n\ndef show_tree(tree, nid=None, line_type='ascii-ex', data_property=None, idhidden=False, func='write', filter=None,\n key=None, reverse=False\n ):\n\t\n\treader = \"\"\n\t\n\tdef write(line): reader += line.decode('utf-8') + \"\\n\"\n\t\n\tif data_property:\n\t\tif idhidden:\n\t\t\tdef get_label(node):\n\t\t\t\treturn getattr(node.data, data_property)\n\t\telse:\n\t\t\tdef get_label(node):\n\t\t\t\treturn \"%s[%s]\" % (getattr(node.data, data_property), node.identifier)\n\t\t\t\n\telse:\n\t\tif idhidden:\n\t\t\tdef get_label(node):\n\t\t\t\treturn node.tag\n\t\telse:\n\t\t\tdef get_label(node):\n\t\t\t\treturn \"%s[%s]\" % (node.tag, node.identifier)\n\t\t\t\n\tif key is None:\n\t\tdef key(node):\n\t\t\treturn node\n\t\t\n\t\tfor pre, node in self.__get(nid, level, filter, key, reverse, line_type):\n\t\t\tlabel = get_label(node)\n\t\t\tfunc('{0}{1}'.format(pre, label).encode('utf-8'))\n\t\t\t\n\t\t\t\n####\n\t\"\"\"LITERAL MATCH 'word' FULL_IGNORE_CASE\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tSTART_OF_WORD MATCH == `m`\n\t\t\t\t\t\t\t\t\t\"\"\"\nlogging_template = '[%(asctime)s] %(name)-10s %(levelname)-5s %(message)-5s %(funcName)-5s (%(lineno)d)'\n\n\n\n\nif __name__ == '__main__': print(__file__)","sub_path":"startups/regular/guess_regex.py","file_name":"guess_regex.py","file_ext":"py","file_size_in_byte":5217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"378261001","text":"import d6tflow\nimport sklearn, sklearn.datasets, sklearn.svm, sklearn.linear_model\nimport pandas as pd\n\n# define workflow\nclass TaskGetData(d6tflow.tasks.TaskPqPandas): # save dataframe as parquet\n\n def run(self):\n ds = sklearn.datasets.load_breast_cancer()\n df_train = pd.DataFrame(ds.data, columns=ds.feature_names)\n df_train['y'] = ds.target\n self.save(df_train) # quickly save dataframe\n\n\n@d6tflow.requires(TaskGetData) # define dependency\nclass TaskPreprocess(d6tflow.tasks.TaskPqPandas):\n do_preprocess = d6tflow.BoolParameter(default=True) # parameter for preprocessing yes/no\n\n def run(self):\n df_train = self.input().load() # quickly load required data\n if self.do_preprocess:\n df_train.iloc[:,:-1] = sklearn.preprocessing.scale(df_train.iloc[:,:-1])\n self.save(df_train)\n\n@d6tflow.requires(TaskPreprocess) # automatically pass parameters upstream\nclass TaskTrain(d6tflow.tasks.TaskPickle): # save output as pickle\n model = d6tflow.Parameter(default='ols') # parameter for model selection\n\n def run(self):\n df_train = self.input().load()\n if self.model=='ols':\n model = sklearn.linear_model.LogisticRegression()\n elif self.model=='svm':\n model = sklearn.svm.SVC()\n else:\n raise ValueError('invalid model selection')\n model.fit(df_train.drop('y',1), df_train['y'])\n self.save(model)\n\n# goal: compare performance of two models\nparams_model1 = {'do_preprocess':True, 'model':'ols'}\nparams_model2 = {'do_preprocess':False, 'model':'svm'}\n\n# run workflow for model 1\nd6tflow.run(TaskTrain(**params_model1))\n\n'''\n===== Luigi Execution Summary =====\n\nScheduled 3 tasks of which:\n* 3 ran successfully:\n - 1 TaskGetData()\n - 1 TaskPreprocess(do_preprocess=False)\n - 1 TaskTrain(do_preprocess=False, model=ols)\n'''\n\n# Intelligently rerun workflow after changing parameters\nd6tflow.preview(TaskTrain(**params_model2))\n\n'''\n└─--[TaskTrain-{'do_preprocess': 'False'} (PENDING)]\n └─--[TaskPreprocess-{'do_preprocess': 'False'} (PENDING)]\n └─--[TaskGetData-{} (COMPLETE)] => this doesn't change and doesn't need to rerun\n'''\n\n# run workflow for model 2\nd6tflow.run(TaskTrain(**params_model2))\n\n# compare results from new model\n# Load task output to pandas dataframe and model object for model evaluation\n\nmodel1 = TaskTrain(**params_model1).output().load()\ndf_train = TaskPreprocess(**params_model1).output().load()\nprint(model1.score(df_train.drop('y',1), df_train['y']))\n# 0.987\n\nmodel2 = TaskTrain(**params_model2).output().load()\ndf_train = TaskPreprocess(**params_model2).output().load()\nprint(model2.score(df_train.drop('y',1), df_train['y']))\n# 0.922\n","sub_path":"docs/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"543620059","text":"\"Dylan Murphy\"\r\n\"2018-07-13\"\r\n'Dylan Murphy 2018-07-03'\r\n\r\n\"\"\"This Program cross checks addresses from the Petroleum spill database with addresses listed in \r\nthe PLUTO csv file. these addresses have been edited and formatted in order to properly match.\r\nIt uses a binary search algorithms to search for matching addresses given one \r\nfrom the active spills in Spills.Geocoding excel file\"\"\"\r\n\r\nclass Id:\r\n def __init__(self,borough, block, lot, numbers, spaced_numbers, letters, BBL, x, y, E_des):\r\n self.borough = borough\r\n self.block= block\r\n self.lot= lot\r\n self.numbers=numbers\r\n self.spaced_numbers= spaced_numbers\r\n self.letters=letters\r\n self.BBL=BBL\r\n self.x=x\r\n self.y=y\r\n self.E_des= E_des\r\n \r\n def __repr__(self):\r\n return repr((self.borough, self.block, self.lot, self.numbers,self.spaced_numbers, self.letters, self.BBL, self.x,self.y,self.E_des))\r\n \r\nclass Goofy:\r\n def __init__(self,numbers, spaced_numbers, letters):\r\n self.numbers=numbers\r\n self.spaced_numbers= spaced_numbers\r\n self.letters=letters\r\n \r\n def __repr__(self):\r\n return repr((self.numbers,self.spaced_numbers, self.letters))\r\n \r\n \r\ndef binary_search(items, desired_item, start=0, end=None,):\r\n \r\n \"\"\"Standard Binary search program takes \r\n \r\n Parameters:\r\n items= a sorted list of Id objects\r\n desired_item = a Goofy Object looking for a matching .numbers field in items; single looking for a match (groovy baby)\r\n start= int value representing the index position of search section\r\n end = end boundary of the search section; when end == start\r\n \r\n Returns:\r\n None = only returned if the desired_item not found in items\r\n pos = returns the index position of desired_item if found.\r\n \"\"\"\r\n \r\n if end == None:\r\n end = len(items)\r\n\r\n if start == end:\r\n return None\r\n# raise ValueError(\"%s was not found in the list.\" % desired_item)\r\n\r\n pos = (end - start) // 2 + start\r\n\r\n if desired_item.numbers == items[pos].numbers:\r\n checkfirstSpill=str(desired_item.letters.upper())\r\n checkfirstAddress=str(items[pos].letters.upper())\r\n# if checkfirstSpill[len(checkfirstSpill)//2:] in checkfirstAddress: # have to make sure that checkfirstspill shorter than checkfirst address\r\n if checkfirstSpill[1:-1] in checkfirstAddress:\r\n return pos\r\n else:\r\n i=1\r\n while desired_item.numbers==items[pos+i].numbers:\r\n checkfirstAddress=items[pos+i].letters.upper()\r\n if checkfirstSpill[1:-1] in checkfirstAddress:\r\n print(\"Special case for {} + {} with {} + {}. Took {} steps\".format(str(desired_item.numbers), checkfirstSpill, str(items[pos+i].numbers), checkfirstAddress, i))\r\n return (pos+i)\r\n else:\r\n i+=1\r\n continue\r\n else:\r\n return \r\n #if the next items dont match in numbers, and its been run thru to check for letter matches\r\n #return nothing\r\n elif int(desired_item.numbers) > int(items[pos].numbers):\r\n return binary_search(items, desired_item, start=(pos + 1), end=end)\r\n else: # desired_item < items[pos]:\r\n return binary_search(items, desired_item, start=start, end=pos)\r\n \r\ndef ReadThru(dic, key, SpillOrPluto):\r\n \"\"\"This file takes a filename string, opens that file and reads its contents, and assigns each file the appropriate class objects.\r\n for the spill files which have a total of three fields in their 'meat' this class is 'Goofy' while for \r\n \r\n Parameters:\r\n dic = dictonary object with values of filename strings\r\n key= key in dic to retrive a specific value \r\n \r\n Returns:\r\n SpillObjects= list of Goofy objects from the Spill csv files.\r\n PlutoObjects= list of Id objects from the Pluto csv files.\r\n \"\"\"\r\n \r\n \r\n sheet = dic.get(key)\r\n file= open(str(sheet), 'r')\r\n data = file.readlines()\r\n file.close()\r\n headers = data[0]\r\n meat = data[1:]#just the meat of the file no headers\r\n \r\n if SpillOrPluto=='Spill':\r\n SpillObjects=[]\r\n pointer = 1\r\n for line in meat:\r\n Drew= \"line\"+str(pointer)\r\n fields=line.split(',')\r\n i=0\r\n for item in fields:\r\n WhoseLine= Goofy(fields[i],fields[i+1],fields[i+2])\r\n SpillObjects.append(WhoseLine) \r\n pointer+=1\r\n \r\n return SpillObjects\r\n \r\n elif SpillOrPluto==\"Pluto\": \r\n PlutoObjects=[]\r\n pointer = 1\r\n for line in meat:\r\n Drew= \"line\"+str(pointer)\r\n fields=line.split(',')\r\n i=0\r\n for item in fields:\r\n WhoseLine= Id(fields[i],fields[i+1],fields[i+2],fields[i+3],fields[i+4],fields[i+5],fields[i+6],fields[i+7],fields[i+8],fields[i+9])\r\n PlutoObjects.append(WhoseLine)\r\n pointer+=1\r\n \r\n return PlutoObjects\r\n \r\ndef WriteTo(linelist, outfile):\r\n \"\"\"writes the matches to a CSV file with name outfile\"\"\"\r\n file = open(str(outfile),'w')\r\n i=0\r\n for line in linelist:\r\n file.write(linelist[i].borough+ ',')\r\n file.write(linelist[i].block+ ',') \r\n file.write(linelist[i].lot+ ',')\r\n file.write(linelist[i].numbers+ ',')\r\n file.write(linelist[i].spaced_numbers+ ',')\r\n file.write(linelist[i].letters+ ',') \r\n file.write(linelist[i].BBL+ ',')\r\n file.write(linelist[i].x+ ',')\r\n file.write(linelist[i].y+ ',')\r\n file.write(linelist[i].E_des)\r\n i+=1\r\n file.close()\r\n \r\ndef main():\r\n plutodict={'BK':\"BK_Pluto_2.0.csv\",'BX':\"BX_Pluto_2.0.csv\",'SI':\"SI_Pluto_2.0.csv\"} \r\n spillsdict={'BK':\"BK_Spills_2.0.csv\",'BX':\"BX_Spills_2.0.csv\",'SI':\"SI_Spills_2.0.csv\"}\r\n keylist= plutodict.keys()\r\n for i in keylist:\r\n SpillsList=ReadThru(spillsdict,i,'Spill')\r\n PlutoList=ReadThru(plutodict,i,'Pluto')\r\n # i=0\r\n # for item in mylist:\r\n # print(SpillsList[i].letters)\r\n # i+=1\r\n matchlist=[]\r\n for goo in SpillsList: #goo is goofy obj were searching for matches to\r\n matchindex=binary_search(PlutoList, goo, start=0, end=None)\r\n if matchindex != None:\r\n matchlist.append(matchindex)\r\n # print(matchlist) #ok i have a match index this list has content \r\n #is it right tho?\r\n #fixed an error where binary search was returning any items which matched in numbers \r\n Matches=[]\r\n for success in matchlist:\r\n Matches.append(PlutoList[success])\r\n WriteTo(Matches, str(i)+\"2.0_Matches.csv\")\r\nmain()","sub_path":"BinSearch.py","file_name":"BinSearch.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"249524525","text":"dict1 = {\r\n \"a\": 1\r\n}\r\nfor v in dict1.values():\r\n print (v)\r\n\r\n\r\n\r\nusers = {\r\n'aeinstein': {\r\n'first': 'albert',\r\n'last': 'einstein',\r\n'location': 'princeton',\r\n},\r\n'mcurie': {\r\n'first': 'marie',\r\n'last': 'curie',\r\n'location': 'paris',\r\n},\r\n}\r\nfor username, user_info in users.items():\r\n print(\"\\nUsername: \" + username)\r\n full_name = user_info['first'] + \" \" + user_info['last']\r\n location = user_info['location']\r\n print(\"\\tFull name: \" + full_name.title())\r\n print(\"\\tLocation: \" + location.title())\r\n\r\npet1 = {\"类型\":\"cat\",\"主人\":\"A\"}\r\npet2 = {\"类型\":\"dog\",\"主人\":\"B\"}\r\npet3 = {\"类型\":\"snake\",\"主人\":\"C\"}\r\npets = (pet1,pet2,pet3)\r\nfor pet in pets:\r\n print (\"pet的类型是\" + pet[\"类型\"] + ',')\r\n","sub_path":"dictforin.py","file_name":"dictforin.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"471067301","text":"#Mekhelef Yassine // Bensitel Younes\njean={\"nom\":\"jean\",\"jeu1\":120, \"jeu3\":75, \"jeu4\":50,\"jeu5\":240} \npierre={\"nom\":\"pierre\",\"jeu1\":100, \"jeu5\":140, \"jeu2\":55,\"jeu10\":85} \nalain={\"nom\":\"alain\",\"jeu2\":75,\"jeu1\":90} \nluc={\"nom\":\"luc\", \"jeu2\":45, \"jeu5\":110,\"jeu1\":100}\n\nliste1=[jean,pierre,alain,luc]\n\ndef combien_jeu(dic):\n c=0\n for x in dic:\n c+=1\n\n return c-1\n\n\ndef score_moyen(dic):\n s=0\n i=0\n for x in dic:\n if x!=\"nom\":\n s+=dic[x]\n i+=1\n return s/i\n\ndef qui(jeu,listedico):\n l=[]\n for i in range(len(listedico)):\n for x in listedico[i]: \n if x==jeu:\n l.append(listedico[i][\"nom\"])\n return l\n \n\ndef champion(jeu,listedico):\n m=0\n for i in range(len(listedico)):\n for x in listedico[i]:\n if x==jeu:\n if listedico[i][x]>m:\n m=listedico[i][x]\n t=(m,listedico[i][\"nom\"])\n return t\n\njean2={\"nom\":\"jean\",\"jeu1\":110, \"jeu2\":60,\"jeu3\":95, \"jeu5\":240}\ndef fusionne(d1,d2):\n d=d1.copy()\n m=0\n for x in d2:\n if x in d1 and x in d2:\n if d1[x]>=d2[x]:\n d[x]=d1[x]\n else:\n d[x]=d2[x]\n \n return d \n\ndef touslesjeux(listedico):\n l=[]\n for i in range(len(listedico)):\n for x in listedico[i]:\n if x not in l:\n l.append(x)\n if 'nom' in l:\n l.remove('nom')\n return l\n\ndef dicodeschampions(listedico):\n dic={}\n l=touslesjeux(listedico)\n for i in range(len(l)):\n dic[l[i]]=champion(l[i],listedico)\n return dic\n","sub_path":"L1/Semestre 2/TP INFO/note/exonotedico.py","file_name":"exonotedico.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"310947706","text":"import json\nimport discord\nimport random\n\ndef main():\n # loads a list of quotes from quotes.json\n with open(\"quotes.json\", \"r\") as qf:\n quotes_json = json.load(qf)\n quotes = quotes_json[\"quotes\"]\n\n # loads bot token from config.json\n with open(\"config.json\", \"r\") as cf:\n config_json = json.load(cf)\n bot_token = config_json[\"token\"]\n\n # create a client\n client = discord.Client()\n\n # register a message event listener\n @client.event\n async def on_message(msg):\n # ignore messages from itself and other bots\n if msg.author == client.user or msg.author.bot:\n return\n \n # if the bot is mentioned select a random quote and send it then play the audio for that quote\n for mention in msg.mentions:\n if mention == client.user:\n random_quote = random.choice(list(quotes))\n \n # check if the user is not in any channel or if the bot is already connected to the channel\n if msg.author.voice is None or client.user not in msg.author.voice.channel.members:\n await msg.channel.send(random_quote)\n \n # check if the quote has a sound file\n if quotes[random_quote]:\n voice_client = await msg.author.voice.channel.connect();\n voice_client.play(discord.FFmpegPCMAudio(\"sounds\\\\\" + quotes[random_quote]), after=lambda e: voice_client.loop.create_task(voice_client.disconnect()))\n\n # run the bot\n client.run(bot_token)\n\nif __name__ == \"__main__\":\n main()","sub_path":"quote_bot.py","file_name":"quote_bot.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"69937594","text":"\"\"\"\nThe 20 newsgroups dataset comprises around 18000 newsgroups posts on 20 topics split in two subsets: one for training (or development) and the other one for testing (or for performance evaluation). The split between the train and test set is based upon a messages posted before and after a specific date.\n\nRef: http://scikit-learn.org/stable/datasets/index.html#the-20-newsgroups-text-dataset\n\n\"\"\"\nfrom __future__ import print_function\n\nimport sys\nimport numpy as np\nfrom time import time\nimport logging\n\nfrom sklearn.datasets import fetch_20newsgroups_vectorized, dump_svmlight_file\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.feature_selection import SelectKBest, chi2\n\n\nprint(__doc__)\n\n# Display progress logs on stdout\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\ndatahome = '.'\nif len(sys.argv) > 1:\n datahome = sys.argv[1] \n\n# #############################################################################\n# Download the data, if not already on disk and load it as numpy arrays\nremove = ('headers', 'footers', 'quotes')\ndata = fetch_20newsgroups_vectorized(subset='all', remove=remove, data_home='.')\n\n\nn_samples, n_features = data.data.shape\nx = data.data\ny = data.target\ntarget_names = data.target_names\nn_classes = np.max(y)\n\nprint(\"Total dataset size:\")\nprint(\"n_samples: %d\" % n_samples)\nprint(\"n_features: %d\" % n_features)\nprint(\"n_classes: %d\" % n_classes)\n\n#save to file\nnp.savez('20news', data= data.data, target=data.target, target_names=data.target_names)\n\ndump_svmlight_file(x, y, '20news.svm')\n\n\n# #########################################################\n# Dimension Reduction\n\n# mapping from integer feature name to original token string\nfeature_names = None\nselect_chi2 = 2000\n\nprint(\"Extracting %d best features by a chi-squared test\" % select_chi2)\nt0 = time()\nch2 = SelectKBest(chi2, k=select_chi2)\nx = ch2.fit_transform(x, y)\n#if feature_names:\n# # keep selected feature names\n# feature_names = [feature_names[i] for i\n# in ch2.get_support(indices=True)]\nprint(\"done in %fs\" % (time() - t0))\nprint()\n\n#save to file\nnp.savez('20news_2k', data = x, target = y, target_names=data.target_names)\n\ndump_svmlight_file(x, y, '20news_2k.svm')\n\n\n\n","sub_path":"harp-daal-python/examples/scdemo/src/make_20news.py","file_name":"make_20news.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"606069983","text":"import json\nimport os\n\nCSV_REL_PATHS = []\n\n\ndef get_tile_metadata(local_folder):\n \"\"\"\n Get tile w, h\n Get list of tile upper x, y from JSON files.\n :param local_folder:\n :return:\n \"\"\"\n m_tlw = str(0) # tile width\n m_tlh = str(0) # tile height\n once = 0\n\n tile_min_point_list = []\n\n # Roll through the folders and JSON files for this case_id.\n for csv_dir1 in CSV_REL_PATHS:\n local = os.path.join(local_folder, csv_dir1)\n\n if os.path.isdir(local) and len(os.listdir(local)) > 0:\n # Get list of JSON files we have to read\n json_filename_list = [f for f in os.listdir(local) if f.endswith('.json')]\n for json_filename in json_filename_list:\n # Read each JSON file\n with open(os.path.join(local, json_filename)) as f:\n # f = _io.TextIOWrapper\n data = json.load(f)\n\n if once == 0:\n once = 1\n m_tlw = data[\"tile_width\"]\n m_tlh = data[\"tile_height\"]\n\n if m_tlw != data[\"tile_width\"] or m_tlh != data[\"tile_height\"]:\n print(\"DIFF TILE W/H\")\n print(m_tlw, m_tlh)\n exit(0)\n\n m_tlw = data[\"tile_width\"]\n m_tlh = data[\"tile_height\"]\n\n # print('data', data)\n # Get point\n # point [67584, 45056]\n # data[analysis_id]\n\n tile_minx = data[\"tile_minx\"]\n tile_miny = data[\"tile_miny\"]\n m_point = [tile_minx, tile_miny]\n tile_min_point_list.append(m_point)\n\n # tmp_set {(67584, 45056)} etc.\n tmp_set = set(map(tuple, tile_min_point_list))\n # for n in tmp_set:\n # print(n)\n # convert to {[67584, 45056]}\n unique_tile_min_point_list = map(list, tmp_set)\n return m_tlw, m_tlh, unique_tile_min_point_list\n\n# For processing slide later on\n# tile_width, tile_height, tile_minxy_list = get_tile_metadata(WORK_DIR)\n","sub_path":"save/get_tile_metadata.py","file_name":"get_tile_metadata.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"138969004","text":"class TeamMember:\n\n def __init__(self, id, first_name, last_name, email, phone_number, school, city, team):\n self.id = id\n self.first_name = first_name\n self.last_name = last_name\n self.email = email\n self.phone_number = phone_number\n self.school = school\n self.city = city\n self.team = team\n\n def to_dict(self):\n return {\n 'id': self.id,\n 'first_name': self.first_name,\n 'last_name': self.last_name,\n 'email': self.email,\n 'phone_number': self.phone_number,\n 'school': self.school,\n 'city': self.city,\n 'team_id': self.team\n }\n","sub_path":"backend-master/app/model/team_member.py","file_name":"team_member.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"422887797","text":"import numpy as np\nimport math\nfrom sympy import solve, Symbol, latex, simplify, symbols, Matrix\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n\ndef find_next_event(b_n, d_n, dt):\n t = 0\n win = -1\n while True:\n rand_1 = np.random.uniform(0, 1)\n rand_2 = np.random.uniform(0, 1)\n if rand_1 < d_n*dt:\n return t, 0\n elif rand_2 < b_n*dt:\n return t, 1\n t += dt\n'''\n p_b = b_n * dt\n p_d = d_n * dt\n t_b = np.random.negative_binomial(n=1, p=p_b)*dt\n t_d = np.random.negative_binomial(n=1, p=p_d)*dt\n return min(t_b,t_d), int(t_b>=t_d) # Returns 1 if recovery happens first. 0 else.\n'''\n\nb_n, d_n = [0.1, 1, 10], [0.2, 2, 5] # b_n: new infection, d_n: recovery\ndt = 0.001 # big time steps cause problems in iterate method for last case as both should pass often but only first does\nn_events = 1000\n\nevents = np.zeros(shape=[n_events, 6])\nfor i in range(n_events):\n events[i,0:2] = find_next_event(b_n=b_n[0], d_n=d_n[0], dt=dt)\n events[i,2:4] = find_next_event(b_n=b_n[1], d_n=d_n[1], dt=dt)\n events[i,4::] = find_next_event(b_n=b_n[2], d_n=d_n[2], dt=dt)\n print(str(i+1) + ' events found')\n\n# Only one set of events for b_n,d_n here!\ndef find_event_distance_time(events):\n cum_time = np.cumsum(events[:,0])\n rec_ix = np.where(events[:,1] == 1)[0]\n inf_ix = np.where(events[:,1] == 0)[0]\n rec_ix_roll, inf_ix_roll = np.roll(rec_ix, 1), np.roll(inf_ix, 1)\n rec_times = (cum_time[rec_ix]-cum_time[rec_ix_roll])[1::]\n inf_times = (cum_time[inf_ix]-cum_time[inf_ix_roll])[1::]\n\n return rec_times, inf_times\n\n\nrec_times_1, inf_times_1 = find_event_distance_time(events[:,0:2])\nrec_times_2, inf_times_2 = find_event_distance_time(events[:,2:4])\nrec_times_3, inf_times_3 = find_event_distance_time(events[:,4:6])\nbins_1 = np.linspace(0, max(max(rec_times_1), max(inf_times_1)), 100)\nbins_2 = np.linspace(0, max(max(rec_times_2), max(inf_times_2)), 100)\nbins_3 = np.linspace(0, max(max(rec_times_3), max(inf_times_3)), 100)\nline_1_b = b_n[0]*np.exp(-b_n[0]*bins_1)\nline_1_d = d_n[0]*np.exp(-d_n[0]*bins_1)\nline_2_b = b_n[1]*np.exp(-b_n[1]*bins_2)\nline_2_d = d_n[1]*np.exp(-d_n[1]*bins_2)\nline_3_b = b_n[2]*np.exp(-b_n[2]*bins_3)\nline_3_d = d_n[2]*np.exp(-d_n[2]*bins_3)\n\nplt.figure()\n\nplt.subplot(3,1,1)\nplt.title('Norm. log. Hist for time between inf/rec', fontsize=17)\nplt.hist(rec_times_1, bins=bins_1, color='r', alpha=.5, label='$t_{rec}$, $b_n=.1, d_n=.2$', density=True)#, log=True)\nplt.hist(inf_times_1, bins=bins_1, color='b', alpha=.5, label='$t_{inf}$, $b_n=.1, d_n=.2$', density=True)#, log=True)\nplt.plot(bins_1, line_1_b, color='r', linewidth=3)\nplt.plot(bins_1, line_1_d, color='b', linewidth=3)\nplt.semilogy()\nplt.ylabel('log(density)', fontsize=15)\nplt.legend(fontsize=10)\n\nplt.subplot(3,1,2)\nplt.hist(rec_times_2, bins=bins_2, color='r', alpha=.5, label='$t_{rec}$, $b_n=1, d_n=2$', density=True)#, log=True)\nplt.hist(inf_times_2, bins=bins_2, color='b', alpha=.5, label='$t_{inf}$, $b_n=1, d_n=2$', density=True)#, log=True)\nplt.plot(bins_2, line_2_b, color='r', linewidth=3)\nplt.plot(bins_2, line_2_d, color='b', linewidth=3)\nplt.semilogy()\nplt.ylabel('log(density)', fontsize=15)\nplt.legend(fontsize=10)\n\nplt.subplot(3,1,3)\nplt.hist(rec_times_3, bins=bins_3, color='r', alpha=.5, label='$t_{rec}$, $b_n=10, d_n=5$', density=True)#, log=True)\nplt.hist(inf_times_3, bins=bins_3, color='b', alpha=.5, label='$t_{inf}$, $b_n=10, d_n=5$', density=True)#, log=True)\nplt.plot(bins_3, line_3_b, color='r', linewidth=3)\nplt.plot(bins_3, line_3_d, color='b', linewidth=3)\nplt.semilogy()\nplt.xlabel('Time', fontsize=15)\nplt.ylabel('log(density)', fontsize=15)\nplt.legend(fontsize=10)\nplt.show()\n\nprint()","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"298766474","text":"'''--- Day 2: I Was Told There Would Be No Math ---\n\nThe elves are running low on wrapping paper, and so they need to submit an order for more. They have a list of the dimensions (length l, width w, and height h) of each present, and only want to order exactly as much as they need.\n\nFortunately, every present is a box (a perfect right rectangular prism), which makes calculating the required wrapping paper for each gift a little easier: find the surface area of the box, which is 2*l*w + 2*w*h + 2*h*l. The elves also need a little extra paper for each present: the area of the smallest side.\n\nFor example:\n\nA present with dimensions 2x3x4 requires 2*6 + 2*12 + 2*8 = 52 square feet of wrapping paper plus 6 square feet of slack, for a total of 58 square feet.\nA present with dimensions 1x1x10 requires 2*1 + 2*10 + 2*10 = 42 square feet of wrapping paper plus 1 square foot of slack, for a total of 43 square feet.\nAll numbers in the elves' list are in feet. How many total square feet of wrapping paper should they order?'''\n\nfrom libpuzzle import Puzzle\nimport itertools\n\npairs = lambda l: itertools.permutations(l, 2)\n\nwith Puzzle(1, 2) as p, open('d2.input') as f:\n\tfor present in f:\n\t\tdimensions = [int(x) for x in present.strip().split('x')]\n\n\t\tfaces = [a*b for a, b in pairs(dimensions)]\n\t\tslack = min(faces)\n\t\tp[1].accumulator += sum(faces) + slack\n\n\t\tsmall_perimeter = min([2*a + 2*b for a, b in pairs(dimensions)])\n\t\tvolume = 1\n\t\tfor dim in dimensions:\n\t\t\tvolume *= dim\n\t\tp[2].accumulator += small_perimeter + volume\n\n\n\tfor part in p.values():\n\t\tpart.text(part.accumulator)","sub_path":"2015/d2.py","file_name":"d2.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"454596118","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/tonra/ohm2/clients/ohm2/entwicklung/ohm2-dev-light/webapp/backend/apps/ohm2_handlers_light/management/commands/ohm2_handlers_light_startapp.py\n# Compiled at: 2017-09-22 11:48:26\n# Size of source mod 2**32: 3142 bytes\nfrom django.core.management.base import BaseCommand, CommandError\nfrom ohm2_handlers_light import utils as h_utils\nfrom subprocess import call\nimport os, shutil\n\ndef load_template(template, name):\n path = os.path.join(os.path.dirname(os.path.realpath(__file__)), template)\n with open(path, 'r') as (f):\n content = f.read()\n return content.format(name.upper(), name.lower(), name.title(), h_utils.get_random_string(32), int(h_utils.random_string_hexdigits(3), 16) * 64)\n\n\ndef append(filename, text):\n with open(filename, 'a') as (f):\n f.write(text)\n\n\ndef override(filename, text):\n with open(filename, 'w') as (f):\n f.write(text)\n\n\nclass Command(BaseCommand):\n\n def add_arguments(self, parser):\n parser.add_argument('-a', '--app')\n parser.add_argument('-m', '--move')\n\n def handle(self, *args, **options):\n app = options['app']\n move = options.get('move')\n if move:\n move_to = os.path.join(move, app)\n exist = os.path.isdir(move_to)\n if exist:\n self.stdout.write('Final destination already exist')\n return\n else:\n move_to = None\n call('./manage.py startapp ' + app, shell=True)\n os.makedirs(app + '/management')\n override(app + '/management/__init__.py', '')\n os.makedirs(app + '/management/commands')\n override(app + '/management/commands/__init__.py', '')\n os.makedirs(app + '/static')\n os.makedirs(app + '/static/' + app)\n os.makedirs(app + '/templates')\n os.makedirs(app + '/templates/' + app)\n to_run = [\n {'src': 'templates/app_test_command.template', 'dst': app + '/management/commands/' + app + '_test_command.py', 'func': override},\n {'src': 'templates/app_settings.template', 'dst': app + '/settings.py', 'func': override},\n {'src': 'templates/app_definitions.template', 'dst': app + '/definitions.py', 'func': override},\n {'src': 'templates/app_errors.template', 'dst': app + '/errors.py', 'func': override},\n {'src': 'templates/app_decorators.template', 'dst': app + '/decorators.py', 'func': override},\n {'src': 'templates/app_utils.template', 'dst': app + '/utils.py', 'func': override},\n {'src': 'templates/app_models.template', 'dst': app + '/models.py', 'func': override},\n {'src': 'templates/app_managers.template', 'dst': app + '/managers.py', 'func': override},\n {'src': 'templates/app_urls.template', 'dst': app + '/urls.py', 'func': override},\n {'src': 'templates/app_views.template', 'dst': app + '/views.py', 'func': override},\n {'src': 'templates/app_dispatcher.template', 'dst': app + '/dispatcher.py', 'func': override},\n {'src': 'templates/app_middlewares.template', 'dst': app + '/middlewares.py', 'func': override},\n {'src': 'templates/app_admin.template', 'dst': app + '/admin.py', 'func': override},\n {'src': 'templates/app_serializers.template', 'dst': app + '/serializers.py', 'func': override},\n {'src': 'templates/app_context_processors.template', 'dst': app + '/context_processors.py', 'func': override}]\n for run in to_run:\n text = load_template(run['src'], app)\n run['func'](run['dst'], text)\n\n if move_to:\n shutil.move(app, move_to)","sub_path":"pycfiles/django-ohm2-handlers-light-0.4.3.tar/ohm2_handlers_light_startapp.cpython-35.py","file_name":"ohm2_handlers_light_startapp.cpython-35.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"263778446","text":"# $Id$\n#\n# @rocks@\n# Copyright (c) 2000 - 2010 The Regents of the University of California\n# All rights reserved. Rocks(r) v5.4 www.rocksclusters.org\n# https://github.com/Teradata/stacki/blob/master/LICENSE-ROCKS.txt\n# @rocks@\n#\n# $Log$\n# Revision 1.2 2010/09/07 23:52:53 bruno\n# star power for gb\n#\n# Revision 1.1 2010/05/07 18:27:43 bruno\n# closer\n#\n#\n\nimport stack.commands\nimport stack.commands.dump\nimport stack.commands.dump.firewall\n\n\nclass Command(stack.commands.OSArgumentProcessor,\n\tstack.commands.dump.firewall.command):\n\t\"\"\"\n\tDump the set of firewall rules for an os\n\n\t\n\tZero or more OS names\n\t\n\n\t\n\tDump firewall rules for redhat OS.\n\t\n\t\"\"\"\n\n\tdef run(self, params, args):\n\t\tfor os in self.getOSNames(args):\n\n\t\t\trows = self.db.execute(\"\"\"select tabletype, name, insubnet,\n\t\t\t\toutsubnet, service, protocol, chain, action, flags,\n\t\t\t\tcomment from os_firewall where os = '%s' \"\"\"\n\t\t\t\t% os)\n\n\t\t\tif rows > 0:\n\t\t\t\tself.dump_firewall('os', os)\n\n","sub_path":"common/src/stack/command/stack/commands/dump/os/firewall/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"49447842","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport random\n\nfortune = {'1'\n :{'zentai':'大吉! すべてよし','shigoto':'仕事運 全て上手くいく'},\n\t \t '2'\n\t \t :{'zentai':'中吉! まぁまぁよし','shigoto':'仕事運 努力すれば実る'},\n\t\t '3'\n\t\t :{'zentai':'吉! よし','shigoto':'仕事運 なかなか実らず'},\n\t '4'\n\t\t :{'zentai':'凶! わるし','shigoto':'仕事運 全てが上手くいかず'}\n }\n\nprint('あなたの名前を入力してください')\n\n# 名前を入力\nname = input('>>')\nprint('{} さんの運勢は、'.format(name))\n\n# 運勢をランダムで取得\nnum = list(fortune)\nfor k,v in (fortune[random.choice(num)].items()):\n\tunsei = v\n\t# 結果を出力\n\tprint(unsei + 'となります!')\n\n# 運勢が吉以上かで判断\nif '吉' in unsei:\n\tprint('おめでとうございます。')\nelse:\n\tprint('またお願いします。')","sub_path":"1st/code/ono/omikuji_7_for_if_ver1.py","file_name":"omikuji_7_for_if_ver1.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"544560244","text":"#model在创建实例的时候;\n#实例里面是有外键的;\n\n#则外键的值一定要是对应值的实例;\n\nCheckImplement_obj = CheckImplement.objects.create(time=end_time_second,day=end_time)\nCheckItems_obj = CheckItems.objects.get(id=int(log_content['id']))\n\n#CheckImplement_id和CheckItems_id为外键\n#CheckImplement_obj和CheckItems_obj为对应的实例\n\nCheckItemDetail.objects.create(CheckImplement_id=CheckImplement_obj, CheckItems_id=CheckItems_obj,\n collect_result=result, is_compliance=is_score, cmdb_id=ip_logs['ip'],\n check_item_class=u'弱口令', order=u'')\n\n\n","sub_path":"数据库实例的创建中带有外键的情况.py","file_name":"数据库实例的创建中带有外键的情况.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"528911429","text":"class Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n counter = 0 \n zero_count = 0 \n for i in range(len(nums)):\n if nums[i] != 0:\n nums[counter] = nums[i]\n counter += 1\n else: \n zero_count += 1 \n if zero_count != len(nums): \n while counter < len(nums):\n nums[counter] = 0\n counter += 1 \n \n ","sub_path":"283.MoveZeroes.py","file_name":"283.MoveZeroes.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"166424422","text":"\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nfrom datetime import datetime, timedelta\r\nfrom dateutil.parser import parse\r\n\r\n##import validators\r\n##from pymongo import MongoClient\r\nimport asyncio\r\n#import websockets\r\nimport urllib.request as web\r\nimport json \r\n\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\nfrom flask import Flask, render_template\r\n \r\napp = Flask(__name__)\r\n\r\n\r\n#webscripting historical data for analysis at last 1 years(360 days) \r\ndef hist_price(tick):\r\n start_date = '20180101'\r\n end_date = '20181221'\r\n ndays = abs((datetime.strptime(end_date, \"%Y%m%d\") - datetime.strptime(start_date, \"%Y%m%d\")).days) +1\r\n \r\n #contruct URL by tick and date and webscripting history data\r\n url = \"https://coinmarketcap.com/currencies/\" + tick +\"/historical-data/?start=\" + start_date +\"&end=\" + end_date \r\n soup = BeautifulSoup(requests.get(url, \"lxml\").content)\r\n header = list(i.get_text() for i in soup.find_all('th'))\r\n values = list(v.get_text().replace(\",\",\"\") for v in soup.find_all('td'))\r\n\r\n #dataframe for 730-days price\r\n hist = []\r\n for i in range(0,ndays):\r\n hist.append(values[i*7:7*i+7]) \r\n hist_df = pd.DataFrame(hist[:],columns=header)\r\n hist_df .insert(0, 'Tick', tick)\r\n \r\n #conver data if it is number or date\r\n hist_df = hist_df.apply(pd.to_numeric, errors='ignore')\r\n hist_df['Date'] = [parse(d).strftime('%m/%d/%y') for d in hist_df['Date']]\r\n hist_df = hist_df.sort_values(by='Date', ascending=True) \r\n\r\n return hist_df[['Tick','Date','Open*','High','Low','Close**']]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n #Top expensive Cryptocurrencies\r\n tickers = ['bitcoin','ethereum','bitcoin-cash','maker']\r\n \r\n col_names1 = ['Tick','Date','Open*','High','Low','Close**']\r\n data = pd.DataFrame(columns=col_names1)\r\n data_mav20 = pd.DataFrame()\r\n data_px = pd.DataFrame()\r\n weekly_return = pd.DataFrame()\r\n \r\n for i in tickers : \r\n df = hist_price(i) \r\n df.set_index('Date')\r\n data = data.append(df)\r\n \r\n \r\n #calculate 20-day Close MAV\r\n #save data to _MAV20.csv file to local drive\r\n df['MAV20'] = df['Close**'].rolling(20).mean()\r\n df_mav20 = df[['Date','Close**','MAV20']]\r\n \r\n fileName = i +'_MAV20.csv'\r\n df_mav20.to_csv(fileName, sep=',',index=False)\r\n \r\n \r\n #calculate Close weekly return\r\n index = 0\r\n wr = []\r\n weeks = []\r\n \r\n \r\n \r\n for index in range(int((len(df)+2)/7)-1) : \r\n rate = ((df['Close**'][index*7])/(df['Close**'][(index+1)*7-1]) -1)*100\r\n wr.append(rate)\r\n index = index + 1 \r\n weeks.append(index)\r\n \r\n data_px['Weeks'] = weeks \r\n data_px['Tick'] = i\r\n data_px['Weekly_rate'] = wr\r\n weekly_return = weekly_return.append(data_px)\r\n \r\n \r\n #save data to .csv file to local drive\r\n data.to_csv('data.csv', sep=',',columns=None, header=True, index=False, index_label=None)\r\n weekly_return.to_csv('weekly_return.csv', sep=',',columns=None, header=True, index=False, index_label=None)\r\n \r\n \r\n","sub_path":"Final Project/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"507886488","text":"import re\r\nfrom gensim.summarization import summarize\r\nimport numpy as np\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom scipy.sparse.linalg import svds\r\nimport networkx\r\n\r\nimport nltk\r\nnltk.download('punkt')\r\nnltk.download('stopwords')\r\n\r\n#FEATURE ENGENEERING FOR LSA AND TEXT RANK\r\ndef feature_engineering(doc):\r\n tv = TfidfVectorizer(min_df=0., max_df=1., use_idf=True)\r\n dt_matrix = tv.fit_transform(nltk_sum(doc, feature_engi=True))\r\n dt_matrix = dt_matrix.toarray()\r\n td_matrix = dt_matrix.T\r\n return td_matrix\r\n\r\n#GENSIM\r\ndef gen_preprocess(doc):\r\n doc_pre = re.sub(r'\\n|\\r', '', doc)\r\n doc_pre = re.sub(r' +', '', doc)\r\n doc_pre = re.sub(',(?!\\s+\\d$)', '', doc)\r\n doc_pre = doc_pre.strip()\r\n return doc_pre\r\n \r\ndef gen_summarize(doc, ratio=0.2):\r\n return summarize(gen_preprocess(doc), ratio=ratio, split=False)\r\n\r\n\r\n#NLTK\r\ndef normalize_document(doc):\r\n stop_words = nltk.corpus.stopwords.words('english')\r\n # lower case and remove special characters\\whitespaces\r\n doc = re.sub(r'[^a-zA-Z\\s]', '', doc, re.I|re.A)\r\n doc = doc.lower()\r\n doc = doc.strip()\r\n # tokenize document\r\n tokens = nltk.word_tokenize(doc)\r\n # filter stopwords out of document\r\n filtered_tokens = [token for token in tokens if token not in stop_words]\r\n # re-create document from filtered tokens\r\n doc = ' '.join(filtered_tokens)\r\n return doc\r\n\r\ndef nltk_sum(doc, num_sent=7, feature_engi=False):\r\n sentences = nltk.sent_tokenize(doc)\r\n normalize_corpus = np.vectorize(normalize_document)\r\n norm_sentences = normalize_corpus(sentences)\r\n \r\n if feature_engi == False:\r\n return norm_sentences[:num_sent]\r\n else:\r\n return norm_sentences\r\n \r\ndef nltk_max_sentences(doc):\r\n return len(nltk.sent_tokenize(doc))\r\n\r\n#LSA\r\ndef low_rank_svd(matrix, singular_count=2):\r\n u, s, vt = svds(matrix, k=singular_count)\r\n return u, s, vt\r\n\r\n\r\ndef LSA_sum(doc, num_sentences=7, num_topics=3):\r\n u, s, vt = low_rank_svd(feature_engineering(doc), singular_count=num_topics)\r\n term_topic_mat, singular_values, topic_document_mat = u, s, vt\r\n \r\n # remove singular values below threshold \r\n sv_threshold = 0.5\r\n min_sigma_value = max(singular_values) * sv_threshold\r\n singular_values[singular_values < min_sigma_value] = 0 \r\n \r\n salience_scores = np.sqrt(np.dot(np.square(singular_values), np.square(topic_document_mat))) \r\n top_sentence_indices = (-salience_scores).argsort()[:num_sentences]\r\n top_sentence_indices.sort()\r\n \r\n sentences = nltk.sent_tokenize(doc)\r\n \r\n return ' '.join(np.array(sentences)[top_sentence_indices])\r\n\r\n\r\n#TEXT RANK\r\ndef text_rank_summ(doc, num_sentences=7):\r\n \r\n similarity_matrix = np.matmul(feature_engineering(doc).T, feature_engineering(doc))\r\n np.round(similarity_matrix, 3)\r\n \r\n similarity_graph = networkx.from_numpy_array(similarity_matrix)\r\n \r\n scores = networkx.pagerank(similarity_graph)\r\n ranked_sentences = sorted(((score, index) for index, score in scores.items()), reverse=True)\r\n ranked_sentences[:num_sentences]\r\n \r\n top_sentence_indices = [ranked_sentences[index][1] for index in range(num_sentences)]\r\n top_sentence_indices.sort()\r\n \r\n sentences = nltk.sent_tokenize(doc)\r\n \r\n return ' '.join(np.array(sentences)[top_sentence_indices])\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"252246956","text":"\"\"\"Self-stabilizing Gaussian Mixture Model\"\"\"\n\n# Authors: Jeffrey Wang\n# License: BSD 3 clause\n\nimport numpy as np\nimport warnings\n\nfrom ._utils import format_array, create_random_state\nfrom ._exceptions import ConvergenceWarning\n\nclass SGMM:\n\t\"\"\"\n\tA modified Gaussian Mixture Model that stabilizes\n\tthe optimal number of components during fitting.\n\n\tSGMM refines the number of components during each\n\titeration of the EM algorithm with a modified\n\tBayesian Information Criterion.\n\n\tParameters\n\t----------\n\tinit_cores : int, default=10\n\t\tThe initial number of Cores (Gaussian components) to fit the data.\n\n\tstabilize : int or None, default=0.5\n\t\tThe adaption rate for stabilization of the number of Cores.\n\t\tIf None, stabilization is disabled.\n\n\tn_init : int, default=10\n\t\tNumber of times the SGMM will be run with different\n Core seeds. The final results will be the best output of\n n_init consecutive runs in terms of inertia.\n\n\tmax_iter : int, default=200\n\t\tMaximum number of iterations of the SGMM for a\n single run.\n\n\ttol : float, default=1e-4\n\t\tRelative tolerance with regards to the difference in inertia\n\t\tof two consecutive iterations to declare convergence.\n\n\trandom_state : None or int or RandomState, default=None\n\t\tDetermines random number generation for Core initialization. Use\n an int to make the randomness deterministic.\n\n\tAttributes\n\t----------\n\tdim : int\n\t\tThe dimensionality of the model; the number of features the model\n\t\texpects.\n\n\tinertia : float\n\t\tAverage of maximal probabilities of each sample to each Core.\n\n\tconverged : bool\n\t\tTrue when convergence was reached in fit(), False otherwise.\n\n\tcores : array-like, shape (n_cores,)\n\t\tA list of Cores.\n\n\t_data_range : array-like, shape (2, n_features)\n\t\tThe range that encompasses the data in each axis.\n\t\"\"\"\n\tdef __init__(self, init_cores=10, stabilize=0.5, n_init=10, max_iter=200,\n\t\t\t\t\ttol=1e-4, random_state=None):\n\t\tself.dim = -1\n\t\tself.init_cores = n_cores\n\t\tself.stabilize = stabilize\n\t\tself.n_init = n_init\n\t\tself.max_iter = max_iter\n\t\tself.tol = tol\n\t\tself.random_state = create_random_state(seed=random_state)\n\t\tself.inertia = -np.inf\n\t\tself.cores = []\n\t\tself._data_range = None\n\n\tdef fit(self, data):\n\t\t\"\"\"\n\t\tEstimate model parameters with the EM algorithm.\n\n\t\tThe method fits the model `n_init` times and sets\n\t\tthe parameters with which the model has the\n\t\tlargest likelihood or lower bound. Within each trial,\n\t\tthe method iterates between E-step and M-step for\n\t\t`max_iter` times until the change of likelihood or lower bound\n\t\tis less than `tol`, otherwise, a ConvergenceWarning is raised.\n\n\t\tParameters\n\t\t----------\n\t\tdata : array-like, shape (n_samples, n_features)\n\t\t\tList of `n_features`-dimensional data points.\n\t\t\tEach row corresponds to a single data point.\n\t\t\"\"\"\n\t\tdata = self._validate_data(data)\n\t\tbest_inertia, best_cores = self.inertia, self.cores\n\t\tfor init in range(1, self.n_init + 1):\n\t\t\tinertia, cores = self._fit_single(data)\n\t\t\tif inertia > best_inertia:\n\t\t\t\tbest_inertia, best_cores = inertia, cores\n\t\tif not self.converged:\n\t\t\twarnings.warn('Initialization %d did not converge. '\n 'Try different init parameters, '\n 'or increase max_iter, tol '\n 'or check for degenerate data.'\n % (init), ConvergenceWarning)\n\t\tself.cores, self.inertia = best_cores, best_inertia\n\t\treturn self\n\n\tdef predict(self, data):\n\t\t\"\"\"\n\t\tPredict the labels for `data` using the model.\n\n\t\tParameters\n\t\t----------\n\t\tdata : array-like, shape (n_samples, n_features)\n\t\t\tList of `n_features`-dimensional data points.\n\t\t\tEach row corresponds to a single data point.\n\n\t\tReturns\n\t\t-------\n\t\tlabels : array, shape (n_samples,)\n\t\t\tComponent labels.\n\t\t\"\"\"\n\t\tdata = self._validate_data(data)\n\t\testimates = np.asarray(self._expectation(data)).T\n\t\treturn estimates.argmax(axis=-1)\n\n\tdef _validate_data(self, data):\n\t\t\"\"\"\n\t\tValidate and format the given `data`.\n\t\tEnsure the data matches the model's dimensionality.\n\t\tIf the model has yet to set a dimensionality, set it\n\t\tto match the dimensionality of `data`.\n\n\t\tParameters\n\t\t----------\n\t\tdata : array-like, shape (n_samples, n_features)\n\t\t\tList of `n_features`-dimensional data points.\n\t\t\tEach row corresponds to a single data point.\n\n\t\tReturns\n\t\t-------\n\t\tformatted_data : array-like, shape (n_samples, n_features)\n\t\t\tList of `n_features`-dimensional data points.\n\t\t\tEach row corresponds to a single data point.\n\t\t\"\"\"\n\t\tdata = format_array(data)\n\t\tif self.dim == -1:\n\t\t\tself.dim = data.shape[-1]\n\t\telif self.dim != data.shape[-1]:\n\t\t\traise ValueError(\"Mismatch in dimensions between model and input data.\")\n\t\treturn data\n\n\tdef _fit_single(self, data):\n\t\t\"\"\"\n\t\tA single attempt to estimate model parameters\n\t\twith the EM algorithm.\n\n\t\tThe method iterates between E-step and M-step for\n\t\t`max_iter` times until the change of likelihood or lower bound\n\t\tis less than `tol`.\n\n\t\tParameters\n\t\t----------\n\t\tdata : array-like, shape (n_samples, n_features)\n\t\t\tList of `n_features`-dimensional data points.\n\t\t\tEach row corresponds to a single data point.\n\n\t\tReturns\n\t\t-------\n\t\tinertia : float\n\t\t\tLog likelihood of the model.\n\n\t\tcores : array-like, shape (n_cores,)\n\t\t\tA list of Cores for this fit trial.\n\t\t\"\"\"\n\t\tcores = self._initialize(data)\n\t\tinertia, bic = -np.inf, np.inf\n\t\tfor iter in range(1, self.max_iter + 1):\n\t\t\tp = self._expectation(data)\n\t\t\tself._maximization(data, p)\n\t\t\tprev_inertia, inertia = inertia, self.score(p)\n\t\t\tif np.abs(inertia - prev_inertia) < self.tol:\n\t\t\t\tself.converged = True\n\t\t\t\tbreak\n\t\t\tprev_bic, bic = bic, self.bic(data)\n\t\t\tif self.stabilize is not None:\n\t\t\t\tself._stabilize(bic, prev_bic, p)\n\t\treturn inertia, cores\n\n\tdef _initialize(self, data):\n\t\t\"\"\"\n\t\tInitialize a set of Cores within the data space.\n\n\t\tParameters\n\t\t----------\n\t\tdata : array-like, shape (n_samples, n_features)\n\t\t\tList of `n_features`-dimensional data points.\n\t\t\tEach row corresponds to a single data point.\n\n\t\tReturns\n\t\t-------\n\t\tcores : array, shape (n_cores,)\n\t\t\tList of Cores within the data space given by `data`.\n\t\t\"\"\"\n\t\tdata = self._validate_data(data)\n\t\tself._data_range = np.asarray([np.min(data, axis=0), np.max(data, axis=0)])\n\t\tcores = []\n\t\tfor n in range(self.init_cores):\n\t\t\tcore = self._initialize_core()\n\t\t\tcores.append(core)\n\t\tcores = np.asarray(cores)\n\t\treturn cores\n\n\tdef _initialize_core(self):\n\t\t\"\"\"\n\t\tInitialize a Core within the data space.\n\n\t\tReturns\n\t\t-------\n\t\tcore : Core\n\t\t\tA Core within the data space given by `data`.\n\t\t\"\"\"\n\t\tif self._data_range is not None:\n\t\t\tmu = self.random_state.rand(self.dim) * (self.data_range[1] - self.data_range[0]) + self.data_range[0]\n\t\t\tsigma = make_spd_matrix(self.dim)\n\t\t\tdelta = np.ones((1)) / self.init_cores\n\t\t\treturn Core(mu=mu, sigma=sigma, delta=delta)\n\t\telse:\n\t\t\traise RuntimeError(\"Data Range hasn't been set, likely because SGMM hasn't been initialized yet\")\n\n\tdef _expectation(self, data):\n\t\t\"\"\"\n\t\tConduct the expectation step.\n\n\t\tParameters\n\t\t----------\n\t\tdata : array-like, shape (n_samples, n_features)\n\t\t\tList of `n_features`-dimensional data points.\n\t\t\tEach row corresponds to a single data point.\n\n\t\tReturns\n\t\t-------\n\t\tp : array, shape (n_cores, n_samples)\n\t\t\tProbabilities of samples under each Core.\n\t\t\"\"\"\n\t\tp = []\n\t\tfor core in self.cores:\n\t\t\tm, s = core.mu, core.sigma\n\t\t\tp.append(core.pdf(data))\n\t\tp = np.asarray(p)\n\t\tif p.shape != (len(self.cores), len(data)):\n\t\t\traise RuntimeError(\"Expectation Step found erroneous shape\")\n\t\treturn p\n\n\tdef _maximization(self, data, prob):\n\t\t\"\"\"\n\t\tConduct the maximization step.\n\n\t\tParameters\n\t\t----------\n\t\tdata : array-like, shape (n_samples, n_features)\n\t\t\tList of `n_features`-dimensional data points.\n\t\t\tEach row corresponds to a single data point.\n\n\t\tprob : array, shape (n_cores, n_samples)\n\t\t\tProbabilities of samples under each Core.\n\t\t\"\"\"\n\t\tfor p, c in zip(range(len(prob)), range(len(self.cores))):\n\t\t\tb_num = prob[p] * self.cores[c].delta\n\t\t\tb_denom = np.sum([prob[i] * self.cores[i].delta for i in range(len(self.cores))], axis=0) + 1e-8\n\t\t\tb = b_num / b_denom\n\t\t\tself.cores[c].mu = np.sum(b.reshape(len(data), 1) * data, axis=0) / np.sum(b + 1e-8)\n\t\t\tself.cores[c].sigma = np.dot((b.reshape(len(data), 1) * (data - self.cores[c].mu)).T,\n\t\t\t\t\t\t\t\t\t\t(data - self.cores[c].mu)) / np.sum(b + 1e-8)\n\t\t\tself.cores[c].delta = np.mean(b)\n\n\tdef _stabilize(self, bic, prev_bic, p):\n\t\t\"\"\"\n\t\tEstimate the ideal number of Cores at the current step.\n\t\tChange the cores in the model to fit this estimate.\n\n\t\tNew cores are seeded randomly within the data space.\n\t\tCores are removed based on their probability and overlap with\n\t\tother Cores.\n\n\t\tParameters\n\t\t----------\n\t\tbic : float\n\t\t\tBayesian Information Criterion of the current step.\n\n\t\tprev_bic : float\n\t\t\tBayesian Information Criterion of the previous step.\n\n\t\tp : array, shape (n_cores, n_samples)\n\t\t\tProbabilities of samples under each Core.\n\t\t\"\"\"\n\t\tgradient = bic - prev_bic if prev_bic != np.inf else 10 * bic\n\t\tstep = round(gradient * self.stabilize)\n\t\tif step > 0:\n\t\t\tfitness = []\n\t\t\tfor i in range(len(p)):\n\t\t\t\tf = np.sum((p[i] - np.sum(np.delete(p, i, axis=0), axis=0)).clip(min=0))\n\t\t\t\tfitness.append(f, i)\n\t\t\tfitness = sorted(fitness, key=lambda x: x[1])\n\t\t\tfor i in step:\n\t\t\t\tnp.delete(self.cores, fitness[i][1], axis=0)\n\t\telif step < 0:\n\t\t\tfor i in range(step):\n\t\t\t\tself.cores.append(self._initialize_core)\n\n\tdef score(self, p):\n\t\t\"\"\"\n\t\tCompute the per-sample average log-likelihood.\n\n\t\tParameters\n\t\t----------\n\t\tp : array-like, shape (n_cores, n_samples)\n\t\t\tProbabilities of samples under each Core.\n\n\t\tReturns\n\t\t-------\n\t\tlog_likelihood : float\n\t\t\tLog likelihood of the model.\n\t\t\"\"\"\n\t\treturn np.mean(np.sum(np.log(p), axis=0))\n\n\tdef bic(self, data):\n\t\t\"\"\"\n\t\tBayesian Information Criterion for the current model\n\t\ton the input `data`.\n\n\t\tParameters\n\t\t----------\n\t\tdata : array-like, shape (n_samples, n_features)\n\t\t\tList of `n_features`-dimensional data points.\n\t\t\tEach row corresponds to a single data point.\n\n\t\tReturns\n\t\t-------\n\t\tbic : float\n\t\t\tBayesian Information Criterion. The lower the better.\n\t\t\"\"\"\n\t\tfit = -2 * self.score(self._expectation(data)) * len(data)\n\t\tpenalty = self._n_parameters() * np.log(len(data))\n\t\treturn fit + penalty\n\n\tdef _n_parameters(self):\n\t\t\"\"\"\n\t\tReturn the number of free parameters in the model.\n\n\t\tReturns\n\t\t-------\n\t\tn_parameters : int\n\t\t\tThe number of free parameters in the model.\n\t\t\"\"\"\n\t\tsigma_params = self.n_cores * self.dim * (self.dim + 1) / 2\n\t\tmu_params = self.dim * self.n_cores\n\t\tdelta_params = self.n_cores\n\t\treturn int(sigma_params + mu_params + delta_params - 1)\n","sub_path":"dsigm/_sgmm.py","file_name":"_sgmm.py","file_ext":"py","file_size_in_byte":10551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"526004593","text":"import sys\nimport torch\nimport torch.nn.functional as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tqdm import tqdm\nfrom gif_writer import write_gif\nfrom common_utils import *\n\nr = [1.0, 1.01]\ng = lambda x,y: x*y*(torch.sin(x*y)**2)\n\nn = 1024 # simulation dimension\nd = 6 # number of grids to traverse\ntolerance = 1e-4\ncpu = False\n\n\nn,d,tolerance,cpu = get_args([\n [\"-n\", int, n],\n [\"-d\", int, d],\n [\"--tolerance\", float, tolerance],\n [\"--cpu\", bool, cpu]\n], verbose=True)\n\n\nif not torch.cuda.is_available():\n print(\"No capable CUDA devices, using CPU ...\")\n cpu = True\n\ndef condition(ub,r):\n # dirichlet boundary conditions\n ub[:, 0] = 0.25 # left\n ub[:,-1] = 0.25 # right\n ub[ 0,:] = 0.25 # top\n ub[-1,:] = 0.25 # bottom\n\n return ub\n\ndef apply_force(x,r,g):\n indices = torch.FloatTensor([list(range(x.shape[-1]))])\n h = (r[1] - r[0]) / (x.shape[-1]-1)\n coords = torch.zeros([2,*x.shape])\n coords[0][:] = r[0] + h*indices\n coords[1][:,:] = r[0] + h*indices.T\n return 0.25 * (h**2) * g(coords[0], coords[1])\n\nmulti_grid = []\nfor i in range(d):\n s = n // (2**(d-i))\n x = torch.zeros([1,3,s+2,s+2])\n x[0,-1] = apply_force(x[0,-1], r, g)\n if not cpu:\n x = x.cuda()\n multi_grid.append(x)\nprint(f\" - Grids {[x.shape[-1]-2 for x in multi_grid]}\")\n\nw = torch.zeros(1,1,3,3)\nw[0,0,1,:] = 0.25\nw[0,0,:,1] = 0.25\nw[0,0,1,1] = 0\nprint(f\" - Kernel: \\n{w}\")\n\nup = torch.ones(1,1,2,2)\nub = torch.zeros([1,3,n+2,n+2])\nub[0,-1] = apply_force(ub[0,-1], r, g)\n\nif not cpu:\n w = w.cuda()\n up = up.cuda()\n ub = ub.cuda()\n\n# apply initial conditions\nmulti_grid[0][:,0:1] = condition(multi_grid[0][0,0], r)\n\n# apply multigridding\nfor i in range(d):\n k = 0\n idx = 0\n while True:\n multi_grid[i][:,(idx+1)%2] = multi_grid[i][:,idx]\n idx = (idx + 1)%2\n\n # -- solve at lower res\n multi_grid[i][:,idx:idx+1] = tf.conv2d(multi_grid[i][:,idx:idx+1], w, padding=1) - multi_grid[i][0,-1]\n multi_grid[i][:,idx:idx+1] = condition(multi_grid[i][0,idx], r)\n\n mse = ((multi_grid[i][0,0]-multi_grid[i][0,1])**2).mean()\n k += 1\n\n space = ' '*(len(str(d)) - len(str(i+1)))\n print(f\"\\r[{space}{i+1}] Iteration: {' '*(6-len(str(k)))}{k} MSE: {mse:.4e}{' '*6}\", end=\"\")\n if mse < tolerance:\n break\n print()\n\n # -- upscale\n if i < d-1:\n multi_grid[i+1][:,0:1,1:-1, 1:-1] = tf.conv_transpose2d(multi_grid[i][:,idx:idx+1,1:-1,1:-1], up, stride=2)\n else:\n ub[:, 0:1, 1:-1, 1:-1] = tf.conv_transpose2d(multi_grid[i][:,idx:idx+1,1:-1,1:-1], up, stride=2)\n\n# solve on target grid\nk = 0\nidx = 0\nwhile True:\n ub[:,(idx+1)%2] = ub[:,idx]\n idx = (idx + 1)%2\n\n ub[:,idx:idx+1] = tf.conv2d(ub[:, idx:idx+1], w, padding=1) - ub[0,-1]\n ub[:,idx:idx+1] = condition(ub[0, idx], r)\n\n mse = ((ub[0,0]-ub[0,1])**2).mean()\n k += 1\n\n s = len(str(d))\n s2 = s // 2\n space = f\"{' '*(s2)}*{' '*(s-s2-1)}\"\n print(f\"\\r[{space}] Iteration: {' '*(6-len(str(k)))}{k} MSE: {mse:.4e}{' '*6}\", end=\"\")\n if mse < tolerance:\n break\n\nub = ub.cpu().numpy()[0]\n\nfinal_error = np.zeros([n+2,n+2])\nfinal_error[1:-1,1:-1] = (ub[idx,2:,1:-1] + ub[idx,:-2,1:-1] + ub[idx,1:-1,2:] + ub[idx,1:-1,:-2])\nfinal_error[1:-1,1:-1] -= 4*ub[idx,1:-1,1:-1]\n\nindices = torch.FloatTensor([list(range(n+2))])\nh = (r[1] - r[0]) / (n+2-1)\ncoords = torch.zeros([2,n+2,n+2])\ncoords[0][:] = r[0] + h*indices\ncoords[1][:,:] = r[0] + h*indices.T\n\nfig,ax = plt.subplots(1,3,figsize=(10,6))\nfor i in range(3):\n ax[i].set_xticks([])\n ax[i].set_yticks([])\n\na = ax[0].imshow(ub[idx])\nb = ax[1].imshow(final_error)\nc = ax[2].imshow(g(coords[0], coords[1]))\n\nplt.colorbar(a, ax=[ax[0]], location='bottom')\nplt.colorbar(b, ax=[ax[1]], location='bottom')\nplt.colorbar(c, ax=[ax[2]], location='bottom')\n\nax[0].set_title(\"$f\\,(x_i,y_i)$\")\nax[1].set_title(\"$\\\\nabla^2 f$\")\nax[2].set_title(\"$g$\")\n\nplt.show()\n","sub_path":"sections/3/3_1_poisson.py","file_name":"3_1_poisson.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"331635102","text":"import equips\n\n\nclass BaseHero():\n life_points = 0\n properties = {}\n resistence = {}\n attack = 0\n defense = 0\n equips = []\n\n def get_equip_by_type(self, equip_type):\n current_equip_type = [equip for equip in self.equips if equip.equip_type == equip_type]\n return current_equip_type, bool(current_equip_type)\n\n def check_equip(self, equip):\n current_equip, exist = self.get_equip_by_type(equip.equip_type)\n if exist:\n self.remove_equip(current_equip_type[0])\n self.add_equip(equip)\n\n def add_equip(self, equip):\n self.equips.append(equip)\n self.life_points += equip.life_points\n for element, amount in equip.resistence.items():\n if self.resistence.get(element):\n self.resistence[element] += amount\n else:\n self.resistence.update({element: amount})\n for element, amount in equip.properties.items():\n if self.properties.get(element):\n self.properties[element] += amount\n else:\n self.properties.update({element: amount})\n\n def remove_equip(self, equip):\n self.equips.remove(equip)\n self.life_points -= equip.life_points\n for element, amount in equip.resistence.items():\n if self.resistence.get(element):\n self.resistence[element] += amount\n else:\n self.resistence.update({element: amount})\n for element, amount in equip.properties.items():\n if self.properties.get(element):\n self.properties[element] += amount\n else:\n self.properties.update({element: amount})\n\n\nclass Paladin(BaseHero):\n\n name = 'Paladin'\n\n def __init__(self, life_points=100, properties={'light': 20}, resistence={'light': 40}, attack=30, defense=20):\n self.life_points = life_points\n self.attack = attack\n self.defense = defense\n self.resistence = resistence\n self.properties = properties\n","sub_path":"src/heroes.py","file_name":"heroes.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"608559240","text":"from django.urls import path\nfrom Insta.views import HelloWorld, PostsView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView\n\nurlpatterns = [\n path('', HelloWorld.as_view(), name='home'),\n path('posts/', PostsView.as_view(), name=\"posts\"),\n path('posts//', PostDetailView.as_view(), name=\"post_detail\"),\n path('post/new/', PostCreateView.as_view(), name=\"make_post\"),\n path('post/update//', PostUpdateView.as_view(), name=\"update_post\"),\n path('post/delete//', PostDeleteView.as_view(), name=\"delete_post\"),\n]\n","sub_path":"Insta/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"451603862","text":"\"\"\"\nRun MP-PCA.\n\"\"\"\nimport numpy as np\nimport nibabel as nib\nfrom nilearn.masking import apply_mask, unmask\n\n\ndef mppca_denoise(img, window=(5, 5, 5), mask=None):\n \"\"\"\n Denoising implementation by Jonas Olesen, Mark Does and Sune Jespersen for diffusion\n MRI data based on the algorithm presented by Veraart et al. (2016) 142, p\n 394-406 https://doi.org/10.1016/j.neuroimage.2016.08.016.\n\n Modified to remove mean across voxels (compute principal components of\n the covariance not correlation matrix).\n\n Parameters\n ----------\n image\n contains MRI image data. The first dimensions must\n discriminate between pixels, while the last dimension should correspond\n to b-value/ gradient variation. Thus image data could for instance be\n structured as [X,Y,Z,N] or [X,Y,N].\n window\n specifies the dimensions of the sliding window. For image data\n structured as [X,Y,Z,N], a window of [5 5 5] is typical.\n mask\n logical array specifying which pixels to include -- if image is\n [X,Y,Z,N] then mask is [X,Y,Z]. Can optionally be left unspecified in\n which case every pixel is included.\n\n Returns\n -------\n denoisedImage\n contains denoised image with same structure as input.\n S2\n contains estimate of variance in each pixel.\n P\n specifies the found number of principal components.\n\n Notes\n -----\n Free to use, but please cite Veraart et al. (2016) 142, p\n 394-406 https://doi.org/10.1016/j.neuroimage.2016.08.016 and Does et al.,\n MRM (2018) (Evaluation of Principal Component Analysis Image Denoising on\n Multi-Exponential MRI Relaxometry), reference will be finalized when\n available.\n \"\"\"\n if isinstance(img, str):\n img = nib.load(img)\n\n dims = img.shape\n assert len(window) > 1 and len(window) < 4\n assert all(np.array(window) > 0)\n assert all([(w % 2) == 1 for w in window]), 'window must be all odd numbers'\n assert all([window[i] < dims[i] for i in range(len(window))])\n window = [int((w - 1) / 2) for w in window] # convert to radii\n\n # Preallocate arrays\n denoised = img.get_data()\n S2 = np.zeros(img.shape[:3])\n P = np.zeros(img.shape[:3])\n counter = np.zeros(img.shape[:3], int)\n\n # Load mask\n if isinstance(mask, str):\n mask = nib.load(mask)\n\n if mask:\n mask_data = mask.get_data()\n else:\n mask_data = np.ones(img.shape)\n\n mask_idx = np.vstack(np.where(mask_data))\n for i in range(mask_idx.shape[1]):\n i, j, k = mask_idx[:, i]\n\n # Define 3D window\n i_min = np.max((i - window[0], 0))\n i_max = np.min((i + window[0] + 1, mask_data.shape[0]))\n j_min = np.max((j - window[1], 0))\n j_max = np.min((j + window[1] + 1, mask_data.shape[1]))\n k_min = np.max((k - window[2], 0))\n k_max = np.min((k + window[2] + 1, mask_data.shape[2]))\n window_mask = mask_data[i_min:i_max, j_min:j_max, k_min:k_max]\n\n # skip if only one voxel of window in mask\n if window_mask.sum() < 2:\n continue\n\n temp_mask = np.zeros(mask_data.shape, int)\n temp_mask[i_min:i_max, j_min:j_max, k_min:k_max] = window_mask\n temp_mask_img = nib.Nifti1Image(temp_mask, img.affine)\n\n masked_data = apply_mask(img, temp_mask_img) # (n_vols, n_voxels)\n denoised_data, sigma2, p = denoise_matrix(masked_data)\n\n # Convert scalars to window-sized arrays\n sigma2 = sigma2 * np.ones(denoised_data.shape[1])\n p = p * np.ones(denoised_data.shape[1])\n\n # create full-sized zero arrays with only window filled with real values\n unmasked_data = unmask(denoised_data, temp_mask_img).get_data()\n unmasked_sigma2 = unmask(sigma2, temp_mask_img).get_data()\n unmasked_p = unmask(p, temp_mask_img).get_data()\n\n # add denoised values to arrays\n denoised += unmasked_data\n S2 += unmasked_sigma2\n P += unmasked_p\n counter += temp_mask_img.get_data()\n\n # Divide the summed arrays by the number of times each voxel\n # is used across windows to get an average\n temp_counter = counter.copy()\n temp_counter[temp_counter == 0] = 1 # workaround for divide-by-zero errors\n denoised = denoised / temp_counter[..., None]\n S2 = S2 / temp_counter\n P = P / temp_counter\n\n # Fill denoised data not in mask or skipped by loop\n # with original data\n original = img.get_data()\n inv_mask = (1 - mask_data).astype(bool)\n skipped_voxels = (mask_data & ~counter).astype(bool)\n denoised[inv_mask, :] = original[inv_mask, :]\n denoised[skipped_voxels, :] = original[skipped_voxels, :]\n\n # Make imgs\n denoised = nib.Nifti1Image(denoised, img.affine)\n S2 = nib.Nifti1Image(S2, img.affine)\n P = nib.Nifti1Image(P, img.affine)\n\n return denoised, S2, P\n\n\ndef denoise_matrix(X):\n \"\"\"\n helper function to denoise.m\n Takes as input matrix X with dimension MxN with n_voxels corresponding to the\n number of pixels and n_vols to the number of data points. The output consists\n of \"newX\" containing a denoised version of X, \"sigma2\" an approximation\n to the data variation, \"p\" the number of signal carrying components.\n\n Parameters\n ----------\n X : (n_voxels, n_vols) array_like\n Array of data to denoise\n \"\"\"\n n_vols, n_voxels = X.shape\n min_mn = np.min(X.shape)\n X_m = np.mean(X, axis=1, keepdims=True) # MDD added Jan 2018; mean added back to signal below\n X = X - X_m\n # [U,S,V] = svdecon(X); MDD replaced with MATLAB svd vvv 3Nov2017\n # U, S, V = svd(X, 'econ')\n # NOTE: full matrices=False should be same as economy-size SVD\n U, S, V = np.linalg.svd(X, full_matrices=True)\n S = np.diag(S) # make S array into diagonal matrix\n\n lambda_ = (np.diag(S) ** 2) / n_voxels\n\n scaling = (n_vols - np.arange(min_mn)) / n_voxels\n scaling[scaling < 1] = 1\n for n_comps in range(min_mn):\n sigma2 = (lambda_[n_comps] - lambda_[min_mn - 1]) / (4 * np.sqrt((n_vols - n_comps) / n_voxels))\n p_test = np.sum(lambda_[n_comps:min_mn]) / scaling[n_comps] >= (min_mn - n_comps) * sigma2\n if p_test:\n continue\n\n sigma2 = np.sum(lambda_[n_comps:min_mn]) / (min_mn - n_comps) / scaling[n_comps]\n new_X = np.dot(np.dot(U[:, :n_comps], S[:n_comps, :n_comps]), V[:, :n_comps].T) + X_m\n return new_X, sigma2, n_comps\n","sub_path":"mppca.py","file_name":"mppca.py","file_ext":"py","file_size_in_byte":6421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"155273401","text":"# Author: Justyna Pawlata\n# Project Euler (https://projecteuler.net/)\n\n# Problem 7:\n# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.\n# What is the 10 001st prime number?\n\n# check if the number is prime (taken from problem no. 3)\ndef ifPrime(num):\n if num <= 1:\n return False\n else:\n for i in range(2, ((num//2)+1)):\n if num % i == 0:\n return False\n return True\n\ndef primeNumList(limit):\n prime_list = []\n for i in range(2, 10000000):\n if ifPrime(i): prime_list.append(i)\n if len(prime_list) == limit: \n return prime_list\n \nlimit = 10001\n\nprime_list = primeNumList(limit)\nprint(prime_list[-1])","sub_path":"python/0007.py","file_name":"0007.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"416260763","text":"\"\"\"models.py - This file contains the class definitions for the Datastore\nentities used by the Game. Because these classes are also regular Python\nclasses they can include methods (such as 'to_form' and 'new_game').\"\"\"\n\nimport random\nfrom datetime import date\nfrom protorpc import messages\nfrom google.appengine.ext import ndb\n \nclass User(ndb.Model):\n \"\"\"User profile\"\"\"\n name = ndb.StringProperty(required=True)\n email =ndb.StringProperty()\n\n game = ndb.KeyProperty(kind='Game', repeated=True)\n\nclass Position(ndb.Model):\n \"\"\"Represents board position\"\"\"\n user=ndb.KeyProperty(required=True, kind='User')\n index= ndb.IntegerProperty(required=True) \n result=ndb.StringProperty() \n\n \n\n\nclass Game(ndb.Model):\n \"\"\"Game object\"\"\"\n \n game_over = ndb.BooleanProperty(required=True, default=False)\n player_one = ndb.KeyProperty(required=True, kind='User')\n player_two = ndb.KeyProperty(required=True, kind='User')\n winner = ndb.KeyProperty(kind='User')\n current_status= ndb.StructuredProperty(Position, repeated=True)\n game_cancelled = ndb.BooleanProperty(default=False)\n\n @classmethod\n def new_game(cls, player1,player2):\n \"\"\"Creates and returns a new game\"\"\"\n \n game = Game(player_one= player1,\n player_two=player2,\n game_over=False,\n game_cancelled=False)\n game.put()\n\n #add the game to the user objects\n player1_user = player1.get()\n player2_user = player2.get()\n\n player1_user.game.append(game.key)\n player2_user.game.append(game.key)\n\n #save users\n player1_user.put()\n player2_user.put()\n\n return game\n\n def to_form(self, message):\n \"\"\"Returns a GameForm representation of the Game\"\"\"\n form = GameForm()\n form.urlsafe_key = self.key.urlsafe()\n form.player1_name = self.player_one.get().name\n form.player2_name = self.player_two.get().name\n form.history=[self.to_history_form(x.user.get().name,x.index,x.result) for x in self.current_status]\n form.game_over = self.game_over\n form.game_cancelled=self.game_cancelled\n form.message = message\n return form\n\n def end_game(self, won,winner):\n \"\"\"Ends the game - if won is True, the player won. -,\n the player lost.\"\"\"\n self.game_over = True\n self.winner=winner\n self.put()\n # Add the game to the score 'board'\n score = Score(user=winner, date=date.today(), won=won, game=self.key)\n score.put()\n\n\n def to_game_history(self):\n \"\"\"returns a GameHistoryForm with a list of all moves\"\"\"\n return GameHistoryForm(items=[self.to_history_form(x.user.get().name,x.index,x.result) \n for x in self.current_status]) \n\n\n def to_history_form(self,player,index,result):\n \"\"\"Returns a HistoryForm with a move\"\"\"\n form=HistoryForm()\n form.player=player\n form.position=index\n form.result=result\n return form \n \n\nclass Score(ndb.Model):\n \"\"\"Score object\"\"\"\n user = ndb.KeyProperty(required=True, kind='User')\n date = ndb.DateProperty(required=True)\n won = ndb.BooleanProperty(required=True)\n game=ndb.KeyProperty(required=True, kind='Game')\n\n \n\nclass HistoryForm(messages.Message):\n \"\"\"HistoryForm for outbound move entry\"\"\"\n player=messages.StringField(1)\n position=messages.IntegerField(2)\n result=messages.StringField(3)\n\nclass GameForm(messages.Message):\n \"\"\"GameForm for outbound game state information\"\"\"\n urlsafe_key = messages.StringField(1, required=True)\n player1_name = messages.StringField(2, required=True)\n player2_name = messages.StringField(3, required=True)\n history=messages.MessageField(HistoryForm,4,repeated=True)\n game_over = messages.BooleanField(5, required=True)\n game_cancelled=messages.BooleanField(6)\n message = messages.StringField(7, required=True)\n\nclass GameForms(messages.Message):\n \"\"\"Return multiple GameForms\"\"\"\n items = messages.MessageField(GameForm, 1, repeated=True)\n\nclass RankForm(messages.Message):\n \"\"\"Rank For a single user entry\"\"\"\n user=messages.StringField(1,required=True)\n wins=messages.IntegerField(2,required=False) \n\n\nclass NewGameForm(messages.Message):\n \"\"\"Used to create a new game\"\"\"\n player1_name = messages.StringField(1, required=True)\n player2_name = messages.StringField(2, required=True)\n\n\nclass MakeMoveForm(messages.Message):\n \"\"\"Used to make a move in an existing game\"\"\"\n player = messages.StringField(1, required=True)\n move = messages.IntegerField(2, required=True)\n\n\nclass RankForms(messages.Message):\n \"\"\"Return multiple RankForms\"\"\"\n items = messages.MessageField(RankForm, 1, repeated=True)\n\n\nclass StringMessage(messages.Message):\n \"\"\"StringMessage-- outbound (single) string message\"\"\"\n message = messages.StringField(1, required=True)\n\nclass GameHistoryForm(messages.Message):\n \"\"\"Return multiple HistoryForms\"\"\"\n items = messages.MessageField(HistoryForm, 1, repeated=True) \n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"630263429","text":"# Regular Expressions\nimport re\n# Requests\nimport requests\n# BS4 for scraping\nfrom bs4 import BeautifulSoup\n# For pretty printing data\nimport pprint as pp\nimport sys\nimport cymysql\n\nsys.setrecursionlimit(1500)\n# Pages\nvisited_pages = []\nvisited_articles = []\n\n# Database connection\n#conn = cymysql.connect(host='127.0.0.1', user='root', passwd='', db='crawlers', charset='utf8')\n#cur = conn.cursor()\n\n\ndef make_soup(url):\n r = requests.get(url)\n soup = BeautifulSoup(r.content, 'html.parser')\n return soup\n\n\ndef get_all_articles(url, news_type):\n complete_url = url + news_type\n\n try:\n soup = make_soup(complete_url)\n articles = soup.select('.eagle-item__body')\n all_articles = []\n\n for article in articles:\n all_articles.append(article.select('a')[0].get('href'))\n\n return all_articles\n except:\n print(\"Error in making soup. Please try again later.\")\n return False, False\n\n\n # def insert_article_in_database(article):\n # try:\n # query = 'INSERT into `aaj_tak` (`id`, `body`, `image_url`, `category`, `title`, `url`, `news_time`) VALUES (NULL, %s, %s, %s, %s, %s, %s)'\n # cur.execute(query, (\n # str(article['body']), str(article['image_url']), str(article['category']), str(article['title']), str(article['url']), str(article['news_time'])))\n # conn.commit()\n # print(\"Saved successfully -->\" + article['title'])\n # except cymysql.err.IntegrityError:\n # print(\"Already present --> \" + article['title'])\n # except:\n # print(\"There was an Error for --> \" + article['title'])\n\ndef get_article(url):\n article_desc = {}\n soup = make_soup(url)\n article_desc['title'] = soup.select('.story-body__h1')[0].contents[0]\n try:\n article_desc['image_url'] = soup.select('.js-image-replace')[0].get('src')\n except:\n pass\n article_desc['news_time'] = soup.select('.date')[0].get('data-datetime')\n\n bodytext = []\n for paragraphs in range (0,20):\n try:\n bodytext.append(soup.select('.story-body__inner p')[paragraphs].get_text())\n except:\n pass\n\n bodytext = [''.join(bodytext)]\n article_desc['body'] = bodytext\n print (article_desc)\n return article_desc\n\n\ndef main():\n\n types = ['international', 'india', 'sport', 'entertainment', 'science']\n\n for link_type in types:\n\n article_urls = get_all_articles(\"http://www.bbc.com/hindi/\", link_type)\n for article_url in article_urls:\n comp_url = \"http://www.bbc.com\" + article_url\n\n\n article_desc = get_article(comp_url)\n article_desc['category'] = link_type\n article_desc['url'] = comp_url\n # insert_article_in_database(article_desc)\n\n # get_article(\"http://aajtak.intoday.in/story/evm-hacking-hackathon-election-commission-1-929419.html\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bbc-hindi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"382058646","text":"from rest_framework import serializers\nfrom devices.models import Device, App, DeviceApp\n\n\nclass AppSerializer(serializers.ModelSerializer):\n id = serializers.IntegerField()\n\n class Meta:\n model = App\n fields = ('id', 'name', 'package_name', 'version', 'apk', )\n\n\nclass DeviceAppSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = DeviceApp\n fields = ('id', 'name', 'package_name', )\n\n\nclass DeviceSerializer(serializers.ModelSerializer):\n apps = AppSerializer(many=True, read_only=False)\n white_list = DeviceAppSerializer(many=True, read_only=False)\n installed_apps = DeviceAppSerializer(many=True, read_only=False)\n\n class Meta:\n model = Device\n fields = ('id', 'device_id', 'info', 'apps', 'white_list', 'block_apps', 'installed_apps')\n\n def create(self, validated_data):\n device = Device(\n device_id=validated_data['device_id'],\n info=validated_data['info']\n )\n device.save()\n\n if validated_data['apps']:\n for item in validated_data['apps']:\n device.apps.add(item['id'])\n device.save()\n\n if validated_data['installed_apps']:\n for item in validated_data['installed_apps']:\n find = DeviceApp.objects.filter(package_name=item['package_name'])\n if find.count() == 1:\n app = find.first()\n else:\n app = DeviceApp.objects.create(**item)\n device.installed_apps.add(app.id)\n if validated_data['white_list']:\n for item in validated_data['white_list']:\n find = DeviceApp.objects.filter(package_name=item['package_name'])\n if find.count() == 1:\n app = find.first()\n else:\n app = DeviceApp.objects.create(**item)\n device.white_list.add(app.id)\n return device\n","sub_path":"server/devices/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"470177325","text":"#!/bin/python3\r\n\r\nimport sys\r\n\r\n# Maior potência k de um primo p, tal que p**kn: return 0\r\n k=0\r\n while (p**k<=n):\r\n k+=1\r\n return k-1\r\n\r\nprimo=[2,3,5,7,11,13,17,19,23,29,31,37]\r\n\r\nt = int(input().strip())\r\nfor a0 in range(t):\r\n n = int(input().strip())\r\n ans=1\r\n for i in range (0,12):\r\n ans *= primo[i]**maior_potencia(primo[i],n)\r\n print(ans)","sub_path":"Hacker Rank - Project Euler/hackerrank-euler005.py","file_name":"hackerrank-euler005.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"52279913","text":"import numpy as np\nfrom gym import utils\nfrom gym.envs.mujoco import mujoco_env\nfrom gym.envs.mujoco.utils import q_inv, q_mult\n\n\nDEFAULT_CAMERA_CONFIG = {\n 'distance': 25.0,\n 'trackbodyid': 2\n}\n\n\nclass AntMTEnv(mujoco_env.MujocoEnv, utils.EzPickle):\n def __init__(self,\n xml_file='ant_v2_white.xml',\n ctrl_cost_weight=5e-3,\n contact_cost_weight=0,\n healthy_reward=0.0,\n dead_cost_weight=100,\n terminate_when_unhealthy=True,\n healthy_z_range=(0.2, 1.0),\n contact_force_range=(-1.0, 1.0),\n reset_noise_scale=0.6,\n velocity_reward_weight=1.0e-0,\n exclude_current_positions_from_observation=False,\n n_rays=20,\n sensor_span=np.pi*0.8,\n sensor_range=5,\n save_init_quaternion=True \n ):\n utils.EzPickle.__init__(**locals())\n\n self._n_tasks = 3\n self._ctrl_cost_weight = ctrl_cost_weight\n self._contact_cost_weight = contact_cost_weight\n self._dead_cost_weight = dead_cost_weight\n\n self._healthy_reward = healthy_reward\n self._terminate_when_unhealthy = terminate_when_unhealthy\n self._healthy_z_range = healthy_z_range\n\n self._contact_force_range = contact_force_range\n self._reset_noise_scale = reset_noise_scale\n\n self._velocity_reward_weight = velocity_reward_weight\n \n self._exclude_current_positions_from_observation = exclude_current_positions_from_observation\n\n self._obstacle_filter = np.asarray([False, True], dtype=np.uint8) \n self._n_rays = n_rays\n self._sensor_span = sensor_span\n self._sensor_range = sensor_range\n self._ray_angles = np.zeros(n_rays)\n for ray in range(self._n_rays):\n self._ray_angles[ray] = self._sensor_span * (- 0.5 + (2*ray + 1)/(2*self._n_rays))\n self._goal_readings = np.zeros(n_rays)\n self._goal_sizes = np.zeros(n_rays)\n\n self._init_quaternion = np.array([1.0, 0.0, 0.0, 0.0])\n self._save_init_quaternion = save_init_quaternion\n \n self._obstacle_types = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\n mujoco_env.MujocoEnv.__init__(self, xml_file, 5)\n\n @property\n def orientation(self):\n a, vx, vy, vz = self.sim.data.qpos[3:7].copy() # quaternion frame (roll-pitch-yaw)\n orientation = [1-2*(vy**2+vz**2), 2*(vx*vy + a*vz), 2*(vx*vz - a*vy)]\n orientation /= np.dot(orientation,orientation)**0.5 \n return orientation\n\n @property\n def orientation_z(self):\n a, vx, vy, vz = self.sim.data.qpos[3:7].copy() # quaternion frame (roll-pitch-yaw)\n orientation = [2*(vx*vz - a*vy), 2*(vy*vz + a*vx), 1-2*(vx**2+vy**2)]\n orientation /= np.dot(orientation,orientation)**0.5 \n return orientation\n\n @property\n def xy_orientation(self):\n orientation = np.array(self.orientation[:2])\n orientation /= np.dot(orientation,orientation)**0.5\n return orientation.copy()\n \n def xy_orientation_init(self):\n a, vx, vy, vz = self._init_quaternion # quaternion frame (roll-pitch-yaw)\n orientation = [1-2*(vy**2+vz**2), 2*(vx*vy + a*vz), 2*(vx*vz - a*vy)]\n orientation /= np.dot(orientation,orientation)**0.5\n xy_orientation = np.array(orientation[:2])\n xy_orientation /= np.dot(xy_orientation,xy_orientation)**0.5\n return xy_orientation \n\n @property\n def xy_orientation_angle(self):\n x, y = self.xy_orientation\n return np.arctan2(y, x)\n\n def ray_orientation(self, theta):\n orientation_quaternion = [0, np.cos(theta), np.sin(theta), 0]\n rotation_quaternion = self.sim.data.qpos[3:7].copy()\n orientation = q_mult(q_mult(rotation_quaternion, orientation_quaternion), q_inv(rotation_quaternion))[1:]\n return orientation\n\n @property\n def head_position(self):\n return np.asarray(self.get_body_com(\"head\")[:3], dtype=np.float64).copy()\n \n @property\n def body_position(self):\n return np.asarray(self.get_body_com(\"torso\")[:3], dtype=np.float64).copy()\n\n def get_current_maze_obs(self): \n wall_readings = np.zeros(self._n_rays)\n self._goal_readings = np.zeros(self._n_rays)\n self._goal_sizes = np.zeros(self._n_rays)\n danger_readings = np.zeros(self._n_rays)\n\n for ray in range(self._n_rays):\n ray_theta = self._ray_angles[ray]\n ray_orientation = np.asarray(self.ray_orientation(ray_theta), dtype=np.float64)\n distance, obstacle_id = self.sim.ray_fast_group(self.head_position, ray_orientation, self._obstacle_filter) \n if obstacle_id >= 0 and distance <= self._sensor_range:\n if self._obstacle_types[obstacle_id] == 1:\n wall_readings[ray] = (self._sensor_range - distance) / self._sensor_range\n elif self._obstacle_types[obstacle_id] == 2 and self._objects_ON[obstacle_id-5] >= 1.0:\n self._goal_readings[ray] = (self._sensor_range - distance) / self._sensor_range\n self._goal_sizes[ray] = self._objects_ON[obstacle_id-5] / self._n_steps_target_depletion\n elif self._obstacle_types[obstacle_id] == 3 and self._objects_ON[obstacle_id-5] >= 1.0:\n danger_readings[ray] = (self._sensor_range - distance) / self._sensor_range \n\n obs = np.concatenate([\n wall_readings.copy(),\n self._goal_readings.copy(),\n self._goal_sizes.copy()# ,\n # danger_readings.copy()\n ])\n \n self._target_in_sight = self._goal_readings.sum() > self._n_rays/4\n\n return obs\n\n def rotate_vector(self, angle, vector):\n c = np.cos(angle)\n s = np.sin(angle)\n rotation_matrix = np.array([[ c, s],\n [-s, c]])\n return np.dot(rotation_matrix, vector) \n\n @property\n def xy_velocity(self):\n return self.sim.data.qvel.flat.copy()[:2]\n\n def velocity_reward(self):\n speed = np.dot(self.xy_velocity, self.xy_velocity)**0.5\n velocity_direction = self.xy_velocity / speed\n similarity = np.dot(velocity_direction, self.xy_orientation)\n similarity_2 = np.dot(self.xy_orientation_init(), self.xy_orientation)\n similarity_3 = np.dot(velocity_direction, self.xy_orientation_init())\n reward = np.sign(similarity) * similarity**2\n reward += np.sign(similarity_2) * similarity_2**2\n reward += np.sign(similarity_3) * similarity_3**2\n return self._velocity_reward_weight * speed * reward/3.0\n\n def angular_velocity_reward(self, orientation_before):\n x_before, y_before = orientation_before\n angle_before = np.arctan2(y_before, x_before)\n x_rotated, y_rotated = self.rotate_vector(angle_before, self.xy_orientation) \n angle_in_previous_frame = np.arctan2(y_rotated, x_rotated)\n velocity = angle_in_previous_frame/(np.pi * self.dt)\n return self._velocity_reward_weight * velocity\n \n @property\n def healthy_reward(self):\n return float(\n self.is_healthy\n or self._terminate_when_unhealthy\n ) * self._healthy_reward\n\n @property\n def dead_cost(self):\n return float(not self.is_healthy) * self._dead_cost_weight\n\n def control_cost(self, action):\n control_cost = self._ctrl_cost_weight * np.sum(np.square(action))\n return control_cost\n\n @property\n def contact_forces(self):\n raw_contact_forces = self.sim.data.cfrc_ext\n min_value, max_value = self._contact_force_range\n contact_forces = np.clip(raw_contact_forces, min_value, max_value)\n return contact_forces\n\n @property\n def contact_cost(self):\n contact_cost = self._contact_cost_weight * np.sum(\n np.square(self.contact_forces))\n return contact_cost\n\n @property\n def is_healthy(self):\n state = self.state_vector()\n min_z, max_z = self._healthy_z_range\n is_healthy = (np.isfinite(state).all() and min_z <= state[2] <= max_z and np.sqrt(2.0)*np.abs(self.orientation[2])<1.0 and self.orientation_z[2] >= 0.5)\n return is_healthy\n\n @property\n def done(self):\n done = (not self.is_healthy and self._terminate_when_unhealthy) # or self.target_reached\n return done\n\n def step(self, action):\n xy_position_before = self.get_body_com(\"torso\")[:2].copy()\n xy_orientation_before = self.xy_orientation\n self.do_simulation(action, self.frame_skip)\n xy_position_after = self.get_body_com(\"torso\")[:2].copy()\n\n xy_velocity = (xy_position_after - xy_position_before) / self.dt\n x_velocity, y_velocity = xy_velocity\n\n ctrl_cost = self.control_cost(action) \n dead_cost = self.dead_cost\n # contact_cost = self.contact_cost\n\n forward_reward = self.velocity_reward()\n anticlock_reward = self.angular_velocity_reward(xy_orientation_before)\n linear_velocity_cost = (xy_velocity**2).sum() * self._velocity_reward_weight\n healthy_reward = self.healthy_reward\n \n rewards = healthy_reward\n costs = ctrl_cost + dead_cost\n\n reward = rewards - costs\n done = self.done\n observation = self._get_obs()\n info = {\n 'reward_0': forward_reward-np.abs(anticlock_reward),\n 'reward_2': anticlock_reward-linear_velocity_cost,\n 'reward_1': -anticlock_reward-linear_velocity_cost\n }\n\n return observation, reward, done, info\n\n def _get_obs(self):\n position = self.sim.data.qpos.flat.copy()\n velocity = self.sim.data.qvel.flat.copy()\n contact_force = self.contact_forces.flat.copy()\n maze_obs = self.get_current_maze_obs()\n\n if self._exclude_current_positions_from_observation:\n position = position[2:]\n\n observations = np.concatenate((position, velocity, self._init_quaternion, maze_obs)) \n\n return observations\n \n def _update_quaternion(self):\n self._init_quaternion = self.sim.data.qpos[3:7].copy()\n\n def reset_model(self):\n noise_low = -self._reset_noise_scale\n noise_high = self._reset_noise_scale\n\n qpos = self.init_qpos + self.np_random.uniform(\n low=noise_low, high=noise_high, size=self.model.nq) \n \n angle = 2*np.pi*(np.random.rand()-0.5)\n qpos[3] = np.cos(angle/2.0)\n qpos[4] = qpos[5] = 0.0\n qpos[6] = np.sin(angle/2.0)\n qpos[2] = self.init_qpos[2]\n\n qpos += self.np_random.uniform(\n low=noise_low/4, high=noise_high/4, size=self.model.nq)\n\n qvel = self.init_qvel + self._reset_noise_scale * self.np_random.randn(\n self.model.nv)\n self.set_state(qpos, qvel)\n\n self._init_quaternion = self.sim.data.qpos[3:7].copy()\n self._goal_readings = np.zeros(self._n_rays)\n self._goal_sizes = np.zeros(self._n_rays)\n\n observation = self._get_obs()\n\n return observation\n\n # def viewer_setup(self):\n # for key, value in DEFAULT_CAMERA_CONFIG.items():\n # if isinstance(value, np.ndarray):\n # getattr(self.viewer.cam, key)[:] = value\n # else:\n # setattr(self.viewer.cam, key, value)\n def viewer_setup(self):\n self.viewer.cam.trackbodyid = 1\n self.viewer.cam.distance = self.model.stat.extent * 4\n self.viewer.cam.elevation = -55\n","sub_path":"gym/envs/ant_multitask.py","file_name":"ant_multitask.py","file_ext":"py","file_size_in_byte":11671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"575186962","text":"# Python v3.5.1\n\nimport re\n\n\n# -------------------- EX. 1 --------------------\n\n\ndef process_date(this_date):\n\n\t# This regex makes sure that this_date is YYYY-MM-DD\n\tif not re.search(r'^\\d\\d\\d\\d\\-\\d\\d\\-\\d\\d$', this_date):\n\t\traise ValueError('please, submit date in YYYY-MM-DD format')\n\t\t# Everything in Python is an object\n\t\t# So when we are raising an exception\n\t\t# We are creating an exception instance\n\n\tprint('the submitted date is {0}'.format(this_date))\n\nprocess_date('1980-01-03')\nprint; print\n# process_date('1/3/1980')\n\n\n\n# -------------------- EX. 2 --------------------\n\nclass MyError(Exception):\n\n\t# *args means any number of arguments\n\tdef __init__(self, *args): # get call when instance is created\n\t\tprint('calling __init__')\n\t\tif args:\n\t\t\tself.message = args[0]\n\t\telse:\n\t\t\tself.message = ''\n\n\tdef __str__(self): # get call when exception is raised\n\t\tprint('calling string')\n\t\tif self.message:\n\t\t\treturn 'Here is a MyError exception with a message: {0}'.format(self.message)\n\t\telse:\n\t\t\treturn 'Here\\'s MyError exception'\n\n#raise MyError # raising with no arguments\n\nraise MyError('Houston, we have a problem') # raising our custom exception with an argument\n\n","sub_path":"cust_except.py","file_name":"cust_except.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"201794170","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass Filters(Model):\n \"\"\"Describes all the filtering operations, such as de-interlacing, rotation\n etc. that are to be applied to the input media before encoding.\n\n :param deinterlace: The de-interlacing settings.\n :type deinterlace: ~azure.mgmt.media.models.Deinterlace\n :param rotation: The rotation, if any, to be applied to the input video,\n before it is encoded. Default is Auto. Possible values include: 'Auto',\n 'None', 'Rotate0', 'Rotate90', 'Rotate180', 'Rotate270'\n :type rotation: str or ~azure.mgmt.media.models.Rotation\n :param crop: The parameters for the rectangular window with which to crop\n the input video.\n :type crop: ~azure.mgmt.media.models.Rectangle\n :param overlays: The properties of overlays to be applied to the input\n video. These could be audio, image or video overlays.\n :type overlays: list[~azure.mgmt.media.models.Overlay]\n \"\"\"\n\n _attribute_map = {\n 'deinterlace': {'key': 'deinterlace', 'type': 'Deinterlace'},\n 'rotation': {'key': 'rotation', 'type': 'str'},\n 'crop': {'key': 'crop', 'type': 'Rectangle'},\n 'overlays': {'key': 'overlays', 'type': '[Overlay]'},\n }\n\n def __init__(self, **kwargs):\n super(Filters, self).__init__(**kwargs)\n self.deinterlace = kwargs.get('deinterlace', None)\n self.rotation = kwargs.get('rotation', None)\n self.crop = kwargs.get('crop', None)\n self.overlays = kwargs.get('overlays', None)\n","sub_path":"azure-mgmt-media/azure/mgmt/media/models/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"187286540","text":"import sys\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\n\nn = sys.argv[1]\n\ntrain_loss, train_acc = [], []\nval_loss, val_acc = [], []\ntest_loss, test_acc = [], []\nwith open('log/log'+n) as f:\n for line in f.readlines():\n line = line.strip().split()\n # print(line)\n if len(line)>1:\n if line[0] == '[Train]':\n train_loss.append(float(line[4]))\n train_acc.append(float(line[6]))\n elif line[0] == '[valid]':\n val_loss.append(float(line[4]))\n val_acc.append(float(line[6]))\n elif line[0] == '[test':\n test_loss.append(float(line[5]))\n test_acc.append(float(line[7]))\nval_acc_sort = sorted(val_acc, reverse=True)\nprint(max(val_acc), val_acc.index(max(val_acc)))\nplt.figure(figsize=(20,10))\n\nplt.subplots_adjust(left=0.05, right=0.95, top=0.9, bottom=0.1)\n\nplt.title('Phase Space Loss&Acc')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.xlim([0,3000])\nplt.ylim([0,1.2])\nplt.grid()\nplt.plot(train_loss, c='b', label='train_loss')\nplt.plot(test_loss, c='m', label='test_loss')\nplt.plot(val_loss, c='g', label='val_loss')\nplt.legend(loc='upper left')\n# plt.xlim([0,60])\nax = plt.twinx()\nax.set_ylim(0,1.2)\nax.set_ylabel('ACC')\nax.plot(train_acc, c='black', label='train_acc')\nax.plot(test_acc, c='y', label='test_acc')\nax.plot(val_acc, c='r', label='val_acc')\nplt.legend()\nplt.savefig('loss'+n)","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"507570715","text":"import random\nimport datetime\nimport numpy as np\n\nimport sc2\nfrom sc2 import Race, Difficulty\nfrom sc2.constants import *\nfrom sc2.position import Point2, Point3\nfrom sc2.unit import Unit\nfrom sc2.player import Bot, Computer\nfrom sc2.player import Human\nfrom sc2.ids.unit_typeid import UnitTypeId\nfrom sc2.ids.ability_id import AbilityId\nfrom sc2.data import Race, ActionResult, Attribute, race_worker, race_townhalls, race_gas\nfrom sc2.game_info import GameInfo\n\n\nclass BansheeBuild:\n\n def __init__(self):\n self.bansheeActions = []\n self.lift_flag = True\n self.flag_fac_land = True\n self.scv_count = 0\n self.supply_depot_count = 0\n self.reaper_count = 0\n self.banshee_count = 0\n \n\n async def execute_banshee_build(self):\n await self.train_scv()\n await self.build_supply_depots()\n await self.build_rax()\n await self.build_gas()\n await self.upgrade_to_oc()\n await self.scouting_reaper()\n await self.build_factory()\n await self.build_starport()\n await self.lift_buildings()\n await self.land_buildings()\n await self.research_cloak()\n await self.build_banshee()\n await self.scouting_reaper_micro()\n\n async def train_scv(self):\n '''Builds SCV's until first expansion is saturated.'''\n for cc in self.units(COMMANDCENTER).ready.noqueue:\n if self.units(SCV).amount < 17:\n if self.can_afford(SCV) and not self.already_pending(SCV):\n self.bansheeActions.append(cc.train(SCV))\n self.scv_count += 1\n #print(\"Current Game Time\", str(datetime.timedelta(seconds=round(self.time))))\n #print(\"Total SCVs built: \" + str(self.scv_count))\n\n if self.units(ORBITALCOMMAND).exists:\n for oc in self.units(ORBITALCOMMAND).ready.noqueue:\n if self.units(SCV).amount < 50:\n if self.can_afford(SCV) and not self.already_pending(SCV):\n self.bansheeActions.append(oc.train(SCV))\n self.scv_count += 1 \n #print(\"Total SCVs built: \" + str(self.scv_count))\n #print(\"Current Game Time\", str(datetime.timedelta(seconds=round(self.time))))\n async def build_supply_depots(self):\n '''Builds supply depots to ensure adequate supply_left.'''\n cc = self.townhalls.first\n ws = self.workers.gathering\n if ws:\n w = ws.furthest_to(ws.center)\n if self.supply_left <= 4 and self.can_afford(SUPPLYDEPOT) and not self.already_pending(SUPPLYDEPOT):\n if self.units(SUPPLYDEPOT).amount < 1:\n first_loc = cc.position.towards(self.game_info.map_center, 6)\n self.bansheeActions.append(w.build(SUPPLYDEPOT, first_loc))\n self.supply_depot_count += 1\n #print(\"Current Game Time\", str(datetime.timedelta(seconds=round(self.time))))\n #print(\"Total depots built: \"+ (str(self.supply_depot_count)))\n else:\n last_depot_loc = self.units(SUPPLYDEPOT)[-1].position\n next_loc = await self.find_placement(SUPPLYDEPOT, last_depot_loc, placement_step=1)\n #next_loc = self.units(SUPPLYDEPOT[-1].random.position, placement_step=4)\n self.bansheeActions.append(w.build(SUPPLYDEPOT, next_loc))\n self.supply_depot_count += 1\n #print(\"Current Game Time\", str(datetime.timedelta(seconds=round(self.time))))\n #print(\"Total depots built: \"+ (str(self.supply_depot_count)))\n\n async def build_rax(self):\n '''Builds 1st barracks, the pre-requisite tech for a factory.'''\n if self.can_afford(BARRACKS) and self.units(SUPPLYDEPOT).exists:\n if not self.already_pending(BARRACKS) and self.units(BARRACKS).amount < 1:\n cc = self.townhalls.first\n ws = self.workers.gathering\n if ws:\n w = ws.furthest_to(ws.center)\n start = self.game_info.player_start_location\n #rax_loc = self.units(SUPPLYDEPOT)[-1].position.towards(start, 3)\n rax_loc = cc.position.towards(self.game_info.map_center, 10)\n self.bansheeActions.append(w.build(BARRACKS, rax_loc))\n \n async def build_gas(self):\n '''Builds initial refineries in main base to reach 100% gas production on 1 base.'''\n for cc in self.units(COMMANDCENTER):\n if self.already_pending(BARRACKS):\n gas = self.state.vespene_geyser.closer_than(15.0, cc)\n for gas in gas:\n if self.can_afford(REFINERY) and not self.already_pending(REFINERY) and self.units(REFINERY).amount < 2:\n ws = self.workers.gathering\n if ws:\n w = ws.furthest_to(ws.center)\n #worker = self.select_build_worker(gas.position)\n self.bansheeActions.append(w.build(REFINERY, gas)) \n\n async def upgrade_to_oc(self):\n \"\"\"Controls upgrade to OC, mule deployment, and scan usage.\"\"\"\n if self.units(BARRACKS).exists and self.units(COMMANDCENTER).ready.exists:\n if not self.already_pending(ORBITALCOMMAND) and self.units(SCV).amount >= 17:\n if self.can_afford(ORBITALCOMMAND) and not self.already_pending(ORBITALCOMMAND):\n self.bansheeActions.append(self.units(COMMANDCENTER)[0](UPGRADETOORBITAL_ORBITALCOMMAND))\n pass\n #Mule drop\n for oc in self.units(ORBITALCOMMAND).ready:\n abilities = await self.get_available_abilities(oc)\n if CALLDOWNMULE_CALLDOWNMULE in abilities:\n mf = self.state.mineral_field.closest_to(oc)\n self.bansheeActions.append(oc(CALLDOWNMULE_CALLDOWNMULE, mf))\n\n async def scouting_reaper(self):\n '''Builds reaper to scout enemy base location/buildings.'''\n for rax in self.units(BARRACKS).ready.noqueue:\n if self.can_afford(REAPER) and not self.already_pending(REAPER) and self.reaper_count < 1:\n self.bansheeActions.append(rax.train(REAPER))\n self.reaper_count += 1\n print(\"Current Game Time\", str(datetime.timedelta(seconds=round(self.time))))\n print(\"Total Reapers made: \" + str(self.reaper_count))\n\n\n async def build_factory(self):\n '''Builds a factory, the pre-requisite tech for a starport.'''\n if not self.units(FACTORYFLYING):\n ws = self.workers.gathering\n if ws:\n w = ws.furthest_to(ws.center)\n if self.units(BARRACKS).exists and self.can_afford(FACTORY) and not self.already_pending(FACTORY):\n if self.units(FACTORY).amount < 1:\n for rax in self.units(BARRACKS):\n rax_loc = rax.position\n building_loc = await self.find_placement(FACTORY, rax_loc, placement_step=6)\n self.bansheeActions.append(w.build(FACTORY, building_loc))\n\n async def build_starport(self):\n '''Builds a starport. This production building is required to build a banshee and research cloak.'''\n '''Tech lab for starport is built on factory after starport starts building.'''\n if not self.units(STARPORTFLYING):\n ws = self.workers.gathering\n if ws:\n w = ws.furthest_to(ws.center)\n if self.units(FACTORY).exists and self.can_afford(STARPORT) and not self.already_pending(STARPORT):\n if self.units(STARPORT).amount < 1:\n fac_loc = self.units(FACTORY)[0].position\n building_loc = await self.find_placement(STARPORT, fac_loc, placement_step=2)\n fac = self.units(FACTORY)[0]\n self.bansheeActions.append(fac.build(FACTORYTECHLAB))\n self.bansheeActions.append(w.build(STARPORT, building_loc))\n\n async def lift_buildings(self):\n '''Lifts starport and factory up.'''\n #Lift factory and starport and swap with each other.\n if self.lift_flag:\n if self.units(STARPORT).ready:\n #added iff statement\n if self.units(FACTORY).exists:\n fac = self.units(FACTORY)[0]\n if fac:\n abilities = await self.get_available_abilities(fac)\n if LIFT_FACTORY in abilities:\n self.bansheeActions.append(fac(LIFT_FACTORY))\n starport = self.units(STARPORT)[0]\n if starport:\n abilities = await self.get_available_abilities(starport)\n if LIFT_STARPORT in abilities:\n self.bansheeActions.append(starport(LIFT_STARPORT))\n self.lift_flag = False\n\n async def land_buildings(self):\n '''Lands starport and factory where the tech lab is now on the starport.'''\n fac = self.units(FACTORYFLYING)\n starport = self.units(STARPORTFLYING)\n if fac:\n abilities = await self.get_available_abilities(fac[0])\n if LAND_FACTORY in abilities:\n if self.flag_fac_land:\n rax_loc = self.units(BARRACKS).first.position\n building_loc = await self.find_placement(FACTORY, rax_loc, placement_step=6)\n self.bansheeActions.append(fac[0](LAND_FACTORY, building_loc))\n self.flag_fac_land = False\n if self.units(TECHLAB).exists:\n addon_loc = self.units(TECHLAB).first.add_on_land_position\n if starport:\n abilities = await self.get_available_abilities(starport[0])\n if LAND_STARPORT in abilities:\n self.bansheeActions.append(starport[0](LAND_STARPORT, addon_loc))\n\n async def research_cloak(self):\n '''Starts the research for banshee cloak upgrade on starport tech lab.'''\n '''Have experienced a rare bug here where the starport will lift up, but cloak will finish researching. '''\n for sp in self.units(STARPORTTECHLAB).ready.noqueue:\n if not self.already_pending_upgrade(BANSHEECLOAK) and self.can_afford(BANSHEECLOAK):\n print(\"Current Game Time\", str(datetime.timedelta(seconds=round(self.time))), \": researching cloak\")\n self.bansheeActions.append(sp.research(BANSHEECLOAK))\n\n async def build_banshee(self):\n '''Builds banshees for harass.'''\n for sp in self.units(STARPORT).ready.noqueue:\n if self.can_afford(BANSHEE) and not self.already_pending(BANSHEE) and self.banshee_count < 3:\n self.bansheeActions.append(sp.train(BANSHEE))\n self.banshee_count += 1\n print(\"Current Game Time\", str(datetime.timedelta(seconds=round(self.time))))\n print(\"Total Banshees made: \" + str(self.banshee_count))\n\n async def scouting_reaper_micro(self):\n '''Function to control objectives of scouting reaper in the early game.'''\n for r in self.units(REAPER):\n if not self.known_enemy_units.not_flying.of_type([PROBE, SCV, DRONE]):\n #Initial reaper scout to find enemy location\n self.bansheeActions.append(r.move(self.enemy_start_locations[0]))\n else:\n fallback_loc = self.game_info.map_center.towards(self.start_location).position\n enemy = self.known_enemy_units.not_flying.exclude_type([ADEPTPHASESHIFT, DISRUPTORPHASED, EGG, LARVA])\n closest_enemy = enemy.closest_to(r)\n if r.health_percentage > 30/60:\n #Reaper will kite units while health_percentage is above half\n if r.position.distance_to(closest_enemy) < 5:\n if r.weapon_cooldown != 0:\n reaper_loc = r.position\n #worker_loc needs to be edited after Issue #8/30/18 is fixed\n worker_loc = self.find_enemy_locs()\n retreat_vec = self.reaper_aggressive_kite(reaper_loc, worker_loc, fallback_loc)\n retreat_loc = Point2(tuple(retreat_vec))\n self.bansheeActions.append(r.move(retreat_loc))\n else:\n #Reaper attacks closest enemy\n self.bansheeActions.append(r.attack(closest_enemy))\n else:\n #Retreat back to start location if reaper health_percentage falls below half.\n self.bansheeActions.append(r.move(fallback_loc))\n\n def find_enemy_locs(self):\n \"\"\"Returns enemy unit location of nearest enemy as highest_priority_locs.\"\"\"\n enemy = self.known_enemy_units.not_flying.exclude_type([ADEPTPHASESHIFT, DISRUPTORPHASED, EGG, LARVA])\n for r in self.units(REAPER):\n if enemy.not_structure.exists:\n highest_priority = enemy.of_type([PROBE, SCV, DRONE])\n print(\"WHAT DATA TYPE DOES THIS PRINT OUT???\")\n print(\"highest_priority: \")\n print(highest_priority)\n #highest_priority = enemy.not_structure.closest_to(r)\n #Position of highest_priority units\n highest_priority_pos = highest_priority.position\n print(\"highest_priority_pos: \")\n print(highest_priority_pos)\n return highest_priority_pos\n\n\n#Issue 8/30/18 - Turn this move_vec function into attraction vector towards workers, repulsion vector from units.\n#This will be a 'worker harassment' function to be implemented into reaper & banshee micro. \n def find_move_vec(self, unit_locs, *args):\n \"\"\"Finds movement vector for reaper.\"\"\"\n friendly_unit_locs = np.array(unit_locs)\n enemy_locs = np.array([0,0])\n for locs in args:\n #feeds in empty array if not recieving any *args inputs to prevent crashing\n vec_args = np.array([0,0])\n vec_args = np.array(locs)\n try:\n vec_args = np.subtract(vec_args, friendly_unit_locs)\n #vec_args = np.add(vec_args, -friendly_unit_locs)\n except TypeError:\n print(\"Crashing here\")\n #find vector length before normalizing.\n vec_len = np.sqrt(vec_args[0] ** 2 + vec_args[1] ** 2)\n norm_vec = np.divide(vec_args, vec_len) \n enemy_locs = np.add(enemy_locs, norm_vec) \n #added a /2 at the end of enemy_locs\n move_vec = friendly_unit_locs - (enemy_locs)/2\n return move_vec\n\n\n\n \n#Implement reaper and banshee micro\n","sub_path":"bansheebuild.py","file_name":"bansheebuild.py","file_ext":"py","file_size_in_byte":14908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"107252462","text":"# Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\n# Copyright 2021 Artificial Intelligence Center, Czech Techical University\n# Copied and adapted from OpenSpiel (https://github.com/deepmind/open_spiel)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Python Exploitability Descent example.\n\nThis example uses a neural network to approximate the policy. For a simple\ntabular example, see the unit tests for the exploitability_descent algorithm:\n\n```\n solver = exploitability_descent.Solver(game)\n with tf.Session() as session:\n for step in range(num_steps):\n nash_conv = solver.Step(session, learning_rate)\n```\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf\n\nfrom open_spiel.python.algorithms import exploitability_descent\nfrom open_spiel.python import simple_nets\nimport pyspiel\n\n# Temporarily disable TF2 until we update the code.\ntf.disable_v2_behavior()\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_integer(\"num_steps\", 100000, \"Number of iterations\")\nflags.DEFINE_string(\"game_name\", \"kuhn_poker\", \"Name of the game\")\nflags.DEFINE_float(\"init_lr\", 0.1, \"The initial learning rate\")\nflags.DEFINE_float(\"lr_scale\", 1., \"Learnign rate multiplier per timestep\")\nflags.DEFINE_float(\"regularizer_scale\", 0.001,\n \"Scale for L2 regularization of NN weights\")\nflags.DEFINE_integer(\"num_hidden\", 64, \"Hidden units.\")\nflags.DEFINE_integer(\"num_layers\", 1, \"Hidden layers.\")\nflags.DEFINE_integer(\"logfreq\", 100, \"logging frequency\")\nflags.DEFINE_string(\"project\", \"openspiel\", \"project name\")\nflags.DEFINE_boolean(\"no_wandb\", False, \"Disables Weights & Biases\")\n\n\ndef main(argv):\n del argv\n\n if not FLAGS.no_wandb:\n import wandb\n wandb.init(project=FLAGS.project)\n wandb.config.update(flags.FLAGS)\n wandb.config.update({\"solver\": \"nn ed\"})\n\n # Create the game to use, and a loss calculator for it\n logging.info(\"Loading %s\", FLAGS.game_name)\n\n if FLAGS.game_name == \"goofspiel\":\n game = pyspiel.load_game_as_turn_based(\n \"goofspiel\", {\n \"imp_info\": pyspiel.GameParameter(True),\n \"num_cards\": pyspiel.GameParameter(4),\n \"points_order\": pyspiel.GameParameter(\"descending\")\n })\n else:\n game = pyspiel.load_game(FLAGS.game_name)\n\n loss_calculator = exploitability_descent.LossCalculator(game)\n\n # Build the network\n num_hidden = FLAGS.num_hidden\n num_layers = FLAGS.num_layers\n layer = tf.constant(loss_calculator.tabular_policy.state_in, tf.float64)\n for _ in range(num_layers):\n regularizer = (tf.keras.regularizers.l2(l=FLAGS.regularizer_scale))\n layer = tf.layers.dense(\n layer, num_hidden, activation=tf.nn.relu, kernel_regularizer=regularizer)\n\n regularizer = (tf.keras.regularizers.l2(l=FLAGS.regularizer_scale))\n layer = tf.layers.dense(\n layer, game.num_distinct_actions(), kernel_regularizer=regularizer)\n tabular_policy = loss_calculator.masked_softmax(layer)\n\n # Build the loss - exploitability descent loss plus regularizer loss\n nash_conv, loss = loss_calculator.loss(tabular_policy)\n loss += tf.losses.get_regularization_loss()\n\n # Use a simple gradient descent optimizer\n learning_rate = tf.placeholder(tf.float64, (), name=\"learning_rate\")\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n #optimizer = tf.train.AdamOptimizer()\n optimizer_step = optimizer.minimize(loss)\n\n # Training loop\n with tf.train.MonitoredTrainingSession() as sess:\n for step in range(FLAGS.num_steps):\n nash_conv_value, _ = sess.run([nash_conv, optimizer_step],\n feed_dict={\n learning_rate: FLAGS.init_lr / np.sqrt(step * FLAGS.lr_scale + 1),\n })\n # Optionally log our progress\n if step % FLAGS.logfreq == 0:\n if not FLAGS.no_wandb:\n wandb.log({\"Iteration\": step, 'NashConv': nash_conv_value})\n\n logging.info(\"Iteration: {} NashConv: {}\".format(\n step, nash_conv_value))\n\n\nif __name__ == \"__main__\":\n app.run(main)\n","sub_path":"algorithms/nn_exp_descent.py","file_name":"nn_exp_descent.py","file_ext":"py","file_size_in_byte":4841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"25436477","text":"'''This program takes a integer number as input and prints sum of digits of that number'''\n\nNumber_str = input('Please enter a numeric number ')\n\ndef sum_of_number(x):\n\n if x.isdigit():\n length_of_Number = len(x)\n sum = 0\n for i in range(0,length_of_Number):\n sum = sum + int(x[i])\n print('The sum of the',x, ' is: ', sum)\n else:\n print('The number is not a numeric Number')\n\n\nsum_of_number(Number_str)\n","sub_path":"Basic Programs/Sum of digits of a number.py","file_name":"Sum of digits of a number.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"429697014","text":"#!/usr/bin/env python\n\nfrom os import listdir\nfrom os.path import isfile, join\nimport re\nimport json\n\nfrom bs4 import BeautifulSoup\n\n\"\"\"\nSetup\n-----\n\n# Install libraries\npip install beautifulsoup4\n\n# Download files\nwget -r -np -k --accept 'list_*.html' --reject 'feedbackno.html','feedbackyes.html' -nc https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html\n\"\"\"\n\n\ndef chomp(string):\n \"\"\"This chomp cleans up all white-space, not just at the ends\"\"\"\n string = str(string)\n response = string.replace(\"\\n\", \" \") # Convert line ends to spaces\n response = re.sub(\n \" [ ]*\", \" \", response\n ) # Truncate multiple spaces to single space\n response = re.sub(\"^[ ]*\", \"\", response) # Clean start\n return re.sub(\"[ ]*$\", \"\", response) # Clean end\n\n\nmypath = \"./docs.aws.amazon.com/IAM/latest/UserGuide/\"\nschema = []\n\n#for filename in ['list_amazoncloudwatchlogs.html']:\nfor filename in [f for f in listdir(mypath) if isfile(join(mypath, f))]:\n if not filename.startswith(\"list_\"):\n continue\n\n with open(mypath + filename, \"r\") as f:\n soup = BeautifulSoup(f.read(), \"html.parser\")\n main_content = soup.find(id=\"main-content\")\n if main_content is None:\n continue\n\n # Get service name\n title = main_content.find(\"h1\", class_=\"topictitle\")\n title = re.sub(\".*Actions, Resources, and Condition Keys for *\", \"\", str(title))\n title = title.replace(\"\", \"\")\n service_name = chomp(title)\n\n prefix = \"\"\n for c in main_content.find(\"h1\", class_=\"topictitle\").parent.children:\n if \"prefix\" in str(c):\n prefix = str(c)\n prefix = prefix.split('')[1]\n prefix = prefix.split(\"\")[0]\n break\n\n service_schema = {\n \"service_name\": service_name,\n \"prefix\": prefix,\n \"privileges\": [],\n \"resources\": [],\n \"conditions\": [],\n }\n\n tables = main_content.find_all(\"div\", class_=\"table-contents\")\n\n for table in tables:\n # There can be 3 tables, the actions table, an ARN table, and a condition key table\n # Example: https://docs.aws.amazon.com/IAM/latest/UserGuide/list_awssecuritytokenservice.html\n if \"Actions\" not in [str(x) for x in table.find_all(\"th\")]:\n continue\n\n rows = table.find_all(\"tr\")\n row_number = 0\n while row_number < len(rows):\n row = rows[row_number]\n\n cells = row.find_all(\"td\")\n if len(cells) == 0:\n # Skip the header row, which has th, not td cells\n row_number += 1\n continue\n\n if len(cells) != 6:\n # Sometimes the privilege might span multiple rows.\n # Example: amazonroute53-DisassociateVPCFromHostedZone\n # We should be handling this, but if we are not, then bail\n raise Exception(\"Unexpected format in {}: {}\".format(prefix, row))\n\n # See if this cell spans multiple rows\n rowspan = 1\n if \"rowspan\" in cells[0].attrs:\n rowspan = int(cells[0].attrs[\"rowspan\"])\n\n priv = \"\"\n # Get the privilege\n for link in cells[0].find_all(\"a\"):\n if \"href\" not in link.attrs:\n # Skip the
    tags\n continue\n priv = chomp(link.text)\n if priv == \"\":\n priv = chomp(cells[0].text)\n\n description = chomp(cells[1].text)\n access_level = chomp(cells[2].text)\n\n resource_types = []\n resource_cell = 3\n\n while rowspan > 0:\n if len(cells) == 3 or len(cells) == 6:\n # ec2:RunInstances contains a few \"scenarios\" which start in the\n # description field, len(cells) is 5.\n # I'm ignoring these as I don't know how to handle them.\n # These include things like \"EC2-Classic-InstanceStore\" and\n # \"EC2-VPC-InstanceStore-Subnet\"\n\n resource_type = chomp(cells[resource_cell].text)\n\n condition_keys_element = cells[resource_cell + 1]\n condition_keys = []\n if condition_keys_element.text != \"\":\n for key_element in condition_keys_element.find_all(\"p\"):\n condition_keys.append(chomp(key_element.text))\n\n dependent_actions_element = cells[resource_cell + 2]\n dependent_actions = []\n if dependent_actions_element.text != \"\":\n for action_element in dependent_actions_element.find_all(\n \"p\"\n ):\n dependent_actions.append(chomp(action_element.text))\n resource_types.append(\n {\n \"resource_type\": resource_type,\n \"condition_keys\": condition_keys,\n \"dependent_actions\": dependent_actions,\n }\n )\n rowspan -= 1\n if rowspan > 0:\n row_number += 1\n resource_cell = 0\n row = rows[row_number]\n cells = row.find_all(\"td\")\n\n if \"[permission only]\" in priv:\n priv = priv.split(\" \")[0]\n\n privilege_schema = {\n \"privilege\": priv,\n \"description\": description,\n \"access_level\": access_level,\n \"resource_types\": resource_types,\n }\n\n service_schema[\"privileges\"].append(privilege_schema)\n row_number += 1\n\n # Get resource table\n for table in tables:\n if \"Resource Types\" not in [str(x) for x in table.find_all(\"th\")]:\n continue\n\n rows = table.find_all(\"tr\")\n for row in rows:\n cells = row.find_all(\"td\")\n\n if len(cells) == 0:\n # Skip the header row, which has th, not td cells\n continue\n\n if len(cells) != 3:\n raise Exception(\n \"Unexpected number of resource cells {} in {}\".format(\n len(cells), filename\n )\n )\n\n resource = chomp(cells[0].text)\n\n arn = chomp(cells[1].text)\n conditions = []\n for condition in cells[2].find_all(\"p\"):\n conditions.append(chomp(condition.text))\n\n service_schema[\"resources\"].append(\n {\"resource\": resource, \"arn\": arn, \"condition_keys\": conditions}\n )\n\n # Get condition keys table\n for table in tables:\n if \"Condition Keys\" not in [\n str(x) for x in table.find_all(\"th\")\n ] or \"Type\" not in [str(x) for x in table.find_all(\"th\")]:\n continue\n\n rows = table.find_all(\"tr\")\n for row in rows:\n cells = row.find_all(\"td\")\n\n if len(cells) == 0:\n # Skip the header row, which has th, not td cells\n continue\n\n if len(cells) != 3:\n raise Exception(\n \"Unexpected number of condition cells {} in {}\".format(\n len(cells), filename\n )\n )\n\n condition = chomp(cells[0].text)\n description = chomp(cells[1].text)\n value_type = chomp(cells[2].text)\n\n service_schema[\"conditions\"].append(\n {\n \"condition\": condition,\n \"description\": description,\n \"type\": value_type,\n }\n )\n schema.append(service_schema)\n\nprint(json.dumps(schema, indent=2, sort_keys=True))\n","sub_path":"utils/update_iam_data.py","file_name":"update_iam_data.py","file_ext":"py","file_size_in_byte":8553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"198612708","text":"from dataset import *\r\nfrom representations import *\r\nfrom classify import *\r\n\r\n\r\n#######################################################################################################################\r\nlimit_num = 80\r\n#######################################################################################################################\r\n\r\n# 20Newsgroup\r\nNews_dataset = read20news_limited(limit_num) # get train & test set\r\n# d_set[0] --> everything for train set\r\n# d_set[1] --> everything for test set\r\n# d_set[*][0] --> labels of * set\r\n# d_set[*][1] --> texts of * set\r\ntrain_text = News_dataset[0][1] # store text of train set\r\ntrain_labels = News_dataset[0][0]\r\ntest_text = News_dataset[1][1] # store text of train set\r\ntest_labels = News_dataset[1][0]\r\n\r\n\r\n# make train, test representations\r\nnews_voc = voc_20newsgroup(train_text, limit_num) # load of vocabulary to use it in BoW representations\r\ntrain_txt_bow = BOW(news_voc, train_text)[0]\r\ntest_txt_bow = BOW(news_voc, test_text)[0]\r\n\r\n# classification\r\ndata_name = \"Newsgroup\"\r\nsim_measure = \"cosine\"\r\ntrain_vectors_dict = dataset_dictionary(train_labels, train_txt_bow, limit_num, data_name)[0]\r\ntest_label_predictions = averaged_representative_classification(train_vectors_dict, test_txt_bow, sim_measure)\r\n\r\n# evaluation\r\npredicted_labels = []\r\nfor lista in test_label_predictions[1]:\r\n predicted_labels.append(lista[0])\r\n\r\naccuracy = sklearn.metrics.accuracy_score(test_labels, predicted_labels)\r\nprint(\"accuracy score: \"+accuracy)\r\n\r\nF1 = sklearn.metrics.f1_score(test_labels, predicted_labels)\r\nprint(\"F1 score: \"+F1)","sub_path":"master_thesis/classification_workflow.py","file_name":"classification_workflow.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"477699945","text":"import torch.nn as nn\n\nfrom .functional import *\nimport params as P\n\n\n# TODO: Implement Hebbian update directly on gpu.\n# TODO: Add other functionalities to Hebbian module\n# - Recurrent computation and lca\n# - Lateral decorrelation\n# - Trisigma wta\n\n\n\nclass Competitive(nn.Module):\n\t# Types of random abstention strategies\n\tHARD_RAND_ABST = 'hard_rand_abst'\n\tSOFT_RAND_ABST = 'soft_rand_abst'\n\t\n\t# Types of LFB kernels\n\tLFB_GAUSS = 'lfb_gauss'\n\tLFB_DoG = 'lfb_DoG'\n\tLFB_EXP = 'lfb_exp'\n\tLFB_DoE = 'lfb_DoE'\n\t\n\t\n\tdef __init__(self,\n\t out_size=None,\n\t competitive_act=None,\n\t k=1,\n\t lrn_k=False,\n\t random_abstention=None,\n\t y_gating=False,\n\t lfb_y_gating=False,\n\t lfb_value=None,\n\t lfb_sigma=None,\n\t lfb_tau=1000):\n\t\tsuper(Competitive, self).__init__()\n\t\t# Enable/disable features such as random abstention, competitive learning, lateral feedback\n\t\tself.competitive_act = competitive_act\n\t\tself.competitive = self.competitive_act is not None\n\t\tself.k = k if not lrn_k else nn.Parameter(torch.tensor(float(k)), requires_grad=True)\n\t\tif self.competitive and random_abstention not in [None, self.SOFT_RAND_ABST, self.HARD_RAND_ABST]:\n\t\t\traise ValueError(\"Invalid value for argument random_abstention: \" + str(random_abstention))\n\t\tself.random_abstention = random_abstention\n\t\tself.random_abstention_on = self.competitive and self.random_abstention is not None\n\t\tself.y_gating = y_gating\n\t\tself.lfb_y_gating = lfb_y_gating\n\t\tself.lfb_on = lfb_value is not None and lfb_value != 0\n\t\tself.lfb_value = lfb_value\n\t\t\n\t\t# Initialize output size, which is necessary only when random abstention or lfb is enabled\n\t\tself.out_size = None\n\t\tself.out_channels = None\n\t\tif self.random_abstention_on or self.lfb_on:\n\t\t\tif out_size is None:\n\t\t\t\traise ValueError(\"Invalid value for argument out_size: \" + str(out_size) + \" when random abstention or lfb is provided\")\n\t\t\tif hasattr(out_size, '__len__') and len(out_size) > 3:\n\t\t\t\traise ValueError(\"Too many dimensions for argument out_size: \" + str(out_size) + \" (up to 3 allowed)\")\n\t\t\tout_size_list = [out_size] if not hasattr(out_size, '__len__') else out_size\n\t\t\tself.out_size = torch.tensor(out_size_list)\n\t\t\tself.out_channels = self.out_size.prod().item()\n\t\t\n\t\t# Set parameters related to the lateral feedback feature\n\t\tif self.lfb_on:\n\t\t\t# Prepare the variables to generate the kernel that will be used to apply lateral feedback\n\t\t\tmap_radius = (self.out_size - 1) // 2\n\t\t\tlfb_sigma = map_radius.max().item() if lfb_sigma is None else lfb_sigma\n\t\t\tx = torch.abs(torch.arange(0, self.out_size[0].item()) - map_radius[0])\n\t\t\tfor i in range(1, self.out_size.size(0)):\n\t\t\t\tx_new = torch.abs(torch.arange(0, self.out_size[i].item()) - map_radius[i])\n\t\t\t\tfor j in range(i): x_new = x_new.unsqueeze(j)\n\t\t\t\tx = torch.max(x.unsqueeze(-1), x_new) # max gives L_infinity distance, sum would give L_1 distance, root_p(sum x^p) for L_p\n\t\t\t# Store the kernel that will be used to apply lateral feedback in a registered buffer\n\t\t\tif lfb_value == self.LFB_EXP or lfb_value == self.LFB_DoE:\n\t\t\t\tself.register_buffer('lfb_kernel', torch.exp(-x.float() / lfb_sigma))\n\t\t\tif lfb_value == self.LFB_GAUSS or lfb_value == self.LFB_DoG:\n\t\t\t\tself.register_buffer('lfb_kernel', torch.exp(-x.pow(2).float() / (2 * (lfb_sigma ** 2))))\n\t\t\telse: # lfb_value is a number\n\t\t\t\tif type(lfb_value) is not int and type(lfb_value) is not float:\n\t\t\t\t\traise ValueError(\"Invalid value for argument lfb_value: \" + str(lfb_value))\n\t\t\t\tself.register_buffer('lfb_kernel', (x == 0).float())\n\t\t\t\tx[x == 0] = lfb_value\n\t\t\t# Padding that will pad the inputs before applying the lfb kernel\n\t\t\tpad_pre = map_radius.unsqueeze(1)\n\t\t\tpad_post = (self.out_size - 1 - map_radius).unsqueeze(1)\n\t\t\tself.pad = list(torch.cat((pad_pre, pad_post), dim=1).flip(0).view(-1))\n\t\t\t# LFB kernel shrinking parameter\n\t\t\tself.gamma = torch.exp(torch.log(torch.tensor(lfb_sigma).float()) / lfb_tau).item() if lfb_tau is not None else None\n\t\t\tif (lfb_value == self.LFB_GAUSS or lfb_value == self.LFB_DoG) and self.gamma is not None: self.gamma = self.gamma ** 2\n\t\telse: self.register_buffer('lfb_kernel', None)\n\t\t\n\t\t# Init variables for statistics collection\n\t\tif self.random_abstention_on:\n\t\t\tself.register_buffer('victories_count', torch.zeros(self.out_channels).float())\n\t\telse: self.register_buffer('victories_count', None)\n\t\n\tdef forward(self, y, t=None):\n\t\t# Random abstention\n\t\tscores = y\n\t\tif self.random_abstention_on:\n\t\t\tabst_prob = self.victories_count / (self.victories_count.max() + y.size(0) / y.size(1)).clamp(1)\n\t\t\tif self.random_abstention == self.SOFT_RAND_ABST: scores = y * abst_prob.unsqueeze(0)\n\t\t\tif self.random_abstention == self.HARD_RAND_ABST: scores = y * (torch.rand_like(abst_prob, device=y.device) >= abst_prob).float().unsqueeze(0)\n\t\t\n\t\t# Competition. The returned winner_mask is a bitmap telling where a neuron won and where one lost.\n\t\tif self.competitive:\n\t\t\tif t is not None: scores = scores * t # When competition is on, teacher signal is used to drive competition, if provided\n\t\t\twinner_mask = self.competitive_act(scores, self.k)\n\t\t\tif self.random_abstention_on and self.training: # Update statistics if using random abstension\n\t\t\t\twinner_mask_sum = winner_mask.sum(0) # Number of inputs over which a neuron won\n\t\t\t\tself.victories_count += winner_mask_sum\n\t\t\t\tself.victories_count -= self.victories_count.min().item()\n\t\telse: winner_mask = torch.ones_like(y, device=y.device)\n\t\t\n\t\t# Apply winner_mask gating by the output if necessary\n\t\tif self.y_gating: winner_mask = winner_mask * y\n\t\t\n\t\t# Lateral feedback\n\t\tif self.lfb_on:\n\t\t\tlfb_kernel = self.lfb_kernel\n\t\t\tif self.lfb_value == self.LFB_DoG or self.lfb_value == self.LFB_DoE: lfb_kernel = 2 * lfb_kernel - lfb_kernel.pow(0.5) # Difference of Gaussians/Exponentials (mexican hat shaped function)\n\t\t\tlfb_in = F.pad(winner_mask.view(-1, *self.out_size), self.pad)\n\t\t\tif self.out_size.size(0) == 1: lfb_out = torch.conv1d(lfb_in.unsqueeze(1), lfb_kernel.unsqueeze(0).unsqueeze(1))\n\t\t\telif self.out_size.size(0) == 2: lfb_out = torch.conv2d(lfb_in.unsqueeze(1), lfb_kernel.unsqueeze(0).unsqueeze(1))\n\t\t\telse: lfb_out = torch.conv3d(lfb_in.unsqueeze(1), lfb_kernel.unsqueeze(0).unsqueeze(1))\n\t\t\tlfb_out = lfb_out.clamp(-1, 1).view_as(y)\n\t\telse: lfb_out = winner_mask\n\t\t\n\t\t# Apply lfb gating by output if necessary\n\t\tif self.lfb_y_gating: lfb_out = lfb_out * y\n\t\t\n\t\t# When competition is off, the teacher signal is used to gate the lfb output, if provided\n\t\tif not self.competitive and t is not None: lfb_out = lfb_out * t\n\t\t\n\t\t# LFB kernel shrinking schedule\n\t\tif self.lfb_on and self.gamma is not None and self.training: self.lfb_kernel = self.lfb_kernel.pow(self.gamma)\n\t\t\n\t\treturn lfb_out\n\n# This module represents a layer of convolutional neurons that are trained with Hebbian algorithms\nclass HebbianConv2d(nn.Module):\n\t# s = sim(w, x), y = act(s) -- e.g.: s = w^T x, y = f(s)\n\t\n\t# Types of weight initialization schemes\n\tINIT_BASE = 'init_base'\n\tINIT_NORM = 'init_norm'\n\t\n\t# Type of gating term\n\tGATE_BASE = 'gate_base' # r = lfb\n\tGATE_HEBB = 'gate_hebb' # r = lfb * y\n\tGATE_DIFF = 'gate_diff' # r = lfb - y\n\tGATE_SMAX = 'gate_smx' # r = lfb - softmax(y)\n\t\n\t# Type of reconstruction scheme\n\tREC_QNT = 'rec_qnt' # reconstr = w\n\tREC_QNT_SGN = 'rec_qnt_sgn' # reconstr = sign(lfb) * w\n\tREC_LIN_CMB = 'rec_lin_cmb' # reconstr = sum_i r_i w_i\n\t\n\t# Type of update step\n\tUPD_RECONSTR = 'upd_reconstr' # delta_w = alpha * r * (x - reconstr)\n\tUPD_ICA = 'upd_ica' # delta w_i = r_i (w_i - y_i rs^T W) # NB: the term r acts as gating\n\tUPD_HICA = 'upd_hica' # delta w_i = r_i (w_i - y_i sum_(k=1..i) rs_k w_k)\n\tUPD_ICA_NRM = 'upd_ica_nrm' # delta w_i = = r_i (w_i w_i^T - I) y_i rs^T W\n\tUPD_HICA_NRM = 'upd_hica_nrm' # delta w_i = r_i (w_i w_i^T - I) y_i sum_(k=1..i) rs_k w_k\n\t\n\t# ICA rule\n\t# Delta W = (I - f(s) s^T) W\n\t# Delta W_i = sum_k (I - f(s) s^T)_ik W_k = sum_k (delta_ik - f(s_i) s_k) W_k\n\t# = delta_ii W_i - f(s_i) sum_k s_k W_k = W_i - f(s_i) sum_k s_k W_k = W_i - f(s_i) s^T W\n\t# ICA with normalization: estimate sigma dinamically\n\t# f(s) = (log(p(s/sigma)))' = (1/sigma) * ( p'(s/sigma)/p(s/sigma) ) = (1/sigma) * phi(s/sigma)\n\t# where phi(s) = p'(s)/p(s)\n\t# rewrite: Delta W = (I - f(s) s^T) W = (I - (1/sigma^2) * sigma^2 f(s) s^T) W -\n\t# [Note that Delta W ~ (sigma^2 - g(s) s^T) W -- where g(s) = sigma^s f(s)]\n\t# Delta W = (I - f(s) s^T) W\n\t# Delta W_i = sum_k (I - f(s) s^T)_ik W_k = sum_k (delta_ik - f(s_i) s_k) W_k\n\t# = W_i - f(s_i) sum_k s_k W_k\n\t# Normalization\n\t# w_new = (w + eta Delta w) / |w + eta Delta w|^2\n\t# |w + eta Delta w|^2 = w^2 (1 + eta w^T Delta w w^-2) + o(eta^2)\n\t# |w + eta Delta w|^-2 = w^-2 (1 - eta w^T Delta w) + o(eta^2)\n\t# w_new = (w + eta Delta w)(w^-2 (1 - eta w^T Delta w) + o(eta^2))\n\t# = (w + eta (Delta w - (w^t Delta w) w) w^-2 + o(eta^2)\n\t# Assuming w normalized --> w^-2 = 1\n\t# w_new = w + eta (Delta w - (w^T Delta w) w) + o(eta^2)\n\t# Delta w corrected = Delta w - (w^T Delta w) w --> x y - y^2 w for oja\n\t# In case of adaptive variance ICA\n\t# Delta w_i corrected = w_i - f(s_i) sum_k s_k w_k - w_i(w_i^2 - f(s_i) sum_k s_k (w_k w_i^T)) ** NB: w_i is row vector\n\t# = w_i - w_i -f(s_i) sum_k s_k (w_k - w_i (w_k w_i^T)) = -f(s_i) sum_(k!=i) s_k (w_k - w_i (w_k w_i^T))\n\t# = -f(s_i) sum_k s_k (w_k - w_k w_i^T w_i) = -f(s_i) sum_k s_k w_k (I - w_i^T w_i) = -f(s_i) s^T W (I - w_i w_i^T)\n\t# = f(s_i) s^T W w_i^T w_i - f(s_i) s^T W = f(s_i) s^T W (w_i^T w_i - I)\n\t\n\t# Type of update reduction scheme\n\tRED_AVG = 'red_avg' # average\n\tRED_W_AVG = 'red_w_avg' # weighted average\n\t\n\t# Types of bias initialization schemes\n\tBIAS_INIT_ZEROS = 'bias_init_zeros'\n\tBIAS_INIT_VAR_ONES = 'bias_init_var_ones'\n\tBIAS_INIT_VAR_DIMS = 'bias_init_var_dims'\n\t\n\t# Types of bias update scheme\n\tBIAS_MODE_BASE = 'bias_mode_base'\n\tBIAS_MODE_HEBB = 'bias_mode_hebb'\n\tBIAS_MODE_VALUE = 'bias_mode_value'\n\t\n\t# Activation inversion modes - activation inversion transforms nonlinearities for some neuron into x - the nonlinearity.\n\t# This can be used during ica training to have different nonlinearities for super-gaussian and sub-gaussian variables.\n\tACT_COMPLEMENT_INIT_RAND = 'act_complement_init_rand'\n\tACT_COMPLEMENT_INIT_SPLT = 'act_complement_init_splt'\n\tACT_COMPLEMENT_INIT_ALT = 'act_complement_init_alt'\n\t\n\t# Types of activation inversion adaptive update scheme\n\tACT_COMPLEMENT_ADAPT_KRT = 'act_complement_adapt_krt'\n\tACT_COMPLEMENT_ADAPT_STB = 'act_complement_adapt_stb'\n\t\n\t\n\tdef __init__(self,\n\t in_channels,\n\t out_channels,\n\t kernel_size,\n\t weight_init=INIT_BASE,\n\t lrn_sim=kernel_mult2d,\n\t lrn_act=identity,\n\t lrn_cmp=None,\n\t out_sim=kernel_mult2d,\n\t out_act=identity,\n\t out_cmp=None,\n\t act_complement_init=None,\n\t act_complement_ratio=0,\n\t act_complement_adapt=None,\n\t act_complement_grp=False,\n\t act_complement_affine=False,\n\t gating=GATE_HEBB,\n\t upd_rule=UPD_RECONSTR,\n\t y_prime_gating=False,\n\t reconstruction=REC_LIN_CMB,\n\t reduction=RED_AVG,\n\t bias_init=None,\n\t bias_mode=None,\n\t bias_target=0,\n\t bias_gating=None,\n\t var_adaptive=False,\n\t var_affine=False,\n\t lamb=1.,\n\t conserve_var=True,\n\t alpha=1.,\n\t alpha_bias=1.,\n\t beta=.1):\n\t\tsuper(HebbianConv2d, self).__init__()\n\t\t# Init weights\n\t\tif weight_init not in [self.INIT_BASE, self.INIT_NORM]:\n\t\t\traise ValueError(\"Invalid value for argument weight_init: \" + str(weight_init))\n\t\tif hasattr(kernel_size, '__len__') and len(kernel_size) == 1: kernel_size = kernel_size[0]\n\t\tif not hasattr(kernel_size, '__len__'): kernel_size = [kernel_size, kernel_size]\n\t\tstdv = 1 / (in_channels * kernel_size[0] * kernel_size[1]) ** 0.5\n\t\tself.weight = nn.Parameter(torch.empty(out_channels, in_channels, kernel_size[0], kernel_size[1]), requires_grad=True)\n\t\tnn.init.uniform_(self.weight, -stdv, stdv) # Same initialization used by default pytorch conv modules (the one from the paper \"Efficient Backprop, LeCun\")\n\t\tif weight_init == self.INIT_NORM: self.weight = self.weight / self.weight.view(self.weight.size(0), -1).norm(dim=1, p=2).view(-1, 1, 1, 1) # normalize weights\n\t\t\n\t\t# Init bias\n\t\tif bias_mode not in [None, self.BIAS_MODE_BASE, self.BIAS_MODE_HEBB, self.BIAS_MODE_VALUE]:\n\t\t\traise ValueError(\"Invalid value for argument bias_mode: \" + str(bias_mode))\n\t\tif bias_init not in [None, self.BIAS_INIT_ZEROS, self.BIAS_INIT_VAR_ONES, self.BIAS_INIT_VAR_DIMS] and bias_mode != self.BIAS_MODE_VALUE:\n\t\t\traise ValueError(\"Invalid value for argument bias_init: \" + str(bias_init) + \" when argument bias_mode is: \" + str(bias_mode))\n\t\tif bias_gating not in [None, self.GATE_BASE, self.GATE_HEBB, self.GATE_DIFF, self.GATE_SMAX]:\n\t\t\traise ValueError(\"Invalid value for argument bias_gating: \" + str(bias_gating))\n\t\tbias = None\n\t\tif bias_init == self.BIAS_INIT_ZEROS: bias = torch.zeros(out_channels).float()\n\t\tif bias_init == self.BIAS_INIT_VAR_ONES: bias = torch.ones(out_channels).float()\n\t\tif bias_init == self.BIAS_INIT_VAR_DIMS: bias = utils.shape2size(tuple(self.weight[0].size())) * torch.ones(out_channels).float()\n\t\tself.bias_mode = bias_mode\n\t\tif self.bias_mode == self.BIAS_MODE_VALUE: self.bias = bias_init\n\t\telse: self.bias = nn.Parameter(bias, requires_grad=True) if bias is not None else self.register_parameter('bias', None)\n\t\tself.bias_target = bias_target\n\t\tself.bias_gating = bias_gating\n\t\tself.using_adaptive_bias = self.bias is not None and self.bias_mode is not None and self.bias_mode != self.BIAS_MODE_VALUE\n\t\t\n\t\t# Set similarity and activation functions\n\t\tself.lrn_sim = lrn_sim\n\t\tself.lrn_act = lrn_act\n\t\tself.lrn_cmp = lrn_cmp if lrn_cmp is not None else Competitive(lfb_y_gating=True) # None gives identity mapping\n\t\tif self.lrn_cmp.out_channels is not None and self.lrn_cmp.out_channels != out_channels:\n\t\t\traise ValueError(\"Argument out_channels: \" + str(out_channels) + \" and lrn_cmp.out_channels: \" + str(self.lrn_cmp.out_channels) + \" must match\")\n\t\tself.out_sim = out_sim\n\t\tself.out_act = out_act\n\t\tself.out_cmp = out_cmp if out_cmp is not None else Competitive(lfb_y_gating=True) # None gives identity mapping\n\t\tif self.out_cmp.out_channels is not None and self.out_cmp.out_channels != out_channels:\n\t\t\traise ValueError(\"Argument out_channels: \" + str(out_channels) + \" and out_cmp.out_channels: \" + str(self.out_cmp.out_channels) + \" must match\")\n\t\tif act_complement_init not in [None, self.ACT_COMPLEMENT_INIT_RAND, self.ACT_COMPLEMENT_INIT_SPLT, self.ACT_COMPLEMENT_INIT_ALT]:\n\t\t\traise ValueError(\"Invalid value for argument act_complement_init: \" + str(act_complement_init))\n\t\tif act_complement_adapt not in [None, self.ACT_COMPLEMENT_ADAPT_STB, self.ACT_COMPLEMENT_ADAPT_KRT]:\n\t\t\traise ValueError(\"Invalid value for argument act_complement_adapt: \" + str(act_complement_adapt))\n\t\tif act_complement_ratio > 1.0:\n\t\t\traise ValueError(\"Invalid value for argument act_complement_ration: \" + str(act_complement_ratio) + \" (required float < 1.0)\")\n\t\tkappa = None\n\t\tself.act_complement_from_idx = out_channels\n\t\tif act_complement_init == self.ACT_COMPLEMENT_INIT_RAND:\n\t\t\tkappa = (torch.rand(out_channels) < act_complement_ratio).float()\n\t\tif act_complement_init == self.ACT_COMPLEMENT_INIT_SPLT:\n\t\t\tkappa = torch.zeros(out_channels).float()\n\t\t\tself.act_complement_from_idx = out_channels - int(round(act_complement_ratio * out_channels))\n\t\t\tif self.act_complement_from_idx < out_channels: kappa[self.act_complement_from_idx:] = 1.\n\t\tif act_complement_init == self.ACT_COMPLEMENT_INIT_ALT:\n\t\t\tif act_complement_ratio <= 0.5:\n\t\t\t\tkappa = torch.zeros(out_channels).float()\n\t\t\t\tif act_complement_ratio > 0:\n\t\t\t\t\tn = int(round(1/act_complement_ratio))\n\t\t\t\t\tidx = [n * (i + 1) - 1 for i in range(out_channels//n)]\n\t\t\t\t\tkappa[idx] = 1.\n\t\t\telse:\n\t\t\t\tkappa = torch.ones(out_channels).float()\n\t\t\t\tif act_complement_ratio < 1:\n\t\t\t\t\tn = int(round(1/(1 - act_complement_ratio)))\n\t\t\t\t\tidx = [n * i for i in range(out_channels//n)]\n\t\t\t\t\tkappa[idx] = 0.\n\t\tself.register_buffer('kappa', kappa)\n\t\tself.act_complement_adapt = act_complement_adapt\n\t\tself.register_buffer('m2', torch.ones(out_channels).float() if self.act_complement_adapt is not None else None)\n\t\tself.register_buffer('m4', (3 * torch.ones(out_channels).float()) if self.act_complement_adapt is not None else None)\n\t\tself.register_buffer('rho', (3 * torch.ones(out_channels).float()) if self.act_complement_adapt == self.ACT_COMPLEMENT_ADAPT_STB else None)\n\t\tself.act_complement_grp = act_complement_grp and (self.act_complement_from_idx < out_channels) and (self.act_complement_adapt is None)\n\t\tself.kappa_affine = act_complement_affine\n\t\tself.kappa_trainable = nn.Parameter(torch.zeros(out_channels).float(), requires_grad=True) if self.kappa_affine else self.register_parameter('kappa_trainable', None)\n\t\t\n\t\t# Learning rule\n\t\tself.teacher_signal = None # Teacher signal for supervised training\n\t\tif gating not in [self.GATE_BASE, self.GATE_HEBB, self.GATE_DIFF, self.GATE_SMAX]:\n\t\t\traise ValueError(\"Invalid value for argument gating: \" + str(gating))\n\t\tself.gating = gating\n\t\tif reconstruction not in [None, self.REC_QNT, self.REC_QNT_SGN, self.REC_LIN_CMB]:\n\t\t\traise ValueError(\"Invalid value for argument reconstruction: \" + str(reconstruction))\n\t\tself.reconstruction = reconstruction\n\t\tif upd_rule not in [self.UPD_RECONSTR, self.UPD_ICA, self.UPD_HICA, self.UPD_ICA_NRM, self.UPD_HICA_NRM]:\n\t\t\traise ValueError(\"Invalid value for argument upd_rule: \" + str(upd_rule))\n\t\tself.upd_rule = upd_rule\n\t\tself.y_prime_gating = y_prime_gating\n\t\tif reduction not in [self.RED_AVG, self.RED_W_AVG]:\n\t\t\traise ValueError(\"Invalid value for argument reductioin: \" + str(reduction))\n\t\tself.reduction = reduction\n\t\t\n\t\t# Alpha is the constant which determines the trade off between global and local updates\n\t\tself.alpha = alpha\n\t\tself.alpha_bias = alpha_bias\n\t\t\n\t\t# Adaptive variance normalization\n\t\tself.beta = beta # Beta is the time constant for running stats tracking\n\t\tself.var_adaptive = var_adaptive\n\t\tself.var_nrm = nn.BatchNorm2d(out_channels, momentum=self.beta, affine=var_affine) if self.var_adaptive else None\n\t\tself.lamb = lamb # lambda is an additional spread parameter for nonlinearities. It determines, for instance, the sparsity measure when a shrinking/clamping nonlinearity is used\n\t\tself.conserve_var = conserve_var\n\t\t\n\t\t# Variables where the weight updates are stored\n\t\tself.delta_w = None\n\t\tself.delta_bias = None\n\t\n\tdef set_teacher_signal(self, t):\n\t\tself.teacher_signal = t\n\t\t\n\tdef forward(self, x):\n\t\tif self.training: self.compute_update(x)\n\t\treturn self.out_cmp(self.apply_act(self.out_sim(x, self.weight, self.bias)))\n\t\n\tdef apply_act(self, s, lrn=False, cpl=True):\n\t\ts_bar = s\n\t\t# Normalize before activation function, if necessary\n\t\tif self.var_adaptive:\n\t\t\tif lrn: _ = self.var_nrm(s) # Track stats\n\t\t\ts_bar = (s - self.var_nrm.running_mean.view(1, -1, 1, 1)) / ((self.var_nrm.running_var.view(1, -1, 1, 1) + self.var_nrm.eps) ** 0.5)\n\t\t\tif self.var_nrm.affine: s_bar = s_bar * self.var_nrm.weight.view(1, -1, 1, 1) + self.var_nrm.bias.view(1, -1, 1, 1)\n\t\t\ts_bar = s_bar + self.var_nrm.running_mean.view(1, -1, 1, 1) # Restore original mean and normalize variance only\n\t\t# Scale width before activation function\n\t\ts_bar = s_bar / self.lamb\n\t\t\n\t\t# Apply activation function\n\t\ty = self.lrn_act(s_bar) if lrn else self.out_act(s_bar)\n\t\t# Apply activation complement, if necessary\n\t\tif cpl:\n\t\t\tkappa = self.kappa.view(1, -1, 1, 1) if self.kappa is not None else 0.\n\t\t\tif self.kappa_affine: kappa = kappa + self.kappa_trainable.view(1, -1, 1, 1)\n\t\t\ty = kappa * s_bar - (2 * kappa - 1) * y\n\t\t\n\t\t# Restore original variance information, if necessary\n\t\tif self.conserve_var and self.var_adaptive: y = y * (self.var_nrm.running_var.view(1, -1, 1, 1) + self.var_nrm.eps)**0.5\n\t\t\n\t\treturn y\n\t\n\tdef compute_update(self, x):\n\t\t# Store previous gradient computation flag and disable gradient computation before computing update\n\t\tprev_grad_enabled = torch.is_grad_enabled()\n\t\ttorch.set_grad_enabled(False)\n\t\t\n\t\tif self.alpha != 0 or (self.alpha_bias != 0 and self.using_adaptive_bias) or self.var_adaptive or self.act_complement_adapt is not None:\n\t\t\t# Compute activation states for the layer: s, y, y'\n\t\t\ts = self.lrn_sim(x, self.weight, self.bias) # Compute similarity metric between inputs and weights\n\t\t\t# Compute y and also y' if y' gating is required\n\t\t\tif self.y_prime_gating:\n\t\t\t\ttorch.set_grad_enabled(True) # Gradient enabling to compute derivative y'\n\t\t\t\ts.requires_grad = True\n\t\t\ty = self.apply_act(s, lrn=True)\n\t\t\ty_prime = torch.ones_like(s)\n\t\t\tif self.y_prime_gating:\n\t\t\t\ty.backward(torch.ones_like(y), retain_graph=prev_grad_enabled)\n\t\t\t\ty_prime = s.grad.clone().detach()\n\t\t\t\ts.grad = None\n\t\t\t\ttorch.set_grad_enabled(False)\n\t\t\t\n\t\t\t# Track higher order moments\n\t\t\tif self.act_complement_adapt == self.ACT_COMPLEMENT_ADAPT_KRT:\n\t\t\t\t# Update statistics and determine kappa\n\t\t\t\tself.m2 = (1 - self.beta) * self.m2 + self.beta * s.pow(2).mean(dim=(0, 2, 3))\n\t\t\t\tself.m4 = (1 - self.beta) * self.m4 + self.beta * s.pow(4).mean(dim=(0, 2, 3))\n\t\t\t\tself.kappa = ((self.m4 - 3 * self.m2 ** 2) < 0).float()\n\t\t\tif self.act_complement_adapt == self.ACT_COMPLEMENT_ADAPT_STB:\n\t\t\t\t# compute y' uncomplemented, which is needed for this type of adaptation\n\t\t\t\ttorch.set_grad_enabled(True) # Gradient enabling to compute derivative y' uncomplemented\n\t\t\t\ts.requires_grad = True\n\t\t\t\ty_uncpl = self.apply_act(s, cpl=False)\n\t\t\t\ty_uncpl.backward(torch.ones_like(y_uncpl), retain_graph=prev_grad_enabled)\n\t\t\t\ty_uncpl_prime = s.grad.clone().detach()\n\t\t\t\ts.grad = None\n\t\t\t\ttorch.set_grad_enabled(False)\n\t\t\t\t# Update statistics and determine kappa\n\t\t\t\tself.m2 = (1 - self.beta) * self.m2 + self.beta * s.pow(2).mean(dim=(0, 2, 3))\n\t\t\t\tself.m4 = (1 - self.beta) * self.m4 + self.beta * (s * y_uncpl).mean(dim=(0, 2, 3))\n\t\t\t\tself.rho = (1 - self.beta) * self.rho + self.beta * y_uncpl_prime.mean(dim=(0, 2, 3))\n\t\t\t\tself.kappa = ((self.m4 - self.m2 * self.rho) < 0).float()\n\t\t\t\n\t\t\tif self.alpha != 0 or (self.alpha_bias != 0 and self.using_adaptive_bias):\n\t\t\t\t# Prepare the necessary tensors and set them in the correct shape\n\t\t\t\tt = self.teacher_signal\n\t\t\t\tif t is not None: t = t.unsqueeze(2).unsqueeze(3) * torch.ones_like(s, device=s.device)\n\t\t\t\ts = s.permute(0, 2, 3, 1).contiguous().view(-1, self.weight.size(0))\n\t\t\t\ty = y.permute(0, 2, 3, 1).contiguous().view(-1, self.weight.size(0))\n\t\t\t\ty_prime = y_prime.permute(0, 2, 3, 1).contiguous().view(-1, self.weight.size(0))\n\t\t\t\tif t is not None: t = t.permute(0, 2, 3, 1).contiguous().view(-1, self.weight.size(0))\n\t\t\t\tx_unf = unfold_map2d(x, self.weight.size(2), self.weight.size(3))\n\t\t\t\tx_unf = x_unf.permute(0, 2, 3, 1, 4).contiguous().view(s.size(0), 1, -1)\n\t\t\t\t\n\t\t\t\t# Run competition\n\t\t\t\tlfb_out = self.lrn_cmp(y, t)\n\t\t\t\t\n\t\t\t\tif self.alpha != 0:\n\t\t\t\t\t# Compute step modulation coefficient\n\t\t\t\t\tr = lfb_out # GATE_BASE\n\t\t\t\t\tif self.gating == self.GATE_HEBB: r = r * y\n\t\t\t\t\tif self.gating == self.GATE_DIFF: r = r - y\n\t\t\t\t\tif self.gating == self.GATE_SMAX: r = r - torch.softmax(y, dim=1)\n\t\t\t\t\tif self.y_prime_gating: r = y_prime * r\n\t\t\t\t\tr_abs = r.abs()\n\t\t\t\t\tr_sign = r.sign()\n\t\t\t\t\n\t\t\t\t\t# Compute delta_w (serialized version for computation of delta_w using less memory)\n\t\t\t\t\tdelta_w_avg = torch.zeros_like(self.weight.view(self.weight.size(0), -1))\n\t\t\t\t\tfor grp in range(2): # repeat the computation for the two neuron groups using complementary nonlinearities\n\t\t\t\t\t\tif grp == 1 and not self.act_complement_grp: break\n\t\t\t\t\t\tgrp_slice = slice(self.weight.size(0))\n\t\t\t\t\t\tif self.act_complement_grp: grp_slice = slice(self.act_complement_from_idx) if grp == 0 else slice(self.act_complement_from_idx, self.weight.size(0))\n\t\t\t\t\t\tw = self.weight.view(1, self.weight.size(0), -1)[:, grp_slice, :]\n\t\t\t\t\t\tx_bar = None\n\t\t\t\t\t\tsw = None\n\t\t\t\t\t\tif self.upd_rule == self.UPD_ICA or self.upd_rule == self.UPD_ICA_NRM: # Computation of s^T * W for ICA\n\t\t\t\t\t\t\tfor i in range((w.size(1) // P.HEBB_UPD_GRP) + (1 if w.size(1) % P.HEBB_UPD_GRP != 0 else 0)):\n\t\t\t\t\t\t\t\tstart = i * P.HEBB_UPD_GRP\n\t\t\t\t\t\t\t\tend = min((i + 1) * P.HEBB_UPD_GRP, w.size(1))\n\t\t\t\t\t\t\t\tw_i = w[:, start:end, :]\n\t\t\t\t\t\t\t\ts_i = s[:, grp_slice].unsqueeze(2)[:, start:end, :]\n\t\t\t\t\t\t\t\tr_i = r[:, grp_slice].unsqueeze(2)[:, start:end, :]\n\t\t\t\t\t\t\t\tsw = (r_i * s_i * w_i).sum(dim=1, keepdim=True) + (sw if sw is not None else 0.)\n\t\t\t\t\t\tfor i in range((w.size(1) // P.HEBB_UPD_GRP) + (1 if w.size(1) % P.HEBB_UPD_GRP != 0 else 0)):\n\t\t\t\t\t\t\tstart = i * P.HEBB_UPD_GRP\n\t\t\t\t\t\t\tend = min((i + 1) * P.HEBB_UPD_GRP, w.size(1))\n\t\t\t\t\t\t\tw_i = w[:, start:end, :]\n\t\t\t\t\t\t\ts_i = s[:, grp_slice].unsqueeze(2)[:, start:end, :]\n\t\t\t\t\t\t\ty_i = y[:, grp_slice].unsqueeze(2)[:, start:end, :]\n\t\t\t\t\t\t\tr_i = r[:, grp_slice].unsqueeze(2)[:, start:end, :]\n\t\t\t\t\t\t\tr_abs_i = r_abs[:, grp_slice].unsqueeze(2)[:, start:end, :]\n\t\t\t\t\t\t\tr_sign_i = r_sign[:, grp_slice].unsqueeze(2)[:, start:end, :]\n\t\t\t\t\t\t\t# Compute update step\n\t\t\t\t\t\t\tdelta_w_i = torch.zeros_like(w_i)\n\t\t\t\t\t\t\tif self.upd_rule == self.UPD_RECONSTR:\n\t\t\t\t\t\t\t\t# Compute reconstr based on the type of reconstruction\n\t\t\t\t\t\t\t\tif self.reconstruction == self.REC_QNT: x_bar = w_i\n\t\t\t\t\t\t\t\tif self.reconstruction == self.REC_QNT_SGN: x_bar = r_sign_i * w_i\n\t\t\t\t\t\t\t\tif self.reconstruction == self.REC_LIN_CMB: x_bar = torch.cumsum(r_i * w_i, dim=1) + (x_bar[:, -1, :].unsqueeze(1) if x_bar is not None else 0.)\n\t\t\t\t\t\t\t\tx_bar = x_bar if x_bar is not None else 0.\n\t\t\t\t\t\t\t\tdelta_w_i = r_i * (x_unf - x_bar)\n\t\t\t\t\t\t\tif self.upd_rule in [self.UPD_ICA, self.UPD_HICA, self.UPD_ICA_NRM, self.UPD_HICA_NRM]:\n\t\t\t\t\t\t\t\tif self.upd_rule == self.UPD_HICA or self.upd_rule == self.UPD_HICA_NRM:\n\t\t\t\t\t\t\t\t\tsw = torch.cumsum((r_i * s_i) * w_i, dim=1) + (sw[:, -1, :].unsqueeze(1) if sw is not None else 0.)\n\t\t\t\t\t\t\t\tysw = (y_i * sw)\n\t\t\t\t\t\t\t\tif self.upd_rule == self.UPD_ICA or self.upd_rule == self.UPD_HICA:\n\t\t\t\t\t\t\t\t\tdelta_w_i = r_i * (w_i - ysw)\n\t\t\t\t\t\t\t\tif self.upd_rule == self.UPD_ICA_NRM or self.upd_rule == self.UPD_HICA_NRM:\n\t\t\t\t\t\t\t\t\tdelta_w_i = r_i * ((ysw * w_i).sum(dim=2, keepdim=True) * w_i - ysw)\n\t\t\t\t\t\t\t# Since we use batches of inputs, we need to aggregate the different update steps of each kernel in a unique\n\t\t\t\t\t\t\t# update. We do this by taking the weighted average of the steps, the weights being the r coefficients that\n\t\t\t\t\t\t\t# determine the length of each step (RED_W_AVG), or the unweighted average (RED_AVG).\n\t\t\t\t\t\t\tif self.reduction == self.RED_W_AVG:\n\t\t\t\t\t\t\t\tr_sum = r_abs_i.sum(0)\n\t\t\t\t\t\t\t\tr_sum = r_sum + (r_sum == 0).float() # Prevent divisions by zero\n\t\t\t\t\t\t\t\tdelta_w_avg[grp_slice, :][start:end, :] = (delta_w_i * r_abs_i).sum(0) / r_sum\n\t\t\t\t\t\t\telse: # RED_AVG\n\t\t\t\t\t\t\t\tdelta_w_avg[grp_slice, :][start:end, :] = delta_w_i.mean(dim=0)\n\t\t\t\t\t\n\t\t\t\t\t# Apply delta\n\t\t\t\t\tself.delta_w = delta_w_avg.view_as(self.weight)\n\t\t\t\t\n\t\t\t\tif self.alpha_bias != 0 and self.using_adaptive_bias:\n\t\t\t\t\t# Compute step modulation coefficient\n\t\t\t\t\tr = lfb_out # GATE_BASE\n\t\t\t\t\tif self.bias_gating == self.GATE_HEBB: r = r * y\n\t\t\t\t\tif self.bias_gating == self.GATE_DIFF: r = r - y\n\t\t\t\t\tif self.bias_gating == self.GATE_SMAX: r = r - torch.softmax(y, dim=1)\n\t\t\t\t\tif self.bias_gating is None: r = 1.\n\t\t\t\t\tif self.y_prime_gating: r = y_prime * r\n\t\t\t\t\tr_abs = r.abs()\n\t\t\t\t\tr_sign = r.sign()\n\t\t\t\t\t\n\t\t\t\t\t# Compute Delta bias\n\t\t\t\t\tdelta_bias = torch.zeros_like(self.bias).unsqueeze(0)\n\t\t\t\t\tdelta_bias_avg = torch.zeros_like(self.bias)\n\t\t\t\t\tif self.bias_mode == self.BIAS_MODE_BASE:\n\t\t\t\t\t\tdelta_bias = r\n\t\t\t\t\tif self.bias_mode == self.BIAS_MODE_HEBB:\n\t\t\t\t\t\tdelta_bias = r * -(s - self.bias_target)\n\t\t\t\t\t# Aggregate bias updates by averaging\n\t\t\t\t\tif self.reduction == self.RED_W_AVG:\n\t\t\t\t\t\tr_sum = r_abs.sum(0)\n\t\t\t\t\t\tr_sum = r_sum + (r_sum == 0).float() # Prevent divisions by zero\n\t\t\t\t\t\tdelta_bias_avg = (delta_bias * r_abs).sum(0) / r_sum\n\t\t\t\t\telse: # RED_AVG\n\t\t\t\t\t\tdelta_bias_avg = delta_bias.mean(dim=0)\n\t\t\t\t\t\n\t\t\t\t\t# Apply delta\n\t\t\t\t\tself.delta_bias = delta_bias_avg.view_as(self.bias)\n\t\t\n\t\t# Restore gradient computation\n\t\ttorch.set_grad_enabled(prev_grad_enabled)\n\t\t\n\t# Takes local update from self.delta_w and self.delta_bias, global update from self.weight.grad and self.bias.grad,\n\t# and combines them using the parameter alpha.\n\tdef local_update(self):\n\t\tif self.alpha != 0:\n\t\t\t# NB: self.delta_w has a minus sign in front because the optimizer will take update steps in the opposite direction.\n\t\t\tself.weight.grad = self.alpha * (-self.delta_w) + (1 - self.alpha) * (self.weight.grad if self.weight.grad is not None else 0.)\n\t\tif self.alpha_bias != 0 and self.using_adaptive_bias:\n\t\t\t# NB: self.delta_bias has a minus sign in front because the optimizer will take update steps in the opposite direction.\n\t\t\tself.bias.grad = self.alpha_bias * (-self.delta_bias) + (1 - self.alpha_bias) * (self.bias.grad if self.bias.grad is not None else 0.)\n\n","sub_path":"hebb/hebb.py","file_name":"hebb.py","file_ext":"py","file_size_in_byte":28977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"533344976","text":"#!/usr/bin/python\n\n\"\"\" \n Starter code for exploring the Enron dataset (emails + finances);\n loads up the dataset (pickled dict of dicts).\n\n The dataset has the form:\n enron_data[\"LASTNAME FIRSTNAME MIDDLEINITIAL\"] = { features_dict }\n\n {features_dict} is a dictionary of features associated with that person.\n You should explore features_dict as part of the mini-project,\n but here's an example to get you started:\n\n enron_data[\"SKILLING JEFFREY K\"][\"bonus\"] = 5600000\n \n\"\"\"\n\nimport pickle\n\ndataset = open(\"test_dump.pkl\", \"rb\")\nenron_data = pickle.load(dataset)\n\nfirst_key = next(iter(enron_data))\n\nprint(first_key)\nprint(enron_data[first_key])\n# print(len(enron_data[first_key]))\n\n# label = \"poi\"\n# x = 0\n\n# for i in enron_data:\n# current_key = next(iter(enron_data))\n# if current_key['poi'] == True:\n# x += 1\n\n# for key in enron_data.items():\n# for value in key:\n# print(value[2])\n# # if value == label:\n# # if value[] == True:\n# # x += 1\n\n# # This gives you only the keys.\n# for key in enron_data:\n# print(key)\n\n# # This prints the content of each key, which is a dictionary\n# for key in enron_data:\n# print(key)\n# print(enron_data[key])\n\n# # This loop prints all of the values in\n# for key in enron_data:\n# for label in enron_data[key]:\n# print(enron_data[key][label])\n\n# print(enron_data[\"PRENTICE JAMES\"][\"total_stock_value\"])\n# print(enron_data[\"SKILLING JEFFREY K\"][\"exercised_stock_options\"])\n\n# top = [\"SKILLING JEFFREY K\", \"FASTOW ANDREW S\", \"LAY KENNETH L\"]\n# total = \"total_payments\"\n#\n# for i in top:\n# print(i, \"=\", enron_data[i][total])\n\npoi = \"poi\"\nlabel = \"total_payments\"\nx = 0\ny = 0\nz = 0\n\nfor key in enron_data:\n if enron_data[key][poi] == True:\n if enron_data[key][label] == \"NaN\":\n print(key, \":\", enron_data[key][label])\n x += 1\n z += 1\n y += 1\n\nprint()\nprint(x/len(enron_data), \"%\")\nprint(y)\nprint(z)\nprint(x)\n","sub_path":"datasets_questions/explore_enron_data.py","file_name":"explore_enron_data.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"243311672","text":"#!/usr/bin/python\nimport json\nimport urllib2\npackages = []\n\n\ndef sizeof_fmt(num, suffix='B'):\n # stolen from stackoverflow, provided by Fred Cirera.\n for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:\n if abs(num) < 1024.0:\n return \"%3.1f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.1f%s%s\" % (num, 'Yi', suffix)\n\n\ndef wget(url):\n filename = url.split('/')[-1]\n stream = urllib2.urlopen(url)\n info = stream.info()\n fileSize = info.getheaders(\"Content-Length\")\n friendlySize = sizeof_fmt(int(fileSize[0]))\n with open(filename, 'wb') as output:\n print(\"Downloading {0} ({1})\".format(filename, friendlySize))\n output.write(stream.read())\n return\n\n\nwith open(\"list.json\", 'r') as f:\n parsed_list = json.loads(f.read())\n\nfor i in parsed_list:\n packages.append(i)\n\nfor package in packages:\n wget(parsed_list[package][\"url\"])\n","sub_path":"packrat.py","file_name":"packrat.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"551349971","text":"\"\"\"Backend producing QASM\"\"\"\n# Copyright © 2019-2021 HQS Quantum Simulations GmbH. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software distributed under the License\n# is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n# or implied. See the License for the specific language governing permissions and limitations under\n# the License.\nfrom qoqo import Circuit\nimport os\nfrom typing import (\n Optional,\n Dict,\n Iterable,\n List,\n)\nfrom qoqo_qasm import qasm_call_circuit\n\n\nclass QasmBackend(object):\n r\"\"\"Backend to qoqo that produces QASM output which can be imported.\n\n This backend takes a qoqo circuit to be run on a certain device and returns a QASM file\n containing the translated circuit. The circuit itself is translated using the qoqo_qasm\n interface. In this backend, the initialization sets up the relevant parameters and the run\n function calls the QASM interface and writes the QASM file, which is saved to be used by the\n user on whatever platform they see fit. QASM input is widely supported on various quantum\n computing platforms.\n \"\"\"\n\n def __init__(self,\n number_qubits: int = 1,\n folder_name: str = '',\n qureg_name: str = 'q',\n qubit_names: Optional[Dict[int, str]] = None) -> None:\n \"\"\"Initialize QASM Backend\n\n Args:\n number_qubits: The number of qubits to use\n folder_name: The name of the folder that is prepended to all filenames in run function\n qureg_name: The name of the qubit register\n qubit_names: The dictionary of qubit names to translate the circuit to\n\n \"\"\"\n self.name = \"qasm\"\n self.number_qubits = number_qubits\n self.folder_name = folder_name\n self.qureg_name = qureg_name\n self.qubit_names = qubit_names\n\n def run_circuit(self, circuit: Circuit, filename: str = 'default_qasm_backend_output',\n overwrite: bool = False, use_symbolic: bool = False) -> None:\n \"\"\"Turn the circuit into QASM and save to file\n\n Args:\n circuit: Circuit to be run\n filename: The name of the file the QASM text is saved to\n overwrite: Whether to overwrite file if it already exists, defaulting to False\n use_symbolic: Whether to use symbolic parameters, defaulting to False\n\n Raises:\n FileExistsError: Qasm file already exists, aborting.\n Use overwrite=True to replace the existing file.\n\n \"\"\"\n filename = os.path.join(os.path.abspath(os.path.expanduser(self.folder_name)),\n filename + '.qasm')\n filedir = os.path.dirname(os.path.expanduser(filename))\n os.makedirs(filedir, exist_ok=True)\n if os.path.isfile(filename) and overwrite is not True:\n raise FileExistsError(\n \"Python file {} already exists, aborting. User overwrite to replace\".format(\n filename))\n output_lines = list()\n output_lines.append('OPENQASM 2.0;\\n')\n output_lines.append('include \"qelib1.inc\";\\n\\n')\n\n qasm_qubit_names: Dict[int, str] = dict()\n for ci in range(self.number_qubits):\n if self.qubit_names is None:\n qasm_qubit_names[ci] = '{}[{}]'.format(self.qureg_name, ci)\n else:\n qasm_qubit_names[ci] = '{}[{}]'.format(self.qureg_name, self.qubit_names[ci])\n output_lines.append('qreg {}[{}];\\n'.format(self.qureg_name, self.number_qubits))\n\n if use_symbolic:\n circuit_lines, self.symbolic_hash_lib = qasm_call_circuit(\n circuit=circuit,\n number_qubits=self.number_qubits,\n qubit_names=qasm_qubit_names,\n use_symbolic=True)\n else:\n circuit_lines, _ = qasm_call_circuit(\n circuit=circuit,\n number_qubits=self.number_qubits,\n qubit_names=qasm_qubit_names,\n use_symbolic=False)\n self.circuit = circuit_lines\n\n output_lines.extend(\n _append_newlines(\n circuit_lines\n )\n )\n with open(filename, 'w') as fo:\n fo.writelines(output_lines)\n\n\ndef _append_newlines(seq: Iterable[str]) -> List[str]:\n return_seq = list()\n for s in seq:\n if s is not None:\n if s not in [\"\", \";\"]:\n return_seq.append(s + '\\n')\n return return_seq\n","sub_path":"qoqo_qasm/qoqo_qasm/backend/qasm_backend.py","file_name":"qasm_backend.py","file_ext":"py","file_size_in_byte":4819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"15981583","text":"from elasticsearch_dsl import Search\n# from dsl_demo.model import Test_index # 如果这里导入了配置,就可以使用model的连接配置\n # s = Search(using=\"default\").query(\"match\", name=\"wangjun\")\n\nfrom elasticsearch import Elasticsearch\nclient = Elasticsearch(\"192.168.59.138:9200\")\n\ndef search_dsl():\n \"\"\"基本查询\"\"\"\n s = Search(using=client,index=\"website\").query(\"match\", title=\"SECOND 一\")\n \"\"\"\n title=\"SECOND 一\" 能匹配到带有secod 或带有一的数据\n 匹配title 中含有关键字second的数据,不区分大小写,但是必须是一个单词或一个汉字\n \"\"\"\n # s = Search(using=client).query(\"match\", title=\"blo\") # 匹配title 中含有关键字My 的数据,中间有空格不生效\n\n de = Search(using=client,index=\"website\").query(\"match\", title=\"二\").delete() #删除匹配的数据\n\n print(de)\n print(s.to_dict())\n for i in s:\n print(i.title)\n print(i.text)\n print(i.date)\n # print(i.pk)\n # print(i.name)\n\n\nif __name__ == '__main__':\n search_dsl()\n","sub_path":"dsl_demo/search_dsl.py","file_name":"search_dsl.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"23666569","text":"import pandas as pd\nimport datetime\nimport yfinance as yf\nimport requests\nimport matplotlib.pyplot as plt\nimport io\nimport keras\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom keras.models import Sequential\nfrom keras.models import load_model\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom sklearn.model_selection import KFold, cross_val_score\n\nfrom sklearn.preprocessing import MinMaxScaler\n\nsymbol_url = \"https://pkgstore.datahub.io/core/nasdaq-listings/nasdaq-listed_csv/data/7665719fb51081ba0bd834fde71ce822/nasdaq-listed_csv.csv\"\ns = requests.get(symbol_url).content\nsymbols = pd.read_csv(io.StringIO(s.decode('utf-8')))['Symbol'].tolist()\nprint(\"Stock Symbols\", symbols)\n\n# Comment this to get the all-symbols\nsymbols = [\"AAL\", \"AAPL\", \"DAL\", \"FB\", \"AMZN\", \"TSLA\", \"MSFT\", \"CRM\"]\nstock_data = pd.DataFrame()\nstart = datetime.datetime(2020, 1, 1)\nend = datetime.datetime(2020, 11, 28)\n\n\ndef sma(data, n):\n sma_values = pd.Series(data['Close'].rolling(n).mean(), name='Sma')\n data = data.join(sma_values)\n return data\n\n\ndef ewma(data, n):\n ema = pd.Series(data['Close'].ewm(span=n, min_periods=n - 1).mean(),\n name='Ewma_' + str(n))\n data = data.join(ema)\n return data\n\n\ndef ATR(data, n):\n df = data.copy()\n df['H_L'] = abs(data['High']-data['Low'])\n df['H_PC'] = abs(data['High']-data['Close'].shift(1))\n df['L_PC'] = abs(data['Low']-data['Close'].shift(1))\n TR = df[['H_L', 'H_PC', 'L_PC']].max(axis=1,skipna=False)\n atr_value = TR.rolling(n).mean()\n atr_value = round(atr_value[-1], 2)\n atr_value = pd.Series(atr_value, name='ATR')\n data = data.join(atr_value)\n return data\n\n\ndef CAGR(data, n):\n p_change = data['Close'].pct_change()\n cum_return = (1 + p_change).cumprod()\n n = len(data) / 252\n cagr = (cum_return[-1]) ** (1 / n) - 1\n cagr = pd.Series(cagr, name='CAGR')\n data = data.join(cagr)\n return data\n\n\ndef volatility(data):\n daily_ret = pd.Series(data['Close'].pct_change(), name='daily_ret')\n data = data.join(daily_ret)\n return data\n\n\ndef cci(data, n):\n TP = (data['High'] + data['Low'] + data['Close']) / 3\n cci_values = pd.Series((TP - TP.rolling(n).mean()) / (0.015 * TP.rolling(n).std()),\n name='Cci')\n data = data.join(cci_values)\n return data\n\n\nfor symbol in symbols:\n try:\n s = []\n n = 15\n s = yf.download(symbol, start=start, end=end)\n if s is not None and len(s) > 0:\n s['Name'] = symbol\n\n # Getting simple moving average\n s = sma(s, n)\n s = s.dropna()\n\n # Exponentially weighted moving average\n s = ewma(s, n)\n s = s.dropna()\n\n # Commodity Channel Index\n s = cci(s, n)\n s = s.dropna()\n\n s = ATR(s, 3)\n\n # volatility\n s = volatility(s)\n\n # volatility\n s = CAGR(s, 3)\n\n stock_data = stock_data.append(s, sort=False)\n except Exception:\n None\n\nprint(stock_data)\n\n\ndef get_model():\n model = Sequential()\n n_input_layer = 3\n model.add(Dense(n_input_layer, input_dim=n_input_layer,\n kernel_initializer='normal',\n activation='relu'))\n model.add(Dense(1, kernel_initializer='normal'))\n model.compile(loss='mean_squared_error', optimizer='adam')\n return model\n\n\nX = stock_data[[\"Sma\", \"Ewma_15\", \"Cci\"]]\nY = stock_data['Close']\n\nestimator = KerasRegressor(build_fn=get_model, epochs=100, batch_size=5, verbose=0)\nkfold = KFold(n_splits=10)\nresults = cross_val_score(estimator, X, Y, cv=kfold)\nprint(\"MSE: %.2f\" % (results.mean()))\n","sub_path":"final_project/scripts/project code.py","file_name":"project code.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"249792934","text":"# -*- coding: utf-8 -*-\n\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom twitdobau.handlers import twit, group, user, friend\n\n\"\"\" Configuração de rotas \"\"\"\napplication = webapp.WSGIApplication([\n # HANDLERS\n (r'/', twit.MainPageAccess),\n (r'/callback', twit.CallbackPage),\n (r'/list', twit.ListPage),\n (r'/update', twit.UpdateTimeline),\n (r'/timeline', twit.ListTimeline),\n # GRUPOS\n (r'/group', group.ListPage),\n (r'/group/list', group.ListPage),\n (r'/group/add', group.AdicionarPage),\n (r'/group/save', group.SalvarGrupoPage),\n (r'/group/edit', group.EditarPage),\n (r'/group/delete', group.DeletarPage),\n # USU��RIO\n (r'/profile', user.ProfilePage),\n # AMIGOS\n (r'/friend', friend.ListPage),\n (r'/friend/list', friend.ListPage),\n (r'/friend/add', friend.AdicionarPage),\n (r'/friend/save', friend.SalvarAmigoPage),\n (r'/friend/edit', friend.EditarPage),\n (r'/friend/delete', friend.DeletarPage)\n], debug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"159139789","text":"#!/usr/bin/env python3\nfrom datetime import datetime, timedelta\nfrom functools import wraps\n\nlasthour2017 = datetime(2017, 6, 20, 19, 11, 12, 926763)\nlasthour2018 = datetime(2018, 10, 1, 19, 11, 12, 926763)\n\n\ndef exetime(lasthour2017, lasthour2018):\n def decorator(func):\n @wraps(func)\n def wrapped_func(*args, **kwargs):\n print('== Start ==')\n lasthour2017_str = str(lasthour2017)\n lasthour2018_str = str(lasthour2018)\n nowtime = datetime.now()\n lasthour2017_new = datetime.strptime(lasthour2017_str, '%Y-%m-%d %H:%M:%S.%f')\n lasthour2018_new = datetime.strptime(lasthour2018_str, '%Y-%m-%d %H:%M:%S.%f')\n if nowtime - lasthour2017_new > timedelta(seconds=1) and nowtime - lasthour2018_new < timedelta(seconds=1):\n print('in time!')\n return func(*args, **kwargs)\n return wrapped_func\n return decorator\n\n\n@exetime(lasthour2017, lasthour2018)\ndef time():\n print(\"== Finish ==\")\n\n\nif __name__ == '__main__':\n time()\n19\n","sub_path":"time_decorator.py","file_name":"time_decorator.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"305751041","text":"def leia_int(msg):\r\n \"\"\"\r\n :param msg: A função informa se a mensagem passada é um valor inteiro, porém não consegui fazê-la declarar que é um\r\n numero real(1.2 por exemplo)\r\n Se a mensagem for uma string, o laço se repetirá até receber um número ''inteiro''\r\n :return:\r\n \"\"\"\r\n estado = False\r\n valor = 0\r\n while True:\r\n d = str(input(msg))\r\n if d.isnumeric():\r\n valor = int(d)\r\n estado = True\r\n break\r\n else:\r\n print(f'Erro, {d}, não é um valor inteiro, é um {type(d)}')\r\n return valor\r\n\r\n\r\nd = leia_int('\\nDigite algo: ')\r\nprint(f'{d}, é um valor inteiro')","sub_path":"Desafio104.py","file_name":"Desafio104.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"539392281","text":"#Задача 7. Вариант 1.\n#Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы большее количество баллов за меньшее количество попыток.\nimport random\nguessesTaken=0\nprint('Компьютер загадал имя одного из трех мушкетеров - товарищей д`Артаньяна. \\nТвоя цель отгадать имя загаданного мушкетера.')\nmusketry=random.choice([\"Атос\", \"Партос\", \"Арамис\"])\nwhile guessesTaken < 2:\n print('Загаданное имя мушкетера: ')\n guess=input()\n guessesTaken=guessesTaken+1\n if guess!=musketry:\n print('Неверно!')\n if guess==musketry:\n break\nif guess==musketry:\n print('Верно! Число использованных попыток: ', guessesTaken)\n if guessesTaken==1:\n print('Количество заработанных баллов: ', 100)\n if guessesTaken==2:\n print('Количество заработанных баллов: ', 50)\nif guess!=musketry:\n print('Попытки кончились')\n print('Вы не набрали баллов')\ninput('Нажмите Enter')\n#Abdrahmanova G. I.\n#28.03.2016","sub_path":"BITs/2014/Abdrahmanova_G_I/task_7_1.py","file_name":"task_7_1.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"499624326","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport re\nimport os\nurl_name = \"https://www.yellowpages.com/search?search_terms=restaurants&geo_location_terms=San%20Diego%2C%20CA&page=\"\ns_ranges = int(input('Enter starting range:'))\nl_ranges = int(input('Enter last range:'))\nids = (s_ranges-1)*30\nif s_ranges == 0:\n ids = 0\nfor k in range(s_ranges, l_ranges):\n url_changed_name = url_name+str(k)\n r = requests.get(url_changed_name)\n soup = BeautifulSoup(r.content, 'html5lib')\n aid = []\n names = []\n reviews = []\n addresses = []\n phones = []\n years = []\n web_links = []\n emails = []\n general_infos = []\n times = []\n payments = []\n categories = []\n neighborhoods = []\n banners = []\n services = []\n other_infos = []\n for all in soup.findAll('div', attrs={'class': 'search-results organic'}):\n all_links = all.findAll('a', attrs={'class': 'business-name'})\n for link in all_links:\n lnk = link.get(\"href\")\n lnk = \"https://www.yellowpages.com\"+lnk\n r = requests.get(lnk)\n soup = BeautifulSoup(r.content, 'html5lib')\n name = soup.find('div', attrs={'class': 'sales-info'})\n names.append(name.text)\n for c in soup.findAll('a', attrs={'class': 'yp-ratings'}):\n review = c.find('span', attrs={'class': 'count'})\n if review is not None:\n review = review.text\n else:\n review = \"(0 Review)\"\n reviews.append(review)\n address = soup.find('h2', attrs={'class': 'address'})\n addresses.append(address.text)\n phone = soup.find('p', attrs={'class': 'phone'})\n phones.append(phone.text)\n c = soup.find('div', attrs={'class': 'years-in-business'})\n if c is None:\n year = ''\n else:\n year = c.find('div', attrs={'class': 'number'}).text\n years.append(year)\n web_link = ''\n w_link = soup.find('a', attrs={'class': 'secondary-btn website-link'})\n if w_link is not None:\n web_link += w_link.get(\"href\")+'; '\n o_links = soup.findAll('a', attrs={'class': 'other-links'})\n for o_link in o_links:\n if o_link is not None:\n web_link += o_link.get(\"href\")+'; '\n web_links.append(web_link)\n o_email = ''\n e_link = soup.findAll('a', attrs={'class': 'email-business'})\n for e in e_link:\n if e is not None:\n email = e.get(\"href\")\n email = re.sub('mailto:', '', email)\n o_email += email+\"; \"\n emails.append(o_email)\n general_info = soup.find('dd', attrs={'class': 'general-info'})\n if general_info is None:\n general_info = \"\"\n else:\n general_info = general_info.text\n general_infos.append(general_info)\n all_time = soup.find('div', attrs={'class': 'open-details'})\n time = ''\n if all_time is not None:\n for t in all_time.findAll('tr'):\n l_time = t.find('th', attrs={'class': 'day-label'}).text\n h_time = t.find('td', attrs={'class': 'day-hours'}).text\n time += l_time+' '+h_time+'; '\n else:\n time = ''\n times.append(time)\n payment = soup.find('dd', attrs={'class': 'payment'})\n if payment is None:\n payment = ''\n else:\n payment = payment.text\n payments.append(payment)\n category = soup.find('dd', attrs={'class': 'categories'})\n if category is None:\n category = ''\n else:\n category = category.text\n categories.append(category)\n neighborhood = soup.find('dd', attrs={'class': 'neighborhoods'})\n if neighborhood is None:\n neighborhood = ''\n else:\n neighborhood = neighborhood.text\n neighborhoods.append(neighborhood)\n banner = soup.find('dd', attrs={'class': 'banner-ad'})\n if banner is not None:\n banner = banner.find('img')\n if banner is None:\n banner = ''\n else:\n banner = banner.get('src')\n else:\n banner = ''\n banners.append(banner)\n service = ''\n o_service = soup.find('section', attrs={'id': 'business-info'})\n c_service = o_service.find('ul')\n if c_service is not None:\n for s in c_service.findAll('li'):\n service += s.text+'|'\n else:\n n_service = o_service.find('dd', attrs={'class': None})\n if n_service is None:\n service = \"\"\n elif '$' in n_service or '$$' in n_service or '$$$' in n_service:\n service = \"\"\n else:\n service = n_service.text\n services.append(service)\n other_info = ''\n o_info = soup.find('dd', attrs={'class': 'other-information'})\n if o_info is not None:\n for p in o_info.findAll('p'):\n other_info += p.text+';'\n other_info = re.sub(' ', '', other_info)\n other_infos.append(other_info)\n ids += 1\n aid.append(ids)\n df = pd.DataFrame({'ID': aid, 'Restaurant Name': names, 'Review': reviews, 'Address': addresses, 'Phone Number': phones,\n 'Years in Business': years, ' Website Link': web_links, 'Email Address': emails,\n 'General Information': general_infos, 'Time(in Hour)': times, 'Payment Methods': payments,\n 'Category': categories, 'Services/Products': services, 'Neighborhood': neighborhoods,\n 'Banner Link': banners, 'Other Information': other_infos})\n if not os.path.isfile('Restaurants.csv'):\n df.to_csv('Restaurants.csv', index=False, encoding='utf-8')\n else:\n df.to_csv('Restaurants.csv', mode='a', header=False, index=False)\n","sub_path":"webscrap/yellowpages.py","file_name":"yellowpages.py","file_ext":"py","file_size_in_byte":6344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"533427053","text":"__author__ = 'sevag'\n\nfrom multiprocessing import Queue\nimport time\n\nfrom python.b2bexecutor import B2BExecutor\n\n\ndef consumer(q):\n item = q.get()\n print('Item: %s'%item)\n\n\nif __name__ == '__main__':\n q = Queue(maxsize=1)\n b = B2BExecutor(consumer, args=(q,), autostart=True)\n\n while True:\n q.put('inserted at {0}'.format(time.time()))\n time.sleep(1)\n q.put('inserted at {0}'.format(time.time()))\n time.sleep(2)\n q.put('inserted at {0}'.format(time.time()))\n time.sleep(3)\n","sub_path":"example/b2b-example.py","file_name":"b2b-example.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"169703659","text":"from setuptools import setup, find_packages\r\ndeps = ['paramiko','matplotlib','numpy', 'requests',]\r\n\r\nsetup(\r\n name='rest_loop_loading',\r\n version='2.0.7',\r\n packages=find_packages(),\r\n python_requires='>=3.6',\r\n install_requires=deps,\r\n entry_points={'console_scripts': ['memory_tester.py = rest_loop_loading.script.memory_tester:main']}\r\n)\r\n","sub_path":"Rest_Loop_CPU_RAM/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"225969808","text":"# -*- coding: utf-8 -*-\n\nfrom tweepy.streaming import StreamListener, Stream\nfrom tweepy.auth import OAuthHandler\nfrom tweepy.api import API\nimport markov, re\n\np = re.compile(r'^@hu__hutest.+')\n\ndef oauth():\n consumer_key = \"\"\n consumer_secret = \"\"\n access_token = \"\"\n access_token_secret = \"\"\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n return auth\n\n\nclass Listener(StreamListener):\n def on_status(self, status):\n try:\n tweet = status.text\n if (p.match(tweet) != None):\n tweet_id = status.id\n mention = (status.user.screen_name).encode('utf-8')\n sentence = markov.study(mention)\n api.update_status(sentence, in_reply_to_status_id = tweet_id)\n except (AttributeError, UnboundLocalError):\n pass\n\n\nif __name__ == \"__main__\":\n auth = oauth()\n api = API(auth)\n stream = Stream(auth, Listener(), secure=True)\n stream.userstream()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"22952580","text":"\n# 1_1\n# vraag: noteer van elke expressie wat de uitkomst en type is:\n\n#invoer Uitkomst Type\n# 5 5 Integer\n# 5.0 5.0 Floating point\n# 5 % 2 1 Integer\n# ‘5’ '5' String\n# 5 * 2 10 Integer\n# ‘5’ * 2 '55' String\n# ‘5’ + ‘2’ '52' String\n# 5 / 2 2.5 Integer\n# 5//2 2 Integer\n# [5, 2, 1] [5,2,1] List\n# 5 in [1, 4, 6] false Boolean\n\n\n\n\n# 1_2\n# Schrijf en evalueer Python expressies die de volgende vragen beantwoorden:\n\n# a. Hoeveel letters zijn er in 'Supercalifragilisticexpialidocious'?\nlen('Supercalifragilisticexpialidocious')\n34\n\n# b. Komt in 'Supercalifragilisticexpialidocious' de tekst 'ice' voor?\na = 'Supercalifragilisticexpialidocious'\na.count('ice')\n1\n\n# c. Is het woord 'Antidisestablishmentarianism' langer dan 'Honorificabilitudinitatibus'?\nlen('Antidisestablishmentarianism') > len('Honorificabilitudinitatibus')\nTrue\n\n# d. Welke componist komt in alfabetische volgorde het eerst: 'Berlioz', 'Borodin', 'Brian', 'Bartok', 'Bellini', 'Buxtehude', 'Bernstein'? Welke het laatst?\nlist = ['Bartok', 'Bellini', 'Berlioz', 'Bernstein', 'Borodin', 'Brian', 'Buxtehude']\nsorted(list)\n['Bartok', 'Bellini', 'Berlioz', 'Bernstein', 'Borodin', 'Brian', 'Buxtehude']\n'Bartok komt het eerst en Buxtehude het laatst.'\n\n\n\n# 1_3\n# Schrijf Python statements die het volgende doen:\n\n# 1. Ken de waarde 6 toe aan variabele a, en waarde 7 aan variabele b.\na = 6\nb = 7\n\n# 2. Ken aan variabele c als waarde het gemiddelde van a en b toe.\nc = (a + b) / 2\n6.5\n\n# 3. Ken aan variabele inventaris de een lijst van strings toe: ‘papier’, ‘nietjes’, en ‘pennen’.\ninventaris = ['papier', 'nietjes', 'pennen']\n\n# 4. Ken aan variabelen voornaam, tussenvoegsel en achternaam je eigen naamgegevens toe.\nvoornaam = 'Mike'\ntussenvoegsel = ''\nachternaam = 'Fraanje'\n\n# 5. Ken aan variabele mijnnaam de variabelen van opdracht 4 (met spaties er tussen) toe.\nmijnnaam = voornaam + ' ' + tussenvoegsel + achternaam\nmijnnaam\n'Mike Fraanje'\n\n\n# 1_4\n# Schrijf booleaanse expressies die van de variabelen van Practice Exercise 1_3 evalueren of:\n\n# 1. 6.75 groter is dan a en kleiner b.\n6.75 > a and 6.75 < b\nTrue\n\n# 2. de lengte van inventaris meer dan 5 keer zo groot is als de lengte van variabele mijnnaam.\nlen(inventaris) > len(mijnnaam)\nFalse\n\n# 3. de lijst inventaris leeg is, of juist meer dan 10 items bevat.\nlen(inventaris) == 0 or len(inventaris) > 10\nFalse\n\n\n# 1_5\n# We gaan een lijst bijhouden met je favoriete artiesten. We gaan de lijst eerst creëren met 1 artiest en\n# dan uitbreiden. Schrijf per stap een expressie om:\n\n# 1. een nieuwe list met 1 artiest aan te maken met de naam favorieten.\nlist = ['Bryan Adams']\n\n# 2. de lijst uit te breiden met een tweede artiest.\nlist = list + ['Tupac']\n\n# 3. de tweede artiest te vervangen door een andere naam.\nlist[1] = ['Biggie']\n\n\n# 1_6\n# Het bereik van een lijst is het verschil tussen het grootste en het kleinste getal. Schrijf een Python\n# expressie die het bereik van een lijst berekent. Als bijvoorbeeld variabele list bestaat uit de getallen 3,\n# 7, -2 en 12, dan moet de expressie evalueren naar 14 (verschil tussen 12 en -2). Zorg dat de expressie\n# altijd werkt, ook al bestaat de lijst uit andere waarden!\n\nabs(a - b)\n","sub_path":"les1/week1.py","file_name":"week1.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"449491598","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport os\nimport warnings\nfrom PIL import Image\nimport matplotlib.patches as patches\nimport random\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom tensorflow.keras.layers import Activation, Dropout, Flatten, Dense\nfrom tensorflow.keras.layers import Convolution2D, MaxPooling2D, ZeroPadding2D\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import to_categorical \nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import applications\nfrom tensorflow.keras.applications import Xception, VGG16\nfrom tensorflow.keras.applications.xception import preprocess_input\nwarnings.filterwarnings(\"ignore\")\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\nfrom utils.delf import image_input_fn, get_features, match_images, get_delf_features_inliners_coordinates\n\n\n\nlandmark_classes = os.listdir(\"./data/train\")\nimg_width, img_height = 224, 224\ntrain_data_dir = './data/train'\nvalidation_data_dir = './data/validation'\nbatch_size = 32\nbatch_size_small = 16\ndatagen = ImageDataGenerator(rescale=1. / 255)\n\ntrain_generator = datagen.flow_from_directory(\n train_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size)\nvalidation_generator = datagen.flow_from_directory(\n validation_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size)\nn_classes = 25 \ntrain_samples = train_generator.samples\nvalidation_samples = validation_generator.samples\n\n\nxception_base_model = Xception(input_shape=(img_width, img_height, 3), weights='imagenet', include_top=False, pooling='avg')\nxception_model = Sequential()\nxception_model.add(xception_base_model)\nxception_model.add(Dense(512, activation='relu'))\n#dropout layer, dropout randomly switches off some neurons in the network which forces the data to find new paths\nxception_model.add(Dropout(0.5)) \nxception_model.add(Dense(n_classes, activation='softmax')) #class prediction(0–24)\n\n# Say not to train first layer (Xception) model. It is already trained\nxception_model.layers[0].trainable = False\n\n# Pixel values rescaling from [0, 255] to [0, 1] interval\ndatagen_xception = ImageDataGenerator(rescale=1. / 255, preprocessing_function=preprocess_input)\n\n# Retrieve images and their classes for train and validation sets\ntrain_generator_xception = datagen_xception.flow_from_directory(\n train_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size_small)\n\nvalidation_generator_xception = datagen_xception.flow_from_directory(\n validation_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size_small)\n\n\n# Compile the model \nxception_model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=0.0005),\n metrics=['accuracy'])\n\n\nxception_model_checkpointer = ModelCheckpoint(filepath='./models/xception_model_checkpoint.h5', monitor='val_acc', verbose=1, save_best_only=True)\n\n# Early stopping\n# early_stopping = EarlyStopping(monitor='val_acc', verbose=1, patience=5)\n\nxception_model_reducer = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3)\n\nhists = []\n\nhist = xception_model.fit_generator(\n train_generator_xception,\n steps_per_epoch=train_samples // batch_size_small,\n epochs=1,\n verbose=1,\n callbacks=[xception_model_reducer, xception_model_checkpointer],\n validation_data=validation_generator_xception,\n validation_steps=validation_samples // batch_size_small)\n\nhists.append(hist)\nhist = xception_model.fit_generator(\n train_generator_xception,\n steps_per_epoch=train_samples // batch_size_small,\n epochs=10,\n verbose=1,\n callbacks=[xception_model_reducer, xception_model_checkpointer],\n validation_data=validation_generator_xception,\n validation_steps=validation_samples // batch_size_small)\n\nhists.append(hist)\n\n\nhist_df = pd.concat([pd.DataFrame(hist.history) for hist in hists], sort=True)\nhist_df.index = np.arange(1, len(hist_df)+1)\nfig, axs = plt.subplots(nrows=2, sharex=True, figsize=(16, 10))\naxs[0].plot(hist_df.val_acc, lw=5, label='Validation')\naxs[0].plot(hist_df.acc, lw=5, label='Training')\naxs[0].set_ylabel('Accuracy')\naxs[0].set_xlabel('Epoch')\naxs[0].grid()\naxs[0].legend(loc=0)\naxs[1].plot(hist_df.val_loss, lw=5, label='Validation')\naxs[1].plot(hist_df.loss, lw=5, label='Training')\naxs[1].set_ylabel('Loss')\naxs[1].set_xlabel('Epoch')\naxs[1].grid()\naxs[1].legend(loc=0)\nplt.show();\n\n# Compile the model \nxception_model.compile(loss='categorical_crossentropy',\n optimizer=Adam(lr=0.0001),\n metrics=['accuracy'])\n\n\nhist = xception_model.fit_generator(\n train_generator_xception,\n steps_per_epoch=train_samples // batch_size_small,\n epochs=3,\n verbose=1,\n callbacks=[xception_model_reducer, xception_model_checkpointer],\n validation_data=validation_generator_xception,\n validation_steps=validation_samples // batch_size_small)\n\nhists.append(hist)\n","sub_path":"XceptionV1.py","file_name":"XceptionV1.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"330255224","text":"# -*- coding: utf-8 -*-\nimport sqlite3\n\ndatabase_name = 'database.db'\n\nclass DBOperations:\n def __init__(self):\n need_init = False\n from os.path import isfile, getsize\n from os import getcwd\n\n if not isfile(getcwd() + '/' + database_name) or getsize(getcwd() + '/' + database_name) < 100:\n need_init =True\n\n self.con = sqlite3.connect(database_name, check_same_thread=False)\n\n if need_init:\n self.init(self.con)\n\n @staticmethod\n def init(con):\n # startup code\n con.execute('''\n CREATE TABLE `Project` (\n `Id`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `Name`\tTEXT NOT NULL UNIQUE,\n `Acronym`\tTEXT NOT NULL,\n `Status`\tTEXT NOT NULL\n );''')\n con.execute('''\n CREATE TABLE `Org` (\n `Id`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `ProjectId`\tINTEGER NOT NULL,\n `Login`\tTEXT NOT NULL,\n `Password`\tTEXT NOT NULL,\n `Token`\tTEXT NOT NULL,\n `Description`\tTEXT\n );''')\n # frame = number of minutes between builds\n con.execute('''\n CREATE TABLE `Plan` (\n `Id`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n `ProjectId`\tINTEGER NOT NULL,\n `OrgId`\tINTEGER NOT NULL,\n `Type`\tTEXT NOT NULL,\n `Active`\tINTEGER NOT NULL,\n `Frame` INTEGER,\n `TotalBuilds`\tINTEGER,\n `TotalSuccessBuilds`\tINTEGER,\n `TotalFailBuilds`\tINTEGER,\n `LastBuildSucceeded`\tTEXT\n );''')\n con.execute('''\n CREATE TABLE `Build` (\n `Id`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `Number`\tINTEGER NOT NULL,\n `ProjectId`\tINTEGER NOT NULL,\n `OrgId`\tINTEGER NOT NULL,\n `PlanId`\tINTEGER NOT NULL,\n `Status` TEXT NOT NULL,\n `BuildLog`\tTEXT NOT NULL,\n `BuildResult`\tINTEGER NOT NULL,\n `ErrorCount`\tINTEGER NOT NULL,\n `TimeElapsed`\tINTEGER NOT NULL\n );''')\n con.commit()\n\n # BEGIN READ SECTION\n # get everything\n def query_all(self, table_name):\n c = self.con.cursor()\n try:\n c.execute('SELECT * FROM ' + table_name)\n except Exception as e:\n raise e\n\n query_result = c.fetchall()\n\n return query_result\n\n def get_projects(self):\n return self.query_all('Project')\n\n def get_builds(self):\n return self.query_all('Build')\n\n def get_orgs(self):\n return self.query_all('Org')\n\n def get_plans(self):\n return self.query_all('Plan')\n\n def query_plan_builds(self, plan_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT * FROM Build WHERE PlanId = ' + str(plan_id))\n except Exception as e:\n raise e\n\n query_result = c.fetchall()\n if len(query_result) > 0:\n return query_result\n else:\n return None\n\n # get all active (1) plans for the Scheduler\n def sc_get_plans(self):\n c = self.con.cursor()\n try:\n # 0 = False\n # 1 = True\n c.execute('SELECT * FROM Plan WHERE Active=0;')\n return c.fetchall()\n except Exception as e:\n raise e\n\n def get_org(self, org_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT Login FROM Org WHERE Id = ' + str(org_id) + ';')\n return c.fetchone()\n except Exception as e:\n raise e\n\n def get_org_info(self, org_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT * FROM Org WHERE Id = ' + str(org_id) + ';')\n return c.fetchone()\n except Exception as e:\n raise e\n\n def get_project_name(self, project_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT Name FROM Project WHERE Id = ' + str(project_id) + ';')\n return c.fetchone()\n except Exception as e:\n raise e\n\n def get_project_info(self, project_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT * FROM Project WHERE Id = ' + str(project_id))\n return c.fetchone()\n except Exception as e:\n raise e\n\n # def get_project_plans(self, project_id):\n # c = self.con.cursor()\n # try:\n # c.execute('')\n # return c.fetchall()\n # except Exception as e:\n # raise e\n #\n # def get_latest_project_builds(self, project_id):\n # c = self.con.cursor()\n # try:\n # c.execute('')\n # return c.fetchall()\n # except Exception as e:\n # raise e\n\n def get_plan(self, plan_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT * FROM Plan WHERE Id =' + str(plan_id))\n return c.fetchone()\n except Exception as e:\n raise e\n\n def get_plan_acronym(self, plan_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT Project.Acronym FROM Project WHERE Project.Id = (SELECT Plan.ProjectId FROM Plan WHERE Id=' + str(plan_id) + ')')\n return c.fetchone()[0]\n except Exception as e:\n raise e\n\n def generate_build_number(self, plan_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT Count(*) FROM Build WHERE Build.ProjectId=' + str(plan_id))\n return c.fetchone()[0]\n except Exception as e:\n raise e\n\n def get_average_build_time_by_plan(self, plan_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT AVG(Build.TimeElapsed) FROM Build WHERE Build.PlanId=' + str(plan_id))\n return c.fetchone()[0]\n except Exception as e:\n raise e\n\n def get_last_insert_id(self):\n c = self.con.cursor()\n try:\n c.execute('SELECT last_insert_rowid()')\n return c.fetchone()[0]\n except Exception as e:\n raise e\n\n def get_build_id(self, plan_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT Id FROM Build WHERE PlanId=' + str(plan_id) + ' AND Status=\\'building\\'')\n return c.fetchone()[0]\n\n except Exception as e:\n raise e\n\n def get_build_status(self, plan_id, build_id):\n c = self.con.cursor()\n try:\n c.execute('SELECT Status FROM Build WHERE PlanId=' + str(plan_id) + ' AND Id=' + str(build_id))\n # print()\n return c.fetchone()[0]\n except Exception as e:\n raise e\n\n def get_latest_completed_builds(self):\n # query for all builds with status = completed, but get\n # only the ones with highest Build.Number per plan\n c = self.con.cursor()\n try:\n # get every plan ID first\n c.execute('SELECT Id FROM Plan;')\n plans = c.fetchall()\n if plans is None:\n return None\n else:\n results = list()\n for plan in plans:\n if plan[0] is not None:\n c.execute('SELECT PlanId, MAX(Number) FROM Build WHERE PlanId=' + str(plan[0]) + ' AND Status=\\'finished\\'')\n # example of result:\n # PlanId - Max(Number)\n # (1, 20)\n result = c.fetchone()\n results.append(result)\n return results\n\n #return c.fetchall()\n except Exception as e:\n raise e\n\n # END READ SECTION\n # BEGIN WRITING SECTION\n\n def add_new_project(self, project_name, project_acronym):\n self.con.execute('''INSERT INTO Project (Name, Acronym, Status) VALUES (?, ?, ?);''', (project_name, project_acronym, 'new'))\n self.con.commit()\n\n def add_new_plan(self, project_id, plan_type, org_id):\n self.con.execute('''\n INSERT INTO Plan (ProjectId, OrgId, Type, Active) VALUES\n (?, ?, ?, ?)''', (project_id, org_id, plan_type, False))\n self.con.commit()\n\n def add_new_org(self, org_login, org_password, org_sectoken, project_id):\n self.con.execute('''\n INSERT INTO Org (Login, Password, Token, ProjectId)\n VALUES (?, ?, ?, ?)''', (org_login, org_password, org_sectoken, project_id))\n self.con.commit()\n\n def add_build(self, plan_id, build_no, build_status, build_log, build_result, error_count, time_elapsed):\n # passing the plan ID and build NO\n # we need to query for the plan to get the\n # org and project ID\n c = self.con.cursor()\n try:\n c.execute('SELECT Plan.OrgId, Plan.ProjectId FROM Plan WHERE Id=' + str(plan_id))\n result = c.fetchone()\n\n self.con.execute('''INSERT INTO `Build` (\n `Number`,\n `ProjectId`,\n `OrgId`,\n `PlanId`,\n `Status`,\n `BuildLog`,\n `BuildResult`,\n `ErrorCount`,\n `TimeElapsed`) VALUES\n (?,?,?,?,?,?,?,?,?);''',\n (build_no,\n result[1],\n result[0],\n plan_id,\n build_status,\n build_log,\n build_result,\n error_count,\n time_elapsed))\n self.con.commit()\n # print('ADDED NEW BUILD TO DB')\n except Exception as e:\n raise e\n\n # END WRITING SECTION\n # BEGIN UPDATE SECTION\n def update_project(self, project_id, project_name, project_acronym, project_status):\n try:\n # print('UPDATE Project SET Name=\\'' + str(project_name) + '\\' , Acronym=\\'' + str(project_acronym) + '\\' , Status=\\'' + str(project_status) + '\\' WHERE Id=' + str(project_id))\n self.con.execute('UPDATE Project SET Name=\\'' + str(project_name) + '\\' , Acronym=\\'' + str(project_acronym) + '\\' , Status=\\'' + str(project_status) + '\\' WHERE Id=' + str(project_id))\n # print('olar mundo')\n self.con.commit()\n except Exception as e:\n raise e\n\n def update_org(self, org_id, org_login, org_password, org_sectoken, org_desc):\n try:\n self.con.execute('UPDATE Org SET Login=\\'' + org_login + '\\', Password=\\'' + org_password + '\\', Token=\\'' + org_sectoken + '\\', Description=\\'' + org_desc + '\\' WHERE Id=' + str(org_id))\n self.con.commit()\n except Exception as e:\n raise e\n\n def set_finish_build(self, build_no, plan_id, time_elapsed):\n try:\n # print('Trying to finish build...')\n self.con.execute('UPDATE Build SET Status=\\'finished\\', TimeElapsed=' + str(time_elapsed) + ' WHERE Build.PlanId=' + str(plan_id) + ' AND Build.Number=' + str(build_no))\n self.con.commit()\n # print('Build finished.')\n except Exception as e:\n raise e\n\n def set_build_status(self, build_id, status):\n try:\n # print(build_id)\n # print(status)\n self.con.execute('UPDATE Build SET Status=\\'' + str(status) + '\\' WHERE Id=' + str(build_id))\n self.con.commit()\n except Exception as e:\n raise e\n\n def set_build_result(self, build_id, build_log):\n c = self.con.cursor()\n try:\n import base64\n log = base64.b64encode(build_log.encode()).decode('ascii')\n if build_id is None:\n build_id = ''\n print('UPDATE Build SET BuildLog=\\'' + str(log) + '\\' WHERE Build.Id=' + str(build_id))\n\n self.con.execute('UPDATE Build SET BuildLog=\\'' + str(log) + '\\' WHERE Id=' + str(build_id))\n self.con.commit()\n except Exception as e:\n raise e\n\n # END UPDATE SECTION","sub_path":"DBOperations.py","file_name":"DBOperations.py","file_ext":"py","file_size_in_byte":12232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"40608929","text":"# Copyright 2017 by Akira Yoshiyama .\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nDatabase handler\n\"\"\"\n\nimport copy\nfrom datetime import datetime\nimport logging\nimport pymongo\nimport time\n\nfrom . import const\n\n\nDB = None\n\n\ndef init_db(db_url, db_name):\n \"\"\"\n Initialize DB object\n\n :param db_url: URL to the MongoDB\n :type db_url: str\n :param db_name: Database name to use\n :type db_name: str\n :rtype: None\n \"\"\"\n global DB\n client = pymongo.MongoClient(db_url)\n DB = client[db_name]\n\n\ndef increase_counter(tenant_name):\n \"\"\"\n Increment a counter within the database\n This is an atomic operation.\n\n :param tenant_name: Tenant ID\n :type tenant_name: str\n :return: The next count to use\n :rtype: int\n \"\"\"\n tenant = DB.tenant.find_one_and_update({'tenant_name': tenant_name},\n {'$inc': {'counter': 1}})\n logging.debug(\"increased. before: %s\", tenant)\n return tenant['counter']\n\n\ndef create_tenant(tenant_name, by, config):\n \"\"\"\n Create a new tenant.\n This ISN'T an atomic operation.\n\n :param tenant_name: Tenant ID\n :type tenant_name: str\n :param by: email address of the operator\n :type by: str\n :param config: Various configuration for the tenant\n :type config: dict\n :rtype: None\n \"\"\"\n config = copy.copy(config)\n new_ml_account = config['new_ml_account']\n tenant = DB.tenant.find_one({'new_ml_account': new_ml_account})\n if tenant:\n logging.error(\"New ML account %s is duplicated\", new_ml_account)\n return\n\n tenant = DB.tenant.find_one({'tenant_name': tenant_name})\n if tenant:\n logging.error(\"Tenant %s already exists: %s\", tenant_name, tenant)\n return\n\n config[\"admins\"] = list(config[\"admins\"])\n log_dict = {\n \"op\": const.OP_CREATE,\n \"config\": config,\n \"by\": by,\n }\n tenant_dict = {\n \"tenant_name\": tenant_name,\n \"created\": datetime.now(),\n \"updated\": datetime.now(),\n \"counter\": 1,\n \"status\": const.TENANT_STATUS_ENABLED,\n \"by\": by,\n \"logs\": [log_dict],\n \"admins\": config[\"admins\"],\n \"charset\": config[\"charset\"],\n \"ml_name_format\": config[\"ml_name_format\"],\n \"new_ml_account\": config[\"new_ml_account\"],\n \"days_to_close\": config[\"days_to_close\"],\n \"days_to_orphan\": config[\"days_to_orphan\"],\n \"welcome_msg\": config[\"welcome_msg\"],\n \"readme_msg\": config[\"readme_msg\"],\n \"add_msg\": config[\"add_msg\"],\n \"remove_msg\": config[\"remove_msg\"],\n \"reopen_msg\": config[\"reopen_msg\"],\n \"goodbye_msg\": config[\"goodbye_msg\"],\n \"report_subject\": config[\"report_subject\"],\n \"report_msg\": config[\"report_msg\"],\n \"orphaned_subject\": config[\"orphaned_subject\"],\n \"orphaned_msg\": config[\"orphaned_msg\"],\n \"closed_subject\": config[\"closed_subject\"],\n \"closed_msg\": config[\"closed_msg\"],\n }\n DB.tenant.insert_one(tenant_dict)\n logging.debug(\"Tenant %s created: %s\", tenant_name, tenant_dict)\n\n\ndef update_tenant(tenant_name, by, **config):\n \"\"\"\n Update a tenant.\n This ISN'T an atomic operation.\n\n :param tenant_name: Tenant ID\n :type tenant_name: str\n :param by: email address of the operator\n :type by: str\n :keyword config: Various configuration for the tenant\n :type config: dict\n :rtype: None\n \"\"\"\n tenant = DB.tenant.find_one({'tenant_name': tenant_name})\n if tenant is None:\n logging.error(\"Tenant %s not found\", tenant_name)\n return\n\n if 'new_ml_account' in config:\n new_ml_account = config['new_ml_account']\n tenant2 = DB.tenant.find_one({'new_ml_account': new_ml_account,\n 'tenant_name': {'$ne': tenant_name}})\n if tenant2:\n logging.error(\"New ML account %s is duplicated\", new_ml_account)\n return\n\n if by not in tenant['admins'] and by != \"CLI\":\n logging.error(\"%s is not an admin of %s\", by, tenant_name)\n return\n\n logging.debug(\"before: %s\", tenant)\n log_dict = {\n \"op\": const.OP_UPDATE,\n \"config\": config,\n \"by\": by,\n }\n for key, value in config.items():\n if key in [\"tenant_name\", \"by\", \"created\", \"updated\", \"logs\"]:\n continue\n if key not in tenant:\n config.pop(key)\n if key == \"admins\":\n config[key] = list(value)\n config[\"updated\"] = datetime.now()\n DB.tenant.find_one_and_update({\"tenant_name\": tenant_name},\n {\"$set\": config,\n \"$push\": {\"logs\": log_dict}})\n if logging.root.level == logging.DEBUG:\n tenant = DB.tenant.find_one({'tenant_name': tenant_name})\n logging.debug(\"after: %s\", tenant)\n\n\ndef delete_tenant(tenant_name):\n \"\"\"\n Delete a ML\n This is an atomic operation.\n\n :param tenant_name: Tenant ID\n :type tenant_name: str\n :rtype: None\n \"\"\"\n DB.ml.delete_many({'tenant_name': tenant_name})\n DB.tenant.delete_one({'tenant_name': tenant_name})\n if logging.root.level == logging.DEBUG:\n logging.debug(\"delete: %s\", tenant_name)\n\n\ndef get_tenant(tenant_name):\n \"\"\"\n Aquire a ML\n This is an atomic operation.\n\n :param tenant_name: Tenant ID\n :type tenant_name: str\n :return: Tenant information\n :rtype: dict\n \"\"\"\n tenant = DB.tenant.find_one({'tenant_name': tenant_name})\n if tenant:\n tenant[\"admins\"] = set(tenant[\"admins\"])\n return tenant\n\n\ndef find_tenants(cond, sortkey=None, reverse=False):\n \"\"\"\n Aquire tenants with conditions\n This is an atomic operation.\n\n :param cond: Conditions\n :type cond: dict\n :keyword sortkey: sort pattern\n :type sortkey: str\n :keyword reverse: Reverse sort or not\n :type reverse: bool\n :return: tenant objects\n :rtype: [dict]\n \"\"\"\n if sortkey:\n if reverse:\n data = list(DB.tenant.find(cond, sort=[(sortkey, -1)]))\n else:\n data = list(DB.tenant.find(cond, sort=[(sortkey, 1)]))\n else:\n data = list(DB.tenant.find(cond))\n\n for i in data:\n i[\"admins\"] = set(i[\"admins\"])\n return data\n\n\ndef create_ml(tenant_name, ml_name, subject, members, by):\n \"\"\"\n Create a new ML and register members into it\n This is an atomic operation.\n\n :param tenant_name: Tenant ID of the ML\n :type tenant_name: str\n :param ml_name: ML ID\n :type ml_name: str\n :param subject: subject of the original mail\n :type subject: str\n :param members: e-mail addresses to register\n :type members: set(str)\n :param by: sender's e-mail address\n :type by: str\n :return: ML object\n :rtype: dict\n \"\"\"\n ml = DB.ml.find_one({'ml_name': ml_name})\n if ml:\n logging.error(\"ML %s already exists: %s\", ml_name, ml)\n return\n\n log_dict = {\n \"op\": const.OP_CREATE,\n \"by\": by,\n \"members\": list(members)\n }\n ml_dict = {\n \"tenant_name\": tenant_name,\n \"ml_name\": ml_name,\n \"subject\": subject,\n \"members\": list(members),\n \"created\": datetime.now(),\n \"updated\": datetime.now(),\n \"status\": const.STATUS_NEW,\n \"by\": by,\n \"logs\": [log_dict]\n }\n DB.ml.insert_one(ml_dict)\n logging.debug(\"created: %s\", ml_dict)\n\n\ndef get_ml(ml_name):\n \"\"\"\n Aquire a ML\n This is an atomic operation.\n\n :param ml_name: ML ID\n :type ml_name: str\n :return: ML object\n :rtype: dict\n \"\"\"\n ml = DB.ml.find_one({'ml_name': ml_name})\n return ml\n\n\ndef find_mls(cond, sortkey=None, reverse=False):\n \"\"\"\n Aquire MLs with conditions\n This is an atomic operation.\n\n :param cond: Conditions\n :type cond: dict\n :keyword sortkey: sort pattern\n :type sortkey: str\n :keyword reverse: Reverse sort or not\n :type reverse: bool\n :return: ML objects\n :rtype: [dict]\n \"\"\"\n if sortkey:\n if reverse:\n return DB.ml.find(cond, sort=[(sortkey, -1)])\n else:\n return DB.ml.find(cond, sort=[(sortkey, 1)])\n else:\n return DB.ml.find(cond)\n\n\ndef mark_mls_orphaned(last_updated, by):\n \"\"\"\n Mark old MLs orphaned if they are updated before last_updated\n This ISN'T an atomic operation.\n\n :param last_updated: Last updated\n :type last_updated: datetime\n :param by: sender's e-mail address\n :type by: str\n :return: ML objects\n :rtype: list(dict)\n \"\"\"\n log_dict = {\n \"op\": const.OP_ORPHAN,\n \"by\": by,\n }\n DB.ml.update_many({'status': const.STATUS_OPEN,\n 'updated': {'$lt': last_updated}},\n {'$set': {'status': const.STATUS_ORPHANED,\n 'updated': datetime.now(),\n 'by': by},\n '$push': {'logs': log_dict}})\n result = DB.ml.find({'status': const.STATUS_ORPHANED})\n logging.debug(\"orphaned: %s\", [_['ml_name'] for _ in result])\n return result\n\n\ndef mark_mls_closed(last_updated, by):\n \"\"\"\n Mark old MLs closed if they are updated before last_updated\n This ISN'T an atomic operation.\n\n :param last_updated: Last updated\n :type last_updated: datetime\n :param by: sender's e-mail address\n :type by: str\n :return: ML objects\n :rtype: list(dict)\n \"\"\"\n log_dict = {\n \"op\": const.OP_CLOSE,\n \"by\": by,\n }\n DB.ml.update_many({'status': const.STATUS_ORPHANED,\n 'updated': {'$lt': last_updated}},\n {'$set': {'status': const.STATUS_CLOSED,\n 'updated': datetime.now(),\n 'by': by},\n '$push': {'logs': log_dict}})\n result = DB.ml.find({'status': const.STATUS_CLOSED})\n logging.debug(\"closed: %s\", [_['ml_name'] for _ in result])\n return result\n\n\ndef change_ml_status(ml_name, status, by):\n \"\"\"\n Alter status of a ML. This is an atomic operation.\n\n :param ml_name: mailing list ID\n :type ml_name: str\n :param status: status; 'orphaned', 'open' or 'closed'\n :type status: str\n :param by: sender's e-mail address\n :type by: str\n :rtype: None\n \"\"\"\n log_dict = {\n \"op\": const.OP_MAP[status],\n \"by\": by,\n }\n DB.ml.update_many({'ml_name': ml_name},\n {'$set': {'status': status,\n 'updated': datetime.now(),\n 'by': by},\n '$push': {'logs': log_dict}})\n logging.debug(\"status changed: ml_name=%s|status=%s|by=%s\",\n ml_name, status, by)\n\n\ndef add_members(ml_name, members, by):\n \"\"\"\n Add e-mail addresses of new members into a ML\n This ISN'T an atomic operation.\n\n :param ml_name: mailing list ID\n :type ml_name: str\n :param members: e-mail addresses to add\n :type members: set(str)\n :param by: sender's e-mail address\n :type by: str\n :rtype: None\n \"\"\"\n ml = DB.ml.find_one({'ml_name': ml_name})\n logging.debug(\"before: %s\", ml)\n _members = set(ml.get('members', []))\n _members |= members\n log_dict = {\n \"op\": const.OP_ADD_MEMBERS,\n \"by\": by,\n \"members\": list(members),\n }\n DB.ml.find_one_and_update({'ml_name': ml_name},\n {'$set': {'members': list(_members),\n 'updated': datetime.now(),\n 'by': by},\n '$push': {'logs': log_dict}})\n if logging.root.level == logging.DEBUG:\n ml = DB.ml.find_one({'ml_name': ml_name})\n logging.debug(\"after: %s\", ml)\n\n\ndef del_members(ml_name, members, by):\n \"\"\"\n Remove e-mail addresses of members from a ML\n This ISN'T an atomic operation.\n\n :param ml_name: mailing list ID\n :type ml_name: str\n :param members: e-mail addresses to add\n :type members: set(str)\n :param by: sender's e-mail address\n :type by: str\n :rtype: None\n \"\"\"\n ml = DB.ml.find_one({'ml_name': ml_name})\n logging.debug(\"before: %s\", ml)\n _members = set(ml.get('members', []))\n _members -= members\n log_dict = {\n \"op\": const.OP_DEL_MEMBERS,\n \"by\": by,\n \"members\": list(members),\n }\n DB.ml.find_one_and_update({'ml_name': ml_name},\n {'$set': {'members': list(_members),\n 'updated': datetime.now(),\n 'by': by},\n '$push': {'logs': log_dict}})\n if logging.root.level == logging.DEBUG:\n ml = DB.ml.find_one({'ml_name': ml_name})\n logging.debug(\"after: %s\", ml)\n\n\ndef get_members(ml_name):\n \"\"\"\n Aquire e-mail addresses of members from a ML\n This is an atomic operation.\n\n :param ml_name: mailing list ID\n :type ml_name: str\n :return: members\n :rtype: set(str)\n \"\"\"\n ml = DB.ml.find_one({'ml_name': ml_name})\n if ml is None:\n return None\n return set(ml.get('members', []))\n\n\ndef log_post(ml_name, members, by):\n \"\"\"\n Append a log about sending a post to a ML\n This is an atomic operation.\n\n :param ml_name: mailing list ID\n :type ml_name: str\n :param members: e-mail addresses to add\n :type members: set(str)\n :param by: sender's e-mail address\n :type by: str\n :rtype: None\n \"\"\"\n if logging.root.level == logging.DEBUG:\n ml = DB.ml.find_one({'ml_name': ml_name})\n logging.debug(\"before: %s\", ml)\n log_dict = {\n \"op\": const.OP_POST,\n \"by\": by,\n \"members\": list(members),\n }\n DB.ml.find_one_and_update({'ml_name': ml_name},\n {'$set': {'updated': datetime.now(),\n 'by': by},\n '$push': {'logs': log_dict}})\n if logging.root.level == logging.DEBUG:\n ml = DB.ml.find_one({'ml_name': ml_name})\n logging.debug(\"after: %s\", ml)\n\n\ndef get_logs(ml_name):\n \"\"\"\n Show operation logs of a ML\n This is an atomic operation.\n\n :param ml_name: mailing list ID\n :type ml_name: str\n :return: operation logs\n :rtype: list[dict]\n \"\"\"\n ml = DB.ml.find_one({'ml_name': ml_name})\n if ml is None:\n return None\n for log in ml['logs']:\n if 'members' in log:\n log['members'] = set(log['members'])\n return ml['logs']\n","sub_path":"amane/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":15059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"342228801","text":"import tensorflow as tf\nimport cv2\nimport SimpleITK as sitk\nimport numpy as np\n\n\nclass SegDataLoader(object):\n\n def __init__(self,\n image_list,\n mask_list,\n n_class,\n batch_size=8,\n image_size=(640, 640),\n augment_rotate=True,\n augment_crop_zoom=True,\n augment_flip=True,\n augment_color=True):\n\n self.image_list = image_list\n self.mask_list = mask_list\n self.n_class = n_class\n self.batch_size_slice = batch_size\n self.image_size = image_size\n self.augment_rotate = augment_rotate\n self.augment_crop_zoom = augment_crop_zoom\n self.augment_flip = augment_flip\n self.augment_color = augment_color\n\n self.data_len = len(image_list)\n assert len(self.image_list) == len(self.mask_list), \"Data list and mask list do not match\"\n self.all_paths = list(zip(image_list, mask_list))\n\n def load_data_label(self, image_mask_path, is_train=True):\n\n data_label = tf.py_func(return_random_slices, [image_mask_path, self.batch_size_slice, self.image_size],\n tf.float32)\n data_label.set_shape([self.batch_size_slice, self.image_size[0], self.image_size[1], 2])\n\n if is_train:\n data_label = tf.map_fn(lambda x: self.preprocess_image_and_label(x[:, :, 0], x[:, :, 1]), data_label)\n data = data_label[:, :, :, 0]\n label = data_label[:, :, :, 1]\n data, label = self._postprocess_label(data, label)\n return data, label\n\n def preprocess_image_and_label(self, image, label):\n if self.augment_flip:\n distortions = tf.round(tf.random_uniform([2], dtype=tf.float32))\n distortions = tf.cast(distortions, tf.bool)\n image = self.flip_distortions(image, distortions=distortions)\n label = self.flip_distortions(label, distortions=distortions)\n if self.augment_rotate:\n random_angle = tf.random.uniform(shape=[1], minval=-np.pi / 4, maxval=np.pi / 4)\n image = self.rotate_image(image, random_angle)\n label = self.rotate_image(label, random_angle, is_label=True)\n if self.augment_crop_zoom:\n sample_distorted_bounding_box = self.random_zoom_box(image)\n image = self.crop_and_resize(image, sample_distorted_bounding_box)\n label = self.crop_and_resize(label, sample_distorted_bounding_box, is_label=True)\n if self.augment_color:\n image = self.color_distortions(image)\n\n image = (image - tf.reduce_min(image)) / (tf.reduce_max(image) - tf.reduce_min(image))\n\n return tf.stack([image, label], axis=-1)\n\n def color_distortions(self, image):\n image = tf.expand_dims(image, -1)\n image = tf.image.random_brightness(image, max_delta=32. / 255.)\n image = tf.image.random_contrast(image, lower=0.5, upper=1.5)\n return tf.squeeze(image)\n\n def rotate_image(self, image, angle, is_label=False):\n if is_label:\n interpolation = 'NEAREST'\n else:\n interpolation = 'BILINEAR'\n return tf.contrib.image.rotate(image, angle, interpolation=interpolation)\n\n def flip_distortions(self, image, distortions):\n # Horizontal flipping\n distort_left_right_random = distortions[0]\n image = tf.cond(distort_left_right_random, lambda: tf.reverse(image, [1]), lambda: tf.identity(image))\n # Vertical flipping\n distort_up_down_random = distortions[1]\n image = tf.cond(distort_up_down_random, lambda: tf.reverse(image, [0]), lambda: tf.identity(image))\n return image\n\n def random_zoom_box(self, image):\n bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])\n sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box(\n [self.image_size[0], self.image_size[1], 1],\n bounding_boxes=bbox,\n min_object_covered=0.65,\n area_range=[0.5, 1])\n return sample_distorted_bounding_box\n\n def crop_and_resize(self, image, sample_distorted_bounding_box, is_label=False):\n # Crop image\n image = tf.expand_dims(image, -1)\n bbox_begin, bbox_size, distort_bbox = sample_distorted_bounding_box\n cropped_image = tf.slice(image, bbox_begin, bbox_size)\n # set cropped image shape since the dynamic slice based upon the bbox_size loses the third dimension\n cropped_image.set_shape([None, None, 1])\n # Resize to original dimensions\n if is_label:\n interpolation = tf.image.ResizeMethod.NEAREST_NEIGHBOR\n else:\n interpolation = tf.image.ResizeMethod.BILINEAR\n image = tf.image.resize_images(cropped_image, image.shape[:2], method=interpolation)\n return tf.squeeze(image)\n\n def _postprocess_label(self, data, label):\n label = tf.cast(label, tf.uint8)\n label = tf.one_hot(label, self.n_class, on_value=1.0, off_value=0.0)\n data = tf.expand_dims(data, axis=3)\n return data, label\n\n def get_train_batch(self, num_parallel_calls=4):\n with tf.name_scope('Train_data_loader'):\n # Apply tf data operations\n train_data = tf.data.Dataset.from_tensor_slices(self.all_paths)\n train_data = train_data.shuffle(buffer_size=self.data_len).repeat()\n train_data = train_data.map(lambda x: self.load_data_label(x, is_train=True),\n num_parallel_calls=num_parallel_calls)\n train_data = train_data.shuffle(buffer_size=self.batch_size_slice*3)\n train_data = train_data.prefetch(buffer_size=10)\n # Get batch from iterators\n train_batch_iterator = train_data.make_one_shot_iterator()\n train_batch_images, train_batch_labels = train_batch_iterator.get_next()\n return train_batch_images, train_batch_labels\n\n def get_eval_batch(self, num_parallel_calls=2):\n with tf.name_scope('Val_data_loader'):\n # Apply tf data operations\n eval_data = tf.data.Dataset.from_tensor_slices(self.all_paths)\n eval_data = eval_data.shuffle(buffer_size=self.data_len).repeat()\n eval_data = eval_data.map(lambda x: self.load_data_label(x, is_train=False),\n num_parallel_calls=num_parallel_calls)\n eval_data = eval_data.shuffle(buffer_size=self.batch_size_slice*3)\n eval_data = eval_data.prefetch(buffer_size=10)\n # Get batch from iterators\n eval_batch_iterator = eval_data.make_one_shot_iterator()\n eval_batch_images, eval_batch_labels = eval_batch_iterator.get_next()\n return eval_batch_images, eval_batch_labels\n\n\ndef return_random_slices(data_label_path, batch_size, image_size):\n\n def _normalize_planes(npzarray):\n maxHU, minHU = 400., -1000.\n npzarray = (npzarray - minHU) / (maxHU - minHU)\n npzarray[npzarray > 1] = 1.\n npzarray[npzarray < 0] = 0.\n return npzarray\n\n def _load_sitk_array(filename):\n image = sitk.ReadImage(filename)\n image = sitk.GetArrayFromImage(image)\n return image\n\n def _get_subsample_indices(label, background_label=0):\n selected_indices = list(\n map(lambda x: np.sum(x == np.ones_like(x) * background_label) != (x.shape[0] * x.shape[1]), label))\n return selected_indices\n\n def _normalize_slice(data_slice):\n data_slice = data_slice.astype(np.float32)\n return (data_slice - np.min(data_slice)) / (np.max(data_slice) - np.min(data_slice))\n\n def _resize_slice(data_slice, label=False):\n if label:\n return cv2.resize(data_slice, (image_size[1], image_size[0]), interpolation=cv2.INTER_NEAREST)\n else:\n return cv2.resize(data_slice, (image_size[1], image_size[0]), interpolation=cv2.INTER_LINEAR)\n\n # Load, normalize\n data = _load_sitk_array(data_label_path[0].decode())\n data = _normalize_planes(data)\n label = _load_sitk_array(data_label_path[1].decode())\n\n # Select informative indices\n selected_indices = _get_subsample_indices(label)\n data = data[selected_indices]\n label = label[selected_indices]\n\n # Shuffle, select batches\n idx = np.arange(len(data))\n np.random.shuffle(idx)\n data = (data[idx])[:batch_size]\n label = (label[idx])[:batch_size]\n\n # Resize and normalize\n data = np.stack([_resize_slice(data_slice) for data_slice in data], axis=0)\n data = _normalize_slice(data)\n label = np.stack([_resize_slice(label_slice, label=True) for label_slice in label], axis=0)\n label = label.astype(np.float32)\n data_label = np.stack([data, label], axis=3)\n\n return data_label\n","sub_path":"code/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":8831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"37962993","text":"# -*- coding: utf-8 -*-\n\n# Imports\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Loading the data\nfrom keras.datasets import reuters\n(x_train, y_train), (x_test, y_test) = reuters.load_data(path=\"reuters.npz\",num_words=10000,skip_top=0,maxlen=None,test_split=0.2,seed=113,start_char=1,oov_char=2,index_from=3)\n\n# Understanding the data\nprint(\"The number of training samples\",len(x_train))\nprint(\"The number of testing samples\",len(x_test))\nprint(\"The shape of training samples array\",np.shape(x_train))\nprint(\"The shape of training samples labels\", np.shape(y_train))\nprint(\"First element in x_train ,its type :\",type(x_train[0]),\"it's shape :\",np.shape(x_train[0]))\n\n# Data Visulization\n\n# A dictionary mapping words to an integer index\nword_index = reuters.get_word_index()\nreverse_word_index = dict([(value, key) for (key, value) in word_index.items()]) # Reversed dictionary\n\ndef decode_review(text):\n return ' '.join([reverse_word_index.get(i, '?') for i in text])\n\n## Viewing the review's\nprint('\\nFirst Review \\n')\nprint(decode_review(x_train[0]))\nprint('\\nIts label :',y_train[0])\n\nprint('\\nSecond Review \\n')\nprint(decode_review(x_train[1]))\nprint('\\nIts label :',y_train[1])\n\n# Data Preprocessing\n\n##Varibles\nclasses = 46\n\n## Padding\nfrom keras.preprocessing.sequence import pad_sequences\nx_train_padded = pad_sequences(x_train,value=0,padding='post',maxlen=256)\nx_test_padded = pad_sequences(x_test,value=0,padding='post',maxlen=256)\n\n## Creating sparse vector representation\nfrom keras.utils import to_categorical\ny_train_sparse = to_categorical(y_train,num_classes=classes)\ny_test_sparse = to_categorical(y_test,num_classes=classes)\n\n\n# Training varibles\nlearning_rate = 0.0005\nlearning_rate_decay = 0.00001\nbatch_size = 512\nepochs = 30\n\n\n# Building the model\n# input shape is the vocabulary count used for the movie reviews (10,000 words)\nvocab_size = 10000\n\nfrom keras.models import Sequential\nfrom keras.layers import Embedding,GlobalAveragePooling1D,Dense,Dropout\nfrom keras.optimizers import Adam\n\nmodel = Sequential()\nmodel.add(Embedding(vocab_size, 512))\nmodel.add(GlobalAveragePooling1D())\nmodel.add(Dense(256, activation = 'relu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(46, activation = 'sigmoid'))\n\nmodel.summary()\n\n# optimizer\noptimizer = Adam(lr=learning_rate, beta_1=0.9, beta_2=0.999, epsilon=None, decay=learning_rate_decay, amsgrad=False)\n\n# Model Compilation\nmodel.compile(optimizer=optimizer,loss='categorical_crossentropy',metrics=['accuracy'])\n\n# Training the model\nmodel_history = model.fit(x_train_padded,y_train_sparse,epochs=epochs,batch_size=batch_size,validation_data=(x_test_padded, y_test_sparse),verbose=1)\n\n# Results\ny_pred = model.predict(x_test_padded)\n\n# Verifying the results\nprint(\"Ground truths of first 10 images in test set\",np.array(y_test[0:10]))\nprint(\"Predicted values of first 10 image in test set\",np.argmax(y_pred,axis=1))\n\nloss = model_history.history['loss']\nval_loss = model_history.history['val_loss']\nplt.plot(loss,label='train')\nplt.plot(val_loss,label='test')\nplt.title('loss Graph')\nplt.ylabel('precentage')\nplt.xlabel('epochs')\nplt.legend()\nplt.show()\n\nacc = model_history.history['acc']\nval_acc = model_history.history['val_acc']\nplt.plot(acc,label='train')\nplt.plot(val_acc,label='test')\nplt.title('Accuracy Graph')\nplt.ylabel('precentage')\nplt.xlabel('epochs')\nplt.legend()\nplt.show()\n\n\n# Visulizing the results\ny_pred = np.argmax(y_pred,axis=1)\ny_pred = pd.Series(y_pred, name='Predicted')\ny_test = pd.Series(y_test, name='Actual')\ndf_confusion = pd.crosstab(y_test,y_pred, rownames=['Actual'], colnames=['Predicted'])\nprint(df_confusion)\nplt.figure(figsize = (20,20))\nplt.xlabel('xlabel', fontsize=18)\nplt.ylabel('ylabel', fontsize=18)\nplt.title('Confusion Matrix',fontsize=20)\nsns.heatmap(df_confusion, annot=True,fmt=\"d\")\n","sub_path":"src/Reuters_newswire_topics_classification_keras_dataset.py","file_name":"Reuters_newswire_topics_classification_keras_dataset.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"533744713","text":"# Set up Amazon S3\nAWS_ACCESS_KEY_ID = \"----------------\"\nAWS_SECRET_ACCESS_KEY = \"------------\"\nAWS_STORAGE_BUCKET_NAME = \"s3.mysite.com\"\nAWS_S3_CUSTOM_DOMAIN = \"s3.mysite.com\"\nAWS_REDUCED_REDUNDANCY = False # We enable this server-wide on our staging server's S3 buckets\nAWS_PRELOAD_METADATA = True # You want this to be on!\nAWS_S3_SECURE_URLS = False\nAWS_HEADERS = { 'Cache-Control': 'max-age=2592000' }\nAWS_QUERYSTRING_AUTH = False\n\n\nMY_DEFAULT_STORAGE = 'myapp.s3.storage.S3BotoStorage' # Used below\nDEFAULT_FILE_STORAGE = MY_DEFAULT_STORAGE\nCOMPRESS_STORAGE = MY_DEFAULT_STORAGE # use with django-compressor\nSTATICFILES_STORAGE = MY_DEFAULT_STORAGE # use with django-staticfiles\nFILER_PUBLICMEDIA_STORAGE = 'myapp.examples.example_prefixes.filer_storage_s3' # user with django-filer\n# Finally, we want to use reduced redundancy storage for all thumbnails:\nFILER_PUBLICMEDIA_THUMBNAIL_STORAGE = 'myapp.examples.example_prefixes.filer_thumb_storage_s3'\nTHUMBNAIL_DEFAULT_STORAGE = 'myapp.examples.example_prefixes.S3BotoStorageReducedRedundancy'\n","sub_path":"s3storage/examples/example_settings.py","file_name":"example_settings.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"6477794","text":"from __future__ import absolute_import, division, print_function\nimport os\nimport hashlib\nfrom cbopensource.tools.eventduplicator.utils import get_process_id, json_encode\nimport json\nimport codecs\nfrom collections import defaultdict\nimport logging\n\n__author__ = 'jgarman'\n\nlog = logging.getLogger(__name__)\n\n\ndef get_process_path(proc_guid):\n key = hashlib.md5(str(proc_guid).encode('utf8')).hexdigest()\n return os.path.join(key[:2].upper(), '%s.json' % proc_guid)\n\n\ndef get_binary_path(md5sum):\n return os.path.join(md5sum[:2].upper(), '%s.json' % md5sum.lower())\n\n\nclass FileInputSource(object):\n def __init__(self, pathname):\n self.pathname = pathname\n self.reader = codecs.getreader(\"utf-8\")\n\n def get_version(self):\n return open(os.path.join(self.pathname, 'VERSION'), 'r').read()\n\n def get_process_docs(self, query_filter=None):\n # TODO: the query_filter is a code smell... we should push the traversal code into the Source?\n if query_filter:\n return\n\n for root, dirs, files in os.walk(os.path.join(self.pathname, 'procs')):\n for fn in files:\n yield json.load(self.reader(open(os.path.join(root, fn), 'rb')))\n\n def get_feed_doc(self, feed_key):\n pathname = os.path.join(self.pathname, 'feeds', '%s.json' % feed_key)\n try:\n return json.load(self.reader(open(pathname, 'rb')))\n except Exception as e:\n log.warning(\"Could not open feed document: %s - %s\" % (pathname, str(e)))\n return None\n\n def get_feed_metadata(self, feed_id):\n pathname = os.path.join(self.pathname, 'feeds', '%s.json' % feed_id)\n try:\n return json.load(self.reader(open(pathname, 'rb')))\n except Exception as e:\n log.warning(\"Could not open feed metadata: %s - %s\" % (pathname, str(e)))\n return None\n\n def get_binary_doc(self, md5sum):\n md5sum = md5sum.lower()\n pathname = os.path.join(self.pathname, 'binaries', get_binary_path(md5sum))\n try:\n return json.load(self.reader(open(pathname, 'rb')))\n except Exception as e:\n log.warning(\"Could not open binary document: %s - %s\" % (pathname, str(e)))\n return None\n\n def get_sensor_doc(self, sensor_id):\n pathname = os.path.join(self.pathname, 'sensors', '%d.json' % sensor_id)\n try:\n return json.load(open(os.path.join(self.pathname, 'sensors', '%d.json' % sensor_id), 'r'))\n except Exception as e:\n log.warning(\"Could not open sensor document: %s - %s\" % (pathname, str(e)))\n return None\n\n def connection_name(self):\n return self.pathname\n\n def cleanup(self):\n pass\n\n\nclass FileOutputSink(object):\n def __init__(self, pathname):\n self.pathname = pathname\n os.makedirs(pathname, 0o755)\n\n os.makedirs(os.path.join(pathname, 'procs'), 0o755)\n os.makedirs(os.path.join(pathname, 'binaries'), 0o755)\n os.makedirs(os.path.join(pathname, 'sensors'), 0o755)\n os.makedirs(os.path.join(pathname, 'feeds'), 0o755)\n\n # TODO: only create the directories we need\n for dirname in ['procs', 'binaries']:\n for segment in ['%02X' % x for x in range(0, 256)]:\n os.makedirs(os.path.join(pathname, dirname, segment), 0o755)\n\n self.written_docs = defaultdict(int)\n self.new_metadata = defaultdict(list)\n\n def output_process_doc(self, doc_content):\n proc_guid = get_process_id(doc_content)\n pathname = os.path.join(self.pathname, 'procs', get_process_path(proc_guid))\n if os.path.exists(pathname):\n log.warning('process %s already existed, writing twice' % proc_guid)\n self.format_date_fields(doc_content)\n open(os.path.join(self.pathname, 'procs', get_process_path(proc_guid)), 'w').write(json_encode(doc_content))\n self.written_docs['proc'] += 1\n\n def format_date_fields(self, doc_content):\n for date_field in ['last_update', 'start', 'server_added_timestamp', 'last_server_update']:\n if (date_field in doc_content) and ('.' not in doc_content[date_field]):\n # Change a date string like 2015-11-10T19:54:45Z to 2015-11-10T19:54:45.000Z\n doc_content[date_field] = '{}.000Z'.format(doc_content[date_field][:-1])\n\n def output_binary_doc(self, doc_content):\n md5sum = doc_content.get('md5').lower()\n open(os.path.join(self.pathname, 'binaries', get_binary_path(md5sum)), 'w').write(json_encode(doc_content))\n self.written_docs['binary'] += 1\n\n def output_sensor_info(self, doc_content):\n open(os.path.join(self.pathname, 'sensors', '%s.json' % doc_content['sensor_info']['id']), 'w').\\\n write(json_encode(doc_content))\n self.new_metadata['sensor'].append(doc_content['sensor_info']['computer_name'])\n\n def output_feed_doc(self, doc_content):\n open(os.path.join(self.pathname, 'feeds', '%s:%s.json' % (doc_content['feed_name'], doc_content['id'])), 'w').\\\n write(json_encode(doc_content))\n self.written_docs['feed'] += 1\n\n def output_feed_metadata(self, doc_content):\n open(os.path.join(self.pathname, 'feeds', '%s.json' % (doc_content['id'],)), 'w').\\\n write(json_encode(doc_content))\n self.new_metadata['feed'].append(doc_content['name'])\n\n def set_data_version(self, version):\n if type(version) != str:\n version = version.decode('utf8')\n open(os.path.join(self.pathname, 'VERSION'), 'w').write(version)\n return True\n\n def cleanup(self):\n pass\n\n def connection_name(self):\n return self.pathname\n\n def report(self):\n report_data = \"Documents saved to %s by type:\\n\" % (self.pathname,)\n for key in self.written_docs.keys():\n report_data += \" %8s: %d\\n\" % (key, self.written_docs[key])\n for key in self.new_metadata.keys():\n report_data += \"New %ss created in %s:\\n\" % (key, self.pathname)\n for value in self.new_metadata[key]:\n report_data += \" %s\\n\" % value\n\n return report_data\n","sub_path":"cbopensource/tools/eventduplicator/file_endpoint.py","file_name":"file_endpoint.py","file_ext":"py","file_size_in_byte":6176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"9183400","text":"import os\nimport sys\nfrom typing import List\nfrom typing import Tuple\n\nimport pkg_resources\nimport setuptools.command.build_py\nimport setuptools.command.test\nfrom grpc_tools import protoc\nfrom setuptools import Command\nfrom setuptools import find_packages\nfrom setuptools import setup\n\nfrom squeaknode import __version__\n\nPACKAGE_DIRECTORIES = {\n '': '.',\n}\n\n\nclass BuildPyCommand(setuptools.command.build_py.build_py):\n \"\"\"Custom build command.\"\"\"\n\n def run(self):\n self.run_command('build_proto_modules')\n setuptools.command.build_py.build_py.run(self)\n\n\ndef build_package_protos(package_root, strict_mode=False):\n proto_files = []\n inclusion_root = os.path.abspath(package_root)\n for root, _, files in os.walk(inclusion_root):\n for filename in files:\n if filename.endswith('.proto'):\n proto_files.append(os.path.abspath(os.path.join(root,\n filename)))\n\n well_known_protos_include = pkg_resources.resource_filename(\n 'grpc_tools', '_proto')\n\n for proto_file in proto_files:\n command = [\n 'grpc_tools.protoc',\n '--proto_path={}'.format(inclusion_root),\n '--proto_path={}'.format(well_known_protos_include),\n '--python_out={}'.format(inclusion_root),\n '--grpc_python_out={}'.format(inclusion_root),\n '--mypy_out={}'.format(inclusion_root),\n ] + [proto_file]\n if protoc.main(command) != 0:\n if strict_mode:\n raise Exception('error: {} failed'.format(command))\n else:\n sys.stderr.write('warning: {} failed'.format(command))\n\n\nclass BuildPackageProtos(Command):\n \"\"\"Command to generate project *_pb2.py modules from proto files.\"\"\"\n\n description = 'build grpc protobuf modules'\n user_options: List[Tuple[str, str, str]] = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n # import grpc_tools.command\n # grpc_tools.command.build_package_protos('.')\n build_package_protos('.')\n\n\nsetup(\n name=\"squeaknode\",\n version=__version__,\n url=\"https://github.com/yzernik/squeaknode\",\n description=\"Server for squeak protocol.\",\n packages=find_packages(),\n # package_dir=PACKAGE_DIRECTORIES,\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'squeaklib>=0.5.3',\n 'importlib_resources',\n 'argparse',\n 'googleapis-common-protos',\n 'grpcio>=1.34.0',\n 'grpcio-tools',\n 'mypy-protobuf',\n 'psycopg2',\n 'requests',\n 'SQLAlchemy',\n 'Flask',\n 'protobuf',\n 'flask-login',\n 'Flask-WTF',\n 'flask-cors',\n 'alembic',\n ],\n extras_require={\"test\": [\"pytest\", \"coverage\"]},\n entry_points={\n 'console_scripts': [\n 'squeaknode = squeaknode.main:main',\n ],\n },\n cmdclass={\n 'build_proto_modules': BuildPackageProtos,\n 'build_py': BuildPyCommand,\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"263382000","text":"from django.contrib.auth import login\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.shortcuts import render, redirect\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.template.loader import render_to_string\nfrom .forms import SignUpForm\nfrom .tokens import account_activation_token\nfrom django.contrib.auth.models import User\nfrom .models import Profile, Country, City\n\n\n@login_required\ndef home(request):\n return render(request, 'home.html')\n\n\ndef signup(request):\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n user = User.objects.create_user(username=request.POST['username'], email=request.POST['email'],\n password=request.POST['password1'])\n user.save()\n Profile.objects.create(user=user, user_country=Country.objects.get(pk=request.POST['user_country']),\n user_city=City.objects.get(pk=request.POST['user_city']),\n birthday=request.POST['birthday']\n )\n\n # user.save()\n\n current_site = get_current_site(request)\n subject = 'Activate Your Account'\n message = render_to_string('accounts/html/account_activation_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'token': account_activation_token.make_token(user),\n })\n user.email_user(subject, message)\n return redirect('account_activation_sent')\n else:\n form = SignUpForm()\n return render(request, 'accounts/html/signup.html', {'form': form})\n\n\ndef activate(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except (TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.profile.email_confirmed = True\n user.save()\n login(request, user)\n return redirect('posts')\n else:\n return render(request, 'accounts/html/account_activation_invalid.html')\n\n\ndef account_activation_sent(request):\n return render(request, 'accounts/html/account_activation_sent.html')","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"466764958","text":"APPLE = 'apple'\nPEAR = 'pear'\nPEACH = 'peach'\nCHERRY = 'cherry'\n\nclass NoFruits(Exception):\n pass\n\nclass Tree(object):\n\n def __init__(self, fruit_type, fruits):\n self.fruit_type = fruit_type\n self.fruits = list(fruits)\n\n def copy(self):\n return Tree(self.fruit_type, self.fruits)\n\n def pick_ripest(self):\n if not self.fruits:\n raise NoFruits\n ripest = sorted(self.fruits)[-1]\n self.fruits.remove(ripest)\n return ripest\n\n def pick_ripests(self, n):\n ripests = sorted(self.fruits)[-n:]\n for fruit in ripests:\n self.fruits.remove(fruit)\n return ripests\n\n def __repr__(self):\n return 'Tree({self.fruit_type}, {self.fruits})'.format(self=self)\n ","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"189767769","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import to_rgb\nfrom matplotlib import cm\nfrom tqdm import tqdm\n\nfrom typing import Dict, Sequence\n\n\ndef plot_video_with_sphere_cylinder(\n rods_history: Sequence[Dict],\n cylinders_history: Sequence[Dict],\n sphere_history: Sequence[Dict],\n video_name=\"video.mp4\",\n fps=60,\n step=1,\n **kwargs,\n): # (time step, x/y/z, node)\n import matplotlib.animation as manimation\n from mpl_toolkits.mplot3d import proj3d, Axes3D\n\n plt.rcParams.update({\"font.size\": 22})\n\n # Cylinders first\n n_visualized_cylinders = len(cylinders_history)\n # n_cyl, n_time, 3,\n # cylinder_com = np.array([x[\"com\"] for x in cylinders_history])\n # n_cyl floats\n cylinder_heights = [x[\"height\"] for x in cylinders_history]\n cylinder_radii = [x[\"radius\"] for x in cylinders_history]\n # sim_time = np.array(cylinders_history[0][\"time\"])\n sim_time = np.array(rods_history[0][\"time\"])\n\n cylinder_cmap = cm.get_cmap(\"Spectral\", n_visualized_cylinders)\n\n # Rods next\n n_visualized_rods = len(rods_history)\n\n # TODO : Should be a generator rather a function\n rod_history_unpacker = lambda rod_idx, t_idx: (\n rods_history[rod_idx][\"position\"][time_idx],\n rods_history[rod_idx][\"radius\"][t_idx],\n )\n com_history_unpacker = lambda rod_idx, t_idx: rods_history[rod_idx][\"com\"][time_idx]\n cylinder_history_unpacker = lambda cyl_idx, t_idx: (\n cylinders_history[cyl_idx][\"com\"][t_idx]\n - 0.5\n * cylinder_heights[cyl_idx]\n * cylinders_history[cyl_idx][\"direction\"].reshape(3),\n cylinder_radii[cyl_idx],\n cylinder_heights[cyl_idx],\n )\n\n # Spheres next\n n_visualized_spheres = len(sphere_history) # should be one for now\n # Sphere radius\n # sphere_radii = [x[\"radius\"] for x in sphere_history]\n # Sphere info\n sphere_history_unpacker = lambda sph_idx, t_idx: (\n sphere_history[sph_idx][\"position\"][t_idx],\n sphere_history[sph_idx][\"radius\"][t_idx],\n )\n # color mapping\n sphere_cmap = cm.get_cmap(\"Spectral\", n_visualized_spheres)\n\n print(\"Plotting videos!\")\n FFMpegWriter = manimation.writers[\"ffmpeg\"]\n metadata = dict(title=\"Movie Test\", artist=\"Matplotlib\", comment=\"Movie support!\")\n writer = FFMpegWriter(fps=fps, metadata=metadata)\n dpi = kwargs.get(\"dpi\", 100)\n\n def make_data_for_cylinder_along_z(cstart, cradius, cheight):\n center_x, center_y = cstart[0], cstart[2]\n z = np.linspace(0, cheight, 3)\n theta = np.linspace(0, 2 * np.pi, 25)\n theta_grid, z_grid = np.meshgrid(theta, z)\n x_grid = cradius * np.cos(theta_grid) + center_x\n y_grid = cradius * np.sin(theta_grid) + center_y\n z_grid += cstart[1]\n return [x_grid, y_grid, z_grid]\n\n xlim = kwargs.get(\"x_limits\", (-1.0, 1.0))\n ylim = kwargs.get(\"y_limits\", (-1.0, 1.0))\n zlim = kwargs.get(\"z_limits\", (-0.05, 1.0))\n difference = lambda x: x[1] - x[0]\n max_axis_length = max(difference(xlim), difference(ylim))\n # The scaling factor from physical space to matplotlib space\n scaling_factor = (2 * 0.1) / max_axis_length # Octopus head dimension\n scaling_factor *= 2.6e3 # Along one-axis\n\n if kwargs.get(\"vis3D\", True):\n fig = plt.figure(1, figsize=(10, 8), frameon=True, dpi=dpi)\n ax = plt.axes(projection=\"3d\")\n ax.set_xlabel(\"x\")\n ax.set_ylabel(\"y\")\n ax.set_zlabel(\"z\")\n\n ax.set_xlim(*xlim)\n ax.set_ylim(*ylim)\n ax.set_zlim(*zlim)\n ax.view_init(elev=20, azim=180)\n\n # Surfaces (cylinders, spheres) first\n time_idx = 0\n cylinder_surfs = [None for _ in range(n_visualized_cylinders)]\n\n for cylinder_idx in range(n_visualized_cylinders):\n XC, YC, ZC = make_data_for_cylinder_along_z(\n *cylinder_history_unpacker(cylinder_idx, time_idx)\n )\n cylinder_surfs[cylinder_idx] = ax.plot_surface(\n XC, YC, ZC, color=cylinder_cmap(cylinder_idx), alpha=1.0\n )\n\n # Rods next\n rod_scatters = [None for _ in range(n_visualized_rods)]\n\n for rod_idx in range(n_visualized_rods):\n inst_position, inst_radius = rod_history_unpacker(rod_idx, time_idx)\n inst_position = 0.5 * (inst_position[..., 1:] + inst_position[..., :-1])\n rod_scatters[rod_idx] = ax.scatter(\n inst_position[0],\n inst_position[2],\n inst_position[1],\n s=np.pi * inst_radius ** 2 * 1e4,\n )\n\n # sphere surfaces\n sphere_artists = [None for _ in range(n_visualized_spheres)]\n for sphere_idx in range(n_visualized_spheres):\n sphere_position, sphere_radius = sphere_history_unpacker(\n sphere_idx, time_idx\n )\n sphere_artists[sphere_idx] = ax.scatter(\n sphere_position[0],\n sphere_position[2],\n sphere_position[1],\n s=np.pi * (scaling_factor * sphere_radius) ** 2,\n )\n # sphere_radius,\n # color=sphere_cmap(sphere_idx),)\n ax.add_artist(sphere_artists[sphere_idx])\n\n # min_limits = global_rot_mat @ np.array([0.0, -0.5 * cylinder_height, 0.0])\n # min_limits = -np.abs(min_limits)\n # max_limits = min_limits + cylinder_height\n\n with writer.saving(fig, video_name, dpi):\n with plt.style.context(\"seaborn-whitegrid\"):\n for time_idx in tqdm(range(0, sim_time.shape[0], int(step))):\n for rod_idx in range(n_visualized_rods):\n inst_position, inst_radius = rod_history_unpacker(\n rod_idx, time_idx\n )\n inst_position = 0.5 * (\n inst_position[..., 1:] + inst_position[..., :-1]\n )\n rod_scatters[rod_idx]._offsets3d = (\n inst_position[0],\n inst_position[2],\n inst_position[1],\n )\n rod_scatters[rod_idx].set_sizes(np.pi * inst_radius ** 2 * 1e4)\n\n for cylinder_idx in range(n_visualized_cylinders):\n XC, YC, ZC = make_data_for_cylinder_along_z(\n *cylinder_history_unpacker(cylinder_idx, time_idx)\n )\n cylinder_surfs[cylinder_idx].remove()\n cylinder_surfs[cylinder_idx] = ax.plot_surface(\n XC, YC, ZC, color=cylinder_cmap(cylinder_idx), alpha=1.0\n )\n\n for sphere_idx in range(n_visualized_spheres):\n sphere_position, _ = sphere_history_unpacker(\n sphere_idx, time_idx\n )\n sphere_artists[sphere_idx]._offsets3d = (\n sphere_position[0],\n sphere_position[2],\n sphere_position[1],\n )\n\n writer.grab_frame()\n\n # Delete all variables within scope\n # Painful\n del (rod_scatters, cylinder_surfs)\n del (time_idx,) # rod_idx, cylinder_idx\n # del inst_position, inst_radius\n # del XC, YC, ZC\n\n # Be a good boy and close figures\n # https://stackoverflow.com/a/37451036\n # plt.close(fig) alone does not suffice\n # See https://github.com/matplotlib/matplotlib/issues/8560/\n plt.close(plt.gcf())\n\n if kwargs.get(\"vis2D\", True):\n from matplotlib.patches import Circle\n\n fig = plt.figure(2, figsize=(10, 8), frameon=True, dpi=dpi)\n ax = fig.add_subplot(111)\n ax.set_xlim(*xlim)\n ax.set_ylim(*ylim)\n\n time_idx = 0\n rod_lines = [None for _ in range(n_visualized_rods)]\n rod_com_lines = [None for _ in range(n_visualized_rods)]\n rod_scatters = [None for _ in range(n_visualized_rods)]\n for rod_idx in range(n_visualized_rods):\n inst_position, inst_radius = rod_history_unpacker(rod_idx, time_idx)\n inst_position = 0.5 * (inst_position[..., 1:] + inst_position[..., :-1])\n rod_lines[rod_idx] = ax.plot(\n inst_position[0], inst_position[2], \"r\", lw=0.5\n )[0]\n inst_com = com_history_unpacker(rod_idx, time_idx)\n rod_com_lines[rod_idx] = ax.plot(inst_com[0], inst_com[2], \"k--\", lw=2.0)[0]\n\n rod_scatters[rod_idx] = ax.scatter(\n inst_position[0],\n inst_position[2],\n s=np.pi * (scaling_factor * inst_radius) ** 2,\n )\n\n # min_limits = np.array([0.0, -0.5 * cylinder_height, 0.0])\n # max_limits = min_limits + cylinder_height\n\n # ax.set_xlim([min_limits[0], max_limits[0]])\n # ax.set_ylim([min_limits[1], max_limits[1]])\n\n cylinder_artists = [None for _ in range(n_visualized_cylinders)]\n for cylinder_idx in range(n_visualized_cylinders):\n cylinder_origin, cylinder_radius, _ = cylinder_history_unpacker(\n cylinder_idx, time_idx\n )\n\n cylinder_artists[cylinder_idx] = Circle(\n (cylinder_origin[0], cylinder_origin[2]),\n cylinder_radius,\n color=cylinder_cmap(cylinder_idx),\n )\n ax.add_artist(cylinder_artists[cylinder_idx])\n\n sphere_artists = [None for _ in range(n_visualized_spheres)]\n for sphere_idx in range(n_visualized_spheres):\n sphere_position, sphere_radius = sphere_history_unpacker(\n sphere_idx, time_idx\n )\n sphere_artists[sphere_idx] = Circle(\n (sphere_position[0], sphere_position[2]),\n sphere_radius,\n color=sphere_cmap(sphere_idx),\n )\n ax.add_artist(sphere_artists[sphere_idx])\n\n ax.set_aspect(\"equal\")\n video_name = \"2D_\" + video_name\n\n with writer.saving(fig, video_name, dpi):\n with plt.style.context(\"seaborn-whitegrid\"):\n for time_idx in tqdm(range(0, sim_time.shape[0], int(step))):\n\n for rod_idx in range(n_visualized_rods):\n inst_position, inst_radius = rod_history_unpacker(\n rod_idx, time_idx\n )\n inst_position = 0.5 * (\n inst_position[..., 1:] + inst_position[..., :-1]\n )\n\n rod_lines[rod_idx].set_xdata(inst_position[0])\n rod_lines[rod_idx].set_ydata(inst_position[2])\n\n com = com_history_unpacker(rod_idx, time_idx)\n rod_com_lines[rod_idx].set_xdata(com[0])\n rod_com_lines[rod_idx].set_ydata(com[2])\n\n # rod_scatters[rod_idx].set_offsets(inst_position[:2].T)\n rod_scatters[rod_idx].set_offsets(\n np.vstack((inst_position[0], inst_position[2])).T\n )\n rod_scatters[rod_idx].set_sizes(\n np.pi * (scaling_factor * inst_radius) ** 2\n )\n\n for cylinder_idx in range(n_visualized_cylinders):\n cylinder_origin, _, _ = cylinder_history_unpacker(\n cylinder_idx, time_idx\n )\n cylinder_artists[cylinder_idx].center = (\n cylinder_origin[0],\n cylinder_origin[2],\n )\n\n for sphere_idx in range(n_visualized_spheres):\n sphere_position, _ = sphere_history_unpacker(\n sphere_idx, time_idx\n )\n sphere_artists[sphere_idx].center = (\n sphere_position[0],\n sphere_position[2],\n )\n\n writer.grab_frame()\n\n # Be a good boy and close figures\n # https://stackoverflow.com/a/37451036\n # plt.close(fig) alone does not suffice\n # See https://github.com/matplotlib/matplotlib/issues/8560/\n plt.close(plt.gcf())\n","sub_path":"Case3/ReacherSoft_Case3_main-text/post_processing.py","file_name":"post_processing.py","file_ext":"py","file_size_in_byte":12559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"290233960","text":"#!/usr/bin/env python3\n\n\"\"\"\nScript for creating the various files required for import of data into \nthe TextGrid Repository. \n\nThe script requires the metadata file produced in the previous step and\nthe full XML-TEI files to be uploaded. \n\nUsage: The only parameter you should need to adjust is the path\nencoded in the variable \"collection\" to be worked on. \nFile preparation is one one language at a time. \n\nOutput: The script writes a collection of files to the output folder for\nthe language collection concerned. \n\nPlease send feedback to Christof at \"schoech@uni-trier.de\". \n\"\"\"\n\n\n\n\n# === Import statements ===\n\nimport os\nimport re\nimport glob\nfrom os.path import join\nfrom os.path import basename\nimport pandas as pd\nfrom collections import Counter\nimport lxml.etree as ET\n\n\n\n# === Files and folders ===\n\ncollection = \"ELTeC-fra\"\nlevel = \"level1\"\n\n\n\n# === Helper functions ===\n\n\ndef read_metadatafile(metadatafile): \n with open(metadatafile, \"r\", encoding=\"utf8\") as infile: \n metadata = pd.read_csv(infile, sep=\"\\t\", index_col=\"xmlid\")\n #print(metadata.head())\n return metadata\n\n\ndef read_template(templateid):\n templatefile = join(\"templates\", templateid)\n with open(templatefile, \"r\", encoding=\"utf8\") as infile: \n template = infile.read()\n return template\n\n\ndef save_template(template, language, templatefile): \n outfolder = join(\"output\", language)\n if not os.path.exists(outfolder): \n os.makedirs(outfolder)\n with open(join(\"output\", templatefile), \"w\", encoding=\"utf8\") as outfile: \n outfile.write(template)\n\n\n\n# === Functions to fill template files: one per language ===\n\n\ndef fill_aggregation_meta(language):\n templatefile = \"-LLL.aggregation.meta\"\n template = read_template(join(templatefile))\n template = re.sub(\"LLL\", language, template)\n templatefile = re.sub(\"LLL\", language, templatefile)\n save_template(template, language, templatefile)\n \n\n# TODO: templatefile = \"LLL.aggregation\"\n\n\n\n# === Functions to fill template files: one per text ===\n\n\ndef fill_LLLNNN_edition_meta(xmlfile, counter, language, metadata):\n # Read the empty templatefile\n templatefile = \"LLLNNN.edition.meta\"\n template = read_template(join(\"LLL\", templatefile))\n template = re.sub(\"LLL\", language, template)\n # Find information for the template\n identifier, rest = basename(xmlfile).split(\"_\")\n author = metadata.loc[identifier, \"author\"]\n title = metadata.loc[identifier, \"title\"]\n # Fill information into the template\n template = re.sub(\"LLL\", language, template) \n template = re.sub(\"NNN\", counter, template) \n template = re.sub(\"#author#\", author, template) \n template = re.sub(\"#title#\", title, template) \n # Adapt the templatefile's filename\n templatefile = re.sub(\"LLL\", language, templatefile)\n templatefile = re.sub(\"NNN\", counter, templatefile)\n templatefile = join(language, templatefile)\n # Save the individual, filled-in templatefile\n save_template(template, language, templatefile)\n\n\n\n# TODO: templatefile = \"LLL/LLLNNN.edition\"\n\n# TODO: templatefile = \"LLL/LLLNNN/-LLLNNN.xml\"\n\n# TODO: templatefile = \"LLL/LLLNNN/-LLLNNN.xml.meta\"\n\n# TODO: templatefile = \"LLL/LLLNNN/LLLNNN.work\"\n\n# TODO: templatefile = \"LLL/LLLNNN/LLLNNN.work.meta\"\n\n\n\n# === Main ===\n\n\ndef main(collection, level):\n language = collection[-3:].upper()\n metadatafile = join(\"metadata\", collection+\".tsv\")\n metadata = read_metadatafile(metadatafile)\n xmlfiles = join(\"input\", collection, level, \"*.xml\") \n fill_aggregation_meta(language)\n # TODO: \"fill_LLL_aggregation\"\n counter = 0\n for xmlfile in glob.glob(xmlfiles):\n counter +=1\n counter = \"{:03}\".format(counter)\n print(counter, basename(xmlfile))\n fill_LLLNNN_edition_meta(xmlfile, counter, language, metadata)\n # TODO: fill_LLL/LLLNNN.edition\n # TODO: fill_LLL/LLLNNN__LLLNNN_xml\n # TODO: fill_LLL_LLLNNN__LLLNNN_xml_meta\n # TODO: fill_LLL_LLLNNN_LLLNNN_work\n # TODO: fill_LLL_LLLNNN_LLLNNN_work_meta\n counter = int(counter)\n\nmain(collection, level)\n\n\n","sub_path":"2020-June/2_build_tgrfiles.py","file_name":"2_build_tgrfiles.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"293197789","text":"# tk test\nimport tkinter as tk\nimport tkinter.messagebox as tkmsgbox\n\nroot = tk.Tk()\nroot.title(\"Tkinter Test\")\nroot.geometry(\"300x300\")\n\n\ndef ok():\n tkmsgbox.showinfo( \"CallBack\", \"Hello!!!\")\n\nb = tk.Button(root, text =\"Click ME!!\" , command = ok)\nb.pack()\n\nB = tk.Button(root, text =\"Exit\" , command = root.destroy)\nB.pack()\n\nroot.mainloop()","sub_path":"Bin/tk-test.py","file_name":"tk-test.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"547843719","text":"import sys\r\nimport io\r\nimport urllib.request as dw\r\n\r\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')\r\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')\r\n\r\n\r\nimgUrl = \"http://cafefiles.naver.net/20150404_41/onehodang2_1428121325007MWF8c_JPEG/10.jpg\"\r\nhtmlURL = \"http://google.com\"\r\n\r\nsavePath1 = \"C:/section2/test1.jpg\"\r\nsavePath2 = \"C:/section2/index.html\"\r\n\r\nf = dw.urlopen(imgUrl).read()\r\nsaveFile1 = open(savePath1,'wb') # w : write, r : read, a:add\r\nsaveFile1.write(f)\r\nsaveFile1.close() # 무조건 해봐야함 리소스 복귀함. 메모리낭비 ㄴㄴ!\r\n\r\n\r\n#위의 구문보다 더 좋음 왜냐하면 리소스를 자동적으로 반납하는 기능이 있음.\r\nf2 = dw.urlopen(htmlURL).read()\r\nwith open(savePath2,'wb') as saveFile2:\r\n saveFile2.write(f2)\r\n\r\n\r\n\r\n\r\nprint(\"파이썬 버전\")\r\nprint(\"다운로드 완료\")\r\n","sub_path":"section2/download2-2.py","file_name":"download2-2.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"577072668","text":"# coding:utf-8\nimport json\nimport random\nimport re\nimport time\n\nimport chardet\nimport requests\nfrom lxml import etree\nfrom lxml.etree import XMLSyntaxError\n\nfrom bank.utils.Comm import CommSession\n\n\nclass IndustrialBank():\n\n def __init__(self):\n self.charset_re = re.compile(r']', flags=re.I)\n self.pragma_re = re.compile(r']', flags=re.I)\n self.index_url = 'https://www.cib.com.cn/cn/index.html'\n self.session = self.instance_session(self.index_url)\n\n def _coding(self, response):\n if self.charset_re.findall(response.text):\n response.encoding = self.charset_re.findall(response.text)[0]\n elif self.pragma_re.findall(response.text):\n response.encoding = self.charset_re.findall(response.text)[0]\n else:\n temp = chardet.detect(response.content)\n response.encoding = temp['encoding']\n return response\n\n def _get(self, url, timeout=30, method='get', post_data=None, retry=3):\n \"\"\"\n 网页下载\n :param url:\n :return:resp\n :rtype: requests.Response\n \"\"\"\n time.sleep(random.randint(2, 4))\n if method == 'get':\n for i in range(retry):\n try:\n resp = self.session.get(url=url, timeout=timeout)\n if resp.status_code // 100 == 2:\n return resp\n except requests.Timeout:\n continue\n raise requests.RequestException('requests error {}'.format(url))\n elif method == 'post' and post_data is not None:\n for i in range(retry):\n try:\n resp = self.session.post(url=url, data=json.dumps(post_data), allow_redirects=True, timeout=timeout)\n if resp.status_code == 200:\n return resp\n except requests.Timeout:\n continue\n raise requests.RequestException('requests error {}'.format(url))\n else:\n raise ValueError('func args error')\n\n @staticmethod\n def content2tree(response):\n if isinstance(response, requests.Response):\n return etree.HTML(response.text)\n else:\n try:\n return etree.HTML(response)\n except XMLSyntaxError as error:\n print(error)\n return response\n\n @staticmethod\n def instance_session(index_url=None):\n session = CommSession(verify=True).session(index_url) if index_url else CommSession(verify=True).session()\n return session\n\n def parse_data(self, response, keys_xpath):\n html = self.content2tree(response)\n xpath_table, xpath_tr, xpath_td = keys_xpath.pop('tables'), keys_xpath.pop('tr'), keys_xpath.pop('td')\n tables = html.xpath(xpath_table)\n for table in tables:\n titles = table.xpath(keys_xpath.get('titles'))\n for tr in table.xpath(xpath_tr):\n data = {}\n for index, title in enumerate(titles):\n try:\n data[''.join(''.join(title.xpath('.//test()')).split())] = ''.join(\n ''.join(tr.xpath(xpath_td)[index].xpath('.//test()')).split())\n except Exception as e:\n print(e.message)\n # self._save_data(data)\n self._data_format(data)\n\n @staticmethod\n def _save_data(data, url=None, source=None):\n temp = json.dumps(data, ensure_ascii=False, encoding='u8')\n fp.write(temp.encode('u8') + '\\n')\n fp.flush()\n print(temp)\n\n @staticmethod\n def final_yield(data, final_data):\n final_yield = data.get(u'客户年化参考净收益率', u'')\n final_yield_1 = data.get(u'比较基准')\n final_yield_2 = data.get(u'业绩比较基准')\n if final_yield:\n final_data['lowest_yield'] = final_yield if '%' in final_yield else ''\n final_data['highest_yield'] = data.get(u'大额客户参考净收益率', u'') if data.get(u'大额客户参考净收益率', u'') else final_data[\n 'lowest_yield']\n elif final_yield_1:\n if '-' in final_yield_1:\n final_data['highest_yield'] = final_yield_1.split('-')[1] if '-' in final_yield_1 else final_yield_1\n final_data['lowest_yield'] = final_yield_1.split('-')[\n 0] + '%' if '-' in final_yield_1 else final_yield_1\n else:\n final_data['highest_yield'] = final_data['lowest_yield'] = final_yield_1\n elif final_yield_2:\n if '-' in final_yield_2:\n final_data['highest_yield'] = final_yield_2.split('-')[1] if '-' in final_yield_2 else final_yield_2\n final_data['lowest_yield'] = final_yield_2.split('-')[\n 0] + '%' if '-' in final_yield_2 else final_yield_2\n else:\n final_data['highest_yield'] = final_data['lowest_yield'] = final_yield_2\n else:\n final_data['highest_yield'] = final_data['lowest_yield'] = ''\n\n def _data_format(self, data):\n \"\"\"\n\n :param data:\n :param final_data:\n :return:\n \"\"\"\n if data.iteritems().next()[0] != data.iteritems().next()[1]:\n final_data = {u'issue_bank': u'兴业银行'}\n final_data['product_name'] = data.get(u'产品名称')\n final_data['sales_start_date'] = data.get(u'募集起始日', u'').replace('/', '-') + ' 00:00:00' if data.get(\n u'募集起始日', u'') else ''\n final_data['sales_end_date'] = data.get(u'募集截止日', u'').replace('/', '-') + ' 00:00:00' if data.get(u'募集截止日',\n u'') else ''\n if not final_data['sales_start_date']:\n final_data['sales_start_date'] = data.get(u'购买时间', u'')\n final_data['value_date'] = data.get(u'收益起日期', u'').replace('/', '-')\n self.final_yield(data, final_data)\n final_data['product_status'] = u'在售'\n final_data['product_term'] = data.get(u'期限(天)/投资周期', u'')\n final_data['min_purchase_amount'] = data.get(u'起购金额(元)', u'') if data.get(u'起购金额(元)', u'') else data.get(\n u'起购金额(元)', u'')\n final_data['sales_target'] = final_data.get(u'销售对象', u'')\n final_data['sales_area'] = data.get(u'销售地区', u'')\n final_data['currency'] = data.get(u'币种', u'')\n final_data['product_nature'] = data.get(u'产品类型', u'') if u'保' in data.get(u'产品类型', u'') else ''\n final_data['product_type'] = data.get(u'产品类型', u'') if u'型' in data.get(u'产品类型', u'') else ''\n final_data['file_url'] = data.get(u'产品说明', u'')\n self._save_data(final_data)\n\n def main(self):\n configs = {\n 'http://wealth.cib.com.cn/retail/onsale/index.html': {\n 'tables': '//table',\n 'titles': '//tr[1]/td',\n 'tr': './/tr',\n 'td': './td'\n },\n # 收益率需要点击产品名称 查看最新收益细则\n 'http://wealth.cib.com.cn/retail/onsale/cash.html': {\n 'tables': '//table',\n 'titles': './/tbody/tr[1]/td',\n 'tr': './/tr',\n 'td': './/td'\n },\n 'http://wealth.cib.com.cn/retail/onsale/open.html': {\n 'tables': '//table',\n 'titles': './/tbody/tr[1]/td',\n 'tr': './/tr',\n 'td': './/td'\n },\n 'http://wealth.cib.com.cn/retail/onsale/wht.html': {\n 'tables': '//table',\n 'titles': './/tbody/tr[1]/td',\n 'tr': './/tr',\n 'td': './/td'\n },\n 'http://wealth.cib.com.cn/retail/onsale/zyb.html': {\n 'tables': '//table',\n 'tr': '',\n 'td': '',\n 'titles': ''\n }\n }\n for url, keys_xpath in configs.iteritems():\n print(url)\n self.parse_data(self._get(url), keys_xpath)\n\n\nif __name__ == '__main__':\n fp = open('products0218.txt', mode='a+')\n t = IndustrialBank()\n t.main()\n fp.close()\n","sub_path":"bank/industrial_bank.py","file_name":"industrial_bank.py","file_ext":"py","file_size_in_byte":8648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"355206782","text":"\nfrom random import randint\nfrom time import sleep\nfrom openpyxl import load_workbook\nfrom bs4 import BeautifulSoup\nfrom review_extraction.utilities.utils.logger import LogJ\nimport threading\nfrom datetime import datetime\nfrom selenium import webdriver\nfrom review_extraction.utilities.xls_generator import *\nfrom review_extraction.lens import *\nfrom pathlib import Path\n\n\n\nTAG = \"www.lens.com\"\nPATH_INPUT = \"C:/Users/Prash/Desktop/Work/scrapj-new/scrapj/data/input/\"\n\n\nclass Lens():\n driver = None\n total_reviews = 0\n total_exp = 0\n start_time = ''\n end_time = ''\n params = ()\n error_logger = LogJ(TAG, \"ERROR\")\n info_logger = LogJ(TAG, \"INFO\")\n\n def __init__(self, driver, params):\n self.driver = driver\n self.params = params\n\n def extract_data(self, excel):\n wb = load_workbook(filename=PATH_INPUT + 'www.lens.com.xlsx', read_only=True)\n ws = wb[wb.get_sheet_names()[0]]\n excel.add_headers(excel.wb.active,\n [\"Title\", \"Comments\", \"Overall\", \"Comfort\", \"Vision\", \"Value for Money\", \"Author\", \"Date\",\n \"Pros\", \"Cons\", \"Original Source\",\n \"Reply from Acuvue\", \"Product Name\", \"Product Link\", \"Website\"])\n for row in ws.rows:\n for cell in row:\n if str(type(cell)).__eq__(\"\") and cell.row != 1:\n if cell.column == 1:\n print(cell.row)\n print(cell.value)\n try:\n excel.save_xls(excel.wb)\n except Exception as e:\n print(e)\n self.total_exp += 1\n # url_to_crawl = \"http://www.visiondirect.co.uk/brand/acuvue-contact-lenses/1-day-acuvue-moist\"\n # self.get_page(url_to_crawl)\n if cell.value is not None and not \"\":\n self.get_page(cell.value)\n self.grab_reviews(excel, row[1].value, cell.value)\n\n # Tell the browser to get a page\n def get_page(self, url):\n print('getting page...')\n start_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]\n print(\"Start Time\" + start_time)\n self.driver.get(url)\n sleep(randint(2, 3))\n\n def grab_reviews(self, excel, product_name, product_url):\n print('grabbing reviews......')\n print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])\n print(len(self.driver.find_elements_by_xpath('//*[@id=\"reviews\"]//*[@class=\"product-review\"]')))\n log = [product_name, product_url]\n curr_reviews = self.total_reviews\n last_thread = None\n try:\n product_name = self.driver.find_element_by_xpath('//*[@id=\"product-information\"]/h1')\n product_name = str(product_name.get_attribute(\"innerHTML\")).strip()\n except:\n print(\"Error getting product name\")\n pass\n for div in self.driver.find_elements_by_xpath('//*[@id=\"reviews\"]//*[@class=\"product-review\"]'):\n try:\n last_thread = threading.Thread(target=self.thread_process, args=\n (div.get_attribute(\"innerHTML\"), product_name, product_url, excel))\n last_thread.start()\n except Exception as e:\n print(e)\n self.total_exp += 1\n print(\"Error: unable to start thread\")\n threading.Thread(target=self.logging, args=(curr_reviews, log, last_thread)).start()\n\n def logging(self, curr_reviews, log, last_thread):\n while last_thread and last_thread.isAlive():\n pass\n log.append(self.total_reviews - curr_reviews)\n self.info_logger.log(log)\n\n def thread_process(self, div, product_name, product_url, excel):\n # row = self.process_elements(div)\n row = self.process_soup(div)\n if row:\n row.append(product_name)\n row.append(product_url)\n row.append(TAG)\n excel.insert_row(getattr(excel, \"wb\"), row)\n\n def process_soup(self, div):\n soup = BeautifulSoup(div, 'lxml')\n attributes = []\n\n try:\n content = soup.select_one(\".description > h4\")\n if content is not None:\n print(content.getText())\n attributes.append(content.getText())\n else:\n attributes.append(\"NA1\")\n except:\n attributes.append(\"NA1\")\n pass\n try:\n content = soup.select_one(\".description > p\")\n if content is not None:\n print(content.getText())\n attributes.append(content.getText())\n else:\n attributes.append(\"NA2\")\n except:\n attributes.append(\"NA2\")\n pass\n try:\n content = soup.select_one(\".stars > span\")\n if content is not None:\n star = str(content.getText()).strip() + \" out of 5\"\n print(star)\n attributes.append(star)\n else:\n return []\n attributes.append(\"NA3\")\n except:\n attributes.append(\"NA3\")\n pass\n attributes.append(\"NA3\")\n attributes.append(\"NA3\")\n attributes.append(\"NA3\")\n try:\n content = soup.select_one(\".reviewer > span\")\n if content is not None:\n author = str(content.getText()).strip()\n print(author)\n attributes.append(author)\n else:\n attributes.append(\"NA4\")\n except:\n attributes.append(\"NA4\")\n pass\n attributes.append(\"\")\n attributes.append(\"NA6\")\n attributes.append(\"NA7\")\n attributes.append(TAG)\n attributes.append(\"NA9\")\n\n self.total_reviews = self.total_reviews + 1\n print(\"Total Number of reviews : \" + str(self.total_reviews))\n print(\"Total Number of exp : \" + str(self.total_exp))\n return attributes\n\n\n# Open headless chromedriver\ndef start_driver():\n print('starting driver...')\n try:\n driver = webdriver.Chrome(\"C:/Users/Prash/Desktop/Work/scrapj-Thread-Implementation/scrapj/input_link_extraction/utilities/drivers/chromedriver.exe\")\n except:\n try:\n driver = webdriver.Chrome(\"C:/Users/Prash/Desktop/Work/scrapj-Thread-Implementation/scrapj/input_link_extraction/utilities/drivers/chromedriver\")\n except:\n print(\"No Driver\")\n\n sleep(4)\n return driver\n\n\n# Close chromedriver\\\ndef close_driver(driver):\n print('closing driver...')\n driver.quit()\n print('closed!')\n\n\nstart_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]\ndriver = start_driver()\n\n\nwg = Excel(\"www.lens.com\") #correct\nwb = getattr(wg, \"wb\")\nlens = Lens(driver, None)\nlens.extract_data(wg)\nwhile True:\n try:\n wg.save_xls(wb)\n Path(\"../status/\" + \"www.lens.com\" + \".txt\").touch()\n break\n except:\n pass","sub_path":"review_extraction/lens/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"355202669","text":"import os\nimport sys\nimport imutils\nimport math\nimport argparse\nimport pickle\n\nimport cv2 as cv\nimport numpy as np\nfrom glob import glob\nfrom skimage import feature\n\nfrom week5 import utils as utils\nimport week5.noise_removal as noise_removal\n\ndef rotate_coords(theta, box, img_shape):\n h,w = img_shape\n cx = w // 2\n cy = h // 2\n theta_rad = math.radians(-theta)\n\n rot_box = []\n\n for box_corner in box:\n\n x, y = box_corner\n\n cos_rad = math.cos(theta_rad)\n sin_rad = math.sin(theta_rad)\n\n rot_x = cos_rad*x + sin_rad*y + (1-cos_rad)*cx - sin_rad*cy\n rot_y = -sin_rad*x + cos_rad*y + sin_rad*cx + (1-cos_rad)*cy\n\n # print(rot_x,rot_y)\n rot_box.append([rot_x,rot_y])\n return rot_box\n\ndef show_hough_lines(img, lines):\n for line in lines:\n rho = line[0][0]\n theta = line[0][1]\n a = math.cos(theta)\n b = math.sin(theta)\n x0 = a * rho\n y0 = b * rho\n pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))\n pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))\n cv.line(img, pt1, pt2, (0,255,0), 5, cv.LINE_AA)\n\n\ndef hough_rotation_theta(img_show, img, rho_res, theta_res, min_lines,\n thr_init, thr_step, show_h_lines, show_v_lines):\n\n def _reject_outliers(values, threshold = 2.):\n hist, bin_edges = np.histogram(values)\n lower_bin_edge = np.argmax(hist)\n upper_bin_edge = np.argmax(hist)+1\n most_common_values = [bin_edges[lower_bin_edge] <= v <= bin_edges[upper_bin_edge] for v in values]\n # print(f'Thetas: {values}')\n # print(f'Most common values: {most_common_values}')\n return values[most_common_values]\n\n found_rotation_theta = False\n iter = 0\n while not found_rotation_theta:\n lines = cv.HoughLines(img.copy(), rho_res, theta_res * np.pi / 180,\n thr_init-thr_step*iter, None, 0, 0)\n if lines is not None:\n horizontal_lines_thetas = []\n horizontal_lines = []\n vertical_lines = []\n for line in lines:\n theta = line[0][1]\n corrected_theta = 90 - theta * 180 / np.pi\n if corrected_theta < 0:\n corrected_theta += 180\n if (0 <= corrected_theta <= 45) or (135 <= corrected_theta <= 180):\n horizontal_lines_thetas.append(corrected_theta)\n horizontal_lines.append(line)\n else:\n vertical_lines.append(line)\n\n if len(horizontal_lines_thetas) >= min_lines:\n found_rotation_theta = True\n inlier_lines_thetas = _reject_outliers(np.array(horizontal_lines_thetas))\n # print(inlier_lines_thetas)\n rotation_theta = sum(inlier_lines_thetas)/len(inlier_lines_thetas)\n # print(rotation_theta)\n if show_h_lines:\n show_hough_lines(img_show, horizontal_lines)\n if show_v_lines:\n show_hough_lines(img_show, vertical_lines)\n\n iter += 1\n return rotation_theta\n\ndef parse_args(args=sys.argv[1:]):\n parser = argparse.ArgumentParser(description='Find sub-optimal parameters to get rotation theta')\n\n parser.add_argument('--rho_res', '-r', type=int, default=1)\n\n parser.add_argument('--theta_res', '-t', type=int, default=1)\n\n parser.add_argument('--min_lines', '-m', type=int, default=3)\n\n parser.add_argument('--thr_init', '-i', type=int, default=450)\n\n parser.add_argument('--thr_step', '-s', type=int, default=25)\n\n parser.add_argument('--show_h_lines', action='store_true')\n\n parser.add_argument('--show_v_lines', action='store_true')\n\n args = parser.parse_args(args)\n\n return args\n\nif __name__ == \"__main__\":\n\n args = parse_args()\n print(args)\n\n max_paintings = 3\n\n query_path = '/home/oscar/workspace/master/modules/m1/project/Team3/data/qsd1_w5'\n query_list = sorted(glob(os.path.join(query_path, '*.jpg')))\n\n gt = pickle.load(open('data/qsd1_w5/frames.pkl','rb'))\n avg_angular_error = 0.0\n count=0\n\n for image_id, img_path in enumerate(query_list):\n if image_id == 25:\n img = cv.imread(img_path)\n\n # img,_,_ = noise_removal.denoise_painting(img)\n\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n cv.imwrite('gray.jpg', gray)\n edges = feature.canny(gray, sigma=3,low_threshold=20,high_threshold=40)\n\n mask = np.zeros(gray.shape)\n\n mask_edges = mask.copy()\n\n mask_edges[edges] = 255\n mask_edges = cv.convertScaleAbs(mask_edges)\n\n gray_copy = np.copy(gray)\n mask_copy2 = np.copy(mask_edges)\n\n rotation_theta = hough_rotation_theta(img, mask_copy2, rho_res=args.rho_res, theta_res=args.theta_res,\n min_lines=args.min_lines, thr_init=args.thr_init, thr_step=args.thr_step,\n show_h_lines=args.show_h_lines, show_v_lines=args.show_v_lines)\n\n cv.imshow('Image', imutils.resize(img, height=600))\n cv.imwrite('hough_img.jpg', img)\n\n if 0 <= rotation_theta <= 90:\n rotation_theta_aux = -rotation_theta\n elif 90 < rotation_theta <= 180:\n rotation_theta_aux = 180 - rotation_theta\n\n cv.imshow('edges', imutils.resize(mask_edges, height=600))\n cv.imwrite('edges.jpg', mask_edges)\n rotated_mask = imutils.rotate(mask_edges, angle=rotation_theta_aux)\n cv.imshow('Rotated mask', imutils.resize(rotated_mask, height=600))\n\n kernel = cv.getStructuringElement(cv.MORPH_RECT,(30,30))\n closed = cv.morphologyEx(rotated_mask, cv.MORPH_CLOSE, kernel)\n\n cnts = cv.findContours(closed.copy(), cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n cnts = sorted(cnts, key = cv.contourArea, reverse = True)[:4]\n\n for c in cnts:\n x, y, w, h = cv.boundingRect(c)\n if w > gray.shape[1]/8 and h > gray.shape[0]/6:\n cv.rectangle(img, (x, y), (x + w, y + h), (255,0,0), 10)\n mask[y:y+h,x:x+w]=255 # fill the mask\n\n found_painting = False\n mask = cv.convertScaleAbs(mask)\n cnts = cv.findContours(mask.copy(), cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)\n cnts = cnts[0] if len(cnts) == 2 else cnts[1]\n\n # cv.imshow('gray'+str(image_id), imutils.resize(gray, height=600))\n # cv.imshow('rotated_mask'+str(image_id), imutils.resize(rotated_mask, height=600))\n # cv.imshow('closed'+str(image_id), imutils.resize(closed, height=600))\n # cv.imshow('img'+str(image_id), imutils.resize(img, height=600))\n # cv.imshow('mask'+str(image_id), imutils.resize(mask, height=600))\n\n desrotated_mask = imutils.rotate(mask.copy(), angle=-rotation_theta_aux)\n cv.imshow('Mask', imutils.resize(desrotated_mask, height=600))\n cv.waitKey()\n\n paintings_coords_aux = []\n for c in cnts:\n # # approximate to the rectangle\n x, y, w, h = cv.boundingRect(c)\n paintings_coords_aux.append([x,y,x+w,y+h])\n found_painting = True\n\n if len(paintings_coords_aux) == max_paintings:\n break\n\n if not found_painting:\n paintings_coords = [0,0,img.shape[1],img.shape[0]]\n\n else:\n paintings_coords = utils.sort_paintings(paintings_coords_aux)\n\n paintings_coords_angle = []\n for painting_coords in paintings_coords:\n tlx,tly,brx,bry = painting_coords\n\n tl_coords = [tlx, tly]\n tr_coords = [brx, tly]\n br_coords = [brx, bry]\n bl_coords = [tlx, bry]\n coords_aux = [tl_coords, tr_coords, br_coords, bl_coords]\n\n painting_coords_angle = [rotation_theta]\n painting_coords_angle.append(rotate_coords(rotation_theta_aux, coords_aux, img.shape[:2]))\n paintings_coords_angle.append(painting_coords_angle)\n\n # print(paintings_coords_angle)\n\n # Evaluation\n gt_angles = [x[0] for x in gt[image_id]]\n hy_angles = [l[0] for l in paintings_coords_angle]\n\n common_vals = min(len(gt_angles), len(hy_angles))\n for kk in range(common_vals):\n gta = gt_angles[kk] * np.pi / 180\n hya = hy_angles[kk] * np.pi / 180\n\n v1 = [abs(np.cos(gta)),np.sin(gta)]\n v2 = [abs(np.cos(hya)),np.sin(hya)]\n ang_error = abs(np.arccos(np.dot(v1,v2)) * 180 / np.pi)\n avg_angular_error += ang_error\n\n #avg_angular_error += abs(gt_angles[kk] - hy_angles[kk])\n count = count + 1\n\n print(f'Img ID: {image_id} -> Err: {ang_error:.2f} Gt: {gt_angles[kk]:.2f} Pred: {hy_angles[kk]:.2f}')\n\n avg_angular_error /= count\n print(f'Avg error: {avg_angular_error:.2f}')\n print('-------------------------------------------------------------------------------------')\n","sub_path":"utils/rotation_theta.py","file_name":"rotation_theta.py","file_ext":"py","file_size_in_byte":9380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"21310087","text":"from pal.misokg import misokg\nfrom pal.constants.solvents import solvents\nfrom pal.kernels.matern import maternKernel52 as mk52\nfrom pal.objectives.binding_energy import get_enthalpy_solvation as BE\n\nimport copy\nimport numpy as np\n\n# Generate the main object\nsim = misokg()\n\n# Assign simulation properties\n###################################################################################################\n# File names\nsim.fname_out = \"enthalpy.dat\"\nsim.fname_historical = None\n\n# Information sources, in order from expensive to cheap\nsim.IS = [\n lambda h, c, s: -1.0 * BE(h, c, s, num_solvents=5, route_lvl=1),\n lambda h, c, s: -1.0 * BE(h, c, s, num_solvents=1, route_lvl=0)\n]\nsim.historical_nsample = 5\n\n# Possible compositions by default\nsim.A = [\"Cs\", \"MA\", \"FA\"]\nsim.B = [\"Pb\"]\nsim.X = [\"Cl\", \"Br\", \"I\"]\nsim.solvents = copy.deepcopy(solvents)\nsim.S = [k for k, _ in sim.solvents.items()]\nsim.mixed_halides = True\nsim.mixed_solvents = False\n\n# Parameters for debugging and overwritting\nsim.debug = False\nsim.verbose = True\nsim.overwrite = True # If True, warning, else Error\n\n# Functional forms of our mean and covariance\n# MEAN: 4 * mu_alpha + mu_zeta\n# COV: sig_alpha * |X> cleaning {FAB} directory')\n c.run(f'rm -rf {FAB}')\n\n\n@task(clean)\ndef plot_all(c):\n Path(FAB).mkdir(parents=True)\n\n # assuming first one is a pcb which needs docs files as well\n first = True\n for pcb in PCBS:\n slug = '_'.join(pcb.split('/')[0:-1])\n\n if not Path(pcb).exists():\n print(f'==> {pcb} not found, omitting!')\n continue\n first = False\n\n if first:\n c.run(f'./scripts/plot_doc.py {pcb} {FAB}/doc/{slug}')\n first = False\n\n c.run(f'./scripts/plot_fab.py {pcb} {FAB}/fab/{slug}')\n c.run(f'7z a {FAB}/fab/{PROJECT}_{slug}.zip ./{FAB}/fab/{slug}/*')\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"375120505","text":"#!/usr/bin/env python\n\nfrom pwn import *\nfrom LibcSearcher import *\ncontext(log_level = \"debug\",arch = \"amd64\",os = \"linux\")\n\nexe = 'shoppingCart.dms'\nlib = ''\nip = ''\nport = 0\nelf = ELF(exe)\n#libc = ELF(lib)\n\nio = process(exe)#, env={\"LD_PRELOAD\":libc.path})\n#io = remote(ip, port)\n\ndef gdb(script = ''):\n\tattach(io,gdbscript = script)\n\ndef cart(context):\n\tio.recvuntil('EMMmmm, you will be a rich man!')\n\tio.sendline('1')\n\tio.recvuntil('RMB or Dollar?')\n\tio.sendline(context)\n\ndef goods():\n\tio.recvuntil('EMMmmm, you will be a rich man!')\n\tio.sendline('3')\n\ndef add(name):\n\tio.recvuntil('Now, buy buy buy!')\n\tio.sendline('1')\n\tio.recvuntil('How long is your goods name?')\n\tio.sendline(str(len(name)+1))\n\tio.recvuntil('What is your goods name?')\n\tio.sendline(name)\n\ndef delete(index):\n\tio.recvuntil('Now, buy buy buy!')\n\tio.sendline('2')\n\tio.recvuntil('Which goods that you')\n\tio.sendline(str(index))\n\ndef edit(index):\n\tio.recvuntil('Now, buy buy buy!')\n\tio.sendline('3')\n\tio.recvuntil('Which goods you need to modify?')\n\tio.sendline(str(index))\n\tio.recvuntil('OK, what would you like to modify ')\n\taddr = u64(io.recv(6).ljust(8, '\\x00'))\n\treturn addr\n\ndef leak(address, text):\n\tedit(-0x2f)\n\tio.send(p64(code_addr+address)[:6])\t\t# leak addr\n\tleak_addr = edit(0)\t\t\t\t# get plt.got\n\tio.send(text[:7])\n\treturn leak_addr\n\nstr_addr = 0x2020A0\nptr_addr = 0x2021E0\n\ngoods()\nadd('A'*0x8)\n\n#gdb()\ncode_addr = edit(-0x2f) - 0x202068\nio.send(p64(code_addr+ptr_addr)[:6])\n\nlibc_main_addr = leak(elf.got['__libc_start_main'], 'A'*7)\n\nobj = LibcSearcher('__libc_start_main', libc_main_addr)\nlibc_main_got = obj.dump(\"__libc_start_main\")\nsystem_got = obj.dump(\"system\")\nsystem_addr = libc_main_addr - (libc_main_got - system_got)\n\nleak(elf.got['free'], p64(system_addr))\nleak(str_addr, '/bin/sh')\ndelete(0)\n\nio.interactive()","sub_path":"2018护网杯/shoppingcart/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"468731085","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef get_random_x(num_x):\n return np.random.rand(num_x) * 2 - 1\n\n\ndef f_org(x):\n return 1.0 / (np.exp(-10 * x ** 2) + 1) - 0.5\n\n\ndef f_noisy(x, s=0.1):\n return f_org(x) + s * np.random.randn(len(x))\n\nx = get_random_x(1000)\nx_test = np.array([1,2,3,4,5,6,7,8,9,0])\ny = f_noisy(x)\nk = 4\nlr = 0.06\nepochs = 50000\nlosses = []\n\nclass Model(object):\n def __init__(self):\n self.w1 = tf.Variable(tf.random.uniform([k,1],dtype=tf.dtypes.float64))\n self.w2 = tf.Variable(tf.random.uniform([1,k],dtype=tf.dtypes.float64))\n self.b1 = tf.Variable(tf.random.uniform([k,1],dtype=tf.dtypes.float64))\n self.b2 = tf.Variable(tf.random.uniform([1],dtype=tf.dtypes.float64))\n\n\n def __call__(self, x):\n hidden_layer=tf.math.sigmoid((tf.matmul(self.w1,x.reshape(1,-1)))+self.b1)\n output_layer = tf.matmul(self.w2,hidden_layer)+self.b2\n return output_layer\n\ndef loss(y,y_hat):\n return tf.reduce_mean(tf.square(y-y_hat))\n\ndef update_param(model):\n with tf.GradientTape() as t:\n c_loss=loss(y,model(x))\n losses.append(c_loss)\n dw1,dw2,db1,db2 =t.gradient(c_loss,[model.w1,model.w2,model.b1,model.b2])\n model.w1.assign_sub(lr*dw1)\n model.w2.assign_sub(lr*dw2)\n model.b1.assign_sub(lr*db1)\n model.b2.assign_sub(lr*db2)\n\nmodel = Model()\nfor i in range(epochs):\n update_param(model)\n\ny_predicted = model(x)\nfig, ax1 = plt.subplots()\nax1.plot(losses,range(epochs))\nfig, ax = plt.subplots()\nax.scatter(x,y)\nax.scatter(x,np.squeeze(y_predicted))\nplt.show()\n\n\n","sub_path":"Week3/Simple-Neural-Network.py","file_name":"Simple-Neural-Network.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"364498312","text":"import streamlit as st\r\nimport datetime\r\nimport pandas as pd\r\n\r\nfrom Flight_Price_Predict import predict\r\n\r\n'''\r\n# Flight Price Prediction\r\nFill the necessary details and get approx price. \r\n'''\r\nairline = ['IndiGo', 'Air India', 'Jet Airways', 'SpiceJet', 'Multiple carriers', 'GoAir', 'Vistara', 'Air Asia', 'Vistara Premium economy', 'Jet Airways Business',\r\n 'Multiple carriers Premium economy', 'Trujet']\r\nsource = ['Kolkata', 'Delhi', 'Chennai', 'Mumbai', 'Banglore']\r\ndestination = ['Banglore', 'Cochin', 'Kolkata', 'Delhi', 'Hyderabad']\r\nstop = [0, 1, 2, 3, 4]\r\n\r\nairline = st.selectbox(\"Select Airline\", airline)\r\nsource = st.selectbox(\"Select Source\", source)\r\ndestination = st.selectbox(\"Select Destination\", destination)\r\ntotal_stop = st.selectbox('Select Number of Stop', stop)\r\n\r\ndate_of_journey = st.date_input('Select Date of Journey')\r\njourney_time = st.time_input(\"Journey time is\", datetime.time())\r\n\r\ndate_of_arrival = st.date_input('Select Date of Arrival')\r\narrival_time = st.time_input('Arrival Time', datetime.time())\r\nstartTime = datetime.datetime.combine(date_of_journey, journey_time)\r\narrivalTime = datetime.datetime.combine(date_of_arrival, arrival_time)\r\ntotal_difference = (arrivalTime - startTime).total_seconds()\r\nprint('total_difference : ', total_difference)\r\nduration = str(int(total_difference / 3600)) + 'h ' + str(int((total_difference % 3600)%60)) + 'm'\r\n\r\n\r\ndef time_difference_check():\r\n flag = True\r\n if total_difference / 60 <= 30:\r\n st.error('Arrival and Start datetime should have atleast 30 minute gap')\r\n flag = False\r\n elif date_of_arrival < date_of_journey:\r\n st.error('Please select a proper date range')\r\n flag = False\r\n return flag\r\n return flag\r\n\r\n\r\nif st.button('Predict Price'):\r\n # print('Airline : ',airline)\r\n # print('Source :',source)\r\n # print('Destination : ',destination)\r\n # print('total stop : ',total_stop)\r\n # print('date of journey : ',date_of_journey)\r\n # print(date_of_journey.day)\r\n # print('journey time : ',type(journey_time))\r\n # print('date of arrival : ',date_of_arrival)\r\n # print('arrival time : ',arrival_time)\r\n flag = time_difference_check()\r\n if flag == True:\r\n predicted_value = predict(airline, date_of_journey, source, destination, journey_time, arrival_time, duration, total_stop)\r\n st.write('Predicted Price is ', int(predicted_value))\r\n","sub_path":"stream_app.py","file_name":"stream_app.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"159934735","text":"\n#initialization\n#starting hands ranked file\n#omaha_hands_file = \"omaha_starting_hands_ranked.txt\"\nomaha_hands_file = \"omaha_hands_sample.txt\"\n#create array of 4 suits spades, hearts, diamonds, clubs\nsuits = [\"s\",\"h\",\"d\",\"c\"]\n#create array of arrays with format; we'll use this to run the pypoker.py program to get associated EV for the given hand against HU random; 3-way random; 4-way random; 5-way random; and then take those associated EV's to rank and group each hand;\n\t#eval_hand = [[\"As\",\"Js\",\"Ah\",\"Jh\"], [\"__\",\"__\",\"__\",\"__\"]]\n\t#need to create an empty array to fill, we'll add it later\nhand_to_eval = []\n#create empty string for the hand that will be evaluated; this comes from the infile line by line; we'll use to write to the output file\n\n#iterate through the different suits\n\n#set action = 1 when processing same suit hands\naction = 0;\nsuited_stack = []\n\n#from bibin r\n# start reading line by line\n# start reading character by character\n# if the character is ( then start pushing the following characters into a stack; first in last out\n# keep pushing the characters into the stack until you hit )\n# once you hit ) then take action 1\n# action 1 will process the cards in the stack and assign the same suit\n# if the next character is not ( then proceed with action 2\n# action 2 will start pushing into another stack until you hit (\n# once you hit ( or the end of the line, pull out the items in the stack and begin assigning unique suits 1 by 1\nwith open(\"outputfile_sample.txt\", \"ab\") as out:\n\twith open(omaha_hands_file) as f:\n\t for line in f:\n\t \tline = line.strip('\\n')\n\t \tsuits = [\"s\",\"h\",\"d\",\"c\"]\n\t \taction = 0\n\t \tsuited_stack = []\n\t \ttemp_suit = \"\"\n\t \thand_to_eval = []\n\t \tfor char in line:\n\t \t\t#the first time we see a ( character we know more suits are to come, let's set action = 1 and goto the next character\n\t \t\tif char == '(':\n\t \t\t\taction = 1\n\t \t\t\tcontinue\n\t \t\t#when we hit the ) character we need to start processing suited_stack by popping out the elements from the bottom of the stack\n\t \t\tif char == ')':\n\t \t\t\ttemp_suit = str(suits.pop())\n\t \t\t\tfor card in suited_stack:\n\t \t\t\t\thand_to_eval.append(card+temp_suit)\n\t \t\t\taction = 0\n\t \t\t\tsuited_stack = []\n\t \t\t\tcontinue\n\t \t\t#we've already seen ( character and need to start adding upcoming cards to the suited_stack\n\t \t\tif action == 1:\n\t \t\t\tsuited_stack.append(char)\n\t \t\t\tcontinue\n\t \t\tif action == 0:\n\t \t\t\ttemp_suit = str(suits.pop())\n\t \t\t\thand_to_eval.append(char+temp_suit)\n\t \tout.write(str(hand_to_eval)+\"\\n\")\n\n\n#run the program for all 16.4K hands, and output to file with original format i.e. (AJ)(AJ); then comma delimmit with associated ev","sub_path":"hand_format_convert.py","file_name":"hand_format_convert.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"28740332","text":"__author__ = 'Vinodkumar'\n\nfrom pratice.xl_utility import XLSMethods as Xls\nfrom Utilities.Const import Constant as C\nfrom Utilities.Post_Request import PostMethod as Post\n\n\nclass RunTest:\n\n for iterate in range(1, Xls.get_no_of_iteration(C.sh_name1, C.ts_ID)):\n run_mode = Xls.read_data(C.sh_name1, iterate, C.ts_rumod)\n\n if run_mode == 'Yes':\n\n file_path = Xls.read_data(C.sh_name1, iterate, C.ts_filoc)\n tc_ID = Xls.read_data(C.sh_name1, iterate, C.ts_ID)\n tc_row = Xls.row_list(C.sh_name2, tc_ID)\n\n if len(tc_row) != 0:\n req_body = Post.post_request(file_path)\n\n for da_pt_iter in range(0, len(tc_row)):\n dapt_key = Xls.read_data(C.sh_name2, tc_row[da_pt_iter], C.to_dp)\n dapt_val = Xls.read_data(C.sh_name2, tc_row[da_pt_iter], C.to_exp)\n\n # Post.write_json_output(req_body, dapt_key, tc_row[da_pt_iter])\n if dapt_key == 'eps':\n Post.post_validate_update(req_body, dapt_key, dapt_val, tc_row[da_pt_iter])\n\n Xls.write_data(C.sh_name1, iterate, C.ts_res, \"Executed - Please check 'Test_Output' sheet\")\n\n elif run_mode == 'No':\n Xls.write_data(C.sh_name1, iterate, C.ts_res, 'Not Executed')\n\n\nif __name__ == '__main__':\n RunTest()\n","sub_path":"pratice/RunTest.py","file_name":"RunTest.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"443622902","text":"import os\nimport csv\nimport random\nimport requests\nfrom bs4 import BeautifulSoup\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"reviewduk.settings\")\nfrom django.conf import settings\n\nparseStr = lambda x: float(x) if '.' in x else int(x)\n\ndef poster_url(code):\n b = BeautifulSoup(requests.get('http://movie.naver.com/movie/bi/mi/photoViewPopup.nhn?movieCode='+code).text)\n try:\n img = b.find('img')\n return [img['src']+\"?type=m203_290_2\", img['alt']]\n except:\n return ['http://static.naver.net/movie/2012/06/dft_img203x290.png','']\n\ndef get_sample(count = 10):\n train_name = settings.TRAIN\n out_name = settings.SAMPLE\n\n with open(train_name) as trainf, open(out_name, 'w') as outf:\n lines = trainf.readlines()\n random.shuffle(lines)\n\n outf.writelines(lines[:count])\n\ndef readSampleFile(file_name = settings.SAMPLE):\n sample = []\n with open(file_name, 'rb') as csvfile:\n predictions = csv.reader(csvfile, delimiter=' ', quotechar='|')\n for row in predictions:\n sample.append((row[1][1:], row[2][2:-2]))\n return sample\n\ndef readPredictFile(file_name = settings.PREDICT):\n y_pred = []\n with open(file_name, 'rb') as csvfile:\n predictions = csv.reader(csvfile, delimiter=' ', quotechar='|')\n for row in predictions:\n pred = parseStr(row[0])\n y_pred.append(pred)\n return y_pred\n","sub_path":"utils/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"402752264","text":"from envs.deep_cure_env import DeepCure, ForeignCountry, random_base_infect_rate\nfrom plotting import plot\nimport gym\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\ndef discretize(state, stepsize, num_states):\n return np.minimum(state / stepsize, num_states - 1).astype(int)\n\ndef index(state, action = None):\n if action is None:\n # corresponds to [:]\n action = slice(None,None)\n else:\n action = sum([b * (2 ** i) for i,b in enumerate(action)])\n index = tuple((*state,action))\n return index\n\ndef greedy_policy(state, q_array):\n action_index = np.argmax(q_array[index(state)])\n action = np.array([int((action_index / (2 ** i)) % 2) for i in range(int(math.log2(q_array.shape[-1])))])\n return action\n\ndef epsilon_greedy_policy(env, state, q_array, epsilon):\n if np.random.rand() < epsilon:\n action = env.action_space.sample()\n else:\n action = greedy_policy(state, q_array)\n return action\n\ndef q_learning(environment, alpha=0.1, alpha_factor=0.9995, gamma=0.99, epsilon=0.5, num_episodes=10000, rate = None, stepsize = 20, max_steps = 100):\n q_array_history = [0]\n last_q_array = None\n alpha_history = []\n num_states = np.minimum((environment.observation_space.high - environment.observation_space.low)/stepsize, max_steps).astype(int)\n num_actions = 2**environment.action_space.n\n q_array = np.zeros(list(num_states) + [num_actions]) # Initial Q table\n for episode_index in range(num_episodes):\n alpha_history.append(alpha)\n\n # Update alpha\n if alpha_factor is not None:\n alpha = alpha * alpha_factor\n\n is_final_state = False\n state = discretize(environment.reset(rate), stepsize, num_states)\n\n while not is_final_state:\n action = epsilon_greedy_policy(environment, state, q_array, epsilon)\n new_state, reward, is_final_state, info = environment.step(action)\n\n new_state = discretize(new_state, stepsize, num_states)\n new_action = greedy_policy(new_state, q_array)\n q_array[index(state, action)] = q_array[index(state, action)] + alpha * (reward + gamma * q_array[index(new_state, new_action)] - q_array[index(state, action)])\n\n state = new_state\n\n if last_q_array is not None:\n q_array_history.append(np.max(np.absolute(q_array - last_q_array)))\n last_q_array = q_array.copy()\n\n return q_array, q_array_history, alpha_history\n\ndef hyperparameter_search(stepsize, max_steps, gamma_range):\n def eval_q_table(env, q_table, n=100):\n rewards = np.zeros(n)\n for i in range(n):\n state = discretize(env.reset(), stepsize, num_states)\n done = False\n while not done:\n action = greedy_policy(state, q_table)\n state, reward, done, _ = env.step(action)\n state = discretize(state, stepsize, num_states)\n rewards[i] = sum(env.hist_reward)\n return np.mean(rewards)\n r = []\n for gamma in gamma_range:\n SEED = 42\n\n np.random.seed(SEED)\n\n env = DeepCure(foreign_countries = [ForeignCountry(0.1,100,100_000, save_history=True)], save_history=True, seed = SEED)\n num_states = np.minimum((env.observation_space.high - env.observation_space.low)/stepsize, max_steps).astype(int)\n q_table, _, _ = q_learning(env, stepsize=stepsize, max_steps=max_steps, gamma=gamma)\n reward = eval_q_table(env, q_table)\n r.append(reward)\n print(f'Gamma={gamma}: {reward}')\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.set_xlabel('$\\\\gamma$')\n ax.set_ylabel('avg. reward')\n ax.plot(gamma_range , r)\n plt.show()\n\nif __name__ == \"__main__\":\n\n #hyperparameter_search(100, 10, [i/100. for i in range(80,100)])\n \n SEED = 42\n\n np.random.seed(SEED)\n\n env = DeepCure(foreign_countries = [ForeignCountry(0.1,100,100_000, save_history=True)], save_history=True, seed = SEED)\n\n q_table, q_array_history, alpha_history = q_learning(env, epsilon=0.5, gamma = 0.98, stepsize = 100, max_steps = 10)\n np.save(f'qtable-100.npy', q_table)\n\n np.random.seed(SEED)\n\n q_table2, q_array_history2, _ = q_learning(env, epsilon=0.5, gamma = 0.98, stepsize = 1000, max_steps = 10)\n np.save(f'qtable-1000.npy', q_table2)\n\n fig = plt.figure()\n ax0 = fig.add_subplot(2,1,1)\n ax0.set_title('Q Table Convergence')\n ax0.set_xlabel('iterations')\n ax0.set_ylabel('absolute difference')\n ax0.plot(range(len(q_array_history)), q_array_history, label='q-table 100')\n ax0.plot(range(len(q_array_history2)), q_array_history2, label='q-table 1000')\n ax0.legend()\n\n ax1 = fig.add_subplot(2,1,2)\n ax1.set_title('$\\\\alpha$')\n ax1.set_xlabel('iterations')\n ax1.set_ylabel('$\\\\alpha$')\n ax1.plot(range(len(alpha_history)), alpha_history)\n\n fig.tight_layout()\n\n plt.show()\n","sub_path":"deep_cure_learning/q_table_agent.py","file_name":"q_table_agent.py","file_ext":"py","file_size_in_byte":4912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"280475861","text":"#!/usr/bin/env python3\nimport pygame, sys\nfrom widgets import SliderCounter, TextBox\nimport numpy as np\nimport physx\nimport simulation\nimport argparse\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--printpos\", action=\"store_true\",\n help=\"Print the global positions\")\n args = parser.parse_args()\n\n # connect to the visualizer\n arm = simulation.Arm()\n\n # create a window for the controls\n pygame.init()\n screen = pygame.display.set_mode((640, 360))\n clock = pygame.time.Clock()\n\n # place widgets to respresent the controls that the user can input\n labels = []\n linkSlides = []\n jointSlides = []\n for i in range(arm.num_joints):\n labels.append(TextBox((0, 50 * i + 15), (80, 30),\n initialValue=\"Link \" + str(i + 1)))\n linkSlides.append(SliderCounter((0, 10),\n (80, 50 * i + 15), (240, 30), radius=8, counterWidth=60, fmt=\"%0.1f\",\n initialValue=arm.default_length[i]))\n labels.append(TextBox((320, 50 * i + 15), (80, 30),\n initialValue=\"Joint \" + str(i + 1)))\n jointSlides.append(\n SliderCounter((arm.joint_limits[i][0], arm.joint_limits[i][1]), \n (400, 50 * i + 15), (240, 30), radius=8, counterWidth=60, fmt=\"%d\"))\n \n while True:\n # update the controls events\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN:\n for link in linkSlides:\n link.setActive(pygame.mouse.get_pos())\n for joint in jointSlides:\n joint.setActive(pygame.mouse.get_pos())\n elif event.type == pygame.MOUSEMOTION:\n for link in linkSlides:\n link.update(pygame.mouse.get_pos())\n for joint in jointSlides:\n joint.update(pygame.mouse.get_pos())\n elif event.type == pygame.MOUSEBUTTONUP:\n for link in linkSlides:\n link.setInactive()\n for joint in jointSlides:\n joint.setInactive()\n\n # using the inputs from the controls panel, calculate the forward kinematics\n # to get the positions and set those on the arm\n positions = physx.forwardKinematics(\n np.array([link.getValue() for link in linkSlides]),\n np.array([joint.getValue() for joint in jointSlides]))\n arm.setPositions(positions)\n if args.printpos:\n print(positions)\n\n # update the controls render\n screen.fill((0xF5, 0xF5, 0xF5))\n for label in labels:\n label.render(screen)\n for link in linkSlides:\n link.render(screen)\n for joint in jointSlides:\n joint.render(screen)\n pygame.display.flip()\n clock.tick(50)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/manual.py","file_name":"manual.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"385439291","text":"import time\n\nfrom boto.ses import SESConnection\nfrom mail.models import Mail\nfrom mash_backend.settings.base import MAX_MAILS_PER_SEC\nfrom mash_backend.settings.production import DEFAULT_EMAIL_SENDER, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY\n\n\ndef send_mail_data(subject, body, format):\n connection = SESConnection(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)\n try:\n emails = Mail.objects.all().values_list('email', flat=True)\n except Mail.DoesNotExist:\n emails = []\n for i in range(0, len(emails), MAX_MAILS_PER_SEC):\n to_addresses = emails[i:(i + MAX_MAILS_PER_SEC)]\n connection.send_email(source=DEFAULT_EMAIL_SENDER, subject=subject, body=body,\n to_addresses=DEFAULT_EMAIL_SENDER,\n bcc_addresses=to_addresses,\n format=format)\n time.sleep(1)\n","sub_path":"mail/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"464574486","text":"# coding=utf-8\n# /user/bin/env python\n\n\"\"\"\nauthor:ranlay\ndate:2019/7/14 21:22\ndesc:线程使用\n\"\"\"\nimport threading,time\n\ndef worker(num):\n print('线程执行%d'%num)\n time.sleep(2)\n\nif __name__ == '__main__':\n for x in range(5):\n # 创建线程\n t = threading.Thread(target=worker, args=(x+1,))\n #执行线程\n t.start()\n print('主线程结束')","sub_path":"basis/14-thread.py","file_name":"14-thread.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"610229806","text":"from parsl import *\n\n\ndef run():\n local_config = {\n \"sites\" : [\n { \"site\" : \"Threads\",\n \"auth\" : { \"channel\" : None },\n \"execution\" : {\n \"executor\" : \"threads\",\n \"provider\" : None,\n \"maxThreads\" : 4\n }\n }],\n \"globals\" : {\"lazyErrors\" : True}\n }\n\n dfk = DataFlowKernel(config=local_config)\n\n @App('bash', dfk)\n def runMLZ():\n return \"./mlz/runMLZ mlz/test/SDSS_MGS_wf.inputs\"\n\n runMLZ()\n dfk.cleanup()\n\n\nif __name__ == '__main__':\n print(\"> Run ...\")\n run()\n print(\"> Done!\")\n","sub_path":"run_app.py","file_name":"run_app.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"82238019","text":"\"\"\"\nTransfer Learning Application Using WPT\n---------------------------------------\n\nThis function uses transfer learning principles to transfer the knowledge obtained from one cutting configuration to another one.\nIt assumes that the reconstructed Wavelet packets and frequency domain features are available an they are in the same folder with the data files.\nIt computes feature matrices for training and test set and performs the classification with chosen algorithm. \nIt returns the results in an array. It also prints the total elapsed time.\n\n\"\"\"\nimport time\nimport numpy as np\nimport scipy.io as sio\nfrom scipy.stats import skew\nfrom sklearn.feature_selection import RFE\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nimport os\nfrom matplotlib import rc\nimport matplotlib\nmatplotlib.rcParams.update({'font.size': 14})\nrc('font',**{'family':'serif','serif':['Palatino']})\nrc('text', usetex=True)\n\n\n#%% Transfer learning application which trains on one dataset and test on another one\n \ndef WPT_Transfer_Learning(stickout_length_training, stickout_length_test, WPT_Level, Classifier):\n \"\"\"\n :param str (stickout_length_training): \n Stickout length for the training data set \n \n * if stickout length is 2 inch, '2'\n * if stickout length is 2.5 inch, '2p5'\n * if stickout length is 3.5 inch, '3p5'\n * if stickout length is 4.5 inch, '4p5'\n \n :param str (stickout_length_test): \n Stickout length for the test data set\n\n * if stickout length is 2 inch, '2'\n * if stickout length is 2.5 inch, '2p5'\n * if stickout length is 3.5 inch, '3p5'\n * if stickout length is 4.5 inch, '4p5'\n \n :param int (WPT_Level): \n Level of Wavelet Packet Decomposition\n \n :param str (Classifier): \n Classifier defined by user\n \n * Support Vector Machine: 'SVC'\n * Logistic Regression: 'LR'\n * Random Forest Classification: 'RF'\n * Gradient Boosting: 'GB'\n \n :Returns:\n\n :results:\n (np.array([])) Classification results for training and test set for all combination of ranked features and devition for both set.\n \n * first column: mean accuracies for training set\n * second column: deviation for training set accuracies\n * third column: mean accuracies for test set\n * fourth column: deviation for test set accuracies\n \n :time:\n (str) Elapsed time during feature matrix generation and classification\n \n :Example:\n \n .. doctest::\n \n >>> from WPT_Transfer_Learning import WPT_Transfer_Learning\n \n #parameters\n \n >>> stickout_length_training = '2'\n >>> stickout_length_test = '4p5'\n >>> WPT_Level=4\n >>> Classifier='SVC'\n \n >>> results = WPT_Transfer_Learning(stickout_length_training, \n >>> stickout_length_test,\n >>> WPT_Level, Classifier) \n Enter the path of training set data files:\n >>> D\\...\\cutting_tests_processed\\data_2inch_stickout\n Enter the path of test set data files:\n >>> D\\...\\cutting_tests_processed\\data_4p5inch_stickout\n\n \"\"\"\n #%% get the path to data files from user\n \n user_input_train = input(\"Enter the path of training set data files: \")\n \n assert os.path.exists(user_input_train), \"Specified file does not exist at, \"+str(user_input_train)\n \n user_input_test = input(\"Enter the path of test set data files: \")\n \n assert os.path.exists(user_input_test), \"Specified file does not exist at, \"+str(user_input_test)\n \n \n folderToLoad1 = os.path.join(user_input_train)\n folderToLoad2 = os.path.join(user_input_test)\n \n #%% start timer\n start2 = time.time()\n \n #%% Loading time series and labels of the classification\n \n #training set data files-------------------------------------------------------\n # import the list including the name of the time series of the chosen case\n file_name_training = 'time_series_name_'+stickout_length_training+'inch.txt'\n file_path_training = os.path.join(folderToLoad1, file_name_training)\n f = open(file_path_training,'r',newline='\\n')\n \n #save the time series name into a list\n namets_training = []\n for line in f:\n names = line.split(\"\\r\\n\")\n namets_training.append(names[0])\n \n #import the classification labels\n label_file_name = stickout_length_training+'_inch_Labels_2Class.npy'\n file_path1 = os.path.join(folderToLoad1, label_file_name)\n label_training = np.load(file_path1)\n \n #test set data files-----------------------------------------------------------\n # import the list including the name of the time series of the chosen case\n file_name_test = 'time_series_name_'+stickout_length_test+'inch.txt'\n file_path_test = os.path.join(folderToLoad2, file_name_test)\n f = open(file_path_test,'r',newline='\\n')\n \n #save the time series name into a list\n namets_test = []\n for line in f:\n names = line.split(\"\\r\\n\")\n namets_test.append(names[0])\n \n #import the classification labels\n label_file_name = stickout_length_test+'_inch_Labels_2Class.npy'\n file_path1 = os.path.join(folderToLoad2, label_file_name)\n label_test = np.load(file_path1) \n \n #%% Upload the Decompositions and compute the feature from them----------------\n \n \n # length of datasets\n numberofcase_train = len(namets_training)\n numberofcase_test = len(namets_test)\n \n featuremat_train= np.zeros((numberofcase_train,10))\n featuremat_test= np.zeros((numberofcase_test,10))\n \n #load datasets and compute features\n for i in range (0,numberofcase_train):\n name = 'ts_%d' %(i+1)\n nameofdata = 'WPT_Level%s_Recon_%sinch_%s' %(str(WPT_Level),stickout_length_training,namets_training[i])\n pathofdata = os.path.join(folderToLoad1, nameofdata)\n ts = sio.loadmat(pathofdata)\n ts= ts[\"recon\"]\n \n featuremat_train[i,0] = np.average(ts)\n featuremat_train[i,1] = np.std(ts)\n featuremat_train[i,2] = np.sqrt(np.mean(ts**2)) \n featuremat_train[i,3] = max(abs(ts))\n featuremat_train[i,4] = skew(ts)\n L=len(ts)\n featuremat_train[i,5] = sum(np.power(ts-featuremat_train[i,0],4)) / ((L-1)*np.power(featuremat_train[i,1],4))\n featuremat_train[i,6] = featuremat_train[i,3]/featuremat_train[i,2]\n featuremat_train[i,7] = featuremat_train[i,3]/np.power((np.average(np.sqrt(abs(ts)))),2)\n featuremat_train[i,8] = featuremat_train[i,2]/(np.average((abs(ts))))\n featuremat_train[i,9] = featuremat_train[i,3]/(np.average((abs(ts)))) \n \n for i in range (0,numberofcase_test):\n name = 'ts_%d' %(i+1)\n nameofdata = 'WPT_Level%s_Recon_%sinch_%s' %(str(WPT_Level),stickout_length_test,namets_test[i])\n pathofdata = os.path.join(folderToLoad2, nameofdata)\n ts = sio.loadmat(pathofdata)\n ts= ts[\"recon\"]\n \n featuremat_test[i,0] = np.average(ts)\n featuremat_test[i,1] = np.std(ts)\n featuremat_test[i,2] = np.sqrt(np.mean(ts**2)) \n featuremat_test[i,3] = max(abs(ts))\n featuremat_test[i,4] = skew(ts)\n L=len(ts)\n featuremat_test[i,5] = sum(np.power(ts-featuremat_test[i,0],4)) / ((L-1)*np.power(featuremat_test[i,1],4))\n featuremat_test[i,6] = featuremat_test[i,3]/featuremat_test[i,2]\n featuremat_test[i,7] = featuremat_test[i,3]/np.power((np.average(np.sqrt(abs(ts)))),2)\n featuremat_test[i,8] = featuremat_test[i,2]/(np.average((abs(ts))))\n featuremat_test[i,9] = featuremat_test[i,3]/(np.average((abs(ts)))) \n \n #%% load frequency domain features (At different levels of WPT) and combine them \n # with the time domain feature\n \n n_feature=14 \n \n #training set------------------------------------------------------------------\n freq_feature_file_name = 'WPT_Level%d_Freq_Features_%sinch.mat'%(WPT_Level,stickout_length_training)\n file_path_Ff = os.path.join(folderToLoad1, freq_feature_file_name) \n freq_features = sio.loadmat(file_path_Ff)\n freq_features = freq_features['Freq_Features']\n \n #concatanate the frequency and time domain features \n featuremat_train = np.concatenate((featuremat_train, freq_features),axis = 1)\n \n #test set----------------------------------------------------------------------\n freq_feature_file_name = 'WPT_Level%d_Freq_Features_%sinch.mat'%(WPT_Level,stickout_length_test)\n file_path_Ff = os.path.join(folderToLoad2, freq_feature_file_name) \n freq_features = sio.loadmat(file_path_Ff)\n freq_features = freq_features['Freq_Features']\n \n #concatanate the frequency and time domain features \n featuremat_test = np.concatenate((featuremat_test, freq_features),axis = 1)\n \n #%%\n #creating train, test, accuracy, meanscore and deviation matrices\n \n accuracy1 = np.zeros((n_feature,10))\n accuracy2 = np.zeros((n_feature,10))\n deviation1 = np.zeros((n_feature,1))\n deviation2 = np.zeros((n_feature,1))\n meanscore1 = np.zeros((n_feature,1))\n meanscore2 = np.zeros((n_feature,1))\n duration1 = np.zeros((n_feature,10))\n meanduration = np.zeros((n_feature,1))\n \n #repeat the procedure ten times \n Rank=[]\n RankedList=[]\n for o in range(0,10):\n \n #split into test and train set\n F_Training_Train,F_Training_Test,Label_Training_Train,Label_Training_Test= train_test_split(featuremat_train, label_training, test_size=0.33)\n F_Test_Train,F_Test_Test,Label_Test_Train,Label_Test_Test= train_test_split(featuremat_test,label_test, test_size=0.70)\n \n #classifier\n if Classifier=='SVC':\n clf = SVC(kernel='linear')\n elif Classifier=='LR':\n clf = LogisticRegression()\n elif Classifier=='RF':\n clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)\n elif Classifier=='GB':\n clf = GradientBoostingClassifier()\n \n #recursive feature elimination\n selector = RFE(clf, 1, step=1)\n Label_train=np.ravel(Label_Training_Train)\n Label_test =np.ravel(Label_Test_Test)\n selector = selector.fit(F_Training_Train, Label_train)\n rank = selector.ranking_\n Rank.append(rank)\n rank = np.asarray(rank)\n \n #create a list that contains index number of ranked features\n rankedlist = np.zeros((14,1))\n \n #finding index of the ranked features and creating new training and test sets with respect to this ranking\n for m in range (1,15):\n k=np.where(rank==m)\n rankedlist[m-1]=k[0][0]\n F_Training_Train[:,m-1] = F_Training_Train[:,int(rankedlist[m-1][0])]\n F_Test_Test[:,m-1] = F_Test_Test[:,int(rankedlist[m-1][0])] \n RankedList.append(rankedlist)\n \n #trying various combinations of ranked features such as ([1],[1,2],[1,2,3]...)\n for p in range(0,14): \n start1 = time.time()\n clf.fit(F_Training_Train[:,0:p+1],Label_train)\n score1=clf.score(F_Test_Test[:,0:p+1],Label_test)\n score2=clf.score(F_Training_Train[:,0:p+1],Label_train)\n accuracy1[p,o]=score1\n accuracy2[p,o]=score2\n end1=time.time()\n duration1[p,o] = end1 - start1\n \n #computing mean score and deviation for each combination tried above \n for n in range(0,14):\n deviation1[n,0]=np.std(accuracy1[n,:])\n deviation2[n,0]=np.std(accuracy2[n,:])\n meanscore1[n,0]=np.mean(accuracy1[n,:])\n meanscore2[n,0]=np.mean(accuracy2[n,:])\n meanduration[n,0]=np.mean(duration1[n,:])\n \n \n results = np.concatenate((meanscore1,deviation1,meanscore2,deviation2),axis=1)\n results = 100*results \n \n #total duration for algorithm \n end2 = time.time()\n duration2 = end2-start2\n \n \n return results,print('Total elapsed time: {}'.format(duration2)) ,featuremat_train, featuremat_test \n ","sub_path":"WPT_EEMD_ML/WPT_Transfer_Learning.py","file_name":"WPT_Transfer_Learning.py","file_ext":"py","file_size_in_byte":12483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"140072429","text":"import os\nimport subprocess\nimport sys\nimport tkinter as tk\nfrom tkinter import ttk, StringVar,PhotoImage\nimport time\nBACKGROUND_LIGHT = \"Light\"\nBACKGROUND_DARK = \"Dark\"\nclass TimerDisplay(tk.Toplevel):\n def __init__(self,parent,bg=BACKGROUND_DARK,*args,**kwargs):\n super().__init__(parent,*args,**kwargs)\n\n\n self.timer_running_flag = 0\n self.flash_color = 0\n s = ttk.Style()\n s.theme_use('clam')\n if bg == BACKGROUND_DARK:\n bg_color = 'deepskyblue4'\n s.configure('time.Label', background='deepskyblue4', foreground='snow', font=('arial', 30, 'bold'))\n s.configure('flash.Label', background='deepskyblue4', foreground='cyan', font=('arial', 60, 'bold'))\n s.configure('timer.Label', background='deepskyblue4', foreground='snow',\n font=('arial', 60, 'bold'))\n s.configure('minutes.Label', background='deepskyblue4', foreground='snow',\n font=('arial', 8, 'bold'))\n s.configure('timer.TButton', background='deepskyblue4', foreground='snow',borderwidth=0)\n s.map('timer.TButton', background=[('pressed', 'deepskyblue4'),('active', '!disabled', 'cyan') ],\n foreground=[('pressed', 'snow'), ('active', 'snow')])\n else:\n bg_color = 'beige'\n s.configure('time.Label', background='beige', foreground='firebrick', font=('arial', 30, 'bold'))\n s.configure('flash.Label', background='beige', foreground='turquoise', font=('arial', 60, 'bold'))\n s.configure('timer.Label', background='beige', foreground='firebrick',\n font=('arial', 60, 'bold'))\n s.configure('timer.TButton', background='beige', foreground='firebrick', borderwidth=0)\n s.map('timer.TButton', background=[('pressed', 'snow'), ('active', '!disabled', 'snow')],\n foreground=[('pressed', 'firebrick'), ('active', 'firebrick')])\n\n\n self.configure(background=bg_color,borderwidth=2,relief=tk.GROOVE)\n #parent.configure(background=bg_color)\n self.time_val = StringVar()\n self.minutes_val = StringVar()\n self.minutes_val.set('00')\n self.time_label = ttk.Label(self,textvariable=self.time_val,style=\"time.Label\")\n self.timer_control_label = ttk.Label(self, textvariable=self.minutes_val, style=\"timer.Label\")\n self.minutes_label = ttk.Label(self, text=\"in minutes\", style=\"minutes.Label\")\n self.image_plus = PhotoImage(file=\"../images/signs_plus_real.png\")\n self.image_minus = PhotoImage(file=\"../images/signs_minus_real.png\")\n self.image_start = PhotoImage(file=\"../images/power-button.png\")\n self.timer_plus_button = ttk.Button(self,text=\"\",image=self.image_plus,style=\"timer.TButton\",command=self.add_minutes)\n self.timer_minus_button = ttk.Button(self, text=\"\", image=self.image_minus,style=\"timer.TButton\",command=self.reduct_minutes)\n self.timer_start_button = ttk.Button(self, text=\"\", image=self.image_start,style=\"timer.TButton\",command=self.timer_control)\n self.time_display()\n self.minutes_label.pack(side=tk.BOTTOM, pady=5, padx=0)\n self.timer_start_button.pack(side=tk.BOTTOM, pady=0,anchor=tk.S)\n\n self.timer_minus_button.pack(side=tk.LEFT,pady = 30)\n\n self.timer_control_label.pack(side=tk.LEFT,pady= 2,padx=10)\n self.timer_plus_button.pack(side=tk.RIGHT, pady = 30)\n\n\n\n\n\n def add_minutes(self):\n minutes = int(self.minutes_val.get())\n if minutes < 100 :\n if minutes < 9:\n self.minutes_val.set('0'+str(minutes+1))\n else:\n self.minutes_val.set(str(minutes+1))\n else:\n self.minutes_val.set('00')\n\n def reduct_minutes(self):\n minutes = int(self.minutes_val.get())\n if minutes > 0:\n if minutes < 10:\n self.minutes_val.set('0'+str(minutes - 1))\n else:\n self.minutes_val.set(str(minutes - 1))\n else:\n self.minutes_val.set(str('00'))\n\n def time_display(self):\n self.time_val.set(time.strftime(\"%I:%M %p\"))\n self.time_label.pack()\n if (self.timer_running_flag == 1):\n if (self.flash_color == 0):\n self.timer_control_label.configure(style=\"flash.Label\")\n self.flash_color = 1\n else:\n self.timer_control_label.configure(style=\"timer.Label\")\n self.flash_color = 0\n else:\n self.timer_control_label.configure(style=\"timer.Label\")\n self.after(1000,self.time_display)\n\n def timer_control(self):\n self.timer_running_flag = 1\n self.minutes_val.set(str(int(self.minutes_val.get()) + 1))\n self.run_timer()\n\n def run_timer(self):\n self.reduct_minutes()\n self.timer_start_button.configure(state=\"disabled\")\n self.timer_minus_button.configure(state=\"disabled\")\n self.timer_plus_button.configure(state=\"disabled\")\n if (int(self.minutes_val.get()) == 0):\n self.timer_start_button.configure(state=\"normal\")\n self.timer_minus_button.configure(state=\"normal\")\n self.timer_plus_button.configure(state=\"normal\")\n self.timer_running_flag = 0\n\n file_beep_path = os.path.abspath(os.path.join(os.getcwd(), \"..\", \"images\", \"beep-12.wav\"))\n\n if sys.platform == \"win32\":\n os.startfile(file_beep_path)\n else:\n opener = \"open\" if sys.platform == \"darwin\" else \"xdg-open\"\n subprocess.call([opener, file_beep_path])\n return\n\n self.after(60000,self.run_timer)\n\n\nif __name__== \"__main__\":\n timer_app = tk.Tk()\n timer_app.title(\"Timer\")\n timer_app.geometry(\"250x250\")\n frame = TimerDisplay(timer_app)\n frame.pack()\n timer_app.mainloop()\n\n\n\n","sub_path":"sources/Timer_Display.py","file_name":"Timer_Display.py","file_ext":"py","file_size_in_byte":5920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"638613466","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom qmt.tasks import Task, SweepManager, SweepTag\n\n\nclass HelloSweepTask(Task):\n\n def __init__(self, language_options):\n super().__init__(options=language_options)\n\n @staticmethod\n def _solve_instance(inputs, options):\n greetings = {'English': 'Hello', 'Spanish': 'Hola'}\n print(greetings[options['language']] + ' World')\n\n\nprint('Run a sweep over the languages:')\nlang_tag = SweepTag('language tag description')\nsweep = [{lang_tag: 'English'}, {lang_tag: 'Spanish'}]\nlm = SweepManager(sweep)\nbilingual = HelloSweepTask({'language': lang_tag})\n\nlm.run(bilingual).result()\n\n\nclass NameTask(Task):\n\n def __init__(self, name_options):\n super().__init__(options=name_options)\n\n @staticmethod\n def _solve_instance(inputs, options):\n return options['name']\n\n\nclass HelloDependentTask(Task):\n\n def __init__(self, name_task, language_options):\n super().__init__(task_list=[name_task], options=language_options)\n\n @staticmethod\n def _solve_instance(inputs, options):\n greetings = {'English': 'Hello', 'Spanish': 'Hola'}\n name = inputs[0]\n print(greetings[options['language']] + ' ' + name)\n\n\nprint('Chaining a NameTask and a sweep of HelloDependingTask:')\nname = NameTask({'name': 'John'})\nlm = SweepManager(sweep)\nbilingual = HelloDependentTask(name, {'language': lang_tag})\n\nlm.run(bilingual).result()\n\nprint('We can build arbitrary sweeps:')\nname_tag = SweepTag('name tag description')\nlang_tag = SweepTag('language tag description')\nname = NameTask({'name': name_tag})\ngreet = HelloDependentTask(name, {'language': lang_tag})\nsweeps = [{name_tag: 'John', lang_tag: 'English'}, {name_tag: 'Jose', lang_tag: 'Spanish'}]\ntm = SweepManager(sweeps)\n\ntm.run(greet).result()\n\nprint('Or cartesian products:')\nname = NameTask({'name': name_tag}) # need new NameTask, 'greet' consumed the previous\ngreet = HelloDependentTask(name, {'language': lang_tag})\nvalues = {name_tag: ['John', 'Jose'], lang_tag: ['English', 'Spanish']}\ncartesian = SweepManager.construct_cartesian_product(values)\n\ncartesian.run(greet).result()\n","sub_path":"examples/task_hello_sweep.py","file_name":"task_hello_sweep.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"73118438","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 21 15:11:31 2014\n\n@author: ibackus\n\"\"\"\n\nimport pynbody\nSimArray = pynbody.array.SimArray\nimport numpy as np\nimport isaac\n\ndef snapshot_gen(ICobj):\n \"\"\"\n Generates a tipsy snapshot from the initial conditions object ICobj.\n \n Returns snapshot, param\n \n snapshot: tipsy snapshot\n param: dictionary containing info for a .param file\n \"\"\"\n \n # Constants\n G = SimArray(1.0,'G')\n kB = SimArray(1.0,'k')\n # ------------------------------------\n # Load in things from ICobj\n # ------------------------------------\n # snapshot file name\n snapshotName = ICobj.settings.filenames.snapshotName\n # particle positions\n theta = ICobj.pos.theta\n r = ICobj.pos.r\n x = ICobj.pos.x\n y = ICobj.pos.y\n z = ICobj.pos.z\n # Number of particles\n nParticles = ICobj.pos.nParticles\n # Temperature power law (used for pressure gradient)\n Tpower = ICobj.settings.physical.Tpower\n # molecular mass\n m = ICobj.settings.physical.m\n # star mass\n m_star = ICobj.settings.physical.M.copy()\n # disk mass\n m_disk = ICobj.sigma.m_disk.copy()\n m_disk = isaac.match_units(m_disk, m_star)[0]\n # mass of the gas particles\n m_particles = np.ones(nParticles) * m_disk / float(nParticles)\n # re-scale the particles (allows making of lo-mass disk)\n m_particles *= ICobj.settings.snapshot.mScale\n \n # ------------------------------------\n # Initial calculations\n # ------------------------------------\n # Find total mass interior to every particle\n N_interior = np.array(r.argsort().argsort())\n m_int = m_particles[[0]]*N_interior + m_star\n # Retrieve rho (density) at each position\n rho = ICobj.rho(z,r)\n # Retrieve radial derivative at each position\n drho_dr = ICobj.rho.drho_dr(z,r)\n # Get temperature at each position\n T = ICobj.T(r)\n \n # ------------------------------------\n # Calculate particle velocities\n # ------------------------------------\n # Find keperlerian velocity squared due to gravity\n v2grav = G*m_int/r\n # Find contribution from density gradient\n v2dens = (kB*T/m)*(r*drho_dr/rho)\n # ignore nans and infs\n v2dens[(np.isnan(v2dens)) | (np.isinf(v2dens))] = 0.0\n # Find contribution from temperature gradient\n v2temp = (kB*T/m)*Tpower\n # Now find velocity from all contributions\n v = np.sqrt(v2grav + v2dens + v2temp)\n # Sometimes, at large r, the velocities due to the pressure and temp\n # Gradients become negative. If this is the case, set them to 0\n nanind = np.isnan(v)\n v[nanind] = 0.0\n \n # -------------------------------------------------\n # Assign output\n # -------------------------------------------------\n # Get units all set up\n m_unit = m_star.units\n pos_unit = r.units\n # time units are sqrt(L^3/GM)\n t_unit = np.sqrt((pos_unit**3)*np.power((G*m_unit), -1)).units\n # velocity units are L/t\n v_unit = (pos_unit/t_unit).ratio('km s**-1')\n # Make it a unit\n v_unit = pynbody.units.Unit('{} km s**-1'.format(v_unit))\n x.convert_units(pos_unit)\n y.convert_units(pos_unit)\n z.convert_units(pos_unit)\n \n # 3-D velocity\n vel = SimArray(np.zeros([nParticles,3]),v_unit)\n vel[:,0] = -np.sin(theta)*v\n vel[:,1] = np.cos(theta)*v\n \n # Generate positions\n xyz = SimArray(np.zeros([nParticles,3]),pos_unit)\n xyz[:,0] = x\n xyz[:,1] = y\n xyz[:,2] = z\n \n # Other settings\n eps = ICobj.settings.snapshot.eps\n star_eps = eps\n eps *= SimArray(np.ones(nParticles), pos_unit)\n metals = ICobj.settings.snapshot.metals\n star_metals = metals\n metals *= SimArray(np.ones(nParticles))\n \n # Generate snapshot\n snapshot = pynbody.new(star=1,gas=nParticles)\n snapshot.gas['vel'] = vel\n snapshot.gas['pos'] = xyz\n snapshot.gas['temp'] = T\n snapshot.gas['mass'] = m_particles\n snapshot.gas['metals'] = metals\n snapshot.gas['eps'] = eps\n snapshot.gas['mu'].derived = False\n snapshot.gas['mu'] = float(m.in_units('m_p'))\n \n snapshot.star['pos'] = SimArray([[ 0., 0., 0.]],pos_unit)\n snapshot.star['vel'] = SimArray([[ 0., 0., 0.]], v_unit)\n snapshot.star['mass'] = m_star\n snapshot.star['metals'] = SimArray(star_metals)\n snapshot.star['eps'] = SimArray(star_eps, pos_unit)\n \n param = isaac.make_param(snapshot, snapshotName)\n \n return snapshot, param","sub_path":"backup01/make_snapshot.py","file_name":"make_snapshot.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"645262414","text":"import sys\nimport glob\nimport codecs\nimport os\n\ndef read_names(path):\n lines = [line.split(\" \")[0] + \".TextGrid\" for line in codecs.open(path)]\n return list(set(lines))\n\ndef main():\n textgrid_folder = sys.argv[1] if sys.argv[1][-1] == '/' else sys.argv[1] + '/' \n textgrids = read_names(sys.argv[2])\n output_folders = [\"abiayi\",\"kouarata\",\"martial\"]\n for name in output_folders:\n try:\n os.stat(textgrid_folder + name)\n except:\n os.makedirs(textgrid_folder + name)\n #print len(audio_file)\n cwd = os.getcwd() + \"/\"\n for file_name in textgrids:\n folder = file_name.split(\"_\")[0]\n new_file_name = cwd + textgrid_folder + file_name.replace(folder+\"_\", folder+\"/\")\n current_file_name = cwd + textgrid_folder + file_name.replace(folder+\"_\", \"\")\n #print current_file_name, new_file_name\n os.rename(current_file_name, new_file_name)\n try: \n os.rename(current_file_name.replace(\".TextGrid\", \".wav\"), new_file_name.replace(\".TextGrid\", \".wav\"))\n except Exception:\n pass\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"praat/scripts/utils/filter_textgrids.py","file_name":"filter_textgrids.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"422287358","text":"import torch\r\nimport torchvision as tv\r\nimport torchvision.transforms as transforms\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\n\r\n#import argparse\r\n# 定义是否使用GPU\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\nprint(device)\r\n# 定义网络结构\r\nclass LeNet_teachehr(nn.Module):\r\n def __init__(self):\r\n super(LeNet_teachehr, self).__init__()\r\n self.conv1 = nn.Conv2d(1, 20, 5, padding=0)\r\n self.bn1 = nn.BatchNorm2d(20)\r\n self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2)\r\n self.conv2 = nn.Conv2d(20, 50, 5, padding=0)\r\n self.bn2 = nn.BatchNorm2d(50)\r\n self.maxpool2 = nn.MaxPool2d(2, 2)\r\n\r\n self.conv3 = nn.Sequential(\r\n nn.Conv2d(50, 500, 4, padding=0),\r\n nn.BatchNorm2d(500),\r\n nn.ReLU(),\r\n\r\n\r\n )\r\n self.conv4 = nn.Conv2d(500, 10, 1, padding=0)\r\n\r\n # 定义前向传播过程,输入为x\r\n def forward(self, x):\r\n print('conv1',x.shape)\r\n out = []\r\n x = self.conv1(x)\r\n out.append(x)\r\n x = self.bn1(x)\r\n x = self.maxpool1(x)\r\n out.append(x)\r\n print('conv2', x.shape)\r\n x = self.conv2(x)\r\n out.append(x)\r\n x = self.bn2(x)\r\n x = self.maxpool2(x)\r\n # print('before conv3', x.shape)\r\n # x = self.conv3(x)\r\n # print('after conv3', x.shape)\r\n # x = self.conv4(x)\r\n # x = x.view(x.size()[0], -1)\r\n return x, out\r\n\r\ndef LNT(pretrained=False, **kwargs):\r\n \"\"\"Constructs a ResNet-18 model.\r\n Args:\r\n pretrained (bool): If True, returns a model pre-trained on ImageNet\r\n \"\"\"\r\n model = LeNet_teachehr()\r\n if pretrained:\r\n #model.load_state_dict(torch.load('/home/yuhan_jiang/handwriting/LeNet_zyy.pth'))\r\n model.load_state_dict(torch.load('./LeNet_teacher.pth'))\r\n return model\r\n","sub_path":"LeNet_teacherclassifer.py","file_name":"LeNet_teacherclassifer.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"603833188","text":"import config\nimport os\nfrom utils import printd, PrintException\n\nclass ConfigManager:\n active_configs = None\n loaded_configs = []\n\n\n def __init__(self):\n self.active_configs = config.ACTIVE_CONFIGS\n self.loadConfigs()\n\n def loadConfigs(self):\n for config in self.active_configs:\n try:\n x = reload(__import__(\"configs.\"+config))\n except ImportError:\n printd (\"Import %s didn't work\" % config)\n continue\n try:\n cls = getattr(getattr(x,config),config)\n\n except AttributeError:\n printd (\"getattr error!\")\n PrintException()\n continue\n self.loaded_configs.append(cls)","sub_path":"lib/ConfigManager.py","file_name":"ConfigManager.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"456572547","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 17 10:14:52 2019\n\n@author: Michael\n\"\"\"\n\n\n# part 1.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Helper_Class\n\nmyhelperclass = Helper_Class.Helper_Class()\n\n# define weight vector for 5 elements\n\nw = np.array([1,2,3,4,5])\n\n# generate 30 training samples by randomly picking feature vector values and generating targets\n\nX_train = 10*np.random.rand(30,5) \ny_train = np.dot(X_train, w) + np.random.normal(0,10, 30)\n\n# generate 30 validation samples by randomly picking feature vector values and generating targets\n\nX_val = 10*np.random.rand(30,5)\ny_val = np.dot(X_val, w) + np.random.normal(0,10, 30)\n\nw_0 = np.zeros(5)\n\nmyhelperclass = Helper_Class.Helper_Class()\n\n# set stopping criterias\n\nepsilon = .5\n\nmax_iter = 100000\n\n# set regularization constant to zero\n\nlambda_0 = 0\n\n# set initial weights to zero\n\nX_train_shape = X_train.shape\n\nw_0 = np.zeros(X_train_shape[1])\n\n# define list of learning rates to try\n\nalpha_list = [10**0,10**(-1),10**(-2),10**(-3),10**(-4),10**(-5),10**(-6),10**(-7)]\n\n# run descent algorithm using each learning rate and compute SSE for training and validation set\n\nSSE_val_final = []\nfinal_w_for_alpha = []\n\nfor alpha in alpha_list:\n \n # run gradient descent using given input values\n\n [w_vecs, w_grad_vecs, w_grad_norms] = myhelperclass.run_gradient_descent(y_train, X_train, w_0,alpha, lambda_0, epsilon, max_iter)\n \n # compute Sum of Square errors for training and test set for ever weight vector generated using \n # gradient descent \n \n SSE_train = myhelperclass.calculuate_SSE(w_vecs, y_train, X_train)\n SSE_val = myhelperclass.calculuate_SSE(w_vecs,y_val, X_val)\n\n # create list of ending weight vectors, \n \n final_w_for_alpha.append(w_vecs[len(SSE_train)-1])\n \n # create integer based spacing to graph SSE for each weight vector associated\n # with a given iteration\n \n x_axis = np.linspace(0,len(SSE_train)-1,len(SSE_train))\n\n plt.figure()\n\n plt.plot(x_axis,SSE_train, x_axis, SSE_val)\n plt.title(\"SSE for training and validation data, alpha: \" + str(alpha) + \" lambda: \" + str(lambda_0))\n plt.xlabel(\"training iteration\")\n plt.ylabel(\"SSE\")\n plt.legend([\"SSE_Training\", \"SSE_Testing\"])\n plt.show()\n\n plt.figure()\n\n plt.plot(x_axis, w_grad_norms)\n plt.title(\"Norm of gradient\")\n plt.xlabel(\"training iteration\")\n plt.ylabel(\"gradient norm\")\n plt.show()\n \n # create list of final sum of squared errors\n \n SSE_val_final.append(SSE_val[len(SSE_val)-1])\n \n# select best learning rate based upon best SSE for final weight using validation data\n \nalpha_best = alpha_list[SSE_val_final.index(min(SSE_val_final))]\n \nprint(\"The best learning rate based upon validation SSE is \" + str(alpha_best))\n \n# select best final weight vector using best SSE for final weights using validation data\n \nw_best = final_w_for_alpha[SSE_val_final.index(min(SSE_val_final))]\n \nprint(\"The best final weight based upon validation SSE is\" +str(w_best))\n\nprint(\"The feature with the greatest weight is in position \" + str(np.max((np.abs(w_best)))))","sub_path":"I1/extra_stuff/Part_1_using_synthetic_data.py","file_name":"Part_1_using_synthetic_data.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"436895471","text":"from django.conf.urls import url\nfrom django.views.generic.base import TemplateView\n\nfrom .views import (\n CategoryListView, NominationView, NominationListView,\n VoteView, WinnersView,\n vote_overview,\n scores\n)\n\n\nurlpatterns = [\n url(r'^vote/overview/$', vote_overview),\n url(r'^vote/scores/$', scores),\n] + [\n url(r'^$', TemplateView.as_view(template_name='awards/base.html'), name='awards_index'),\n url(r'^categories/$', CategoryListView.as_view(), name='category-list'),\n url(r'^categories/(?P\\d+)/$', NominationListView.as_view()),\n url(r'^categories/(?P[\\w0-9\\-_]+)/$', NominationListView.as_view(), name='nominations-list'),\n url(r'^nomination/', NominationView.as_view(), name='add_nomination'),\n url(r'^voting/', VoteView.as_view(), name='voting'),\n url(r'^winners/(?P\\d{4})/$', WinnersView.as_view(), name='winners'),\n url(r'^winners/$', WinnersView.as_view(), name='winners'),\n]\n","sub_path":"src/brouwers/awards/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"553095157","text":"from Model.Tweet import Tweet\nfrom Service.Woordenlijst import negatievewoorden, positievewoorden\n\nimport re\n\nclass AnalyzeService():\n def __init__(self, TweetController):\n self.tweetController = TweetController\n\n def analyze_tweet(self, tweet):\n\n \"\"\"\n De tweets opschonen en analyseren.\n \"\"\"\n text = tweet.get_text()\n \"\"\"methode om de tweet text op te schonen zodat deze te analyseren is.\n Hierna is newText de schone text die de clean_text methode returned.\n \"\"\"\n newText = self.clean_text(text)\n pos = 0\n neg = 0\n print(newText)\n \"\"\"\n Alle positie en negatievewoorden zitten in een lijst. De woorden die in de tweet staan en ook\n in 1 van deze twee lijsten staan worden gecheckt. Als er een woord in 1 van de twee lijsten\n verschijnt dan wordt er bij neg of pos 1 opgeteld. Als neg > pos dan is de tweet negatief.\n Als pos > neg dan is de tweet positief. Als neg = pos of pos = neg dan is de tweet neutraal.\n \"\"\"\n for word in newText:\n if word in negatievewoorden:\n neg += 1\n elif word in positievewoorden:\n pos += 1\n\n if pos > neg:\n tweet.setMood(\"pos\")\n elif neg > pos:\n tweet.setMood(\"neg\")\n else:\n tweet.setMood(\"neu\")\n print(str(pos) + \" -- \" + str(neg))\n self.tweetController.save_tweet(tweet)\n\n \"\"\"\n Methode om tekens uit de tweet te halen.\n \"\"\"\n def clean_text(self, text):\n text = text.lower()\n # Remove links\n text = re.sub('((www\\.[^\\s]+)|(https?://[^\\s]+)|(http://[^\\s]+))','URL',text)\n # Remove mentions\n text = re.sub('@[^\\s]+','MENTION',text)\n # Remove white spaces\n text = re.sub('[\\s]+', ' ', text)\n # Remove hashtag from words\n text = re.sub(r'#([^\\s]+)', r'\\1', text)\n\n #trim\n text = text.strip('\\'\"')\n # Split text to array\n text = text.split()\n return text\n\n\n","sub_path":"Service/AnalyzeService.py","file_name":"AnalyzeService.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"296505000","text":"from django.test import TestCase\n\nfrom nfl_rushing.models import NflPlayerRushing\n\nfrom .utils import reverse_with_args\n\nclass TestCsvDownload(TestCase):\n fixtures = ['test_data.json']\n\n CSV_HEADER = 'Name,Team,Position,Rushing Attempts,Rushing attempts per game,Total rushing yards,Rushing yards per attempt,Rushing yards per game,Total rushing touchdowns,Longest Rush,Longest rush was touchdown,Rush first downs,Rush first down %,Rush 20+ yards,Rush 40+ yards,Rush fumbles'\n\n player_1 = 'Person 1,A,QB,0,0.0,0,0.0,0.0,2,1,false,0,0.0,0,0,0'\n player_2 = 'Person 2,B,QB,1,1.0,1,1.0,1.1,1,0,false,1,1.0,1,1,1'\n player_3 = 'Person 3,C,QB,2,2.0,2,2.0,2.0,0,2,false,2,2.0,2,2,2'\n\n def test_csv_download(self):\n response = self.client.get(reverse_with_args('nfl_rushing:download_csv'))\n self.assertEqual(response.status_code, 200)\n\n expected_content = '\\r\\n'.join([self.CSV_HEADER, self.player_1, self.player_2, self.player_3])\n\n self.assertEqual(response.content.decode('utf-8').strip(), expected_content)\n \n def test_csv_download_with_filter(self):\n url = reverse_with_args(\n 'nfl_rushing:download_csv',\n query_kwargs={\n 'name_filter': '2'\n }\n )\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n\n expected_content = '\\r\\n'.join([self.CSV_HEADER, self.player_2])\n\n self.assertEqual(response.content.decode('utf-8').strip(), expected_content)\n \n def test_csv_download_with_sort(self):\n url = reverse_with_args(\n 'nfl_rushing:download_csv',\n query_kwargs={\n 'sort_option': 'longest_rush'\n }\n )\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n\n expected_content = '\\r\\n'.join([self.CSV_HEADER, self.player_3, self.player_1, self.player_2])\n\n self.assertEqual(response.content.decode('utf-8').strip(), expected_content)\n\n def test_csv_download_with_sort_inc(self):\n url = reverse_with_args(\n 'nfl_rushing:download_csv',\n query_kwargs={\n 'sort_option': 'longest_rush',\n 'sort_direction': 'asc'\n }\n )\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)\n\n expected_content = '\\r\\n'.join([self.CSV_HEADER, self.player_2, self.player_1, self.player_3])\n\n self.assertEqual(response.content.decode('utf-8').strip(), expected_content)","sub_path":"web/nfl_rushing/tests/test_csv.py","file_name":"test_csv.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"229256899","text":"import socket\nimport nmap\nfrom netaddr import IPNetwork\n\n\ndef check_if_scan_available(device_names_to_avoid=()):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n s = s.getsockname()[0]\n ip = str(IPNetwork(str(f'{s}/255.255.255.0')).cidr)\n nm = nmap.PortScanner()\n scan = nm.scan(ip, arguments=\"-sn\")\n for host in scan.get('scan'):\n device = scan['scan'][host]\n if len(device['hostnames']) > 0:\n if device['hostnames'][0]['name'] != '' and device['hostnames'][0]['name'] in device_names_to_avoid:\n return False\n return True\n\n\nif __name__ == '__main__':\n allowed = check_if_scan_available()\n","sub_path":"spd_core/network_tools/network_tools.py","file_name":"network_tools.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"66452023","text":"\"\"\"\nGiven a collection of integers that might contain duplicates, nums, \nreturn all possible subsets.\n\nNote:\nElements in a subset must be in non-descending order.\nThe solution set must not contain duplicate subsets.\nFor example,\nIf nums = [1,2,2], a solution is:\n\n[\n [2],\n [1],\n [1,2,2],\n [2,2],\n [1,2],\n []\n]\n\"\"\"\ndef subsetsWithDup(nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n nums = sorted(nums)\n result = [[]]\n if len(nums) == 0:\n return result\n subset_help(nums, 0, [], result)\n return result\n\n\ndef subset_help(nums, index, item, result):\n for i in xrange(index, len(nums)):\n if i > index and nums[i] == nums[i - 1]:\n continue\n new_one = item + [nums[i]]\n result.append(new_one)\n subset_help(nums, i + 1, new_one, result)","sub_path":"leetcode/subsets_ii.py","file_name":"subsets_ii.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"436889786","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nimport requests\nfrom lxml.html import document_fromstring\n\ndef update_head(head, sid):\n \"\"\"update headers for second request\"\"\"\n\n head.update({'Referer': sid})\n head.update({'X-Requested-With': 'XMLHttpRequest'})\n head.update({'Content-Type': 'application/x-www-form-urlencoded'})\n head.update({'Accept': 'application/json, text/javascript, */*'})\n return head\n\ndef date_check(value, compare_date):\n \"\"\"cheking date for issues\"\"\"\n\n valid = False\n while not valid:\n try:\n datetime.strptime(value, '%Y-%m-%d')\n if datetime.strptime(value, '%Y-%m-%d').date() < compare_date:\n print('you are late... Are you interested in another date, by any chance?')\n value = input()\n else:\n valid = True\n except ValueError:\n print(\"I SAID 'YYYY-MM-DD' !!!\")\n print('Would you please insert correct date?')\n value = input()\n return value\n\ndef ports_base():\n \"\"\"retrieve airport values\"\"\"\n\n url = ('http://www.flyniki.com/en/site/json/suggestAirport.php?searchfor='\n 'departures&searchflightid=0&departures%5B%5D=&destinations%5B%5D='\n 'City%2C+airport&suggestsource%5B0%5D=activeairports&withcountries'\n '=0&withoutroutings=0&promotion%5Bid%5D=&promotion%5Btype%5D=&get_'\n 'full_suggest_list=false&routesource%5B0%5D=airberlin&routesource%5B1%5D=partner')\n request_port = requests.get(url) #webserver gives the data away\n x = request_port.json().get('suggestList') \n base = [i.get('code') for i in x]\n return base\n\ndef getting_params():\n \"\"\"gathering parameters\"\"\"\n\n places = ['departure', 'destination']\n base = ports_base()\n k = 'you will never guess what I contain, never ever!'\n for place in places:\n print('insert ', place)\n inserted_iata = input().upper()\n while inserted_iata not in base or inserted_iata == k:\n print('value is not acceptable or the same as the previous one, try again')\n inserted_iata = input().upper()\n data_first_request.update({place: inserted_iata})\n k = inserted_iata\n\n print('insert outbound date - yyyy-mm-dd')\n out = date_check(input(), datetime.today().date()) #comparing inserted date with current one\n data_first_request.update({'outboundDate': out})\n json_second_request.update({'_ajax[requestParams][outboundDate]': out})\n\n print('insert return date - yyyy-mm-dd, skip for oneway')\n ret = input()\n if ret != '':\n ret = date_check(ret, datetime.strptime(out, '%Y-%m-%d').date())#compering with 1st date\n data_first_request.update({'returnDate': ret})\n json_second_request.update({'_ajax[requestParams][returnDate]': ret})\n else:\n data_first_request.update({'oneway': '1'})\n json_second_request.update({'_ajax[requestParams][returnDate]': out})\n json_second_request.update({'_ajax[requestParams][oneway]': 'on'})\n\ndef request_flyniki(count, url=None):\n \"\"\"making required requests and retrieving data from responses\"\"\"\n\n head = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',\n 'Accept-Encoding': 'gzip, deflate',\n 'Connection': 'keep-alive',\n 'Upgrade-Insecure-Requests': '1'\n }\n if count == 'first':\n url = 'http://www.flyniki.com/en/booking/flight/vacancy.php?'\n first_request = s.get(url, headers=head, params=data_first_request)\n\n tree_1 = document_fromstring(first_request.text) #getting names of airports\n dst_name = tree_1.get_element_by_id('destination').get('value').replace(' ', '+')\n dep_name = tree_1.get_element_by_id('departure').get('value').replace(' ', '+')\n json_second_request.update({'_ajax[requestParams][destination]': dst_name})\n json_second_request.update({'_ajax[requestParams][departure]': dep_name})\n\n return first_request.url\n elif count == 'second':\n second_request = s.post(url, headers=update_head(head, url), data=json_second_request)\n\n tree = document_fromstring(str(second_request.json()))\n to_parse = tree.xpath('//div[@class=\"lowest\"]/span') #2nd response's info\n if to_parse: #checking that server gave valid html and there is data in it\n for i in range(len(to_parse)):\n print(to_parse[i].attrib.get('title'), 'pounds')\n else: print('no data was found')\n\ndata_first_request = {\n 'openDateOverview': '0',\n 'adultCount': '1',\n 'childCount': '0',\n 'infantCount': '0',\n 'oneway': '0'\n }\njson_second_request = {\n '_ajax[templates][]': ['main', 'priceoverview', 'infos', 'flightinfo',],\n '_ajax[requestParams][returnDeparture]' : '',\n '_ajax[requestParams][returnDestination]': '',\n '_ajax[requestParams][adultCount]':\tdata_first_request.get('adultCount'),\n '_ajax[requestParams][childCount]': data_first_request.get('childCount'),\n '_ajax[requestParams][infantCount]': data_first_request.get('infantCount'),\n '_ajax[requestParams][openDateOverview]': '',\n '_ajax[requestParams][oneway]': ''\n }\n\ngetting_params()\ns = requests.Session()\nurl_sid = request_flyniki('first')\nrequest_flyniki('second', url_sid)\n","sub_path":"iata_start.py","file_name":"iata_start.py","file_ext":"py","file_size_in_byte":5467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"418294134","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.shortcuts import HttpResponse\nfrom .forms import RecipeModel, NewProfileModel, newProfileForm, RecipeForm\n\nfrom django.contrib.auth.models import User\n\n# this page renders from startup, if user is logged in, the user can see all entries\ndef index(request):\n if request.user.is_authenticated:\n\n profile = NewProfileModel.objects.get(name=request.user)\n\n allEntries = RecipeModel.objects.filter(foreignkeyToNewProfile=profile)\n else:\n allEntries = \"\"\n\n context = {'allEntries': allEntries}\n\n return render(request, 'recipeApp/index.html', context)\n\n# this creates a user and saves it the database\ndef newUser(request):\n\n form = newProfileForm(request.POST or None)\n if form.is_valid():\n form.save()\n User.objects.create_user(request.POST['name'], '', request.POST['password1'])\n return redirect('index')\n else:\n\n context = {'errors': form.errors,\n 'form': form\n }\n return render(request, 'recipeApp/newuser.html', context)\n\n# function that renders the form to add a recipe to a LOGGED IN user\ndef addRecipe(request):\n form = RecipeForm()\n context = {\n 'recipeform': form\n }\n return render(request, 'recipeApp/addrecipe.html', context)\n\n# renders the data/details of the page.\ndef recipeInfo(request):\n form = RecipeForm(request.POST)\n print(request.user)\n profile = NewProfileModel.objects.get(name=request.user)\n\n newform = form.save(commit=False)\n newform.foreignkeyToNewProfile = profile\n newform.save()\n return render(request, 'recipeApp/addrecipe.html',)\n\n\n# renders a selected object and allows it to be changed/edited,\n\ndef editRecipe(request, recipeID):\n editthisrecipe = get_object_or_404(RecipeModel, pk=recipeID)\n if request.method == 'POST':\n form = RecipeForm(request.POST, instance=editthisrecipe)\n if form.is_valid():\n form.save()\n else:\n print('not valid')\n return redirect('index')\n form = RecipeForm(instance=editthisrecipe)\n context = {\n 'recipeform': form,\n 'recipeID': recipeID\n }\n\n return render(request, 'recipeApp/editrecipe.html', context)\n\n# deletes a recipe\ndef deleteRecipe(request, recipeID):\n deleteThisrecipe = get_object_or_404(RecipeModel, pk=recipeID)\n deleteThisrecipe.deltet()\n return redirect('index')\n","sub_path":"recipeProject/recipeApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"421471235","text":"\"\"\"\nCreated on Tue Jan 26 16:41:35 2021\n\n@author: mark\n\"\"\"\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom aircraft_detector.utils.utils import print_verbose\nimport aircraft_detector.utils.pytorch_earlystopping as es\n\n\"\"\"\nconv1d: in shape = (N, C_in, L_in) -> out shape = (N, C_out, L_out)\nconv2d: in shape = (N, C_in, H_in, W_in) -> out_shape = (N, C_out, H_out, W_out)\nlinear: in_shape = (N, L_in) -> out shape = (N, L_out)\nGru/Lstm: in_shape = L_in, out_shape = L_out\nbatchnorm1d: num_features = L_out\nbatchnorm2d: num_features = C_out\nall dropout\n\"\"\"\n\n\nclass Net(nn.Module):\n # assumes conv->fc, rec->fc, fc or conv+fc2->fc\n def __init__(\n self, config, input_shape, output_size, device=None, input_2_size=None\n ):\n super().__init__()\n\n # get number of layers per type\n n_conv_layers = 0\n n_rec_layers = 0\n n_fc_layers = 0\n n_fc2_layers = 0\n for layer in config:\n if \"Conv\" in layer[\"layer_type\"]:\n n_conv_layers += 1\n elif layer[\"layer_type\"] == \"Linear\":\n n_fc_layers += 1\n elif layer[\"layer_type\"] == \"Linear_2\":\n n_fc2_layers += 1\n else:\n n_rec_layers += 1\n\n # set network type and generate empty network\n if n_conv_layers > 0:\n self._net_type = \"CNN\"\n self._modules_conv, in_features = self._generate_conv_modules(\n config, input_shape\n )\n if n_fc2_layers > 0:\n self._modules_lin2, in_features_2 = self._generate_linear_modules(\n config, input_2_size, layer_name=\"Linear_2\"\n )\n in_features += in_features_2\n self._modules_lin, in_features = self._generate_linear_modules(\n config, in_features\n )\n\n elif n_rec_layers > 0:\n self._net_type = \"RNN\"\n self._rnn_type = config[0][\"layer_type\"]\n self._device = device\n (\n self._modules_rec,\n in_features,\n self._hidden_sizes,\n ) = self._generate_recurrent_modules(config, input_shape)\n self._modules_lin, in_features = self._generate_linear_modules(\n config, in_features,\n )\n\n else:\n self._net_type = \"MLP\"\n self._modules_lin, in_features = self._generate_linear_modules(\n config, np.prod(input_shape)\n )\n\n # use a linear output layer\n self._out = nn.Linear(in_features, output_size)\n\n def _generate_conv_modules(self, config, input_shape, modules=None):\n # empty module list\n if modules is None:\n modules = nn.ModuleList()\n\n in_channels = input_shape[0]\n input_sizes = input_shape[1:] # HxW\n # go over all type conv layers in config\n i = 0\n while i < len(config):\n # empty module, to be filled with 'layers' from the config\n layers_in_module = []\n # current layer settings\n layer_dict = config[i].copy()\n layer_type = layer_dict.pop(\"layer_type\")\n # stop as soon as a fully-connected layer is found\n if layer_type == \"Linear\" or layer_type == \"Linear_2\":\n break\n # set up layer and its parameters\n layer = getattr(nn, layer_type) # i.e. nn.Conv2d\n layer = layer(in_channels, **layer_dict)\n # add to module\n layers_in_module.append(layer)\n i += 1\n # set new 'in_channels' to current 'out_channels'\n in_channels = layer_dict[\"out_channels\"]\n # calculate new 'input_sizes' (height, width)\n input_sizes = _calc_conv_layer_output_shape(\n layer_type, layer_dict, input_sizes\n )\n\n # apply batch normalization if in config and before relu\n if i < len(config):\n if (\n \"BatchNorm\" in config[i][\"layer_type\"]\n and config[i].get(\"location\", None) == \"before\"\n ):\n bn_dict = config[i].copy()\n _ = bn_dict.pop(\"location\")\n bn_type = bn_dict.pop(\"layer_type\")\n bn = getattr(nn, bn_type)\n # supply new 'in_channels' and eps, along with layer parameters\n bn = bn(in_channels, eps=1e-8, **bn_dict)\n layers_in_module.append(bn)\n i += 1\n\n # apply pooling if in config\n if i < len(config):\n if \"MaxPool\" in config[i][\"layer_type\"]:\n pool_dict = config[i].copy()\n pool_type = pool_dict.pop(\"layer_type\")\n pool = getattr(nn, pool_type)\n # supply parameters\n pool = pool(**pool_dict)\n layers_in_module.append(pool)\n i += 1\n # calculate new 'input_sizes' (height, width)\n input_sizes = _calc_conv_layer_output_shape(\n pool_type, pool_dict, input_sizes\n )\n\n # add ReLU\n layers_in_module.append(nn.ReLU())\n\n # apply dropout if in config\n if i < len(config):\n if \"Dropout\" in config[i][\"layer_type\"]:\n dropout_dict = config[i].copy()\n _ = dropout_dict.pop(\"layer_type\")\n # supply parameters in dict\n dropout = nn.Dropout(**dropout_dict)\n layers_in_module.append(dropout)\n i += 1\n\n # apply batch normalization if in config and after relu (default)\n if i < len(config):\n if (\n \"BatchNorm\" in config[i][\"layer_type\"]\n and config[i].get(\"location\", None) != \"before\"\n ):\n bn_dict = config[i].copy()\n _ = bn_dict.pop(\"location\")\n bn_type = bn_dict.pop(\"layer_type\")\n bn = getattr(nn, bn_type)\n # supply new 'in_channels' and eps, along with layer parameters\n bn = bn(in_channels, eps=1e-8, **bn_dict)\n layers_in_module.append(bn)\n i += 1\n\n # add module to module list\n module = nn.Sequential(*layers_in_module)\n modules.append(module)\n\n # calculate number of output units (required for FC layers)\n output_units = in_channels * np.prod(input_sizes)\n\n return modules, output_units\n\n def _generate_recurrent_modules(self, config, input_shape, modules=None):\n # empty module list\n if modules is None:\n modules = nn.ModuleList()\n\n # hidden sizes are used in forward() to init. hidden states with 0s\n hidden_sizes = []\n\n input_size = input_shape[-1] # no. of input features (freq. bins)\n # go over all recurrent layers in config\n i = 0\n while i < len(config):\n # current layer settings\n layer_dict = config[i].copy()\n layer_type = layer_dict.pop(\"layer_type\")\n # stop as soon as a fully-connected layer is found\n if layer_type == \"Linear\":\n break\n # set up layer and its parameters\n layer = getattr(nn, layer_type) # i.e. nn.Conv2d\n layer = layer(input_size, **layer_dict, batch_first=True)\n # add to module list\n modules.append(layer)\n i += 1\n # set new 'input_size' to current 'hidden_size'\n input_size = layer_dict[\"hidden_size\"]\n hidden_sizes.append(input_size)\n\n return modules, input_size, hidden_sizes\n\n def _generate_linear_modules(\n self, config, in_features, modules=None, layer_name=\"Linear\"\n ):\n # empty module list\n if modules is None:\n modules = nn.ModuleList()\n\n # skip layers until the first fully-connected layer is found\n i = 0\n while config[i][\"layer_type\"] != layer_name:\n i += 1\n if i >= len(config):\n # in case no linear layers in config (not recommended)\n return modules, in_features\n\n # search remaining layers\n while i < len(config):\n # check for interference with second linear module\n if (config[i][\"layer_type\"] == \"Linear\" and layer_name == \"Linear_2\") or (\n config[i][\"layer_type\"] == \"Linear_2\" and layer_name == \"Linear\"\n ):\n break\n\n # empty module, to be filled with 'layers' from the config\n layers_in_module = []\n # current layer settings\n layer_dict = config[i].copy()\n layer_type = layer_dict.pop(\"layer_type\").split(\"_\")[0]\n # set up layer and its parameters\n layer = getattr(nn, layer_type) # i.e. nn.Conv2d\n layer = layer(in_features, **layer_dict)\n # add to module\n layers_in_module.append(layer)\n i += 1\n\n # set new 'in_features' to current 'out_features'\n in_features = layer_dict[\"out_features\"]\n\n # add ReLU\n layers_in_module.append(nn.ReLU())\n\n # apply dropout if in config\n if i < len(config):\n if \"Dropout\" in config[i][\"layer_type\"]:\n dropout_dict = config[i].copy()\n _ = dropout_dict.pop(\"layer_type\")\n # supply parameters in dict\n dropout = nn.Dropout(**dropout_dict)\n layers_in_module.append(dropout)\n i += 1\n\n # add module to module list\n module = nn.Sequential(*layers_in_module)\n modules.append(module)\n\n return modules, in_features\n\n def forward(self, x, x2=None): # add support for double input net!!!\n if self._net_type == \"CNN\":\n x = self._forward_convolutional(x)\n elif self._net_type == \"RNN\":\n x = self._forward_recurrent(x)\n else:\n pass\n # reshape output for fully-connected layer\n x = x.reshape(x.size(0), -1)\n if x2 is not None:\n for module in self._modules_lin2:\n x2 = module(x2)\n x = torch.cat((x, x2), dim=1)\n # forward pass: FC layers\n for module in self._modules_lin:\n x = module(x)\n # linear output layer\n x = self._out(x)\n\n return x\n\n def _forward_convolutional(self, x):\n for module in self._modules_conv:\n x = module(x)\n\n return x\n\n def _forward_recurrent(self, x):\n for i, module in enumerate(self._modules_rec):\n # initialize hidden state with zeros\n hidden_size = self._hidden_sizes[i]\n h0 = (\n torch.zeros(1, x.size(0), hidden_size).requires_grad_().to(self._device)\n )\n # initialize hidden cell state with zeros if lstm is used\n if self._rnn_type == \"LSTM\": # or check type in module??\n c0 = (\n torch.zeros(1, x.size(0), hidden_size)\n .requires_grad_()\n .to(self._device)\n )\n # detach h0, c0 to avoid BPTT through previous batches\n x, _ = module(x, (h0.detach(), c0.detach()))\n else:\n # detach h0 to avoid BPTT through previous batches\n x, _ = module(x, h0.detach())\n\n # extract output from last timestep\n x = x[:, -1, :]\n\n return x\n\n\ndef _calc_conv_layer_output_shape(layer_type, layer_dict, input_shape):\n\n assert layer_type in [\"Conv1d\", \"Conv2d\", \"MaxPool1d\", \"MaxPool2d\"]\n\n if \"1d\" in layer_type:\n in_shape = input_shape[0]\n # get layer params or default\n kernel = layer_dict[\"kernel_size\"]\n if layer_type == \"Conv1d\":\n stride = layer_dict.get(\"stride\", 1)\n else:\n stride = layer_dict.get(\"stride\", 2)\n padding = layer_dict.get(\"padding\", 0)\n dilation = layer_dict.get(\"dilation\", 1)\n # compute output length\n out_shape = int(\n (in_shape + 2 * padding - dilation * (kernel - 1) - 1) / stride + 1\n )\n else:\n in_height = input_shape[0]\n in_width = input_shape[1]\n # get layer params or default\n kernel = layer_dict[\"kernel_size\"]\n if layer_type == \"Conv2d\":\n stride = layer_dict.get(\"stride\", (1, 1))\n else:\n stride = layer_dict.get(\"stride\", (2, 2))\n padding = layer_dict.get(\"padding\", (0, 0))\n dilation = layer_dict.get(\"dilation\", (1, 1))\n # compute output shape\n out_height = int(\n (in_height + 2 * padding[0] - dilation[0] * (kernel[0] - 1) - 1) / stride[0]\n + 1\n )\n out_width = int(\n (in_width + 2 * padding[1] - dilation[1] * (kernel[1] - 1) - 1) / stride[1]\n + 1\n )\n out_shape = [out_height, out_width]\n\n return out_shape\n\n\n# network configuration\n\n\ndef set_net_configuration(layers, test_set):\n # fetch input shape and output size from test set\n input_shape = list(test_set.tensors[0].size()[1:])\n output_size = int(np.prod(test_set.tensors[-1].size()[1:])) # cast to int for json\n\n # set device\n if torch.cuda.is_available():\n device = \"cuda\"\n else:\n device = \"cpu\"\n\n # set network configuration\n net_config = {\n \"layers\": layers,\n \"input_shape\": input_shape,\n \"output_size\": output_size,\n \"device\": device,\n }\n if len(test_set.tensors) > 2:\n net_config[\"input_2_size\"] = np.prod(test_set.tensors[1].size()[1:])\n\n return net_config\n\n\ndef train_network(\n train_settings,\n train_set,\n val_set,\n net_config,\n loss_fn,\n verbose=True,\n super_verbose=False,\n):\n\n # reset the seed\n torch.manual_seed(42)\n\n # create network from config\n network = _create_network(net_config)\n\n # copy optimizer settings to avoid modifying train_settings\n dict_optimizer = train_settings[\"optimizer\"].copy()\n # select the optimizer in torch.optim from settings\n optimizer = getattr(torch.optim, dict_optimizer.pop(\"optimizer\"))\n # bind network, unpack optimizer settings\n optimizer = optimizer(network.parameters(), **dict_optimizer)\n\n if \"lr_scheduler\" in train_settings:\n # copy scheduler settings to avoid modifying train_settings\n dict_scheduler = train_settings[\"lr_scheduler\"].copy()\n # select the lr scheduler in torch.optim from settings\n lr_scheduler = getattr(\n torch.optim.lr_scheduler, dict_scheduler.pop(\"scheduler\")\n )\n # bind optimizer, unpack scheduler settings\n lr_scheduler = lr_scheduler(optimizer, **dict_scheduler)\n\n # create train dataloader\n train_loader = torch.utils.data.DataLoader(\n dataset=train_set,\n batch_size=train_settings[\"batch_size\"],\n shuffle=True,\n drop_last=False,\n )\n # create validation dataloader\n if len(val_set) > 2048:\n val_batch_size = 2048 # cap batch size to avoid memory issues\n else:\n val_batch_size = len(val_set)\n val_loader = torch.utils.data.DataLoader(\n dataset=val_set, batch_size=val_batch_size, drop_last=False\n )\n\n if \"es_patience\" in train_settings:\n # set up early stopping checkpoint\n fp_checkpoint = \"checkpoint-es.pt\"\n early_stopping = es.EarlyStopping(\n patience=train_settings[\"es_patience\"],\n delta=1e-7,\n verbose=super_verbose,\n output_fp=fp_checkpoint,\n )\n\n training_loss_history = []\n validation_loss_history = []\n # loop over epochs\n for epoch in range(train_settings[\"epochs\"]):\n train_losses = []\n # set in training mode\n network.train()\n for data in train_loader:\n # to device (gpu/cpu)\n x_train = data[0].to(net_config[\"device\"])\n if len(data) > 2:\n x2_train = data[1].to(net_config[\"device\"])\n y_train = data[-1].to(net_config[\"device\"])\n # clear gradient of optimizer\n optimizer.zero_grad()\n # forward pass\n if len(data) == 2:\n yhat = network(x_train)\n else:\n yhat = network(x_train, x2_train)\n # compute loss\n loss = loss_fn(yhat, y_train)\n # backward pass\n loss.backward()\n # record loss\n train_losses.append(loss.item())\n # update parameters\n optimizer.step()\n # record loss and update loss history\n training_loss = np.mean(train_losses)\n training_loss_history.append(training_loss)\n\n # validation loss\n with torch.no_grad():\n val_losses = []\n # set in eval mode\n network.eval()\n for data in val_loader:\n # to device (gpu/cpu)\n x_val = data[0].to(net_config[\"device\"])\n if len(data) > 2:\n x2_val = data[1].to(net_config[\"device\"])\n y_val = data[-1].to(net_config[\"device\"])\n # forward pass\n if len(data) == 2:\n yhat = network(x_val)\n else:\n yhat = network(x_val, x2_val)\n # compute loss\n val_loss = loss_fn(yhat, y_val)\n # record loss\n val_losses.append(val_loss.item())\n # record loss and update loss history\n validation_loss = np.mean(val_losses)\n validation_loss_history.append(validation_loss)\n\n print_verbose(\n super_verbose,\n \"epoch %d: training loss = %.6f, validation loss = %.6f\"\n % (epoch + 1, training_loss, validation_loss),\n )\n\n if \"es_patience\" in train_settings:\n # check early stopping criterion\n early_stopping(validation_loss, network)\n if early_stopping.early_stop:\n # get training loss at best epoch\n training_loss = training_loss_history[\n epoch - train_settings[\"es_patience\"]\n ]\n # get validation loss at best epoch\n validation_loss = early_stopping.val_loss_min\n print_verbose(\n super_verbose,\n \"Early stopping (using model at epoch %d with val. loss %.5f)\"\n % (epoch + 1 - train_settings[\"es_patience\"], validation_loss),\n )\n # end training\n break\n\n if \"lr_scheduler\" in train_settings:\n # update learning rate\n lr_scheduler.step(validation_loss)\n\n if \"es_patience\" in train_settings:\n # load network from checkpoint\n network.load_state_dict(torch.load(early_stopping.output_fp))\n # delete checkpoint !!!\n\n loss = (training_loss, validation_loss)\n loss_history = (training_loss_history, validation_loss_history)\n return network, loss, loss_history\n\n\ndef _create_network(net_config, verbose=True, super_verbose=False):\n # set up network\n network = Net(*net_config.values())\n network.to(net_config[\"device\"])\n\n print_verbose(verbose, \"Device: %s.\" % net_config[\"device\"])\n print_verbose(super_verbose, network)\n print_verbose(\n verbose,\n \"Number of trainable parameters in network: %d.\"\n % sum([p.numel() for p in network.parameters()]),\n )\n\n return network\n\n\ndef test_network(network, test_set, device, loss_fn):\n\n # create test dataloader\n if len(test_set) > 2048:\n test_batch_size = 2048 # cap batch size to avoid memory issues\n else:\n test_batch_size = len(test_set)\n test_loader = torch.utils.data.DataLoader(\n dataset=test_set, batch_size=test_batch_size, drop_last=False\n )\n\n # calc. loss\n with torch.no_grad():\n losses = []\n # set in eval mode\n network.eval()\n for data in test_loader:\n # to device (gpu/cpu)\n x = data[0].to(device)\n if len(data) > 2:\n x2 = data[1].to(device)\n y = data[-1].to(device)\n # forward pass\n if len(data) == 2:\n yhat = network(x)\n else:\n yhat = network(x, x2)\n # compute loss\n loss = loss_fn(yhat, y)\n # record loss\n losses.append(loss.item())\n # record loss and update loss history\n loss = np.mean(losses)\n\n return loss\n","sub_path":"aircraft_detector/utils/dynamic_net.py","file_name":"dynamic_net.py","file_ext":"py","file_size_in_byte":20886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"35676116","text":"import datetime, boto3, json\nimport argparse\nfrom boto3.dynamodb.conditions import Key\n\n# This script is used a tool to manage the ETL jobs, such as for backfilling past data or resubmit failed jobs.]\n# Usage to submit past dates: python3 manage-etl-jobs.py run-job --start-date --end-date \n# Usage to resubmit any failed jobs: python3 manage-etl-jobs.py resubmit-failed\n\ndef invoke_lambda(l_client, d):\n\tyear = str(d.year)\n\tmonth = \"{0:0=2d}\".format(d.month)\n\tday = \"{0:0=2d}\".format(d.day)\n\tprint(\"{}-{}-{}\".format(year, month, day))\n\tpayload = {\"year\": year, \"month\": month, \"day\": day}\n\tpayload = json.dumps(payload)\n\tpayload = payload.encode()\n\tresponse = l_client.invoke(FunctionName=\"ETL-Scheduler\", InvocationType=\"Event\", Payload=payload)\n\ndef run_job_func(args):\n\tprint(\"Running job\")\n\tend_date = datetime.datetime.strptime(args.end_date, \"%Y-%m-%d\")\n\tstart_date = datetime.datetime.strptime(args.start_date, \"%Y-%m-%d\")\n\tdelta = end_date - start_date\n\tif args.profile:\n\t\tboto3.setup_default_session(profile_name=args.profile)\n\n\tif args.region:\n\t\tl_client = boto3.client(\"lambda\", region_name=args.region)\n\telse:\n\t\tl_client = boto3.client(\"lambda\")\n\n\tprint(\"Invoking Lambda function:\")\n\tfor i in range(delta.days + 1):\n\t\td = start_date + datetime.timedelta(days=i)\n\t\tinvoke_lambda(l_client, d)\n\ndef resubmit_failed_func(args):\n\tif args.profile:\n\t\tboto3.setup_default_session(profile_name=args.profile)\n\n\tif args.region:\n\t\tl_client = boto3.client(\"lambda\", region_name=args.region)\n\telse:\n\t\tl_client = boto3.client(\"lambda\")\n\n\tif args.region:\n\t\tddb = boto3.resource(\"dynamodb\", region_name=args.region)\n\telse:\n\t\tddb = boto3.resource(\"dynamodb\")\n\n\ttable = ddb.Table('Covid-Project')\n\n\t# Get items from DDB which are stuck in RUNNING status.\n\t# It'll invoke Lambda function with such dates, then Lambda function will only submit those jobs which have their corresponding EMR Steps as FAILED.\n\tuncompleted_jobs = table.query(IndexName='status-date-index', KeyConditionExpression=Key('status').eq('RUNNING'))\n\tfor item in uncompleted_jobs['Items']:\n\t\td = datetime.datetime.strptime(item.get('date'), \"%Y-%m-%d\")\n\t\tinvoke_lambda(l_client, d)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--profile\", type=str, help=\"AWS profile name. If not specified, default will be used.\")\nparser.add_argument(\"--region\", type=str, help=\"AWS Region where Lambda function is located.\")\n\nsubparsers = parser.add_subparsers(title='subcommands',\n description='valid subcommands: run-job, resubmit-failed',\n help='additional help')\nrun_parser = subparsers.add_parser(\"run-job\", help=\"run-job --start-date --end-date \")\nrun_parser.add_argument(\"--start-date\", type=str, required=True, help=\"Start date for ETL. Eg. 2020-01-01\")\nrun_parser.add_argument(\"--end-date\", type=str, required=True, help=\"Start date for ETL. Eg. 2020-02-01\")\n\nresubmit_parser = subparsers.add_parser(\"resubmit-failed\")\nrun_parser.set_defaults(func=run_job_func)\nresubmit_parser.set_defaults(func=resubmit_failed_func)\n\nargs = parser.parse_args()\nargs.func(args)\n","sub_path":"manage-etl-jobs.py","file_name":"manage-etl-jobs.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"648825510","text":"## @ StitchLoader.py\r\n# This is a python stitching script for Slim Bootloader WHL/CFL build\r\n#\r\n# Copyright (c) 2019, Intel Corporation. All rights reserved.
    \r\n# SPDX-License-Identifier: BSD-2-Clause-Patent\r\n#\r\n##\r\nimport os\r\nimport sys\r\nimport argparse\r\nfrom ctypes import *\r\nfrom functools import reduce\r\n\r\nsys.dont_write_bytecode = True\r\nsys.path.append (os.path.join(os.getenv('SBL_SOURCE', ''), \"BootloaderCorePkg\" , \"Tools\"))\r\ntry:\r\n from IfwiUtility import *\r\nexcept ImportError:\r\n err_msg = \"Cannot find IfwiUtility module!\\n\"\r\n err_msg += \"Please make sure 'SBL_SOURCE' environment variable is set to open source SBL root folder.\"\r\n raise ImportError(err_msg)\r\n\r\nextra_usage_txt = \\\r\n\"\"\"This script creates a new Whiskeylake/Coffeelake Slim Bootloader IFWI image basing\r\non an existing IFWI base image. Please note, this stitching method will work\r\nonly if Boot Guard in the base image is not enabled, and the silicon is not\r\nfused with Boot Guard enabled.\r\nPlease follow steps below:\r\n 1. Download an existing Whiskeylake/Coffeelake UEFI IFWI image associated\r\n with the target platform.\r\n Alternatively, the original IFWI image from the onboard SPI flash can be\r\n read out as the base image too.\r\n 2. Build Slim Bootloader source tree.\r\n The generated Slim Bootloader binary is located at:\r\n $(WORKSPACE)/Outputs/cfl/SlimBootloader.bin\r\n 3. Stitch to create a new IFWI image.\r\n EX:\r\n python StitchLoader.py -i WHL_UEFI_IFWI.bin -s SlimBootloader.bin -o WHL_SBL_IFWI.bin\r\n 4. Optionally, to view the flash layout for an given IFWI image,\r\n specify '-i' option only.\r\n EX:\r\n python StitchLoader.py -i IFWI.bin\r\n\"\"\"\r\ndef add_platform_data (bios_data, platform_data = None):\r\n if platform_data:\r\n # Parse BIOS image\r\n ifwi_parser = IFWI_PARSER ()\r\n bios = ifwi_parser.parse_ifwi_binary (bios_data)\r\n if not bios:\r\n return None\r\n\r\n for part in range(2):\r\n path = 'IFWI/BIOS/TS%d/SG1A' % part\r\n stage1A = ifwi_parser.locate_component (bios, path)\r\n if stage1A:\r\n plat_data_offset = stage1A.offset + stage1A.length - 12\r\n c_uint32.from_buffer (bios_data, plat_data_offset).value = platform_data\r\n print(\"Platform data was patched for %s\" % path)\r\n\r\n return bios_data\r\n\r\n\r\ndef create_ifwi_image (ifwi_in, ifwi_out, sbl_in, platform_data):\r\n ifwi_data = bytearray (get_file_data (ifwi_in))\r\n ifwi_parser = IFWI_PARSER ()\r\n ifwi = ifwi_parser.parse_ifwi_binary (ifwi_data)\r\n if not ifwi:\r\n print (\"Invalid IFWI input image!\")\r\n return -1\r\n\r\n # update bios region\r\n bios = ifwi_parser.locate_component (ifwi, 'IFWI/BIOS')\r\n if not bios:\r\n print (\"Cound not find BIOS region!\")\r\n return -2\r\n\r\n bios_data = bytearray (get_file_data (sbl_in))\r\n bios_data = add_platform_data (bios_data, platform_data)\r\n if not bios_data:\r\n print (\"Failed to parse BIOS image!\")\r\n return -3\r\n\r\n padding = bios.length - len(bios_data)\r\n if padding < 0:\r\n print (\"BIOS image is too big to fit into BIOS region!\")\r\n return -4\r\n\r\n bios_data = b'\\xff' * padding + bios_data\r\n ret = ifwi_parser.replace_component (ifwi_data, bios_data, 'IFWI/BIOS')\r\n if ret != 0:\r\n print (\"Failed to replace BIOS region!\")\r\n return -5\r\n\r\n # create new ifwi\r\n print(\"Creating IFWI image ...\")\r\n if ifwi_out == '':\r\n ifwi_out = ifwi_in\r\n gen_file_from_object (ifwi_out, ifwi_data)\r\n\r\n print ('done!')\r\n\r\n\r\ndef print_ifwi_layout (ifwi_file):\r\n ifwi_data = bytearray (get_file_data (ifwi_file))\r\n ifwi_parser = IFWI_PARSER ()\r\n ifwi = ifwi_parser.parse_ifwi_binary (ifwi_data)\r\n if ifwi:\r\n ifwi_parser.print_tree (ifwi)\r\n\r\n\r\nif __name__ == '__main__':\r\n hexstr = lambda x: int(x, 16)\r\n\r\n ap = argparse.ArgumentParser()\r\n ap.add_argument('-i',\r\n '--input-ifwi-file',\r\n dest='ifwi_in',\r\n type=str,\r\n required=True,\r\n help='Specify input template IFWI image file path')\r\n\r\n ap.add_argument('-o',\r\n '--output-ifwi-file',\r\n dest='ifwi_out',\r\n type=str,\r\n default='',\r\n help='Specify generated output IFWI image file path')\r\n\r\n ap.add_argument('-s',\r\n '--sbl-input',\r\n dest='sbl_in',\r\n type=str,\r\n default='',\r\n help='Specify input sbl binary file path')\r\n\r\n ap.add_argument('-p',\r\n '--platform-data',\r\n dest='plat_data',\r\n type=hexstr,\r\n default=None,\r\n help='Specify a platform specific data (HEX, DWORD) for customization')\r\n\r\n\r\n if len(sys.argv) == 1:\r\n print ('%s' % extra_usage_txt)\r\n\r\n args = ap.parse_args()\r\n\r\n if args.ifwi_out == '' and args.sbl_in == '':\r\n print_ifwi_layout (args.ifwi_in)\r\n ret = 0\r\n else:\r\n ret = create_ifwi_image (args.ifwi_in, args.ifwi_out, args.sbl_in, args.plat_data)\r\n\r\n\r\n sys.exit(ret)\r\n\r\n","sub_path":"Platform/CoffeelakeBoardPkg/Script/StitchLoader.py","file_name":"StitchLoader.py","file_ext":"py","file_size_in_byte":5275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"123279875","text":"from django.core.exceptions import ImproperlyConfigured\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom duct_tape.lib.template_queue import TemplateQueue\nfrom anyjson import deserialize\n\nclass JSBehaviorQueueMixin(object):\n def get_context_data(self, **kwargs):\n context = super(JSBehaviorQueueMixin,self).get_context_data(**kwargs)\n\n # always create a behavior queue at the top level context\n context['duct_tape__behavior_queue'] = TemplateQueue()\n return context\n\nclass ModelUrlPathMixin(object):\n # this is needed because the base generic view class introspects in on itself\n # to insure that it is only receiving params that already exist in it\n url_list_path='list'\n url_detail_path='detail'\n url_update_path='update'\n url_delete_path='delete'\n url_create_path='create'\n url_api_autocomplete_path='api:foo:autocomplete_list'\n\n def get_context_data(self, **kwargs):\n context = super(ModelUrlPathMixin,self).get_context_data(**kwargs)\n\n context['url_list_path'] = self.url_list_path\n context['url_detail_path'] = self.url_detail_path\n context['url_update_path'] = self.url_update_path\n context['url_delete_path'] = self.url_delete_path\n context['url_create_path'] = self.url_create_path\n context['url_api_autocomplete_path'] = self.url_api_autocomplete_path\n\n return context\n\n\nclass LoginRequiredMixin(object):\n @method_decorator(login_required)\n def dispatch(self,request, *args, **kwargs ):\n return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)\n\nclass NamedUrlOnSuccessMixin(object):\n '''\n This mixin trys reverse on the success_url\n and falls back to the original method if there is no success\n '''\n def get_success_url(self):\n '''\n first look for a param called next\n '''\n if 'next' in self.request.REQUEST:\n try:\n url = reverse(self.request.REQUEST['next'])\n return url\n except:\n return self.request.REQUEST['next']\n elif self.success_url:\n try:\n reverse(self.success_url)\n return url\n except:\n return super(NamedUrlOnSuccessMixin,self).get_success_url()\n else:\n return super(NamedUrlOnSuccessMixin,self).get_success_url()\n\nclass MultipleObjectFilterMixin(object):\n '''\n Used to provide generic list views a way of filtering\n\n Provides a mechanism for passing a filter_string through the request\n '''\n\n def get_queryset(self,*args,**kwargs):\n super(MultipleObjectFilterMixin,self).get_queryset(*args,**kwargs)\n qs = self.queryset\n if 'filter' in self.request.GET:\n data = deserialize(self.request.GET['filter'])\n qs=qs.filter(**data)\n return qs.all()\n","sub_path":"duct_tape/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"160144916","text":"import math\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport numpy as np\r\nfrom scipy.interpolate import interp1d\r\n\r\ndef axisEqual3D(ax):\r\n extents = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz'])\r\n sz = extents[:,1] - extents[:,0]\r\n centers = np.mean(extents, axis=1)\r\n maxsize = max(abs(sz))\r\n r = maxsize/2\r\n for ctr, dim in zip(centers, 'xyz'):\r\n getattr(ax, 'set_{}lim'.format(dim))(ctr - r, ctr + r)\r\n\r\na1 = 292\r\nb1 = 300\r\nc1 = 272.8377777777778\r\nd1 = 241.925\r\n\r\ndef profilvalka(x_valka, a1,b1,c1,d1):\r\n r1 = a1/2\r\n r2 = b1/2\r\n r3 = c1/2\r\n r4 = d1/2\r\n\r\n #ang1 = 1.77*math.pi/180\r\n\r\n if r1 > r2:\r\n ang1 = math.atan((r1 - r2) / 130)\r\n else:\r\n ang1 = math.atan((r2 - r1) / 130)\r\n\r\n if r2 > r3:\r\n ang2 = math.atan((r2 - r3) / 90)\r\n else:\r\n ang2 = math.atan((r2 - r3) / 90)\r\n if r3>r4:\r\n ang3 = math.atan((r3-r4)/50)\r\n else:\r\n ang3 = math.atan((r4 - r3) / 50)\r\n\r\n if 0 <= x_valka <= 130:\r\n if r1>r2:\r\n return float(r1 - x_valka*math.tan(ang1))\r\n else:\r\n return float(r1 + x_valka * math.tan(ang1))\r\n\r\n if 130 < x_valka <= 220:\r\n if r2>r3:\r\n return float(r2 - (x_valka-130)*math.tan(ang2))\r\n else:\r\n return float(r2 + (x_valka - 130) * math.tan(ang2))\r\n\r\n if 220 < x_valka <= 270:\r\n if r3>r4:\r\n return float(r3 - (x_valka-220)*math.tan(ang3))\r\n else:\r\n return float(r3 + (x_valka - 220) * math.tan(ang3))\r\n\r\n\r\nalpha = 10*math.pi/180\r\nbetta = 18*math.pi/180\r\n\r\n\r\n#a = np.array([0,130,220,270])\r\n\r\n#x , u = np.mgrid[0:271:3j, 0:2*np.pi:100j]\r\nfor b in range(100):\r\n space = np.linspace(25,30,100)\r\n a11 = 292\r\n b11 = 300\r\n c1 = 272.8377777777778\r\n d1 = 261.9910660660661\r\n a11 = a11+space[b]\r\n print(space[b])\r\n profilvalka1 = np.vectorize(profilvalka)\r\n a = np.array([0, 130, 220, 270])\r\n #a = np.linspace(0, 270, 100)\r\n b = np.linspace(2.7, 3.7, 1000)\r\n\r\n u, x = np.meshgrid(b, a)\r\n print(x[0][0])\r\n\r\n y = profilvalka1(x,a11,b11,c1,d1)*np.sin(u)\r\n z = profilvalka1(x,a11,b11,c1,d1)*np.cos(u)\r\n x-=130\r\n z = z + profilvalka(130,a11,b11,c1,d1)\r\n\r\n for i in range(len(x)):\r\n for k in range(len(x[i])):\r\n a1 = x[i][k]*math.cos(alpha)+z[i][k]*math.sin(alpha)\r\n b1 = x[i][k]*(-1)*math.sin(alpha)+ z[i][k]*math.cos(alpha)\r\n x[i][k] = a1\r\n z[i][k] = b1\r\n\r\n\r\n for i in range(len(x)):\r\n for k in range(len(x[i])):\r\n a1 = x[i][k]*math.cos(betta)-y[i][k]*math.sin(betta)\r\n b1 = x[i][k]*math.sin(betta)+y[i][k]*math.cos(betta)\r\n x[i][k] = a1\r\n y[i][k] = b1\r\n\r\n\r\n z+=52.5\r\n\r\n short_radius = np.sqrt(z**2+y**2)\r\n\r\n\r\n short_lenght = np.argmin(short_radius, axis = 1)\r\n\r\n xs = []\r\n ys = []\r\n zs = []\r\n\r\n for i in range(len(short_lenght)):\r\n xs.append(x[i][short_lenght[i]])\r\n ys.append(y[i][short_lenght[i]])\r\n zs.append(z[i][short_lenght[i]])\r\n\r\n xs = np.array(xs)\r\n ys = np.array(ys)\r\n zs = np.array(zs)\r\n\r\n\r\n rads = []\r\n for i in range(len(xs)):\r\n rads.append(np.sqrt(ys[i] ** 2 + zs[i] ** 2))\r\n print(rads[0])\r\n print(a11)\r\n if float(rads[0])>float(69.5) and float(rads[0]= k:\n if numbers[nums[0] - 1] == 0:\n numbers[nums[0] - 1] = []\n if numbers[nums[1] - 1] == 0:\n numbers[nums[1] - 1] = []\n numbers[nums[0] - 1].append(nums[1])\n numbers[nums[1] - 1].append(nums[0])\n\nif k == 1:\n for1()\nelse:\n removeLine()\nprint(-1)\n","sub_path":"A-OI/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"443550793","text":"def add_contents(new_cont):\n \"\"\"\n args is tweets contents that users want to tweet.\n add args to tw_contents (list)\n \"\"\"\n return tweets_contents.append(new_cont)\n\ntweets_contents = ['apiを叩く','テスト2apiを叩く','apiをターミナルかたから叩くテスト3','api']\nrand_status=random.choice(tweets_contents)\n#api.update_status(rand_status) #TweepError code:187 Status is a duplicate\t投稿した文章は、このアカウントですでにツイートされています\n\ndef follow_back() :\n \"\"\"\n フォロバする\n \"\"\"\n following = set(api.friends_ids(MY_USERID))\n followered = set(api.followers_ids(MY_USERID))\n not_foll_bk = followered - following\n # following = set(api.friends_ids(MY_USERID))\n # followered = set(api.followers_ids(MY_USERID))\n # not_foll_bk:フォロワーのうち自分がフォロー仕返していない人\n print(\"set of not_foll_bk:\" ,not_foll_bk)\n\n for item in not_foll_bk:\n api.create_friendship(item)\n\n return not_foll_bk\n \n\ndef Conditional_follow():\n \"\"\"\n 最後に実行したときから関数を実行した期間のうちに獲得した新規フォロワー\n のうちフォロワー100人未満の新規フォロワーに対してはフォロバしない\n \"\"\"\n following = set(api.friends_ids(MY_USERID))\n followered = set(api.followers_ids(MY_USERID))\n not_foll_bk = followered - following\n print(\"処理前:\",not_foll_bk)\n for item in not_foll_bk :\n follower = api.get_user(item)\n #Twitter error response: status code = 414\n # api.get_user returns a ton of data for the user that isn't\n # necessarily their user ID or anything relevant. \n try:\n if follower.followers_count >=100:\n sleep(1)\n api.create_friendship(item)\n except tweepy.error.TweepError as te:\n print(te)\n else:\n print(\"処理完了:反映に時間要す\",not_foll_bk)\n \n\n\n","sub_path":"tw_bot/tw_bump/tw_follow.py","file_name":"tw_follow.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"290108687","text":"import os,sys\r\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\r\nfrom ctypes import *\r\nfrom ctypes_wrap import *\r\nfrom cFpVector import *\r\n\r\nimport steenrod\r\n\r\nclass cAdemBasisElement:\r\n def __init__(self, algebra, elt):\r\n self.c_elt = elt\r\n self.algebra = algebra\r\n self.generateReprString(algebra.generic)\r\n self.degree = self.c_elt.contents.degree\r\n assert self.degree < algebra.max_degree\r\n self.idx = CSteenrod.AdemAlgebra_basisElement_toIndex(self.algebra.c_algebra, self.c_elt.contents)\r\n self.py_rep = None\r\n\r\n def generateReprString(self, generic):\r\n P_or_Sq = \"P\" if generic else \"Sq\"\r\n ps = []\r\n bocksteins = self.c_elt.contents.bocksteins\r\n for i in range(self.c_elt.contents.P_length):\r\n if self.algebra.generic and (bocksteins & 1) !=0:\r\n ps += [\"b\"]\r\n bocksteins >>= 1\r\n ps += [P_or_Sq + str(self.c_elt.contents.Ps[i])]\r\n if self.algebra.generic and (bocksteins & 1) != 0:\r\n ps += [\"b\"]\r\n repr_str = \" \".join(ps)\r\n if(len(repr_str) == 0):\r\n repr_str = \"0\"\r\n self.repr_str = repr_str\r\n \r\n def __repr__(self):\r\n return self.repr_str\r\n\r\n def mult(self, other):\r\n if(self.algebra != other.algebra):\r\n raise Exception(\"Algebras don't match.\")\r\n if(self.degree + other.degree > self.algebra.max_degree):\r\n raise Exception(\"Degree exceeds maximum.\")\r\n result = cAdemElement(algebra = self.algebra, degree = self.degree + other.degree)\r\n CSteenrod.AdemAlgebra_multiply(\r\n self.algebra.c_alg_ptr, \r\n result.cVect.vector, 1, self.degree, self.idx, other.degree, other.idx, 0\r\n )\r\n return result\r\n\r\n def toPyTuple(self):\r\n if self.py_rep:\r\n return self.py_rep\r\n length = self.c_elt.contents.P_length\r\n if self.algebra.generic:\r\n bocksteins = [0] * (length + 1)\r\n bitstring = self.c_elt.contents.bocksteins\r\n i = 0\r\n while bitstring != 0:\r\n if bitstring & 1 != 0:\r\n bocksteins[i] = 1\r\n i += 1\r\n bitstring >>= 1\r\n Ps = [0] * length\r\n for i in range(length):\r\n Ps[i] = self.c_elt.contents.Ps[i]\r\n if self.algebra.generic:\r\n result = [0] * (2* length + 1)\r\n result[0::2] = bocksteins\r\n result[1::2] = Ps\r\n else:\r\n result = Ps\r\n result = tuple(result)\r\n self.py_rep = result\r\n return result\r\n\r\n def toPy(self):\r\n return self.algebra.py_algebra.get_basis_element(self.toPyTuple())\r\n\r\nclass cAdemElement:\r\n def __init__(self, *, algebra, degree, vector = None):\r\n self.algebra = algebra\r\n self.degree = degree\r\n self.dimension = algebra.getDimension(degree)\r\n if(vector):\r\n if vector.dimension != self.dimension:\r\n raise Exception(\"Dimensions don't match!\")\r\n self.cVect = vector\r\n else:\r\n self.cVect = cVector(self.algebra.p, dim = self.dimension)\r\n self.repr_string = None\r\n self.freed = False\r\n\r\n def generateReprString(self):\r\n basis_strs = []\r\n basis = self.algebra.getBasis(self.degree)\r\n for idx, v in enumerate(self.cVect.unpack()):\r\n if v==0:\r\n continue\r\n cur_str = \"\" \r\n if v!=1:\r\n cur_str += \"%s*\" % v\r\n cur_str += str(basis[idx])\r\n basis_strs += [cur_str]\r\n self.repr_string = \" + \".join(basis_strs)\r\n if len(self.repr_string) == 0:\r\n self.repr_string = \"0\" \r\n\r\n\r\n def __repr__(self):\r\n if not self.repr_string:\r\n self.generateReprString()\r\n return self.repr_string\r\n\r\n def add(self, elt, c=1):\r\n self.repr_string = None\r\n if elt.degree != self.degree:\r\n raise Error(\"Degrees don't match.\")\r\n c = c % self.algebra.p\r\n self.cVect.add(elt.cVect, c)\r\n \r\n def __setitem__(self, idx, value):\r\n self.repr_string = None\r\n self.cVect[idx] = value\r\n\r\n def __getitem__(self, idx, value):\r\n return self.cVect[idx] \r\n\r\n def __iter__(self):\r\n return self.cVect.__iter__()\r\n\r\n def toPy(self):\r\n result = {}\r\n basis = self.algebra.getBasis(self.degree)\r\n for i, entry in enumerate(self.cVect.unpack()):\r\n if entry == 0:\r\n continue\r\n result[basis[i].toPyTuple()] = entry\r\n return self.algebra.py_algebra.get_element(result) \r\n\r\n def free(self):\r\n self.freed = True\r\n self.cVect.free()\r\n\r\nclass cAdemAlgebra:\r\n def __init__(self, p, generic=None, max_degree = None):\r\n if generic is None:\r\n generic = p != 2\r\n self.p = p\r\n self.generic = generic\r\n self.c_algebra = CSteenrod.AdemAlgebra_construct(p, generic, False) \r\n self.py_algebra = steenrod.AdemAlgebra.getInstance(p, generic)\r\n self.c_alg_ptr = cast(self.c_algebra, POINTER(c_Algebra))\r\n self.max_degree = 0\r\n self.basis_type = cAdemBasisElement\r\n self.bases = {}\r\n self.Sq = self.py_algebra.Sq\r\n self.P = self.py_algebra.P\r\n self.b = self.py_algebra.b\r\n if max_degree:\r\n self.generateBasis(max_degree)\r\n\r\n def generateBasis(self, max_degree):\r\n if(max_degree > self.max_degree):\r\n CSteenrod.AdemAlgebra_generateBasis(self.c_alg_ptr, max_degree)\r\n self.max_degree = max_degree\r\n\r\n def getDimension(self, degree):\r\n return CSteenrod.AdemAlgebra_getDimension(self.c_alg_ptr, degree, 0)\r\n\r\n def getBasis(self, degree):\r\n if degree in self.bases:\r\n return self.bases[degree]\r\n if degree > self.max_degree:\r\n raise Exception(\"C basis only known through degree %s < %s.\" % (self.max_degree, degree))\r\n c_basisElementList = CSteenrod.AdemAlgebra_getBasis(self.c_alg_ptr, degree, 0)\r\n result = [None] * int(c_basisElementList.length)\r\n for i in range(c_basisElementList.length):\r\n b = c_basisElementList.list[i]\r\n result[i] = cAdemBasisElement(self, b)\r\n self.bases[degree] = result\r\n return result\r\n \r\n def basis_elt_to_elt(self, b):\r\n idx = CSteenrod.AdemAlgebra_basisElement_toIndex(self.c_algebra, b.c_elt)\r\n v = cVector(self.p, dim=self.getDimension(b.degree))\r\n v[idx] = 1\r\n return cAdemElement(algebra=self,degree=b.degree, vector=v)\r\n\r\n def multiply(self, m1, m2):\r\n m1_deg = m1.degree()\r\n m2_deg = m2.degree()\r\n out_degree = m1_deg + m2_deg\r\n if out_degree > self.max_degree:\r\n raise Exception(\"C basis only known through degree %s < %s.\" % (self.max_degree, out_degree))\r\n result = cAdemElement(algebra = self, degree=out_degree)\r\n b1 = next(iter(m1))\r\n b2 = next(iter(m2))\r\n m1_idx = self.idxFromPy(b1)\r\n m2_idx = self.idxFromPy(b2)\r\n CSteenrod.AdemAlgebra_multiply(self.c_alg_ptr, result.cVect.vector, 1, m1_deg, m1_idx, m2_deg, m2_idx,0)\r\n py_res = result.toPy()\r\n # result.free()\r\n return py_res\r\n\r\n def basisEltFromIdx(self, degree, idx):\r\n return self.getBasis(degree)[idx]\r\n\r\n def idxFromPy(self, b):\r\n bitstring = 0\r\n p_part = b\r\n if self.generic:\r\n for idx, x in enumerate(b[0::2]):\r\n bitstring |= x << idx\r\n p_part = b[1::2]\r\n p_array = (c_uint * len(p_part))(*p_part)\r\n basis_elt = c_AdemBasisElement()\r\n basis_elt.degree = self.py_algebra.basis_degree(b)\r\n basis_elt.bocksteins = bitstring\r\n basis_elt.P_length = len(p_part)\r\n basis_elt.Ps = p_array\r\n basis_elt_ptr = POINTER(c_AdemBasisElement)(basis_elt)\r\n return CSteenrod.AdemAlgebra_basisElement_toIndex(self.c_algebra, basis_elt_ptr)\r\n \r\n def basisEltFromPy(self, b):\r\n degree = self.py_algebra.basis_q_degree(b) + self.py_algebra.basis_p_degree(b)\r\n idx = self.idxFromPy(b)\r\n return self.getBasis(degree)[idx]\r\n\r\ncAdemAlgebra.cAlgebras = {} \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n pass\r\n A = cAdemAlgebra(p=2, max_degree=100)\r\n Sq = A.py_algebra.Sq\r\n P = A.py_algebra.P\r\n #A3 = makeCAdemAlgebra(p=3, dim=200)\r\n","sub_path":"python/CWrappers/cAdemAlgebra.py","file_name":"cAdemAlgebra.py","file_ext":"py","file_size_in_byte":8517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"385971781","text":"\"\"\"rename tables\n\nRevision ID: d502cfd729d6\nRevises: 4699e18f3fc1\nCreate Date: 2017-03-21 00:43:35.656647\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = 'd502cfd729d6'\ndown_revision = '4699e18f3fc1'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.rename_table('periodic_task', 'tasks')\n op.rename_table('interval', 'intervals')\n op.rename_table('crontab', 'crontabs')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.rename_table('tasks', 'periodic_task')\n op.rename_table('intervals', 'interval')\n op.rename_table('crontabs', 'crontab')\n # ### end Alembic commands ###\n","sub_path":"server/models/migrations/versions/rename_tables.py","file_name":"rename_tables.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"216752546","text":"from django.shortcuts import render\nfrom products import models\nfrom django.core.paginator import Paginator\n# Create your views here.\n\ndef home(request):\n home = models.Item.objects.all()\n paginator = Paginator(home , 10)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n return render(request , 'home/index.html',{\n 'home':page_obj\n })","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"334026998","text":"# --------------------------------------------------------------\n# Homework 7 - Histograms and Function Fitting\n# --------------------------------------------------------------\n\nimport sys\nimport math\nimport numpy as np\nimport numpy.random as ran\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n\nprint(\"\\nProblem 2\\tLinear fit\\n\")\n\n# Create figure and subplot.\nplt.figure(figsize=(8,6), dpi=80)\nplt.subplot(111)\n\n# Title and axis labels\nplt.title('Linear Fit')\nplt.xlabel(r'$x$')\nplt.ylabel(r'$y$')\n\n# Read in linear fit data.\nx, y = np.loadtxt(\"HW07-linearFit.dat\", np.float64, usecols={0, 1}, unpack=True)\n\n# a0 + a1x + a2x^2 + ... + anx^n\n\n# Plot the data.\ndotSize = 20\nplt.scatter(x, y, dotSize, color=\"black\", zorder=2, label=\"Data\")\n\ndef fit_poly(x, *coeffs):\n y = np.polyval(coeffs, x)\n return y\n\nhigher_order = 7\nfit_results = []\nfor n in range(2, higher_order):\n # The initial guess of the parameters to be found by curve_fit.\n p0 = np.ones(n)\n\n (popt, pcov) = curve_fit(fit_poly, x, y, p0=p0, sigma=None, bounds=(-np.inf,np.inf))\n \n fit_results.append(popt)\n\nxmin = -6.1\nxmax = 5.22\nplt.xlim(xmin, xmax)\n\nfor p in fit_results:\n y_fitted = fit_poly(x, *p)\n plt.plot(x, y_fitted, label='n = %d' % len(p))\n\nplt.legend(loc=\"upper right\", frameon=False, fontsize=10)\n\nprint(\"Minimum value of n = {} obtains a reasonable fit.\".format(higher_order - 1))\n\n# Export figure and show.\nplt.savefig(\"hw7-problem2.pdf\")\nplt.tight_layout()\nplt.show()\n\n","sub_path":"PHYS 162/Homework/07histograms/hw7p2.py","file_name":"hw7p2.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"123168161","text":"from collections import namedtuple\nfrom geoip import geolite2\nfrom IPy import IP\nimport re\nimport os\nimport glob\n\nEventPlayerJoin = namedtuple('EventPlayerJoin', ['player', 'ip'])\nEventNextMap = namedtuple('EventNextMap', ['map'])\n\n\ndef get_events(r, keys, soldat_dir):\n skipped_files = 0\n root = os.path.join(soldat_dir, 'logs')\n\n # Make sure we go by filename sorted in ascending order, as we can't sort\n # our global kill log after items are inserted.\n files = sorted(map(os.path.basename, glob.glob(os.path.join(root, 'consolelog*.txt'))))\n\n skipped_files = 0\n\n for filename in files:\n key = keys.log_file(filename=filename)\n path = os.path.join(root, filename)\n size = os.path.getsize(path)\n prev = r.get(key)\n if prev is None:\n pos = 0\n else:\n pos = int(prev)\n if size > prev:\n print('reading {filename} from offset {pos}'.format(filename=filename, pos=pos))\n with open(path, 'r') as h:\n h.seek(pos)\n for event in parse_events(h):\n yield event\n r.set(key, size)\n else:\n skipped_files += 1\n\n print('skipped {count} unchanged console logs'.format(count=skipped_files))\n\n\ndef parse_events(contents):\n header = '\\d\\d\\-\\d\\d\\-\\d\\d \\d\\d:\\d\\d:\\d\\d '\n event_regexen = [\n (EventPlayerJoin, re.compile(''.join([header, '(?P.+) joining game \\((?P[^:]+):\\d+\\) HWID:\\S+']))),\n (EventNextMap, re.compile(''.join([header, 'Next map: (?P[^$]+)']))),\n ]\n\n for line in contents:\n for event, regex in event_regexen:\n m = regex.match(line)\n if not m:\n continue\n yield event(**m.groupdict())\n\n\ndef update_events(r, keys, soldat_dir):\n for event in get_events(r, keys, soldat_dir):\n if isinstance(event, EventPlayerJoin):\n update_country(r, keys, event.ip, event.player)\n elif isinstance(event, EventNextMap):\n update_map(r, keys, event.map)\n\n\ndef update_country(r, keys, ip, player):\n if not r.exists(keys.player_hash(player)):\n return\n if IP(ip).iptype() != 'PUBLIC':\n return\n match = geolite2.lookup(ip)\n if not match:\n return\n country_code = match.country\n if r.hset(keys.player_hash(player), 'lastcountry', country_code):\n r.zincrby(keys.top_countries, country_code)\n\n\ndef update_map(r, keys, map):\n r.zincrby(keys.top_maps, map)\n","sub_path":"piestats/update/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"563528314","text":"from django.db import models\n\n\nclass ApprovalAbstract(models.Model):\n STATUS_CHOICES = (\n ('pending', 'Pending'),\n ('approved', 'Approved'),\n ('disapproved', 'Disapproved'),\n ('frozen', 'Frozen'),\n ('unfrozen', 'UnFrozen')\n )\n ROLE_CHOICES = (\n ('staff', 'Staff'),\n ('theme_leader', 'Theme Leader'),\n ('programme_coordinator', 'Programme Coordinator'),\n ('regional_programme_manager', 'Regional Programme Manager'),\n ('supervisor', 'Supervisor'),\n ('next_supervisor', 'Next Supervisor'),\n )\n status = models.CharField(max_length=32, choices=STATUS_CHOICES, default='pending')\n role = models.CharField(max_length=32, choices=ROLE_CHOICES, default='staff')\n remarks = models.TextField(blank=True)\n is_archieved = models.BooleanField(default=0)\n created_on = models.DateTimeField(auto_now_add=True)\n updated_on = models.DateTimeField(auto_now=True)\n \n class Meta:\n abstract = True\n","sub_path":"src/mbocore/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"621080533","text":"### Daniel Kronovet (dbk2123)\n### EECS E6892 HW 03\n### November 20, 2015\n\nimport os\nimport math\nimport random\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nfrom models import VIRegression\n\n\nrandom.seed(' ')\npath = os.path.dirname(os.path.realpath(__file__))\n\nX1 = pd.read_csv(path + '/data_csv/X_set1.csv', header=None)\nX2 = pd.read_csv(path + '/data_csv/X_set2.csv', header=None)\nX3 = pd.read_csv(path + '/data_csv/X_set3.csv', header=None)\ny1 = pd.read_csv(path + '/data_csv/y_set1.csv', header=None, squeeze=True)\ny2 = pd.read_csv(path + '/data_csv/y_set2.csv', header=None, squeeze=True)\ny3 = pd.read_csv(path + '/data_csv/y_set3.csv', header=None, squeeze=True)\nz1 = pd.read_csv(path + '/data_csv/z_set1.csv', header=None, squeeze=True)\nz2 = pd.read_csv(path + '/data_csv/z_set2.csv', header=None, squeeze=True)\nz3 = pd.read_csv(path + '/data_csv/z_set3.csv', header=None, squeeze=True)\n\n'''\nfrom HW03.hw3 import *; vir = init(X1, y1)\n'''\n\ndef transform(z):\n return z.apply(np.sinc) * 10\n\ndef init(X, y):\n small = 10 ** -16\n vir = VIRegression(X, y, a=small, b=small, e=1, f=1)\n vir.train()\n return vir\n\ndef A(vir):\n plt.plot(vir.loglikelihood)\n\ndef B(vir):\n a = vir.a\n alphas = [bk/a for bk in vir.b]\n idx = range(len(alphas))\n markerline, stemlines, baseline = plt.stem(idx, alphas, '-.')\n plt.show()\n\ndef C(vir):\n return vir.f / vir.e\n\ndef D(vir):\n yhat = vir.X.dot(vir.mu)\n plt.plot(z1, yhat, 'bo-', z1, transform(z1), 'g-')\n\nif __name__ == '__main__':\n A()\n\n","sub_path":"HW03/hw3.py","file_name":"hw3.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"423764938","text":"#!/usr/bin/env python\n\"\"\"\nSAWICKIPEDIA.EXE\nmain.py\n@author: Kyle Sawicki\n----------------------------------------\nMain startup module for the bot\n\"\"\"\n#Imports\nimport discord \nfrom discord.ext import commands\nimport asyncio\nimport datetime\nimport io\nimport sys\nimport os\nimport gc\nimport logging\nimport random\nimport json\nfrom json.decoder import JSONDecodeError\nimport io\nimport sys\n\n#Constants\nDEBUG = True\n\n#Logging\n# root_logger = logging.getLogger()\n# root_logger.setLevel(logging.INFO)\n# \n# log_formatter = logging.Formatter(\"%(asctime)s -%(levelname)s- %(message)s\", datefmt=\"%d-%b-%y %H:%M:%S\")\n# \n# console_handler = logging.StreamHandler(sys.stdout)\n# console_handler.setFormatter(log_formatter)\n# root_logger.addHandler(console_handler)\n\n#Prefix\ndef get_prefix(bot, message):\n \"\"\"A callable Prefix for our bot. This could be edited to allow per server prefixes.\"\"\"\n try:\n with open('serverdata' + os.sep + str(message.guild.id) + \".json\") as guild_file:\n guild_data = json.load(guild_file)\n \n prefix = guild_data[\"server_data\"][\"prefix\"]\n except:\n prefix = \"?\"\n if (not message.guild): #Check to see if we are outside of a guild. e.g DM's etc.\n return \"?\" #Only allow ? to be used in DMs\n return commands.when_mentioned_or(prefix)(bot, message)\n\n#Bot Instantiation\ndescription = \"A bot that can do things.\"\nstartup_extensions = [\"modules.developer\",\n \"modules.economy\",\n \"modules.minigames\",\n \"modules.misc\",\n \"modules.moderation\",\n \"modules.transfer\",\n \"modules.settings\"\n ]\nbot = commands.Bot(command_prefix=get_prefix, description=description)\n\n\nasync def background_task(): #Runs every 1 second, constantly.\n await bot.wait_until_ready()\n #Main loop\n while (not bot.is_closed()):\n #Adds data to files for each server:\n for guild in bot.guilds:\n try:\n with open(\"serverdata\" + os.sep + str(guild.id) + \".json\") as guild_file:\n guild_data = json.load(guild_file)\n for user in guild.members:\n if str(user.id) not in guild_data[\"user_data\"].keys():\n guild_data[\"user_data\"][user.id] = {}\n with open(\"serverdata\" + os.sep + str(guild.id) + \".json\", \"w\") as guild_file:\n json.dump(guild_data, guild_file, indent=4)\n except JSONDecodeError:\n pass\n except FileNotFoundError:\n pass\n #Logging\n global log_buffer\n global err_buffer\n if bot.user.id == 421015092830666754:\n to_channel=bot.get_channel(496780822553034752)\n else:\n to_channel=bot.get_channel(496794388689584146)\n to_send = log_buffer.getvalue()\n to_send2 = err_buffer.getvalue()\n log_buffer.close()\n err_buffer.close()\n sys.stdout = log_buffer = io.StringIO()\n sys.stderr = err_buffer = io.StringIO()\n if to_send != \"\":\n await to_channel.send(to_send)\n if to_send2 != \"\":\n await to_channel.send(to_send2)\n \n \n #Moderation:\n for guild in bot.guilds:\n for member in guild.members:\n for role in member.roles:\n if role.name == \"Muted\":\n with open(\"serverdata\" + os.sep + str(guild.id) + \".json\") as guild_file:\n guild_data = json.load(guild_file)\n \n try:\n mute_data = guild_data['user_data'][str(member.id)]['mute_data']\n except:\n mute_data = {\"time\":\"forever\"}\n \n if mute_data['time'] == 'forever':\n pass\n elif int(mute_data['time']) <= 0:\n mute_data = {}\n for role in guild.roles:\n if role.name == \"Muted\":\n mute_role = role\n await member.remove_roles(mute_role)\n await member.edit(speak = True)\n try:\n mute_old_channel = guild_data['user_data'][str(member.id)]['mute_old_channel']\n for channel in guild.text_channels:\n mute_old_perm_obj = channel.overwrites_for(member)\n mute_old_perm_obj.send_messages = mute_old_channel[str(channel.id)][0]\n mute_old_perm_obj.add_reactions = mute_old_channel[str(channel.id)][1]\n await channel.set_permissions(member, overwrite=mute_old_perm_obj)\n if channel.overwrites_for(member).is_empty():\n await channel.set_permissions(member, overwrite=None)\n \n for channel in ctx.guild.voice_channels:\n mute_old_perm_obj = channel.overwrites_for(member)\n mute_old_perm_obj.speak = mute_old_channel[str(channel.id)]\n await channel.set_permissions(member, overwrite=mute_old_perm_obj)\n if channel.overwrites_for(member).is_empty():\n await channel.set_permissions(member, overwrite=None)\n except:\n pass\n else:\n mute_data['time'] = str(int(mute_data['time']) - 1)\n \n guild_data['user_data'][str(member.id)]['mute_data'] = mute_data\n with open(\"serverdata\" + os.sep + str(guild.id) + \".json\", \"w\") as guild_file:\n json.dump(guild_data, guild_file, indent=4)\n \n #Other:\n gc.collect()\n await asyncio.sleep(1)\n \nasync def slow_background_task(): #Runs every 30 seconds, constantly.\n await bot.wait_until_ready()\n games_file = open(\"botdata\" + os.sep + \"games.txt\", \"r\")\n GAMES = games_file.read().split(\"\\n\")\n while (not bot.is_closed()):\n \n await asyncio.sleep(30)\n #Change playing status\n await bot.change_presence(activity=discord.Game(name=str(random.choice(GAMES))))\n \n \n#Events:\n@bot.event \nasync def on_ready():\n #Create files for each server\n for guild in bot.guilds:\n try:\n my_file = open(\"serverdata\" + os.sep + str(guild.id) + \".json\", \"x\")\n json.dump({\"server_data\" : {}, \"user_data\": {}}, my_file, indent=4)\n except:\n pass #File exists, so no need to do anything\n \n #Main bot startup\n ready_str = (\"\\n**______----------------------------STARTING----------------------------______**\\n\"\n \"Logged in as\\n\" +bot.user.name+ \"\\n\"\n +str(bot.user.id)+ \"\\n\"\n \"**Date:** \" +str(datetime.datetime.now())+ \"\\n\"\n \"------\")\n print(ready_str)\n await bot.change_presence(activity=discord.Game(name=\"with Startup Caches\"))\n\n@bot.event\nasync def on_guild_join(guild):\n #Creates file for new guild\n try:\n my_file = open(\"serverdata\" + os.sep + str(guild.id) + \".json\", \"x\")\n json.dump({\"server_data\" : {}, \"user_data\": {}}, my_file, indent=4)\n except:\n pass #File exists, so no need to do anything\n\n@bot.event\nasync def on_member_join(member):\n #Automatically adds roles/nicknames for Custom Join\n with open('serverdata' + os.sep + str(member.guild.id) + \".json\") as guild_file:\n guild_data = json.load(guild_file)\n \n try:\n custom_join = guild_data['user_data'][str(member.id)]['custom_join']\n except:\n custom_join = []\n \n if custom_join != []:\n role_list = []\n for role in custom_join[1:]:\n try:\n role_list.append(member.guild.get_role(role))\n except Exception as e:\n pass\n await member.edit(nick=custom_join[0], roles = role_list)\n \n \n@bot.event\nasync def on_message(message):\n await bot.process_commands(message)\n if message.author == bot.user: #Make sure bot doesn't respond to itself\n return\n #Send all DMs to owner\n if isinstance(message.channel, discord.abc.PrivateChannel)and (message.author.id != 357953549738573835):\n to_channel = bot.get_user(357953549738573835).dm_channel\n if to_channel == None:\n to_channel = await bot.get_user(357953549738573835).create_dm()\n await to_channel.send(\"**Message from {}[*{}*]:** {}\".format(str(message.author), str(message.author.id), str(message.content)))\n if message.attachments != []:\n to_say = \"**Attachments**: \"\n for thing in message.attachments:\n to_say = to_say + thing.url + \"\\n\"\n await to_channel.send(to_say)\n \n \n \n \n #Continues Blackjack game:\n if message.content.lower() == \"hit\" or message.content.lower() == \"h\" or message.content.lower() == \"stand\" or message.content.lower() == \"s\" or message.content.lower() == \"double\" or message.content.lower() == \"d\":\n with open('serverdata' + os.sep + str(message.guild.id) + \".json\") as guild_file:\n guild_data = json.load(guild_file)\n try:\n if guild_data['user_data'][str(message.author.id)]['playing_bj']: \n bj_data = guild_data['user_data'][str(message.author.id)]['bj_data']\n if message.content.lower() == \"double\" or message.content.lower() == \"d\":\n bj_data['done'] = True\n guild_data['user_data'][str(message.author.id)]['money'] -= bj_data['bet']\n bj_data['bet'] *= 2\n if message.content.lower() == \"stand\" or message.content.lower() == \"s\":\n #stand\n bj_data['done'] = True\n else:\n #hit/double\n bj_data['player_cards'].append(bj_data['deck'].pop())\n \n #Totals up the cards \n ace_found = False\n bj_data['player_total'] = 0\n result = -1 #-1 is not done, 0 is lose, 1 is tie, 2 is win\n for card in bj_data['player_cards']:\n try:\n bj_data['player_total'] += int(card)\n except:\n if card == 'A':\n if ace_found:\n bj_data['player_total'] += 1\n else:\n ace_found = True\n bj_data['player_total'] += 11\n bj_data['soft_ace'] = True\n else:\n bj_data['player_total'] += 10\n \n if bj_data['player_total'] > 21 and bj_data['soft_ace']:\n bj_data['player_total'] -= 10\n bj_data['soft_ace'] = False\n elif bj_data['player_total'] > 21:\n bj_data['done'] = True\n result = 0\n elif bj_data['player_total'] == 21:\n bj_data['done'] = True\n \n \n soft_deal = False\n if bj_data['done']:\n guild_data['user_data'][str(message.author.id)]['playing_bj'] = False\n #Add dealer cards, and deal more to them\n ace_found = False\n bj_data['dealer_total'] = 0\n x = 0\n while x < len(bj_data['dealer_cards']):\n card = bj_data['dealer_cards'][x]\n try:\n bj_data['dealer_total'] += int(card)\n except:\n if card == 'A':\n if ace_found:\n bj_data['dealer_total'] += 1\n else:\n ace_found = True\n bj_data['dealer_total'] += 11\n soft_deal = True\n else:\n bj_data['dealer_total'] += 10\n \n if bj_data['dealer_total'] > 21 and soft_deal:\n bj_data['dealer_total'] -= 10\n soft_deal = False\n elif bj_data['dealer_total'] > 21:\n result = 2\n print(x)\n print(bj_data['dealer_cards'])\n print(bj_data['dealer_total'])\n x += 1\n if (x > 1):\n if bj_data['dealer_total'] < 17 and result == -1:\n card = bj_data['deck'].pop()\n bj_data['dealer_cards'].append(card)\n else:\n break\n \n \n \n #Get results\n if result == -1:\n if bj_data['dealer_total'] > bj_data['player_total']:\n result = 0\n elif bj_data['dealer_total'] < bj_data['player_total']:\n result = 2\n else:\n result = 1\n else:\n bj_data['dealer_total'] = bj_data['dealer_cards'][0]\n \n \n \n #Formats result\n is_done = False\n if not bj_data['done']:\n bj_embed = discord.Embed(title=\"Blackjack\",description='Use `?bj hit` to draw another card, and `?bj stand` to end your turn.' \n + 'Use `?bj double` to double down (draw one card more, and double your bet). This game is for ${:,}.'.format(bj_data['bet']), color=255)\n else:\n bj_data['done'] = False\n is_done = True\n if result == 0:\n bj_embed = discord.Embed(title=\"Blackjack\", description='Player Loses $' + '{:,}'.format(int(bj_data['bet'])),color=16711680)\n elif result == 1:\n bj_embed = discord.Embed(title=\"Blackjack\", description='Push, money back', color=16744448)\n guild_data['user_data'][str(message.author.id)]['money'] += bj_data['bet']\n else:\n bj_embed = discord.Embed(title=\"Blackjack\", description='Player Wins ${:,}'.format(int(bj_data['bet'])), color=65280)\n guild_data['user_data'][str(message.author.id)]['money'] += int(bj_data['bet']) * 2\n \n \n \n \n #Saves data:\n guild_data['user_data'][str(message.author.id)]['bj_data'] = bj_data\n with open('serverdata' + os.sep + str(message.guild.id) + \".json\", \"w\") as guild_file:\n json.dump(guild_data, guild_file, indent=4)\n \n #Displays data\n player_card_str = ''\n dealer_card_str = ''\n for card in bj_data['player_cards']:\n player_card_str = player_card_str + '|{}| '.format(str(card))\n dealer_card_string = ''\n if is_done:\n for card in bj_data['dealer_cards']:\n dealer_card_str = dealer_card_str + '|{}| '.format(str(card))\n else:\n dealer_card_str = '|{}| |?|'.format(bj_data['dealer_cards'][0])\n \n if soft_deal:\n dealer_total_str = \"Soft \" + str(bj_data['dealer_total'])\n elif int(bj_data['dealer_total']) > 21:\n dealer_total_str = \"Bust \" + str(bj_data['dealer_total'])\n else:\n dealer_total_str = str(bj_data['dealer_total'])\n \n if bj_data['soft_ace']:\n player_total_str = \"Soft \" + str(bj_data['player_total'])\n elif int(bj_data['player_total']) > 21:\n player_total_str = \"Bust \" + str(bj_data['player_total'])\n else:\n player_total_str = str(bj_data['player_total'])\n \n bj_embed.set_author(name=str(message.author), icon_url=message.author.avatar_url)\n bj_embed.add_field(name=\"Player's Hand ({})\".format(player_total_str), value=player_card_str, inline=True)\n bj_embed.add_field(name=\"Dealer's Hand ({})\".format(dealer_total_str), value=dealer_card_str, inline=True)\n await message.channel.send(embed=bj_embed)\n except Exception as e:\n trace_back = sys.exc_info()[2]\n line = trace_back.tb_lineno\n await message.channel.send(\"```css\\n[{} | Line: {}]\\n```\".format(e, line))\n\n\n#Main \nif __name__ == \"__main__\":\n for extension in startup_extensions:\n try:\n bot.load_extension(extension)\n except Exception as e:\n exc = \"{}: {}\".format(type(e).__name__, e)\n print(\"Failed to load extension {}\\n{}\".format(extension, exc))\n sys.stdout = log_buffer = io.StringIO()\n sys.stderr = err_buffer = io.StringIO()\n bot.loop.create_task(background_task())\n bot.loop.create_task(slow_background_task())\n bot.run(open(\"botdata\" + os.sep + \"secret.txt\").readline())","sub_path":"discord_bots/sawickipedia.exe/bot-1.5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"126254740","text":"import pandas as pd\nimport numpy as np\ndf = pd.read_csv('/Users/nn31/Dropbox/40-githubRrepos/mmci-practical-datascience/lecture07_170624/dataset_diabetes/holdback/diabetic_data.csv',\n na_values='?',\n dtype={'encounter_id':object,'patient_nbr':object,'race':object,'gender':object,\n 'age':object,\n 'weight':object,\n 'admission_type_id':object,\n 'discharge_disposition_id':object,\n 'admission_source_id':object,\n 'time_in_hospital':object,\n 'payer_code':object,\n 'medical_specialty':object,\n 'num_lab_procedures':np.int,\n 'num_procedures':np.int,\n 'num_medications':np.int,\n 'number_outpatient':np.int,\n 'number_emergency':np.int,\n 'number_inpatient':np.int,\n 'diag_1':object,\n 'diag_2':object,\n 'diag_3':object,\n 'number_diagnoses':np.int,\n 'max_glu_serum':object,\n 'A1Cresult':object,\n 'metformin':object,\n 'repaglinide':object,\n 'nateglinide':object,\n 'chlorpropamide':object,\n 'glimepiride':object,\n 'acetohexamide':object,\n 'glipizide':object,\n 'glyburide':object,\n 'tolbutamide':object,\n 'pioglitazone':object,\n 'rosiglitazone':object,\n 'acarbose':object,\n 'miglitol':object,\n 'troglitazone':object,\n 'tolazamide':object,\n 'examide':object,\n 'citoglipton':object,\n 'insulin':object,\n 'glyburide-metformin':object,\n 'glipizide-metformin':object,\n 'glimepiride-pioglitazone':object,\n 'metformin-rosiglitazone':object,\n 'metformin-pioglitazone':object,\n 'change':object,\n 'diabetesMed':object,\n 'readmitted':object})\ndf['admitted'] = df['readmitted'].apply(lambda x: 0 if x=='NO' else 1)\n\nnp.random.seed(42)\nmsk = np.random.rand(len(df)) < 0.7\n\ndf_train = df[msk]\nprint(df_train.shape)\ndf_test = df[~msk]\nprint(df_test.shape)\n\ndf_train.to_csv('/Users/nn31/Dropbox/40-githubRrepos/mmci-practical-datascience/lecture07_170624/dataset_diabetes/diabetic-deliver.csv',\n index=False)\ndf_test.to_csv('/Users/nn31/Dropbox/40-githubRrepos/mmci-practical-datascience/lecture07_170624/dataset_diabetes/holdback/diabetic-holdback.csv',\n index=False)","sub_path":"lecture09_Saturday180623/dataset_diab/read_split_out.py","file_name":"read_split_out.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"390567704","text":"# from library import download_gambar, get_url_list\nimport time\nimport datetime\nfrom multiprocessing import Process, Pool\n\nimport socket\n\nTARGET_IP = \"192.168.122.255\" #Bcast = Broadcast Address\nTARGET_PORT = 5005\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nsock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEPORT, 1)\nsock.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST, 1)\n\n\ndef kirim_semua():\n texec = dict()\n list_file = ['data.jpg','asteroid.png']\n status_task = dict()\n task_pool = Pool(processes=20) #2 task yang dapat dikerjakan secara simultan, dapat diset sesuai jumlah core\n catat_awal = datetime.datetime.now()\n for k in range(len(list_file)):\n print(f\"mendownload {list_file[k]}\")\n #bagian ini merupakan bagian yang mengistruksikan eksekusi fungsi download gambar secara multiprocess\n texec[k] = task_pool.apply_async(func=kirimfile, args=(list_file[k],))\n\n #setelah menyelesaikan tugasnya, dikembalikan ke main process dengan mengambil hasilnya dengan get\n for k in range(len(list_file)):\n status_task[k]=texec[k].get(timeout=10)\n\n catat_akhir = datetime.datetime.now()\n selesai = catat_akhir - catat_awal\n print(f\"Waktu TOTAL yang dibutuhkan {selesai} detik {catat_awal} s/d {catat_akhir}\")\n print(\"status TASK\")\n print(status_task)\n\ndef kirimfile(list_file=0):\n if(list_file==0):\n print(\"Tidak ada file\")\n exit(1)\n file = open(list_file, 'rb')\n hasil = file.read(1024)\n terkirim = 0\n for x in hasil:\n k_bytes = bytes([x])\n sock.sendto(k_bytes, (TARGET_IP, TARGET_PORT))\n terkirim = terkirim + 1\n\n#fungsi download_gambar akan dijalankan secara multi process\n\nif __name__=='__main__':\n kirim_semua()","sub_path":"progjar3/JAWABAN TUGAS/multi_process_async.py","file_name":"multi_process_async.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"53684153","text":"#!/usr/bin/python\nimport requests\nimport csv\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"filename\", help=\"specify the csv file name\")\nargs = parser.parse_args()\n\ndef url_scan( url, string ):\n #from csv file, requests urls and checks whether strings are present.\n r = requests.get(url, timeout=2)\n c = r.text\n hc = string\n if hc in c:\n print (\"SUCCESS:\\t\\\"{}\\\" was found at {}\".format(string,url))\n else:\n print (\"FAILURE:\\t\\\"{}\\\" was NOT found at {}\".format(string,url))\n\nwith open(args.filename) as csvfile:\n #opens csv file and iterates url and strings with url_scan function.\n reader = csv.DictReader(csvfile)\n for row in reader:\n url_scan(row['hostname'],row['string'])","sub_path":"health_checker_cmdline.py","file_name":"health_checker_cmdline.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"558984107","text":"#USING split() method\nstring = \"thank.you.very.much.rohit.roshan\"\n\ndef reverse1(string):\n\tk =string.split(\".\")\n\trev =k[::-1]\n\ttemp=\"\"\n\tfor ele in rev:\n\t\ttemp = temp+ele\n\t\ttemp=temp+\".\"\n\tprint(temp[:len(temp)-1])\n\n\n# USING STACK\n\nfrom collections import deque\ndef reverse2(s):\n l = h = 0\n stack = deque()\n for i, k in enumerate(s):\n if k == '.':\n stack.append(s[l:h + 1])\n l = h = i + 1\n else:\n h = i\n\n stack.append(s[l:])\n tmp = \"\"\n while stack:\n tmp += stack.pop() + \".\"\n \n return(tmp[:-1]) \n\nprint(reverse2(string))\nreverse1(string)\n\n\n#INPUT\n\n# string = \"thank.you.very.much.rohit.roshan\"\n\n#OUTPUT\n\n# roshan.rohit.much.very.you.thank\n","sub_path":"revstringbutnotwords.py","file_name":"revstringbutnotwords.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"443113212","text":"# -*- coding: UTF-8 -*-\r\nimport datetime\r\nimport os\r\n\r\nfrom BaseLib.HandleFile import file_utils\r\nfrom BaseLib.LoggerConfig import logger\r\nfrom BaseLib.web.SeleniumDriver import driver\r\n\r\n'''\r\n 整个页面截图\r\n'''\r\ndef slm_screen(driver,img_name=None,file_path=\"logs/image\"):\r\n if not img_name:\r\n img_name = datetime.datetime.now().strftime('%H%M%S')\r\n dir_patn = file_utils.location_file(\"{}/{}\".format(file_path, datetime.datetime.now().strftime(\"%Y-%m-%d\")))\r\n if not os.path.exists(dir_patn):\r\n file_utils.mkdir_path(dir_patn)\r\n path = file_utils.location_file(\"{}/{}.png\".format(dir_patn, img_name))\r\n logger.info(path)\r\n driver.save_screenshot(path)\r\n logger.info(\"保存截图:{}\".format(path))\r\n return path\r\n\r\n\r\nif __name__ == '__main__':\r\n driver.browser(driver.Chrome,local=True)\r\n driver.handle_windows(driver.Max)\r\n slm_screen(driver.get_web_driver())","sub_path":"BaseLib/HandleImage.py","file_name":"HandleImage.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"199328025","text":"import ujson as json\nimport uuid\nfrom pymemcache.client.base import Client\nfrom pymemcache.exceptions import MemcacheUnexpectedCloseError\n\nfrom .config import settings\nfrom .singleton import Singleton\n\n\nclass MemcacheSession(object, metaclass=Singleton):\n \"\"\"\n This class creates a dict like Session object that uses memcached to store the session\n data for Authomatic social login/registration.\n \"\"\"\n __session_client__ = None\n __session_key__ = None\n __original_data__ = {}\n __session_data__ = {}\n\n def set_session_key(self, request):\n self.__session_key__ = None\n self.__original_data__ = self.__session_data__ = {}\n\n # We support both cookies and Authorization header\n # The Authorization header is useful for native apps or API consumers who may not deal with cookies\n try:\n # Check if there is a current cookie with session key\n if request.cookies[settings.SESSION_COOKIE_NAME]:\n self.__session_key__ = request.cookies[settings.SESSION_COOKIE_NAME]\n except KeyError:\n pass\n\n if self.__session_key__ is None:\n # If the cookie does not exist in request, check if we have an Authorization header\n auth_header = request.headers.get(\"authorization\", None)\n if auth_header:\n _, self.__session_key__ = auth_header.split(\" \")\n\n if self.__session_key__ is None:\n # If we did not get a session key at all, then we generate a new one\n self.__session_key__ = uuid.uuid4().hex\n self.load()\n\n def get_session_key(self):\n return self.__session_key__\n\n def session_store(self):\n if not self.__session_client__:\n self.__session_client__ = Client((settings.MEMCACHED_HOST, 11211))\n return self.__session_client__\n\n def load(self):\n try:\n data = self.session_store().get(\"sess/%s\" % self.__session_key__)\n except MemcacheUnexpectedCloseError:\n data = None\n if data is None:\n self.__session_data__ = {}\n self.__original_data__ = {}\n else:\n self.__session_data__ = json.loads(data)\n self.__original_data__ = json.loads(data)\n\n def save(self):\n self.session_store().set(\"sess/%s\" % self.__session_key__, json.dumps(self.__session_data__))\n\n def get(self, key, default=None):\n try:\n return self.__session_data__[key]\n except KeyError:\n return default\n\n @property\n def is_dirty(self):\n return True if self.__original_data__ != self.__session_data__ else False\n\n def __setitem__(self, key, value):\n self.__session_data__[key] = value\n\n def __getitem__(self, key):\n return self.__session_data__[key]\n\n def __delitem__(self, key):\n del self.__session_data__[key]\n return True\n","sub_path":"backstack/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"393271112","text":"# It is possible to show that the square root of two can be expressed as an infinite\n# continued fraction.\n\n# sqrt(2) = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...\n\n# By expanding this for the first four iterations, we get:\n\n# 1 + 1/2 = 3/2 = 1.5\n# 1 + 1/(2 + 1/2) = 7/5 = 1.4\n# 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...\n# 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...\n\n# The next three expansions are 99/70, 239/169, and 577/408, but the eighth \n# expansion, 1393/985, is the first example where the number of digits in the numerator \n# exceeds the number of digits in the denominator.\n\n# In the first one-thousand expansions, how many fractions contain a numerator \n# with more digits than denominator?\n\nfrom black_box import int2list\nimport sys\n\ndef recSqEntry(iterations):\n [num, den] = recSq(iterations)\n finalNum = den + num\n finalDen = den\n return [finalNum, finalDen]\n\ndef recSq(iterations):\n iterations-= 1\n if(iterations <= 0):\n return [1, 2]\n else:\n [newNum, newDen] = recSq(iterations)\n thisDen = 2*newDen + newNum\n thisNum = newDen\n return [thisNum, thisDen]\n\nsys.setrecursionlimit(10000) \n\nn = 0\nd = 0\ncount = 0\nfor i in range(1, 1001):\n [n, d] = recSqEntry(i)\n nList = int2list(n)\n dList = int2list(d)\n if(len(nList) > len(dList)):\n count += 1\n # print(str(i) + \" \" + str(n) + \"/\" + str(d) + \" \" + str(count))\n\n\nprint(count)\n\n","sub_path":"Python/prob57.py","file_name":"prob57.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"161621845","text":"#!/usr/bin/python3\n#scaffold_7\t106\t+\t0\t13\tCG\t0\nimport pickle,sys\n\nfile_in = sys.argv[1]\ndicW2C = {}\nwin = 10000\ndef write_array2file(dic,Outfile_name):\n Outfile = open(Outfile_name,'wb')\n pickle.dump(dic, Outfile)\n Outfile.close()\n\ndef open_array(filename):\n pkl_file = open(filename, 'rb')\n mydict2 = pickle.load(pkl_file)\n pkl_file.close()\n return(mydict2)\n\nfor line in open(file_in):\n\tcell = line.strip().split('\\t')\n\tstrC = cell[0]\n\tstrL = cell[1]\n\tstrD = cell[2]\n\tstrM = cell[3]\n\tstrU = cell[4]\n\tstrQ = cell[-1]\n\tif 1:\n\t\ttry:\n\t\t\tdicW2C[(strC,int(int(strL)/win))].append([strL,strM,strU,strD])\n\t\texcept KeyError:\n\t\t\tdicW2C[(strC,int(int(strL)/win))] = [[strL,strM,strU,strD]]\n\nwrite_array2file(dicW2C,file_in+'.q.dict')\n\n","sub_path":"py/kyunggi/4_indexing.py","file_name":"4_indexing.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"583970881","text":"import pygame\r\nimport gameModule\r\nimport sys\r\nfrom pygame.locals import *\r\nimport random\r\n\r\ndef main():\r\n\t#color list for blocks\r\n\tcolorList = [['Z', Color(53, 206, 69)], ['X', Color(96, 240, 233)], ['Y', Color(29, 1, 166)], ['S', Color(231, 13, 13)], ['V', Color(247, 240, 43)], ['W', Color(0, 0, 0)], ['T', Color(204, 111, 111)]]\r\n\t#initialize\r\n\trow = 13\r\n\tcolumn = 6\r\n\tpygame.init()\r\n\tscreen = pygame.display.set_mode((40 * column, 40 * row))\r\n\r\n\t#set caption\r\n\tpygame.display.set_caption('Pygame testing')\r\n\t#set mouse visibility\r\n\tpygame.mouse.set_visible(0)\r\n\t#set background\r\n\tbackground = pygame.Surface(screen.get_size())\r\n\tbackground = background.convert()\r\n\tbackground.fill((250, 250, 250))\r\n\r\n\t#send everything to the screen\r\n\tscreen.blit(background, (0, 0))\r\n\tpygame.display.flip()\r\n\tTICKER = pygame.USEREVENT+1\r\n\tpygame.time.set_timer(TICKER, 1000)\r\n\t#game object\r\n\tgame = gameModule.Game()\r\n\twhile 1:\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tgame.remove_faller()\r\n\t\t\tif event.type == QUIT:\r\n\t\t\t\treturn\r\n\t\t\tif event.type == KEYDOWN and event.key == K_LEFT:\r\n\t\t\t\tgame.move_left()\r\n\t\t\tif event.type == KEYDOWN and event.key == K_SPACE:\r\n\t\t\t\tgame.rotate_faller()\r\n\t\t\tif event.type == KEYDOWN and event.key == K_RIGHT:\r\n\t\t\t\tgame.move_right()\r\n\t\t\tif event.type == TICKER:\r\n\t\t\t\tif game.faller.size == 0:\r\n\t\t\t\t\tfaller_data = generate_new_faller(column, colorList)\r\n\t\t\t\t\tgame.new_faller(faller_data[1], faller_data[0], faller_data[2], faller_data[3])\r\n\t\t\t\telse:\r\n\t\t\t\t\tgame.faller_down()\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tfor i in range(row):\r\n\t\t\t\tfor j in range(column):\r\n\t\t\t\t\tif game.game_board[i][j] != \" \":\r\n\t\t\t\t\t\tif game.game_board[i][j][0] == \"[\" or game.game_board[i][j][0] == \"|\":\r\n\t\t\t\t\t\t\tblock_data = game.game_board[i][j][1]\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tblock_data = game.game_board[i][j]\r\n\t\t\t\t\t\tfor k in range(len(colorList)):\r\n\t\t\t\t\t\t\tif (colorList[k][0] == block_data):\r\n\t\t\t\t\t\t\t\tcolor = colorList[k][1]\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\tpygame.draw.rect(screen, color, (j * 40, i*40, 40, 40))\r\n\t\t\t\t\t\tpygame.draw.rect(screen, Color(0, 0, 0), (j * 40, i*40, 40, 40), 1)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tpygame.draw.rect(screen, Color(255, 255, 255), (j * 40, i*40, 40, 40))\r\n\t\t\t\t\t\tpygame.draw.rect(screen, Color(0, 0, 0), (j * 40, i*40, 40, 40), 1)\r\n\t\tpygame.display.update()\r\n\r\ndef generate_new_faller(column, colorList):\r\n\trow = 0\r\n\tcolumn = random.randint(0, column-1)\r\n\tsize = 3\r\n\tblock = []\r\n\tfor i in range(size):\r\n\t\tblock.append(colorList[random.randint(0, len(colorList)-1)][0])\r\n\treturn [row, column, size, block]\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"pygameModule.py","file_name":"pygameModule.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"386909127","text":"import requests\nfrom bs4 import BeautifulSoup\nimport operator\n\n\n'''\ndef skroutz_spider(max_pages):\n page = 1\n while page <= max_pages:\n url = 'https://www.skroutz.gr/c/25/laptop.html?page=' + str(page)\n source_code = requests.get(url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text, 'html.parser')\n for link in soup.findAll('a', {'class': 'js-sku-link'}):\n title = 'Title: ' + link.get('title')\n href = 'Link: ' + 'https://www.skroutz.gr' + link.get('href')\n print(title)\n print(href + '\\n\\n')\n page += 1\n\n\nskroutz_spider(1)\n'''\n\n\ndef start(url):\n word_list = []\n source_code = requests.get(url).text\n soup = BeautifulSoup(source_code, 'html.parser')\n for link in soup.findAll('a', {'class': 'js-sku-link'}):\n title = link.get('title')\n words = title.lower().split()\n for word in words:\n word_list.append(word)\n clean_up_list(word_list)\n\n\ndef clean_up_list(word_list):\n clean_word_list = []\n for word in word_list:\n symbols = '!@#$%^&*()_+-=[]{};:,.<>/?\\|\\'\"'\n for i in range(len(symbols)):\n word = word.replace(symbols[i], '')\n if 1 < len(word) < 12:\n clean_word_list.append(word)\n print(word + ' added to the clean list.\\n')\n create_dictionary(clean_word_list)\n\n\ndef create_dictionary(clean_word_list):\n word_count = {}\n for word in clean_word_list:\n if word in word_count:\n word_count[word] += 1\n else:\n word_count[word] = 1\n for key, value in sorted(word_count.items(), key=operator.itemgetter(1)):\n print(key, value)\n\n\nskroutz_url = 'https://www.skroutz.gr/c/25/laptop.html?page=1'\nstart(skroutz_url)\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"641061584","text":"\"\"\"\nFind all pngs in a directory\n\"\"\"\nimport os\n\n\ndef find_png(dir_name, result=[]):\n \"\"\"\n Does a recursive search of a directory and returns a list of pngs discovered\n\n :param dir_name: The path of the directory to search\n :param result: List to append results to\n \"\"\"\n all_files = [os.path.join(dir_name, x) for x in os.listdir(dir_name)]\n files = filter(os.path.isfile, all_files)\n pngs = []\n for file in files:\n filename, file_extension = os.path.splitext(file)\n if file_extension == '.png':\n pngs.append(os.path.basename(file))\n if pngs:\n result.append(os.path.abspath(dir_name))\n result.append(pngs)\n\n dirs = filter(os.path.isdir, all_files)\n for directory in dirs:\n find_png(directory, result)\n return result\n\n\nif __name__ == \"__main__\":\n png_list = find_png('./data')\n print(png_list)\n","sub_path":"students/rod_musser/lesson09/assignment/jpgdiscover.py","file_name":"jpgdiscover.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"106386013","text":"from database import DB\n\n\nclass Comment:\n def __init__(self, id, post, message):\n self.id = id\n self.post = post\n self.message = message\n\n def create(self):\n with DB() as db:\n values = (self.post.id, self.message)\n db.execute(\n 'INSERT INTO comments (post_id, message) VALUES (?, ?)',\n values\n )\n return self\n\n @staticmethod\n def find_by_post(post):\n with DB() as db:\n rows = db.execute(\n 'SELECT * FROM comments WHERE post_id = ?',\n (post.id,)\n ).fetchall()\n return [Comment(*row) for row in rows]\n","sub_path":"school_year_2019_2020/flask1/comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"289277217","text":"# coding=utf-8\n# Copyright 2019 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Regularizers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport six\nimport tensorflow as tf\n\nfrom tensorflow_probability import edward2 as ed\n\n\nclass NormalKLDivergence(tf.keras.regularizers.Regularizer):\n \"\"\"KL divergence regularizer from one normal distribution to another.\"\"\"\n\n def __init__(self, mean=0., stddev=1.):\n \"\"\"Construct regularizer where default is a KL towards the std normal.\"\"\"\n self.mean = mean\n self.stddev = stddev\n\n def __call__(self, x):\n \"\"\"Computes regularization given an ed.Normal random variable as input.\"\"\"\n if not isinstance(x, ed.RandomVariable):\n raise ValueError('Input must be an ed.RandomVariable.')\n random_variable = ed.Independent(\n ed.Normal(\n loc=tf.broadcast_to(self.mean, x.distribution.event_shape),\n scale=tf.broadcast_to(self.stddev, x.distribution.event_shape)\n ).distribution,\n reinterpreted_batch_ndims=len(x.distribution.event_shape))\n return random_variable.distribution.kl_divergence(x.distribution)\n\n def get_config(self):\n return {\n 'mean': self.mean,\n 'stddev': self.stddev,\n }\n\n\n# Compatibility aliases, following tf.keras\n\n\nnormal_kl_divergence = NormalKLDivergence # pylint: disable=invalid-name\n\n# Utility functions, following tf.keras\n\n\ndef serialize(initializer):\n return tf.keras.utils.serialize_keras_object(initializer)\n\n\ndef deserialize(config, custom_objects=None):\n return tf.keras.utils.deserialize_keras_object(\n config,\n module_objects=globals(),\n custom_objects=custom_objects,\n printable_module_name='regularizers')\n\n\ndef get(identifier, value=None):\n \"\"\"Getter for loading from strings; returns value if can't load.\"\"\"\n if value is None:\n value = identifier\n if identifier is None:\n return None\n elif isinstance(identifier, dict):\n try:\n return deserialize(identifier)\n except ValueError:\n return value\n elif isinstance(identifier, six.string_types):\n config = {'class_name': str(identifier), 'config': {}}\n try:\n return deserialize(config)\n except ValueError:\n return value\n elif callable(identifier):\n return identifier\n return value\n","sub_path":"tensor2tensor/keras/regularizers.py","file_name":"regularizers.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"645818370","text":"from rest_framework.parsers import JSONParser\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework.status import (\n HTTP_200_OK, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND)\nfrom django.http import JsonResponse\nfrom django.db import IntegrityError\nfrom django.utils import timezone\nfrom .serializers import AuthUserSerializer, TwitSerializer\nfrom .models import AuthUser, AuthToken, Twit, Comment\nfrom .decorators import login_required\nimport json\nfrom django.core import serializers\n\n\n@api_view(['POST'])\ndef Register(request):\n\n data = JSONParser().parse(request)\n serializer = AuthUserSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return Response({'User email: {}'.format(serializer.data['email'])}, status=HTTP_201_CREATED)\n return JsonResponse(serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\ndef Login(request):\n\n data = JSONParser().parse(request)\n\n if AuthUser.objects.verify_password(data['email'], data['password']):\n user = AuthUser.objects.get(email=data['email'])\n if user is None:\n return JsonResponse(data, status=HTTP_400_BAD_REQUEST)\n\n token = AuthToken.objects.create(user)\n token.save()\n user.last_login = timezone.now()\n user.save()\n return Response(token.code, status=HTTP_200_OK)\n\n return JsonResponse(data, status=HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\n@login_required()\ndef Logout(request):\n if AuthToken.objects.remove(request.session['user_token']):\n del request.session['user_id']\n return Response(status=HTTP_204_NO_CONTENT)\n\n return Response(status=HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\n@login_required()\ndef CreateTwit(request):\n\n user = AuthUser.objects.get(\n id=request.session['user_id'])\n data = JSONParser().parse(request)\n\n twit = Twit.objects.create(user=user, text=data['content'])\n twit.save()\n return Response({'New twit {} is created at {}'.format(twit.content, twit.created_at)}, status=HTTP_201_CREATED)\n\n\n@api_view(['POST'])\n@login_required()\ndef CreateComment(request):\n\n user = AuthUser.objects.get(\n id=request.session['user_id'])\n data = JSONParser().parse(request)\n\n twit = Twit.objects.get(id=data['twit_id'])\n\n comment = Comment.objects.create(\n user=user, twit=twit, text=data['content'])\n comment.save()\n return Response({'New Comment {} is created at {}'.format(comment.content, comment.created_at)}, status=HTTP_201_CREATED)\n\n\n@api_view(['POST'])\n@login_required()\ndef CreateLikeit(request):\n\n user = AuthUser.objects.get(\n id=request.session['user_id'])\n data = JSONParser().parse(request)\n\n twit = Twit.objects.get(id=data['twit_id'])\n\n twit.likeit.add(user)\n\n return Response({}, status=HTTP_201_CREATED)\n\n\n@api_view(['DELETE'])\n@login_required()\ndef DestoryLikeit(request):\n\n user = AuthUser.objects.get(\n id=request.session['user_id'])\n data = JSONParser().parse(request)\n\n twit = Twit.objects.get(id=data['twit_id'])\n\n twit.likeit.remove(user)\n\n return Response({}, status=HTTP_204_NO_CONTENT)\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\n@login_required()\ndef TwitDetail(request, pk):\n\n try:\n twit = Twit.objects.get(id=pk)\n except Twit.DoesNotExist:\n return Response({}, status=HTTP_400_BAD_REQUEST)\n\n if request.method == 'GET':\n\n try:\n twits = Twit.objects.filter(id=pk)\n except Twit.DoesNotExist:\n return Response({}, status=HTTP_400_BAD_REQUEST)\n\n return Response({serializers.serialize('json', twits)}, status=HTTP_200_OK)\n\n if request.method == 'DELETE':\n if twit.user_id == request.session['user_id']:\n twit.delete()\n return Response({}, status=HTTP_204_NO_CONTENT)\n\n if request.method == 'PUT':\n if twit.user_id == request.session['user_id']:\n data = JSONParser().parse(request)\n twit = Twit.objects.update(twit=twit, text=data['content'])\n twit.save()\n return Response({}, status=HTTP_204_NO_CONTENT)\n\n return Response({}, status=HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET'])\n@login_required()\ndef TwitCommentDetail(request, pk):\n\n try:\n twit = Twit.objects.get(id=pk)\n except Twit.DoesNotExist:\n return Response({}, status=HTTP_400_BAD_REQUEST)\n\n try:\n comments = Comment.objects.filter(twit=twit)\n except Comment.DoesNotExist:\n return Response({}, status=HTTP_400_BAD_REQUEST)\n\n return Response({serializers.serialize('json', comments)}, status=HTTP_200_OK)\n\n\n@api_view(['GET', 'PUT', 'DELETE'])\n@login_required()\ndef CommentDetail(request, pk):\n\n try:\n comment = Comment.objects.get(id=pk)\n except Comment.DoesNotExist:\n return Response({}, status=HTTP_400_BAD_REQUEST)\n\n if request.method == 'GET':\n return JsonResponse({'Comment': comment.content}, status=HTTP_200_OK)\n\n if request.method == 'DELETE':\n if comment.user_id == request.session['user_id']:\n comment.delete()\n return Response({}, status=HTTP_204_NO_CONTENT)\n\n if request.method == 'PUT':\n if comment.user_id == request.session['user_id']:\n data = JSONParser().parse(request)\n comment = Comment.objects.update(\n comment=comment, text=data['content'])\n comment.save()\n return Response({}, status=HTTP_204_NO_CONTENT)\n\n return Response({}, status=HTTP_400_BAD_REQUEST)\n","sub_path":"simpleTwit/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"206508279","text":"class EmptyHeapException(Exception):\n pass\nclass Heap():\n ''' represents a heap, which is a complete binary tree, and satisfies \n a heap-order, using a list.\n In this implelmentation, each node contains the keys only. \n you complete this code by storing an entry (key, value) in each node.\n ''' \n def __init__(self, root_data):\n '''(eah, obj) -> NoneType\n construct a heap with data as its root'''\n #representation invariant\n # _heap is a list\n # _heap[0] represents the root of the tree\n # _heap[0] has the highest priority\n # _heap[2*i + 1] represents the left child of the \n # node that stored at index i, and _heap[2*i + 1] >= _heap[i] \n # _heap[2*i + 2] represents the right child of the \n # node that stored at index i, and _heap[2*i + 2] >= _heap[i]\n # _heap[len(_heap) -1] shows the last node\n # _heap[:] represents the result of traversing the tree by BFS, if not empty\n \n \n # append root_data to a newly created empty list.\n self._heap = []\n self._heap.append(root_data)\n \n def size(self):\n '''(Heap) -> int\n returns the number of nodes in the heap'''\n return len(self._heap)\n\n def is_empty(self):\n '''(Heap) -> bool\n returns True if this heap is empty'''\n return len(self._heap) == 0\n\n def remove_last_node(self):\n '''(Heap) -> obj\n removes the last node from the heap and returns the key stored in this node\n Raises: EmptyHeapException if this heap is empty'''\n if (self.is_empty()):\n raise EmptyHeapException(\"Heap is empty\")\n return self._heap.pop(len(self._heap)-1)\n \n def min(self):\n '''(Heap) -> obj\n returns the item with the highest priority\n Raises: EmptyHeapException'''\n if (self.is_empty()):\n raise EmptyHeapException(\"Heap is empty\")\n return self._heap[0]\n\n def insert(self, data):\n '''(Heap, obj) -> NoenType\n insert the given data at right place in the heap'''\n # step 1, 2, 3: find the new last node, insert data, update last node\n # new last node is the element at len(self._heap)\n self._heap.append(data)\n #step 3, restore heap-order\n self.upheap_bubbling()\n def upheap_bubbling (self):\n '''(Heap) -> None\n restores heap order by swaping the items along an upward path from inserted node'''\n # find the last node index\n cur = len(self._heap)-1\n # find the parent (always (last_node - 1//2) because it rounded down)\n parent = (cur -1 )//2\n # continue swapping until last node in right place or you get to the root\n while (cur > 0 and self._heap[parent] > self._heap[cur]):\n self._heap[parent] , self._heap[cur] = self._heap[cur] , self._heap[parent]\n # update cur and parent\n cur = parent\n parent = (cur -1 )//2\n \n def extract_min(self):\n '''(Heap) -> obj\n removes the highest priority item and return it.\n Raises: EmptyHeapException\n '''\n # raise an exception if heap is empty\n if (self.is_empty()):\n raise EmptyHeapException (\"Heap is empty\")\n # step 1: get the min value \n min_value = self._heap[0]\n # remove the last node\n l_node = self._heap.pop(len(self._heap) -1)\n # step2: replace the root with last node if at least there is one item in the heap\n if(len(self._heap) != 0):\n # replace root with the last node\n self._heap[0] = l_node\n # step 3, 4: last node will be updated automatically, so restore the heap_order\n self.downheap_bubbling()\n # return the highest priority item\n return min_value\n \n def downheap_bubbling(self):\n '''(Heap) -> NoneType\n restore the heap order by swapping the items down the path'''\n # start from the root\n cur = 0\n # continue going down while heap order is violated\n while (self.violates(cur)):\n # find the index of the child which contains smaller data/ violates heap order\n child_index = self.find_index(cur)\n # swap data at cur and data at child\n self._heap[cur] , self._heap[child_index] = self._heap[child_index] , self._heap[cur]\n # update cur to point to child_index\n cur = child_index\n def violates(self, index):\n '''(Heap, index) -> bool\n checks if the given index has a key greater than one of its children'''\n # get left and right child index\n left = index * 2 + 1\n right = index * 2 + 2\n # raise a flag as an indicator of the violation\n violates = True\n # if cur index points to a leaf, it does not violate the heap order. a leaf is a node whose left child index is greater than the heap's length\n if (left >= len(self._heap)):\n violates = False\n # otherwise, it may have one child. since the heap is a complete tree, therfore it has a left child, which means the index to right child is >= than the heap's length. In this case we check the left child for the violation of heap-order\n elif (right >= len(self._heap)):\n violates = self._heap[index] > self._heap[left]\n #otherwise, it has two children, therefore you need to check both the children \n else:\n violates = (self._heap[index] > self._heap[left]) or (self._heap[index] > self._heap[right])\n return violates\n def find_index(self, index): \n '''(Heap, int) -> int\n return the index where it violates the heap order'''\n # find left and right child and initialize returned index\n left = index * 2 + 1\n right = index * 2 + 2\n returned_index = 0\n #if it has one child, it is left child. which means right child's index >= len of heap\n if (right >= len (self._heap)):\n returned_index = left\n # otherwise, we should find which one of its children has smaller data\n elif (self._heap[left] < self._heap[right]):\n returned_index = left\n else:\n returned_index = right\n #return the found index\n return returned_index\n \n def BFS(self):\n '''(BT) -> str\n traverse the tree in Breadth First search mehtod\n '''\n # remove all Nones from the list\n result = \"\"\n for item in self._heap:\n if (item is not None):\n result = result + \" \" + str(item)\n return result\n \n \n\n \n\n \n \n\nif (__name__ == \"__main__\"):\n ''' construct a priority queue using a heap\n containing these keys:\n 95, 40, 55, 60, 20, 50, 85\n '''\n heap = Heap(95)\n heap.insert(40)\n heap.insert(55)\n heap.insert(60)\n heap.insert(20)\n heap.insert(50)\n heap.insert(85)\n \n print(heap.BFS())\n \n print(heap.extract_min())\n print(heap.BFS())\n print(heap.extract_min())\n print(heap.BFS())\n print(heap.extract_min())\n print(heap.BFS())\n print(heap.extract_min())\n print(heap.BFS())\n print(heap.extract_min())\n print(heap.BFS())\n print(heap.extract_min())\n print(heap.BFS())\n print(heap.extract_min())\n print(heap.BFS())\n \"\"\"this should raise an exception\n print(heap.extract_min())\n \"\"\"\n","sub_path":"Python/week_notes/week6_heap.py","file_name":"week6_heap.py","file_ext":"py","file_size_in_byte":7455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"93790707","text":"# USAGE STRINGS\nXKCD_USAGE = 'Usage: *!xkcd* _OR_ *!xkcd #*'\nNICE_USAGE = 'Usage: *really?*'\nEIGHTBALL_USAGE = 'Usage: *!8ball [question]?*'\nSTATUS_USAGE = 'Usage: !status or !status sisi'\nWH_USAGE = 'Usage: *!wh X###* eg. !wh H296'\n\n# Color codes: discord_bot.py requires an inbuilt 'discord.Color' object, or an int\nclass COLOR:\n GREEN = 0x00ff00\n ORANGE = 0xff7c00\n RED = 0xff0000\n\n# MISC\nEIGHTBALL_VALID_QUESTION = [\n 'It is certain.',\n 'It is decidedly so.',\n 'Without a doubt.',\n 'Yes, definitely.',\n 'You may rely on it.',\n 'Reply hazy, try again.',\n 'Ask again later.',\n 'Cannot predict now.',\n 'Concentrate and ask again.',\n 'Don\\'t count on it.',\n 'My reply is no.',\n 'My sources say no.',\n 'Outlook not so good.',\n 'Very doubtful.'\n]\n\nEIGHTBALL_INVALID_QUESTION = [\n 'Was that supposed to be a question?',\n 'No you.',\n 'I\\'ve met toasters who could speak english better than that.',\n 'Cmon, you can do better than that.',\n 'I\\'m an 8ball, not a translator.'\n]\n\n\nDOOSTER_PHRASES = [\n 'Nice',\n 'Get lit',\n ':350:',\n 'What happened?',\n 'P gud p gud',\n 'Tama. Tama tama tama. Tama?',\n 'Sorry for feed',\n 'Mhm'\n]\n\n\nK162ERROR = \"_Have you become trapped?_ :ghost:\"\n\n\nWORMHOLE_ATTR = \"*{wormhole_id}* leads to _{leads_to}_\\n\" \\\n \"*Size*: {jump_mass}\\n\" \\\n \"*Total Mass*: {total_mass} kg\\n\" \\\n \"*Lifetime*: {lifetime}h\"\n\nWORMHOLE_ATTR_REGEN = \"*{wormhole_id}* leads to _{leads_to}_\\n\" \\\n \"*Size*: {jump_mass}\\n\" \\\n \"*Total Mass*: {total_mass} kg\\n\" \\\n \"*Regen*: {regenMass} kg per cycle\\n\" \\\n \"*Lifetime*: {lifetime}h\"\n\n\nJUMP_MASS_CATEGORIES = {\n 5000000: \"Small\",\n 20000000: \"Medium\",\n 300000000: \"Large\",\n 1000000000: \"Freighter\",\n 1350000000: \"Very Large\",\n 1480000000: \"Very Large\",\n 1800000000: \"Very Large\"\n}\n\nDESTINATION_CATEGORIES = {\n 1: \"Class 1 W-Space\",\n 2: \"Class 2 W-Space\",\n 3: \"Class 3 W-Space\",\n 4: \"Class 4 W-Space\",\n 5: \"Class 5 W-Space\",\n 6: \"Class 6 W-Space\",\n 7: \"Highsec\",\n 8: \"Lowsec\",\n 9: \"Nullsec\",\n 12: \"Thera\",\n 13: \"Class 13 W-Space\",\n 14: \"the Sentinel Drifter Wormhole\",\n 15: \"the Barbican Drifter Wormhole\",\n 16: \"the Vidette Drifter Wormhole\",\n 17: \"the Conflux Drifter Wormhole\",\n 18: \"the Redoubt Drifter Wormhole\"\n}\n","sub_path":"Miscellaneous/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"644733804","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /users/payno/.local/share/virtualenvs/tomwer_venc/lib/python3.7/site-packages/tomwer/gui/test/test_scanselector.py\n# Compiled at: 2019-12-11 09:05:53\n# Size of source mod 2**32: 3041 bytes\n__authors__ = [\n 'H. Payno']\n__license__ = 'MIT'\n__date__ = '22/01/2017'\nfrom tomwer.gui.qtapplicationmanager import QApplicationManager\nfrom tomwer.test.utils import skip_gui_test\nfrom silx.gui.utils.testutils import TestCaseQt\nfrom tomwer.gui.scanselectorwidget import ScanSelectorWidget\nfrom tomwer.core.utils.scanutils import MockEDF\nimport shutil, tempfile, unittest, logging\n_qapp = QApplicationManager()\nlogging.disable(logging.INFO)\n\n@unittest.skipIf((skip_gui_test()), reason='skip gui test')\nclass TestScanSelector(TestCaseQt):\n __doc__ = '\\n Simple test for the ScanSelectorOW\\n '\n\n def setUp(self):\n self._folder1 = tempfile.mkdtemp()\n self._folder2 = tempfile.mkdtemp()\n self._folder3 = tempfile.mkdtemp()\n for _folder in (self._folder1, self._folder2, self._folder3):\n MockEDF.mockScan(scanID=_folder, nRadio=5, nRecons=5, nPagRecons=0, dim=10)\n\n self.widget = ScanSelectorWidget(parent=None)\n\n def tearDown(self):\n shutil.rmtree(self._folder1)\n shutil.rmtree(self._folder2)\n shutil.rmtree(self._folder3)\n\n def test(self):\n self.widget.add(self._folder1)\n self.widget.add(self._folder2)\n self.widget.add(self._folder3)\n self.assertTrue(self.widget.dataList.length() is 3)\n self.widget.remove(self._folder3)\n self.assertTrue(self.widget.dataList.length() is 2)\n\n\ndef suite():\n test_suite = unittest.TestSuite()\n for ui in (TestScanSelector,):\n test_suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(ui))\n\n return test_suite\n\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')","sub_path":"pycfiles/tomwer-0.4.0.linux-x86_64.tar/test_scanselector.cpython-37.py","file_name":"test_scanselector.cpython-37.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"126521913","text":"# 2164.py\n# 2018.06.16\n\nimport sys\nimport collections\n\n\np = collections.deque(range(1, int(sys.stdin.readline())+1))\nwhile len(p) != 1:\n\tp.popleft()\n\tp.rotate(-1)\nprint(p.popleft())\n\n# queue의 size가 1이 될 때까지, popleft해주고 rotate해준다. \n","sub_path":"2000/2164.py","file_name":"2164.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"340892991","text":"# PyCutest problem interface module initialization file\n# (C)2011 Arpad Buermen\n# (C)2018 Jaroslav Fowkes, Lindon Roberts\n# Licensed under GNU GPL V3\n\n\"\"\"Interface module for CUTEst problem ARGLALE with ordering\n efirst=False, lfirst=False, nvfirst=False\nsifdecode parameters : N=100 M=200 \nsifdecode options : \n\nAvailable functions\ngetinfo -- get problem information\nvarnames -- get names of problem's variables\nconnames -- get names of problem's constraints\nobjcons -- objective and constraints\nobj -- objective and objective gradient\ncons -- constraints and constraints gradients/Jacobian\nlagjac -- gradient of objective/Lagrangian and constraints Jacobian\njprod -- product of constraints Jacobian with a vector\nhess -- Hessian of objective/Lagrangian\nihess -- Hessian of objective/constraint\nhprod -- product of Hessian of objective/Lagrangian with a vector\ngradhess -- gradient and Hessian of objective (unconstrained problems) or\n gradient of objective/Lagrangian, Jacobian of constraints and\n Hessian of Lagrangian (constrained problems)\nscons -- constraints and sparse Jacobian of constraints\nslagjac -- gradient of objective/Lagrangian and sparse Jacobian\nsphess -- sparse Hessian of objective/Lagrangian\nisphess -- sparse Hessian of objective/constraint\ngradsphess -- gradient and sparse Hessian of objective (unconstrained probl.)\n or gradient of objective/Lagrangian, sparse Jacobian of\n constraints and sparse Hessian of Lagrangian (constrained probl.)\nreport -- get usage statistics\n\"\"\"\n\n# Ensure compatibility with Python 2\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom ._pycutestitf import *\nfrom . import _pycutestitf\nimport os\nfrom scipy.sparse import coo_matrix\nfrom numpy import zeros\n\n# Get the directory where the binary module (and OUTSDIF.d) are found.\n(_directory, _module)=os.path.split(_pycutestitf.__file__)\n\n# Problem info structure and dimension\ninfo=None\nn=None\nm=None\n\n# Constraints and variable ordering\nefirst=False\nlfirst=False\nnvfirst=False\n\n# Remember current directory and go to module directory where OUTSDIF.d is located\nfromDir=os.getcwd()\nos.chdir(_directory)\n\n# Get problem dimension\n(n, m)=_pycutestitf._dims()\n\n# Set up the problem and get basic information\ninfo=_pycutestitf._setup(efirst, lfirst, nvfirst)\n\n# Store constraint and variable ordering information\nif m>0:\n info['efirst']=efirst\n info['lfirst']=lfirst\ninfo['nvfirst']=nvfirst\n\n# Store sifdecode parameters and options\ninfo['sifparams']={'N': 100, 'M': 200}\ninfo['sifoptions']=None\n\n# Go back to initial directory\nos.chdir(fromDir)\n\n# Return problem info\ndef getinfo():\n \"\"\"\n Return the problem info dictionary.\n\n info=geinfo()\n\n Output\n info -- dictionary with the summary of test function's properties\n\n The dictionary has the following members:\n name -- problem name\n n -- number of variables\n m -- number of constraints (excluding bounds)\n x -- initial point (1D array of length n)\n bl -- 1D array of length n with lower bounds on variables\n bu -- 1D array of length n with upper bounds on variables\n nnzh -- number of nonzero elements in the diagonal and upper triangle of\n sparse Hessian\n vartype -- 1D integer array of length n storing variable type\n 0=real, 1=boolean (0 or 1), 2=integer\n nvfirst -- boolean flag indicating that nonlinear variables were placed\n before linear variables\n sifparams -- parameters passed to sifdecode with the -param option\n None if no parameters were given\n sifoptions -- additional options passed to sifdecode\n None if no additional options were given.\n\n For constrained problems the following additional members are available\n nnzj -- number of nonzero elements in sparse Jacobian of constraints\n v -- 1D array of length m with initial values of Lagrange multipliers\n cl -- 1D array of length m with lower bounds on constraint functions\n cu -- 1D array of length m with upper bounds on constraint functions\n equatn -- 1D boolean array of length m indicating whether a constraint\n is an equation constraint\n linear -- 1D boolean array of length m indicating whether a constraint\n is a linear constraint\n efirst -- boolean flag indicating that equation constraints were places\n before inequation constraints\n lfirst -- boolean flag indicating that linear constraints were placed\n before nonlinear constraints\n \"\"\"\n return info\n\ndef varnames():\n \"\"\"\n Return the names of problem's variables.\n\n nameList=varnames()\n\n nameList -- a list of strings representing the names of problem's variables.\n The variabels are ordered according to nvfirst flag.\n \"\"\"\n return _pycutestitf._varnames()\n\ndef connames():\n \"\"\"\n Return the names of problem's constraints.\n\n nameList=connames()\n\n nameList -- a list of strings representing the names of problem constraints.\n The constraints are ordered according to efirst and lfirst flags.\n \"\"\"\n return _pycutestitf._connames()\n\n# Sparse tool wrappers (return scipy.sparse.coo_matrix matrices)\n# _scons() wrapper\ndef scons(x, i=None):\n \"\"\"Returns the value of constraints and\n the sparse Jacobian of constraints at x.\n\n (c, J)=_scons(x) -- Jacobian of constraints\n (ci, gi)=_scons(x, i) -- i-th constraint and its gradient\n\n Input\n x -- 1D array of length n with the values of variables\n i -- integer index of constraint (between 0 and m-1)\n\n Output\n c -- 1D array of length m holding the values of constraints at x\n J -- a scipy.sparse.coo_matrix of size m-by-n holding the Jacobian at x\n ci -- 1D array of length 1 holding the value of i-th constraint at x\n gi -- a scipy.sparse.coo_matrix of size 1-by-n holding the gradient of i-th constraint at x\n\n This function is a wrapper for _scons().\n \"\"\"\n\n if i is None:\n (c, Ji, Jif, Jv)=_pycutestitf._scons(x)\n return (c, coo_matrix((Jv, (Jif, Ji)), shape=(m, n)))\n else:\n (c, gi, gv)=_pycutestitf._scons(x, i)\n return (c, coo_matrix((gv, (zeros(len(gv)), gi)), shape=(1, n)))\n\n# _slagjac() wrapper\ndef slagjac(x, v=None):\n \"\"\"Returns the sparse gradient of objective at x or Lagrangian at (x, v),\n and the sparse Jacobian of constraints at x.\n\n (g, J)=_slagjac(x) -- objective gradient and Jacobian\n (g, J)=_slagjac(x, v) -- Lagrangian gradient and Jacobian\n\n Input\n x -- 1D array of length n with the values of variables\n v -- 1D array of length m with the values of Lagrange multipliers\n\n Output\n g -- a scipy.sparse.coo_matrix of size 1-by-n holding the gradient of objective at x or\n the gradient of Lagrangian at (x, v)\n J -- a scipy.sparse.coo_matrix of size m-by-n holding the sparse Jacobian\n of constraints at x\n\n This function is a wrapper for _slagjac().\n \"\"\"\n\n if v is None:\n (gi, gv, Ji, Jfi, Jv)=_pycutestitf._slagjac(x)\n else:\n (gi, gv, Ji, Jfi, Jv)=_pycutestitf._slagjac(x, v)\n return (\n coo_matrix((gv, (zeros(len(gv)), gi)), shape=(1, n)),\n coo_matrix((Jv, (Jfi, Ji)), shape=(m, n))\n )\n\n# _sphess() wrapper\ndef sphess(x, v=None):\n \"\"\"Returns the sparse Hessian of the objective at x (unconstrained problems)\n or the sparse Hessian of the Lagrangian (constrained problems) at (x, v).\n\n H=_sphess(x) -- Hessian of objective (unconstrained problems)\n H=_sphess(x, v) -- Hessian of Lagrangian (constrained problems)\n\n Input\n x -- 1D array of length n with the values of variables\n v -- 1D array of length m with the values of Lagrange multipliers\n\n Output\n H -- a scipy.sparse.coo_matrix of size n-by-n holding the sparse Hessian\n of objective at x or the sparse Hessian of the Lagrangian at (x, v)\n\n This function is a wrapper for _sphess().\n \"\"\"\n\n if v is None:\n (Hi, Hj, Hv)=_pycutestitf._sphess(x)\n else:\n (Hi, Hj, Hv)=_pycutestitf._sphess(x, v)\n return coo_matrix((Hv, (Hi, Hj)), shape=(n, n))\n\n# _isphess() wrapper\ndef isphess(x, i=None):\n \"\"\"Returns the sparse Hessian of the objective or the sparse Hessian of i-th\n constraint at x.\n\n H=_isphess(x) -- Hessian of objective\n H=_isphess(x, i) -- Hessian of i-th constraint\n\n Input\n x -- 1D array of length n with the values of variables\n i -- integer holding the index of constraint (between 0 and m-1)\n\n Output\n H -- a scipy.sparse.coo_matrix of size n-by-n holding the sparse Hessian\n of objective or the sparse Hessian i-th constraint at x\n\n This function is a wrapper for _isphess().\n \"\"\"\n\n if i is None:\n (Hi, Hj, Hv)=_pycutestitf._isphess(x)\n else:\n (Hi, Hj, Hv)=_pycutestitf._isphess(x, i)\n return coo_matrix((Hv, (Hi, Hj)), shape=(n, n))\n\n# _gradsphess() wrapper\ndef gradsphess(x, v=None, lagrFlag=False):\n \"\"\"Returns the sparse Hessian of the Lagrangian, the sparse Jacobian of\n constraints, and the gradient of the objective or Lagrangian.\n\n (g, H)=gradsphess(x) -- unconstrained problems\n (g, J, H)=gradsphess(x, v, gradl) -- constrained problems\n\n Input\n x -- 1D array of length n with the values of variables\n v -- 1D array of length m with the values of Lagrange multipliers\n gradl -- boolean flag. If False the gradient of the objective is returned,\n if True the gradient of the Lagrangian is returned.\n Default is False\n\n Output\n g -- a scipy.sparse.coo_matrix of size 1-by-n holding the gradient of objective at x or\n the gradient of Lagrangian at (x, v)\n J -- a scipy.sparse.coo_matrix of size m-by-n holding the sparse Jacobian\n of constraints at x\n H -- a scipy.sparse.coo_matrix of size n-by-n holding the sparse Hessian\n of objective at x or the sparse Hessian of the Lagrangian at (x, v)\n\n This function is a wrapper for _gradsphess().\n \"\"\"\n\n if v is None:\n (g, Hi, Hj, Hv)=_pycutestitf._gradsphess(x)\n return (coo_matrix(g), coo_matrix((Hv, (Hi, Hj)), shape=(n, n)))\n else:\n (gi, gv, Ji, Jfi, Jv, Hi, Hj, Hv)=_pycutestitf._gradsphess(x, v, lagrFlag)\n return (\n coo_matrix((gv, (zeros(len(gv)), gi)), shape=(1, n)),\n coo_matrix((Jv, (Jfi, Ji)), shape=(m, n)),\n coo_matrix((Hv, (Hi, Hj)), shape=(n, n))\n )\n\n# Clean up\ndel os, fromDir, efirst, lfirst, nvfirst\n","sub_path":"pycutest_cache_holder/ARGLALE_M200_N100/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"60394938","text":"from __future__ import absolute_import, division, print_function\n\n# ------------------------------------------------------------------------------ #\n# reference\n# https://github.com/huggingface/transformers/blob/master/examples/utils_ner.py\n# ------------------------------------------------------------------------------ #\n\nimport os\nimport pdb\n\nfrom tqdm import tqdm\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nclass InputExample(object):\n def __init__(self, guid, words, label):\n self.guid = guid\n self.words = words\n self.label = label\n\nclass InputFeature(object):\n def __init__(self, input_ids, input_mask, segment_ids, label_id):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n\ndef read_examples_from_file(file_path, mode='train'):\n guid_index = 1\n examples = []\n tot_num_line = sum(1 for _ in open(file_path, 'r'))\n with open(file_path, encoding=\"utf-8\") as f:\n for idx, line in enumerate(tqdm(f, total=tot_num_line)):\n sent, label = line.strip().split('\\t')\n words = sent.split()\n assert(len(words) >= 1)\n examples.append(InputExample(guid=\"{}-{}\".format(mode, guid_index),\n words=words,\n label=label))\n guid_index += 1\n return examples\n\ndef convert_single_example_to_feature(example,\n label_map,\n max_seq_length,\n tokenizer,\n cls_token=\"[CLS]\",\n cls_token_segment_id=0,\n sep_token=\"[SEP]\",\n sep_token_extra=False,\n pad_token=0,\n pad_token_segment_id=0,\n sequence_a_segment_id=0,\n ex_index=-1):\n\n tokens = []\n label = example.label\n label_id = -1\n for word in example.words:\n word_tokens = tokenizer.tokenize(word)\n tokens.extend(word_tokens)\n if label in label_map: label_id = label_map[label]\n if len(label.split()) >= 2: # logits as label\n label_id = label\n \n # Account for [CLS] and [SEP] with \"- 2\" and with \"- 3\" for RoBERTa.\n special_tokens_count = 3 if sep_token_extra else 2\n if len(tokens) > max_seq_length - special_tokens_count:\n tokens = tokens[:(max_seq_length - special_tokens_count)]\n\n # convention in BERT:\n # for single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # input_ids: x x x x x x x 0 0 0 ...\n # segment_ids: 0 0 0 0 0 0 0 0 0 0 ...\n # input_mask: 1 1 1 1 1 1 1 0 0 0 ...\n\n tokens += [sep_token]\n if sep_token_extra:\n # roberta uses an extra separator b/w pairs of sentences\n tokens += [sep_token]\n segment_ids = [sequence_a_segment_id] * len(tokens)\n\n tokens = [cls_token] + tokens\n segment_ids = [cls_token_segment_id] + segment_ids\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n input_mask = [1] * len(input_ids)\n\n # zero-pad up to the sequence length.\n padding_length = max_seq_length - len(input_ids)\n input_ids += ([pad_token] * padding_length)\n input_mask += ([0] * padding_length)\n segment_ids += ([pad_token_segment_id] * padding_length)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n if ex_index != -1 and ex_index < 5:\n logger.info(\"*** Example ***\")\n logger.info(\"guid: %s\", example.guid)\n logger.info(\"tokens: %s\", \" \".join([str(x) for x in tokens]))\n logger.info(\"input_ids: %s\", \" \".join([str(x) for x in input_ids]))\n logger.info(\"input_mask: %s\", \" \".join([str(x) for x in input_mask]))\n logger.info(\"segment_ids: %s\", \" \".join([str(x) for x in segment_ids]))\n logger.info(\"label: %s\", label)\n logger.info(\"label_id: %s\", label_id)\n\n feature = InputFeature(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id)\n return feature\n\ndef convert_examples_to_features(examples,\n label_map,\n max_seq_length,\n tokenizer,\n cls_token=\"[CLS]\",\n cls_token_segment_id=0,\n sep_token=\"[SEP]\",\n sep_token_extra=False,\n pad_token=0,\n pad_token_segment_id=0,\n sequence_a_segment_id=0):\n\n features = []\n for (ex_index, example) in enumerate(tqdm(examples)):\n '''\n if ex_index % 1000 == 0:\n logger.info(\"Writing example %d of %d\", ex_index, len(examples))\n '''\n feature = convert_single_example_to_feature(example,\n label_map,\n max_seq_length,\n tokenizer,\n cls_token=cls_token,\n cls_token_segment_id=cls_token_segment_id,\n sep_token=sep_token,\n sep_token_extra=sep_token_extra,\n pad_token=pad_token,\n pad_token_segment_id=pad_token_segment_id,\n sequence_a_segment_id=sequence_a_segment_id,\n ex_index=ex_index)\n features.append(feature)\n return features\n","sub_path":"util_bert.py","file_name":"util_bert.py","file_ext":"py","file_size_in_byte":6242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"271256355","text":"import psutil\r\nfrom Projeto import cpu\r\nfrom variaveis import *\r\n\r\n#Início\r\npygame.init()\r\n\r\n\r\n######################## Defs ###########################\r\n##### Memória #####\r\ndef uso_memoria(x, y, z):\r\n tela_memoria.fill(white)\r\n font = pygame.font.Font(None, 32)\r\n larg = largura_tela - 2* 20\r\n pygame.draw.rect(tela_memoria, blue, (0, 10, larg, 80))\r\n larg = larg* memoria.porcentagem() /100\r\n pygame.draw.rect(tela_memoria, red, (0, 10, larg, 80))\r\n info_memoria = str(memoria.porcentagem())\r\n texto_barra = \"Uso da Memória (Total: \" + str(memoria.total()) + \"): \" + info_memoria + \"%\"\r\n text = font.render(texto_barra, True, black)\r\n tela.blit(text, (10, z))\r\n tela.blit(tela_memoria, (x, y))\r\n\r\ndef mostra_info_memoria():\r\n memoria_total = font.render(\"Memória Total: \" + str(memoria.total()), True, black)\r\n memoria_utilizada = font.render(\"Memória Utilizada: \" + str(memoria.utilizado()), True, black)\r\n memoria_disponível = font.render(\"Memória Disponível: \" + str(memoria.disponivel()), True, black)\r\n\r\n tela.blit(memoria_total, (10, 65))\r\n tela.blit(memoria_utilizada, (10, 95))\r\n tela.blit(memoria_disponível, (10, 125))\r\n\r\n\r\n\r\n##### HD #####\r\ndef uso_hd(x, y, z):\r\n tela_hd.fill(white)\r\n font = pygame.font.Font(None, 32)\r\n larg = largura_tela - 2 * 20\r\n pygame.draw.rect(tela_hd, blue, (0, 10, larg, 80))\r\n larg = larg * hd.porcentagem() / 100\r\n pygame.draw.rect(tela_hd, red, (0, 10, larg, 80))\r\n info = str (hd.porcentagem())\r\n texto_barra = \"Uso do Disco: (Total: \" + str(hd.total()) + \"): \" + info + \"%\"\r\n text = font.render(texto_barra, True, black)\r\n tela.blit(text, (10, z))\r\n tela.blit(tela_hd, (x, y))\r\n\r\ndef mostra_info_hd():\r\n hd_total = font.render(\"Armazenamento Total: \" + str(hd.total()), True, black)\r\n hd_utilizado = font.render(\"Armazenamento Utilizado: \" + str(hd.utilizado()), True, black)\r\n hd_disponivel = font.render(\"Armazenamento Disponível: \" + str(hd.disponivel()), True, black)\r\n\r\n tela.blit(hd_total, (10, 65))\r\n tela.blit(hd_utilizado, (10, 95))\r\n tela.blit(hd_disponivel, (10, 125))\r\n\r\n\r\n\r\n##### CPU #####\r\ndef uso_cpu(x, y, z):\r\n tela_cpu2.fill(white)\r\n font = pygame.font.Font(None, 32)\r\n larg = largura_tela - 2 * 20\r\n pygame.draw.rect(tela_cpu2, blue, (0, 10, larg, 80))\r\n larg = larg * cpu.porcentagem() / 100\r\n pygame.draw.rect(tela_cpu2, red, (0, 10, larg, 80))\r\n texto_barra = \"Uso da CPU: \" + str(round((larg/10), 1)) + \"%\"\r\n text = font.render(texto_barra, True, black)\r\n tela.blit(text, (10, z))\r\n tela.blit(tela_cpu2, (x, y))\r\n\r\ndef usos_cpu_todos(l_cpu_percent):\r\n tela_cpu.fill(white)\r\n num_cpu = len(l_cpu_percent)\r\n x = y = 10\r\n desl = 10\r\n alt = tela_cpu.get_height() - 5*y\r\n larg = (tela_cpu.get_width()-45*y -(num_cpu+1) *desl ) /num_cpu\r\n d = x + desl\r\n for i in l_cpu_percent:\r\n pygame.draw.rect(tela_cpu, red, (d, y, larg, alt))\r\n pygame.draw.rect(tela_cpu, blue, (d, y, larg, (1-i/100)*alt))\r\n d = d + larg + desl\r\n tela.blit(tela_cpu, (largura_tela/6, altura_tela/1.4))\r\n\r\nclass Info:\r\n def __init__(self):\r\n self.__name = str(cpu.name())\r\n self.__arquitetura = str(cpu.arch())\r\n self.__palavra = str(cpu.bits())\r\n self.__max = str(cpu.freq_max())\r\n self.__cores = str(cpu.cores())\r\n\r\n def name(self):\r\n return self.__name\r\n\r\n def arquitetura(self):\r\n return self.__arquitetura\r\n\r\n def palavra(self):\r\n return self.__palavra\r\n\r\n def max(self):\r\n return self.__max\r\n\r\n def cores(self):\r\n return self.__cores\r\n\r\nI = Info()\r\n\r\ndef mostra_info_cpu():\r\n nome_processador = font.render(\"Nome: \" + I.name(), True, black)\r\n arquitetura_processador = font.render(\"Arquitetura: \" + I.arquitetura(), True, black)\r\n palavra_processador = font.render(\"Palavra: \" + I.palavra() + \" bits\", True, black)\r\n frequencia_processador = font.render(\"Frequência Atual: \" + str(cpu.freq_atual()), True, black)\r\n max_frequencia_processador = font.render(\"Frequência Máxima: \" + I.max(), True, black)\r\n nucleo_processador = font.render(\"Núcleos (lógicos): \" + I.cores() + \" (\" + str(cpu.physical_processors()) + \")\", True, black)\r\n tempo_processador = font.render(\"Tempo Ativo: \" + str(cpu.tempo_ativo()), True, black)\r\n\r\n tela.blit(nome_processador, (10, 65))\r\n tela.blit(arquitetura_processador, (10, 95))\r\n tela.blit(palavra_processador, (10, 125))\r\n tela.blit(frequencia_processador, (10, 155))\r\n tela.blit(max_frequencia_processador, (10, 185))\r\n tela.blit(nucleo_processador, (10, 215))\r\n tela.blit(tempo_processador, (10, 245))\r\n\r\n\r\n\r\n\r\n##### Ethernet #####\r\ndef mostra_info_ethernet():\r\n net_mac = font.render(\"Mac: \" + str(ethernet.get_mac()), True, black)\r\n net_ip = font.render(\"IPv4: \" + str(ethernet.get_ip()), True, black)\r\n net_mask = font.render(\"Máscara de Rede: \" + str(ethernet.get_mask()), True, black)\r\n dados_enviados = font.render(\"Dados Enviados: \" + str(ethernet.enviados()), True, black)\r\n dados_recebidos = font.render(\"Dados Recebidos: \" + str(ethernet.recebidos()), True, black)\r\n pid_text = font.render(\"PID: \", True, black)\r\n\r\n tela.blit(net_mac, (10, 65))\r\n tela.blit(net_ip, (10, 95))\r\n tela.blit(net_mask, (10, 125))\r\n tela.blit(dados_enviados, (10, 155))\r\n tela.blit(dados_recebidos, (10, 185))\r\n tela.blit(pid_text, (10, 225))\r\n\r\ndef info_pid_ethernet(x):\r\n global info_pids\r\n info_pids = psutil.Process(x).connections()\r\n print(info_pids)\r\n\r\n\r\n\r\n\r\n\r\ndef info_pid_ethernet2():\r\n a = \"\"\r\n b = ''\r\n c = ''\r\n d = ''\r\n\r\n try:\r\n a = str(info_pids[0].laddr[0])\r\n b = str(info_pids[0].laddr[1])\r\n c = str(info_pids[0].raddr[0])\r\n d = str(info_pids[0].raddr[1])\r\n\r\n print(\"Endereço Local\")\r\n print(\"IP:\", info_pids[0].laddr[0])\r\n print(\"Porta:\", info_pids[0].laddr[1])\r\n\r\n print()\r\n\r\n print(\"Endereço Remoto\")\r\n print(\"IP:\", info_pids[0].raddr[0])\r\n print(\"Porta:\", info_pids[0].raddr[1])\r\n\r\n\r\n print(b)\r\n\r\n except:\r\n print(\"Error\")\r\n\r\n end_local = font.render(\"Endereço Local\", True, black)\r\n ip_local = font.render(\"IP: \" + a, True, black)\r\n porta_local = font.render(\"Porta: \" + b, True, black)\r\n end_remoto = font.render(\"Endereço Remoto\", True, black)\r\n ip_remoto = font.render(\"IP: \" + c, True, black)\r\n porta_remoto = font.render(\"PID: \" + d, True, black)\r\n\r\n tela.blit(end_local, (10, 260))\r\n tela.blit(ip_local, (30, 290))\r\n tela.blit(porta_local, (30, 320))\r\n tela.blit(end_remoto, (10, 350))\r\n tela.blit(ip_remoto, (30, 380))\r\n tela.blit(porta_remoto, (30, 410))","sub_path":"Projeto/Projeto/usos.py","file_name":"usos.py","file_ext":"py","file_size_in_byte":6733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"1955711","text":"# -*- coding: utf-8 -*-\nimport wave\nimport sys\nimport threading\nimport time\nimport RPi.GPIO as GPIO\nfrom subprocess import Popen\n\n\n# Mapping Table/Dictionary for the \"time of reminder\" and the\n# \"reminder voice content file to be played\"\n# Actual Field Values\n# Last value @ 00:00 is for testing\nreminder = {'09:00':'sartel40Reminder.wav',\n '21:00':'nebula2pt5Reminder.wav'}\n\ndef playWavFileUsingaplay(wavFile):\n logToFile(\"\\nEntering playWavFileUsingaplay() function !....\")\n wavFile = '/home/pi/myWorkspace/python_programs/MedicineReminder/' + wavFile\n Popen(['aplay', wavFile])\n logToFile(\"\\nExiting playWavFileUsingaplay() function !\")\n\ndef scheduleTimer():\n logToFile(\"\\nEntering scheduleTimer() function!\")\n timer = threading.Timer(30, timerCallback) \n timer.start()\n logToFile(\"\\nExiting scheduleTimer() function!\")\n\ndef timerCallback():\n global reminderNotification\n global wavFileGlobal\n \n logToFile(\"\\nEntering timerCallback() function : Timer Expired!....\")\n currentTime = time.ctime()\n timer = threading.Timer(30, timerCallback) \n timer.start()\n logToFile(\"\\nNew 30 Sec Timer Started\") \n\n reminderTimeHit = reminder.get(currentTime[11:16], 'No')\n if(reminderTimeHit != 'No'):\n # New time/reminder hit\n logToFile(\"\\nNotification Condition Hit !\")\n reminderNotification = True\n wavFileGlobal = reminderTimeHit\n logToFile(wavFileGlobal)\n \n if(reminderNotification):\n logToFile(\"\\nReminder : Every 30 sec\")\n logToFile(wavFileGlobal)\n playWavFileUsingaplay(wavFileGlobal)\n logToFile(\"\\nWave File Played!\")\n\ndef button_callback(channel):\n global reminderNotification\n global pinValueEqualsZeroCounter\n global debounceInProgress\n \n logToFile(\"Entering button_callback() function.......\")\n\n # Get value on the given pin number\n pinValue = GPIO.input(18)\n\n if(pinValue == 0):\n pinValueEqualsZeroCounter += 1\n \n if((debounceInProgress == False) and (pinValue == False)):\n debounceInProgress = True\n # Debounce interval set 200 ms\n switchDebounce(18, 0.2)\n\n logToFile(\"Exiting button_callback() function.......\")\n\ndef switchDebounce(pinNum, debounceInterval):\n logToFile(\"Entering switchDebounce() function.......\")\n # Start debouce timer\n debounceTimer = threading.Timer(debounceInterval, debounceTimerCallback) \n debounceTimer.start()\n logToFile(\"Exiting switchDebounce() function.......\")\n\ndef debounceTimerCallback():\n global pinValueEqualsZeroCounter\n global reminderNotification\n global debounceInProgress\n\n logToFile(\"Entering debounceTimerCallback() function.......\")\n \n # Get value on the given pin number\n pinValue = GPIO.input(18)\n # Check if the first reading is same as the reading\n # after debounce interval\n if((pinValueEqualsZeroCounter >= 3) or (pinValue == 0)):\n pinValueEqualsZeroCounter = 0\n # Switch genuinely pressed\n reminderNotification = False\n logToFile(\"Multiple hits to the required key press value detected: Button Pressed!\")\n \n logToFile(\"Exiting debounceTimerCallback() function.......\")\n debounceInProgress = False\n\ndef init():\n global reminderNotification\n global wavFileGlobal\n global debounceInProgress\n global pinValueEqualsZeroCounter\n \n reminderNotification = False\n wavFileGlobal = 'sartel40Reminder.wav'\n debounceInProgress = False\n pinValueEqualsZeroCounter = 0\n \n # Each pin on the Raspberry Pi has several different names, so you need to tell the program\n # which naming convention is to be used.\n GPIO.setmode(GPIO.BCM)\n \n # This tells Python not to print GPIO warning messages to the screen. \n GPIO.setwarnings(False)\n \n # This line tells the Python interpreter that pin 18 is going to be used for outputting information,\n # which means you are going to be able to turn the pin ‘on’ and ‘off’.\n # Set pin 18 to be an input pin and set initial value to be pulled HIGH (ON)\n GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n \n # Setup event on pin 18 falling edge\n GPIO.add_event_detect(18,GPIO.FALLING,callback=button_callback)\n\ndef logToFile(logText):\n logData = True\n if(logData):\n f1=open('/home/pi/myWorkspace/python_programs/MedicineReminder/Log.txt', 'a')\n # Log the current time\n f1.write(time.ctime())\n f1.write('\\n')\n f1.write(logText)\n f1.close()\n\ndef test():\n # 2 min in future\n estimatedHr = str(time.localtime(time.time() + 120).tm_hour)\n if(len(estimatedHr) == 1):\n estimatedHr = '0' + estimatedHr\n \n estimatedMin = str(time.localtime(time.time() + 120).tm_min)\n if(len(estimatedMin) == 1):\n estimatedMin = '0' + estimatedMin\n \n reminder[estimatedHr + ':' + estimatedMin] = 'nebula2pt5Reminder.wav'\n logToFile(str(reminder))\n\n\n# Start of program execution\ninit()\n# test()\nscheduleTimer()\n","sub_path":"MedicineReminder/MedicineReminder.py","file_name":"MedicineReminder.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"647700252","text":"import datetime\nfrom django.contrib import messages\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.mail import EmailMessage\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.template.loader import render_to_string\nfrom django.views.generic import View, CreateView, UpdateView, FormView, ListView, DetailView\nfrom BookMyDoc.settings import EMAIL_HOST_USER\nfrom .forms import PatientProfileForm, UserProfileForm\nfrom django.contrib.auth import get_user_model\nfrom .models import Patient\nfrom doctor.models import Appointment\nfrom doctor.models import DoctorProfile, Qualification, DocTimeSlot\nfrom hospital.models import Hospital\nfrom datetime import datetime, timezone\nfrom django.http import JsonResponse\n\n\n# Create your views here.\n\n# @login_required\ndef index(request):\n return render(request, 'patient/patient_index.html', {})\n\n\ndef write(request):\n return HttpResponse(\"wrongg\")\n\n\nclass UserProfile(LoginRequiredMixin, UpdateView):\n model = get_user_model()\n form_class = UserProfileForm\n template_name = 'patient/user_profile.html'\n success_url = '/patient/index'\n\n\nclass PatientMedicalHistory(LoginRequiredMixin, View):\n template_name = 'patient/patient_medical_history.html'\n form_class = PatientProfileForm\n\n def get(self, request, *args, **kwargs):\n user = request.user\n try:\n patient_data = Patient.objects.get(user_id=user.id)\n except ObjectDoesNotExist:\n patient_data = None\n\n if patient_data is None:\n form = self.form_class()\n return render(request, self.template_name, {'form': form})\n else:\n form = self.form_class(instance=patient_data)\n return render(request, self.template_name, {'form': form})\n\n def post(self, request, *args, **kwargs):\n try:\n patient_data = Patient.objects.get(user_id=request.user.id)\n form = self.form_class(request.POST, instance=patient_data)\n except ObjectDoesNotExist:\n patient_data = None\n form = self.form_class(request.POST)\n\n if form.is_valid():\n if patient_data is None:\n instance = form.save(commit=False)\n instance.user = request.user\n instance.save()\n messages.success(request, 'Patient detail will updated.')\n return redirect('patient:patient_medical_history')\n else:\n messages.success(request, 'Patient detail will updated.')\n form.save()\n return redirect('patient:patient_medical_history')\n else:\n return render(request, self.template_name, {'form': form})\n\n\nclass DisplayHospital(ListView):\n template_name = 'patient/all_hospital.html'\n model = Hospital\n context_object_name = 'all_hospital'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\nclass HospitalDetailView(DetailView):\n template_name = 'patient/hospital_detail.html'\n\n def get(self, request, *args, **kwargs):\n hospital_id = self.kwargs.get('pk')\n hospital_obj = Hospital.objects.get(id=hospital_id)\n doc_lists = DoctorProfile.objects.filter(hospital_id=hospital_id)\n return render(request, self.template_name, {'doc_lists': doc_lists, 'hospital_obj': hospital_obj})\n\n\nclass BookingView(LoginRequiredMixin, View):\n template_name = \"patient/booking_detail.html\"\n\n def get(self, request, *args, **kwargs):\n doc_id = self.kwargs.get('pk')\n data = DoctorProfile.objects.get(id=doc_id)\n return render(self.request, self.template_name, {'data': data})\n\n def post(self, request, *args, **kwargs):\n date = request.POST.get('the_post')\n doc_pro_id = self.kwargs.get('pk')\n convert_date = datetime.strptime(date, \"%m/%d/%Y\").date()\n day_of_week = convert_date.strftime(\"%A\")\n\n current_date = datetime.now().date()\n current_time = datetime.now().time().strftime('%H:%M')\n convert_time = datetime.strptime(current_time, \"%H:%M\").time()\n\n if convert_date == current_date:\n match_booking = Appointment.objects.filter(date=convert_date, doctor_id=doc_pro_id,\n status__in=[Appointment.Booked, Appointment.Ongoing,\n Appointment.Completed])\n\n exclude_data = []\n for i in match_booking:\n exclude_data.append(i.time_slot_id)\n\n doc_time_slot = DocTimeSlot.objects.filter(doc_id=doc_pro_id, from_time__gte=convert_time,\n days=day_of_week).exclude(id__in=exclude_data)\n\n if not doc_time_slot:\n messages.error(request, \"This date in any time slot is not available.\")\n html = render_to_string(request=request, template_name='patient/time_slot.html',\n context={'doc_time_slot': doc_time_slot})\n return JsonResponse(data={'html': html})\n else:\n html = render_to_string(request=request, template_name='patient/time_slot.html',\n context={'doc_time_slot': doc_time_slot})\n return JsonResponse(data={'html': html})\n\n else:\n match_booking = Appointment.objects.filter(date=convert_date, doctor_id=doc_pro_id,\n status__in=[Appointment.Booked, Appointment.Ongoing,\n Appointment.Completed])\n exclude_data = []\n for i in match_booking:\n exclude_data.append(i.time_slot_id)\n\n doc_time_slot = DocTimeSlot.objects.filter(doc_id=doc_pro_id, days=day_of_week).exclude(id__in=exclude_data)\n\n if not doc_time_slot:\n messages.error(request, \"This date in any time slot is not available.\")\n html = render_to_string(request=request, template_name='patient/time_slot.html',\n context={'doc_time_slot': doc_time_slot})\n return JsonResponse(data={'html': html})\n else:\n html = render_to_string(request=request, template_name='patient/time_slot.html',\n context={'doc_time_slot': doc_time_slot})\n return JsonResponse(data={'html': html})\n\n\nclass AppointmentBooking(LoginRequiredMixin, View):\n\n def post(self, request, *args, **kwargs):\n date = request.POST.get('selected_date')\n convert_date = datetime.strptime(date, \"%m/%d/%Y\").date()\n slot_id = request.POST.get('selected_slot')\n slot_data = DocTimeSlot.objects.get(id=slot_id)\n\n appointment = Appointment(\n hospital_id=slot_data.hospital_id,\n patient_id=request.user.patient.id,\n doctor_id=slot_data.doc_id,\n date=convert_date,\n time_slot_id=slot_id,\n created_by=request.user,\n status=Appointment.Booked\n )\n appointment.save()\n messages.success(request, 'appointment is successful booked.')\n return redirect('patient:all_hospital')\n\n\nclass MyAppointmentsView(LoginRequiredMixin, ListView):\n template_name = 'patient/my_appointments.html'\n\n def get(self, request, *args, **kwargs):\n my_appointments = Appointment.objects.filter(created_by=request.user,\n status__in=[Appointment.Booked, Appointment.Cancel, Appointment.Completed]).order_by('-id')\n if my_appointments:\n return render(request, self.template_name, {'my_appointments': my_appointments})\n else:\n messages.error(request, 'you have not booked any appointment.')\n return render(request, self.template_name, {})\n\n\nclass CancelAppointments(LoginRequiredMixin, View):\n def post(self, request, *args, **kwargs):\n appointments_id = kwargs.get('pk')\n patient_app = Appointment.objects.get(id=appointments_id)\n patient_app.status = Appointment.Cancel\n patient_app.canceled_by = request.user\n patient_app.save()\n to_email = patient_app.doctor.user.email\n doctor_name = patient_app.doctor.user.first_name + ' ' + patient_app.doctor.user.last_name\n time_slot = str(patient_app.time_slot.from_time) + ' to ' + str(patient_app.time_slot.to_time)\n cancel_date = str(patient_app.date)\n patient_name = patient_app.patient.user.first_name\n\n html_content = 'hello, Dr ' + doctor_name + '
    cancel_date:' +\\\n cancel_date + '
    time_slot:' + time_slot + '
    patient name:'\\\n + patient_name + ''\n subject = 'Appointment will cancel'\n to_mail = to_email\n msg = EmailMessage(subject, html_content, EMAIL_HOST_USER, [to_mail])\n msg.content_subtype = \"html\"\n msg.send()\n messages.success(request, 'appointment will be cancel.')\n return redirect('patient:my_appointments')\n","sub_path":"BookMyDoc/patient/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"331433283","text":"# write_sin_01\n# \n# Make a wave file (.wav) consisting of a sine wave\n# Adapted from http://www.swharden.com/blog/2011-07-08-create-mono-and-stereo-wave-files-with-python/\n\n# 16 bits per sample\n\n# For 'wave' functions, see:\n# https://docs.python.org/3/library/wave.html\n\n# For 'pack' function see:\n# https://docs.python.org/3/library/struct.html\n\nfrom struct import pack\nfrom math import sin, pi\nimport wave\n\nFs = 8000\n\n# Write a mono wave file\n\nwf = wave.open('sin_01_mono.wav', 'w')\t\t# wf : wave file\nwf.setnchannels(1)\t\t\t# one channel (mono)\nwf.setsampwidth(2)\t\t\t# two bytes per sample (16 bits per sample)\nwf.setframerate(Fs)\t\t\t# samples per second\n\nA = 2**15 - 1.0 \t\t\t# amplitude\nf = 220.0\t\t\t\t\t# frequency in Hz (note A3)\nN = int(0.5*Fs)\t\t\t\t# half-second in samples\n\nfor n in range(0, N):\t # half-second loop \n\tx = A * sin(2*pi*f/Fs*n) \t# signal value (float)\n\tbyte_string = pack('h', int(x)) \n\t# 'h' stands for 'short integer' (16 bits)\n\twf.writeframes(byte_string)\nwf.close()\n","sub_path":"dsp_hw1/demo 02 - wave files/write_sin_01_mono.py","file_name":"write_sin_01_mono.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"46229540","text":"# The purpose of this program is to determine if the 80-20 filtering program\n# correctly partitioned the original data into two files\n\nimport sys\nimport csv\n\n# opens file containing the points removed from the original file\n# then find the greatest point intensity that the file contains\nwith open(sys.argv[1]) as in_file:\n reader = csv.reader(in_file)\n\n greatest_signal = 0.0\n for x in reader:\n if float(x[2]) > greatest_signal:\n greatest_signal = float(x[2])\n\n\n# opens file the points kept from the original file\n# then determines the lowest point intensity that file contains\nwith open(sys.argv[2]) as in_file:\n reader = csv.reader(in_file)\n\n smallest_signal = 10.0 ** 9\n for x in reader:\n if x[2] == \"intensity\":\n pass\n elif float(x[2]) < smallest_signal:\n smallest_signal = float(x[2])\n\n# outputs the results of max and min intensity\nprint(\"Most intense signal from %s: %f\" % (sys.argv[1], greatest_signal))\nprint(\"Least intense signal from %s: %f\" % (sys.argv[2], smallest_signal))\n\n# outputs the result of the test program\nif greatest_signal < smallest_signal:\n print(\"The original CSV was successfully filtered\")\nelse:\n print(\"Error: Original CSV not filted correctly\")","sub_path":"Python/80-20_reduction/removed_point_checker.py","file_name":"removed_point_checker.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"96480890","text":"import numpy as np\n\nimport sys\nsys.path.append(\"/opt/openrobots/lib/python2.7/site-packages\")\n\nimport yarp\n\nimport matplotlib.pylab as mpl\n\nyarp.Network.init()\n\ninput_port = yarp.Port() #BufferedPortImageRgba()\ninput_port.open(\"/image-port\")\n\nyarp.Network.connect(\"/morse/atrv/videocameraL/out\", \"/image-port\")\n\n\n\n\nimageLeft = np.zeros((512,768,4), dtype=np.uint8)\n\nyarp_image = yarp.ImageRgba()\nyarp_image.resize(512, 768)\n\nyarp_image.setExternal(imageLeft, imageLeft.shape[1], imageLeft.shape[0])\n\n\nimport cv2\nimport os\n\n\nclassifier_dirs = os.listdir(\"./classifiers\")\n\ncolorPixHSV = np.array([[[0,255,255]]], dtype=np.uint8)\ncolorIncrement = 180 / len(classifier_dirs) if len(classifier_dirs) else 1\n\nclassifiers = []\nfor dirc in classifier_dirs:\n\tname = dirc\n\tclasf = cv2.CascadeClassifier('./classifiers/'+dirc+'/cascade.xml')\n\n\ttemp = cv2.cvtColor(colorPixHSV, cv2.COLOR_HSV2BGR)\n\tcolor = tuple(map(int,temp[0][0]))\n\tcolorPixHSV[0][0][0] += colorIncrement\n\n\tclassifiers.append((name, color, clasf))\n\n\nwhile True:\n\t\n\t\n\tinput_port.read(yarp_image)\n\n\n\ttest = cv2.cvtColor(np.delete(imageLeft,3,2), cv2.COLOR_RGB2BGR)\n\n\tgray = cv2.cvtColor(test, cv2.COLOR_BGR2GRAY)\n\n\n\tfor (name, color, cascade) in classifiers:\n\t\tstuff = cascade.detectMultiScale(gray, scaleFactor=1.1, \\\n\t\t\t minNeighbors=500 \\\n\t\t\t)\n\n\t\tfor (x,y,w,h) in stuff:\n\t\t\tcv2.rectangle(test, (x,y), (x+w, y+h), color, 2)\n\t\t\tcv2.putText(test, name, (x,y), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)\n\n\n\tcv2.imshow(\"dd\", test)\n\n\tif cv2.waitKey(1) & 0xFF == ord('q'):\n\t\tbreak\n\ninput_port.close()","sub_path":"computer_vision/classifier_samples/test_classifier.py","file_name":"test_classifier.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"251081686","text":"from PIL import Image\nfrom numpy import genfromtxt\n# import gzip, cPickle\nimport gzip\nimport _pickle as cPickle\nimport pickle\nfrom glob import glob\nimport numpy as np\nimport pandas as pd\n\nfrom builtins import range\nfrom six.moves import cPickle as pickle\nimport os\nfrom scipy.misc import imread\nimport platform\n\ndef dir_to_dataset(glob_files, loc_train_labels=\"\"):\n dataset = []\n for file_count, file_name in enumerate( sorted(glob(glob_files),key=len) ):\n image = Image.open(file_name)\n img = Image.open(file_name).convert('LA') #tograyscale\n pixels = [f[0] for f in list(img.getdata())]\n dataset.append(pixels)\n\n if len(loc_train_labels) > 0:\n df = pd.read_csv(loc_train_labels)\n print()\n return np.array(dataset), np.array(df[\"emotion\"])\n else:\n return np.array(dataset)\n\n\nnumber_train = 28709\nnumber_test = 3589\nNUMBER_PIC = number_train + number_test\n\ndef load_pickle(f):\n version = platform.python_version_tuple()\n if version[0] == '2':\n return pickle.load(f)\n elif version[0] == '3':\n return pickle.load(f, encoding='latin1')\n raise ValueError(\"invalid python version: {}\".format(version))\n\ndef load_FER2013_batch(filename):\n \"\"\" load single batch of FER2013 \"\"\"\n with open(filename, 'rb') as f:\n datadict = load_pickle(f)\n X = datadict['data']\n Y = datadict['labels']\n\n if(X.shape[0] == number_train):\n number_pic = X.shape[0]\n elif (X.shape[0] == number_test):\n number_pic = X.shape[0]\n X = X.reshape(number_pic,1,48,48).transpose(0,2,3,1).astype(\"float\")\n Y = np.array(Y)\n return X, Y\ndef load_FER2013(ROOT):\n \"\"\" load all of FER2013 \"\"\"\n\n Xtr, Ytr = load_FER2013_batch(os.path.join(ROOT, 'train_batch'))\n\n Xte, Yte = load_FER2013_batch(os.path.join(ROOT, 'test_batch'))\n return Xtr, Ytr, Xte, Yte\n\ndef get_FER2013_data(num_training=49000, num_validation=1000, num_test=1000,\n subtract_mean=True):\n \"\"\"\n Load the FER2013 dataset from disk and perform preprocessing to prepare\n it for classifiers. These are the same steps as we used for the SVM, but\n condensed to a single function.\n \"\"\"\n # Load the raw FER2013 data\n\n FER2013_dir = '/homes/nj2217/ML/neuralnets/src/fer2013-batches'\n\n\n X_train, y_train, X_test, y_test = load_FER2013(FER2013_dir)\n\n # Subsample the data\n mask = list(range(num_training, num_training + num_validation))\n X_val = X_train[mask]\n y_val = y_train[mask]\n mask = list(range(num_training))\n X_train = X_train[mask]\n y_train = y_train[mask]\n mask = list(range(num_test))\n X_test = X_test[mask]\n y_test = y_test[mask]\n\n # Normalize the data: subtract the mean image\n if subtract_mean:\n mean_image = np.mean(X_train, axis=0)\n X_train -= mean_image\n X_val -= mean_image\n X_test -= mean_image\n\n # Transpose so that channels come first\n X_train = X_train.transpose(0, 3, 1, 2).copy()\n X_val = X_val.transpose(0, 3, 1, 2).copy()\n X_test = X_test.transpose(0, 3, 1, 2).copy()\n\n # Package data into a dictionary\n return {\n 'X_train': X_train, 'y_train': y_train,\n 'X_val': X_val, 'y_val': y_val,\n 'X_test': X_test, 'y_test': y_test,\n }\n","sub_path":"CW2_NEURAL_NETWORK/src/data_utils_fer2013.py","file_name":"data_utils_fer2013.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"618055821","text":"from django.urls import path\nfrom .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, AddCategoryView, CategoryView, CategoryListView, RateView\nfrom . import views\n\nurlpatterns = [\n path('', HomeView.as_view(), name = 'home'),\n path('article/', ArticleDetailView.as_view(), name = 'article-detail'),\n path('add_post/', AddPostView.as_view(), name = 'add_post'),\n path('search_things', views.SearchPosts, name = 'search_things'),\n path('article/edit/', UpdatePostView.as_view(), name = 'update_post'),\n path('article//delete/', DeletePostView.as_view(), name = 'delete_post'),\n path('add_category/', AddCategoryView.as_view(), name = 'add_category'),\n path('category/', CategoryView, name = 'category'),\n path('category-list', CategoryListView, name = 'category-list'),\n path('article//rate_post/', RateView, name = 'rate_post'),\n]\n\n","sub_path":"mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"78082575","text":"from flask import Flask, Response\r\nimport json\r\nimport datetime\r\n\r\nimport Services.measurements_service as measurements_service\r\nfrom Models.measurement import Measurement\r\nfrom DTO.measurement_list_dto import Measurement_list_dto\r\n\r\napp = Flask(__name__)\r\napp.config['JSON_ADD_STATUS'] = True\r\n\r\n\r\n@app.route(\"/measurement//\")\r\ndef get_measurements(timestamp_from, timestamp_to):\r\n try:\r\n datetime_from = datetime.datetime.fromtimestamp(timestamp_from)\r\n datetime_to = datetime.datetime.fromtimestamp(timestamp_to)\r\n except:\r\n content = {\r\n \"ErrorMessage\" : \"Wrong input data\"\r\n }\r\n content_as_json = json.dumps(content)\r\n resp = Response(content_as_json, status=400, mimetype='application/json')\r\n return resp\r\n\r\n\r\n measurements = measurements_service.get_measurements(datetime_from, datetime_to)\r\n measurements_dto = []\r\n for measurement in measurements:\r\n measurements_dto.append(measurement.to_dto_json())\r\n result = Measurement_list_dto(measurements_dto)\r\n result_json = result.to_json()\r\n return result_json\r\n \r\n\r\n@app.route(\"/measurement\")\r\ndef get_latest_measurement():\r\n measurement = measurements_service.get_latest_measurement()\r\n return measurement.to_dto_json()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(use_reloader=False)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"476127144","text":"import numpy as np\n\ndef fprop(input_batch, word_embedding_weights, embed_to_hid_weights, hid_to_output_weights, hid_bias, output_bias):\n '''\n This method forward propagates through a neural network.\n Inputs:\n input_batch: The input data as a matrix of size numwords X batchsize where, numwords is the number of words, batchsize is the number of data points.\n So, if input_batch(i, j) = k then the ith word in data point j is word index k of the vocabulary.\n word_embedding_weights: Word embedding as a matrix \n of size vocab_size X numhid1, where vocab_size is the size of the vocabulary, numhid1 is the dimensionality of the embedding space.\n embed_to_hid_weights: Weights between the word embedding layer and hidden layer as a matrix \n of size numhid1*numwords X numhid2, numhid2 is the number of hidden units.\n hid_to_output_weights: Weights between the hidden layer and output softmax unit as a matrix \n of size numhid2 X vocab_size\n hid_bias: Bias of the hidden layer as a matrix of size numhid2 X 1.\n output_bias: Bias of the output layer as a matrix of size vocab_size X 1.\n Outputs:\n embedding_layer_state: State of units in the embedding layer as a matrix of size numhid1*numwords X batchsize\n hidden_layer_state: State of units in the hidden layer as a matrix of size numhid2 X batchsize\n output_layer_state: State of units in the output layer as a matrix of size vocab_size X batchsize\n '''\n \n # Note: no weights update within one mini batch.\n numwords, batchsize = input_batch.shape\n vocab_size, numhid1 = word_embedding_weights.shape\n numhid2 = embed_to_hid_weights.shape[1]\n \n ## COMPUTE STATE OF WORD EMBEDDING LAYER.\n # Look up the inputs word indices in the word_embedding_weights matrix.\n embedding_layer_state = np.reshape(np.array([word_embedding_weights[word_idx - 1, :].T for word_idx in np.reshape(input_batch, (1, -1))]), (numhid1 * numwords, -1))\n \n # JC COMMENTS: NO activation at embedding node. ? Just a linear transformation?\n \n ## COMPUTE STATE OF HIDDEN LAYER.\n # Compute inputs to hidden units.\n inputs_to_hidden_units = embed_to_hid_weights.T.dot(embedding_layer_state) + np.repeat(hid_bias, batchsize, axis = 1)\n \n # Apply logistic activation function.\n #hidden_layer_state = zeros(numhid2, batchsize);\n hidden_layer_state = np.ones((numhid2, batchsize)) / (np.ones((numhid2, batchsize)) + np.exp(-inputs_to_hidden_units))\n \n ## COMPUTE STATE OF OUTPUT LAYER.\n # Compute inputs to softmax.\n #inputs_to_softmax = zeros(vocab_size, batchsize);\n inputs_to_softmax = hid_to_output_weights.T.dot(hidden_layer_state) + np.repeat(output_bias, batchsize, axis = 1)\n \n # Subtract maximum. \n # Remember that adding or subtracting the same constant from each input to a\n # softmax unit does not affect the outputs. Here we are subtracting maximum to\n # make all inputs <= 0. This prevents overflows when computing their exponents.\n inputs_to_softmax = inputs_to_softmax - np.repeat(inputs_to_softmax.max(axis = 0).reshape(1,-1), vocab_size, axis = 0)\n \n # Compute exp.\n output_layer_state = np.exp(inputs_to_softmax)\n \n # Normalize to get probability distribution.\n # This is softmax.\n output_layer_state = output_layer_state / np.repeat(np.sum(output_layer_state, axis = 0).reshape(1,-1), vocab_size, axis = 0)\n \n states = {}\n states['embedding_layer_state'] = embedding_layer_state\n states['hidden_layer_state'] = hidden_layer_state\n states['output_layer_state'] = output_layer_state\n return states\n","sub_path":"NeuralNetsByHinton/Assignment2inPython/fprop.py","file_name":"fprop.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"374245770","text":"# Homework Day 1 - extras\n# BorisRubin\n\n# http://codegists.com/snippet/python/hw_day1_extra1py_borisrubin_python\n# Task 1 Напишите программу, которая считает площадь прямоугольника, спрашивая у пользователя длину двух сторон \n \nside_a = input('Введите длину стороны А прямоугольника: ')\nside_b = input('Введите длину стороны B прямоугольника: ')\n \nprint('Площадь прямоугольника: ', int(side_a)*int(side_b))\n\n# http://codegists.com/snippet/python/hw_day1_extra2py_borisrubin_python\n# Task 2 Напишите программу, которая спрашивает у пользователя два числа и знак: \"+\" или \"-\". В зависимости от знака выводит их сумму или разницу \n \ndef all_numbers(*numbers):\n is_numbers = True\n for num in numbers:\n if isinstance(num, float):\n is_numbers = is_numbers and True\n else:\n is_numbers = is_numbers and False\n \n return is_numbers\n \n \ndef operation(x, y, sign):\n if sign == '+':\n return x + y\n elif sign == '-':\n return x - y\n \nnum1 = float(input('Введите 1ое число : '))\nnum2 = float(input('Введите 2ое число : '))\n \nsign = ''\nwhile (sign != '+') and (sign != '-'):\n sign = input('Введите знак \"+\" или \"-\" : ')\n \nif all_numbers(num1, num2):\n print('Результат {} {} {} = {}'.format(num1, sign, num2, operation(num1, num2, sign)))\n\t\n# http://codegists.com/snippet/python/hw_day1_extra3-4py_borisrubin_python\n# Task 3 Напишите программу, которая находит все простые числа между 0 и пользовательским числом\n\n# введем число, заранее знаем, что оно должно быть типа int\nprint('Задание 1: \\nРасчитываем все простые числа от 0 до выбранного Вами числа\\n')\nlimit = int(input('Введите число: '))\n \nnumbers = list()\n \n# обойдем все числа от 2 до указанного числа + 1\nfor n in range(2, limit+1):\n # обойдем все числа от 2 до текущего числа в обходе\n for m in range(2, n):\n # если делится без остатка то число НЕ простое - прерываем внутренний цикл для перехода к след. числу\n if n % m == 0:\n break\n else:\n # в противном случае оно простое и добавляем его в список\n numbers.append(n)\n \nprint(numbers)\n \n# http://codegists.com/snippet/python/hw_day1_extra3-4py_borisrubin_python\n# Task 4 Напишите программу, которая выводит все кратные 5 числа между двумя пользовательскими числами\n \n# вводим два числа типа int так как должны быть кратны 5\nprint('\\n\\nЗадание 2: \\nНайдем все числа в заданном 2 числами диапазоне кратные 5\\n')\nnum1 = int(input('Введите 1ое число: '))\nnum2 = int(input('Введите 2ое число: '))\n \nnumbers = list(x for x in range(num1, num2) if x % 5 == 0)\nprint(numbers)","sub_path":"WEB_COURSE/Home_work_class_1/extra task #1.py","file_name":"extra task #1.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"301179421","text":"from collections import deque\r\n\r\n#N 노드의 개수, M 간선의 개수 \r\nN, M = map(int,input().split())\r\n\r\n\r\ngraph_light = [ [] for _ in range (N+1) ]\r\ngraph_heavy = [ [] for _ in range (N+1) ]\r\n\r\nfor i in range(M):\r\n u, v = map(int,input().split())\r\n graph_light[v].append(u)\r\n graph_heavy[u].append(v)\r\n\r\ndef bfs(x,graph):\r\n visited = [False]*(N+1)\r\n visited[x] = True\r\n que = deque()\r\n que.append(x)\r\n cnt = 0\r\n while que:\r\n cv = que.popleft()\r\n\r\n for adj in graph[cv]:\r\n if not visited[adj]:\r\n cnt+=1\r\n visited[adj] = True\r\n que.append(adj)\r\n return cnt \r\n\r\ncnt = 0\r\nfor i in range(1,N+1):\r\n heavy = bfs(i,graph_heavy)\r\n light = bfs(i,graph_light)\r\n if light > (N-1)//2 or heavy >(N-1)//2:\r\n cnt+=1\r\n\r\nprint(cnt)\r\n\r\n","sub_path":"백준/Gold/2617. 구슬 찾기/구슬 찾기.py","file_name":"구슬 찾기.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"162023382","text":"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.utils.data\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\nfrom torchvision.utils import save_image\nfrom models import *\nfrom data_loader import *\n\nimport numpy as np\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nparser = argparse.ArgumentParser(description='VAE MNIST Example')\nparser.add_argument('--batch-size', type=int, default=1, metavar='N',\n help='input batch size for training (default: 128)')\nparser.add_argument('--epochs', type=int, default=10, metavar='N',\n help='number of epochs to train (default: 10)')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='enables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\ntorch.manual_seed(args.seed)\n\ndevice = torch.device(\"cuda\" if args.cuda else \"cpu\")\n\nkwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}\n\ntrain_loader = DataLoader(Audio('train'),batch_size=args.batch_size, shuffle=True, num_workers=4)\n#test_loader = DataLoader(Audio('test'),batch_size=args.batch_size, shuffle=False, num_workers=4)\n\n\nmodel = Generator().to(device)\noptimizer = optim.Adam(model.parameters(), lr=1e-4)\n\nprint('# parameters:', sum(param.numel() for param in model.parameters()) /1000000.0 * 4)\n\n\nloss_function = nn.L1Loss()\n\n\ndef savefig(path, mel, mel1, mel2):\n plt.figure(figsize=(10, 5))\n plt.plot(mel)\n plt.plot(mel1)\n plt.plot(mel2)\n plt.savefig(path, format=\"png\")\n plt.close()\n\ndef train(epoch):\n model.train()\n train_loss = 0\n for batch_idx, (mel, cqt) in enumerate(train_loader):\n x = mel.to(device)\n y = cqt.to(device)\n\n optimizer.zero_grad()\n \n rx = model(x)\n loss = loss_function(rx, y)\n loss.backward()\n train_loss += loss.item()\n optimizer.step()\n\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(mel), len(train_loader),\n 100. * batch_idx / len(train_loader),\n loss.item() / len(mel), \n ))\n\n# if epoch % 20 == 0:\n# torch.save(model.state_dict(),\"/data/tree/voice/csp_wav_%03d.pt\" % epoch)\n# \n#\n print('====> Epoch: {} Average loss: {:.4f}'.format(\n epoch, train_loss /len(train_loader)))\n\n\n#def test(epoch):\n# model.eval()\n# test_loss = 0\n# with torch.no_grad():\n# for i, (data, f0, c) in enumerate(test_loader):\n# x = data.to(device)\n# c = c.to(device)\n# f0 = f0.to(device)\n#\n# c1 = torch.zeros_like(c)\n# c2 = torch.zeros_like(c)\n# c1[:,0] = 1\n# c2[:,1] = 1\n#\n# t = torch.arange(100)\n# t = t.type(torch.FloatTensor)\n# t = t.to(device)\n# #z = torch.cat((f0, c), dim=1)\n#\n# rx = model(x, c, t)\n# loss = loss_function(rx, x)\n# test_loss += loss.item()\n#\n#\n# if i == 0:\n# rx1 = model(x, c1, t)\n# rx2 = model(x, c2, t)\n# img = torch.cat((x, rx, rx1, rx2), dim=1)\n# img = img.view(-1, 1, 24 * 4, 200)\n# save_image(img.cpu(),\n# 'images/csp_test_%03d.png' % epoch, nrow=4)\n# \n# test_loss /= len(test_loader.dataset)\n# print('====> Test set loss: {:.4f} '.format(test_loss))\n#\nif __name__ == \"__main__\":\n for epoch in range(1, args.epochs + 1):\n train(epoch)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"104482047","text":"import math\n\n# Quadratic Formula Solver\n\nprint(\"This program will solve a quadratic equation in the form ax^2 + bx +c = 0\")\n\nuserSatisfied = False\n\nwhile not userSatisfied:\n a = int(input(\"a = \"))\n b = int(input(\"b = \"))\n c = int(input(\"c = \"))\n\n isUserSatisfied = input(str(\"Therefore, your equation is: \" + str(a)+\"x^2\" + \" + \" + str(b)+\"x\" + \" + \" + str(c) + \" = 0 (y/n) \")).lower()\n if isUserSatisfied != \"n\":\n userSatisfied = True\n else:\n print(\"Very well, please input the values again.\")\ntry:\n solution1 = ((0-b)+math.sqrt((b*b)-(4*a*c)))/(2*a)\n solution2 = ((0-b)-math.sqrt((b*b)-(4*a*c)))/(2*a)\n flagSuccess = True\nexcept ValueError:\n flagSuccess = False\n\nif flagSuccess:\n if solution1 == solution2:\n print(\"There is one solution:\")\n print(solution1)\n else:\n print(\"These are the solutions:\")\n print(solution1, \",\", solution2)\n\nelse:\n print(\"There was an error during the calculation; the equation has complex roots.\")\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"444021464","text":"import xml.etree.ElementTree as ET\nfrom sys import argv\nfrom sys import stdin\nimport random\n\n\ndoc = ET.parse(argv[1])\nrootDict = doc.find('dict')\ntracksDict = rootDict.find('dict')\ntracks = tracksDict.findall('dict')\n\nclass Song(object):\n def __init__(self,name,artist,playCount,path):\n self.name = name\n self.artist = artist\n if playCount == \"\":\n self.playCount = 0\n else:\n self.playCount = playCount\n self.path = path\n\nsongs = {}\nfor track in tracks:\n name = \"\"\n playCount = \"\"\n nameBool = 1\n artistBool = 1\n playCountBool = 1\n pathBool = 1\n for child in track:\n if nameBool == 0:\n name = child.text\n nameBool = 1\n elif artistBool == 0:\n artist = child.text\n artistBool = 1\n elif playCountBool == 0:\n playCount = child.text\n playCountBool = 1\n elif pathBool == 0:\n path = child.text\n pathBool = 1\n elif child.text == \"Name\" and child.tag == \"key\":\n nameBool = 0\n elif child.text == \"Artist\" and child.tag == \"key\":\n artistBool = 0\n elif child.text == \"Play Count\" and child.tag == \"key\":\n playCountBool = 0\n elif child.text == \"Location\" and child.tag == \"key\":\n pathBool = 0\n songs[name] = Song(name,artist,playCount,path)\n\ni = 0\nweightedSongs = {}\nfor song in songs:\n count = int(songs[song].playCount)\n if count != 0:\n j = 0\n while j < count:\n weightedSongs[i] = songs[song]\n i = i + 1\n j = j + 1\n\nrand = random.randint(0,i-1)\nprint(weightedSongs[rand].path)\n","sub_path":"xmlWeightedShuffle.py","file_name":"xmlWeightedShuffle.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"542067082","text":"import sys\nsys.path.append(\".\")\nimport pickle\nimport glob\nimport argparse\nimport pandas as pd\nimport os\nfrom utils.utils import *\nimport pdb\nfrom matplotlib import gridspec\nfrom matplotlib import pyplot as plt\nfrom db_utils.utils import *\nfrom db_utils.query_storage import *\nfrom parsing_utils import *\nfrom cardinality_estimation.cost_dataset import CostDataset\nfrom torch.utils import data\nfrom utils.net import *\nfrom sklearn.model_selection import train_test_split\n\nfrom metric_learn import LMNN, NCA\n\ndef read_flags():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--training_data_file\", type=str, required=False,\n default=\"./join_loss_data/1a.pkl\")\n parser.add_argument(\"--query_dir\", type=str, required=False,\n default=\"./our_dataset/queries\")\n parser.add_argument(\"--feat_type\", type=str, required=False,\n default=\"fcnn\")\n parser.add_argument(\"--tfboard_dir\", type=str, required=False,\n default=None)\n parser.add_argument(\"--lr\", type=float, required=False,\n default=0.0001)\n parser.add_argument(\"--test_size\", type=float, required=False,\n default=0.2)\n parser.add_argument(\"--hidden_layer_multiple\", type=float, required=False,\n default=2)\n parser.add_argument(\"--num_hidden_layers\", type=int, required=False,\n default=1)\n parser.add_argument(\"--add_true\", type=int, required=False,\n default=0)\n parser.add_argument(\"--mb_size\", type=int, required=False,\n default=32)\n parser.add_argument(\"--max_epochs\", type=int, required=False,\n default=10)\n parser.add_argument(\"--input_feat_type\", type=int, required=False,\n default=1)\n parser.add_argument(\"--input_norm_type\", type=int, required=False,\n default=1)\n parser.add_argument(\"--test_while_training\", type=int, required=False,\n default=0)\n parser.add_argument(\"--learn_type\", type=str, required=False,\n default=\"metric\")\n\n return parser.parse_args()\n\ndef periodic_eval(net, loader, loss_func):\n\n losses = []\n for xbatch,ybatch in loader:\n preds = net(xbatch).squeeze(1)\n loss = loss_func(preds, ybatch).cpu().detach().numpy()\n losses.append(loss)\n return sum(losses) / len(losses)\n\ndef main():\n mapping = qkey_map(args.query_dir)\n assert len(mapping) != 0\n training_data = load_object(args.training_data_file)\n print(len(training_data[\"jloss\"]), len(np.unique(training_data[\"jloss\"])))\n print(\"num queries: \", len(set(training_data[\"key\"])))\n tr_keys, test_keys, tr_ests, test_ests, tr_costs, test_costs, tr_ratios, \\\n test_ratios = \\\n train_test_split(training_data[\"key\"], training_data[\"est\"],\n training_data[\"jloss\"], training_data[\"jratio\"], random_state=1234,\n test_size=args.test_size)\n # split it\n print(len(tr_keys), len(test_keys))\n train_dataset = CostDataset(mapping, tr_keys, tr_ests, tr_costs, tr_ratios,\n args.feat_type, input_feat_type = args.input_feat_type,\n add_true=args.add_true)\n test_dataset = CostDataset(mapping, test_keys, test_ests, test_costs,\n test_ratios,\n args.feat_type, input_feat_type = args.input_feat_type,\n add_true=args.add_true)\n train_loader = data.DataLoader(train_dataset,\n batch_size=args.mb_size, shuffle=True, num_workers=0)\n test_loader = data.DataLoader(test_dataset,\n batch_size=10000, shuffle=False, num_workers=0)\n print(\"num train: {}, num test: {}\".format(len(train_dataset),\n len(test_dataset)))\n\n # TODO: make this the test set\n eval_loader = data.DataLoader(train_dataset,\n batch_size=10000, shuffle=False, num_workers=0)\n\n inp_len = len(train_dataset[0][0])\n print(\"inp len: \", inp_len)\n\n net = CostModelNet(inp_len, args.hidden_layer_multiple, 1,\n num_hidden_layers=args.num_hidden_layers)\n loss_func = torch.nn.MSELoss()\n\n if args.tfboard_dir:\n make_dir(tfboard_dir)\n tfboard = TensorboardSummaries(tfboard_dir + \"/tf_cost_logs/\" +\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime()))\n tfboard.init()\n\n optimizer = torch.optim.Adam(net.parameters(), lr=args.lr)\n\n for epoch in range(0, args.max_epochs):\n\n if args.test_while_training or \\\n epoch == args.max_epochs-1:\n print(\"epoch: {}, train loss: {}, test_loss: {}\".format(epoch, periodic_eval(net,\n eval_loader, loss_func), periodic_eval(net, test_loader,\n loss_func)))\n else:\n print(\"epoch: {}, N: {} train loss: {}\".format(epoch,\n len(train_dataset), periodic_eval(net,\n eval_loader, loss_func)))\n\n # train loop\n for _, (xbatch, ybatch) in enumerate(train_loader):\n pred = net(xbatch).squeeze(1)\n assert pred.shape == ybatch.shape\n loss = loss_func(pred, ybatch)\n optimizer.zero_grad()\n loss.backward()\n # if args.clip_gradient is not None:\n # clip_grad_norm_(self.net.parameters(), args.clip_gradient)\n optimizer.step()\n\n torch.save(net, \"./cm_fcnn.pt\")\n\nif __name__ == \"__main__\":\n args = read_flags()\n main()\n","sub_path":"scripts/train_cost_model.py","file_name":"train_cost_model.py","file_ext":"py","file_size_in_byte":5379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"317308938","text":"import numpy as np\nfrom torch.utils.data import Dataset\n\n\nclass dataset(Dataset):\n def __init__(self, image, mask, ignore=None, sky=None, aug_sky=[0, 0], part=None, f_val=0.1, seed=1):\n \"\"\" custom pytorch dataset class to load deepCR-mask training data\n :param image: image with CR\n :param mask: CR mask\n :param ignore: loss mask, e.g., bad pixel, saturation, etc.\n :param sky: (np.ndarray) [N,] sky background level\n :param aug_sky: [float, float]. If sky is provided, use random sky background in the range\n [aug_sky[0] * sky, aug_sky[1] * sky]. This serves as a regularizers to allow the trained model to adapt to a\n wider range of sky background or equivalently exposure time. Remedy the fact that exposure time in the\n training set is discrete and limited.\n :param part: either 'train' or 'val'. split by 0.8, 0.2\n :param f_val: percentage of dataset reserved as validation set.\n :param seed: fix numpy random seed to seed, for reproducibility.\n \"\"\"\n\n np.random.seed(seed)\n len = image.shape[0]\n assert f_val < 1 and f_val > 0\n f_train = 1 - f_val\n if sky is None:\n sky = np.zeros_like(image)\n if ignore is None:\n ignore = np.zeros_like(image)\n\n if part == 'train':\n slice = np.s_[:int(len * f_train)]\n elif part == 'val':\n slice = np.s_[int(len * f_train):]\n else:\n slice = np.s_[0:]\n\n self.image = image[slice]\n self.mask = mask[slice]\n self.ignore = ignore[slice]\n self.sky = sky[slice]\n\n self.aug_sky = aug_sky\n\n def __len__(self):\n return self.image.shape[0]\n\n def __getitem__(self, i):\n a = (self.aug_sky[0] + np.random.rand() * (self.aug_sky[1] - self.aug_sky[0])) * self.sky[i]\n return self.image[i] + a, self.mask[i], self.ignore[i]\n","sub_path":"deepCR/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"422749402","text":"import torch\nfrom torch.nn import MSELoss\nfrom torch.nn import Sequential\nfrom torch.nn import ReLU\n\n# in_channels,\n# out_channels,\n# kernel_size: int | (int, int),\n# stride: int | (int, int) = 1,\n# padding: int | (int, int) = 0\nfrom torch.nn import Conv2d\n\n# kernel_size: int | (int, int),\n# stride: int | (int, int) = 1\n# padding: int | (int, int) = 0\nfrom torch.nn import MaxPool2d\n\n# in_features: int,\n# out_features: int,\n# bias: bool = True\nfrom torch.nn import Linear\n\n# start_dim: int = 1,\n# end_dim: int = -1\nfrom torch.nn import Flatten\n\nmodel = Sequential(\n Conv2d(1, 6, 5),\n ReLU(),\n MaxPool2d(2),\n Conv2d(6, 16, 5),\n ReLU(),\n MaxPool2d(2),\n Flatten(),\n Linear(16 * 5 * 5, 120),\n ReLU(),\n Linear(120, 84),\n ReLU(),\n Linear(84, 10)\n)\n\n\ndef demo_backward():\n # 生成1张单通道32×32像素的图片\n data_x = torch.randn(1, 1, 32, 32)\n # data_y = torch.randn(10).view(1, -1)\n\n # 前向传播\n pred_y = model(data_x)\n\n # 反向传播\n pred_y.backward(torch.randn(1, 10))\n print(\"RAND\", \"channel[0].weight.grad[0][0][0]:\", model[0].weight.grad[0][0][0])\n\n # 梯度置为0\n model.zero_grad()\n print(\"ZERO\", \"channel[0].weight.grad[0][0][0]:\", model[0].weight.grad[0][0][0])\n\n\ndef demo_loss_backward():\n data_x = torch.randn(1, 1, 32, 32)\n data_y = torch.randn(10).view(1, -1)\n pred_y = model(data_x)\n\n # 损失函数\n loss_fn = MSELoss()\n loss_val = loss_fn(data_y, pred_y)\n print(\"LOSS\", loss_val)\n loss_val.backward()\n print(\"LOSS\", \"channel[0].weight.grad[0][0][0]:\", model[0].weight.grad[0][0][0])\n\n\nif __name__ == '__main__':\n demo_backward()\n demo_loss_backward()\n","sub_path":"notes/pytorch/src/demo_backward.py","file_name":"demo_backward.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"579737044","text":"#!/usr/bin/env python3\nfrom __future__ import print_function\n\nimport rospy\nimport cv2\nfrom ki_robotics.srv import AIService, AIServiceResponse\n\ndef handel_prediction(req):\n print(\"Returning the class of the image ....\")\n return AIServiceResponse(1)\n\n\ndef main():\n rospy.init_node(\"ai_servise\",anonymous=True)\n s = rospy.Service(\"predict_image\",AIService,handel_prediction)\n print(\"Prediction Service is Ready\")\n rospy.spin()\n\n\nif __name__==\"__main__\":\n try:\n main()\n except rospy.ROSInterruptException as e:\n print(e)","sub_path":"catkin_ws/build/ki_robotics/catkin_generated/installspace/AI.py","file_name":"AI.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"61670747","text":"# Copyright 2016: Mirantis Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport os.path\n\nimport mock\nimport testtools\n\nimport health.main\n\n\nclass APITestCase(testtools.TestCase):\n\n def setUp(self):\n super(APITestCase, self).setUp()\n self.addCleanup(mock.patch.stopall)\n self.client = health.main.app.test_client()\n self.app = health.main.app\n\n config_path = os.path.join(\n os.path.dirname(__file__), 'etc/config.json')\n config = json.load(open(config_path))\n self.app.config.update(config)\n\n def test_not_found(self):\n resp = self.client.get('/404')\n self.assertEqual({\"error\": \"Not Found\"},\n json.loads(resp.data.decode()))\n self.assertEqual(404, resp.status_code)\n","sub_path":"tests/unit/api/v1/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"621084602","text":"import os\nimport pytest\nimport time\n\nfrom selenium.webdriver.common.by import By\nfrom selenium import webdriver\n\n\n@pytest.fixture\ndef driver(request):\n driver = webdriver.Chrome()\n driver.implicitly_wait(10)\n def fin(): driver.quit()\n request.addfinalizer(fin)\n return driver\n\n\ndef test_upload_radical(driver):\n driver.get('https://konflic.github.io/examples/editor/index.html')\n uploader = driver.find_element(By.CSS_SELECTOR, \"#file-uploader\")\n filename = os.path.join(os.path.dirname(__file__), 'selenium.png')\n uploader.send_keys(filename)\n time.sleep(10)\n","sub_path":"3_uploads/test_upload.py","file_name":"test_upload.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"358096386","text":"# Import statements\n# Declare Imports\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nimport operator\nfrom textwrap import wrap\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.metrics import make_scorer, r2_score\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.ensemble import RandomForestRegressor\n\n# Set a variable for current notebook's path for various loading/saving mechanisms\nnb_path = os.getcwd()\n\n'''Data import functions'''\n\ndef load_census_csv(table_list, statistical_area_code='SA3'):\n '''\n Navigates the file structure to import the relevant files for specified data tables at a defined statistical area level\n \n INPUTS\n table_list: LIST of STRING objects - the ABS Census Datapack table to draw information from (G01-G59)\n statistical_area_code: STRING - the ABS statistical area level of detail required (SA1-SA3)\n \n OUTPUTS\n A pandas dataframe\n '''\n statistical_area_code = statistical_area_code.upper()\n \n df_csv_load = pd.DataFrame()\n for index, table in enumerate(table_list):\n \n if index==0:\n df_csv_load = pd.read_csv('{}\\\\Data\\\\{}\\\\AUST\\\\2016Census_{}_AUS_{}.csv'.format(nb_path,\n statistical_area_code,\n table,\n statistical_area_code\n ),\n engine='python')\n else:\n temp_df = pd.read_csv('{}\\\\Data\\\\{}\\\\AUST\\\\2016Census_{}_AUS_{}.csv'.format(nb_path,\n statistical_area_code,\n table,\n statistical_area_code\n ),\n engine='python')\n merge_col = df_csv_load.columns[0]\n df_csv_load = pd.merge(df_csv_load, temp_df, on=merge_col)\n \n return df_csv_load\n\n\n\ndef refine_measure_name(table_namer, string_item, category_item, category_list):\n '''Simple function for generating measure names based on custom metadata information on ABS measures'''\n position_list = []\n for i, j in enumerate(category_item.split(\"|\")):\n if j in category_list:\n position_list.append(i)\n return table_namer + '|' + '_'.join([string_item.split(\"|\")[i] for i in position_list])\n\n\ndef load_table_refined(table_ref, category_list, statistical_area_code='SA3', drop_zero_area=True):\n '''\n Function for loading ABS census data tables, and refining/aggregating by a set of defined categories\n (e.g. age, sex, occupation, English proficiency, etc.) where available.\n \n INPUTS\n table_ref: STRING - the ABS Census Datapack table to draw information from (G01-G59)\n category_list: LIST of STRING objects - Cetegorical information to slice/aggregate information from (e.g. Age)\n statistical_area_code: STRING - the ABS statistical area level of detail required (SA1-SA3)\n drop_zero_area: BOOLEAN - an option to remove \"non-geographical\" area data points such as \"no fixed address\" or \"migratory\"\n '''\n df_meta = pd.read_csv('{}\\\\Data\\\\Metadata\\\\Metadata_2016_refined.csv'.format(os.getcwd()))\n index_reference = 'Area_index'\n \n # slice meta based on table\n meta_df_select = df_meta[df_meta['Profile table'].str.contains(table_ref)].copy()\n \n # for category in filter_cats, slice based on category >0\n for cat in category_list:\n # First, check if there *are* any instances of the given category\n try:\n if meta_df_select[cat].sum() > 0:\n # If so, apply the filter\n meta_df_select = meta_df_select[meta_df_select[cat]>0]\n else:\n pass # If not, don't apply (otherwise you will end up with no selections)\n except:\n pass\n \n # select rows with lowest value in \"Number of Classes Excl Total\" field\n min_fields = meta_df_select['Number of Classes Excl Total'].min()\n meta_df_select = meta_df_select[meta_df_select['Number of Classes Excl Total'] == min_fields]\n \n # Select the table file(s) to import\n import_table_list = meta_df_select['DataPack file'].unique()\n \n # Import the SA data tables\n df_data = load_census_csv(import_table_list, statistical_area_code.upper())\n \n # Select only columns included in the meta-sliced table above\n df_data.set_index(df_data.columns[0], inplace=True)\n refined_columns = meta_df_select.Short.tolist()\n df_data = df_data[refined_columns]\n \n # aggregate data by:\n # transposing the dataframe\n df_data_t = df_data.T.reset_index()\n df_data_t.rename(columns={ df_data_t.columns[0]: 'Short' }, inplace = True)\n # merging with the refined meta_df to give table name, \"Measures\" and \"Categories\" fields\n meta_merge_ref = meta_df_select[['Short','Table name','Measures','Categories']]\n df_data_t = df_data_t.merge(meta_merge_ref, on='Short')\n \n # from the \"Categories\" field, split an individual entry by the \"|\" character\n # to give the index of the measure you are interested in grouping by.\n # Create a new column based on splitting the \"Measure\" field and selecting the value of this index/indices.\n # Merge above with the table name to form \"[Table_Name]|[groupby_value]\" to have a good naming convention\n # e.g. \"Method_of_Travel_to_Work_by_Sex|Three_methods_Females\".\n df_data_t[index_reference] = df_data_t.apply(lambda x: refine_measure_name(x['Table name'], \n x['Measures'], \n x['Categories'], \n category_list), axis=1)\n \n # then groupby this new column \n # then transpose again and either create the base data_df for future merges or merge with the already existing data_df\n df_data_t = df_data_t.drop(['Short','Table name','Measures','Categories'], axis=1)\n df_data_t = df_data_t.groupby([index_reference]).sum()\n df_data_t = df_data_t.T\n \n if drop_zero_area:\n df_zero_area = pd.read_csv('{}\\\\Data\\\\Metadata\\\\Zero_Area_Territories.csv'.format(os.getcwd()))\n zero_indicies = set(df_zero_area['AGSS_Code_2016'].tolist())\n zero_indicies_drop = set(df_data_t.index.values).intersection(zero_indicies)\n df_data_t = df_data_t.drop(zero_indicies_drop, axis=0)\n \n return df_data_t\n\n\ndef load_tables_specify_cats(table_list, category_list, statistical_area_code='SA3'):\n '''\n Function for loading ABS census data tables, and refining/aggregating by a set of defined categories\n (e.g. age, sex, occupation, English proficiency, etc.) where available.\n \n INPUTS\n table_list: LIST of STRING objects - list of the ABS Census Datapack tables to draw information from (G01-G59)\n category_list: LIST of STRING objects - Cetegorical information to slice/aggregate information from (e.g. Age)\n statistical_area_code: STRING - the ABS statistical area level of detail required (SA1-SA3)\n \n OUTPUTS\n A pandas dataframe\n '''\n for index, table in enumerate(table_list):\n if index==0:\n df = load_table_refined(table, category_list, statistical_area_code)\n df.reset_index(inplace=True)\n else:\n temp_df = load_table_refined(table, category_list, statistical_area_code)\n temp_df.reset_index(inplace=True)\n merge_col = df.columns[0]\n df = pd.merge(df, temp_df, on=merge_col)\n \n df.set_index(df.columns[0], inplace=True)\n \n return df\n\n\n\ndef build_model(verbosity = 3):\n ''' \n Builds a Gridsearch object for use in supervised learning modelling.\n Imputes for missing values and build a model to complete a quick Gridsearch over RandomForestRegressor key parameters.\n \n INPUTS\n None\n \n OUTPUTS\n cv - An SKLearn Gridsearch object for a pipeline that includes Median imputation and RandomForestRegressor model.\n '''\n pipeline_model = Pipeline([\n ('impute', SimpleImputer(missing_values=np.nan, strategy='median')),\n ('clf', RandomForestRegressor(n_estimators=100, random_state=42, max_depth=100))\n ])\n # specify parameters for grid search\n parameters = {'clf__n_estimators':[20,40], # this used to start at 10 and go to 80 but was a huge timesuck and not improving performance\n 'clf__max_depth':[16,32,64], # this used to go to 128 but had no impact on performance\n #'clf__min_samples_leaf':[1,2,4] This wasn't really having an impact on performance\n }\n\n # create grid search object\n scorer = make_scorer(r2_score)\n cv = GridSearchCV(pipeline_model, param_grid=parameters, scoring=scorer, verbose = verbosity, cv=3)\n\n return cv\n\ndef WFH_create_Xy(stat_a_level, load_tables, load_features):\n '''\n A function which compiles a set of background information from defined ABS census tables and \n creates input and output vectors to allow model training for the \"Work from home participation \n rate\" in a given region. Cleans the data for outliers (defined as >3 standard deviations from the mean) in the\n WFH participation rate, and scales all data by dividing by the \"Total Population\" feature for each region.\n \n INPUTS\n stat_a_level - String. The statistical area level of information the data should be drawn from (SA1-3)\n load_tables - List of Strings. A list of ABS census datapack tables to draw data from (G01-59)\n load_features - List of Strings. A list of population characteristics to use in analysis (Age, Sex, labor force status, etc.)\n \n OUTPUTS\n X - pandas DataFrame - a dataframe of features from the census datapacks tables, normalised by dividing each feature by \n the population attributable to the region\n y - pandas series - the Work from Home Participation Rate by region\n \n '''\n # Load table 59 (the one with commute mechanism) and have a quick look at the distribution of WFH by sex\n response_vector = 'WFH_Participation'\n df_travel = load_table_refined('G59', ['Number of Commuting Methods'], statistical_area_code=stat_a_level)\n cols_to_delete = [x for x in df_travel.columns if 'Worked_at_home' not in x]\n df_travel.drop(cols_to_delete,axis=1, inplace=True)\n\n df_pop = load_census_csv(['G01'], statistical_area_code=stat_a_level)\n df_pop.set_index(df_pop.columns[0], inplace=True)\n df_pop = df_pop.drop([x for x in df_pop.columns if 'Tot_P_P' not in x], axis=1)\n df_travel = df_travel.merge(df_pop, left_index=True, right_index=True)\n \n # Create new \"Work From Home Participation Rate\" vector to ensure consistency across regions\n # Base this off population who worked from home divided by total population in the region\n df_travel[response_vector] = (df_travel['Method of Travel to Work by Sex|Worked_at_home']/\n df_travel['Tot_P_P'])\n # Drop the original absolute values column\n df_travel = df_travel.drop(['Method of Travel to Work by Sex|Worked_at_home'], axis=1)\n \n # load input vectors\n input_vectors = load_tables_specify_cats(load_tables, load_features, statistical_area_code=stat_a_level)\n \n # Remove duplicate column values\n input_vectors = input_vectors.T.drop_duplicates().T\n\n # Bring in total population field and scale all the values by this item\n input_vectors = input_vectors.merge(df_pop, left_index=True, right_index=True)\n\n # convert input features to numeric\n cols = input_vectors.columns\n input_vectors[cols] = input_vectors[cols].apply(pd.to_numeric, errors='coerce')\n\n # Drop rows with zero population\n input_vectors = input_vectors.dropna(subset=['Tot_P_P'])\n input_vectors = input_vectors[input_vectors['Tot_P_P'] > 0]\n\n # Scale all factors by total region population\n for cols in input_vectors.columns:\n if 'Tot_P_P' not in cols:\n input_vectors[cols] = input_vectors[cols]/input_vectors['Tot_P_P']\n\n # merge and drop na values from the response vector\n df_travel = df_travel.merge(input_vectors, how='left', left_index=True, right_index=True)\n df_travel = df_travel.dropna(subset=[response_vector])\n\n df_travel = df_travel.drop([x for x in df_travel.columns if 'Tot_P_P' in x], axis=1)\n\n # drop outliers based on the WFHPR column\n # only use an upper bound for outlier detection in this case, based on 3-sigma variation \n # had previously chosen to remove columns based on IQR formula, but given the skew in the data this was not effective\n #drop_cutoff = (((df_travel[response_vector].quantile(0.75)-df_travel[response_vector].quantile(0.25))*1.5)\n # +df_travel[response_vector].quantile(0.75))\n drop_cutoff = df_travel[response_vector].mean() + (3* df_travel[response_vector].std())\n df_travel = df_travel[df_travel[response_vector] <= drop_cutoff]\n \n # Remove duplicate column values\n df_travel = df_travel.T.drop_duplicates().T\n\n # Create X & y\n X = df_travel.drop(response_vector, axis=1)\n y = df_travel[response_vector]\n\n # Get the estimator\n return X, y\n\n\ndef model_WFH(stat_a_level, load_tables, load_features):\n '''\n A function which compiles a set of background information from defined ABS census tables and trains a \n Random Forest Regression model (including cleaning and gridsearch functions) to predict the \"Work from home\n participation rate\" in a given region.\n \n INPUTS\n stat_a_level - String. The statistical area level of information the data should be drawn from (SA1-3)\n load_tables - List of Strings. A list of ABS census datapack tables to draw data from (G01-59)\n load_features - List of Strings. A list of population characteristics to use in analysis (Age, Sex, labor force status, etc.)\n \n OUTPUTS\n grid_fit.best_estimator_ - SKLearn Pipeline object. The best grid-fit model in training the data.\n X_train - Pandas dataframe. The training dataset used in fitting the model.\n X_test - Pandas dataframe. A testing dataset for use in analysing model performance.\n y_train - Pandas dataframe. The training dataset for the response vector (WFH participation)\n used in fitting the model.\n y_test - Pandas dataframe. A testing dataset for the response vector (WFH participation)\n for use in analysing model performance.\n \n '''\n \n # Create X & y\n X, y = WFH_create_Xy(stat_a_level, load_tables, load_features)\n\n # Split the 'features' and 'response' vectors into training and testing sets\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)\n\n # build a model using all the above inputs\n grid_obj = build_model()\n\n # TODO: Fit the grid search object to the training data and find the optimal parameters using fit()\n grid_fit = grid_obj.fit(X_train, y_train)\n\n # Get the estimator\n return grid_fit.best_estimator_, X_train, X_test, y_train, y_test\n\n\ndef sort_series_abs(S):\n '''Takes a pandas Series object and returns the series sorted by absolute value'''\n temp_df = pd.DataFrame(S)\n temp_df['abs'] = temp_df.iloc[:,0].abs()\n temp_df.sort_values('abs', ascending = False, inplace = True)\n return temp_df.iloc[:,0]\n\n\n'''Plotting functions'''\n\ndef feature_plot_h(model, X_train, n_features):\n '''\n Takes a trained model and outputs a horizontal bar chart showing the \"importance\" of the\n most impactful n features.\n \n INPUTS\n model = Trained model in sklearn with variable \".feature_importances_\". Trained supervised learning model.\n X_train = Pandas Dataframe object. Feature set the training was completed using.\n n_features = Int. Top n features you would like to plot.\n '''\n importances = model.feature_importances_\n # Identify the n most important features\n indices = np.argsort(importances)[::-1]\n columns = X_train.columns.values[indices[:n_features]]\n values = importances[indices][:n_features]\n \n columns = [ '\\n'.join(wrap(c, 30)).replace(\"_\", \" \") for c in columns ]\n \n # Create the plot\n plt.figure(figsize = (9,n_features))\n plt.title(\"Normalized Weights for {} Most Predictive Features\".format(n_features), fontsize = 16)\n plt.barh(np.arange(n_features), values, height = 0.4, align=\"center\", color = '#00A000', \n label = \"Feature Weight\")\n plt.barh(np.arange(n_features) - 0.3, np.cumsum(values), height = 0.2, align = \"center\", color = '#00A0A0', \n label = \"Cumulative Feature Weight\")\n plt.yticks(np.arange(n_features), columns)\n plt.xlabel(\"Weight\", fontsize = 12)\n \n plt.legend(loc = 'upper right')\n \n plt.gca().invert_yaxis()\n plt.tight_layout()\n plt.show() \n\n \ndef feature_impact_plot(model, X_train, n_features, y_label, pipeline=None, consistent_X=False, share_y = True):\n '''\n Takes a trained model and training dataset and synthesises the impacts of the top n features\n to show their relationship to the response vector (i.e. how a change in the feature changes\n the prediction). Returns n plots showing the variance for min, max, median, 1Q and 3Q.\n \n INPUTS\n model = Trained model in sklearn with variable \".feature_importances_\". Trained supervised learning model.\n X_train = Pandas Dataframe object. Feature set the training was completed using.\n n_features = Int. Top n features you would like to plot.\n y_label = String. Description of response variable for axis labelling.\n pipeline = Optional, sklearn pipeline object. If the sklearn model was compiled using a pipeline, \n this object needs to be specified separately.\n consistent_X = Optional Boolean. Input True to specify if the range of simulated feature ranges should be consistent.\n this makes the impact charts easier to compare between features where they have consistent \n units of meaure (e.g. share of population).\n share_y = Optional Boolean. Have a shared y-axis for all sub plots. Very good for comparing impacts of changes to \n individual features, but can make distinguishing the impacts of a feature difficult if there is \n significant variance in other plots.\n \n OUTPUT\n Plot with n subplots showing the variance for min, max, median, 1Q and 3Q as a result of simulated outcomes.\n '''\n # Display the n most important features\n indices = np.argsort(model.feature_importances_)[::-1]\n columns = X_train.columns.values[indices[:n_features]]\n \n sim_var = [[]]\n \n if pipeline == None:\n pipeline=model\n \n # get statistical descriptors\n X_descriptor = X_train[columns].describe()\n \n # Shorten the simulated outcomes for efficiency\n sample_length = min(X_train.shape[0], 1000)\n \n X_train = X_train.sample(sample_length, random_state=42)\n \n if consistent_X:\n value_dispersion = X_descriptor.loc['std',:].max()\n \n for col in columns:\n base_pred = pipeline.predict(X_train)\n # Add percentiles of base predictions to a df for use in reporting\n base_percentiles = [np.percentile(base_pred, pc) for pc in range(0,101,25)]\n\n # Create new predictions based on tweaking the parameter\n # copy X, resetting values to align to the base information through different iterations\n df_copy = X_train.copy() \n \n if consistent_X != True:\n value_dispersion = X_descriptor.loc['std',col] * 1.5\n\n for val in np.arange(-value_dispersion, value_dispersion, value_dispersion/50):\n df_copy[col] = X_train[col] + val\n # Add new predictions based on changed database\n predictions = pipeline.predict(df_copy)\n \n # Add percentiles of these predictions to a df for use in reporting\n percentiles = [np.percentile(predictions, pc) for pc in range(0,101,25)]\n \n # Add variances between percentiles of these predictions and the base prediction to a df for use in reporting\n percentiles = list(map(operator.sub, percentiles, base_percentiles))\n percentiles = list(map(operator.truediv, percentiles, base_percentiles))\n sim_var.append([val, col] + percentiles)\n\n # Create a dataframe based off the arrays created above\n df_predictions = pd.DataFrame(sim_var,columns = ['Value','Feature']+[0,25,50,75,100])\n \n # Create a subplot object based on the number of features\n num_cols = 2\n subplot_rows = int(n_features/num_cols) + int(n_features%num_cols)\n fig, axs = plt.subplots(nrows = subplot_rows, ncols = num_cols, sharey = share_y, figsize=(15,5*subplot_rows))\n\n nlines = 1\n\n # Plot the feature variance impacts\n for i in range(axs.shape[0]*axs.shape[1]):\n if i < len(columns):\n # Cycle through each plot object in the axs array and plot the appropriate lines\n ax_row = int(i/num_cols)\n ax_column = int(i%num_cols)\n \n axs[ax_row, ax_column].plot(df_predictions[df_predictions['Feature'] == columns[i]]['Value'],\n df_predictions[df_predictions['Feature'] == columns[i]][25],\n label = '25th perc')\n axs[ax_row, ax_column].plot(df_predictions[df_predictions['Feature'] == columns[i]]['Value'],\n df_predictions[df_predictions['Feature'] == columns[i]][50],\n label = 'Median')\n axs[ax_row, ax_column].plot(df_predictions[df_predictions['Feature'] == columns[i]]['Value'],\n df_predictions[df_predictions['Feature'] == columns[i]][75],\n label = '75th perc')\n \n axs[ax_row, ax_column].set_title(\"\\n\".join(wrap(columns[i], int(100/num_cols))))\n axs[ax_row, ax_column].legend()\n # Create spacing between charts if chart titles happen to be really long.\n nlines = max(nlines, axs[ax_row, ax_column].get_title().count('\\n'))\n\n axs[ax_row, ax_column].set_xlabel('Simulated +/- change to {} feature'.format(y_label))\n \n # Format the y-axis as %\n if ax_column == 0 or share_y == False:\n vals = axs[ax_row, ax_column].get_yticks()\n axs[ax_row, ax_column].set_yticklabels(['{:,.2%}'.format(x) for x in vals])\n axs[ax_row, ax_column].set_ylabel('% change to {}'.format(y_label))\n \n # If there is a \"spare\" plot, hide the axis so it simply shows as an empty space\n else:\n axs[int(i/num_cols),int(i%num_cols)].axis('off')\n \n # Apply spacing between subplots in case of very big headers\n fig.subplots_adjust(hspace=0.5*nlines)\n \n # Return the plot\n plt.tight_layout() \n plt.show()\n \ndef model_analyse_pred(X_test, y_test, model):\n ''' \n A function for outputting a fitting chart, showing the pairing of prediction vs actual in a modelled test set.\n \n INPUTS\n X_test - Pandas dataframe. The test set of characteristics to feed into a prediction model.\n y_test - Pandas Series. The test set of responses to compare to predictions made in the model.\n model - SKLearn fitted supervised learning model.\n \n OUTPUTS\n A plot showing the relationship between prediction and actual sets.\n '''\n preds = model.predict(X_test)\n model_analyse(y_test, preds)\n\ndef model_analyse(y_test, y_pred):\n ''' \n A function for outputting a fitting chart, showing the pairing of prediction vs actual in a modelled test set.\n \n INPUTS\n X_test - Pandas dataframe. The test set of characteristics to feed into a prediction model.\n y_test - Pandas Series. The test set of responses to compare to predictions made in the model.\n \n OUTPUTS\n A plot showing the relationship between prediction and actual sets.\n '''\n lineStart = min(y_pred.min(), y_test.min()) \n lineEnd = max(y_pred.max()*1.2, y_test.max()*1.2)\n\n plt.figure()\n plt.scatter(y_pred, y_test, color = 'k', alpha=0.5)\n plt.gca().set_aspect('equal', adjustable='box')\n plt.plot([lineStart, lineEnd], [lineStart, lineEnd], 'k-', color = 'r')\n plt.xlim(lineStart, lineEnd)\n plt.ylim(lineStart, lineEnd)\n plt.xlabel('Predictions')\n plt.ylabel('Actuals')\n plt.text(y_test.max()/5, y_test.max()*1.1, 'R2 Score: {:.3f}'.format(r2_score(y_test, y_pred)))\n plt.show()\n \ndef top_n_features(model, X_train, n_features):\n '''\n Takes a trained model and training dataset and returns the top n features by feature importance\n \n INPUTS\n model = Trained model in sklearn with variable \".feature_importances_\". Trained supervised learning model.\n X_train = Pandas Dataframe object. Feature set the training was completed using.\n n_features = Int. Top n features you would like to plot.\n '''\n # Display the n most important features\n indices = np.argsort(model.feature_importances_)[::-1]\n columns = X_train.columns.values[indices[:n_features]].tolist()\n \n return columns","sub_path":"app/au_census_analysis_functions.py","file_name":"au_census_analysis_functions.py","file_ext":"py","file_size_in_byte":25781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"324081931","text":"'''\n@Author: longfengpili\n@Date: 2019-09-18 07:39:03\n@LastEditTime: 2020-02-29 19:20:40\n@github: https://github.com/longfengpili\n'''\n\n#!/usr/bin/env python3\n#-*- coding:utf-8 -*-\n\nfrom .get_html import GetResponseBase\nfrom bs4 import BeautifulSoup\nimport re\nfrom api_urls import api_urls\nimport json\nimport datetime\n\nimport logging\nfrom logging import config\nconfig.fileConfig('vip_log.conf')\niqylogger = logging.getLogger('iqy')\n\nclass Iqiyi(GetResponseBase):\n def __init__(self, headers, api_id, search=None):\n self.search = search\n self.api_id = api_id\n self.url = f'https://so.iqiyi.com/so/q_{search}'\n self.headers = headers\n super(Iqiyi, self).__init__(self.url, self.headers)\n\n def get_html_from_iqiyi(self):\n soup = self.get_response_soup()\n # with open('./test.csv', 'w' ,encoding='utf-8') as f:\n # f.write(str(soup))\n return soup\n\n def get_search(self, first=False):\n soup = self.get_html_from_iqiyi()\n title = soup.title\n while not title or '404' in title.string:\n soup = self.get_html_from_iqiyi()\n title = soup.title\n title = title.string\n results = soup.find_all('h3', class_=\"qy-search-result-tit\")\n search_results = []\n for result in results:\n search_result = {}\n if 'title' in str(result.a):\n search_result['src'] = self.url\n search_result['api_id'] = self.api_id\n search_result['title'] = result.a['title']\n url = result.a['href']\n url = url if url.startswith('http') else 'http:' + url\n search_result['url'] = url\n if search_result not in search_results and '\", \"\", string)\n\n\ndef remove_tags(text):\n return \"\".join(ET.fromstring(text).itertext())\n","sub_path":"feeds/get_news.py","file_name":"get_news.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"504146645","text":"\n\n\nimport requests, json\nimport time \n\n\n#contries: 7 - russia\n\n\n\ndef get_phone(apikey):\n tzid = -1\n r = requests.get(\"http://onlinesim.ru/api/getNum.php?apikey=\" + apikey + \"&country=7&service=VKcom\")\n if r.json()['response'] == 1:\n tzid = r.json()['tzid']\n else:\n print(\"sorry boys\", r.json()['response'])\n return tzid\n\n\n\nclass onlinesimApi(object):\n \n \n def __init__(self, api_key =\"9b6d760fa5e3137d3d826d9859b4fb5b\" ):\n self.http = requests.Session()\n self.api_key = api_key\n self.tzid = None\n self.phone_number = None\n \n \n def get_balance(self):\n resp = self.http.get(\"http://onlinesim.ru/api/getBalance.php?apikey=\" + self.api_key)\n return resp.json()['balance']\n \n def get_info_of_numbers(self):\n resp1 = self.http.get(\"http://onlinesim.ru/api/getServiceList.php?country=7&apikey=\" + self.api_key)\n a = resp1.json()['0']\n ans = {'rus' : {'amount': a['limit'], 'price': a['index']}\n }\n return ans\n \n def get_number(self, country = 7):\n tzid = get_phone(self.api_key)\n print(tzid)\n if tzid == -1:\n print(\"sorry boys, something goes wrong\")\n return None\n else:\n self.tzid = tzid\n time.sleep(10)\n r = requests.get(\"http://onlinesim.ru/api/getState.php?apikey=\" + self.api_key + \"&message_to_code=1&tzid=\" + str(tzid))\n print(r.json())\n while 'number' not in r.json()[0]:\n time.sleep(10)\n r = requests.get(\"http://onlinesim.ru/api/getState.php?apikey=\" + self.api_key + \"&message_to_code=1&tzid=\" + str(tzid))\n print(r.json())\n self.phone_number = r.json()[0]['number']\n \n return self.phone_number\n \n def check(self):\n r = requests.get(\"http://onlinesim.ru/api/getState.php?apikey=\" + self.api_key + \"&message_to_code=1&tzid=\" + str(self.tzid))\n if r.json()[0]['response'] == 'TZ_NUM_ANSWER':\n return r.json()[0]['msg']\n return r.json()\n \n def ban(self):\n pass\n \n def finish(self):\n pass\n\n#ss = onlinesimApi()\n#print(ss.get_balance())\n#print(ss.get_info_of_numbers())","sub_path":"PythonServer/apisms/onlinesim.py","file_name":"onlinesim.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"596807395","text":"# -*- coding: utf-8 -*-\n'''\nЗадание 7.3b\n\nСделать копию скрипта задания 7.3a.\n\nДополнить скрипт:\n- Запросить у пользователя ввод номера VLAN.\n- Выводить информацию только по указанному VLAN.\n\nОграничение: Все задания надо выполнять используя только пройденные темы.\n\n'''\nt1 = '{0:<8} {1} {2:>8}'\nvout = {}\nvlist = []\n\nwith open('CAM_table.txt','r') as mctab:\n for string in mctab:\n if 'DYNAMIC' in string:\n string = string.split()\n vout[string[0]] = string\n vlist.append(int(string[0]))\n else:\n continue \n vlist.sort()\nvlan = input('Input VLAN: ')\nif vout.get(vlan) is not None:\n print(t1.format(vout[str(vlan)][0],vout[str(vlan)][1],vout[str(vlan)][3]))\nelse:\n print('Invalid VLAN')","sub_path":"exercises/07_files/task_7_3b.py","file_name":"task_7_3b.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"48865380","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Oct 26 10:15:17 2019\r\n\r\n@author: solis\r\n\"\"\"\r\nmyapykey = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzb2xpc2diQGdtYWlsLmNvbSIsImp0aSI6ImY1M2QzOGQ1LTc0M2QtNDVlMi04NWNhLWVkZGY4YWUyNDY2ZCIsImlzcyI6IkFFTUVUIiwiaWF0IjoxNTY0ODQ4ODk4LCJ1c2VySWQiOiJmNTNkMzhkNS03NDNkLTQ1ZTItODVjYS1lZGRmOGFlMjQ2NmQiLCJyb2xlIjoiIn0.dAuxZhnq0CC8d6a_2D4eIInioTtlrV5QhdTLU3tVIrg'\r\nestaciones_get = '/opendata/api/valores/climatologicos/inventarioestaciones/todasestaciones/'\r\nestaciones_url = 'https://opendata.aemet.es/opendata/api/valores/climatologicos/inventarioestaciones/todasestaciones/'\r\nmeteoro_mes_get = 'https://opendata.aemet.es/opendata/api/valores/climatologicos/mensualesanuales/datos/anioini/{}/aniofin/{}/estacion/{}'\r\nmeteoro_dia_get = 'https://opendata.aemet.es/opendata/api/valores/climatologicos/diarios/datos/fechaini/{}/fechafin/{}/estacion/{}'\r\nfData = r'C:\\Users\\solis\\Downloads\\data.txt'\r\n\r\nRESPONSEOK = 200\r\nUNAUTHORIZED = 401\r\nNOTFOUND = 404\r\nTOOMANYREQUESTS = 429\r\nMAXREQUEST = 3\r\n\r\n\r\ndef meteoro_url_get(url: str):\r\n \"\"\"\r\n Devuelve respuesta de request.get realizada con los argumentos headers y\r\n params. Si la respuesta es correcta devuelve una url donde se pueden\r\n descargar los datos meteorológicos solicitados\r\n url. url\r\n dst. file name to write the data\r\n \"\"\"\r\n import requests\r\n querystring = {\"api_key\":f\"{myapykey}\"}\r\n headers = {'cache-control': \"no-cache\"}\r\n nrequest = 0\r\n while True:\r\n response = requests.get(url, headers=headers, params=querystring,\r\n timeout=3)\r\n\r\n if response.status_code == RESPONSEOK:\r\n response.encoding = response.apparent_encoding\r\n return response, RESPONSEOK\r\n elif response.status_code == TOOMANYREQUESTS:\r\n nrequest += 1\r\n if nrequest <= MAXREQUEST:\r\n continue\r\n else:\r\n return None, TOOMANYREQUESTS\r\n elif response.status_code == NOTFOUND:\r\n print('No hay datos')\r\n return None, NOTFOUND\r\n elif response.status_code == UNAUTHORIZED:\r\n raise ValueError('No tengo autorización')\r\n else:\r\n raise ValueError(f'Request error {response.status_code}')\r\n\r\n\r\ndef meteoro_data_get(url: str, dst: str) ->int:\r\n \"\"\"\r\n Graba los datos metereoloógicos a un fichero utilizando la url devuelta\r\n por la función meteoro_url_get\r\n url. url\r\n dst. file name to write the data\r\n \"\"\"\r\n import requests\r\n nrequest = 0\r\n while True:\r\n response = requests.get(url, timeout=3)\r\n\r\n if response.status_code == RESPONSEOK:\r\n response.encoding = response.apparent_encoding\r\n with open(dst, 'wb') as f:\r\n f.write(response.content)\r\n return RESPONSEOK\r\n elif response.status_code == TOOMANYREQUESTS:\r\n nrequest += 1\r\n if nrequest <= MAXREQUEST:\r\n continue\r\n else:\r\n return TOOMANYREQUESTS\r\n elif response.status_code == NOTFOUND:\r\n print('No hay datos')\r\n return NOTFOUND\r\n elif response.status_code == UNAUTHORIZED:\r\n raise ValueError('No tengo autorización')\r\n else:\r\n raise ValueError(f'Request error {response.status_code}')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n try:\r\n from datetime import datetime, timedelta\r\n from time import time\r\n import traceback\r\n import littleLogging as logging\r\n\r\n now = datetime.now()\r\n\r\n startTime = time()\r\n\r\n estacion = '7228'\r\n meteoro_mes_url = meteoro_mes_get.format('2000', '2000', estacion)\r\n meteoro_dia_url = meteoro_dia_get.format('2000-01-01T00:00:00UTC', '2000-01-31T00:00:00UTC', estacion)\r\n r, rcode = meteoro_url_get(meteoro_dia_url)\r\n if r:\r\n if rcode == RESPONSEOK:\r\n url = r.json()['datos']\r\n rcode2 = meteoro_data_get(url, fData)\r\n\r\n xtime = time() - startTime\r\n\r\n except ValueError:\r\n msg = traceback.format_exc()\r\n logging.append(f'ValueError exception\\n{msg}')\r\n except ImportError:\r\n msg = traceback.format_exc()\r\n print (f'ImportError exception\\n{msg}')\r\n except Exception:\r\n msg = traceback.format_exc()\r\n logging.append(f'Exception\\n{msg}')\r\n finally:\r\n print('El script tardó {0}'.format(str(timedelta(seconds=xtime))))\r\n logging.dump()\r\n print('\\nFin')\r\n\r\n","sub_path":"aemetOpenDataTests.py","file_name":"aemetOpenDataTests.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"420277527","text":"import math\r\nfrom collections import Counter\r\n\r\n\r\ndef nCr(n,r):\r\n f = math.factorial\r\n return f(n) / f(r) / f(n-r)\r\n\r\nclass Importer:\r\n ''' Reads the file, and queues up inputs'''\r\n def __init__(self,file):\r\n self.file = file\r\n self.fhandle = open(self.file, 'r')\r\n self.T = int(self.fhandle.readline())\r\n\r\n def pop(self):\r\n word = [int(x) for x in list(self.fhandle.readline().strip().split(' '))]\r\n return (word[0],word[1])\r\n\r\nclass Exporter:\r\n ''' writes output in proper format, line by line'''\r\n def __init__(self,file):\r\n self.file = file\r\n with open(self.file, 'w'): pass\r\n self.fhandle = open(self.file, 'w')\r\n self.ind = 1\r\n\r\n\r\n def put(self,impos,ans):\r\n outs = 'Case #'+str(self.ind)+':'\r\n if not impos:\r\n outs += ' IMPOSSIBLE\\n'\r\n else:\r\n outs += ' POSSIBLE\\n'\r\n B = len(ans)\r\n for i in range(B):\r\n for j in range(B):\r\n\r\n outs += str(ans[i][j])\r\n outs+='\\n'\r\n self.fhandle.write(outs)\r\n self.ind += 1\r\n\r\n\r\n\r\nclass Runner(object):\r\n ''' Run algo one case at a time'''\r\n\r\n def run(self, B,M):\r\n maxPossibility = int(sum([nCr(B-2,i) for i in range(0,B-1)]))\r\n if M>maxPossibility:\r\n return((False,0))\r\n pathMap = list(reversed(list(str(\"{0:b}\".format(M-1)))))\r\n print(pathMap)\r\n finMAP = [[0]*(B) for i in range(B)]\r\n finMAP[0][B-1] = 1\r\n for i in range(0,B-2):\r\n if i>=len(pathMap):\r\n pass\r\n else:\r\n if pathMap[i] is '1':\r\n finMAP[0][B-2-i] = 1\r\n for x in range(B-2-i,B):\r\n for j in range(x+1,B):\r\n finMAP[x][j] = 1\r\n\r\n return((True,finMAP))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n print(Runner)\r\n read = Importer('B-small-attempt1.in')\r\n sol = Runner()\r\n write = Exporter('output.txt')\r\n for i in range(read.T):\r\n (B,M) = read.pop()\r\n #print(B,M)\r\n (impos,ans) = sol.run(B,M)\r\n #print(ans)\r\n write.put(impos,ans)\r\n","sub_path":"solutions_5744014401732608_0/Python/jgalaro/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"634369795","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 28 16:35:14 2018\n\n@author: ghkim\n\"\"\"\n\nimport numpy as np\nfrom scipy.ndimage import maximum_filter\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d.axes3d import Axes3D\nfrom matplotlib import cm\n\n\nimport parameter as par\nimport movie_io as fr\n\ndef remove_background(one_frame, thre):\n return one_frame * (one_frame > thre)\n \ndef peak_find(dire, movie_name, param):\n movie = fr.frame(dire, movie_name, param)\n peak_data = [0, 0]\n for i in range(movie.length):\n one_frame = remove_background(movie.get_next_frame(), 30)\n temp = find_from_intensity(one_frame)\n peak_data = np.vstack((peak_data, temp))\n return peak_data[1:]\n\ndef find_from_intensity(one_frame, gridsize = 8):\n max_point = [0,0]\n for i in range(512//gridsize):\n start_x = i * gridsize\n for j in range(512//gridsize):\n start_y = j * gridsize\n grided_image = one_frame[start_x:start_x+gridsize, start_y:start_y+gridsize]\n if grided_image.max() == 0:\n continue;\n ind = np.unravel_index(np.argmax(grided_image, axis=None), grided_image.shape)\n if (grided_image[ind[0] - 1:ind[0] + 1, ind[1] - 1:ind[1] + 1] > grided_image[ind[0], ind[1]] * 0.4).sum() - 1 >= 2:\n max_point = np.vstack([max_point, [ind[0]+start_x, ind[1]+start_y]])\n return max_point[1:]","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"57719950","text":"\"\"\"\nProblem Statement\nGiven an input string consisting of only { and }, figure out the minimum number of reversals required to make the brackets balanced.\n\nFor example:\n\nFor input_string = \"}}}}, the number of reversals required is 2.\nFor input_string = \"}{}}, the number of reversals required is 1.\nIf the brackets cannot be balanced, return -1 to indicate that it is not possible to balance them.\n\"\"\"\n\nclass LinkedListNode:\n\n def __init__(self, value):\n self.value = value\n self.next = None\n\n\nclass Stack:\n\n def __init__(self):\n self.num_elements = 0\n self.head = None\n\n def push(self, value):\n new_node = LinkedListNode(value)\n if self.head is None:\n self.head = new_node\n else:\n new_node.next = self.head\n self.head = new_node\n self.num_elements += 1\n\n def pop(self):\n if self.is_empty():\n return None\n temp = self.head.value\n self.head = self.head.next\n self.num_elements -= 1\n return temp\n\n def top(self):\n if self.head is None:\n return None\n return self.head.value\n\n def size(self):\n return self.num_elements\n\n def is_empty(self):\n return self.num_elements == 0\n\ndef minimum_bracket_reversals(input_string):\n movements = 0\n if input_string[0] == \"}\":\n input_string = \"{\" + input_string[1:]\n movements += 1\n if input_string[len(input_string) - 1] == \"{\":\n input_string = input_string[:len(input_string) - 1] + \"}\"\n movements += 1\n prevChar = \"-\"\n\n if len(input_string) % 2 != 0:\n return -1\n else:\n stack = Stack()\n for char in input_string:\n if prevChar + char == \"{}\":\n _ = stack.pop()\n prevChar = stack.top()\n if stack.size() == 0:\n prevChar = \"-\"\n else:\n stack.push(char)\n prevChar = char\n\n return int(stack.size() / 2) + movements\n\n\ndef test_function(test_case):\n input_string = test_case[0]\n expected_output = test_case[1]\n output = minimum_bracket_reversals(input_string)\n\n if output == expected_output:\n print(\"Pass\")\n else:\n print(\"Fail\")\n\n\ntest_case_1 = [\"}}}}\", 2]\ntest_function(test_case_1)\n\ntest_case_2 = [\"}}{{\", 2]\ntest_function(test_case_2)\n\ntest_case_3 = [\"{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}\", 13]\n\ntest_function(test_case_1)\n\ntest_case_4 = [\"}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{\", 2]\ntest_function(test_case_2)\n\ntest_case_5 = [\"}}{}{}{}{}{}{}{}{}{}{}{}{}{}{}\", 1]\n\ntest_function(test_case_3)\n","sub_path":"Another 3/minimumBracketReversal.py","file_name":"minimumBracketReversal.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"284277477","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Mar 12 23:01:56 2017\r\n\r\n@author: Arun\r\n\"\"\"\r\nimport os\r\nos.getcwd()\r\n\r\nos.chdir('your directory')\r\n\r\nimport numpy as np\r\nfrom stl import mesh\r\nimport trimesh\r\n\r\n# load a file by name or from a buffer\r\nmesh = trimesh.load_mesh('Your.stl file')\r\n\r\n# is the current mesh watertight?\r\nmesh.is_watertight\r\n\r\n# what's the euler number for the mesh?\r\nmesh.euler_number\r\n\r\n# the convex hull is another Trimesh object that is available as a property\r\n# lets compare the volume of our mesh with the volume of its convex hull\r\nnp.divide(mesh.volume, mesh.convex_hull.volume)\r\na=mesh.vertices\r\nmin(a[:,[2]])+0.5\r\n\r\n# since the mesh is watertight, it means there is a\r\n# volumetric center of mass which we can set as the origin for our mesh\r\nmesh.vertices -= mesh.center_mass\r\n# what's the moment of inertia for the mesh?\r\nmesh.moment_inertia\r\n\r\n# if there are multiple bodies in the mesh we can split the mesh by\r\n# connected components of face adjacency\r\n# since this example mesh is a single watertight body we get a list of one mesh\r\nmesh.split()\r\n\r\n# find groups of coplanar adjacent faces\r\nfacets, facets_area = mesh.facets(return_area=True)\r\n\r\n# set each facet to a random color\r\n# colors are 8 bit RGBA by default (n,4) np.uint8\r\nfor facet in facets:\r\n mesh.visual.face_colors[facet] = trimesh.visual.random_color()\r\n\r\n# preview mesh in an opengl window if you installed pyglet with pip\r\nmesh.show()\r\n\r\n# transform method can be passed a (4,4) matrix and will cleanly apply the transform\r\nmesh.apply_transform(trimesh.transformations.random_rotation_matrix())\r\n\r\n# axis aligned bounding box is available\r\nmesh.bounding_box.extents\r\n\r\n# a minimum volume oriented bounding box also available\r\n# primitives are subclasses of Trimesh objects which automatically generate\r\n# faces and vertices from data stored in the 'primitive' attribute\r\nmesh.bounding_box_oriented.primitive.extents\r\nmesh.bounding_box_oriented.primitive.transform\r\n\r\n# show the mesh appended with its oriented bounding box\r\n# the bounding box is a trimesh.primitives.Box object, which subclasses\r\n# Trimesh and lazily evaluates to fill in vertices and faces when requested\r\n# (press w in viewer to see triangles)\r\n(mesh + mesh.bounding_box_oriented).show()\r\n\r\n# bounding spheres and bounding cylinders of meshes are also\r\n# available, and will be the minimum volume version of each\r\n# except in certain degenerate cases, where they will be no worse\r\n# than a least squares fit version of the primitive.\r\nprint(mesh.bounding_box_oriented.volume,\r\n mesh.bounding_cylinder.volume,\r\n mesh.bounding_sphere.volume)\r\n\r\n\r\n","sub_path":"CODE/mesh.py","file_name":"mesh.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"405395976","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 27 14:02:45 2019\n\n@author: stephan\n\nMain file to declare and run the models through the experiment.py file\n\"\"\"\n#import tensorflow as tf\n\nfrom experiment import run_experiment\nimport argparse\n\n\nargparser = argparse.ArgumentParser(\n description='run and train experiments')\n\nargparser.add_argument('-m', '--model', type=str, help='which model to use')\nargparser.add_argument('--batch_size', default=32, type=int, help='mini batch size to use')\nargparser.add_argument('--augmentations', default=True, type=bool, help='use augmentations (True, False)')\nargparser.add_argument('--lr', default=0.0001, type=float, help='learning rate')\nargparser.add_argument('--sa', default=True, type=bool, help='use under/over sampling? (True, False)')\nargparser.add_argument('--epoch', default=10, type=int, help='number of epochs (int)')\n \n \ndef _main_(args):\n # ======================\n # BASE PARAMETERS\n # ======================\n print(args)\n #os.nice(19)\n fit_params = {'model': args.model,\n 'lr': args.lr,\n 'epochs': args.epoch,\n 'reduce_lr_on_plateau': True}\n\n data_params = {'use_sampling': args.sa,\n 'batch_size' :args.batch_size,\n 'buffer_size':3000,\n 'augmentations': args.augmentations}\n\n model_params = {'channels': ['B4', 'B3', 'B2', 'AVE'],\n 'target_size': [257, 257],\n 'num_classes': 2,\n 'weights': 'imagenet'}\n\n config = {'fit_params': fit_params,\n 'data_params': data_params,\n 'model_params': model_params}\n\n run_experiment(config)\n\nif __name__ == '__main__':\n _args = argparser.parse_args()\n _main_(_args)\n\n","sub_path":"classification/run_models.py","file_name":"run_models.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"564402555","text":"import os\n# Write a program which prints the full path for all files in the current directory, one per line.\ncomplete_path= os.getcwd()\nfiles=os.listdir(complete_path)\nfor f in files:\n print(complete_path+\"\\\\\"+f)\n\n# Write a program which copies a file from a source, to a destination)\nwith open('input.txt', 'r') as from_file, open('output.txt', 'w') as to_file:\n clipboard = from_file.read()\n to_file.write(clipboard)","sub_path":"students/srepking/Lesson04/activity2.py","file_name":"activity2.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"628842885","text":"\"\"\"\nzadanie 6, matura 2018 pr - stara formuła\n\"\"\"\n\n\ndef anagram(para):\n a = list(sorted(para[0]))\n b = list(sorted(para[1]))\n if a == b:\n return True\n return False\n\n\ndane = []\nwith open(\"slowa.txt\", \"r\") as file:\n for line in file:\n line = line.strip()\n dane.append(line.split(\" \"))\n\n# 6.1\nlicznik1 = 0\nfor P in dane:\n for S in P:\n if S[-1] == \"A\":\n licznik1 += 1\n\n# 6.2 6.3\nlicznik2 = 0\nlicznik3 = 0\nzad3 = \"\"\nfor para in dane:\n if para[0] in para[1]:\n licznik2 += 1\n if anagram(para):\n licznik3 += 1\n zad3 += \"\\t\".join(slowo for slowo in para)\n zad3 += \"\\n\"\n\nwith open(\"wyniki6.txt\", \"w\") as odp:\n odp.write(\"6.1\\n\" + str(licznik1))\n odp.write(\"\\n\\n6.2\\n\" + str(licznik2))\n odp.write(\"\\n\\n6.3\\n\" + f'{licznik3}\\n{zad3}')","sub_path":"2018 pr - stara/zadanie6/zadanie6.py","file_name":"zadanie6.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"196896220","text":"# 의석이의 세로로 말해요\n\ntest = int(input())\n\nfor case in range(test):\n words = []\n for i in range(5):\n word = list(input())\n words.append(word)\n\n max = 0\n for i in words:\n if len(i) > max:\n max = len(i)\n \n new_word = []\n for i in range(max):\n for j in range(5):\n try:\n new_word.append(words[j][i])\n except IndexError:\n continue\n \n print(f'#{case + 1}', end = ' ')\n for i in new_word:\n print(i, end = '')\n print()\n\n","sub_path":"Python/201014/5356.py","file_name":"5356.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"201560008","text":"# from pulse.preprocessing.before_run import BeforeRun\nfrom data.user_input.project.printMessageInput import PrintMessageInput\nimport numpy as np\n\nwindow_title_1 = \"ERROR\"\nwindow_title_2 = \"WARNING\"\n\nclass BeforeRun:\n def __init__(self, preprocessor, **kwargs):\n self.preprocessor = preprocessor\n self.nodes = preprocessor.nodes\n self.structural_elements = preprocessor.structural_elements\n self.acoustic_elements = preprocessor.acoustic_elements\n self.dict_tag_to_entity = preprocessor.dict_tag_to_entity\n\n\n def check_input_NodeID(self, lineEdit, single_ID=False):\n try:\n\n title = \"Invalid entry to the Node ID\"\n message = \"\"\n tokens = lineEdit.strip().split(',')\n\n try:\n tokens.remove('')\n except:\n pass\n\n _size = len(self.nodes)\n\n list_nodes_typed = list(map(int, tokens))\n\n if len(list_nodes_typed) == 0:\n message = \"An empty input field for the Node ID has been detected. \\n\\nPlease, enter a valid Node ID to proceed!\"\n \n elif len(list_nodes_typed) >= 1: \n if single_ID and len(list_nodes_typed) > 1:\n message = \"Multiple Node IDs\"\n else:\n try:\n for node_ID in list_nodes_typed:\n self.nodes[node_ID]\n except:\n message = \"Dear user, you have typed an invalid entry at the Node ID input field.\\n\\n\" \n message += f\"The input value(s) must be integer(s) number(s) greater than 1 and\\n less than {_size}.\"\n\n except Exception as log_error:\n message = f\"Wrong input for the Node ID's! \\n\\n{str(log_error)}\"\n\n if message != \"\":\n PrintMessageInput([title, message, window_title_1]) \n return True, [] \n\n if single_ID:\n return False, list_nodes_typed[0]\n else:\n return False, list_nodes_typed\n\n\n def check_input_ElementID(self, lineEdit, single_ID=False):\n try:\n\n title = \"Invalid entry to the Element ID\"\n message = \"\"\n tokens = lineEdit.strip().split(',')\n\n try:\n tokens.remove('')\n except:\n pass\n\n _size = len(self.structural_elements)\n\n list_elements_typed = list(map(int, tokens))\n\n if len(list_elements_typed) == 0:\n message = \"An empty input field for the Element ID has been detected. \\n\\nPlease, enter a valid Element ID to proceed!\"\n\n elif len(list_elements_typed) >= 1: \n if single_ID and len(list_elements_typed)>1:\n message = \"Multiple Element IDs\"\n else:\n try:\n for element_ID in list_elements_typed:\n self.structural_elements[element_ID]\n except:\n message = \"Dear user, you have typed an invalid entry at the Element ID input field.\\n\\n\" \n message += f\"The input value(s) must be integer(s) number(s) greater than 1 and\\n less than {_size}.\"\n\n except Exception as log_error:\n message = f\"Wrong input for the Element ID's! \\n\\n{str(log_error)}\"\n\n if message != \"\":\n PrintMessageInput([title, message, window_title_1]) \n return True, [] \n\n if single_ID:\n return False, list_elements_typed[0]\n else:\n return False, list_elements_typed\n\n\n def check_input_LineID(self, lineEdit, single_ID=False):\n try:\n\n title = \"Invalid entry to the Line ID\"\n message = \"\"\n tokens = lineEdit.strip().split(',')\n\n try:\n tokens.remove('')\n except:\n pass\n\n _size = len(self.dict_tag_to_entity)\n\n list_lines_typed = list(map(int, tokens))\n\n if len(list_lines_typed) == 0:\n message = \"An empty input field for the Line ID has been detected. \\n\\nPlease, enter a valid Line ID to proceed!\"\n\n elif len(list_lines_typed) >= 1: \n if single_ID and len(list_lines_typed)>1:\n message = \"Multiple Line IDs\"\n else:\n try:\n for line_ID in list_lines_typed:\n self.dict_tag_to_entity[line_ID]\n except:\n message = \"Dear user, you have typed an invalid entry at the Line ID input field.\\n\\n\" \n message += f\"The input value(s) must be integer(s) number(s) greater than 1 and\\n less than {_size}.\"\n\n except Exception as log_error:\n message = f\"Wrong input for the Line ID's! \\n\\n{str(log_error)}\"\n\n if message != \"\":\n PrintMessageInput([title, message, window_title_1]) \n return True, [] \n\n if single_ID:\n return False, list_lines_typed[0]\n else:\n return False, list_lines_typed\n\n\n def check_material_all_elements(self):\n \"\"\"\n This method checks if all structural elements have a material object attributed.\n \"\"\"\n self.check_set_material = False\n self.check_poisson = False\n for element in self.structural_elements.values():\n if element.material is None:\n self.check_set_material = True\n return\n\n def check_poisson_all_elements(self):\n \"\"\"\n This method checks if all structural elements have a Poisson ratio attributed.\n \"\"\"\n self.check_poisson = False\n for element in self.structural_elements.values():\n if element.material.poisson_ratio == 0:\n self.check_poisson = True\n return\n\n\n def check_material_and_cross_section_in_all_elements(self):\n \"\"\"\n This method checks if all structural elements have a material object and a cross section object attributed.\n \"\"\"\n self.check_set_material = False\n self.check_set_crossSection = False\n self.check_poisson = False\n for element in self.structural_elements.values():\n if element.material is None:\n self.check_set_material = True\n return\n if element.cross_section is None:\n if element.element_type:\n self.check_set_crossSection = True\n return\n else: \n\n if element.element_type == 'expansion_joint':\n if element.cross_section.area_fluid == 0:\n self.check_set_crossSection = True\n return\n else:\n if element.cross_section.thickness == 0:\n if element.cross_section.area == 0:\n self.check_set_crossSection = True\n return\n\n\n def check_fluid_and_cross_section_in_all_elements(self):\n \"\"\"\n This method checks if all acoustic elements have a fluid object and a cross section object attributed.\n \"\"\"\n self.check_set_fluid = False\n self.check_set_crossSection = False\n for element in self.acoustic_elements.values():\n \n if element.fluid is None:\n if 'pipe_' in self.structural_elements[element.index].element_type:\n self.check_set_fluid = True\n return\n\n if element.cross_section is None:\n self.check_set_crossSection = True\n return\n\n if self.structural_elements[element.index].element_type == 'expansion_joint':\n if element.cross_section.area_fluid == 0:\n self.check_set_crossSection = True\n return\n else: \n if element.cross_section.thickness == 0:\n if element.cross_section.area == 0:\n self.check_set_crossSection = True\n return\n\n\n def check_fluid_inputs_in_all_elements(self):\n \"\"\"\n This method checks if each acoustic element has the necessary fluid data to evaluate the analysis according to its element type.\n \"\"\"\n self.check_all_fluid_inputs = False\n for element in self.acoustic_elements.values():\n if element.element_type in ['wide-duct', 'LRF fluid equivalent', 'LRF full']:\n if 'pipe_' in self.structural_elements[element.index].element_type:\n _list = [ element.fluid.isentropic_exponent, element.fluid.thermal_conductivity, \n element.fluid.specific_heat_Cp, element.fluid.dynamic_viscosity ]\n if None in _list:\n self.check_all_fluid_inputs = True\n return\n\n\n def check_nodes_attributes(self, acoustic=False, structural=False, coupled=False):\n \"\"\"\n This method checks if there is the necessary nodal input data to evaluate the analysis according to its type.\n\n Parameters\n ----------\n acoustic : boll, optional\n True if a acoustic analysis will be performed. False otherwise.\n Default is False.\n\n structural : boll, optional\n True if a structural analysis will be performed. False otherwise.\n Default is False.\n\n coupled : boll, optional\n True if a coupled analysis will be performed. False otherwise.\n Default is False.\n \"\"\"\n self.is_there_loads = False\n self.is_there_prescribed_dofs = False\n self.is_there_acoustic_pressure = False\n self.is_there_volume_velocity = False\n for node in self.nodes.values():\n\n if structural:\n if node.there_are_nodal_loads:\n self.is_there_loads = True\n return\n\n if node.there_are_prescribed_dofs:\n if True in [True if isinstance(value, np.ndarray) else False for value in node.prescribed_dofs]:\n self.is_there_prescribed_dofs = True\n return\n\n elif sum([value if value is not None else complex(0) for value in node.prescribed_dofs]) != complex(0):\n self.is_there_prescribed_dofs = True\n return\n\n if acoustic or coupled:\n if node.acoustic_pressure is not None:\n self.is_there_acoustic_pressure = True\n return\n\n if node.volume_velocity is not None:\n self.is_there_volume_velocity = True\n return \n\n\n def check_all_acoustic_criteria(self):\n window_title = \"WARNING\"\n title = \"Acoustic criteria not satisfied\"\n \n flag_plane_wave = False\n flag_wide_duct = False\n flag_lrf_fluid_eq = False\n flag_lrf_full = False\n flag_unflanged_radiation_impedance = False\n \n message_plane_wave = \"flag_plane_wave\"\n message_wide_duct = \"flag_wide_duct\"\n message_lrf_fluid_eq = \"flag_lrf_fluid_eq\"\n message_lrf_full = \"flag_lrf_full\"\n message_unflanged_radiation_impedance = \"The unflanged radiation impedance model is out of its validity frequency range. It is recommended to check the results carefully.\"\n\n for element in self.acoustic_elements.values():\n\n if element.flag_plane_wave and not flag_plane_wave:\n flag_plane_wave = True\n \n if element.flag_wide_duct and not flag_wide_duct:\n flag_wide_duct = True\n \n if element.flag_lrf_fluid_eq and not flag_lrf_fluid_eq:\n flag_lrf_fluid_eq = True\n \n if element.flag_lrf_full and not flag_lrf_full:\n flag_lrf_full = True\n \n if element.flag_unflanged_radiation_impedance and not flag_unflanged_radiation_impedance:\n flag_unflanged_radiation_impedance = True\n\n list_flags = [flag_plane_wave, flag_wide_duct, flag_lrf_fluid_eq, flag_lrf_full, flag_unflanged_radiation_impedance]\n list_messages = [message_plane_wave, message_wide_duct, message_lrf_fluid_eq, message_lrf_full, message_unflanged_radiation_impedance]\n\n for index, flag in enumerate(list_flags):\n if flag:\n PrintMessageInput([title, list_messages[index], window_title])\n\n\n def check_is_there_a_problem(self, analysis_ID):\n\n title = \" Insufficient model inputs \"\n\n cross_section_message = \"You should to set a Cross-Section to all\\n elements before trying to run any Analysis!\"\n material_message = \"You should to set a Material to all elements\\n before trying to run any Analysis!\"\n fluid_message = \"You should to set a Fluid to all elements\\n before trying to run any Analysis!\"\n all_fluid_inputs_message = \"You should insert all fluid properties for wide-duct, LRF \\nfluid equivalent and LRF full acoustic element types.\"\n structural_message = \"You should to apply an external load to the model or prescribe a \\nnon-null DOF value before trying to solve the Harmonic Analysis!\"\n acoustic_message = \"You should to insert a Volume Velocity or prescribe an Acoustic \\nPressure to a node before trying to solve the Harmonic Analysis!\"\n \n if analysis_ID == 2:\n self.check_material_and_cross_section_in_all_elements()\n if self.check_set_material:\n PrintMessageInput([title, material_message, window_title_1])\n return True\n elif self.check_set_crossSection:\n PrintMessageInput([title, cross_section_message, window_title_1])\n return True\n \n elif analysis_ID == 4:\n self.check_material_all_elements()\n self.check_fluid_and_cross_section_in_all_elements()\n self.check_fluid_inputs_in_all_elements()\n if self.check_set_material:\n PrintMessageInput([title, material_message, window_title_1])\n return True\n elif self.check_set_fluid:\n PrintMessageInput([title, fluid_message, window_title_1])\n return True\n elif self.check_all_fluid_inputs:\n PrintMessageInput([title, all_fluid_inputs_message, window_title_1])\n return True\n elif self.check_set_crossSection:\n PrintMessageInput([title, cross_section_message, window_title_1])\n return True\n\n elif analysis_ID == 0 or analysis_ID == 1:\n self.check_material_and_cross_section_in_all_elements()\n self.check_nodes_attributes(structural=True)\n if self.check_set_material:\n PrintMessageInput([title, material_message, window_title_1])\n return True\n elif self.check_set_crossSection:\n PrintMessageInput([title, cross_section_message, window_title_1])\n return True\n elif not self.is_there_loads:\n if not self.is_there_prescribed_dofs:\n PrintMessageInput([title, structural_message, window_title_1])\n return True\n \n elif analysis_ID == 3:\n self.check_material_all_elements()\n self.check_fluid_and_cross_section_in_all_elements()\n self.check_fluid_inputs_in_all_elements()\n self.check_nodes_attributes(acoustic=True)\n if self.check_set_fluid:\n PrintMessageInput([title, fluid_message, window_title_1])\n return True\n elif self.check_all_fluid_inputs:\n PrintMessageInput([title, all_fluid_inputs_message, window_title_1])\n return True\n elif self.check_set_material:\n PrintMessageInput([title, material_message, window_title_1])\n return True\n elif self.check_set_crossSection:\n PrintMessageInput([title, cross_section_message, window_title_1])\n return True\n elif not self.is_there_volume_velocity:\n if not self.is_there_acoustic_pressure:\n PrintMessageInput([title, acoustic_message, window_title_1])\n return True\n\n elif analysis_ID == 5 or analysis_ID == 6:\n self.check_material_and_cross_section_in_all_elements()\n self.check_fluid_and_cross_section_in_all_elements()\n self.check_fluid_inputs_in_all_elements()\n self.check_nodes_attributes(coupled=True)\n if self.check_set_material:\n PrintMessageInput([title, material_message, window_title_1])\n return True\n elif self.check_set_fluid:\n PrintMessageInput([title, fluid_message, window_title_1])\n return True\n elif self.check_all_fluid_inputs:\n PrintMessageInput([title, all_fluid_inputs_message, window_title_1])\n return True\n elif self.check_set_crossSection:\n PrintMessageInput([title, cross_section_message, window_title_1])\n return True\n elif not self.is_there_volume_velocity:\n if not self.is_there_acoustic_pressure:\n PrintMessageInput([title, acoustic_message, window_title_1])\n return True","sub_path":"pulse/preprocessing/before_run.py","file_name":"before_run.py","file_ext":"py","file_size_in_byte":17730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"276268328","text":"# zadanie 1\r\ndef zadanie_1():\r\n a = input ('Podaj tekst: ')\r\n print('Spacja wystepuje', a.count(' '), 'razy')\r\n\r\n# zadanie 2\r\ndef zadanie_2():\r\n import sys\r\n print('Podaj pierwsza liczbe: ')\r\n a = sys.stdin.readline()\r\n a = int(a)\r\n print('Podaj druga liczbe: ')\r\n b = sys.stdin.readline()\r\n b = int(b)\r\n c = a*b\r\n print('Wynikiem mnozenia tych liczb jest:',c)\r\n # c = str(c)\r\n # sys.stdout.write(c)\r\n\r\n# zadanie 4\r\ndef zadanie_4():\r\n a = input ('Podaj liczbe: ')\r\n a = int(a)\r\n if a<0:\r\n a = a*-1\r\n print('Wartoscc bezwzgleda tej liczby to: ',a)\r\n else:\r\n print('Wartoscc bezwzgleda tej liczby to: ',a)\r\n\r\n# zadanie 5\r\ndef zadanie_5():\r\n a = input ('Podaj liczbe a: ')\r\n b = input ('Podaj liczbe b: ')\r\n c = input ('Podaj liczbe c: ')\r\n a = int(a)\r\n b = int(b)\r\n c = int(c)\r\n if (a>=0 and a<=10) and (a>b or b>c):\r\n print('Warunki spelnione\\n')\r\n else:\r\n print('Warunki nie zostaly spelnione')\r\n\r\n# zadanie 6\r\ndef zadanie_6():\r\n lista = [5,3,7,20,25,6,15]\r\n lista.sort()\r\n for x in lista:\r\n if(x % 5 == 0):\r\n print(str(x))\r\n\r\n# zadanie 7\r\ndef zadanie_7():\r\n lista = []\r\n for licznik in range(1, 6, 1):\r\n liczba = input('podaj '+str(licznik)+' liczbe: ')\r\n lista.append(int(liczba))\r\n for licznik in range(0, 5, 1):\r\n print(str(lista[licznik])+'^2 = '+str(lista[licznik]**2))\r\n\r\n# zadanie 8\r\ndef zadanie_8():\r\n lista = []\r\n i = 0\r\n while (i<5):\r\n liczba = input('podaj liczbe: ')\r\n lista.append(int(liczba))\r\n i=i+1\r\n lista.sort()\r\n print(lista)\r\n\r\n# zadanie 9\r\ndef zadanie_9():\r\n a = input('Podaj liczbe: ')\r\n a = int(a)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"wd_cw02.py","file_name":"wd_cw02.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"521031203","text":"#!/usr/bin/env python\n\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\nimport xbmc, xbmcgui, xbmcaddon\nimport os, sys, itertools, math\nimport xml.etree.ElementTree as et\nfrom operator import itemgetter\n\n__settings__ = xbmcaddon.Addon(id='script.service.kodimal')\n__cwd__ = __settings__.getAddonInfo('path')\n__icon__ = os.path.join(__cwd__, \"icon.png\")\n__scriptname__ = \"KodiMAL\"\n__configFile__ = xbmc.translatePath('special://profile/addon_data/script.service.kodimal/config.xml')\nBASE_RESOURCE_PATH = xbmc.translatePath( os.path.join(__cwd__, 'resources', 'lib' ) )\nsys.path.append(BASE_RESOURCE_PATH)\n\nimport myanimelist\n\nclass XML():\n def __init__(self, xmlFile=__configFile__):\n self.xmlFile = xmlFile\n self.tree = et.ElementTree()\n\n def parseConfig(self):\n \"\"\" Parses the configuration XML File, returns a list of XML Elements corresponding to the shows or an empty list\"\"\"\n try:\n self.tree.parse(self.xmlFile)\n except IOError:\n self.tree._setroot(et.Element('shows'))\n return []\n\n return self.tree.findall('show')\n\n def showInConfig(self, showid, season):\n \"\"\" Checks to see if a show is in the config file, based on show id and season, returns the appropriate mal id or false. \"\"\"\n if self.tree.findall('show') == []:\n return False\n try:\n for item in self.tree.iterfind('show'):\n if (item.attrib['xbmcID'] == str(showid)) and (item.attrib['season'] == str(season)):\n return item\n except:\n for item in self.tree.findall('show'):\n if (item.attrib['xbmcID'] == str(showid)) and (item.attrib['season'] == str(season)):\n return item\n return False\n\n def replace(self, oldItem, location, item):\n \"\"\" Replaces the item with the given id with the given item, returns list of XML Elements \"\"\"\n self.tree.getroot().remove(oldItem)\n self.tree.getroot().insert(location,item)\n return self.tree.findall('show')\n\n def add(self, showid, season, title, malid, maltitle, malepisodes, offset):\n \"\"\" Adds an item to the config file, returns a list of xml elements \"\"\"\n et.SubElement(self.tree.getroot(), 'show', attrib={'malID':str(malid), 'malTitle':maltitle, 'malEpisodes':str(malepisodes), 'xbmcID':str(showid), 'season':str(season), 'xbmcTitle':title, 'offset':offset})\n return self.tree.findall('show')\n\n def remove(self, item):\n self.tree.getroot().remove(item)\n\n def writeConfig(self):\n \"\"\" Writes the configuration xml file.\"\"\"\n o = output()\n o.log(__settings__.getLocalizedString(413), xbmc.LOGNOTICE)\n #Python 2.7\n try:\n self.tree.write(self.xmlFile, encoding=\"UTF-8\", xml_declaration=True)\n except:\n self.tree.write(self.xmlFile, encoding=\"UTF-8\")\n\nclass MAL():\n def __init__(self):\n self.mal = myanimelist.MAL((str(__settings__.getSetting(\"malUser\")), str(__settings__.getSetting(\"malPass\"))))\n self.mal.init_anime()\n self.a = self.mal.anime\n\nclass server():\n def __init__(self):\n pass\n\n def getXBMCshows(self):\n \"\"\" Gets all of the TV Shows from the XBMC library. Returns a list of shows if successful, empty list if not.\"\"\"\n json_query = xbmc.executeJSONRPC('{\"jsonrpc\":\"2.0\", \"method\":\"VideoLibrary.GetEpisodes\",\"params\":{\"properties\":[\"tvshowid\",\"season\",\"showtitle\",\"playcount\"], \"sort\": {\"method\":\"episode\"} }, \"id\":0}')\n json_query = unicode(json_query, 'utf-8', errors='ignore')\n json_response = json.loads(json_query)['result']\n\n gen_query = xbmc.executeJSONRPC('{\"jsonrpc\":\"2.0\", \"method\":\"VideoLibrary.GetTVShows\",\"params\":{\"properties\":[\"genre\"]}, \"id\":1}')\n gen_query = unicode(gen_query, 'utf-8', errors='ignore')\n gen_response = json.loads(gen_query)['result']['tvshows']\n genres = {}\n for genre in gen_response:\n genres[genre['tvshowid']] = genre['genre']\n\n if json_response.has_key('episodes'):\n json_response = json_response['episodes']\n tvshows = [list(group) for key,group in itertools.groupby(sorted(json_response,key=itemgetter('tvshowid')),key=itemgetter('tvshowid'))]\n\n tvshowdetails = []\n\n for tvshow in tvshows :\n seasons = [list(group) for key,group in itertools.groupby(sorted(tvshow, key=itemgetter('season')), key=itemgetter('season'))]\n tvshowdetail = {\"name\":tvshow[0]['showtitle'],\"tvshowid\":tvshow[0]['tvshowid'],\"seasons\":[],\"seasonall\":{},\"total\":len(tvshow),\"watched\":0,\"seasonwatched\":{}, \"genre\":genres[tvshow[0]['tvshowid']], \"rewatch\":{}}\n for season in seasons :\n tvshowdetail['seasons'].append(season[0]['season'])\n tvshowdetail['seasonall'][season[0]['season']] = len(season)\n rewatch = season[0]['playcount']\n for ep in season:\n if ep['playcount'] < rewatch:\n rewatch = ep['playcount']\n if ep['playcount'] > 0:\n tvshowdetail['watched'] += 1\n if ep['season'] in tvshowdetail['seasonwatched']:\n tvshowdetail['seasonwatched'][ep['season']] += 1\n else:\n tvshowdetail['seasonwatched'][ep['season']] = 1\n if rewatch > 0:\n rewatch -= 1\n tvshowdetail['rewatch'][season[0]['season']] = rewatch\n tvshowdetails.append(tvshowdetail)\n else:\n tvshowdetails = []\n\n return tvshowdetails\n\nclass output():\n def __init__(self):\n pass\n\n def notify(self, notice):\n \"\"\" Sends a notification to XBMC \"\"\"\n xbmc.executebuiltin(\"XBMC.Notification(%s,%s,%s,%s)\" % (__scriptname__,notice,10,__icon__))\n\n def log(self, msg, loglevel):\n \"\"\" Logs into the xbmc.log file \"\"\"\n if type(msg).__name__ == 'unicode':\n msg = msg.encode('utf-8')\n xbmc.log(\"### [%s] - %s\" %(__scriptname__,msg), level=loglevel)\n","sub_path":"script.service.kodimal/resources/lib/kodimal.py","file_name":"kodimal.py","file_ext":"py","file_size_in_byte":6274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"274405909","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 14 14:58:57 2021\n\n@author: hyewon\n\"\"\"\n\nimport izhikevich_cells as izh\n\nclass CCell(izh.izhCell):\n def __init__(self, stimVal):\n \"\"\"\n Has different variable values\n \"\"\"\n super().__init__(stimVal)\n self.celltype = 'Chattering' \n self.C=50\n self.vr=-60\n self.vt=-40\n self.k=1.5\n self.a=0.03\n self.b=1\n self.c=-40\n self.d=150\n self.vpeak=25\n \n def createCell():\n \"\"\"\n overrides the izh function and creates CCell instead of izhikevich cell\n \"\"\"\n myCell = CCell(stimVal=200) \n myCell.simulate()\n izh.plotMyData(myCell)\n \n \n#myCell = CCell(4000)\n#myCell.simulate()\n\nif __name__=='__main__':\n CCell.createCell()","sub_path":"chattering_cell.py","file_name":"chattering_cell.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"633782075","text":"# GPIO Zero: a library for controlling the Raspberry Pi's GPIO pins\n# Copyright (c) 2016-2019 Dave Jones \n# Copyright (c) 2016 Andrew Scheller \n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom __future__ import (\n unicode_literals,\n print_function,\n absolute_import,\n division,\n )\nstr = type('')\n\nfrom threading import Thread, Event\n\nfrom .exc import ZombieThread\n\n\n_THREADS = set()\ndef _threads_shutdown():\n while _THREADS:\n threads = _THREADS.copy()\n # Optimization: instead of calling stop() which implicitly calls\n # join(), set all the stopping events simultaneously, *then* join\n # threads with a reasonable timeout\n for t in threads:\n t.stopping.set()\n for t in threads:\n t.join(10)\n\n\nclass GPIOThread(Thread):\n def __init__(self, group=None, target=None, name=None, args=(), kwargs=None):\n if kwargs is None:\n kwargs = {}\n self.stopping = Event()\n super(GPIOThread, self).__init__(group, target, name, args, kwargs)\n self.daemon = True\n\n def start(self):\n self.stopping.clear()\n _THREADS.add(self)\n super(GPIOThread, self).start()\n\n def stop(self, timeout=10):\n self.stopping.set()\n self.join(timeout)\n\n def join(self, timeout=None):\n super(GPIOThread, self).join(timeout)\n if self.is_alive():\n assert timeout is not None\n # timeout can't be None here because if it was, then join()\n # wouldn't return until the thread was dead\n raise ZombieThread(\n \"Thread failed to die within %d seconds\" % timeout)\n else:\n _THREADS.discard(self)\n","sub_path":"logs/finals/can/pi/.local/lib/python3.5/site-packages/gpiozero/threads.py","file_name":"threads.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"448660370","text":"class Solution:\n # 往上下左右四个方向进行DFS。\n # 需要注意的就是访问一个字母后visited标识1,\n # 当DFS调用返回后,如果还没有找完,应该让visited置0,并返回false\n def exist(self, board, word):\n if len(word) == 0:\n return False\n for i in range(len(board)):\n for j in range(len(board[0])):\n if self.dfs(board, word, 0, i, j): \n # i,j是一开始遍历的位置\n return True\n return False\n \n def dfs(self, board, word, index, x, y):\n # 递归的出口\n if not board or index == len(word):\n return True\n # 是否越界\n if x < 0 or x == len(board) or y < 0 or y == len(board[0]):\n return False\n # 不是要找的元素\n if board[x][y] != word[index]:\n return False\n # 这几句什么意思?? \n source = board[x][y]\n board[x][y] = '\\0' # 表示此位置已经访问过,‘1’也可以,访问过的元素不再访问\n # 递归变成了四个方向的递归判断 \n exist = self.dfs(board, word, index + 1, x, y + 1) or self.dfs(board, word, index + 1, x, y - 1) or self.dfs(\n board, word, index + 1, x + 1, y) or self.dfs(board, word, index + 1, x - 1, y)\n board[x][y] = source \n return exist\n\n\"\"\"\n这实际上还是一个回溯法解决的问题。例如,对于word = 'ABCCED',\n我们从第一个元素开始,首先匹配到A,然后向后面寻找。\n我们规定好寻找的顺序为:⬆️,➡️,⬇️,⬅️。我们接着找B,上面越界,右边找到了。\n我们接着找C,上面越界,右边找到了。我们接着找C,上面越界了,右边不对,下面找到了。\n接着找E,我们发现上面访问过,不再访问。接着向右查找,发现不匹配,接着向下查找,\n发现越界了,接着想做查找,OK!我们所有元素匹配成功。\n\"\"\"\n\n\nif __name__ == \"__main__\":\n board =[['A','B','C','E'],['S','F','C','S'],['A','D','E','E']]\n word = \"ABCCED\"\n res = Solution()\n print(res.exist(board,word))\n ","sub_path":"DFS与BFS与递归/79-单词搜索.py","file_name":"79-单词搜索.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"141245669","text":"import os\n\nfrom dvc.command.common.base import CmdBase\nfrom dvc.config import ConfigI\nfrom dvc.logger import Logger\nfrom dvc.state_file import StateFile\nfrom dvc.path.data_item import DataItem\nfrom dvc.system import System\nfrom dvc.command.checkout import CmdCheckout\n\n\nclass CmdMerge(CmdBase):\n def __init__(self, settings):\n super(CmdMerge, self).__init__(settings)\n\n def print_info(self, targets):\n for item in targets:\n Logger.info('Restored original data after merge:')\n Logger.info(' {}'.format(item.data.relative))\n\n def collect_data(self):\n dlist = []\n flist = self.git.get_last_merge_changed_files()\n for fname in flist:\n if fname.endswith(DataItem.STATE_FILE_SUFFIX):\n data = fname[:-len(DataItem.STATE_FILE_SUFFIX)]\n dlist.append(data)\n return dlist\n\n def collect_targets(self):\n targets = []\n flist = self.collect_data()\n items = self.settings.path_factory.to_data_items(flist)[0]\n\n for item in items:\n command = StateFile.load(item)\n\n if not command.cmd and command.locked:\n targets.append(item)\n\n return targets\n\n def checkout_targets(self, targets):\n data = []\n for item in targets:\n prev_state = StateFile.loads(self.git.get_file_content_before_last_merge(item.state.relative))\n curr_state = StateFile.load(item)\n\n state = StateFile(data_item=item,\n cmd=curr_state.cmd,\n out=curr_state.out,\n out_git=curr_state.out_git,\n locked=curr_state.locked,\n deps=curr_state.deps,\n md5=prev_state.md5)\n state.save()\n\n CmdCheckout.checkout([item])\n\n msg = 'DVC merge files: {}'.format(' '.join(data))\n self.commit_if_needed(msg)\n\n def run(self):\n targets = self.collect_targets()\n if not targets:\n return 1\n\n self.checkout_targets(targets)\n self.print_info(targets)\n\n return 0\n","sub_path":"dvc/command/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"562844241","text":"def encrypt(number):\n if type(number) is not int or number < 1:\n raise ValueError('The number must be an integer greater than 0 (zero)')\n\n result = ()\n\n while number > 0:\n if number % 2 == 0:\n coded_digit = (number + 2) % 10\n else:\n coded_digit = (number - 2) % 10\n\n number = number // 10\n result = (coded_digit,) + result\n\n return result\n","sub_path":"cap4/ex7.py","file_name":"ex7.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"258262786","text":"\nimport numpy as np\nimport Environment\nimport tensorflow as tf\nimport random\nimport math\nimport os\nimport cv2\n\nMAX_MEMORY_SIZE = 350\n# hyperparameters\nn_obs = 100 * 50 # dimensionality of observations\nh = 200 # number of hidden layer neurons\nn_actions = 4 # number of available actions\nlearning_rate = 1e-4\ngamma = .90 # discount factor for reward\n\ndecay = 0.99 # decay rate for RMSProp gradients\nsave_path = 'models_Attemp21/Attempt21'\nINITIAL_EPSILON = 1\n\n# gamespace\ndisplay = False\ngame=Environment.GameV1(display)\ngame.populateGameArray()\nprev_x = None\nxs, rs, rs2, ys = [], [], [], []\nrunning_reward = None\nreward_sum = 0\nobservation = np.zeros(shape=(200,300))\nepisode_number = 0\n\n\n# initialize model\ntf_model = {}\nwith tf.variable_scope('layer_one', reuse=False):\n xavier_l1 = tf.truncated_normal_initializer(mean=0, stddev=1. / np.sqrt(n_obs), dtype=tf.float32)\n tf_model['W1'] = tf.get_variable(\"W1\", [n_obs, h], initializer=xavier_l1)\n tf_model['b1'] = tf.Variable(tf.truncated_normal([h], stddev=1./np.sqrt(h), dtype=tf.float32), name='b1')\nwith tf.variable_scope('layer_two', reuse=False):\n xavier_l2 = tf.truncated_normal_initializer(mean=0, stddev=1. / np.sqrt(h), dtype=tf.float32)\n tf_model['W2'] = tf.get_variable(\"W2\", [h, n_actions], initializer=xavier_l2)\n tf_model['b2'] = tf.Variable(tf.truncated_normal([n_actions], stddev=.5, dtype=tf.float32), name=\"b2\")\ndef discount_rewards(rewardarray):\n\n gamenumber = 0\n episodeoneend = 0\n for i in range(len(rewardarray)):\n if rewardarray[i] > 0:\n if gamenumber ==0:\n rewardarray[i] = (177-i)/30 * rewardarray[i] *2\n episodeoneend = i\n gamenumber +=1\n else:\n rewardarray[i] = (177 - (i - episodeoneend)) / 30 * rewardarray[i] * 2\n gamenumber += 1\n episodeoneend = i\n\n elif rewardarray[i] < 0:\n rewardarray[i] = rewardarray[i] * math.pow(3, (170-i)/170)\n gamenumber += 1\n episodeoneend = i\n else:\n rewardarray[i] = rewardarray[i]\n\n rewardarray.reverse()\n for i in range(len(rewardarray) -1):\n\n rewardarray[i+1] = rewardarray[i] * gamma\n rewardarray.reverse()\n return rewardarray\ndef discount_smallrewards(rewardarray):\n rewardarray.reverse()\n\n for i in range(len(rewardarray) -1):\n if rewardarray[i] != 0:\n rewardarray[i] = rewardarray[i] * 15\n rewardarray.reverse()\n return rewardarray\n\n\n# tf operations\ndef tf_discount_rewards(tf_r): # tf_r ~ [game_steps,1]\n discount_f = lambda a, v: a * gamma + v;\n tf_r_reverse = tf.scan(discount_f, tf.reverse(tf_r, [True, False]))\n tf_discounted_r = tf.reverse(tf_r_reverse, [True, False])\n return tf_discounted_r\n\n\ndef tf_policy_forward(x): # x ~ [1,D]\n h = tf.matmul(x, tf_model['W1']) + tf_model['b1']\n h = tf.nn.relu(h)\n logp = tf.matmul(h, tf_model['W2']) + tf_model['b2']\n p = tf.nn.softmax(logp)\n return p\n\ndef displayImage(image):\n __debug_diff__ = False\n if __debug_diff__:\n cv2.namedWindow(\"debug image\")\n cv2.imshow('debug image', image)\n cv2.waitKey(100)\n cv2.destroyWindow(\"debug image\")\n\n\ndef prepro(I):\n \"\"\" prepro 210x160x3 uint8 frame into 5000 (50x100) 1D float vector \"\"\"\n I = I[::4, ::3] # downsample by factor of 2\n return I.astype(np.float)\n\ndef diff(X0, X1):\n X0[X0==0.5] = 0 # erase the player car in the first image\n diff_image = X1 - X0\n\n displayImage(diff_image)\n return diff_image\n\n# tf placeholders\ntf_x = tf.placeholder(dtype=tf.float32, shape=[None, n_obs], name=\"tf_x\")\ntf_y = tf.placeholder(dtype=tf.float32, shape=[None, n_actions], name=\"tf_y\")\ntf_epr = tf.placeholder(dtype=tf.float32, shape=[None, 1], name=\"tf_epr\")\n\n# tf reward processing (need tf_discounted_epr for policy gradient wizardry)\n#tf_discounted_epr = tf_discount_rewards(tf_epr)\ntf_mean, tf_variance = tf.nn.moments(tf_epr, [0], shift=None, name=\"reward_moments\")\ntf_epr_normed = tf_epr - tf_mean\ntf_epr_normed /= tf.sqrt(tf_variance + 1e-6)\n\n\n# tf optimizer op\ntf_aprob = tf_policy_forward(tf_x)\nl2_loss = tf.nn.l2_loss(tf_y - tf_aprob, name=\"tf_l2_loss\")\noptimizer = tf.train.RMSPropOptimizer(learning_rate, decay=decay)\ntf_grads = optimizer.compute_gradients(l2_loss, var_list=tf.trainable_variables(), grad_loss=tf_epr)\ntrain_op = optimizer.apply_gradients(tf_grads)\n\n\n# write out losses to tensorboard\ngrad_summaries = []\nfor g, v in tf_grads:\n if g is not None:\n grad_hist_summary = tf.summary.histogram(\"{}/grad/hist\".format(v.name), g)\n sparsity_summary = tf.summary.scalar(\"{}/grad/sparsity\".format(v.name), tf.nn.zero_fraction(g))\n grad_summaries.append(grad_hist_summary)\n grad_summaries.append(sparsity_summary)\ngrad_summaries_merged = tf.summary.merge(grad_summaries)\n\nl2_loss_summary = tf.summary.scalar(\"l2_loss\", l2_loss)\n\ntrain_summary_op = tf.summary.merge([l2_loss_summary, grad_summaries_merged])\n\n\n# tf graph initialization\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\n\n\n\n# try load saved model\nsaver = tf.train.Saver(tf.global_variables())\nload_was_success = True # yes, I'm being optimistic\ntry:\n save_dir = '/'.join(save_path.split('/')[:-1])\n ckpt = tf.train.get_checkpoint_state(save_dir)\n load_path = ckpt.model_checkpoint_path\n saver.restore(sess, load_path)\nexcept:\n print(\n \"no saved model to load. starting new session\")\n load_was_success = False\nelse:\n print(\n \"loaded model: {}\".format(load_path))\n saver = tf.train.Saver(tf.global_variables())\n episode_number = int(load_path.split('-')[-1])\n\n\ntrain_summary_dir = os.path.join(save_dir, \"summaries\", \"train\")\ntrain_summary_writer = tf.summary.FileWriter(train_summary_dir, sess.graph)\nx = np.zeros(n_obs)\n# training loop\nepsilon = math.pow(0.5, episode_number/1000)\n\nwait_time = 1\nwaited_time = 0\n\nwhile True:\n\n\n # preprocess the observation, set input to network to be difference image\n cur_x = prepro(observation)\n x = cur_x - prev_x if prev_x is not None else np.zeros(n_obs)\n\n prev_x = cur_x\n #x = observation\n\n if waited_time < wait_time:\n action = 0\n waited_time += 1\n observation, reward, smallreward, done = game.runGame(action, False)\n else:\n\n\n # stochastically sample a policy from the network\n feed = {tf_x: np.reshape(x, (1, -1))}\n aprob = sess.run(tf_aprob, feed);\n aprob = aprob[0, :]\n\n if random.random() < epsilon:\n action = random.randint(0, n_actions-1)\n else:\n action = np.random.choice(n_actions, p=aprob)\n #action = np.random.choice(n_actions, p=aprob)\n observation, reward, smallreward, done = game.runGame(action, False)\n\n\n\n label = np.zeros_like(aprob);\n label[action] = 1\n\n # step the environment and get new measurements\n\n reward_sum += reward\n\n # record game history\n # if len(rs) < MAX_MEMORY_SIZE:\n # xs.append(x)\n # ys.append(label)\n # rs.append(reward)\n #else:\n # xs.pop(0)\n # ys.pop(0)\n # rs.pop(0)\n #if np.shape(x) == (2):\n x= np.reshape(x, [-1])\n xs.append(x)\n ys.append(label)\n rs.append(reward)\n rs2.append(smallreward)\n #if smallreward > 0:\n\n if done:\n #reset\n waited_time = 0\n prev_x = None\n\n\n # update running reward\n epsilon = math.pow(0.5, episode_number / 1000)\n running_reward = reward_sum if running_reward is None else running_reward * 0.99 + reward_sum * 0.01\n running = len(rs)\n\n if episode_number % 2:\n #if True:\n\n rs2 = discount_smallrewards(rs2)\n rs = discount_rewards(rs)\n\n for i in range(len(rs)):\n rs[i] += rs2[i]\n\n excess = len(rs) - MAX_MEMORY_SIZE\n if excess < 0:\n excess = 0\n if excess > 0:\n for i in range(excess):\n rsabs = []\n for i in range(len(rs)):\n rsabs.append(math.fabs(rs[i]))\n lowest = np.argmin(rsabs)\n rsabs = []\n rs.pop(lowest)\n xs.pop(lowest)\n ys.pop(lowest)\n\n\n\n x_t = np.vstack(xs)\n r_t = np.vstack(rs)\n y_t = np.vstack(ys)\n\n # parameter update\n feed = {tf_x: x_t, tf_epr: r_t, tf_y: y_t}\n _, train_summaries = sess.run([train_op, train_summary_op], feed)\n\n epr_val, mean_val, variance_val, l2_loss_val = sess.run([tf_epr_normed, tf_mean, tf_variance, l2_loss], feed)\n # bookkeeping\n xs, rs, rs2, ys = [], [], [], [] # reset game history\n\n train_summary_writer.add_summary(train_summaries, episode_number)\n # print progress console\n if episode_number % 5 == 0:\n print(\n 'ep {}: reward: {}, mean reward: {:3f}, running: {}'.format(episode_number, reward_sum, running_reward, running))\n else:\n print(\n '\\tep {}: reward: {}'.format(episode_number, reward_sum))\n\n\n episode_number += 1 # the Next Episode\n\n reward_sum = 0\n if episode_number % 1000 == 0:\n saver.save(sess, save_path, global_step=episode_number)\n print(\n \"SAVED MODEL #{}\".format(episode_number))\n","sub_path":"RLAttempt4.py","file_name":"RLAttempt4.py","file_ext":"py","file_size_in_byte":9697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"498546129","text":"#find intersection point of two linked list\n\nclass Node:\n def __init__(self,data):\n self.data = data\n self.next = None\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n \n def printList(self):\n temp = self.head\n while(temp):\n print(temp.data)\n temp = temp.next\n \n def insert(self, data):\n new = Node(data)\n new.next = self.head\n self.head = new\n return new\n\ndef findIntersectionPoint(ll1, ll2):\n size1 = findSize(ll1)\n size2 = findSize(ll2)\n diff = abs(size1 - size2)\n head1 = ll1.head\n head2 = ll2.head\n if size1 > size2:\n for i in range(diff):\n head1 = head1.next\n elif size2 > size1:\n for i in range(diff):\n head2 = head2.next\n while(head1 and head2):\n if(head1 == head2):\n return head1.data\n head1 = head1.next\n head2 = head2.next\n\n return False\n\ndef findSize(ll):\n head = ll.head\n count = 0\n while(head):\n count += 1\n head = head.next\n return count\n\nllist = LinkedList()\nllist.insert(1)\nllist.insert(2)\nllist.insert(3)\nllist.insert(2)\nllist.insert(1)\n\nllist2 = LinkedList()\nllist2.insert(4)\nllist2.head.next = llist.head.next.next\nprint(findIntersectionPoint(llist, llist2))","sub_path":"LinkedList/2_7.py","file_name":"2_7.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"437327270","text":"\"\"\"\nScript that does all the major work\nThis gets the lyrics\n\"\"\"\nimport re\nimport dbus\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nbrowser = webdriver.PhantomJS(executable_path=\"../browser/phantomjs\")\n\n\ndef open_link(link):\n \"\"\"\n Function to open the link\n Searching for the song\n \"\"\"\n browser.get(link)\n try:\n target = browser.find_element(\n By.XPATH, \"//td[@class='text-left visitedlyr']\")\n to_click = target.find_element(By.TAG_NAME, 'a')\n lyric_page = to_click.get_attribute('href')\n return lyric_page\n except:\n return 'error'\n\n\ndef get_lyrics(link):\n \"\"\"\n Function to go to the first choice on AZLyrics\n And fetch the lyrics\n \"\"\"\n browser.get(link)\n title = browser.find_element(By.TAG_NAME, 'h1')\n\n wording = browser.find_element(\n By.XPATH, \"//div[@class='ringtone']/following-sibling::div\")\n\n lyrics = title.text + '\\n\\n' + wording.text\n return lyrics\n\n\ndef print_lyrics():\n \"\"\"\n Display the fetched lyrics to the user\n \"\"\"\n song_info = get_spotify_song_data()\n song_name = remove_braces(song_info['title'])\n song_name = song_name.lower()\n song_artist = song_info['artist']\n song_artist = song_artist.lower()\n songn = song_name.replace(\" \", \"+\")\n songa = song_artist.replace(\" \", \"+\")\n if 'mad world' in song_name:\n query = 'mad+world+gary+jules'\n elif 'run' in song_name and 'bts' == song_artist:\n query = 'run+run+bts'\n else:\n query = songn + '+' + songa\n print(query)\n link = \"https://search.azlyrics.com/search.php?q=\" + query\n link = open_link(link)\n special_case = ('advertisement', 'spotify')\n if song_name in special_case:\n lyrics = \"Buy Spotify Premium\"\n elif link == 'error':\n lyrics = \"Lyrics not found on AZLyrics\"\n else:\n lyrics = get_lyrics(link)\n return lyrics\n\n\ndef remove_braces(string):\n \"\"\"\n Remove braces from song name\n like (ft. Alouette)\n \"\"\"\n string = re.sub(r\"\\(.*\\)\", \"\", string)\n string = re.sub(r\"\\[.*\\]\", \"\", string)\n return string\n\n\ndef get_spotify_song_data():\n \"\"\"\n Function to read the song\n being played on Spotify\n \"\"\"\n session_bus = dbus.SessionBus()\n spotify_bus = session_bus.get_object(\n \"org.mpris.MediaPlayer2.spotify\", \"/org/mpris/MediaPlayer2\")\n spotify_properties = dbus.Interface(\n spotify_bus, \"org.freedesktop.DBus.Properties\")\n metadata = spotify_properties.Get(\n \"org.mpris.MediaPlayer2.Player\", \"Metadata\")\n title = metadata['xesam:title'].encode(\n 'utf-8').decode('utf-8').replace(\"&\", \"&\")\n artist = metadata['xesam:artist'][0].encode(\n 'utf-8').decode('utf-8').replace(\"&\", \"&\")\n if '&' in title:\n title = title.replace(\"&\", \"%26\")\n if '&' in artist:\n artist = artist.replace(\"&\", \"%26\")\n return {'title': title, 'artist': artist}\n","sub_path":"LyFy(Tkinter)/main/lyfy.py","file_name":"lyfy.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"335257855","text":"# -*- coding: UTF-8 -*-\n'''\nCreated on 2021/1/12 16:06\n@File : get_kicp_ner_align.py\n@author: ZL\n@Desc :\n'''\n\nimport json\nimport requests\n\n\ndef ner_align_test(str):\n string = str\n # 10.13.8.230:8246\n # http://192.168.26.105:30246\n url = 'http://10.13.8.230:8246/entity_align/andrology/v1'\n URL = 'http://192.168.26.105:30248/ner/v1?utterance={}&model_name={}'.format(string, 'andrology')\n print(requests.get(URL.format(string, 'andrology')).json())\n params = {\n 'sentence': string,\n 'entity': json.dumps(requests.get(URL.format(string, 'andrology')).json()['data'])\n }\n print(params)\n print(requests.post(url, data=params).json())\n if len(requests.post(url, data=params).json()[\"align\"].get(\"item\")) != 0:\n return {\"item\": requests.post(url, data=params).json()[\"align\"].get(\"item\")[0]}\n elif len(requests.post(url, data=params).json()[\"align\"].get(\"symptom\")) != 0:\n return {\"symptom\": requests.post(url, data=params).json()[\"align\"].get(\"symptom\")[0]}\n else:\n return {\"无项目\": \"无项目\"}\n\n\ndef get_knowledge(industry, str):\n if industry == \"andrology\":\n align_url = 'http://192.168.26.105:30246/entity_align/andrology/v1'\n ner_url = 'http://192.168.26.105:30248/ner/v1?utterance={}&model_name={}'.format(str, 'andrology')\n # intention_url = 'http://192.168.26.105:30250/andrology_intent_kicp/v2?utterance={}'.format(str)\n elif industry == \"gynaecology\":\n align_url = 'http://192.168.26.105:30243/entity_align/gynaecology/v1'\n ner_url = 'http://192.168.26.105:30253/ner/v1?utterance={}&model_name={}'.format(str, 'gynaecology')\n # intention_url = 'http://192.168.26.105:30255/intention/v2/kicp_gynaecology?utterance={}'.format(str)\n\n\n # http://10.13.8.230:8201/knowledge_graph/v1/answer / http://192.168.26.105:30249/kbqa/v1\n # http://192.168.26.105:30201/knowledge_graph/v1/answer\n # 预生产:http://10.14.250.11:30249/kbqa/v1\n # 线上: http://10.13.8.12:30249/kbqa/v1\n # 不走负载均衡 :10.12.8.15:30201\n # 249: /10.0.210.249\n knowledge_url = \"http://10.12.8.11:30249/kbqa/v1\"\n source_entities = json.dumps(requests.get(ner_url.format(str, 'andrology')).json()['data'])\n align_params = {\n 'sentence': str,\n 'entity': source_entities\n }\n align_entities = eval(json.dumps(requests.post(align_url, data=align_params).json()[\"align\"]))\n # intention = requests.get(intention_url.format(str)).json()['data'][\"intent\"]\n params = {\n \"department\": industry,\n 'sentence': str,\n 'source_entities': eval(source_entities),\n 'aligned_entities': align_entities,\n 'intention': ''\n }\n print(params)\n result = requests.post(knowledge_url, json=params)\n print(result.json(), result.elapsed.total_seconds())\n\n\nget_knowledge(\"gynaecology\", \"多囊卵巢综合症有哪些表现啊\")\n","sub_path":"kicp/get_kicp_ner_align.py","file_name":"get_kicp_ner_align.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"64935546","text":"from flask import render_template, g\nfrom flask_login import current_user\nimport flask_menu as menu\n\nfrom app import app, lm\nfrom app.user.models import User\nfrom app.contest.models import Contest\nfrom app.submission.models import Submission\nfrom app.common.tasks import run_code\nfrom app.common.utils import generate_random_string\n\n\n@app.before_request\ndef before_request():\n g.user = current_user\n\n\n@lm.user_loader\ndef load_user(user_id):\n return User.query.get(int(user_id))\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n@app.route('/')\n@app.route('/index')\n@menu.register_menu(app, '.index', 'Home', order=0)\ndef index():\n contests = Contest.query.order_by(Contest.id.desc()).all()\n return render_template(\n 'index.html',\n contests=contests\n )\n\n\n@app.route('/')\n@app.route('/scoreboard')\n@menu.register_menu(app, '.scoreboard', 'Score Board', order=1)\ndef scoreboard():\n users = User.query.all()\n raw = {}\n for user in users:\n for submission in user.submissions:\n if submission.is_accepted():\n if not raw.has_key(submission.user.email):\n raw[submission.user.email] = 0\n raw[submission.user.email] += submission.received_point\n\n summary = [(email, total_score) for email, total_score in raw.items()]\n summary = sorted(summary, key=lambda x: x[1], reverse=True)\n max_score = summary[0][1]\n\n return render_template(\n 'scoreboard.html',\n max_score=max_score,\n summary=summary\n )\n\n@app.route('/howto')\n@menu.register_menu(app, '.howto', 'How to', order=2)\ndef howto():\n return render_template('howto.html')","sub_path":"app/common/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"389433637","text":"# actions: 0 for left, 1 for right, 2 for up, 3 for down\n\nclass state:\n Array_States={}\n def __init__(self,Q,Q2,reward,i,j):\n self.Q=Q\n self.Q2=Q2\n self.reward=reward\n self.i=i\n self.j=j\n self.optimal_action=0\n\n# implements state transition function\n def state_transition(self,action,i,j,n):\n if (action==0):\n if(j==0):\n return (i,j)\n if(j!=0):\n return (i,j-1)\n if (action==1):\n if(j==n-1):\n return (i,j)\n if(j!=n-1):\n return (i,j+1)\n if (action==2):\n if(i==0):\n return (i,j)\n if(i!=0):\n return (i-1,j)\n if (action==3):\n if(i==n-1):\n return (i,j)\n if(i!=n-1):\n return (i+1,j)","sub_path":"SARSA/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"360340668","text":"\"\"\"\n This is the communicator file for the HomeServer proxy.\n Here are specified the communicator class, used to interconnect proxy and CoAP server\n and a helper Response class, used to ease the management of CoAP responses\n\"\"\"\nfrom coapthon.client.helperclient import HelperClient\nfrom coapthon import defines\nfrom utils import AppError\n\n__author__ = \"Jose Requeijo Dias\"\n\nclass Communicator(object):\n \"\"\"\n This represents a CoAP communicator. It is used to establish connections\n and send data to the CoAP server.\n \"\"\"\n def __init__(self, host, port=5683):\n\n self.host = host\n self.port = port\n self.client = None\n\n def start(self):\n \"\"\"\n This method starts a new communicator.\n \"\"\"\n self.client = HelperClient(server=(self.host, self.port))\n\n def stop(self):\n \"\"\"\n This method stops a communicator.\n \"\"\"\n self.client.stop()\n\n def restart(self):\n \"\"\"\n This method restarts a communicator.\n \"\"\"\n self.stop()\n self.start()\n\n def get(self, path, timeout=None):\n \"\"\"\n This method send a get message to the resource specified by path\n on the CoAP server. It waits timeout seconds to receive the response \n to the get call.\n \"\"\"\n try:\n self.start()\n resp = self.client.get(path, timeout=timeout)\n except:\n self.stop()\n raise AppError(504, \"Connection Timeout. Home Server is down.\")\n\n self.stop()\n\n return resp\n\n def post(self, path, payload, timeout=None):\n \"\"\"\n This method send a post message to the resource specified by path\n on the CoAP server with the payload JSON message. It waits timeout\n seconds to receive the response to the post call.\n \"\"\"\n try:\n self.start()\n resp = self.client.post(path, (defines.Content_types[\"application/json\"],\\\n payload), timeout=timeout)\n except:\n self.stop()\n raise AppError(504, \"Connection Timeout. Home Server is down.\")\n self.stop()\n\n return resp\n\n def put(self, path, payload=\"\", timeout=None):\n \"\"\"\n This method send a put message to the resource specified by path\n on the CoAP server with the payload JSON message. It waits timeout\n seconds to receive the response to the put call.\n \"\"\"\n try:\n self.start()\n resp = self.client.put(path, (defines.Content_types[\"application/json\"],\\\n payload), timeout=timeout)\n except:\n self.stop()\n raise AppError(504, \"Connection Timeout. Home Server is down.\")\n self.stop()\n\n return resp\n\n def delete(self, path, timeout=None):\n \"\"\"\n This method send a delete message to the resource specified by path\n on the CoAP server. It waits timeout seconds to receive the response\n to the delete call.\n \"\"\"\n try:\n self.start()\n resp = self.client.delete(path, timeout=timeout)\n except:\n self.stop()\n raise AppError(504, \"Connection Timeout. Home Server is down.\")\n self.stop()\n\n return resp\n\n def discover(self, path, timeout=None):\n \"\"\"\n This method send a discover message to the resource specified by path\n on the CoAP server. It waits timeout seconds to receive the response\n to the discover call.\n \"\"\"\n try:\n self.start()\n resp = self.client.discover(path, timeout=timeout)\n except:\n self.stop()\n raise AppError(504, \"Connection Timeout. Home Server is down.\")\n self.stop()\n\n return resp\n\n def get_response(self, data):\n \"\"\"\n This method use the data received in response to a call, to\n construct a Response object that can be easily used to manage the\n response data.\n \"\"\"\n return Response(data)\n\nclass Response(object):\n \"\"\"\n This represents a Response to a call made by the communicator to the\n CoAP server.\n \"\"\"\n def __init__(self, data):\n self.payload = data.payload\n self.code = data.code\n self.content_type = [k for k in defines.Content_types if defines.Content_types[k] == data.content_type]\n self.content_type = self.content_type[0]\n\n def data(self):\n \"\"\"\n This method returns a dictionary with a simple representation of the data received.\n \"\"\"\n return {\"payload\":self.payload, \"code\":self.code, \"content-type\":self.content_type}\n\n def __str__(self):\n return \"\\nPayload:\"+str(self.payload)+\"\\nCode:\"+\\\n str(self.code)+\"\\nContent-Type:\"+str(self.content_type)+\"\\n\"\n","sub_path":"proxy/communicator.py","file_name":"communicator.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"487521349","text":"import dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nfrom dash.dependencies import Input, Output\r\nimport plotly.graph_objs as go\r\nimport pandas as pd\r\nimport numpy as np\r\nimport plotly.offline as pyo\r\nfrom plotly import subplots\r\nimport math\r\nimport chart_studio\r\n\r\n\r\n\r\ndf = pd.read_csv('../assets/liga/mf_pass.csv')\r\n\r\nclubs = df['Club'].unique()\r\n\r\ndf_by_season = df[df['Season'] == '2019-2020']\r\n\r\nfig = subplots.make_subplots(rows=7, cols=3, subplot_titles=(clubs))\r\n\r\n\r\n# print(df_by_season[['Name','Cmpper']])\r\n# print(df_by_cmpper)\r\n# print(df_by_season['Name'].unique())\r\napp = dash.Dash()\r\n# s = len(df_by_season['Name'].unique())\r\n\r\n\r\n\r\nrow = 1\r\ncol = 1\r\n\r\nfor club in clubs:\r\n df_by_club = df_by_season[df_by_season['Club'] == club]\r\n # print(df_by_club)\r\n\r\n CMPPER = df_by_club['Cmpper']\r\n\r\n NAMES = []\r\n for name in df_by_club['Name'].unique():\r\n if ' ' in name:\r\n name = name.split()\r\n name = name[-1]\r\n NAMES.append(name)\r\n\r\n graph = go.Bar(\r\n x=CMPPER,\r\n y=NAMES,\r\n name=club.title(),\r\n text=CMPPER,\r\n textposition='auto',\r\n orientation='h'\r\n )\r\n\r\n fig.append_trace(graph, row, col)\r\n col += 1\r\n if col == 4:\r\n col = 1\r\n row += 1\r\n if row == 8:\r\n break\r\n\r\n\r\nfig['layout'].update(\r\n height=1500,\r\n width=1000,\r\n # title='Pass'\r\n # xaxis_type=\"linear\", yaxis_type=\"log\",\r\n margin={\r\n # 'l': 50, 'r': 50, 't': 50, 'b': 50,\r\n 'autoexpand': True\r\n },\r\n # padding={'l': 20, 'r':30},\r\n font={\"family\": \"Cursive,Monospace\", \"size\": 12},\r\n paper_bgcolor=\"#fff\",\r\n # plot_bgcolor=\"#fff\"\r\n # template=\"plotly_dark\"\r\n)\r\napp.layout = html.Div([\r\n\r\n html.Div([\r\n dcc.Graph(\r\n id='pass',\r\n figure=fig,\r\n\r\n\r\n\r\n )\r\n ])\r\n],style=dict(display='flex', justifyContent='center')\r\n)\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)\r\n","sub_path":"statics/liga_mf.py","file_name":"liga_mf.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"634151971","text":"from PySide import QtGui\nimport cmt.cqueue.core as core\nimport cmt.cqueue.fields as fields\nimport cmt.deform.skinio as skinio\n\n\nclass Component(core.Component):\n \"\"\"A Component that imports skin weights using skinio.\"\"\"\n\n @classmethod\n def image(cls, size=32):\n return QtGui.QPixmap(':/importSmoothSkin.png').scaled(size, size)\n\n def __init__(self, file_paths=None, **kwargs):\n super(Component, self).__init__(**kwargs)\n self.array_field = fields.ArrayField(name='File Paths', add_label_text='Add Skin File', display_name=False,\n parent=self)\n if file_paths is None:\n file_paths = ['']\n if isinstance(file_paths, basestring):\n file_paths = [file_paths]\n for file_path in file_paths:\n fields.FilePathField(\n name='File Path',\n value=file_path,\n filter='Skin Files (*.skin)',\n help_text='The Skeleton file path.',\n parent=self.array_field)\n\n def execute(self):\n for file_field in self.array_field:\n file_path = file_field.value()\n skinio.import_skin(file_path)\n\n","sub_path":"scripts/cmt/cqueue/components/deform/skin.py","file_name":"skin.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"125024231","text":"import json\nimport multiprocessing as mp\n\nfrom aqbot.bot import AQBot\n\n\nclass BotFactory:\n AQBOT_CONF = 'conf/aqbot.conf'\n bots = []\n\n def __init__(self):\n try:\n with open(self.AQBOT_CONF) as f:\n config = json.load(f)\n except IOError:\n exit(1)\n except:\n exit(1)\n\n try:\n for network in config['networks']:\n for channel in network['channels']:\n worker = mp.Process(target=self._connect, args=(network, channel,))\n worker.start()\n except:\n exit(1)\n\n def _connect(self, network, channel):\n bot = AQBot(network, channel)\n self.bots.append(bot)\n\n","sub_path":"aqbot/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"185219315","text":"\"\"\"Module with simple TCP server and client.\n\"\"\"\nimport argparse\nimport socket\nimport sys\n\nENCODING = 'utf-8'\n\ndef run_server(host: str, port: int):\n\twith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n\t\ts.bind((host, port))\n\t\ts.listen()\n\n\t\twhile True:\n\t\t\tprint(f'Waiting for a new connection on {host}:{port}')\n\t\t\tc, a = s.accept()\n\n\t\t\tprint(f'Accepted connection from {a}')\n\n\t\t\twith c:\n\t\t\t\tmsg = c.recv(1024)\n\t\t\t\tprint(f'Received message: ' +\n\t\t\t\t\tmsg.decode(ENCODING))\n\t\t\t\t\n\t\t\t\t# shout back\n\t\t\t\tc.sendall(msg.decode(ENCODING).upper() \\\n\t\t\t\t\t.encode(ENCODING))\n\ndef run_client(host: str, port: int, msg: str):\n\twith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n\t\tprint(f'Connecting to server {host}:{port}')\n\t\ts.connect((host, port))\n\t\tprint(f'Sending message: {msg}')\n\t\ts.sendall(msg[0:1024].encode(ENCODING))\n\t\treply = s.recv(1024).decode(ENCODING)\n\t\tprint(f'Received reply: {reply}')\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--server', '-s', dest='server',\n\t\taction='store_true', help='Run TCP server')\n\tparser.add_argument('--client', '-c', dest='client',\n\t\taction='store_true', help='Run TCP client')\n\t\n\tparser.add_argument('--host', dest='host', required=True,\n\t\ttype=str, help='Connect to host')\n\tparser.add_argument('--port', dest='port', required=True,\n\t\ttype=int, help='Connect to port')\n\t\n\tparser.add_argument('--message', '-m', dest='message', required=False,\n\t\ttype=str, default='Some message', help='Message to echo')\n\n\n\targs = parser.parse_args()\n\n\t# Cannot be both server and client, and cannot be neither\n\tif args.server == args.client:\n\t\tprint('Cannot be both or neither a server and client')\n\t\tsys.exit(1)\n\n\tif args.server:\n\t\trun_server(args.host, args.port)\n\n\tif args.client:\n\t\trun_client(args.host, args.port, args.message)\n","sub_path":"python/simple_tcp_echo.py","file_name":"simple_tcp_echo.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"616627480","text":"# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\nfrom paddle.optimizer.lr import *\n\"\"\"\nPaddleVideo Learning Rate Schedule:\nYou can use paddle.optimizer.lr\nor define your custom_lr in this file.\n\"\"\"\n\n\nclass CustomWarmupCosineDecay(LRScheduler):\n r\"\"\"\n We combine warmup and stepwise-cosine which is used in slowfast model.\n\n Args:\n warmup_start_lr (float): start learning rate used in warmup stage.\n warmup_epochs (int): the number epochs of warmup.\n cosine_base_lr (float|int, optional): base learning rate in cosine schedule.\n max_epoch (int): total training epochs.\n num_iters(int): number iterations of each epoch.\n last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.\n verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .\n Returns:\n ``CosineAnnealingDecay`` instance to schedule learning rate.\n \"\"\"\n def __init__(self,\n warmup_start_lr,\n warmup_epochs,\n cosine_base_lr,\n max_epoch,\n num_iters,\n last_epoch=-1,\n verbose=False):\n self.warmup_start_lr = warmup_start_lr\n self.warmup_epochs = warmup_epochs\n self.cosine_base_lr = cosine_base_lr\n self.max_epoch = max_epoch\n self.num_iters = num_iters\n #call step() in base class, last_lr/last_epoch/base_lr will be update\n super(CustomWarmupCosineDecay, self).__init__(last_epoch=last_epoch,\n verbose=verbose)\n\n def step(self, epoch=None):\n \"\"\"\n ``step`` should be called after ``optimizer.step`` . It will update the learning rate in optimizer according to current ``epoch`` .\n The new learning rate will take effect on next ``optimizer.step`` .\n Args:\n epoch (int, None): specify current epoch. Default: None. Auto-increment from last_epoch=-1.\n Returns:\n None\n \"\"\"\n if epoch is None:\n if self.last_epoch == -1:\n self.last_epoch += 1\n else:\n self.last_epoch += 1 / self.num_iters # update step with iters\n else:\n self.last_epoch = epoch\n self.last_lr = self.get_lr()\n\n if self.verbose:\n print('Epoch {}: {} set learning rate to {}.'.format(\n self.last_epoch, self.__class__.__name__, self.last_lr))\n\n def _lr_func_cosine(self, cur_epoch, cosine_base_lr, max_epoch):\n return cosine_base_lr * (math.cos(math.pi * cur_epoch / max_epoch) +\n 1.0) * 0.5\n\n def get_lr(self):\n \"\"\"Define lr policy\"\"\"\n lr = self._lr_func_cosine(self.last_epoch, self.cosine_base_lr,\n self.max_epoch)\n lr_end = self._lr_func_cosine(self.warmup_epochs, self.cosine_base_lr,\n self.max_epoch)\n\n # Perform warm up.\n if self.last_epoch < self.warmup_epochs:\n lr_start = self.warmup_start_lr\n alpha = (lr_end - lr_start) / self.warmup_epochs\n lr = self.last_epoch * alpha + lr_start\n return lr\n\n\nclass CustomPiecewiseDecay(PiecewiseDecay):\n def __init__(self, **kargs):\n kargs.pop('num_iters')\n super().__init__(**kargs)\n","sub_path":"paddlevideo/solver/custom_lr.py","file_name":"custom_lr.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"455633246","text":"import torch\nimport torch.nn as nn\n\nimport torch.nn.functional as F\n\n\nclass KimCNNEncoder(nn.Module):\n def __init__(self, args):\n super().__init__()\n self.args = args\n\n dataset = args.dataset\n words_num = args.words_num\n words_dim = args.words_dim\n target_class = args.target_class\n output_channel = args.output_channel\n\n if args.mode == 'rand':\n input_channel = 1\n rand_embed_init = torch.Tensor(words_num, words_dim).uniform_(-0.25, 0.25)\n self.embed = nn.Embedding.from_pretrained(rand_embed_init, freeze=False)\n elif args.mode == 'static':\n input_channel = 1\n self.static_embed = nn.Embedding.from_pretrained(dataset.fields['input'].vocab.vectors, freeze=True)\n elif args.mode == 'non-static':\n input_channel = 1\n self.non_static_embed = nn.Embedding.from_pretrained(dataset.fields['input'].vocab.vectors, freeze=False)\n elif args.mode == 'multichannel':\n input_channel = 2\n self.static_embed = nn.Embedding.from_pretrained(dataset.fields['input'].vocab.vectors, freeze=True)\n self.non_static_embed = nn.Embedding.from_pretrained(dataset.fields['input'].vocab.vectors, freeze=False)\n else:\n raise ValueError(\"Unsupported embedding mode\")\n\n self.conv1 = nn.Conv2d(input_channel, output_channel, (3, words_dim), padding=(2,0))\n self.conv2 = nn.Conv2d(input_channel, output_channel, (4, words_dim), padding=(3,0))\n self.conv3 = nn.Conv2d(input_channel, output_channel, (5, words_dim), padding=(4,0))\n\n self.dropout = nn.Dropout(args.dropout)\n self.fc1 = nn.Linear(3 * output_channel, target_class)\n\n def forward(self, x):\n if self.args.mode == 'rand':\n word_input = self.embed(x) # (batch, sent_len, embed_dim)\n x = word_input.unsqueeze(1) # (batch, channel_input, sent_len, embed_dim)\n elif self.args.mode == 'static':\n static_input = self.static_embed(x)\n x = static_input.unsqueeze(1) # (batch, channel_input, sent_len, embed_dim)\n elif self.args.mode == 'non-static':\n non_static_input = self.non_static_embed(x)\n x = non_static_input.unsqueeze(1) # (batch, channel_input, sent_len, embed_dim)\n elif self.args.mode == 'multichannel':\n non_static_input = self.non_static_embed(x)\n static_input = self.static_embed(x)\n x = torch.stack([non_static_input, static_input], dim=1) # (batch, channel_input=2, sent_len, embed_dim)\n\n x = [F.relu(self.conv1(x)).squeeze(3),\n F.relu(self.conv2(x)).squeeze(3),\n F.relu(self.conv3(x)).squeeze(3)] # (batch, channel_output, ~=sent_len) * num_conv\n\n x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] # (batch, channel_output) * num_conv\n x = torch.cat(x, 1) # (batch, channel_output * num_conv)\n return x\n","sub_path":"lib/models/sm_cnn/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"484226301","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport webapp2\nimport cgi\nimport string\nimport os\nimport jinja2\nimport re\nimport datetime\nfrom google.appengine.ext import db\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\njinja_env = jinja2.Environment(autoescape = True,\n\tloader = jinja2.FileSystemLoader(template_dir))\n\ndef rot13(text):\n\tout = ''\n\toffset = 13\n\taval = ord('a')\t\n\tAval = ord('A')\n\talp_range = ord('z') - ord('a') + 1\n \n\tfor char in text:\n\t\tchar_num = ord(char)\n\t\tif (char_num >= ord('a')) and (char_num <= ord('z')):\n\t\t\tnew_char = ((char_num - aval + offset) % alp_range) + aval\n\t\t\tnew_char = chr(new_char)\n\t\t\tout += new_char\n\t\telif (char_num >= ord('A')) and (char_num <= ord('Z')):\n\t\t\tnew_char = ((char_num - Aval + offset) % alp_range) + Aval\n\t\t\tnew_char = chr(new_char)\n\t\t\tout += new_char\n\t\telse:\n\t\t\tout += char\n\treturn out\n\ndef render_str(template, **params):\n\tt = jinja_env.get_template(template)\n\treturn t.render(params)\n\nclass BaseHandler(webapp2.RequestHandler):\n\tdef render(self,template, **kw):\n\t\tself.response.out.write(render_str(template,**kw))\n\tdef write(self,*a,**kw):\n\t\tself.response.out(*a,**kw)\n\nclass Rot13(BaseHandler):\n\tdef get(self):\n\t\tself.render('rot13.html')\n\tdef post(self):\n\t\ttext = self.request.get('text')\n\t\tenc_text = rot13(text)\n\t\tself.render('rot13.html',text =enc_text)\n\nclass Signup(BaseHandler):\n\tdef get(self):\n\t\tself.render('signup.html')\n\tdef post(self):\n\t\tusername_re = re.compile(r\"^[a-zA-Z0-9_-]{3,20}$\")\n\t\tpassword_re = re.compile(r\"^.{3,20}$\")\n\t\temail_re = re.compile(r\"^[\\S]+@[\\S]+\\.[\\S]+$\")\n\n\t\tusername = self.request.get('username') \n\t\tpassword = self.request.get('password') \n\t\tverify = self.request.get('verify') \n\t\temail = self.request.get('email')\n\n\t\thas_error = False\n\t\tfields = {}\n\t\tfields['username'] = username\n\t\tfields['email'] = email\n\n\t\tif username_re.search(username) is None:\n\t\t\thas_error = True\n\t\t\tfields['username_error'] = \"That's not a valid username\" \n\t\tif password_re.match(password) is None:\n\t\t\thas_error = True\n\t\t\tfields['password_error'] = \"That wasn't a valid password\"\n\t\tif password != verify:\n\t\t\thas_error = True\n\t\t\tfields['verify_error'] = \"Your passwords do not match\"\n\t\tif email and (email_re.match(email) is None):\n\t\t\thas_error = True\n\t\t\tfields['email_error'] = 'Bad e-mail entered'\n\n\t\tif has_error:\n\t\t\tself.render('signup.html', **fields)\n\t\telse:\n\t\t\tself.redirect('/unit2/welcome?username='+username)\n\nclass Welcome(BaseHandler):\n\tdef get(self):\n\t\tusername = self.request.get('username')\n\t\tself.render('welcome.html',username = username)\n\n# ############################################################################\n# BLOG STUFF HERE ------------------------------------------------------------\n# ############################################################################\n\ndef blog_key(name = 'default'):\n\treturn db.Key.from_path('blogs',name)\n\nclass BlogHandler(webapp2.RequestHandler):\n\tdef write(self,*a,**kw):\n\t\tself.response.out.write(*a,**kw)\n\tdef render_str(self,template,**params):\n\t\tt = jinja_env.get_template(template)\n\t\treturn t.render(params)\n\tdef render(self,template,**kw):\n\t\tself.write(self.render_str(template,**kw))\n\nclass Submit(BlogHandler):\n\tdef get(self):\n\t\tself.render('submit.html')\n\tdef post(self):\n\t\tsubject = self.request.get(\"subject\")\n\t\tcontent = self.request.get(\"content\")\n\n\t\tif subject and content:\n\t\t\tblog_post = Entry(subject=subject, content=content)\n\t\t\tblog_post.put() #stores the blog post\n\t\t\tblog_id = blog_post.key().id()\n\t\t\tself.redirect('/blog/%s' % blog_id)\n\t\telse:\n\t\t\terror = \"You need both a subject and content to be filled out\"\n\t\t\tself.render('submit.html',subject=subject,content=content, error= error)\n\nclass FrontPage(BlogHandler):#\n\tdef get(self):\n\t\tentries = db.GqlQuery(\"SELECT * FROM Entry ORDER BY date_created DESC LIMIT 10\")\n\t\tself.render(\"frontpage.html\",entries=entries)\n\nclass Permalink(BlogHandler):\n\tdef get(self, blog_id):\n\t\tkey = db.Key.from_path('Entry',int(blog_id))\n\t\tentry = db.get(key)\n\t\tif entry:\n\t\t\tself.render(\"entry.html\",entry=entry)\n\t\telse:\n\t\t\tself.error(404)\n\t\t\treturn\n\nclass Entry(db.Model):\n\tsubject = db.StringProperty(required = True)\n\tcontent = db.TextProperty(required = True)\n\tdate_created = db.DateTimeProperty(auto_now_add = True)\n\tlast_modified = db.DateTimeProperty(auto_now = True)\n\n\tdef render(self):\n\t\tself._render_text = self.content.replace('\\n','
    ')\n\t\treturn render_str(\"entry.hml\", entry = self)\n\napp = webapp2.WSGIApplication([('/unit2/rot13',Rot13),\n\t\t\t\t\t\t\t ('/unit2/signup',Signup),\n\t\t\t\t\t\t\t ('/unit2/welcome',Welcome),\n\t\t\t\t\t\t\t ('/blog/newpost',Submit),\n\t\t\t\t\t\t\t ('/blog/([0-9]+)',Permalink),\n\t\t\t\t\t\t\t ('/blog',FrontPage)],\n\t\t\t\t\t\t\t debug=True)\n","sub_path":"blog4.py","file_name":"blog4.py","file_ext":"py","file_size_in_byte":4671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"197104465","text":"import param\nimport panel as pn\nimport numpy as np\nimport pandas as pd\n# import hvplot.pandas\nimport holoviews as hv\nfrom holoviews.streams import Pipe\nimport xarray as xr\nfrom PyEMD import EEMD, EMD, CEEMDAN, Visualisation\nvis = Visualisation()\nimport colorcet as cc\n\npn.extension('vega', 'katex')\nhv.extension('bokeh')\n\npaths_iniciales = [dict(x=np.zeros(10), y=np.zeros(10), z=np.zeros(10)),\n dict(x=np.zeros(10), y=np.zeros(10), z=np.zeros(10))]\n# figuras\n\nclass SerieTemporal(param.Parameterized):\n\n # widgets en comun para la clase.\n N = param.Integer(300, bounds=(100, 1000), step=1, doc='Número de muestras')\n fs = param.Number(10, bounds=(1., 50.0), step=1., doc='Frecuencia de muestreo')\n\n # en comun\n stop_fixe = param.Integer(1, bounds=(1, 15), step=1, doc='FIXE')\n stop_fixe_h = param.Integer(1, bounds=(1, 15), step=1, doc='FIXE_H')\n max_imf = param.Integer(1, bounds=(1, 15), step=1, doc='Máxima cantidad de IMFs')\n\n # para EMD\n spline_kind = param.Selector(objects=['cubic', 'akima', 'slinear'], doc='Interpolación')\n nbsym = param.Integer(2, bounds=(1, 5), step=1, doc='Cantidad de extremos en los bordes')\n extrema_detection = param.Selector(objects=['simple', 'parabol'], doc='Detector de extremos')\n\n # para EEMD\n trials = param.Integer(20, bounds=(1, 250), step=1, doc='Numero de ensambles por IMF')\n noise_width = param.Number(0.05, bounds=(0.01, 2.0), step=.05, doc='Desvio del ruido')\n\n # para CEEMDAN\n epsilon = param.Number(0.005, bounds=(0.001, 0.1), step=.005, doc='Factor de escala del ruido')\n\n def __init__(self, **params):\n super(SerieTemporal, self).__init__(**params) # hereda atributos de Parametrized.\n # series.\n self.inicializar()\n\n def inicializar(self):\n self.set_tiempo()\n self.serie = np.zeros(self.N)\n self.paths = None\n self.nonlinear_methods = EMD()\n # self.update_parametros()\n\n self.imfs = None\n self.freqs = None\n self.n_imfs = None\n self.ds = None\n self.eemd = None\n self.ceemdan = None\n\n def set_tiempo(self):\n self.t = np.arange(self.N)*(1/self.fs)\n\n def plotter(self):\n pipe_serie.send(dict(x=self.t, y=self.serie))\n # debug_panel.object = 'PLOTTER'\n\n def set_emd(self):\n self.imfs = self.nonlinear_methods.emd(self.serie,\n T=self.t,\n max_imf=self.max_imf)\n self.freqs = vis._calc_inst_freq(self.imfs, self.t)\n self.imfs = np.delete(self.imfs, self.N-1, axis=1)\n self.n_imfs = len(self.imfs)\n self.ds = xr.Dataset({'frecuencia': (['imf', 'tiempo'], self.freqs),\n 'amplitud': (['imf', 'tiempo'], self.imfs)},\n coords={'tiempo': ('tiempo', self.t[:-1]),\n 'imf': ('imf', [ 'IMF %d' % k for k in range(self.n_imfs)])})\n self.set_paths(self.ds, self.n_imfs)\n\n\n def set_eemd(self):\n self.eemd = EEMD(trials=self.trials,\n noise_width=self.noise_width,\n ext_EMD=self.nonlinear_methods,\n parallel=True)\n self.imfs = self.eemd.eemd(self.serie,\n T=self.t,\n max_imf=self.max_imf)\n self.freqs = vis._calc_inst_freq(self.imfs, self.t)\n self.imfs = np.delete(self.imfs, self.N-1, axis=1)\n self.n_imfs = len(self.imfs)\n self.ds = xr.Dataset({'frecuencia': (['imf', 'tiempo'], self.freqs),\n 'amplitud': (['imf', 'tiempo'], self.imfs)},\n coords={'tiempo': ('tiempo', self.t[:-1]),\n 'imf': ('imf', [ 'IMF %d' % k for k in range(self.n_imfs)])})\n self.set_paths(self.ds, self.n_imfs)\n\n def set_ceemdan(self):\n self.ceemdan = CEEMDAN(trials=self.trials,\n epsilon=self.epsilon,\n ext_EMD=self.nonlinear_methods,\n parallel=True)\n self.imfs = self.ceemdan.ceemdan(self.serie, # en la doc dice que es emd!\n T=self.t,\n max_imf=self.max_imf)\n self.freqs = vis._calc_inst_freq(self.imfs, self.t)\n self.imfs = np.delete(self.imfs, self.N-1, axis=1)\n self.n_imfs = len(self.imfs)\n self.ds = xr.Dataset({'frecuencia': (['imf', 'tiempo'], self.freqs),\n 'amplitud': (['imf', 'tiempo'], self.imfs)},\n coords={'tiempo': ('tiempo', self.t[:-1]),\n 'imf': ('imf', [ 'IMF %d' % k for k in range(self.n_imfs)])})\n self.set_paths(self.ds, self.n_imfs)\n\n def set_paths(self, ds, n_imfs):\n self.paths = []\n for imf in range(self.n_imfs):\n self.paths.append(dict(x=self.ds['tiempo'].data,\n y=self.ds.isel(imf=imf)['frecuencia'].data,\n z=self.ds.isel(imf=imf)['amplitud'].data))\n\n\nclass ejA(SerieTemporal):\n\n f1 = param.Number(5., bounds=(1., 10.0), step=0.1, doc='Parámetro f1')\n f2 = param.Number(2., bounds=(1., 10.0), step=0.1, doc='Parámetro f2')\n\n def set_funcion(self):\n self.set_tiempo()\n self.serie = np.cos(2*np.pi*self.f1*self.t) + np.cos(2*np.pi*self.f2*self.t)\n\n def set_math(self):\n latex_panel.object = '$\\cos (2 \\pi f_1 t) + \\cos (2 \\pi f_2 t)$'\n\n @param.depends('f1', 'f2', 'N', 'fs',\n 'stop_fixe', 'stop_fixe_h',\n 'spline_kind', 'nbsym',\n 'extrema_detection', watch=True)\n def update(self):\n self.set_funcion()\n self.plotter()\n\n @param.depends('stop_fixe', 'stop_fixe_h',\n 'spline_kind', 'nbsym',\n 'extrema_detection', watch=True)\n def update_parametros(self):\n self.nonlinear_methods = EMD(spline_kind=self.spline_kind,\n nbsym=self.nbsym,\n extrema_detection=self.extrema_detection)\n self.nonlinear_methods.FIXE = self.stop_fixe\n self.nonlinear_methods.FIXE_H = self.stop_fixe_h\n\n\nclass ejC(SerieTemporal):\n\n f1 = param.Number(5., bounds=(1., 10.0), step=0.1, doc='Parámetro f1')\n f2 = param.Number(2., bounds=(1., 10.0), step=0.1, doc='Parámetro f2')\n A = param.Number(1., bounds=(1., 10.0), step=0.1, doc='Parámetro A')\n\n def set_funcion(self):\n self.set_tiempo()\n self.serie = np.cos(2*np.pi*self.f1*self.t + self.A*np.sin(2*np.pi*self.f2*self.t))\n\n def set_math(self):\n latex_panel.object = '$\\cos (2 \\pi f_1 t + A \\sin (2 \\pi f_2 t))$'\n\n @param.depends('f1', 'f2', 'A', 'N', 'fs',\n 'stop_fixe', 'stop_fixe_h',\n 'spline_kind', 'nbsym',\n 'extrema_detection', watch=True)\n def update(self):\n self.set_funcion()\n self.plotter()\n\n @param.depends('stop_fixe', 'stop_fixe_h',\n 'spline_kind', 'nbsym',\n 'extrema_detection', watch=True)\n def update_parametros(self):\n self.nonlinear_methods = EMD(spline_kind=self.spline_kind,\n nbsym=self.nbsym,\n extrema_detection=self.extrema_detection)\n self.nonlinear_methods.FIXE = self.stop_fixe\n self.nonlinear_methods.FIXE_H = self.stop_fixe_h\n\nejercicios = dict(A=ejA(), B=ejC())\n\nclass SerieViewer(param.Parameterized):\n\n # widgets.\n ejercicio = param.ObjectSelector(default=ejercicios['A'],\n objects=ejercicios,\n doc='Selección de ejercicio')\n\n run_emd = param.Action(lambda x: x.param.trigger('run_emd'), label='EMD')\n run_eemd = param.Action(lambda x: x.param.trigger('run_eemd'), label='EEMD')\n run_ceemdan = param.Action(lambda x: x.param.trigger('run_ceemdan'), label='CEEMDAN')\n\n @param.depends('ejercicio', watch=True)\n def cambia_ejercicio(self):\n self.ejercicio.inicializar()\n self.ejercicio.set_math() # escribe la función en LaTeX.\n self.ejercicio.update()\n # pipe_emd.send(paths_iniciales)\n # pipe_eemd.send(paths_iniciales)\n # self.limpiar_memoria()\n # gc.collect()\n\n # self.ejercicio = ejA()\n\n @param.depends('run_emd', watch=True)\n def plot_emd(self):\n self.ejercicio.set_emd()\n pipe_emd.send(self.ejercicio.paths)\n\n @param.depends('run_eemd', watch=True)\n def plot_eemd(self):\n self.ejercicio.set_eemd()\n pipe_eemd.send(self.ejercicio.paths)\n\n @param.depends('run_ceemdan', watch=True)\n def plot_ceemdan(self):\n self.ejercicio.set_ceemdan()\n pipe_ceemdan.send(self.ejercicio.paths)\n\n\n def plot(self, data):\n plot = hv.Path(data, vdims='z')\n plot.opts(color='z', # cmap='blues',\n width=500,\n line_width=2,\n colorbar=True,\n xlabel='Tiempo [s]',\n ylabel='Frecuencia [Hz]')\n # bgcolor=cc.blues[0])\n return plot\n\nif __name__ == \"__main__\": # Esto es necesario porque la libreria de EEMD usa multithreading y conflictua con tornado de panel.\n\n pipe_serie = Pipe(data=[])\n figure_serie = hv.DynamicMap(hv.Curve, streams=[pipe_serie])\n figure_serie.opts(width=500,\n framewise=True, # NO OLVIDAR EL FRAMEWISE. Es analogo a axiswise pero para dinamico.\n title='Serie temporal',\n ylabel='Amplitud',\n xlabel='Tiempo [s]')\n\n pipe_emd = Pipe(data=paths_iniciales) # path_iniciales no llevan []. Costo darme cuenta.\n pipe_eemd = Pipe(data=paths_iniciales)\n pipe_ceemdan = Pipe(data=paths_iniciales)\n\n viewer = SerieViewer()\n figure_emd = hv.DynamicMap(viewer.plot, streams=[pipe_emd]).opts(framewise=True, title='EMD')\n figure_eemd = hv.DynamicMap(viewer.plot, streams=[pipe_eemd]).opts(framewise=True, title='EEMD')\n figure_ceemdan = hv.DynamicMap(viewer.plot, streams=[pipe_ceemdan]).opts(framewise=True, title='CEEMDAN')\n layout = (figure_serie +\n figure_emd +\n figure_eemd +\n figure_ceemdan)\n layout.opts(shared_axes=False, toolbar='right')\n layout.cols(2)\n\n param_custom = dict(N={'name': 'Cantidad de muestras'},\n fs={'name': 'Frecuencia de muestreo'},\n stop_fixe={'name': 'FIXE'},\n stop_fixe_h={'name': 'FIXE_H'},\n max_imf={'name': 'Cantidad max. IMFs'},\n spline_kind={'name': 'Interpolacion'},\n nbsym={'name': 'Muestras de borde'},\n extrema_detection={'name': 'Detector de extremos'},\n trials={'name': 'Ensambles por IMF'},\n noise_width={'name': 'Desvio del ruido'},\n epsilon={'name': 'Escala del ruido'},\n ejercicio={'name': 'Ejercicio'},\n f1={'name': 'Frecuencia f1'},\n f2={'name': 'Frecuencia f2'},\n A={'name': 'Amplitud A'}\n )\n \n expand_layout = pn.Column()\n latex_panel = pn.pane.LaTeX(object='')\n debug_panel = pn.pane.Markdown('0')\n panel = pn.Column(pn.Row(\n pn.Column(\n pn.panel(viewer.param, expand_button=False, expand=True, expand_layout=expand_layout, widgets=param_custom),\n latex_panel,\n expand_layout),\n layout)) # IMPORTATE. NO USAR panel(), USAR panel\n # panel.append(debug_panel)\n # panel = pn.Row(viewer.param, viewer.panel)\n panel.show()\n","sub_path":"src/nolinear_dash.py","file_name":"nolinear_dash.py","file_ext":"py","file_size_in_byte":11930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"134805067","text":"from flask import jsonify, url_for\nfrom typing import Optional\n\nfrom rx_sharh.model.fake_user import faker\nfrom rx_sharh.components.optional_get import optional_get\nimport rx_sharh.states.database as db\n\n\ndef redirect_with_302(location: str, has_been_url_for_handled=False, **kwargs):\n return jsonify(status=302, location=location if has_been_url_for_handled else url_for(location, **kwargs))\n\n\ndef get_number_from_user(user: db.User):\n try:\n user_student = user.ref_students.first()\n number = user_student.student.number if user_student else user.ref_teachers.first().teacher.number\n except:\n return user.account\n return number\n\n\ndef load_side_info(user: db.User):\n if not user.is_authenticated:\n number = '未登录'\n user = faker\n else:\n number = get_number_from_user(user)\n\n return dict(\n avatar=user.avatar if user.avatar else url_for('get_image', imagep='avatar.jpg'),\n name=user.nickname or f\"用户{user.account}\",\n number=number)\n\n\ndef load_side_options():\n return [dict(href=url_for('schedule.today_course_'), icon='assignment', title='课程'),\n dict(href=url_for('attendance.center'), icon='assignment_turned_in', title='签到'),\n dict(href=url_for('profile.profile'), icon='person', title='个人中心'),\n dict(href=url_for('group.center'), icon='group', title='群组')]\n\n\ndef load_function_list():\n return [['课表', url_for('get_image', imagep=\"Course.png\"), url_for('schedule.today_course_'), 0],\n ['签到', url_for('get_image', imagep=\"Attendance.png\"), url_for('attendance.center'), 1],\n ['个人中心', url_for('get_image', imagep=\"Person.png\"), url_for('profile.profile'), 0],\n ['群组', url_for('get_image', imagep=\"Group.png\"), url_for('group.center'), 0]]\n","sub_path":"rx_sharh/service/view/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"90300240","text":"#!/usr/bin/env python3\n#!/usr/bin/python\n\n# http://mcsp.wartburg.edu/zelle/python/graphics.py\n\nfrom graphics import *\n\nSCALE = 10\n\ndef test():\n win = GraphWin()\n win.setCoords(0,0,10,10)\n t = Text(Point(5,5), \"Centered Text\")\n t.draw(win)\n p = Polygon(Point(1,1), Point(5,3), Point(2,7))\n p.draw(win)\n e = Entry(Point(5,6), 10)\n e.draw(win)\n win.getMouse()\n p.setFill(\"red\")\n p.setOutline(\"blue\")\n p.setWidth(2)\n s = \"\"\n for pt in p.getPoints():\n s = s + \"(%0.1f,%0.1f) \" % (pt.getX(), pt.getY())\n t.setText(e.getText())\n e.setFill(\"green\")\n e.setText(\"Spam!\")\n e.move(2,0)\n win.getMouse()\n p.move(2,3)\n s = \"\"\n for pt in p.getPoints():\n s = s + \"(%0.1f,%0.1f) \" % (pt.getX(), pt.getY())\n t.setText(s)\n win.getMouse()\n p.undraw()\n e.undraw()\n t.setStyle(\"bold\")\n win.getMouse()\n t.setStyle(\"normal\")\n win.getMouse()\n t.setStyle(\"italic\")\n win.getMouse()\n t.setStyle(\"bold italic\")\n win.getMouse()\n t.setSize(14)\n win.getMouse()\n t.setFace(\"arial\")\n t.setSize(20)\n win.getMouse()\n win.close()\n\n\ndef circle():\n win = GraphWin(\"My Circle\", 100 * SCALE, 100 * SCALE)\n c = Circle(Point(50 * SCALE,50 * SCALE), 10 * SCALE)\n c.draw(win)\n win.getMouse() # Pause to view result\n win.close() # Close window when done\n\ndef main():\n test()\n circle()\n\nmain()\n","sub_path":"python3/graphics/graph3.py","file_name":"graph3.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"132220148","text":"import os\nimport json\nfrom config import global_config\nfrom utils.funcs import post_rpc\n\nserve_port = global_config[\"serve_port\"]\n\ncwd = os.path.abspath(os.path.dirname(__file__))\nparams = json.load(open(os.path.join(cwd, \"params.json\")))\n\ndata = {\n \"robotId\": params[\"robot_code\"],\n \"userCode\": \"user1\",\n \"params\": params[\"params\"]\n}\nresponse = post_rpc(\n \"http://127.0.0.1:{}/api/v1/session/create\".format(serve_port),\n data\n)\nprint(response)\n\nwhile True:\n says = input(\"用户说:\")\n data = {\n \"robotId\": params[\"robot_code\"],\n \"userCode\": \"user1\",\n \"sessionId\": response[\"data\"][\"sessionId\"],\n \"userSays\": says\n }\n response = post_rpc(\n \"http://127.0.0.1:{}/api/v1/session/reply\".format(serve_port),\n data\n )\n print(response)\n","sub_path":"bin/service_interact.py","file_name":"service_interact.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"550461296","text":"import chainer.datasets\nimport warnings\n\n\ndef scatter_dataset(dataset, comm):\n \"\"\"Scatter the given dataset to the workers in the communicator.\n\n The dataset of worker 0 (i.e., the worker whose ``comm.rank`` is 0) is\n scattered to all workers. The given dataset of other workers are ignored.\n The dataset is split to sub datasets of almost equal sizes and scattered\n to workers. To create a sub dataset, ``chainer.datasets.SubDataset`` is\n used.\n\n Args:\n dataset: A dataset (e.g., ``list``, ``numpy.ndarray``,\n ``chainer.datasets.TupleDataset``, ...).\n comm: ChainerMN communicator or MPI4py communicator.\n\n Returns:\n Scattered dataset.\n \"\"\"\n\n if hasattr(comm, 'mpi_comm'):\n comm = comm.mpi_comm\n assert hasattr(comm, 'send')\n assert hasattr(comm, 'recv')\n\n # We cannot use `mpi_comm.scatter`. This is due to MPI4py's bug.\n # For large datasets, when using `mpi_comm.scatter`, it causes MemoryError.\n if comm.rank == 0:\n mine = None\n n_total_samples = len(dataset)\n n_sub_samples = (n_total_samples + comm.size - 1) // comm.size\n for i in range(comm.size):\n b = n_total_samples * i // comm.size\n e = b + n_sub_samples\n subds = chainer.datasets.SubDataset(dataset, b, e)\n if i == 0:\n mine = subds\n else:\n comm.send(subds, dest=i)\n return mine\n else:\n return comm.recv(source=0)\n\n\ndef get_n_iterations_for_one_epoch(dataset, local_batch_size, comm):\n \"\"\"Get the number of iterations for one epoch.\n\n .. note::\n\n This API is deprecated. Please use standard epoch triggers.\n\n Args:\n dataset: Sub dataset of each worker.\n local_batch_size (int): Batch size of each worker.\n comm: ChainerMN communicator or MPI4py communicator.\n\n Returns:\n int: the number of iterations for one epoch.\n \"\"\"\n\n warnings.warn(\n 'get_n_iterations_for_one_epoch is deprecated. Please use '\n 'standard epoch triggers.', DeprecationWarning)\n\n if hasattr(comm, 'mpi_comm'):\n comm = comm.mpi_comm\n assert hasattr(comm, 'bcast')\n\n n_iterations = None\n if comm.rank == 0:\n n_iterations = (len(dataset) + local_batch_size -\n 1) // local_batch_size\n return comm.bcast(n_iterations)\n\n\ndef get_epoch_trigger(n_epochs, dataset, local_batch_size, comm):\n \"\"\"Get the trigger that behaves like an epoch trigger.\n\n .. note::\n\n This API is deprecated. Please use standard epoch triggers.\n\n Args:\n n_epochs (int): The number of epochs.\n dataset: Sub dataset of each worker.\n local_batch_size (int): Batch size of each worker.\n comm: ChainerMN communicator or MPI4py communicator.\n\n Returns:\n The trigger that behaves like the epoch trigger.\n \"\"\"\n\n warnings.warn(\n 'get_epoch_trigger is deprecated. Please use standard epoch triggers.',\n DeprecationWarning)\n\n n_iterations = n_epochs * get_n_iterations_for_one_epoch(\n dataset, local_batch_size, comm)\n return n_iterations, 'iteration'\n","sub_path":"chainermn/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"229036387","text":"################################################################################\n# Code and images by Aaron Penne\n# https://github.com/aaronpenne/generative_art\n#\n# Released under the MIT license (https://opensource.org/licenses/MIT)\n################################################################################\n\n\n#TODO\n# Break away from config files to allow snapshotting of py file\n# Draw white borders on input image\n# Clean up this hot mess of code and modularize/parameterize\n\n\n# Processing mode uses Python 2.7 but I prefer Python 3.x\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import with_statement\n\n# Normal Python imports\nimport os\nimport sys\n\n# Bad way to make our \"imports\" dir available so we can import modules from it\nsys.path.insert(0, '/Users/apenne/github.com/generative_art/ppy_terminal/imports')\nfrom utilities import DrawUtils, OpsUtils, ConfigUtils\nfrom setup_logging import log\n\n# argparse doesn't work with command line processing, using config files instead\nargs = ConfigUtils().config_to_dict('config')\n\n\n\ndef setup():\n\n global ima\n ima = createGraphics(args['width'], args['height'])\n\n global imb\n imb = createGraphics(args['width'], args['height'])\n\n global imc\n \n global out\n out = createGraphics(args['width'], args['height'])\n out.beginDraw()\n out.endDraw()\n\n # Only run draw() function once\n #noLoop()\n\ndef draw(): \n\n\n if args['seeded']:\n seed = int(random(0,9999999))\n else:\n seed = args['seed']\n\n # Instantiate primary drawing class\n du = DrawUtils(script_path=os.path.abspath(__file__),\n width=args['width'], \n height=args['height'], \n seed=seed)\n \n # Initialize random number generators with seed\n randomSeed(du.seed)\n noiseSeed(du.seed)\n\n global imc\n imc_file = du.get_ext_agnostic_file('input', args['imc'])\n imc = loadImage(imc_file)\n imc.resize(args['width'], args['height'])\n imc.filter(BLUR, 2)\n # du.save_graphic(imc, 'output', 3)\n\n ima.beginDraw()\n ima.colorMode(HSB, 360, 100, 100, 100)\n ima.rectMode(CENTER)\n ima.background(0, 0, 100)\n ima.noStroke()\n x_min = du.width * 0.3\n x_max = du.width * 0.7\n y_min = du.height * 0.3\n y_max = du.height * 0.7\n for i in range(int(random(200))):\n if int(random(100))%2==0:\n shape = 0\n else:\n shape = 1\n x = random(x_min, x_max)\n y = random(y_min, y_max)\n w = random(du.width * 0.3)\n h = random(du.height * 0.3)\n for j in range(int(random(10))):\n ima.fill(0, 0, random(100))\n if shape == 0:\n ima.ellipse(x, y, w-j*du.width*0.01, h-j*du.height*0.01)\n else:\n ima.rect(x, y, w-j*du.width*0.01, h-j*du.height*0.01)\n ima.filter(BLUR,int(random(10,40)))\n for i in range(int(random(200))):\n if int(random(100))%2==0:\n shape = 0\n else:\n shape = 1\n x = random(x_min, x_max)\n y = random(y_min, y_max)\n w = random(du.width * 0.3)\n h = random(du.height * 0.3)\n for j in range(int(random(10))):\n ima.fill(0, 0, random(100))\n if shape == 0:\n ima.ellipse(x, y, w-j*du.width*0.01, h-j*du.height*0.01)\n else:\n ima.rect(x, y, w-j*du.width*0.01, h-j*du.height*0.01)\n ima.filter(BLUR,int(random(20,40)))\n# for i in range(int(random(200))):\n# x = random(x_min, x_max)\n# y = random(y_min, y_max)\n# w = random(du.width * 0.3)\n# h = random(du.height * 0.3)\n# for j in range(int(random(20))):\n# ima.fill(0, 0, random(100))\n# ima.rect(x, y, w-j*du.width*0.01, h-j*du.height*0.01)\n# ima.filter(BLUR,int(random(2,30)))\n# for i in range(int(random(200))):\n# x1 = random(x_min, x_max)\n# ima.strokeWeight(random(40))\n# ima.stroke(0, 0, random(100))\n# ima.line(x1, y_min, x1-x_min/2, y_max)\n# ima.filter(BLUR,int(random(2,30)))\n ima.endDraw()\n #du.save_graphic(ima, 'output', 1)\n\n\n imb.beginDraw()\n imb.colorMode(HSB, 360, 100, 100, 100)\n imb.rectMode(CENTER)\n imb.background(0, 0, 100)\n imb.noStroke()\n x_min = du.width * 0.2\n x_max = du.width * 0.8\n y_min = du.height * 0.2\n y_max = du.height * 0.8\n for i in range(args['num_objs_imb']):\n x = random(x_min, x_max)\n y = random(y_min, y_max)\n w = random(du.width * 0.3)\n h = random(du.height * 0.3)\n for j in range(int(random(1,args['num_folds_imb']))):\n imb.fill(0, 0, random(100))\n imb.rect(x, y, w-j*du.width*0.02, h-j*du.width*0.02)\n imb.filter(BLUR, 30)\n imb.endDraw()\n\n #du.save_graphic(imb, 'output', 2)\n\n\n ima.beginDraw()\n imb.beginDraw()\n out.beginDraw()\n\n ima.colorMode(HSB, 360, 100, 100, 100)\n imb.colorMode(HSB, 360, 100, 100, 100)\n out.colorMode(HSB, 360, 100, 100, 100)\n\n ima.loadPixels()\n imb.loadPixels()\n imc.loadPixels()\n out.loadPixels()\n#\n# # Strips of white around source image\n# for x in range(du.width):\n# loc = x\n# imc.pixels[loc] = ima.color(0, 0, 100)\n#\n# loc = x+((du.height-1)*du.width)\n# imc.pixels[loc] = ima.color(0, 0, 100)\n#\n# for y in range(du.height):\n# loc = 0+(y*du.width)\n# imc.pixels[loc] = ima.color(0, 0, 100)\n#\n# loc = (du.height-1)+(y*du.width)\n# imc.pixels[loc] = ima.color(0, 0, 100)\n\n imc.updatePixels()\n\n mx = [brightness(a) for a in ima.pixels]\n mx_min = min(mx)\n mx_max = max(mx)\n# mx = [map(i, mx_min, mx_max, 0, 100) for i in mx]\n\n my = [brightness(b) for b in ima.pixels]\n my_min = min(my)\n my_max = max(my)\n# my = [map(i, my_min, my_max, 0, 100) for i in my]\n\n for x in range(du.width):\n for y in range(du.height):\n loc = x+(y*du.width)\n\n x_ = map(mx[loc], mx_min, mx_max, 0, du.width-1)\n y_ = map(my[loc], my_min, my_max, 0, du.height-1)\n loc_ = int(x_+(y_*du.width))\n \n out.pixels[loc] = imc.pixels[loc_]\n\n\n ima.updatePixels()\n imb.updatePixels()\n out.updatePixels()\n \n ima.endDraw()\n imb.endDraw()\n out.endDraw()\n\n# for i,n in enumerate(m):\n# index = floor(map(n, 0, 255, 0, len(m)-1))\n# out.pixels[i] = imc.pixels[index]\n# if n > 253 or n < 3:\n# out.pixels[i] = out.color(0, 0, 100)\n# out.updatePixels()\n\n du.save_graphic(out, 'output', 0)\n\n # close Processing\n# exit()\n","sub_path":"ppy_terminal/sketches/img_map/img_map.py","file_name":"img_map.py","file_ext":"py","file_size_in_byte":6631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"427280224","text":"from drugdev import db, ma\n\n\nclass Contact(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(100), index=True, unique=True) # Assume unique usernames\n first_name = db.Column(db.String(50))\n surname = db.Column(db.String(50))\n emails = db.relationship('Email', backref='contact', lazy=True, cascade=\"all,delete\")\n\n def __repr__(self):\n return f''\n\n\nclass Email(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n email = db.Column(db.String(150), nullable=False)\n contact_id = db.Column(db.Integer, db.ForeignKey('contact.id'), nullable=False)\n\n def __repr__(self):\n return f''\n\n\nclass EmailSchema(ma.ModelSchema):\n class Meta:\n model = Email\n fields = ['email']\n\n\nclass ContactSchema(ma.ModelSchema):\n class Meta:\n model = Contact\n uri = ma.Hyperlinks(ma.URLFor('contactcall', username=''))\n emails = ma.Nested(EmailSchema, many=True)\n","sub_path":"drugdev/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"142696090","text":"#!/usr/bin/python3\n#-*- coding:UTF-8 -*-\n__author__ = 'linen'\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\nimport jieba #分词包\nimport pandas as pd\nimport numpy #numpy计算包\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.rcParams['figure.figsize'] = (2, 4)#视图窗口的大小\nfrom wordcloud import WordCloud#词云包\nimport os\n# os.chdir('F:/1network/project/py')\nf = open('comments.txt','a',encoding='utf-8')\n\n#分析网页函数\ndef getNowPlayingMovie_list(url): \n\tposition='https://movie.douban.com/cinema/nowplaying/'+url\n\t# html = urlopen('https://movie.douban.com/cinema/nowplaying/jiangmen/')\n\thtml = urlopen(position)\n\tbsObj=BeautifulSoup(html, \"html.parser\")\n\tnowplaying_movie = bsObj.findAll('div',{'id':'nowplaying'})\n\tnowplaying_movie_list = nowplaying_movie[0].findAll('li',{'class':'list-item'})\n\tnowplaying_list=[]\n\tfor item in nowplaying_movie_list:\n\t\tnowplaying_dict={}\n\t\tnowplaying_dict['id']=item['id']\n\t\tnowplaying_dict['name']=item['data-title']\n\t\tnowplaying_list.append(nowplaying_dict)\n\treturn nowplaying_list\n\n# 以电影“寻梦环游记”为例,找到其短评网址:https://movie.douban.com/subject/20495023/comments\n#爬取评论函数\ndef getCommentsById(movieId, pageNum): \n\tif pageNum>0: \n\t\tstart = (pageNum-1) * 20 \n\telse: \n\t\treturn False \n\trequrl='https://movie.douban.com/subject/'+movieId +'/comments'+'?' +'start=' + str(start) + '&limit=20'\n\tprint(requrl)\n\treap = urlopen(requrl)\n\tbsreap=BeautifulSoup(reap, \"html.parser\")\n\tcomment_div_list = bsreap.findAll('div',{'class':'comment'})\n\teachCommentList=[]\n\tfor item in comment_div_list:\n\t\tif item.findAll('p')[0].string is not None:\n\t\t\teachCommentList.append(item.findAll('p')[0].string)\n\treturn eachCommentList\n\n# 数据写入文件\ndef writeFile(s,parameter):\n\tf.write(s)\n\tf.write('\\n')\n\tf.write(parameter)\n\tf.write('\\n\\n\\n')\n\ndef main(url):\n\tcommentList = []\n\tNowPlayingMovie_list = getNowPlayingMovie_list(url)\n\t# 获取前五页的短评数据\n\tfor i in range(5): \n\t\tnum = i + 1 \n\t\tcommentList_temp = getCommentsById(NowPlayingMovie_list[7]['id'], num)\n\t\tcommentList.append(commentList_temp)\n\n\t#将列表中的数据转换为字符串\n\tcomments=''\n\tfor k in range(len(commentList)):\n\t\tcomments=comments+(str(commentList[k])).strip()\n\n\twriteFile('原始短评数据:',comments)\n\n\t# 数据清洗,正则匹配,只留汉字\n\tpattern = re.compile(r'[\\u4e00-\\u9af5]+')\n\tfilterdata=re.findall(pattern,comments)\n\tcleaned_comments = ''.join(filterdata)\n\n\twriteFile('数据清洗后的短评数据:',cleaned_comments)\n\n\t# 进行中文分词操作\n\tsegment = jieba.lcut(cleaned_comments)\n\n\tf.write('进行中文分词操作:\\n')\n\tfor item in segment:\n\t\tf.write(item)\n\t\tf.write('\\t')\n\tf.write('\\n\\n\\n')\n\n\t# 为中文分词加上序列号\n\twords_df=pd.DataFrame({'segment':segment})\n\n\twords_df_trans = str(words_df)\n\twriteFile('为中文分词加上序列号:',words_df_trans)\n\n\t# 去除停用词\n\tstopwords=pd.read_csv(\"stopwords.txt\",index_col=False,quoting=3,sep=\"\\n\",names=['stopword'], encoding='utf-8')\t\n\twords_df=words_df[~words_df.segment.isin(stopwords.stopword)]\n\n\twords_df_trans = str(words_df)\n\twriteFile('去除停用词后的分词:',words_df_trans)\n\n\t# 词频统计\n\twords_stat=words_df.groupby(by=['segment'])['segment'].agg({\"计数\":numpy.size})\n\twords_stat=words_stat.reset_index().sort_values(by=[\"计数\"],ascending=False)\n\n\twords_stat_trans=str(words_stat)\n\twriteFile('词频统计:',words_stat_trans)\n\n\t# 用词云显示\n\twordcloud=WordCloud(font_path=\"simhei.ttf\",background_color=\"white\",max_font_size=80) \n\tword_frequence = {x[0]:x[1] for x in words_stat.head(1000).values} \n\n\tword_frequence_trans=str(word_frequence)\n\twriteFile('词频字典:',word_frequence_trans)\n\t\n\tf.close()\n\n\twordcloud=wordcloud.fit_words(word_frequence)\n\tplt.imshow(wordcloud)\n\tplt.show()\n\t# plt.imsave('F:/1network/project/py/jiangmen.jpg',wordcloud)\n\tplt.imsave('jiangmen.jpg',wordcloud)\n\n# 主函数\nposition='jiangmen'\nmain(position)\n\n\n\n","sub_path":"douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"117727890","text":"# working with maps for numbers\ndef square(num):\n return num ** 2\n\nmy_nums = [1,2,3,4,5,6,10]\n\nfor item in map(square,my_nums):\n print(item)\n\nprint(list(map(square,my_nums)))\n\n# working with maps for strings\ndef splicer(mystring):\n if(len(mystring)%2 == 0):\n return \"even\"\n else:\n return \"uneven\"\n\nnames = [\"Brock\",\"Rose\",\"Casey\",\"Trisha\"]\n\nprint(list(map(splicer,names)))\n\n# filter function practice\ndef check_even(num):\n return num%2 == 0\n\nother_nums = [1,2,3,4,5,6,6,7,7,9,8,10]\n\nfor n in filter(check_even,other_nums):\n print(n)\n\nprint(list(filter(check_even,other_nums)))\n\n# don't usually name lambda\n# squareLambda = lambda num: num ** 2\n# print(squareLambda(123))\n\n# better use syntax for lambda\nprint(list(map(lambda num: num ** 2,other_nums)))\n\nprint(list(map(lambda mystr: mystr[::-1],names)))\nreverseList = list(filter(lambda num: num%2 == 0, other_nums))\nreverseList = reverseList[::-1]\nprint(reverseList)","sub_path":"map_and_filter.py","file_name":"map_and_filter.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"124588745","text":"import os\nimport shutil\nfrom sklearn.model_selection import train_test_split\nfrom multiprocessing import Pool\n\n\ndef move_data(src_dir, dst_dir, *args):\n src_dir_images = src_dir[\"images\"]\n src_dir_masks = src_dir[\"masks\"]\n\n dst_dir_images = dst_dir[\"images\"]\n dst_dir_masks = dst_dir[\"masks\"]\n\n images, mask = args\n\n os.makedirs(dst_dir_images, exist_ok=True)\n os.makedirs(dst_dir_masks, exist_ok=True)\n\n for image_name, mask_name in zip(images, mask):\n image_path = os.path.join(src_dir_images, image_name)\n mask_path = os.path.join(src_dir_masks, mask_name)\n\n dst_image_path = os.path.join(dst_dir_images, image_name)\n dst_mask_path = os.path.join(dst_dir_masks, mask_name)\n\n shutil.copyfile(image_path, dst_image_path)\n shutil.copyfile(mask_path, dst_mask_path)\n\n new_mask_name = mask_name.replace(r\"_mask.gif\", \".jpg\")\n\n os.rename(\n os.path.join(dst_dir_masks, mask_name),\n os.path.join(dst_dir_masks, new_mask_name),\n )\n\n print(\"Done\")\n return\n\n\nif __name__ == \"__main__\":\n MAIN_DIR = r\"dataset\"\n IMG_DIR = r\"train\"\n MASK_DIR = r\"train_masks\"\n\n all_images = sorted(os.listdir(os.path.join(MAIN_DIR, IMG_DIR)))\n all_masks = sorted(os.listdir(os.path.join(MAIN_DIR, MASK_DIR)))\n\n train_image, val_image, train_mask, val_mask = train_test_split(\n all_images, all_masks, shuffle=True, random_state=10, test_size=0.1\n )\n\n src = {\n \"images\": os.path.join(MAIN_DIR, IMG_DIR),\n \"masks\": os.path.join(MAIN_DIR, MASK_DIR),\n }\n dst_train = {\n \"images\": os.path.join(MAIN_DIR, \"data\", \"train_set\", \"images\"),\n \"masks\": os.path.join(MAIN_DIR, \"data\", \"train_set\", \"masks\"),\n }\n dst_val = {\n \"images\": os.path.join(MAIN_DIR, \"data\", \"validation_set\", \"images\"),\n \"masks\": os.path.join(MAIN_DIR, \"data\", \"validation_set\", \"masks\"),\n }\n\n half = len(train_mask) // 2\n arguments = [\n (src, dst_train, train_image[:half], train_mask[:half]),\n (src, dst_train, train_image[half:], train_mask[half:]),\n (src, dst_val, val_image, val_mask),\n ]\n\n pool = Pool(processes=3)\n print(\"[INFO] processes starting...\")\n pool.starmap(move_data, arguments)\n print(\"[INFO] waiting for processes to finish...\")\n pool.close()\n pool.join()\n print(\"[INFO] multiprocessing complete\")\n","sub_path":"Unet-implementation/create_sets.py","file_name":"create_sets.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"589973434","text":"from django.apps import apps as django_apps\nfrom django.db import models\nfrom django.db.models.deletion import PROTECT\nfrom django.utils import timezone\nfrom edc_base.model_validators.date import datetime_not_future\nfrom edc_base.model_managers import HistoricalRecords\nfrom edc_base.model_mixins import BaseUuidModel\nfrom edc_consent.model_mixins import RequiresConsentFieldsModelMixin\nfrom edc_constants.constants import NOT_APPLICABLE\nfrom edc_identifier.model_mixins import NonUniqueSubjectIdentifierFieldMixin\nfrom edc_lab.choices import PRIORITY\nfrom edc_lab.models import RequisitionIdentifierMixin\nfrom edc_lab.models import RequisitionModelMixin, RequisitionStatusMixin\nfrom edc_metadata.model_mixins.updates import UpdatesRequisitionMetadataModelMixin\nfrom edc_reference.model_mixins import RequisitionReferenceModelMixin\nfrom edc_search.model_mixins import SearchSlugManager\nfrom edc_visit_tracking.managers import CrfModelManager as VisitTrackingCrfModelManager\nfrom edc_visit_tracking.model_mixins import CrfModelMixin as VisitTrackingCrfModelMixin\nfrom edc_visit_tracking.model_mixins import PreviousVisitModelMixin\n\nfrom edc_visit_schedule.model_mixins import SubjectScheduleCrfModelMixin\n\n\nfrom .subject_visit import SubjectVisit\nfrom .model_mixins import SearchSlugModelMixin\nfrom edc_base.model_fields.custom_fields import OtherCharField\n\n\nclass Manager(VisitTrackingCrfModelManager, SearchSlugManager):\n pass\n\n\nclass SubjectRequisition(\n NonUniqueSubjectIdentifierFieldMixin,\n RequisitionModelMixin, RequisitionStatusMixin, RequisitionIdentifierMixin,\n VisitTrackingCrfModelMixin, SubjectScheduleCrfModelMixin,\n RequiresConsentFieldsModelMixin, PreviousVisitModelMixin,\n RequisitionReferenceModelMixin, UpdatesRequisitionMetadataModelMixin,\n SearchSlugModelMixin, BaseUuidModel):\n\n lab_profile_name = 'training_subject'\n\n subject_visit = models.ForeignKey(SubjectVisit, on_delete=PROTECT)\n\n requisition_datetime = models.DateTimeField(\n default=timezone.now,\n verbose_name='Requisition Date and Time',\n validators=[datetime_not_future, ])\n\n study_site = models.CharField(\n verbose_name='Study site',\n max_length=25,)\n\n estimated_volume = models.DecimalField(\n verbose_name='Estimated volume in mL',\n max_digits=7,\n decimal_places=2,\n help_text=(\n 'If applicable, estimated volume of sample for this test/order. '\n 'This is the total volume if number of \"tubes\" above is greater than 1'))\n\n item_count = models.IntegerField(\n verbose_name='Total number of items',\n help_text=(\n 'Number of tubes, samples, etc being sent for this test/order only. '\n 'Determines number of labels to print'))\n\n item_type = models.CharField(\n verbose_name='Item collection type',\n max_length=25,\n default=NOT_APPLICABLE)\n\n item_type_other = OtherCharField()\n\n priority = models.CharField(\n verbose_name='Priority',\n max_length=25,\n choices=PRIORITY,\n default='normal',)\n\n reason_not_drawn = models.CharField(\n verbose_name='If not drawn, please explain',\n max_length=25,\n default=NOT_APPLICABLE,)\n\n drawn_datetime = models.DateTimeField(\n verbose_name='Date / Time Specimen Drawn',\n validators=[datetime_not_future, ],\n null=True,\n blank=True,\n help_text=(\n 'If not drawn, leave blank.'))\n\n urgent_specify = models.TextField(\n verbose_name='If urgent, please specify',\n max_length=250,\n null=True,\n blank=True,)\n\n comments = models.TextField(\n max_length=350,\n null=True,\n blank=True)\n\n# on_site = CurrentSiteManager()\n\n objects = Manager()\n\n history = HistoricalRecords()\n\n def __str__(self):\n return (\n f'{self.requisition_identifier} '\n f'{self.panel_object.verbose_name}')\n\n def save(self, *args, **kwargs):\n if not self.id:\n edc_protocol_app_config = django_apps.get_app_config(\n 'edc_protocol')\n self.protocol_number = edc_protocol_app_config.protocol_number\n self.report_datetime = self.requisition_datetime\n self.subject_identifier = self.subject_visit.subject_identifier\n super().save(*args, **kwargs)\n\n def get_search_slug_fields(self):\n fields = super().get_search_slug_fields()\n fields.extend([\n 'requisition_identifier',\n 'human_readable_identifier', 'identifier_prefix'])\n return fields\n\n class Meta:\n unique_together = ('panel', 'subject_visit')\n","sub_path":"training_subject/models/subject_requisition.py","file_name":"subject_requisition.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"602275626","text":"import subprocess\nfrom celery import Celery\n\ncelery_app = Celery('tasks', broker='redis://localhost:6379/',\n backend='redis://localhost:6379/')\n\n\n@celery_app.task\ndef get_vid(id):\n process = subprocess.Popen(['./youtube-dl',id,'-x','--audio-format','mp3','-o','static/media/%(id)s.%(ext)s'])\n process.wait()","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"613381608","text":"import pandas as pd\nimport hashlib\n\n\ndef hash_float(text, salt='1', base=1000000):\n return int(hashlib.sha256((text+salt).encode('utf-8')).hexdigest(), 16) % base / base\n\n\ndef load_train_data(path='../data/training_data/training_nouns.tsv'):\n train_n = pd.read_csv(path, sep='\\t', encoding='utf-8')\n train_n['parents_list'] = train_n.PARENTS.apply(lambda x: x.split(','))\n\n ttrain = train_n[train_n.synset_hash <= 0.8]\n ttest = train_n[train_n.synset_hash > 0.8]\n ttest_dev = ttest[ttest.synset_hash <= 0.82]\n ttest_test1 = ttest[(ttest.synset_hash > 0.82) & (ttest.synset_hash <= 0.84)]\n ttest_test2 = ttest[(ttest.synset_hash > 0.84) & (ttest.synset_hash <= 0.86)]\n ttest_hidden = ttest[(ttest.synset_hash > 0.86)]\n forbidden_id = set(ttest.SYNSET_ID)\n return ttrain, ttest_dev, ttest_test1, ttest_test2, ttest_hidden, forbidden_id\n\n\ndef split_dict(\n dataset,\n train_share = 0.8,\n dev_share = 0.02,\n test1_share = 0.02,\n test2_share = 0.02,\n hid_share = 0.14,\n):\n assert train_share + dev_share + test1_share + test2_share + hid_share == 1\n train, dev, test1, test2, hid = {}, {}, {}, {}, {}\n\n for k, v in dataset.items():\n h = hash_float(k)\n if h <= train_share:\n train[k] = v\n elif h <= train_share + dev_share:\n dev[k] = v\n elif h <= train_share + dev_share + test1_share:\n test1[k] = v\n elif h <= train_share + dev_share + test1_share + test2_share:\n test2[k] = v\n else:\n hid[k] = v\n forbidden_words = {w for s in [dev, test1, test2, hid] for w in s.keys()}\n return train, dev, test1, test2, hid, forbidden_words\n","sub_path":"code/dale/data_split.py","file_name":"data_split.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"4074527","text":"import os\nimport re\n\nimport pandas as pd\nimport numpy as np\n\ndef pymeasure_parser(data_fname, swept_column, swept_params, codename_converter={}, column_name_converter={}, comment='#'):\n \"\"\"\n Parses information out of a pymeasure data file\n\n Parameters\n ----------\n data_fname : str\n filename\n swept_column : str\n name of data column which was swept\n swept_params : list of str\n The \"code\" names of the parameters swept\n codename_converter : dict\n Dictionary where keys are the plain names of the parameters in the\n pymeasure procedure, and the value is a tuple whose first element is a\n string of the codename of the parameter and the second is a function to\n cast the value (int, float, bool, str etc.)\n column_name_converter : dict\n Dictionary used to map any pymeasure column names to different column\n names. Keys are the expected original column names, values are the \n new ones. Will only attempt to rename columns included as keys in the\n converter.\n comment : str\n Character used to represent a commented line\n\n Returns\n -------\n swept_col_data : numpy.array\n Array containing the swept column data values\n data : dict\n Dictonary where the key is a name of a data column and the value is\n a numpy array of values to use.\n param_values : dict\n A dictonary where the key is the name of a parameter and the value is\n its value for this particular data file\n \"\"\"\n\n # read parameter plain names and values from data file\n header_read = False\n parameters = {} # plain name : value\n with open(data_fname) as f:\n while not header_read:\n line = f.readline()\n if line.startswith(comment+'\\t'): # is a parameter line\n regex = (comment+\"\\t(?P[^:]+):\\s(?P[^\\s]+)\"\n \"(?:\\s(?P.+))?\")\n search = re.search(regex, line)\n if search is None:\n raise Exception(\"Error parsing header line {}.\".format(line))\n else:\n parameters[search.group('name')] = search.group(\"value\")\n elif line.startswith(comment):\n pass\n else:\n header_read = True\n\n # get list of plain names of swept_params to check against\n swept_params_plain = [] # plain names\n # TODO: deal with multiple plain names for the same codename\n plainname_converter = {v[0]: k for k, v in codename_converter.items()}\n for pname in swept_params:\n try:\n swept_params_plain.append(plainname_converter[pname])\n except KeyError:\n raise KeyError(\"Parameter {} missing from codename converter!\".format(pname))\n\n # convert parameters to dictionary of codenames : converted values\n param_values = {}\n for swept_param in swept_params_plain:\n try:\n v = parameters[swept_param]\n codename = codename_converter[swept_param][0]\n converted_val = codename_converter[swept_param][1](v)\n param_values[codename] = converted_val\n except KeyError: # if we do not find the swept param in the parameters dict\n raise ValueError(f\"Did not find {swept_param} parameter in the data file!\")\n\n # retrieving procedure data\n data_df = pd.read_csv(data_fname, comment='#')\n data_dict = data_df.to_dict('list')\n new_data_keys = {}\n for k in data_dict.keys():\n if k in column_name_converter:\n new_data_keys[k] = column_name_converter[k]\n else:\n new_data_keys[k] = k\n data_dict = {new_data_keys[k]: np.array(v) for k, v in data_dict.items()}\n\n # separate swept column data from the non-swept columns\n try:\n swept_col_data = data_dict.pop(swept_column)\n except KeyError:\n raise KeyError(f\"{swept_column} was not found in the data file columns!\")\n\n return swept_col_data, data_dict, param_values\n\ndef FMR_parser(data_fname, swept_column, swept_params, codename_converter={}, comment='#'):\n \"\"\"\n Parses information out of a pymeasure data file without using Results.load()\n For particular use with classes from Colin to get nominal field points in\n FMR scans.\n\n Parameters\n ----------\n data_fname : str\n filename\n swept_column : str\n name of data column which was swept. Not used in this instance, but\n needs to be accepted so callers function properly\n swept_params : list of str\n The names of the parameters swept\n codename_converter : dict\n Dictionary where keys are the plain names of the parameters in the\n pymeasure procedure, and the value is a tuple whose first element is a\n string of the codename of the parameter and the second is a function to\n cast the value (int, float, bool, str etc.)\n comment : str\n Character used to represswept_colent a commented line\n\n Returns\n -------\n swept_col_data : numpy.array\n Array containing the swept column data values\n data : dict\n Dictonary where the key is a name of a data column and the value is\n a numpy array of values to use.\n param_values : dict\n A dictonary where the key is the name of a parameter and the value is\n its value for this particular data file\n \"\"\"\n # read parameter plain names and values from data file\n header_read = False\n parameters = {} # plain name to value found\n with open(data_fname) as f:\n while not header_read:\n line = f.readline()\n if line.startswith(comment+'\\t'): # is a parameter line\n regex = (comment+\"\\t(?P[^:]+):\\s(?P[^\\s]+)\"\n \"(?:\\s(?P.+))?\")\n search = re.search(regex, line)\n if search is None:\n raise Exception(\"Error parsing header line {}.\".format(line))\n else:\n parameters[search.group('name')] = search.group(\"value\")\n elif line.startswith(comment):\n pass\n else:\n header_read = True\n\n # get list of plain names of swept_params to check against\n swept_params_plain = [] # plain names\n plainname_converter = {v[0]: k for k, v in codename_converter.items()}\n for pname in swept_params:\n try:\n swept_params_plain.append(plainname_converter[pname])\n except KeyError:\n raise KeyError(\"Parameter {} missing from codename converter!\".format(pname))\n\n # convert parameters to dictionary of codenames\n param_values = {}\n for k, v in parameters.items():\n if k in swept_params_plain:\n codename = codename_converter[k][0]\n converted_val = codename_converter[k][1](v)\n param_values[codename] = converted_val\n # don't care if we have extra (unused) parameters in the data file\n\n # check if values for all swept params were found\n for pname in swept_params:\n if pname not in param_values.keys():\n raise ValueError(\"Did not find {} parameter value in the data file!\".format(pname))\n\n # retrieving procedure data\n data_df = pd.read_csv(data_fname, comment='#')\n data_dict = data_df.to_dict('list') # converts to a dictionary\n data_dict = {k: np.array(v) for k, v in data_dict.items()}\n # Don't delete any columns since we will make a column of nominal field\n # points.\n\n # make our own swept column\n field_params = {}\n for k, v in parameters.items():\n if codename_converter[k][0] == 'start_field':\n field_params['field_start'] = codename_converter[k][1](v)\n elif codename_converter[k][0] == 'end_field':\n field_params['field_stop'] = codename_converter[k][1](v)\n elif codename_converter[k][0] == 'field_points':\n field_params['num_field_points'] = codename_converter[k][1](v)\n else:\n pass\n field_points_nominal = np.linspace(field_params['field_start'],\n field_params['field_stop'],\n field_params['num_field_points'])\n\n return field_points_nominal, data_dict, param_values\n\ndef extract_parameters(fname, param_codes=[], codename_converter={}, comment='#'):\n \"\"\"\n Parses pymeasure data files and extracts particular parameter values.\n\n Parameters\n ----------\n fname : str\n filename\n param_codes : list of str\n The codenames of the parameters whose we wish to extract\n codename_converter : dict\n Dictionary where keys are the plain names of the parameters in the\n pymeasure procedure, and the value is a tuple whose first element is a\n string of the codename of the parameter and the second is a function to\n cast the value (int, float, bool, str etc.)\n comment : str\n Character used to represent a commented line\n\n Returns\n -------\n dict\n A dictionary mapping parameter codenames to their values\n \"\"\"\n # plainnames of params which we need\n needed_param_plainnames = [k for k, v in codename_converter.items() if v[0] in param_codes]\n\n # read header and extract needed parameter values\n header_read = False\n parameters = {}\n with open(fname) as f:\n while not header_read:\n line = f.readline()\n if line.startswith(comment+'\\t'): # is a parameter line\n regex = (comment+\"\\t(?P[^:]+):\\s(?P[^\\s]+)\"\n \"(?:\\s(?P.+))?\")\n search = re.search(regex, line)\n if search is None:\n raise Exception(\"Error parsing header line {}.\".format(line))\n else:\n if search.group('name') in needed_param_plainnames:\n converter = codename_converter[search.group('name')]\n parameters[converter[0]] = converter[1](search.group(\"value\"))\n elif line.startswith(comment):\n pass\n else:\n header_read = True\n return parameters\n","sub_path":"analysis/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":10156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"401629849","text":"import socket\n\nmysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntry:\n\n url = input(\"Enter the full url address: \")\n #hostname = urlparse(url).netloc\n hostname=url.split('/')[2]\n print(hostname)\nexcept:\n print('URL entered is not in correct format')\n print('Please enter url in format http://hostame.com/path/to/the/url')\n print('or in format https://hostame.com/path/to/the/url')\n#added try/except blocks\ntry:\n mysock.connect((hostname, 80))\n cmd = 'GET {0} HTTP/1.0\\r\\n\\r\\n'.format(url).encode()\n mysock.sendall(cmd)\n count=0\n while True:\n \n data = mysock.recv(512)\n if len(data) < 1:\n break\n \n if count < 3000:\n count = count + len(data)\n print(data.decode(),end='')\n print('\\n Total Count of Characters: ',count) \n mysock.close()\nexcept:\n print('something is not right')\n","sub_path":"socket/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"88477392","text":"#-*-coding:utf-8-*-\n# date:2020-03-28\n# Author: X.L.Eric\n# function: image pixel - uint8 (0~255)\n\nimport cv2 # 加载 OpenCV 库\nimport numpy as np # 加载 numpy 库\nif __name__ == \"__main__\":\n img_h = 480\n img_w = 640\n img = np.zeros([img_h,img_w], dtype = np.uint8)\n\n cv2.namedWindow('image_0', 1)\n cv2.imshow('image_0', img)\n cv2.waitKey(0)\n\n img.fill(100)\n cv2.namedWindow('image_100', 1)\n cv2.imshow('image_100', img)\n cv2.waitKey(0)\n\n img.fill(255)\n cv2.namedWindow('image_255', 1)\n cv2.imshow('image_255', img)\n cv2.waitKey(0)\n","sub_path":"chapter_01/example_1-2.py","file_name":"example_1-2.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"259517510","text":"#!/bin/env python3\nimport click\nimport re\nimport os\nimport sys\n\ndef findTTS(gff,genelist):\n dict_cds={}\n #dict_utr={}\n with open (gff,'r') as f:\n File=f.read()\n for gene in genelist:\n cds1=re.findall(r'(\\w+?)\\tIRHS-2017\\tCDS\\t(\\d+)\\t(\\d+)\\t.\\t(.)\\t(\\d)\\tID=CDS:'+gene+r'[.]1',File,re.M)\n #cds1=[('Chr11','1','100','+','0/1/2'),.....]\n #utr5=re.findall(r'five_prime_UTR\\t(\\d+)\\t(\\d+)\\t.\\t(.)\\t(.+?)\\tID=five_prime_UTR:'+gene+r'[.]\\d+?;',File,re.M)\n #utr5=[('1','1000','-','.'),......]\n if cds1 !=[]:\n dict_cds[gene]=cds1\n #if utr5 != []:\n # dict_utr[gene]=utr5\n return dict_cds #,dict_utr\n\ndef trans_base(seq):\n seq=seq[::-1]\n dict_base={\"A\":\"T\",\"C\":\"G\",\"T\":\"A\",\"G\":\"C\"}\n for i in range(len(seq)):\n re_seq.append(dict_base[seq[i]])\n\n return re_seq\n\n\n@click.command()\n@click.option('--gene')\n@click.option('--gff')\n@click.option('--out')\n@click.option('--cutscript')\n@click.option('--genome')\n\ndef main(gene,gff,out,cutscript):\n with open( gene ,'r') as f:\n genelist=[]\n for gene in f:\n gene=gene.strip()\n if gene != '':\n genelist.append(gene)\n dict_cds=findTTS(gff,genelist)\n with open(out+'.cdspromoter_chr_pos.tmp','w') as fc:\n #with open(out+'utrpromoter_chr_pos.tmp') as fu:\n for gene in genelist:\n if gene in dict_cds:\n cds_chr=dict_cds[gene][0][0]\n cds_start=int(dict_cds[gene][0][1])\n cds_end=int(dict_cds[gene][0][2])\n cds_strand=dict_cds[gene][0][3]\n if cds_strand == '+':\n seq_start=cds_start-2000\n seq_end=cds_start-1\n elif cds_strand == '-':\n seq_start=cds_end+1\n seq_end=cds_end+2000\n fc.write('{}\\t{}\\t{}\\t{}\\t{}\\n'.format(gene,cds_chr,str(seq_start),str(seq_end),cds_strand))\n cmd=\"perl \"+ cutscript +' '+genome+' '+out+'.cdspromoter_chr_pos.tmp ' +out+'.cut_seq.fa'\n print(cmd)\n result=os.system(cmd)\n if result == '0':\n with open (out+'.cdspromoter_chr_pos.tmp','r') as fi:\n #>genename_chr_1_100_+\n dict_seq={}\n for line in f:\n if line[0] == '>':\n line=line.strip().split('_')\n header=line.strip()\n else:\n seq=line.strip()\n if line[3] == '+':\n dict[header]=seq\n elif line[3] == '-':\n reseq=trans_base(seq)\n dict[header]=reseq\n with open(out,'w') as fp:\n for k,v in dict_seq:\n fp.write(k+'\\n'+v+'\\n')\n else:\n sys.exit('Cut sequences Error!')\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"get_Promoter.py","file_name":"get_Promoter.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"207219703","text":"from django.http import HttpResponse\r\nfrom lab2 import db as DataBase\r\nimport re as RegExp\r\n\r\ndef fillDataBaseWithJSONFile(table, fields, values):\r\n\treturn DataBase.insert(DataBase.escapeBySymbol(table, '`'), fields, values)\r\n\r\ndef addOrderer(request, flag = False):\r\n\tif (flag):\r\n\t\tif (not RegExp.match('\\w{3,10}\\s\\w{3,10}', request.GET['orderer'])):\r\n\t\t\treturn -1\r\n\t\tordererName = request.GET['orderer'].split(' ')[0]\r\n\t\tordererSurname = request.GET['orderer'].split(' ')[1]\r\n\telse:\r\n\t\tif (not RegExp.match('\\w{3,10}\\s\\w{3,10}', request.GET['name'] + request.GET['surname'])):\r\n\t\t\treturn -1\r\n\t\tordererName = request.GET['name']\r\n\t\tordererSurname = request.GET['surname']\r\n\tordererWhere = ' '.join(('WHERE `name` = ',\r\n\t\t\t\t\t\t\tDataBase.escapeBySymbol(ordererName, \"'\"),\r\n\t\t\t\t\t\t\t' AND `surname` = ',\r\n\t\t\t\t\t\t\tDataBase.escapeBySymbol(ordererSurname, \"'\")))\r\n\torderer = DataBase.selectAllOrderers(where = ordererWhere)\r\n\tif (len(orderer) == 0):\r\n\t\tordererId = DataBase.insert(DataBase.escapeBySymbol('orderers', \"`\"),\r\n\t\t\t\t\t\t\t\t\t['name', 'surname'], [ordererName, ordererSurname])\r\n\telse:\r\n\t\tordererId = orderer[0][0]\r\n\treturn ordererId\r\n\r\ndef addProduct(request):\r\n\t_where = ' '.join(('WHERE `product` = ', DataBase.escapeBySymbol(request.GET['product'], \"'\")))\r\n\tproduct = DataBase.select(DataBase.escapeBySymbol('products', '`'), where = _where)\r\n\tdepartmentId = addDepartment(request, flag = True)\t\r\n\tif (len(product) != 0 or departmentId < 0):\r\n\t\treturn -1\r\n\treturn DataBase.insert(DataBase.escapeBySymbol('products', '`'),\r\n\t\t\t\t\t\t\t['product', 'cost', 'department'],\r\n\t\t\t\t\t\t\t[request.GET['product'], str(request.GET['cost']), str(departmentId)])\r\n\r\ndef addDepartment(request, flag = False):\r\n\tres = DataBase.select(DataBase.escapeBySymbol('departments', \"`\"),\r\n\t\t\t\t\t\t\twhere = 'WHERE `name` = ' + DataBase.escapeBySymbol(request.GET['department'], \"'\"))\r\n\tif (len(res) == 0):\r\n\t\treturn DataBase.insert(DataBase.escapeBySymbol('departments', '`'), ['name'], [request.GET['department']])\r\n\tif (flag):\r\n\t\treturn res[0][0]\r\n\treturn -1\r\n\r\ndef addOrder(request):\r\n\t_where = ' '.join(('WHERE `product` = ', DataBase.escapeBySymbol(request.GET['product'], \"'\")))\r\n\tproduct = DataBase.select(DataBase.escapeBySymbol('products', \"`\"), where = _where)\r\n\torderer = addOrderer(request, True)\r\n\tif (len(product) == 0 or orderer <= 0):\r\n\t\treturn {'res': -1}\r\n\treturn {'res': DataBase.insert(DataBase.escapeBySymbol('orders', '`'),\r\n\t\t\t\t\t\t\t['product', 'count', 'orderer', 'terms'],\r\n\t\t\t\t\t\t\t[str(product[0][0]), str(request.GET['count']), str(orderer), request.GET['terms']]),\r\n\t\t\t'cost': int(product[0][2]) * int(request.GET['count'])}","sub_path":"models/addmodels.py","file_name":"addmodels.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"481338997","text":"from pyfirmata import Arduino, util\nimport time\nprint(\"- Firmata Test -\")\nprint(\"Init device\")\n\ntry:\n board = Arduino('/dev/cu.usbserial-FT9A0FK7')\n it = util.Iterator(board)\n it.start()\n board.analog[0].enable_reporting()\n\n print(\"Turn on led\")\n board.digital[2].write(1)\n time.sleep(1)\n print(\"Turn off led\")\n board.digital[2].write(0)\n\n for i in range(0, 10):\n print(\"Read analog value\")\n print(board.analog[0].read())\n time.sleep(1)\n\n print(\"Done\")\n\nexcept Exception as e:\n print(e)\n\nfinally:\n print(\"Quit\")\n board.exit()","sub_path":"AtmegaSlave/Evaluation/firmata_test.py","file_name":"firmata_test.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"355377634","text":"import sys\ninput = lambda: sys.stdin.readline().rstrip() \nimport bisect as bs\n\ndef resolve():\n n = int(input())\n ukv = [list(map(int, input().split())) for _ in range(n)]\n\n d = [-1]*n\n f = [-1]*n\n stk = []\n status = [0]*n\n\n t = 1\n for i in range(n):\n if status[i]==0:\n stk.append(i)\n while len(stk)>0:\n a = stk[-1]\n if status[a]==0:\n d[a] = t\n t += 1\n status[a] = 1\n elif status[a]==1:\n stk.pop()\n f[a] = t\n t += 1\n status[a] = 2\n else:\n stk.pop()\n for i in reversed(ukv[a][2:]):\n if status[i-1]==0:\n stk.append(i-1) \n\n for i in range(n):\n print(i+1, d[i], f[i])\n\nif __name__ == '__main__':\n resolve()\n","sub_path":"Python_codes/p02238/s548202198.py","file_name":"s548202198.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"302680388","text":"#! /usr/bin/env python\n\nfrom homie.device_lock import Device_Lock\nfrom .base import Base\n\n\nclass Door_Lock(Base, Device_Lock):\n def __init__(self, isy_device=None, homie_settings=None, mqtt_settings=None):\n\n Base.__init__(self, isy_device)\n\n Device_Lock.__init__(\n self,\n self.get_homie_device_id(),\n isy_device.name,\n homie_settings,\n mqtt_settings,\n )\n\n lock = self.isy_device.get_property(\"lock\")\n if lock is not None:\n self.property_change(\"lock\", lock)\n\n def get_homie_device_id(self):\n return \"lock-\" + Base.get_homie_device_id(self)\n\n def lock(self):\n self.isy_device.lock()\n\n def unlock(self):\n self.isy_device.unlock()\n\n def property_change(self, property_, value):\n if property_ == \"lock\":\n self.update_lock(value.upper())\n\n Base.property_change(self, property_, value)\n\n","sub_path":"isy_homie/devices/door_lock.py","file_name":"door_lock.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"231100882","text":"from selenium import webdriver\r\nfrom webdriver_manager.chrome import ChromeDriverManager\r\nimport json\r\nimport requests\r\n\r\n\r\n#as a example!!! More to try :)\r\nURL = \"https://www.geeksforgeeks.org/vector-in-cpp-stl/\"\r\n\r\n\r\ndef get_driver():\r\n \r\n chrome_options = webdriver.ChromeOptions()\r\n settings = {\r\n \"recentDestinations\": [\r\n {\"id\": \"Save as PDF\", \"origin\": \"local\", \"account\": \"\"}\r\n ],\r\n \"selectedDestinationId\": \"Save as PDF\",\r\n \"version\": 2,\r\n }\r\n prefs = {\r\n \"printing.print_preview_sticky_settings.appState\": json.dumps(settings)\r\n }\r\n chrome_options.add_experimental_option(\"prefs\", prefs)\r\n chrome_options.add_argument(\"--kiosk-printing\")\r\n\r\n \r\n browser = webdriver.Chrome(\r\n executable_path=ChromeDriverManager().install(), options=chrome_options\r\n )\r\n return browser\r\n\r\n\r\ndef download_article(URL):\r\n browser = get_driver()\r\n browser.get(URL)\r\n\r\n \r\n browser.execute_script(\"window.print();\")\r\n browser.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n URL = input(\"provide article URL: \")\r\n \r\n if requests.get(URL).status_code == 200:\r\n try:\r\n download_article(URL)\r\n print(\"Your article is successfully downloaded\")\r\n except Exception as e:\r\n print(e)\r\n else:\r\n print(\"Enter a valid working URL\")","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"512454141","text":"# Copyright 2017-2019 Aaron C. Prunty\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#==============================================================================\n\nimport sys\nimport argparse\nimport textwrap\nimport numpy as np\nimport pickle\nfrom pathlib import Path\nfrom vezda.signal_utils import add_noise\nfrom vezda.plot_utils import default_params\nfrom vezda.plot_utils import FontColor\n\ndef info():\n commandName = FontColor.BOLD + 'vznoise:' + FontColor.END\n description = ' add band-limited white noise to the recorded data'\n \n return commandName + description\n\ndef cli():\n parser = argparse.ArgumentParser()\n parser.add_argument('--fmin', type=float,\n help='Specify the minimum frequency component of the noise.')\n parser.add_argument('--fmax', type=float,\n help='Specify the maximum frequency component of the noise.')\n parser.add_argument('--snr', type=float,\n help='''Specify the desired signal-to-noise ratio. Must be a positive\n real number.''')\n args = parser.parse_args()\n \n #==============================================================================\n try:\n Dict = np.load('noisyData.npz')\n fmin = Dict['fmin']\n fmax = Dict['fmax']\n snr = Dict['snr']\n except FileNotFoundError:\n fmin, fmax, snr = None, None, None\n \n # Used for getting frequency units\n if Path('plotParams.pkl').exists():\n plotParams = pickle.load(open('plotParams.pkl', 'rb'))\n else:\n plotParams = default_params()\n \n if all(v is None for v in [args.fmin, args.fmax, args.snr]):\n # if no arguments are passed\n \n if all(v is None for v in [fmin, fmax, snr]):\n # and no parameters have been assigned values\n sys.exit(textwrap.dedent(\n '''\n No noise has been added to the data.\n '''))\n else:\n # print fmin, fmax, snr and exit\n fu = plotParams['fu']\n if fu != '':\n sys.exit(textwrap.dedent(\n '''\n Band-limited white noise has already been added to the data:\n \n Minimum frequency: {:0.2f} {}\n Maximum frequency: {:0.2f} {}\n Signal-to-noise ratio: {:0.2f}\n '''.format(fmin, fu, fmax, fu, snr)))\n else:\n sys.exit(textwrap.dedent(\n '''\n Band-limited white noise has already been added to the data:\n \n Minimum frequency: {:0.2f}\n Maximum frequency: {:0.2f}\n Signal-to-noise ratio: {:0.2f}\n '''.format(fmin, fmax, snr)))\n \n elif all(v is not None for v in [args.fmin, args.fmax, args.snr]):\n # if all arguments were passed\n \n if args.fmax < args.fmin:\n sys.exit(textwrap.dedent(\n '''\n RelationError: The maximum frequency component of the nosie must be greater\n than or equal to the mininum frequency component.\n '''))\n elif args.fmin <= 0:\n sys.exit(textwrap.dedent(\n '''\n ValueError: The minimum frequency component of the noise must be strictly positive.\n '''))\n elif args.snr <= 0:\n sys.exit(textwrap.dedent(\n '''\n ValueError: The signal-to-noise ratio (SNR) must be strictly positive.\n '''))\n \n fmin = args.fmin\n fmax = args.fmax\n snr = args.snr\n fu = plotParams['fu']\n if fu != '':\n print(textwrap.dedent(\n '''\n Adding band-limited white noise:\n \n Minimum frequency: {:0.2f} {}\n Maximum frequency: {:0.2f} {}\n Signal-to-noise ratio: {:0.2f}\n '''.format(fmin, fu, fmax, fu, snr)))\n else:\n print(textwrap.dedent(\n '''\n Adding band-limited white noise:\n \n Minimum frequency: {:0.2f}\n Maximum frequency: {:0.2f}\n Signal-to-noise ratio: {:0.2f}\n '''.format(fmin, fmax, snr)))\n \n # Load the 3D data array and recording times from data directory\n datadir = np.load('datadir.npz')\n recordedData = np.load(str(datadir['recordedData']))\n recordingTimes = np.load(str(datadir['recordingTimes']))\n dt = recordingTimes[1] - recordingTimes[0]\n \n noisyData = add_noise(recordedData, dt, fmin, fmax, snr)\n np.savez('noisyData.npz', noisyData=noisyData, fmin=fmin, fmax=fmax, snr=snr)\n \n else:\n sys.exit(textwrap.dedent(\n '''\n Error: All command-line arguments \\'--fmin\\', \\'--fmax\\', and \\'--snr\\' must\n be used when parameterizing the noise.\n '''))","sub_path":"vezda/addNoise.py","file_name":"addNoise.py","file_ext":"py","file_size_in_byte":5752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"86622749","text":"import sys\nfrom PyQt4 import QtCore, QtGui\nfrom src.gui.ui_MainWindow import Ui_MainWindow\nimport src.gui.Gnuplot as Gnuplot\n\nfrom src.genetic.selection import *\nfrom src.problem import *\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n _fromUtf8 = lambda s: s\n\nclass MainWindow(QtGui.QWidget):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n\n self.selectionMethod = None\n self.problemController = None\n\n self.gp = Gnuplot.Gnuplot()\n self.setupConnections()\n\n self.realtimePlot = False\n self.plotDataBest = None\n self.plotDataAvg = None\n self.plotDataWorst = None\n\n def setupConnections(self):\n QtCore.QObject.connect(self.ui.selectionCombo, QtCore.SIGNAL(_fromUtf8(\"currentIndexChanged(const QString)\")), self.applySelectionMethod)\n QtCore.QObject.connect(self.ui.selectionOptionsButton, QtCore.SIGNAL(_fromUtf8(\"clicked(bool)\")), self.applySelectionMethod)\n QtCore.QObject.connect(self.ui.problemCombo, QtCore.SIGNAL(_fromUtf8(\"currentIndexChanged(const QString)\")), self.applyProblem)\n \n # Konsola\n QtCore.QObject.connect(self.ui.consoleBox, QtCore.SIGNAL(_fromUtf8(\"textChanged()\")), self.autoScrollConsole)\n\n # Przyciski Rozpocznij i zatrzymaj\n QtCore.QObject.connect(self.ui.startButton, QtCore.SIGNAL(_fromUtf8(\"clicked(bool)\")), self.startClicked)\n QtCore.QObject.connect(self.ui.stopButton, QtCore.SIGNAL(_fromUtf8(\"clicked(bool)\")), self.stopClicked)\n \n # Wykres\n QtCore.QObject.connect(self.ui.realtimePlotCheckbox, QtCore.SIGNAL(_fromUtf8(\"toggled(bool)\")), self.toggleRealtimePlot)\n QtCore.QObject.connect(self.ui.plotButton, QtCore.SIGNAL(_fromUtf8(\"clicked(bool)\")), self.plotPopulation)\n\n def setProblemConnections(self):\n QtCore.QObject.connect(self.ui.crossoverChanceSpin, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.problemController.setCrossoverChance)\n QtCore.QObject.connect(self.ui.mutationChanceSpin, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.problemController.setMutationChance)\n QtCore.QObject.connect(self.ui.populationSpin, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.problemController.setPopulationSize)\n QtCore.QObject.connect(self.ui.maxGenerationSpin, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.problemController.setGenerationStop)\n QtCore.QObject.connect(self.ui.geneMutation, QtCore.SIGNAL(_fromUtf8(\"toggled(bool)\")), self.problemController.setGeneMutation)\n QtCore.QObject.connect(self.ui.bestToNewGeneration, QtCore.SIGNAL(_fromUtf8(\"toggled(bool)\")), self.problemController.setBestToNewGeneration)\n \n # Podlaczmy sygnaly dla komunikacji watek -> gui\n QtCore.QObject.connect(self.problemController.problemThread, QtCore.SIGNAL(_fromUtf8(\"consoleWrite(PyQt_PyObject)\")), self.updateConsole)\n QtCore.QObject.connect(self.problemController.problemThread, QtCore.SIGNAL(_fromUtf8(\"plotData(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)\")), self.updatePlotData)\n QtCore.QObject.connect(self.problemController.problemThread, QtCore.SIGNAL(_fromUtf8(\"problemEnd()\")), self.stopClicked)\n\n def destroyProblemConnections(self):\n QtCore.QObject.disconnect(self.ui.crossoverChanceSpin, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.problemController.setCrossoverChance)\n QtCore.QObject.disconnect(self.ui.mutationChanceSpin, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.problemController.setMutationChance)\n QtCore.QObject.disconnect(self.ui.populationSpin, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.problemController.setPopulationSize)\n QtCore.QObject.disconnect(self.ui.maxGenerationSpin, QtCore.SIGNAL(_fromUtf8(\"valueChanged(int)\")), self.problemController.setGenerationStop)\n QtCore.QObject.disconnect(self.ui.geneMutation, QtCore.SIGNAL(_fromUtf8(\"toggled(bool)\")), self.problemController.setGeneMutation)\n QtCore.QObject.disconnect(self.ui.bestToNewGeneration, QtCore.SIGNAL(_fromUtf8(\"toggled(bool)\")), self.problemController.setBestToNewGeneration)\n\n # Komunikacja watek -> gui\n QtCore.QObject.disconnect(self.problemController.problemThread, QtCore.SIGNAL(_fromUtf8(\"consoleWrite(PyQt_PyObject)\")), self.updateConsole)\n QtCore.QObject.disconnect(self.problemController.problemThread, QtCore.SIGNAL(_fromUtf8(\"plotData(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)\")), self.updatePlotData)\n QtCore.QObject.disconnect(self.problemController.problemThread, QtCore.SIGNAL(_fromUtf8(\"problemEnd()\")), self.stopClicked)\n \n def passStartValues(self):\n self.problemController.setCrossoverChance(self.ui.crossoverChanceSpin.value())\n self.problemController.setMutationChance(self.ui.mutationChanceSpin.value())\n self.problemController.setPopulationSize(self.ui.populationSpin.value())\n self.problemController.setGenerationStop(self.ui.maxGenerationSpin.value())\n self.problemController.setGeneMutation(self.ui.geneMutation.isChecked())\n self.problemController.setBestToNewGeneration(self.ui.bestToNewGeneration.isChecked())\n\n def startClicked(self):\n if not self.ui.plotButton.isEnabled():\n self.ui.plotButton.setEnabled(True)\n \n # Czyscimy dane do wykresu\n self.plotDataBest = []\n self.plotDataAvg = []\n self.plotDataWorst = []\n self.gp = Gnuplot.Gnuplot()\n\n self.ui.startButton.setEnabled(False)\n self.ui.stopButton.setEnabled(True)\n self.ui.consoleBox.clear()\n\n # Inicjujemy watek i przekazujemy wartosci poczatkowe do problemu\n self.problemController.initSolvingThread()\n self.passStartValues()\n\n # Zadbajmy o polaczenia\n self.setProblemConnections()\n\n # Uruchamiamy watek do rozwiazywania problemu\n self.problemController.startSolvingThread()\n\n def stopClicked(self):\n self.ui.stopButton.setEnabled(False)\n self.ui.startButton.setEnabled(True)\n self.problemController.stopSolvingThread()\n\n # Zerwijmy polaczenia\n self.destroyProblemConnections()\n\n def applyProblem(self):\n if self.problemController is not None:\n QtCore.QObject.disconnect(self.ui.problemOptionsButton, QtCore.SIGNAL(_fromUtf8(\"clicked(bool)\")), self.problemController.showOptionsDialog)\n\n p = self.ui.problemCombo.currentIndex()\n # 0 - Ekstrama lokalne\n if p == 0:\n self.problemController = localExtremumController.LocalExtremumController()\n # 1 - problem plecakowy\n if p == 1:\n self.problemController = backpackController.backpackController()\n # 2 - miejsca zerowe\n if p == 2:\n self.problemController = zeroController.ZeroController()\n \n if self.selectionMethod is not None:\n self.problemController.selection = self.selectionMethod\n\n self.problemController.showOptionsDialog()\n \n # Odblokujmy panel z opcjami i przycisk opcji problemu\n self.ui.optionsBox.setEnabled(True)\n self.ui.problemOptionsButton.setEnabled(True)\n self.ui.selectionOptionsButton.setEnabled(False)\n QtCore.QObject.connect(self.ui.problemOptionsButton, QtCore.SIGNAL(_fromUtf8(\"clicked(bool)\")), self.problemController.showOptionsDialog)\n\n def applySelectionMethod(self):\n text = self.ui.selectionCombo.currentText()\n if text == \"Turniej\":\n self.ui.selectionOptionsButton.setEnabled(True)\n [value,ok] = QtGui.QInputDialog.getInt(self,\"Rozmiar grupy\",\"Podaj rozmiar grupy turniejowej\", 4,2,50000,1)\n if ok:\n self.selectionMethod = competition.CompetitionSelection(value)\n else:\n self.selectionMethod = competition.CompetitionSelection(4)\n if text == \"Ruletka\":\n self.ui.selectionOptionsButton.setEnabled(False)\n self.selectionMethod = roulette.RouletteSelection()\n\n self.problemController.selection = self.selectionMethod\n \n # Odblokuj przycisk Rozpocznij\n self.ui.startButton.setEnabled(True)\n \n def updateConsole(self, data):\n d = str(data)\n self.ui.consoleBox.appendPlainText(d)\n \n def autoScrollConsole(self):\n c = self.ui.consoleBox.textCursor();\n c.movePosition(QtGui.QTextCursor.End);\n self.ui.consoleBox.setTextCursor(c);\n\n def updatePlotData(self,best,avg,worst):\n self.plotDataBest.append(best)\n self.plotDataAvg.append(avg)\n self.plotDataWorst.append(worst)\n if self.realtimePlot:\n self.plotPopulation()\n\n def toggleRealtimePlot(self, value):\n self.realtimePlot = value\n\n def plotPopulation(self):\n self.gp.title(self.ui.problemCombo.currentText())\n plotBest = Gnuplot.PlotItems.Data(self.plotDataBest, with_=\"lines\", title=\"Najlepszy organizm\")\n plotAvg = Gnuplot.PlotItems.Data(self.plotDataAvg, with_=\"lines\", title=\"Srednia z populacji\")\n plotWorst = Gnuplot.PlotItems.Data(self.plotDataWorst, with_=\"lines\", title=\"Najgorszy organizm\")\n self.gp.plot(plotBest, plotAvg, plotWorst);\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n myapp = MainWindow()\n myapp.show()\n sys.exit(app.exec_())\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":9463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"48531053","text":"# -*- coding: utf-8 -*-\r\nimport os, sys, time\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom lib.page.abstract_page import AbstractPage\r\n\r\n\r\nclass DocPage(AbstractPage):\r\n def get_doc_num(self):\r\n self.driver.get(self.base_url + \"/doc-browse.html\")\r\n time.sleep(1)\r\n num = self.driver.find_element_by_xpath(u'//*[@id=\"docList\"]/tfoot/tr/td/div/strong[1]').text\r\n return int(num)\r\n\r\n def create_doc(self):\r\n self.driver.get(self.base_url + \"/doc-browse.html\")\r\n time.sleep(1)\r\n create_doc_btn = u'//*[@id=\"featurebar\"]/div[1]/a'\r\n self.driver.find_element_by_xpath(create_doc_btn).click()\r\n time.sleep(3)\r\n\r\n doc_title = \"测试doc_\" + time.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n self.driver.find_element_by_id('title').clear()\r\n self.driver.find_element_by_id('title').send_keys(doc_title.decode('utf-8'))\r\n time.sleep(1)\r\n\r\n if self.driver.name == 'internet explorer':\r\n self.driver.find_element_by_xpath(u'//*[@id=\"fileBox1\"]/tbody/tr/td[1]/div/input').click()\r\n os.system(os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + '/data/upload/doc_ie.exe')\r\n elif self.driver.name == 'firefox':\r\n self.driver.find_element_by_xpath(u'//*[@id=\"fileBox1\"]/tbody/tr/td[1]/div/input').click()\r\n os.system(os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + '/data/upload/doc_firefox.exe')\r\n else:\r\n file_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) + '/data/upload/a.doc'\r\n self.driver.find_element_by_xpath(u'//*[@id=\"fileBox1\"]/tbody/tr/td[1]/div/input').send_keys(file_path)\r\n time.sleep(1)\r\n\r\n self.driver.execute_script(r'scrollTo(0,3000)')\r\n actions = ActionChains(self.driver)\r\n actions.move_to_element(self.driver.find_element_by_id('submit')).click().perform()\r\n time.sleep(3)\r\n","sub_path":"lib/page/doc_page.py","file_name":"doc_page.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"253167144","text":"from django.http import HttpResponse\nfrom django.template import RequestContext, loader\nfrom django.shortcuts import render\nimport datetime, math\nfrom american_history_usa import models \nfrom main import utils\n\n# The Four Horsemen:\n # 2) Author Pages\n # 3) Category Pages\n # 4) Articles\n # 5) Other Pages (i.e. front page, about the site, etc.)\ndef amusa_home(request):\n context = RequestContext(request, {\n })\n return render(request, 'american_history_usa/home.html', context)\n\ndef amusa_author(request, url_slug):\n author = models.Author.objects.get(url_slug=url_slug)\n context = RequestContext(request, {\n 'author': author, \n }) \n return render(request, 'american_history_usa/author.html', context)\n\ndef amusa_category(request, url_slug):\n category = models.Category.objects.get(url_slug=url_slug)\n context = RequestContext(request, {\n 'category': category,\n })\n return render(request, 'american_history_usa/category.html', context)\n\ndef amusa_article(request, url_slug):\n article = models.Article.objects.get(url_slug=url_slug)\n author = models.Author.objects.get(id=article.author_id)\n context = RequestContext(request, {\n 'article': article,\n 'author': author,\n })\n return render(request, 'american_history_usa/article.html', context)\n\ndef amusa_page(request, url_slug):\n page = models.Page.objects.get(url_slug=url_slug)\n context = RequestContext(request, {\n 'page': page,\n })\n return render(request, 'american_history_usa/page.html', context)\n\n\ndef amusa_archive(request, page_number):\n articles_per_page = 40\n articles = []\n page_count = math.ceil(len(models.Article.objects.all()) / articles_per_page)\n \n try:\n page_number = abs(int(page_number))\n except:\n page_number = 1\n\n x = (page_number * articles_per_page) - articles_per_page\n\n for j in range(x, x + articles_per_page):\n try:\n articles.append(models.Article.objects.order_by('postdate_key')[j])\n except:\n 1\n\n context = RequestContext(request, {\n 'page_number': page_number,\n 'page_count': page_count,\n 'articles': articles,\n })\n return render(request, 'american_history_usa/archive.html', context)\n\n\ndef amusa_search_results(request):\n query_string = ''\n found_entries = None\n if ('q' in request.GET) and request.GET['q'].strip():\n query_string = request.GET['q']\n entry_query = utils.get_query(query_string, ['title', 'content',])\n found_entries = models.Article.objects.filter(entry_query).order_by('postdate_key')\n\n context = RequestContext(request, {\n 'query_string': query_string,\n 'found_entries': found_entries,\n })\n return render(request, 'american_history_usa/search_results.html', context) \n\n\n\n","sub_path":"american_history_usa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"166544874","text":"# -*- coding: utf-8 -*-\nfrom django import template\nfrom django.utils.safestring import mark_safe\n\nregister = template.Library()\n\n\ndef pluralize_fr(value, arg=u's'):\n \"\"\"\n Returns a plural suffix if the value is greater than 1. By default, 's' is used as\n the suffix.\n \"\"\"\n if not u',' in arg:\n arg = u',' + arg\n bits = arg.split(u',')\n if len(bits) > 2:\n return u''\n singular_suffix, plural_suffix = bits[:2]\n\n try:\n if int(value) > 1:\n return plural_suffix\n except ValueError: # Invalid string that's not a number.\n pass\n except TypeError: # Value isn't a string or a number; maybe it's a list?\n try:\n if len(value) > 1:\n return plural_suffix\n except TypeError: # len() of unsized object.\n pass\n return singular_suffix\n\n\ndef price_display(price, currency=u\"€\"):\n \"\"\" Displays the price in human unicode format \"\"\"\n if isinstance(price, float):\n if round(price, 2) == round(price, 0):\n htmlamount = u\"%d%c%s\" % (int(round(price, 0)),\n unichr(160),\n currency)\n else:\n htmlamount = (u\"%0.2f\" % round(price, 2)).replace(\".\", \",\") + unichr(160) + currency\n elif isinstance(price, int):\n htmlamount = u\"%d%c%s\" % (price, unichr(160), currency)\n else:\n htmlamount = u\"%s%c%s\" % (str(price), unichr(160), currency)\n return htmlamount\n\n\ndef price_display_nocur(price):\n \"\"\" Displays the price in human unicode format without the currency \"\"\"\n if isinstance(price, float):\n if round(price, 2) == round(price, 0):\n htmlamount = u\"%d\" % (int(round(price, 0)))\n else:\n htmlamount = (u\"%0.2f\" % round(price, 2)).replace(\".\", \",\")\n elif isinstance(price, int):\n htmlamount = unicode(price)\n else:\n htmlamount = unicode(price)\n return htmlamount\n\n\ndef truncatechars(string, length=30):\n \"\"\" Shortens a string to max characters or add \"...\" at the end.\n @return: the shortened string \"\"\"\n if len(string) > length - 3:\n return \"%s...\" % string[:(length - 3)]\n return string\n\n\ndef cssclass(field, cssclasses):\n \"\"\"\n Add the attribute css class for form Field 'field' with 'cssclasses'.\n \"\"\"\n cssclass_list = cssclasses.split(\" \")\n attrs = field.field.widget.attrs\n for cssclass in cssclass_list:\n if cssclass.lower() not in attrs.get(\"class\", \"\").lower():\n attrs[\"class\"] = attrs.get(\"class\", \"\") + \" \" + cssclass.lower()\n return str(field)\n\n\ndef placeholder(field, placeholder):\n \"\"\"\n Add the attribute placeholder for form Field 'field' with 'placeholder'.\n If string already, add it manually.\n \"\"\"\n try:\n attrs = field.field.widget.attrs\n attrs[\"placeholder\"] = placeholder\n except AttributeError:\n parts = field.split(\"input \")\n return mark_safe(parts[0] + 'input placeholder=\"%s\" ' % placeholder + parts[1])\n return str(field)\n\n\ndef value(field, value):\n \"\"\"\n Add the attribute value for form Field 'field' with 'value'.\n If string already, add it manually.\n \"\"\"\n try:\n attrs = field.field.widget.attrs\n attrs[\"value\"] = value\n except AttributeError:\n parts = field.split(\"input \")\n return mark_safe(parts[0] + 'input value=\"%s\" ' % value + parts[1])\n return str(field)\n\n\nclass AddGetParameter(template.Node):\n def __init__(self, values):\n self.values = values\n\n def render(self, context):\n req = template.resolve_variable('request', context)\n params = req.GET.copy()\n try:\n del params['page']\n except:\n pass\n for key, value in self.values.items():\n params[key] = value.resolve(context)\n return '?%s' % params.urlencode()\n\n\ndef add_get(parser, token):\n pairs = token.split_contents()[1:]\n values = {}\n for pair in pairs:\n s = pair.split('=', 1)\n values[s[0]] = parser.compile_filter(s[1])\n return AddGetParameter(values)\n\n\nregister.tag('add_get', add_get)\nregister.filter('price_display', price_display)\nregister.filter('price_display_nocur', price_display_nocur)\nregister.filter('truncatechars', truncatechars)\nregister.filter('cssclass', cssclass)\nregister.filter('placeholder', placeholder)\nregister.filter('value', value)\nregister.filter('pluralize_fr', pluralize_fr)\n","sub_path":"project_name/libs/common/templatetags/common_extras.py","file_name":"common_extras.py","file_ext":"py","file_size_in_byte":4492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"410818860","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def widthOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if not root: return 0\n level = collections.deque([root])\n res = -sys.maxsize\n while level:\n n = len(level)\n res = max(n, res)\n #print(level)\n nextlevel = collections.deque([])\n for i in range(n):\n temp = level.popleft()\n if not temp:\n nextlevel += [None, None]\n else:\n nextlevel += [temp.left, temp.right]\n while nextlevel and not nextlevel[0]:\n nextlevel.popleft()\n while nextlevel and not nextlevel[-1]:\n nextlevel.pop()\n level = nextlevel\n return res\n","sub_path":"Leetcode/tree/662_MaximumWidthOfBinaryTree/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"364912654","text":"#!/usr/bin/env python3\n\n\"\"\"\nConstruct Athenaeum and Parameterise molecule example.\n\nThis example creates two Athenaeums out of the amino acid files in ./SourceMolecules:\n- AutomaticAthenaem: contains all possible fragments of the amino acids, with 1 atom\noverlaps\n- ManualAthenaeum: contains fragments as defined by the .frag files in ./SourceMolecules.\n\nThis example runs CherryPicker using these Athenaeums to parameterise the molecules\nin ./TestMolecules. The parameters are saved in the same folder in .itp format.\n\nNote that ManualAthenaeum is added to CherryPicker first, meaning full amino acids will\nbe preferentially identified before the algorithm resorts to smaller fragments in the\nAutomaticAthenaeum.\n\"\"\"\n\nimport indigox as ix\nfrom pathlib import Path\nimport time\nimport fnmatch\nimport os\n\n# You always need a forcefield\nff = ix.GenerateGROMOS54A7()\n\nmanualAthPath = \"ManualAthenaeum.ath\"\nautoAthPath = \"AutomaticAthenaeum.ath\"\n\n\ndef LoadAndSaveAthenaeums():\n \"\"\" Generate and save the Athenaeums used in the paper\n On our system this takes approximately 6.5 minutes to execute and uses a maximum of 3.5GB of memory.\n The saved files are 463 kB and 684.2 MB respectively.\n :return:\n \"\"\"\n\n settings = ix.Athenaeum.Settings\n man_ath = ix.Athenaeum(ff)\n man_ath.SetBool(settings.SelfConsistent)\n auto_ath = ix.Athenaeum(ff, 1)\n\n # Need to set a larger than default limit as some of the amino acid molecules are large\n auto_ath.SetInt(settings.MoleculeSizeLimit, 60)\n\n mol_path = \"SourceMolecules\"\n mol_extn = \"*.frag\"\n\n index = 1\n mol_count = len(fnmatch.filter(os.listdir(mol_path), mol_extn))\n\n print(\"Loading molecules into Athenaeums...\")\n\n # Load all the molecules\n for aa in Path(mol_path).glob(mol_extn):\n print(\"\\tLoading Amino acid #{} of {}\".format(index, mol_count))\n index += 1\n\n mol, fragments = ix.LoadFragmentFile(aa, ff)\n mol.SetName(aa.stem)\n\n # add the fragments to the manual Athenaeum\n for frag in fragments:\n man_ath.AddFragment(frag)\n\n # add the molecule to the automatic Athenaeum\n auto_ath.AddAllFragments(mol)\n\n # Save the athenaeums\n ix.SaveAthenaeum(man_ath, manualAthPath)\n ix.SaveAthenaeum(auto_ath, autoAthPath)\n\n\ndef RunCherryPicker():\n \"\"\" Load athenaeums and run the cherrypicker algorithm on the 3 molecules used in the paper.\n On our system, loading the Athenaeums takes about 12 seconds,\n then running Loading, Running CherryPicker, and Saving the test molecules takes about 5 seconds.\n :return:\n \"\"\"\n\n # Load the athenaeums\n man_ath = ix.LoadAthenaeum(manualAthPath)\n auto_ath = ix.LoadAthenaeum(autoAthPath) # Is a large file so may take a few seconds to load\n\n # Create the CherryPicker algorithm to use\n cherrypicker = ix.algorithm.CherryPicker(ff)\n cherrypicker.AddAthenaeum(man_ath) # add the manual one first so it's used first\n cherrypicker.AddAthenaeum(auto_ath)\n\n # Set the CherryPicker options we want\n settings = ix.algorithm.CherryPicker.Settings\n cherrypicker.SetInt(settings.MinimumFragmentSize, 2)\n cherrypicker.SetInt(settings.MaximumFragmentSize, 20)\n\n # Load each of the test molecules and run cherrypicker\n for test in Path(\"TestMolecules\").glob(\"*.pdb\"):\n mol = ix.LoadPDBFile(test, test.with_suffix(\".ixd\"))\n parameterised = cherrypicker.ParameteriseMolecule(mol)\n\n # save the parameterisation in ITP format\n ix.SaveITPFile(test.with_suffix(\".itp\"), mol, parameterised)\n print()\n\n\nif __name__ == \"__main__\":\n before_loadAth = time.time()\n if not (Path(manualAthPath).is_file() and Path(autoAthPath).is_file()):\n LoadAndSaveAthenaeums()\n\n before_CP = time.time()\n RunCherryPicker()\n\n print(\"\\nLoad Athenaeums: {:10.3f} s\".format(before_CP - before_loadAth))\n print(\"Run CherryPicker: {:10.3f} s\".format(time.time() - before_CP))\n","sub_path":"examples/CherryPicker/cherrypicker_example.py","file_name":"cherrypicker_example.py","file_ext":"py","file_size_in_byte":3942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"590762075","text":"import pymongo\nfrom datetime import datetime\nmyclient = pymongo.MongoClient(\"mongodb+srv://mlh115:Keybo%40rd1@siot-bzvep.mongodb.net/test?retryWrites=true&w=majority\")\n\nmydb = myclient[\"gas\"]\nmycol = mydb[\"readings\"]\n\ndatetime_now = datetime.now()\n\nmydict = { \"LPG\": \"John\", \"CO\": \"Highway 37\", \"Smoke\": \"hello\", \"readingDate\": datetime_now}\n\nx = mycol.insert_one(mydict)\nprint(x)\n","sub_path":"Sensing/Smoke/test-dbupload.py","file_name":"test-dbupload.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"182601139","text":"import glob\nimport numpy as np\nimport cv2\nfrom numpy.lib.npyio import load\nfrom skimage.feature import hog\nfrom skimage.transform import rescale\nfrom sklearn import preprocessing\nimport pickle\n\nclass Dataset:\n\n scalar_file_name = 'scalar'\n\n # Min Number of Files in Each Class = 1000\n\n def __init__(self, recaptcha_data_location, batch_size=32, max_each_class=1000, train_percent = 0.8):\n self.recaptcha_data_location = recaptcha_data_location\n\n # Initialize \n self.batch_size = batch_size\n self.current_index = 0\n self.max_each_class = max_each_class\n self.train_percent = train_percent\n\n # Initialize x data locations and y labels\n self.x_data_locations = []\n self.y_labels = []\n test_x_locations = []\n test_y_labels = []\n\n\n # Labels\n self.label_dict = {\n 'paper': 0,\n 'rock': 1,\n 'scissors': 2,\n }\n \n # Set Number Classes\n self.num_classes_list = [0, 1, 2]\n\n # Load data\n self.load_data()\n self.shuffle_data()\n # Save out Test Data\n self.test_x_locations = self.x_data_locations[int(len(self.x_data_locations)*self.train_percent):]\n self.test_y_labels = self.y_labels[int(len(self.y_labels)*self.train_percent):]\n\n # Remove test data from training data\n self.x_data_locations = self.x_data_locations[:int(len(self.x_data_locations)*self.train_percent)]\n self.y_labels = self.y_labels[:int(len(self.y_labels)*self.train_percent)]\n # Calculate Scalar of Train Data\n # self.calculate_scalar()\n\n print(np.array(self.x_data_locations).shape)\n print(np.array(self.y_labels).shape)\n\n def __len__(self):\n if len(self.x_data_locations) != len(self.y_labels):\n raise Exception('x_data_loaded and y_labels are not the same length')\n return len(self.x_data_locations)\n\n\n # Loads Labels and X Data Locations\n def load_data(self):\n # Glob folders in train folder\n folders = glob.glob(self.recaptcha_data_location + '\\\\*')\n \n for folder in folders:\n # Get label\n label = folder.split('\\\\')[-1]\n label_id = self.label_dict[label]\n\n # Get image files\n image_files = glob.glob(folder + '\\\\*.png')\n\n # Add data to x_data and y_labels\n added = 0\n for image_file in image_files:\n self.x_data_locations.append(image_file)\n self.y_labels.append(label_id)\n added += 1\n if added>=self.max_each_class:\n break\n\n # Shuffles data locations and labels together\n def shuffle_data(self):\n # Shuffle data\n # Zip x locations and y labels together and turn into a list\n combined = list(zip(self.x_data_locations, self.y_labels))\n # Shuffle this list\n np.random.shuffle(combined)\n # Unzip the list after zipping it again\n self.x_data_locations, self.y_labels = zip(*combined)\n\n # Returns an image and label (after loading into memory)\n def get_index(self, index):\n # Get image and label at index\n image = cv2.imread(self.x_data_locations[index])\n \n # Testing Transforms\n # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # image = cv2.GaussianBlur(image, (5, 5), 0)\n # image = cv2.medianBlur(image, 5)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n image = cv2.Canny(image, 70, 90)\n\n # Reshape Image\n image = image.reshape(1, -1)\n # Normalize Image\n # image = self.scalar.transform(image) \n\n # Flatten image to get rid of arbitrary first dimension after we transform the image\n image = image.flatten() \n label = self.y_labels[index]\n return image, label\n\n # Calculatee Scalar for data\n def calculate_scalar(self):\n # Load all x data into ram\n x_data = []\n print('Loading x data into ram')\n loaded_counter = 0\n for x_location in self.x_data_locations:\n image = cv2.imread(x_location)\n\n # Testing Transforms\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n image = cv2.GaussianBlur(image, (5, 5), 0)\n image = cv2.medianBlur(image, 5)\n\n x_data.append(image.flatten())\n loaded_counter += 1\n if loaded_counter % 1000 == 0:\n print('Loaded ' + str(loaded_counter) + ' images')\n print('Calculating Scalar')\n # Calculate Scalar\n self.scalar = preprocessing.StandardScaler().fit(x_data)\n\n def get_next_batch(self):\n # Get Batch\n x_data = []\n y_labels = []\n for i in range(self.current_index, self.current_index + self.batch_size):\n # Get image and label\n if i < len(self.x_data_locations):\n image, label = self.get_index(i)\n x_data.append(image)\n y_labels.append(label)\n # Update current index\n self.current_index += self.batch_size\n\n return x_data, y_labels\n\n def get_test_data(self):\n x_data = []\n y_labels = []\n # Loads Images\n for i in range(len(self.test_x_locations)):\n # Load Image\n image = cv2.imread(self.test_x_locations[i])\n\n # Testing Transforms\n # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # image = cv2.GaussianBlur(image, (5, 5), 0)\n # image = cv2.medianBlur(image, 5)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n image = cv2.Canny(image, 70, 90)\n\n # Reshape Image\n image = image.reshape(1, -1)\n # Normalize Image\n # image = self.scalar.transform(image)\n\n # Flatten Image\n image = image.flatten()\n # Get Label\n label = self.test_y_labels[i]\n # Add to list\n x_data.append(image)\n y_labels.append(label)\n return x_data, y_labels\n\n # Resets Index\n def reset_index(self):\n self.current_index = 0\n # Shuffle Data after each epoch\n self.shuffle_data()\n ","sub_path":"DataLoader.py","file_name":"DataLoader.py","file_ext":"py","file_size_in_byte":6266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"524988771","text":"'''\nCreated on 2016/4/11\n\n:author: hubo\n'''\nfrom vlcp.event.runnable import RoutineContainer\nfrom vlcp.server.module import callAPI\nfrom uuid import uuid1\nfrom vlcp.event.event import Event, withIndices\nfrom vlcp.utils.dataobject import multiwaitif\nfrom vlcp.protocol.openflow.openflow import OpenflowErrorResultException\nfrom namedstruct.namedstruct import dump\nfrom pprint import pformat\nimport logging\n\n@withIndices('updater', 'type')\nclass FlowUpdaterNotification(Event):\n STARTWALK = 'startwalk'\n DATAUPDATED = 'dataupdated'\n FLOWUPDATE = 'flowupdate'\n\nclass FlowUpdater(RoutineContainer):\n def __init__(self, connection, initialkeys, requestid = None, logger = None):\n RoutineContainer.__init__(self, connection.scheduler)\n self._initialkeys = initialkeys\n self._connection = connection\n self._walkerdict = {}\n self._savedkeys = ()\n self._savedresult = []\n self._updatedset = set()\n self._updatedset2 = set()\n if not logger:\n self._logger = logging.getLogger(__name__ + '.FlowUpdater')\n else:\n self._logger = logger\n if requestid is None:\n self._requstid = str(uuid1())\n else:\n self._requstid = requestid\n self._dataupdateroutine = None\n self._flowupdateroutine = None\n def reset_initialkeys(self, keys, values):\n pass\n def walkcomplete(self, keys, values):\n if False:\n yield\n def updateflow(self, connection, addvalues, removevalues, updatedvalues):\n if False:\n yield\n def shouldupdate(self, newvalues, updatedvalues):\n return True\n def restart_walk(self):\n self._restartwalk = True\n for m in self.waitForSend(FlowUpdaterNotification(self, FlowUpdaterNotification.STARTWALK)):\n yield m\n def _dataobject_update_detect(self):\n _initialkeys = set(self._initialkeys)\n def expr(newvalues, updatedvalues):\n if any(v.getkey() in _initialkeys for v in updatedvalues if v is not None):\n return True\n else:\n return self.shouldupdate(newvalues, updatedvalues)\n while True:\n for m in multiwaitif(self._savedresult, self, expr, True):\n yield m\n updatedvalues, _ = self.retvalue\n if not self._updatedset:\n self.scheduler.emergesend(FlowUpdaterNotification(self, FlowUpdaterNotification.DATAUPDATED))\n self._updatedset.update(updatedvalues)\n def updateobjects(self, updatedvalues):\n if not self._updatedset:\n self.scheduler.emergesend(FlowUpdaterNotification(self, FlowUpdaterNotification.DATAUPDATED))\n self._updatedset.update(set(updatedvalues).intersection(self._savedresult))\n def _flowupdater(self):\n lastresult = set(v for v in self._savedresult if v is not None and not v.isdeleted())\n flowupdate = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.FLOWUPDATE)\n while True:\n currentresult = set(v for v in self._savedresult if v is not None and not v.isdeleted())\n additems = currentresult.difference(lastresult)\n removeitems = lastresult.difference(currentresult)\n updateditems = set(self._updatedset2).intersection(currentresult)\n updateditems.difference_update(removeitems)\n updateditems.difference_update(additems)\n self._updatedset2.clear()\n lastresult = currentresult\n if not additems and not removeitems and not updateditems:\n yield (flowupdate,)\n continue\n for m in self.updateflow(self._connection, additems, removeitems, updateditems):\n yield m\n \n def main(self):\n try:\n lastkeys = set()\n dataupdate = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.DATAUPDATED)\n startwalk = FlowUpdaterNotification.createMatcher(self, FlowUpdaterNotification.STARTWALK)\n self.subroutine(self._flowupdater(), False, '_flowupdateroutine')\n presave_update = set()\n while True:\n self._restartwalk = False\n presave_update.clear()\n presave_update.update(self._updatedset)\n self._updatedset.clear()\n _initialkeys = set(self._initialkeys)\n for m in callAPI(self, 'objectdb', 'walk', {'keys': self._initialkeys, 'walkerdict': self._walkerdict,\n 'requestid': self._requstid}):\n yield m\n if self._updatedset:\n if any(v.getkey() in _initialkeys for v in self._updatedset):\n continue\n lastkeys = set(self._savedkeys)\n self._savedkeys, self._savedresult = self.retvalue\n removekeys = tuple(lastkeys.difference(self._savedkeys))\n self.reset_initialkeys(self._savedkeys, self._savedresult)\n _initialkeys = set(self._initialkeys)\n if self._dataupdateroutine:\n self.terminate(self._dataupdateroutine)\n self.subroutine(self._dataobject_update_detect(), False, \"_dataupdateroutine\")\n self._updatedset.update(v for v in presave_update)\n if removekeys:\n for m in callAPI(self, 'objectdb', 'munwatch', {'keys': removekeys,\n 'requestid': self._requstid}):\n yield m\n for m in self.walkcomplete(self._savedkeys, self._savedresult):\n yield m\n self._updatedset2.update(self._updatedset)\n self._updatedset.clear()\n for m in self.waitForSend(FlowUpdaterNotification(self, FlowUpdaterNotification.FLOWUPDATE)):\n yield m\n while not self._restartwalk:\n if self._updatedset:\n if any(v.getkey() in _initialkeys for v in self._updatedset):\n break\n else:\n self._updatedset2.update(self._updatedset)\n self._updatedset.clear()\n self.scheduler.emergesend(FlowUpdaterNotification(self, FlowUpdaterNotification.FLOWUPDATE))\n yield (dataupdate, startwalk)\n finally:\n self.subroutine(callAPI(self, 'objectdb', 'munwatch', {'keys': self._savedkeys,\n 'requestid': self._requstid}))\n if self._flowupdateroutine:\n self.terminate(self._flowupdateroutine)\n self._flowupdateroutine = None\n if self._dataupdateroutine:\n self.terminate(self._dataupdateroutine)\n self._dataupdateroutine = None\n def execute_commands(self, conn, cmds):\n if cmds:\n try:\n for m in conn.protocol.batch(cmds, conn, self):\n yield m\n except OpenflowErrorResultException:\n self._logger.warning(\"Some Openflow commands return error result on connection %r, will ignore and continue.\\n\"\n \"Details:\\n%s\", conn,\n \"\\n\".join(\"REQUEST = \\n%s\\nERRORS = \\n%s\\n\" % (pformat(dump(k)), pformat(dump(v)))\n for k,v in self.openflow_replydict.items()))\n","sub_path":"vlcp/utils/flowupdater.py","file_name":"flowupdater.py","file_ext":"py","file_size_in_byte":7665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"150652878","text":"import pandas as pd\nimport re\nfrom utilities import files_metadata as fm\n\n\n\"\"\"\nHelper function to remove unwanted columns from a csv.\nCan either return the modified df or write it to a file\n\"\"\"\n\n\ndef remove_unused_cols(file_path, file_out_path, out_type, drop_cols, enc_type='utf-8'):\n initial_file = pd.read_excel(file_path, encoding=enc_type)\n initial_file_df = pd.DataFrame(initial_file)\n\n initial_file_req_df = initial_file_df.drop(drop_cols, axis=1)\n\n if out_type == 'file':\n initial_file_req_df.to_csv(file_out_path, encoding='utf-8', index=False)\n elif out_type == 'df':\n return initial_file_req_df\n\n\n# Removing Byrne, LLEB, WEED, GOT_COPS, HIRING_TOT2, HIRING_RATE columns from main file which won't be used.\n'''\nremove_unused_cols(file_path='C:/Users/sshaik2/Criminal_Justice/Projects/main_census_merge/data/Final_Main_1990_2001.xlsx',\n enc_type=\"ISO-8859-1\", file_out_path='C:/Users/sshaik2/Criminal_Justice/Projects/main_census_merge/data/Final_Main_Var_1990_2001.csv',\n drop_cols=['BYRNE_DISCRET_580', 'LLEBG_592', 'WEED_AND_SEED_595', 'GOT_COPS', 'HIRING_TOT2', 'HIRING_RATE'], out_type='file')\n'''\n\n\n\"\"\"\nRemove 2nd column header row i.e Id, Id2, Geography etc..\nRename \n\"\"\"\n\n\ndef remove_unused_rows(file_path):\n initial_df = pd.DataFrame(pd.read_csv(file_path, encoding='utf-8'))\n # Dropping the 1st row which has Id, Id2, Geography etc.. values below the 1st column headers. drop() returns a new df\n reduced_df = initial_df.drop(initial_df.index[0])\n return reduced_df\n\n\n\"\"\"\n- renames 'GEO.display-label'column to 'placename'\n- strip ',' and state name from placename value\n\"\"\"\n\n\ndef remove_state_from_placename(pl_name, ptrn):\n pattern = re.compile(ptrn)\n match = pattern.search(pl_name)\n if match:\n return pl_name[:match.start()]\n else:\n return pl_name\n\n\n\"\"\"\n extracts the corresponding 'P**' string from the filename and prefixes it to each of the column headers\n\"\"\"\n\n\ndef update_census_file_headers(df_obj, file_path):\n # rename 'GEO.display-label' col\n df_obj.rename(columns={'GEO.display-label': 'placename'}, inplace=True)\n\n \"\"\"\n Remove statename from placename variable\n Ex: Remove \",Alaska\" from Anchorage municipality, Alaska\n \"\"\"\n\n ############### To-Do: See if you can just split at , instead of using regex ###################\n df_obj['placename'] = df_obj['placename'].apply(remove_state_from_placename, args=('\\,',))\n\n # extract file name from the file path\n file_name = file_path.split('/')[-1]\n\n # extract the corresponding 'P**' string from the filename\n file_type = file_name.split('_')[3]\n\n # get the list of column headers\n col_headers = list(df_obj)\n\n # create new list of column headers by appending correpsonding P*** string to the existing column headers\n new_col_headers = col_headers[:3]+list(file_type+x for x in col_headers[3:])\n df_obj.columns = new_col_headers\n return df_obj\n\n\n\"\"\"\nWrite the modified df to modified_files folder\n\"\"\"\n\n\ndef write_updated_df_file(updated_df, out_path):\n updated_df.to_csv(out_path, encoding='utf-8', index=False)\n\n\n\"\"\"\nIterates over each directory(cities 00/10, counties 00/10) and then works on each census file within that directory\nUses remove_unused_rows, update_all_census_files functions to modify census files to have required headers with corresponding P*** prefixes\n\"\"\"\n\nif __name__ == '__main__':\n # get the list of input and output file path tuples\n file_paths_list = fm.find_files_path('/Users/salma/Studies/Research/Criminal_Justice/research_projects/US Crime Analytics/data',\n ori_files_folder_name='reduced_census_files', mod_files_folder_name='updated_col_headers')\n\n\n # for every tuple of inp and out file paths, perform the reqd operations\n for f_paths in file_paths_list:\n ip_file, op_file = f_paths\n df1 = remove_unused_rows(ip_file)\n updated_df = update_census_file_headers(df1, ip_file)\n write_updated_df_file(updated_df, op_file)","sub_path":"utilities/clean_files.py","file_name":"clean_files.py","file_ext":"py","file_size_in_byte":4067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"434225874","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nfrom main import read_input_pheno_file\nfrom map_phenotype_to_gene import map2hpoWithPhenoSynonyms\nimport pandas as pd\nfrom langdetect import detect\nfrom google import google\nimport json\nimport requests\nimport jieba\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nBASE = os.path.dirname(os.path.abspath(__file__))\nCHPO = os.path.join(BASE, \"data/chpo.2016-10.xls\")\n\n\ndef smart_match(input_en, chpo):\n search_results = google.search(input_en, 1)\n wiki = list(set([i.name[:-12] for i in search_results if i.name[-9:]=='Wikipedia']))\n for i in wiki:\n try:\n wiki_match = chpo[chpo['表型英文名']==i]\n if len(wiki_match) > 0:\n return wiki_match.to_json(orient='records')\n except:\n pass\n\n match_result = map2hpoWithPhenoSynonyms(input_en)\n match_result = sorted(match_result, key = lambda x: x[2], reverse = True)\n if match_result == []:\n match_result = []\n else:\n if match_result[0][2] == 1.0:\n match_result = match_result[:1]\n match_id = [i[1] for i in match_result]\n for indx,i in enumerate(match_id):\n if i[-7:]=='synonym':\n match_id[indx] = match_id[indx][:-8]\n match_table = chpo[chpo.iloc[:,2].isin(match_id)].iloc[:7,:].reset_index(drop=True)\n match_result = match_table.to_json(orient='records')\n return match_result\n\ndef map_chpo(input_pheno):\n try:\n if not input_pheno:\n match_result = ''\n else:\n chpo = pd.read_excel(CHPO)\n chpo.columns = ['类别','HPO编号','表型英文名','表型中文名','英文释义','释义']\n chpo = chpo.iloc[:,[3,2,1,0,5]]\n word_cant_be_detected = ['癫痫']\n manual_dir = {u'愣神': u'癫痫'}\n if input_pheno in manual_dir.keys():\n input_pheno = manual_dir[input_pheno]\n if input_pheno in word_cant_be_detected or detect(unicode(input_pheno)) in [\"zh-cn\",\"ko\"]:\n direct_match = chpo[chpo['表型中文名']==input_pheno]\n input_cut = list(jieba.cut_for_search(input_pheno))\n substring_match = [i for i,j in enumerate(list(chpo['表型中文名'])) if set(input_cut).issubset(set(list(jieba.cut_for_search(j))))]\n if len(direct_match) > 0:\n match_result = direct_match.to_json(orient='records')\n elif len(substring_match) > 0:\n match_table = chpo.iloc[substring_match,:].reset_index(drop=True)\n match_result = match_table.to_json(orient='records')\n else:\n phenos, corner_cases, original_phenos, phenotype_translate = read_input_pheno_file(input_pheno)\n match_result = smart_match(phenotype_translate, chpo)\n else:\n match_result = smart_match(input_pheno, chpo)\n except:\n match_result = []\n\n return match_result","sub_path":"deepb/map_chpo.py","file_name":"map_chpo.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"623110753","text":"#!/usr/bin/env python\nu\"\"\"\nleast_squares_mascon_timeseries.py\nWritten by Tyler Sutterley (05/2023)\n\nCalculates a time-series of regional mass anomalies through a\n least-squares mascon procedure procedure from an index of\n spherical harmonic coefficient files\n\nINPUTS:\n Input index file for model harmonics\n\nCOMMAND LINE OPTIONS:\n --help: list the command line options\n -O X, --output-directory X: output directory for mascon files\n -P X, --file-prefix X: prefix string for mascon files\n -S X, --start X: starting GRACE/GRACE-FO month\n -E X, --end X: ending GRACE/GRACE-FO month\n -N X, --missing X: Missing GRACE/GRACE-FO months\n --lmin X: minimum spherical harmonic degree\n -l X, --lmax X: maximum spherical harmonic degree\n -m X, --mmax X: maximum spherical harmonic order\n -R X, --radius X: Gaussian smoothing radius (km)\n -d, --destripe: use decorrelation filter (destriping filter)\n -n X, --love X: Treatment of the Love Love numbers\n 0: Han and Wahr (1995) values from PREM\n 1: Gegout (2005) values from PREM\n 2: Wang et al. (2012) values from PREM\n 3: Wang et al. (2012) values from PREM with hard sediment\n 4: Wang et al. (2012) values from PREM with soft sediment\n --reference X: Reference frame for load love numbers\n CF: Center of Surface Figure (default)\n CM: Center of Mass of Earth System\n CE: Center of Mass of Solid Earth\n -F X, --format X: input data format\n ascii\n netCDF4\n HDF5\n --mask X: Land-sea mask for redistributing mascon mass and land water flux\n --mascon-file X: index file of mascons spherical harmonics\n --mascon-format X: input format for mascon files\n --redistribute-mascons: redistribute mascon mass over the ocean\n --fit-method X: method for fitting sensitivity kernel to harmonics\n 1: mass coefficients\n 2: geoid coefficients\n -s X, --solver X: Least squares solver for sensitivity kernels\n inv: matrix inversion\n lstsq: least squares solution\n gelsy: complete orthogonal factorization\n gelss: singular value decomposition (SVD)\n gelsd: singular value decomposition (SVD) with divide and conquer method\n --redistribute-mass: redistribute input mass fields over the ocean\n --harmonic-errors: input spherical harmonic fields are data errors\n --remove-file X: Monthly files to be removed from the harmonic data\n --remove-format X: Input data format for files to be removed\n --redistribute-removed: redistribute removed mass fields over the ocean\n --log: Output log of files created for each job\n -V, --verbose: Verbose output of processing run\n -M X, --mode X: Permissions mode of the files created\n\nPYTHON DEPENDENCIES:\n numpy: Scientific Computing Tools For Python\n https://numpy.org\n https://numpy.org/doc/stable/user/numpy-for-matlab-users.html\n dateutil: powerful extensions to datetime\n https://dateutil.readthedocs.io/en/stable/\n netCDF4: Python interface to the netCDF C library\n https://unidata.github.io/netcdf4-python/netCDF4/index.html\n h5py: Pythonic interface to the HDF5 binary data format.\n http://www.h5py.org/\n future: Compatibility layer between Python 2 and Python 3\n http://python-future.org/\n\nPROGRAM DEPENDENCIES:\n read_love_numbers.py: reads Load Love Numbers from Han and Wahr (1995)\n ocean_stokes.py: reads a land-sea mask and converts to spherical harmonics\n spatial.py: spatial data class for reading, writing and processing data\n gen_stokes.py: converts a spatial field into spherical harmonic coefficients\n gauss_weights.py: Computes the Gaussian weights as a function of degree\n harmonics.py: spherical harmonic data class for processing GRACE/GRACE-FO\n destripe_harmonics.py: calculates the decorrelation (destriping) filter\n and filters the GRACE/GRACE-FO coefficients for striping errors\n units.py: class for converting GRACE/GRACE-FO Level-2 data to specific units\n utilities.py: download and management utilities for files\n\nREFERENCES:\n I Velicogna, T C Sutterley and M R van den Broeke. \"Regional acceleration\n in ice mass loss from Greenland and Antarctica using GRACE\n time-variable gravity data\". Geophysical Research Letters,\n 41(22):8130-8137, 2014. https://doi.org/10.1002/2014GL061052\n\n T Jacob, J Wahr, W Pfeffer, and S C Swenson \"Recent contributions of\n glaciers and ice caps to sea level rise\". Nature, 482, 514-518 (2012).\n https://doi.org/10.1038/nature10847\n\n V M Tiwari, J Wahr, S and Swenson, \"Dwindling groundwater resources in\n northern India, from satellite gravity observations\",\n Geophysical Research Letters, 36(18), L18401, (2009).\n https://doi.org/10.1029/2009GL039401\n\nUPDATE HISTORY:\n Updated 05/2023: use pathlib to define and operate on paths\n Updated 02/2023: use love numbers class with additional attributes\n Updated 12/2022: single implicit import of spherical harmonic tools\n Updated 11/2022: use f-strings for formatting verbose or ascii output\n Updated 05/2022: use argparse descriptions within sphinx documentation\n Updated 04/2022: use wrapper function for reading load Love numbers\n include utf-8 encoding in reads to be windows compliant\n Updated 12/2021: can use variable loglevels for verbose output\n Updated 10/2021: using python logging for handling verbose output\n Updated 08/2021: add option for setting input format of the mascon files\n Updated 06/2021: switch from parameter files to argparse arguments\n Updated 05/2021: define int/float precision to prevent deprecation warning\n Updated 04/2021: add parser object for removing commented or empty lines\n Updated 02/2021: changed remove index to files with specified formats\n Updated 01/2021: harmonics object output from gen_stokes.py/ocean_stokes.py\n Updated 12/2020: added more love number options\n Updated 10/2020: use argparse to set command line parameters\n Updated 08/2020: use utilities to define path to load love numbers file\n Updated 04/2020: using the harmonics class for spherical harmonic operations\n updated load love numbers read function\n Updated 03/2020: switched to destripe_harmonics for filtering harmonics\n Updated 10/2019: changing Y/N flags to True/False\n Updated 11/2018: can remove sets of spherical harmonics\n Updated 10/2018: verify integers for python3 compatibility\n Updated 06/2018: using python3 compatible octal and input\n Updated 03/2018: include order_str denoting if MMAX != LMAX\n added extrapolation of load love numbers if LMAX > 696\n Updated 01/2018: recursively make output directories\n Updated 09/2017: use a different land-sea mask for calculating ocean_Ylms\n use rcond=-1 in numpy least-squares algorithm\n Updated 02/2017: input spherical harmonic mapping indices as integers\n clean up ocean redistribution read function\n Updated 01/2017: ocean_stokes.py for reading/converting ocean function\n Updated 05-07/2016: using __future__ print function\n Updated 02/2016: direct calculation of number of harmonics n_harm\n use getopt parameters to set number of PROCESSES to run in parallel,\n whether or not to output a log file, added new help module\n Updated 11/2015: create unique log filenames\n Updated 08/2015: changed sys.exit to a raise exception instance\n Updated 06/2015: will output logs with parameters and output_files\n Updated 05/2015: added parameter MMAX for LMAX != MMAX\n Updated 04/2015: forked to add start and end months (only run months of interest)\n Updated 03/2015: updated code with updates from calc_mascon program\n error handling with traceback, ocean redistribution, multiple data types\n Updated 11/2014: general program for non-grace fields\n Updated 10/2014: distributed computing of tasks with the multiprocessing module\n Updated 05/2014: added import functions\n Updated 02/2014: updated comments and added os.path.joins for connecting\n directories and files (generalizing code)\n Updated 09/2013: saving GRACE DELTA file to improve computational times\n Updated 08/2013: general updates to inputting data\n wrote grace_find_months, grace_input_months, gia_input\n to input spherical harmonics similar to python programs\n Updated 03/2012: edited to use new gen_stokes time-series option\n Updated 02/2012: Added sensitivity kernels\n Written 02/2012\n\"\"\"\nfrom __future__ import print_function, division\n\nimport sys\nimport os\nimport re\nimport time\nimport logging\nimport pathlib\nimport argparse\nimport traceback\nimport numpy as np\nimport scipy.linalg\nimport gravity_toolkit as gravtk\n\n# PURPOSE: keep track of threads\ndef info(args):\n logging.info(pathlib.Path(sys.argv[0]).name)\n logging.info(args)\n logging.info(f'module name: {__name__}')\n if hasattr(os, 'getppid'):\n logging.info(f'parent process: {os.getppid():d}')\n logging.info(f'process id: {os.getpid():d}')\n\n# PURPOSE: calculate a regional time-series through a least\n# squares mascon process\ndef least_squares_mascons(input_file, LMAX, RAD,\n START=None,\n END=None,\n MISSING=None,\n LMIN=None,\n MMAX=None,\n DESTRIPE=False,\n LOVE_NUMBERS=0,\n REFERENCE=None,\n DATAFORM=None,\n MASCON_FILE=None,\n MASCON_FORMAT=None,\n REDISTRIBUTE_MASCONS=False,\n FIT_METHOD=0,\n SOLVER=None,\n REDISTRIBUTE=False,\n DATA_ERROR=False,\n REMOVE_FILES=None,\n REMOVE_FORMAT=None,\n REDISTRIBUTE_REMOVED=False,\n LANDMASK=None,\n OUTPUT_DIRECTORY=None,\n FILE_PREFIX=None,\n MODE=0o775):\n\n # recursively create output directory if not currently existing\n OUTPUT_DIRECTORY = pathlib.Path(OUTPUT_DIRECTORY).expanduser().absolute()\n OUTPUT_DIRECTORY.mkdir(mode=MODE, parents=True, exist_ok=True)\n\n # list object of output files for file logs (full path)\n output_files = []\n # file parser for reading index files\n # removes commented lines (can comment out files in the index)\n # removes empty lines (if there are extra empty lines)\n parser = re.compile(r'^(?!\\#|\\%|$)', re.VERBOSE)\n\n # read load love numbers\n LOVE = gravtk.load_love_numbers(LMAX, LOVE_NUMBERS=LOVE_NUMBERS,\n REFERENCE=REFERENCE, FORMAT='class')\n\n # Earth Parameters\n factors = gravtk.units(lmax=LMAX).harmonic(*LOVE)\n # Average Density of the Earth [g/cm^3]\n rho_e = factors.rho_e\n # Average Radius of the Earth [cm]\n rad_e = factors.rad_e\n\n # Calculating the Gaussian smoothing for radius RAD\n if (RAD != 0):\n wt = 2.0*np.pi*gravtk.gauss_weights(RAD,LMAX)\n gw_str = f'_r{RAD:0.0f}km'\n else:\n # else = 1\n wt = np.ones((LMAX+1))\n gw_str = ''\n\n # output string for both LMAX==MMAX and LMAX != MMAX cases\n MMAX = np.copy(LMAX) if not MMAX else MMAX\n order_str = 'M{MMAX:d}' if (MMAX != LMAX) else ''\n # output string for destriped harmonics\n ds_str = '_FL' if DESTRIPE else ''\n\n # Read Ocean function and convert to Ylms for redistribution\n if (REDISTRIBUTE_MASCONS | REDISTRIBUTE):\n # read Land-Sea Mask and convert to spherical harmonics\n ocean_Ylms = gravtk.ocean_stokes(LANDMASK, LMAX,\n MMAX=MMAX, LOVE=LOVE)\n ocean_str = '_OCN'\n else:\n # not distributing uniformly over ocean\n ocean_str = ''\n\n # Range of months from start_mon to end_mon\n mon_range = np.arange(START,END+1)# end_mon+1 to include end_mon\n # Removing the missing months and months not to consider\n for i in MISSING:\n mon_range = mon_range[np.nonzero(mon_range != i)]\n # number of months to consider in analysis\n n_files = len(mon_range)\n\n # read spherical harmonics file in data format\n if DATAFORM in ('ascii','netCDF4','HDF5'):\n # ascii (.txt)\n # netCDF4 (.nc)\n # HDF5 (.H5)\n data_Ylms = gravtk.harmonics().from_file(input_file,\n format=DATAFORM, date=True)\n elif DATAFORM in ('index-ascii','index-netCDF4','index-HDF5'):\n # read from index file\n _,DATAFORM = DATAFORM.split('-')\n data_Ylms = gravtk.harmonics().from_index(input_file,\n format=DATAFORM, date=True)\n # reduce to GRACE/GRACE-FO months and truncate to degree and order\n data_Ylms = data_Ylms.subset(mon_range).truncate(lmax=LMAX, mmax=MMAX)\n # distribute Ylms uniformly over the ocean\n if REDISTRIBUTE:\n # calculate ratio between total removed mass and\n # a uniformly distributed cm of water over the ocean\n ratio = data_Ylms.clm[0,0,:]/ocean_Ylms.clm[0,0]\n # for each spherical harmonic\n for m in range(0,MMAX+1):# MMAX+1 to include MMAX\n for l in range(m,LMAX+1):# LMAX+1 to include LMAX\n # remove the ratio*ocean Ylms from Ylms\n # note: x -= y is equivalent to x = x - y\n data_Ylms.clm[l,m,:] -= ratio*ocean_Ylms.clm[l,m]\n data_Ylms.slm[l,m,:] -= ratio*ocean_Ylms.slm[l,m]\n # filter data coefficients\n if DESTRIPE:\n data_Ylms = data_Ylms.destripe()\n\n # input spherical harmonic datafiles to be removed from the harmonics data\n # Remove sets of Ylms from the harmonics data before returning\n remove_Ylms = data_Ylms.zeros_like()\n remove_Ylms.time[:] = np.copy(data_Ylms.time)\n remove_Ylms.month[:] = np.copy(data_Ylms.month)\n if REMOVE_FILES:\n # extend list if a single format was entered for all files\n if len(REMOVE_FORMAT) < len(REMOVE_FILES):\n REMOVE_FORMAT = REMOVE_FORMAT*len(REMOVE_FILES)\n # for each file to be removed\n for REMOVE_FILE,REMOVEFORM in zip(REMOVE_FILES,REMOVE_FORMAT):\n if REMOVEFORM in ('ascii','netCDF4','HDF5'):\n # ascii (.txt)\n # netCDF4 (.nc)\n # HDF5 (.H5)\n Ylms = gravtk.harmonics().from_file(REMOVE_FILE,\n format=REMOVEFORM)\n elif REMOVEFORM in ('index-ascii','index-netCDF4','index-HDF5'):\n # read from index file\n _,removeform = REMOVEFORM.split('-')\n # index containing files in data format\n Ylms = gravtk.harmonics().from_index(REMOVE_FILE,\n format=removeform)\n # reduce to GRACE/GRACE-FO months and truncate to degree and order\n Ylms = Ylms.subset(data_Ylms.month).truncate(lmax=LMAX,mmax=MMAX)\n # distribute removed Ylms uniformly over the ocean\n if REDISTRIBUTE_REMOVED:\n # calculate ratio between total removed mass and\n # a uniformly distributed cm of water over the ocean\n ratio = Ylms.clm[0,0,:]/ocean_Ylms.clm[0,0]\n # for each spherical harmonic\n for m in range(0,MMAX+1):# MMAX+1 to include MMAX\n for l in range(m,LMAX+1):# LMAX+1 to include LMAX\n # remove the ratio*ocean Ylms from Ylms\n # note: x -= y is equivalent to x = x - y\n Ylms.clm[l,m,:] -= ratio*ocean_Ylms.clm[l,m]\n Ylms.slm[l,m,:] -= ratio*ocean_Ylms.slm[l,m]\n # filter removed coefficients\n if DESTRIPE:\n Ylms = Ylms.destripe()\n # add data for month t and INDEX_FILE to the total\n # remove_clm and remove_slm matrices\n # redistributing the mass over the ocean if specified\n remove_Ylms.add(Ylms)\n\n # input mascon spherical harmonic datafiles\n MASCON_FILE = pathlib.Path(MASCON_FILE).expanduser().absolute()\n with MASCON_FILE.open(mode='r', encoding='utf8') as f:\n mascon_files = [l for l in f.read().splitlines() if parser.match(l)]\n # number of mascons\n n_mas = len(mascon_files)\n # spatial area of the mascon\n area_tot = np.zeros((n_mas))\n # name of each mascon\n mascon_name = []\n # for each valid file in the index (iterate over mascons)\n mascon_list = []\n for k in range(n_mas):\n # read mascon spherical harmonics\n Ylms = gravtk.harmonics().from_file(mascon_files[k],\n format=MASCON_FORMAT, date=False)\n # Calculating the total mass of each mascon (1 cmH2O uniform)\n area_tot[k] = 4.0*np.pi*(rad_e**3)*rho_e*Ylms.clm[0,0]/3.0\n # distribute MASCON mass uniformly over the ocean\n if REDISTRIBUTE_MASCONS:\n # calculate ratio between total mascon mass and\n # a uniformly distributed cm of water over the ocean\n ratio = Ylms.clm[0,0]/ocean_Ylms.clm[0,0]\n # for each spherical harmonic\n for m in range(0,MMAX+1):# MMAX+1 to include MMAX\n for l in range(m,LMAX+1):# LMAX+1 to include LMAX\n # remove ratio*ocean Ylms from mascon Ylms\n # note: x -= y is equivalent to x = x - y\n Ylms.clm[l,m] -= ratio*ocean_Ylms.clm[l,m]\n Ylms.slm[l,m] -= ratio*ocean_Ylms.slm[l,m]\n # truncate mascon spherical harmonics to d/o LMAX/MMAX and add to list\n mascon_list.append(Ylms.truncate(lmax=LMAX, mmax=MMAX))\n # stem is the mascon file without directory or suffix\n # if lower case: will capitalize\n # if mascon name contains degree and order info: scrub from string\n stem = re.sub(r'_L(\\d+)(M\\d+)?', r'', Ylms.filename.stem.upper())\n mascon_name.append(stem)\n # create single harmonics object from list\n mascon_Ylms = gravtk.harmonics().from_list(mascon_list, date=False)\n # clear mascon list variable\n del mascon_list\n\n # Calculating the number of cos and sin harmonics between LMIN and LMAX\n # taking into account MMAX (if MMAX == LMAX then LMAX-MMAX=0)\n n_harm=np.int64(LMAX**2 - LMIN**2 + 2*LMAX + 1 - (LMAX-MMAX)**2 - (LMAX-MMAX))\n\n # Initialing harmonics for least squares fitting\n # mascon kernel\n M_lm = np.zeros((n_harm,n_mas))\n # mascon kernel converted to output unit\n MA_lm = np.zeros((n_harm,n_mas))\n # corrected clm and slm\n Y_lm = np.zeros((n_harm,n_files))\n # sensitivity kernel\n A_lm = np.zeros((n_harm,n_mas))\n # Initializing output Mascon time-series\n mascon = np.zeros((n_mas,n_files))\n # Initializing conversion factors\n # factor for converting to coefficients of mass\n fact = np.zeros((n_harm))\n # smoothing factor\n wt_lm = np.zeros((n_harm))\n\n # ii is a counter variable for building the mascon column array\n ii = 0\n # Creating column array of clm/slm coefficients\n # Order is [C00...C6060,S11...S6060]\n # Switching between Cosine and Sine Stokes\n for cs,csharm in enumerate(['clm','slm']):\n # copy cosine and sin harmonics\n mascon_harm = getattr(mascon_Ylms, csharm)\n data_harm = getattr(data_Ylms, csharm)\n remove_harm = getattr(remove_Ylms, csharm)\n # for each spherical harmonic degree\n # +1 to include LMAX\n for l in range(LMIN,LMAX+1):\n # for each spherical harmonic order\n # Sine Stokes for (m=0) = 0\n mm = np.min([MMAX,l])\n # +1 to include l or MMAX (whichever is smaller)\n for m in range(cs,mm+1):\n # Mascon Spherical Harmonics\n M_lm[ii,:] = np.copy(mascon_harm[l,m,:])\n # Data Spherical Harmonics\n # (remove sets of harmonics if specified)\n Y_lm[ii,:] = data_harm[l,m,:] - remove_harm[l,m,:]\n # degree dependent factor to convert to mass\n fact[ii] = (2.0*l+1.0)/(1.0 + LOVE.kl[l])\n # degree dependent smoothing\n wt_lm[ii] = np.copy(wt[l])\n # add 1 to counter\n ii += 1\n # free up memory from data harmonics\n data_Ylms.clm = None\n data_Ylms.slm = None\n remove_Ylms = None\n\n # Converting mascon coefficients to fit method\n if (FIT_METHOD == 1):\n # Fitting Sensitivity Kernel as mass coefficients\n # converting M_lm to mass coefficients of the kernel\n for i in range(n_harm):\n MA_lm[i,:] = M_lm[i,:]*wt_lm[i]*fact[i]\n fit_factor = wt_lm*fact\n else:\n # Fitting Sensitivity Kernel as geoid coefficients\n for i in range(n_harm):\n MA_lm[:,:] = M_lm[i,:]*wt_lm[i]\n fit_factor = wt_lm*np.ones((n_harm))\n\n # Fitting the sensitivity kernel from the input kernel\n for i in range(n_harm):\n # setting kern_i equal to 1 for d/o\n kern_i = np.zeros((n_harm))\n # converting to mass coefficients if specified\n kern_i[i] = 1.0*fit_factor[i]\n # spherical harmonics solution for the\n # mascon sensitivity kernels\n if (SOLVER == 'inv'):\n kern_lm = np.dot(np.linalg.inv(MA_lm), kern_i)\n elif (SOLVER == 'lstsq'):\n kern_lm = np.linalg.lstsq(MA_lm, kern_i, rcond=-1)[0]\n elif SOLVER in ('gelsd', 'gelsy', 'gelss'):\n kern_lm, res, rnk, s = scipy.linalg.lstsq(MA_lm, kern_i,\n lapack_driver=SOLVER)\n for k in range(n_mas):\n A_lm[i,k] = kern_lm[k]*area_tot[k]\n\n # for each mascon\n for k in range(n_mas):\n # output filename format:\n # mascon name, LMAX, order flag, Gaussian smoothing radii, filter flag\n fargs = (FILE_PREFIX, mascon_name[k], LMAX, order_str,\n gw_str, ds_str, ocean_str)\n file_format = '{0}{1}_L{2:d}{3}{4}{5}{6}.txt'\n output_file = OUTPUT_DIRECTORY.joinpath(file_format.format(*fargs))\n\n # Output mascon datafiles\n # Will output each mascon mass time series\n # month, date, mascon mass, mascon area\n # open output mascon time-series file\n fid = output_file.open(mode='w', encoding='utf8')\n # for each date\n for f,mon in enumerate(data_Ylms.month):\n # Summing over all spherical harmonics for mascon k, and time t\n # multiplies by the degree dependent factor to convert\n # the harmonics into mass coefficients\n # Converting mascon mass time-series from g to gigatonnes\n if DATA_ERROR:\n # if input data are errors (i.e. estimated dealiasing errors)\n mascon[k,f] = np.sqrt(np.sum((A_lm[:,k]*Y_lm[:,f])**2))/1e15\n else:\n mascon[k,f] = np.sum(A_lm[:,k]*Y_lm[:,f])/1e15\n # output to file\n args = (mon, data_Ylms.time[f], mascon[k,f], area_tot[k]/1e10)\n fid.write('{0:03d} {1:12.4f} {2:16.10f} {3:16.5f}\\n'.format(*args))\n # close the output file\n fid.close()\n # change the permissions mode of the output file\n output_file.chmod(mode=MODE)\n # add output files to list object\n output_files.append(output_file)\n\n # return the list of output files\n return output_files\n\n# PURPOSE: print a file log for the mascon analysis\ndef output_log_file(input_arguments, output_files):\n # format: calc_mascon_run_2002-04-01_PID-70335.log\n args = (time.strftime('%Y-%m-%d',time.localtime()), os.getpid())\n LOGFILE = 'calc_mascon_run_{0}_PID-{1:d}.log'.format(*args)\n # create a unique log and open the log file\n DIRECTORY = pathlib.Path(input_arguments.output_directory)\n fid = gravtk.utilities.create_unique_file(DIRECTORY.joinpath(LOGFILE))\n logging.basicConfig(stream=fid, level=logging.INFO)\n # print argument values sorted alphabetically\n logging.info('ARGUMENTS:')\n for arg, value in sorted(vars(input_arguments).items()):\n logging.info(f'{arg}: {value}')\n # print output files\n logging.info('\\n\\nOUTPUT FILES:')\n for f in output_files:\n logging.info(f)\n # close the log file\n fid.close()\n\n# PURPOSE: print a error file log for the mascon analysis\ndef output_error_log_file(input_arguments):\n # format: calc_mascon_failed_run_2002-04-01_PID-70335.log\n args = (time.strftime('%Y-%m-%d',time.localtime()), os.getpid())\n LOGFILE = 'calc_mascon_failed_run_{0}_PID-{1:d}.log'.format(*args)\n # create a unique log and open the log file\n DIRECTORY = pathlib.Path(input_arguments.output_directory)\n fid = gravtk.utilities.create_unique_file(DIRECTORY.joinpath(LOGFILE))\n logging.basicConfig(stream=fid, level=logging.INFO)\n # print argument values sorted alphabetically\n logging.info('ARGUMENTS:')\n for arg, value in sorted(vars(input_arguments).items()):\n logging.info(f'{arg}: {value}')\n # print traceback error\n logging.info('\\n\\nTRACEBACK ERROR:')\n traceback.print_exc(file=fid)\n # close the log file\n fid.close()\n\n# PURPOSE: create argument parser\ndef arguments():\n parser = argparse.ArgumentParser(\n description=\"\"\"Calculates a time-series of regional mass anomalies\n through a least-squares mascon procedure procedure from an index\n of spherical harmonic coefficient files\n \"\"\",\n fromfile_prefix_chars=\"@\"\n )\n parser.convert_arg_line_to_args = gravtk.utilities.convert_arg_line_to_args\n # command line parameters\n parser.add_argument('infile',\n type=pathlib.Path,\n help='Input index file with spherical harmonic data files')\n # working data directory\n parser.add_argument('--output-directory','-O',\n type=pathlib.Path, default=pathlib.Path.cwd(),\n help='Output directory for mascon files')\n parser.add_argument('--file-prefix','-P',\n type=str,\n help='Prefix string for mascon files')\n # minimum spherical harmonic degree\n parser.add_argument('--lmin',\n type=int, default=1,\n help='Minimum spherical harmonic degree')\n # maximum spherical harmonic degree and order\n parser.add_argument('--lmax','-l',\n type=int, default=60,\n help='Maximum spherical harmonic degree')\n parser.add_argument('--mmax','-m',\n type=int, default=None,\n help='Maximum spherical harmonic order')\n # start and end GRACE/GRACE-FO months\n parser.add_argument('--start','-S',\n type=int, default=4,\n help='Starting GRACE/GRACE-FO month')\n parser.add_argument('--end','-E',\n type=int, default=232,\n help='Ending GRACE/GRACE-FO month')\n MISSING = [6,7,18,109,114,125,130,135,140,141,146,151,156,162,166,167,\n 172,177,178,182,187,188,189,190,191,192,193,194,195,196,197,200,201]\n parser.add_argument('--missing','-N',\n metavar='MISSING', type=int, nargs='+', default=MISSING,\n help='Missing GRACE/GRACE-FO months')\n # different treatments of the load Love numbers\n # 0: Han and Wahr (1995) values from PREM\n # 1: Gegout (2005) values from PREM\n # 2: Wang et al. (2012) values from PREM\n # 3: Wang et al. (2012) values from PREM with hard sediment\n # 4: Wang et al. (2012) values from PREM with soft sediment\n parser.add_argument('--love','-n',\n type=int, default=0, choices=[0,1,2,3,4],\n help='Treatment of the Load Love numbers')\n # option for setting reference frame for gravitational load love number\n # reference frame options (CF, CM, CE)\n parser.add_argument('--reference',\n type=str.upper, default='CF', choices=['CF','CM','CE'],\n help='Reference frame for load Love numbers')\n # Gaussian smoothing radius (km)\n parser.add_argument('--radius','-R',\n type=float, default=0,\n help='Gaussian smoothing radius (km)')\n # Use a decorrelation (destriping) filter\n parser.add_argument('--destripe','-d',\n default=False, action='store_true',\n help='Use decorrelation (destriping) filter')\n # input data format (ascii, netCDF4, HDF5)\n choices = []\n choices.extend(['ascii','netCDF4','HDF5'])\n choices.extend(['index-ascii','index-netCDF4','index-HDF5'])\n parser.add_argument('--format','-F',\n metavar='FORMAT', type=str,\n default='netCDF4', choices=choices,\n help='Input data format')\n # mascon index file and parameters\n parser.add_argument('--mascon-file',\n type=pathlib.Path,\n help='Index file of mascons spherical harmonics')\n parser.add_argument('--mascon-format',\n type=str, default='netCDF4', choices=['ascii','netCDF4','HDF5'],\n help='Input data format for mascon files')\n parser.add_argument('--redistribute-mascons',\n default=False, action='store_true',\n help='Redistribute mascon mass over the ocean')\n # 1: mass coefficients\n # 2: geoid coefficients\n parser.add_argument('--fit-method',\n type=int, default=1, choices=(1,2),\n help='Method for fitting sensitivity kernel to harmonics')\n # least squares solver\n choices = ('inv','lstsq','gelsd', 'gelsy', 'gelss')\n parser.add_argument('--solver','-s',\n type=str, default='lstsq', choices=choices,\n help='Least squares solver for sensitivity kernel solutions')\n # redistribute total mass over the ocean\n parser.add_argument('--redistribute-mass',\n default=False, action='store_true',\n help='Redistribute total mass over the ocean')\n # calculating with data errors\n parser.add_argument('--harmonic-errors',\n default=False, action='store_true',\n help='Input spherical harmonic fields are data errors')\n # monthly files to be removed from the harmonic data\n parser.add_argument('--remove-file',\n type=pathlib.Path, nargs='+',\n help='Monthly files to be removed from the harmonic data')\n choices = []\n choices.extend(['ascii','netCDF4','HDF5'])\n choices.extend(['index-ascii','index-netCDF4','index-HDF5'])\n parser.add_argument('--remove-format',\n type=str, nargs='+', choices=choices,\n help='Input data format for files to be removed')\n parser.add_argument('--redistribute-removed',\n default=False, action='store_true',\n help='Redistribute removed mass fields over the ocean')\n # land-sea mask for redistributing mascon mass and land water flux\n lsmask = gravtk.utilities.get_data_path(['data','landsea_hd.nc'])\n parser.add_argument('--mask',\n type=pathlib.Path, default=lsmask,\n help='Land-sea mask for redistributing mascon mass and land water flux')\n # Output log file for each job in forms\n # calc_mascon_run_2002-04-01_PID-00000.log\n # calc_mascon_failed_run_2002-04-01_PID-00000.log\n parser.add_argument('--log',\n default=False, action='store_true',\n help='Output log file for each job')\n # print information about processing run\n parser.add_argument('--verbose','-V',\n action='count', default=0,\n help='Verbose output of processing run')\n # permissions mode of the local directories and files (number in octal)\n parser.add_argument('--mode','-M',\n type=lambda x: int(x,base=8), default=0o775,\n help='permissions mode of output files')\n # return the parser\n return parser\n\n# This is the main part of the program that calls the individual functions\ndef main():\n # Read the system arguments listed after the program\n parser = arguments()\n args,_ = parser.parse_known_args()\n\n # create logger\n loglevels = [logging.CRITICAL, logging.INFO, logging.DEBUG]\n logging.basicConfig(level=loglevels[args.verbose])\n\n # try to run the analysis with listed parameters\n try:\n info(args)\n # run least_squares_mascons algorithm with parameters\n output_files = least_squares_mascons(\n args.infile,\n args.lmax,\n args.radius,\n START=args.start,\n END=args.end,\n MISSING=args.missing,\n LMIN=args.lmin,\n MMAX=args.mmax,\n DESTRIPE=args.destripe,\n LOVE_NUMBERS=args.love,\n REFERENCE=args.reference,\n DATAFORM=args.format,\n MASCON_FILE=args.mascon_file,\n MASCON_FORMAT=args.mascon_format,\n REDISTRIBUTE_MASCONS=args.redistribute_mascons,\n FIT_METHOD=args.fit_method,\n SOLVER=args.solver,\n REDISTRIBUTE=args.redistribute_mass,\n DATA_ERROR=args.harmonic_errors,\n REMOVE_FILES=args.remove_file,\n REMOVE_FORMAT=args.remove_format,\n REDISTRIBUTE_REMOVED=args.redistribute_removed,\n LANDMASK=args.mask,\n OUTPUT_DIRECTORY=args.output_directory,\n FILE_PREFIX=args.file_prefix,\n MODE=args.mode)\n except:\n # if there has been an error exception\n # print the type, value, and stack trace of the\n # current exception being handled\n logging.critical(f'process id {os.getpid():d} failed')\n logging.error(traceback.format_exc())\n if args.log:# write failed job completion log file\n output_error_log_file(args)\n else:\n if args.log:# write successful job completion log file\n output_log_file(args,output_files)\n\n# run main program\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/least_squares_mascon_timeseries.py","file_name":"least_squares_mascon_timeseries.py","file_ext":"py","file_size_in_byte":32968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"296061678","text":"'''\nGiven an image represented by NxN matrix, where each pixel in\nthe image is 4 bytes write a method to rotate\nthe image by 90 degrees. Can you do this in place?\n'''\nfrom copy import deepcopy\ndef rotate_matrix_cw90(matrix):\n if len(matrix) == 0 or len(matrix) != len(matrix[0]):\n return\n matrix_size = len(matrix)\n for layer in range(0, int(matrix_size/2)):\n first = layer\n last = matrix_size - 1 - layer\n for i in range(first, last):\n offset = i - first\n #save top\n top = matrix[first][i]\n #left ->top\n matrix[first][i] = matrix[last - offset][first]\n # bottom -> left\n matrix[last - offset][first] = matrix[last][last - offset]\n #right -> bottom\n matrix[last][last - offset] = matrix[i][last]\n #top -> right\n matrix[i][last] = top\n#not in-place\ndef rotate_matrix_with_deepcopy(matrix, matrix_size):\n res = deepcopy(matrix)\n for i in range(0, matrix_size):\n for j in range(matrix_size-1, -1, -1):\n res[i][matrix_size-j-1] = matrix[j][i]\n return res\n\ndef main():\n \"\"\"test\"\"\"\n matrix = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]\n print(str(matrix))\n print(rotate_matrix_with_deepcopy(matrix, 4))\n rotate_matrix_cw90(matrix)\n print(matrix)\n\nif __name__ == '__main__':\n main()\n","sub_path":"old/Cracking_coding_interview_Python/Ch1/q1_7.py","file_name":"q1_7.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"412227314","text":"import url_utils\nimport collections \nimport operator\nimport json\nimport itertools\nfrom flask import jsonify\n\n'''\nAPI to sort sites by number of visits\n'''\ndef sort_by_frequency(results):\n\tsites_count = {}\n\t#results = stats()\n\tfor url, count in results:\n\t\turl = url_utils.parse(url)\n\t\tif url in sites_count:\n\t\t\tsites_count[url] += 1\n\t\telse:\n\t\t\tsites_count[url] = 1\n\n\tsites_count_sorted = collections.OrderedDict(sorted(sites_count.items(), key=lambda kv: kv[1], reverse=True))\n\tnumberOfElementsToDisplay = 3\n\ttop3_sorted_dict = {k: sites_count_sorted[k] for k in list(sites_count_sorted.keys())[:numberOfElementsToDisplay]}\n\t# with open(\"data_file.json\", \"w\") as write_file:\n\t# \tjson.dump(top3_sorted_dict, write_file)\n\n\treturn jsonify(top3_sorted_dict)\n\n\n'''\nAPI to sort sites by time spent on each site\n'''\ndef sort_by_recently_spent_time(results):\n\tsites_rank = {}\n\n\tfor url, rank in results:\n\t\turl = url_utils.parse(url)\n\t\t#sites_rank[url] = rank+1\n\t\tif rank == 0:\n\t\t\tsites_rank[1] = url\n\t\telif rank == 1:\n\t\t\tsites_rank[2] = url\n\t\telif rank == 2:\n\t\t\tsites_rank[3] = url\n\n\t#sites_rank_sorted = collections.OrderedDict(sorted(sites_rank.items(), key=lambda kv: kv[1], reverse=False))\n\t#numberOfElementsToDisplay = 3\n\t#top3_ranked_dict = {k: sites_rank_sorted[k] for k in list(sites_rank_sorted.keys())[:numberOfElementsToDisplay]}\n\n\treturn jsonify(sites_rank)","sub_path":"api/sorting_apis.py","file_name":"sorting_apis.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"481515793","text":"#!/usr/bin/python\n'''\nModule: read_omi_no2_so2_and_list_sds.py\n==========================================================================================\nDisclaimer: The code is for demonstration purposes only. Users are responsible to check for accuracy and revise to fit their objective.\n\nAuthor: Justin Roberts-Pierel, 2015 \nOrganization: NASA ARSET\nPurpose: To print all SDS from an OMI hdf5 file\n\nSee the README associated with this module for more information.\n==========================================================================================\n'''\n\n#import necessary modules\nimport h5py\nimport os\n\nOMI_file_path = 'C:\\\\Projects\\\\OMI\\\\NO2\\\\download2\\\\'\nos.chdir(OMI_file_path)\n#This finds the user's current path so that all hdf4 files can be found\ntry:\n\tfileList=open('fileList.txt','r')\nexcept:\n\tprint('Did not find a text file contaiyning file names (perhaps name does not match)')\n\tsys.exit()\n\n#loops through all files listed in the text file\nfor FILE_NAME in fileList:\n\tFILE_NAME=FILE_NAME.strip()\n\tuser_input=input('\\nWould you like to process\\n' + FILE_NAME + '\\n\\n(Y/N)')\n\tif(user_input == 'N' or user_input == 'n'):\n\t\tprint('Skipping...')\n\t\tcontinue\n\telse:\n\t\tfile = h5py.File(FILE_NAME, 'r') # 'r' means that hdf5 file is open in read-only mode\t#saves the file as a variable named 'hdf'\n\t\t#checks if the file contains NO2 or SO2 data, and reacts accordingly\n\t\tif 'NO2' in FILE_NAME:\n\t\t\tprint('\\nThis is an OMI NO2 file. Here is a list of SDS in your file:\\n')\n\t\t\tdataFields=file['HDFEOS']['SWATHS']['ColumnAmountNO2']['Data Fields'] \n\t\t\tgeolocation=file['HDFEOS']['SWATHS']['ColumnAmountNO2']['Geolocation Fields']\n\t\telif 'SO2' in FILE_NAME:\n\t\t\tprint('\\nThis is an OMI SO2 file. Here is a list of SDS in your file:\\n')\n\t\t\tdataFields=file['HDFEOS']['SWATHS']['OMI Total Column Amount SO2']['Data Fields']\n\t\t\tgeolocation=file['HDFEOS']['SWATHS']['OMI Total Column Amount SO2']['Geolocation Fields']\n\t\telse:\n\t\t\tprint('The file named :',FILE_NAME, ' is not a valid OMI file. \\n')\n\t\t\tcontinue\t\n\t\t#Print the list of SDS found in the file \n\t\t[print('---Data Fields---')]\n\t\t[print(' ' + i + ', dim='+ str(dataFields[i].shape) +' \\n') for i in dataFields]\n\t\t[print('---Geolocation Fields---')]\n\t\t[print(' ' + i + ', dim='+ str(geolocation[i].shape) +' \\n') for i in geolocation]\n\t\t#close the hdf5 file \n\t\tfile.close()","sub_path":"read_omi_no2_so2_and_list_sds.py","file_name":"read_omi_no2_so2_and_list_sds.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"638747682","text":"class ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def detectCycle(self, head):\n def hasCycle():\n slow = head\n while fast[0] and fast[0].next:\n slow = slow.next\n fast[0] = fast[0].next.next\n if slow is fast[0]:\n return True\n return False\n\n fast = [head]\n if hasCycle():\n slow, fast = head, fast[0]\n while fast:\n if slow is fast:\n return slow\n slow, fast = slow.next, fast.next\n\n return None\n\n def print_answer(self, ans, head):\n ind = 0\n ptr = head\n while ptr:\n if ans is ptr:\n break\n ind += 1\n ptr = ptr.next\n print('tail connects to node index {}'.format(ind))\n\n def build_linked_list(self, vals, pos):\n n = len(vals)\n head = ListNode(vals[0])\n prev = head\n for i in range(1, n):\n curr = ListNode(vals[i])\n prev.next = curr\n prev = curr\n if i == n-1: # tail\n if pos != -1:\n loop = head\n for i in range(pos):\n loop = loop.next\n curr.next = loop\n return head\n\n def print_linked_list(self, head):\n ptr = head\n while ptr:\n print(ptr.val, ' ', end='')\n ptr = ptr.next\n print()\n\n def test(self):\n vals = [3, 2, 0, -4]\n pos = 1\n head = self.build_linked_list(vals, pos)\n # self.print_linked_list(head)\n ans = self.detectCycle(head)\n self.print_answer(ans, head)\n\n\nif __name__ == '__main__':\n s = Solution()\n s.test()\n","sub_path":"142_linked_list_cycle_II_2.py","file_name":"142_linked_list_cycle_II_2.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"619246897","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom tools.ui.pager import get_record_index\n\nfrom todolist.models import Step, Status, Item, ItemWork\nfrom secu.models import User\nimport json\n\nfrom attendence.decrator import *\n\nclass _Item:\n @valid_user\n def index(request):\n return render(request, 'todolist/item.html')\n\n def add(request):\n if request.method == 'POST':\n item = Item()\n item.title = request.POST['title']\n item.description = request.POST['description']\n item.minutes = request.POST['minutes']\n item.save()\n return JsonResponse(item.json)\n elif request.method == 'GET':\n return render(request, 'todolist/item_detail.html')\n\n def list(request):\n if request.method == 'GET':\n record = get_record_index(request)\n data = [ \n {\n \"id\": item.id, \n \"title\": item.title,\n \"step\": item.step.name if item.step else ' -- ',\n \"status\": item.status.name if item.status else ' -- ',\n \"person_in_charge\": item.person_in_charge.first_name+' '+ item.person_in_charge.last_name if item.person_in_charge else '--',\n \"entry_date\": item.entry_date \n }\n for item in Item.objects.all()[record['start']:record['end']] \n ]\n \n context = {\n \"totalrecords\": Item.objects.all().count(),\n \"data\": data\n }\n return JsonResponse(context, safe=False)\n \n def instance(request):\n if request.method == 'GET':\n instance = Item.objects.get(pk=request.GET['id'])\n return JsonResponse(instance.json, safe=False) \n\n def edit(request):\n if request.method == 'POST':\n item = Item.objects.get(pk=request.POST['id'])\n if request.POST['from_flag'] == 'item_work':\n step = Step.objects.get(pk=request.POST['step'])\n status = Status.objects.get(pk=request.POST['status'])\n user = User.objects.get(pk=request.POST['person_in_charge'])\n item.step = step\n item.status = status\n item.person_in_charge = user\n else:\n item.title = request.POST['title']\n item.description = request.POST['description']\n item.minutes = request.POST['minutes']\n item.save() \n return HttpResponse(50000)\n elif request.method == 'GET':\n return render(request, 'todolist/item_detail.html')\n\n def delete(request):\n if request.method == 'POST':\n item = Item.objects.get(pk=request.POST['id'])\n item.delete() \n return HttpResponse(50000) \n\n def get_options(args=0):\n result, step, status, user = {}, '', '', ''\n\n for obj in Step.objects.all():\n step = step + obj.as_option('id', 'name') \n\n for obj in Status.objects.all():\n status = status + obj.as_option('id', 'name') \n\n for obj in User.objects.all():\n user = user + obj.as_option_by_two_text('id', 'first_name', 'last_name')\n\n result['step'] = step\n result['status'] = status\n result['user'] = user\n return result \n\n def workflow(request):\n if request.method == 'GET':\n context = _Item.get_options()\n return render(request, 'todolist/item_work.html', context)","sub_path":"todolist/views/_Item.py","file_name":"_Item.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"198416885","text":"from Geometry.Rectangle import Rectangle\n\ndef get_bw_img_cropped_to_bounds(img, image):\n return get_img_cropped_to_bounds(img, get_bw_img_bounds(img, image))\n\ndef get_bw_img_bounds(img, image):\n left_x = img.size[0]\n right_x = 0\n up_y = img.size[1]\n down_y = 0\n for x in range(0, img.size[0]):\n for y in range(0, img.size[1]):\n if image[x,y] != 0:\n if x < left_x:\n left_x = x\n if x > right_x:\n right_x = x\n if y < up_y:\n up_y = y\n if y > down_y:\n down_y = y\n return Rectangle(left_x, up_y, (right_x - left_x), (down_y - up_y))\n \ndef get_img_cropped_to_bounds(img, rect):\n return img.crop((rect.get_x(), rect.get_y(), rect.get_x() + rect.get_width(), rect.get_y() + rect.get_height()))\n\n ","sub_path":"ImageProcessingFinalRewrite/ImageOperation/Crop.py","file_name":"Crop.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"515173598","text":"from mylib.shell.ver1 import Shell\nfrom mylib.os.ver1 import yield_filelist\n\n# BASE_CMD's converting speed is fast. but duration meta is not accurate.\n# if you want accurate duration\nBASE_CMD = '/usr/bin/avconv -i {0} -threads auto -vn -c:a libmp3lame -qscale:a 3 {1}'\n# ACCURATE_DURATION_CMD = '/usr/bin/avconv -i {0} -b:a 128k -f mp3 - > {1}'\n\n\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in xrange(0, len(l), n):\n yield l[i:i + n]\n\n\ndef main(src_dir):\n cmds = []\n for fp in yield_filelist(src):\n fp = fp.replace(' ', '\\ ')\n out_fp = fp.replace('.mp4', '.mp3')\n c = cmd.format(fp, out_fp)\n cmds.append(c)\n\n for l in chunks(cmds, 3):\n tmps = [Shell(c) for c in l]\n for i in tmps:\n i.communicate()\n\n\nif __name__ == '__main__':\n src_dir = ''\n main()\n","sub_path":"py/convert_mp4_to_mp3/avconv.py","file_name":"avconv.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"376310460","text":"import os\n\nfrom flask import Blueprint, make_response, jsonify, request\nfrom flask.views import MethodView\n\nfrom server import db\nfrom server.models import UserViewsData, User\nfrom server.userviewsdata import UserDataView\nfrom utils.cache_utils import cache_get\nfrom utils.utils import auth_token_check\n\ndashboard_blueprint = Blueprint('dashboard', __name__, url_prefix=os.environ.get('API_VERSION'))\n\n\nclass DashboardAPI(MethodView):\n\n def get(self):\n \"\"\"\n Get user's data for the dash board page, where the LOEWI Score, general categorization of lab results\n and the nutritional recommendations are shown.\n \"\"\"\n user_id = auth_token_check(request.headers.get('Authorization'))\n if not isinstance(user_id, int):\n return user_id\n user = User.query.filter_by(id=user_id).first()\n\n response_object = {}\n response_object['labResults'] = cache_get(str(user_id) + \"_dashboard_labResults\")\n if response_object['labResults']:\n loewi_score = cache_get(str(user_id) + \"_loewiScore\")\n if loewi_score:\n response_object['loewiScore'] = loewi_score['loewiScore']\n response_object['loewiScoreChart'] = loewi_score['loewiScoreChart']\n response_object['loewiScoreImportances'] = loewi_score['loewiScoreImportances']\n if not response_object['loewiScore'] or not response_object['loewiScoreChart']:\n loewi_score = UserDataView(user_id).get_data(\"loewi_score\")\n response_object['loewiScore'] = loewi_score['loewiScore']\n response_object['loewiScoreChart'] = loewi_score['loewiScoreChart']\n response_object['loewiScoreImportances'] = loewi_score['loewiScoreImportances']\n else:\n loewi_score = UserDataView(user_id).get_data(\"loewi_score\")\n response_object['loewiScore'] = loewi_score['loewiScore']\n response_object['loewiScoreChart'] = loewi_score['loewiScoreChart']\n response_object['loewiScoreImportances'] = loewi_score['loewiScoreImportances']\n response_object['recipes'] = cache_get(str(user_id) + '_recipeList')\n response_object['foods'] = cache_get(str(user_id) + '_foodList')\n if not response_object['foods']:\n response_object['foods'] = UserDataView(user_id).get_data(\"foods\")['foods']\n if not response_object['recipes']:\n response_object['recipes'] = UserDataView(user_id).get_data(\"recipes\")['recipes']\n else:\n uvd = UserViewsData.query.filter_by(user_id=user_id).first()\n if not uvd:\n uvd = UserViewsData(user=user)\n db.session.add(uvd)\n db.session.commit()\n response_object['labResults'] = {}\n response_object['loewiScore'] = 0\n response_object['loewiScoreChart'] = []\n response_object['loewiScoreImportances'] = []\n\n recipe_fields = {}\n try:\n for k, v in response_object['recipes'].items():\n if k != 'normal':\n recipe_fields[k] = v.keys()\n except Exception:\n pass\n response_object['recipes'] = recipe_fields\n\n if user.userType:\n response_object['usertype'] = user.userType.name\n else:\n response_object['usertype'] = \"\"\n response_object['profilePictureUrl'] = user.pictureUrl\n response_object['username'] = user.first_name\n\n return make_response(jsonify(response_object)), 200\n\n\n# API Resources\ndashboard_view = DashboardAPI.as_view('dashboard_api')\n\n# Rules for API Endpoints\ndashboard_blueprint.add_url_rule(\n '/dashboard_bv_summary_list',\n view_func=dashboard_view,\n methods=['GET']\n)\n","sub_path":"server/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"89443599","text":"# Задача на программирование: покрыть отрезки точками\n#\n#\n# По данным 𝑛 отрезкам необходимо найти множество точек минимального размера,\n# для которого каждый из отрезков содержит хотя бы одну из точек.\n#\n# В первой строке дано число 1≤𝑛≤100 отрезков.\n# Каждая из последующих 𝑛 строк содержит по два числа 0≤𝑙≤𝑟≤109, задающих начало и конец отрезка.\n# Выведите оптимальное число 𝑚 точек и сами 𝑚 точек. Если таких множеств точек несколько, выведите любое из них.\n#\n# Sample Input 1:\n#\n# 3\n# 1 3\n# 2 5\n# 3 6\n# Sample Output 1:\n#\n# 1\n# 3\n\nresult = []\n\ndef findPoints(sections):\n if not sections:\n return result\n else:\n newSections = []\n point = sections[0][1]\n result.append(point)\n for item in sections:\n if not contains(point, item[0], item[1] + 1):\n newSections.append(item)\n return findPoints(newSections)\n\ndef findPoints2(segments):\n dots = [segments.pop(0)[1]]\n for l, r in segments:\n if l > dots[-1]:\n dots.append(r)\n return dots\n\ndef contains(x, *tuple):\n return (x in range(tuple[0], tuple[1]))\n\nif __name__ == '__main__':\n sections = []\n sectionCount = int(input())\n\n for i in range(sectionCount):\n x, y = map(int, input().split())\n sections.append([x, y])\n\n sections.sort(key= lambda x: x[1])\n\n dots = findPoints2(sections)\n\n print(len(dots))\n print(\" \".join(map(str, dots)))\n\n\n","sub_path":"hungry/PointSection.py","file_name":"PointSection.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"135325489","text":"import time\nfrom goerr import Trace\n\nerr = Trace()\n\n\ndef func1():\n print(\"Func 1 running\")\n time.sleep(0.5)\n try:\n 'x' > 1\n except Exception as e:\n err.new(\"Errmsg frun func1\", e)\n print(\"Func 1 finished\")\n\n \ndef func2():\n func1()\n time.sleep(0.5)\n err.via(\"Errmsg frun func2\")\n print(\"Func 2 running\")\n\n \ndef func3():\n func2()\n time.sleep(0.5)\n err.via()\n print(\"Func 3 running\")\n\n \nfunc3()\nerr.trace()\n","sub_path":"examples/call_stack.py","file_name":"call_stack.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"20460414","text":"from django.urls import path,include\nfrom . import views\n\napp_name = 'client'\n\nurlpatterns = [\n path('signin/',views.sign_in,name='sign_in'),\n path('signout/',views.sign_out,name='sign_out'),\n path('',views.hello,name='hello'),\n]","sub_path":"client/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"495767460","text":"_base_ = [\n '../_base_/models/retinanet_r50_fpn.py',\n '../_base_/datasets/coco_detection.py'\n]\nmodel = dict(\n pretrained='/media/amax/Passport_4T/backbone-crossformer-s.pth',\n backbone=dict(\n type='CrossFormer_S',\n group_size=[7, 7, 7, 7],\n crs_interval=[8, 4, 2, 1]),\n neck=dict(\n type='FPN',\n in_channels=[96,192,384,768],\n out_channels=256,\n start_level=1,\n add_extra_convs='on_input',\n num_outs=5))\n# optimizer\noptimizer = dict(type='AdamW', lr=0.0001, weight_decay=0.0001)\noptimizer_config = dict(grad_clip=None)\n# learning policy\nlr_config = dict(\n policy='step',\n warmup='linear',\n warmup_iters=500,\n warmup_ratio=0.001,\n step=[8, 11])\ntotal_epochs = 12\ncheckpoint_config = dict(interval=1)\n# yapf:disable\nlog_config = dict(\n interval=50,\n hooks=[\n dict(type='TextLoggerHook'),\n # dict(type='TensorboardLoggerHook')\n ])\n# yapf:enable\ndist_params = dict(backend='nccl')\nlog_level = 'INFO'\nload_from = None\nresume_from = None\nworkflow = [('train', 1)]\nwork_dir = 'work_dirs/coco/crossformer/retinanet_crossformer_s_fpn_1x_coco'","sub_path":"configs/crossformer/retinanet_crossformer_s_fpn_1x_coco.py","file_name":"retinanet_crossformer_s_fpn_1x_coco.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"646961355","text":"#!/usr/bin/python3\r\nfrom QuickSort import quick_sort\r\nfrom Queue import LinkedQueue\r\n\r\n\r\ndef AddValues(queue, fp):\r\n '''\r\n :param queue: queue to add values to\r\n :param fp: file pointer to read from\r\n :return: None\r\n '''\r\n for num in fp:\r\n queue.enqueue( float(num))\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n fp = open(input(\"Please Enter File Name: \"), \"r\")\r\n queue = LinkedQueue()\r\n\r\n AddValues(queue, fp)\r\n fp.close()\r\n\r\n quick_sort(queue)\r\n print(queue)\r\n","sub_path":"CSE-331-Projects/Project5/project5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"153158422","text":"import pickle\nimport tempfile\nfrom indra.tools.small_model_tools.modelScope.buildPriorModel import build_prior\nfrom indra.statements import *\nfrom indra.tools import assemble_corpus as ac\nfrom indra.tools.small_model_tools.modelScope.buildDrugTreatmentStatements import buildExperimentalStatements\nfrom indra.tools.small_model_tools.modelScope.buildDrugTreatmentStatements import buildDrugTargetStmts\nfrom indra.tools.small_model_tools.modelScope.buildUseCaseModel import expandModel\nfrom indra.tools.small_model_tools.modelScope.addBNGLParameters import addObservables\nfrom indra.tools.small_model_tools.modelScope.addBNGLParameters import addSimParamters\nfrom indra.tools.small_model_tools.modelContext import extraModelReductionTools as ex\nfrom indra.assemblers import PysbAssembler\nimport pysb\n\n\n#Build Prior\n\n\nmodel_types = [Phosphorylation,Dephosphorylation,ActiveForm,IncreaseAmount,DecreaseAmount,Complex] #Gef,GtpActivation]#Check sos and raf stmts \ndrugTargets = ['PDGFRA']#,'KDR','FLT3']\nmodifiedNodes = ['RPS6','PKM','HIF1A']# ['JUN','STAT1','PKM','RPS6','AURKA','HIF1A','MYC']\n#modifiedNodes = ['PKM']# ['JUN','STAT1','PKM','RPS6','AURKA','HIF1A','MYC']\notherNodes =[]# ['MYC','JUN']#ligands = ['PDGFA','PDGF','VEGF','VEGFA','FLT3LG']\nmodel_genes = drugTargets + modifiedNodes + otherNodes\n\n\nreach_stmts = './indraReading/raw_stmts/reach_output.pkl'\ntrips_stmts = './indraReading/raw_stmts/trips_output.pkl'\nprior_stmts = build_prior(model_genes,model_types,dbs=True,additional_stmts_files=[])\n\n#Prior reduction\n\n#Map to model_types\nmods_to_keep = list(map(lambda obj: obj.__name__.lower(), model_types))\n\nstmts_to_remove = []\nfor st in prior_stmts:\n full_mods = list(map(lambda obj: obj.mods, st.agent_list())) #gives mods for a stmt, in list of lists. Actually need mod types. [(phosphorylation, Y, 589)]\n flattened_mods = list(itertools.chain.from_iterable(full_mods))\n #mod_types = list(map(lambda obj: obj.mod_type, mods) #mod types in lol \n mod_types = list(map(lambda obj: obj.mod_type, flattened_mods))\n if any([el for el in mod_types if el not in mods_to_keep]):\n stmts_to_remove.append(st)\nprior_model_stmts = [st for st in prior_stmts if st not in stmts_to_remove]\n\n\nstmts_to_remove = []\nfor st in prior_model_stmts:\n for ag in st.agent_list():\n for mod in ag.mods:\n if mod.mod_type not in mods_to_keep:\n stmts_to_remove.append(st)\n\nprior_model_stmts = [st for st in prior_model_stmts if st not in stmts_to_remove]\n\n\nprior_model_stmts = ex.removeMutations(prior_model_stmts)\nprior_model_stmts = ex.removeDimers(prior_model_stmts)\n\n\n#Add drug-target interactions \ndrugSentences = 'SORAFENIB dephosphorylates PDGFRA. SORAFENIB dephosphorylates KDR. SORAFENIB dephosphorylates FLT3'\ndrug_stmts = buildDrugTargetStmts(drugSentences)\nprior_model_stmts = prior_stmts + drug_stmts\n\n#save prior model \nac.dump_statements(prior_model_stmts,'../final_testing_models/cardiotoxPrior_akt.pkl')\n\n\n\n###########################################################################\n\n#Expand model to match experimental observations\n\nprior_model_stmts = ac.load_statements('../final_testing_models/cardiotoxPrior_akt.pkl')\n#otherNodes = ['MYC','JUN']#ligands = ['PDGFA','PDGF','VEGF','VEGFA','FLT3LG']\n\nexpSentences = 'SORAFENIB dephosphorylates RPS6. SORAFENIB phosphorylates PKM. SORAFENIB transcribes HIF1A.'\nexp_stmts = buildExperimentalStatements(expSentences)\n\n\nexpObservations = {'RPS6':['phosphorylation',exp_stmts[0]],'PKM':['dephosphorylation',exp_stmts[1]],'HIF1A':['decreaseamount',exp_stmts[2]]}\n#expObservations = {'PKM':['phosphorylation',exp_stmts[1]]}\n#expObservations = {'PKM':['dephosphorylation',exp_stmts[1]]}\ndrug = 'SORAFENIB'\n#drugTargets = ['FLT3','PDGFRA','KDR']\ndrugTargets = ['PDGFRA']\ninitialStmts = prior_model_stmts\ninitialNodes = []\nfor st in prior_model_stmts:\n for ag in st.agent_list():\n if ag.name not in initialNodes:\n initialNodes.append(ag.name)\n\n\nmodelStmts = expandModel(expObservations,drug,drugTargets,initialStmts,initialNodes,otherNodes)\n\n\n###########################################################################\n\n#Build and write bngl model \n\npa = PysbAssembler()\npa.add_statements(modelStmts)\npysbModel = pa.make_model()\n#WARNING: [2018-08-29 16:12:59] indra/pysb_assembler - HIF1A transcribes itself, skipping???\n\nmodel_obs = addObservables(pysbModel,bound=True)\n\n\nbngl_model_filter = pysb.export.export(model_obs,'bngl')\nbngl_file_filter = open('../final_testing_models/cardiotoxPrior_akt.bngl','w')\nbngl_file_filter.write(bngl_model_filter+'\\n')\nbngl_file_filter.close()\nmodel_actions = addSimParamters(method='ode',equil=True,equilSpecies=['SORAFENIB()'],viz=True)\nbngl_file_filter = open('../final_testing_models/cardiotoxPrior_akt.bngl','w')\nbngl_file_filter.write(model_actions)\nbngl_file_filter.close()\n\n\n\n#from indra.util import _require_python3\n#import os\n#import json\n#import time\n#import pickle\n\n## CREATE A JSON FILE WITH THIS INFORMATION, E.G., a file consisting of:\n## {\"basename\": \"fallahi_eval\", \"basedir\": \"output\"}\n#with open('config.json', 'rt') as f:\n# config = json.load(f)\n## This is the base name used for all files created/saved\n#basen = config['basename']\n## This is the base folder to read/write (potentially large) files from/to\n## MODIFY ACCORDING TO YOUR OWN SETUP\n#based = config['basedir']\n\n## This makes it easier to make standardized pickle file paths\n#prefixed_pkl = lambda suffix: os.path.join(based, basen + '_' + suffix + '.pkl')\n\n#def pkldump(suffix, content):\n# fname = prefixed_pkl(suffix)\n# with open(fname, 'wb') as fh:\n# pickle.dump(content, fh)\n\n#def pklload(suffix):\n# fname = prefixed_pkl(suffix)\n# print('Loading %s' % fname)\n# ts = time.time()\n# with open(fname, 'rb') as fh:\n# content = pickle.load(fh)\n# te = time.time()\n# print('Loaded %s in %.1f seconds' % (fname, te-ts))\n# return content\n\n\n\n\n","sub_path":"modelBuildingCode/buildCardiotoxModel_akt_ex.py","file_name":"buildCardiotoxModel_akt_ex.py","file_ext":"py","file_size_in_byte":5921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"451646726","text":"from unityagents import UnityEnvironment\nimport numpy as np\nimport random\nimport torch\nfrom collections import deque\nfrom ddpg_agent import Agent\nimport matplotlib.pyplot as plt\n\n#env = UnityEnvironment(file_name='Reacher_Linux_NoVis/Reacher.x86_64')\nenv = UnityEnvironment(file_name='Reacher_Linux_NoVis_20/Reacher.x86_64')\n\nbrain_name = env.brain_names[0]\nbrain = env.brains[brain_name]\n\nagent = Agent(state_size=33, action_size=4, random_seed=1)\n\ndef ddpg(n_episodes=3000, max_t=2000, print_every=100):\n scores_deque = deque(maxlen=print_every)\n scores = []\n for i_episode in range(1, n_episodes+1):\n env_info = env.reset(train_mode=True)[brain_name]\n states = env_info.vector_observations\n agent.reset()\n score = np.zeros(len(env_info.agents))\n #for t in range(max_t):\n while True:\n actions = agent.act(states)\n env_info = env.step(actions)[brain_name]\n next_states = env_info.vector_observations\n rewards = env_info.rewards \n dones = env_info.local_done \n \n agent.step(states, actions, rewards, next_states, dones)\n \n score += rewards # update the score (for each agent)\n states = next_states # roll over states to next time step\n if np.any(dones): # exit loop if episode finished\n break\n scores_deque.append(np.mean(score))\n scores.append(np.mean(score))\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)), end=\"\")\n torch.save(agent.actor_local.state_dict(), 'checkpoint_actor.pth')\n torch.save(agent.critic_local.state_dict(), 'checkpoint_critic.pth')\n if i_episode % print_every == 0:\n print('\\rEpisode {}\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))\n if np.mean(scores_deque)>=30.0:\n print('\\nEnvironment solved in {:d} episodes!\\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))\n torch.save(agent.actor_local.state_dict(), 'checkpoint_actor.pth')\n torch.save(agent.critic_local.state_dict(), 'checkpoint_critic.pth')\n break\n \n return scores\n\nscores = ddpg()\n\n# plot the scores\nfig = plt.figure()\nax = fig.add_subplot(111)\nplt.plot(np.arange(len(scores)), scores)\nplt.ylabel('Score')\nplt.xlabel('Episode #')\nplt.savefig(\"score.png\")","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"31527107","text":"# nafsmon\n# preSetup.py - setup for db and other stuff\n# Copyright Vilhelm Prytz 2018\n\nimport logging\n\n# imports\nfrom database import dbConnection\n\ndef setupServerListConfDb(config):\n connection, cursor, connectionStatus = dbConnection(config.serverListConfPath)\n\n if connectionStatus == False:\n logging.critical(\"Exit due to SQL connection failure\")\n exit(1)\n","sub_path":"nafsmon/preSetup.py","file_name":"preSetup.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"519065870","text":"from sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import MinMaxScaler\nimport numpy as np\nimport firebase as fb\nimport pickle\n\n\nclass Model:\n\n models = {\n \"log_reg\": LogisticRegression,\n \"clf\": DecisionTreeClassifier,\n \"knn\": KNeighborsClassifier,\n \"lda\": LinearDiscriminantAnalysis,\n \"gnb\": GaussianNB,\n \"svm\": SVC,\n }\n\n def __init__(self, model_type=\"\"):\n \"\"\"\n REQUIRES: model_type in models == True\n \"\"\"\n if model_type not in self.models and model_type != \"\":\n raise ValueError(f\"Invalid model name: {model_type}.\")\n\n if model_type != \"\":\n self.type = model_type\n self.model = self.models[model_type]()\n else:\n self.type = None\n self.model = None\n self.scaler = None\n\n def build(self, X, y):\n self.scaler = MinMaxScaler()\n X = self.scaler.fit_transform(X)\n return self.model.fit(X, y.reshape(-1))\n\n def predict(self, prediction_variables):\n \"\"\"\n REQUIRES: loaded_model a representation of our loaded model object\n prediction_variables a well-typed list of length expected \n args for loaded model \n ENSURES: returns what that particularly trained model predicts\n given those inputs\n \"\"\"\n X_predict = [list(map(float, prediction_variables))]\n if self.scaler is not None:\n X_predict = self.scaler.transform(X_predict)\n guess = self.model.predict(X_predict)\n # issues with jsonify and numpy Int64\n if(isinstance(guess[0], str)):\n return guess[0]\n return float(guess[0])\n\n def get_accuracy(self, X, y):\n if self.scaler is not None:\n X = self.scaler.transform(X)\n guess = self.model.predict(X)\n return round(np.mean(guess == y.reshape(-1)), 4)\n\n def pickle(self):\n return pickle.dumps(self)\n\n @staticmethod\n def load_model(uid, pid, model_type):\n \"\"\"\n REQUIRES: uid valid user id (string)\n pid valid project id (string)\n model_type valid model type (string)\n ENSURES: returns a Model object corresponding to \n the user uid, project pid, and model model_type\n \"\"\"\n # get firebase stuff\n path = fb.make_path(uid, pid, model_type)\n bucket = fb.bucket_init()\n\n # load model\n unpickled_model = fb.get_pickle(bucket, path)\n if isinstance(unpickled_model, Model):\n return unpickled_model\n model = Model()\n model.type = model_type\n model.model = unpickled_model\n\n return model\n","sub_path":"api/src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"343144798","text":"# 나의 코드\ndef solution(n, m):\n answer = []\n for i in range(min(n,m), 0, -1):\n if n % i == 0 and m % i == 0:\n answer = [i, n*m/i]\n break\n\n return answer\n\n# 다른 코드\ndef solution(a, b):\n c, d = max(a, b), min(a, b)\n t = 1\n while t > 0:\n t = c % d # 최댓값, 최솟값\n c, d = d, t # 최댓값 = 최솟값, 최솟값 = 최댓값과 최솟값의 나머지\n answer = [c, int(a*b/c)]\n\n return answer\n","sub_path":"Programmers/Level1/최대공약수와_최소공배수.py","file_name":"최대공약수와_최소공배수.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"583268984","text":"import tweepy\nimport random\nimport os\n\n # NOW, create a file in the same mani file called \"secret.txt\": consumer key, consumer secret, acess token, acess secret. [direct copy and paste].\n\n#opens secret.txt file\nwith open (\"secret.txt\") as f: \t\n\tsecrets = f.realines ()\n\t#secrets = [consumer key, consumer secret, access token, access secret] ---an array\nf.close() #closes the file\n\n\n#get/set Twitter authorization information from secret array\n#REMEMBER to remove newline characters: \"\\n\"\nCONSUMER_KEY=secret[0].rstrip('\\n') #sets the consumer_key to the first element in the array\nCONSUMER_SECRET=secrets[1].rstrip('\\n') #removes newline character from b/c API does not expect enter line in secret.txt\nACCESS_TOKEN = secrets[2].rstrip('\\n')\nACCESS_SECRET=secrets[3].rstrip('\\n')\n\n\n#Give your access info to Tweepy so that you can access the Twitter API\n#Otherwise your Tweepy API calls will be rejected :<\nauth =tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) #set auth. OAuthHandler function belongs to tweepy, and we put in the parameters\nauth.set_access_token(ACCESS_TOKEN,ACCESS_SECRET) #adding this ACCESS-thingy info to auth. Essentially, paring [consumer_key/secret with access_token/secret]\napi = tweepy.API(auth); #access our API and abstract it to a single variable by calling tweepy.api(auth).\n#Now we've got our tweepy api access!\n#Now, we can do our stuff- getting images, quotes, & posting...\n\n\n#Build list of tweets! (check out github for building more complex tweetlist)\ntweetlist = [\n\"Physics puns are no joke. It's a relatively dark matter\",\n\"The universe was cold, before it mattered\",\n\"What does a subatomic duck sound like? QUARK!\"]\n\n#Set up a shortcut to your image directory so you have esay access to it later\n##We first need to store images in a seperate folder called \"img\". \n##In order to access these, we set imgdir = to os. get the stuff in this \"img/\" directory/folder\nimgdir= os.listdir(\"img/\") \n\n\n#Tweeting! this is the tweet API call!\n#Tweepy has function called api.update_with_media \n#that lets you make a new tweet with a photo and text.\n#time.sleep(10) means there will be a 10s break between each tweet.\nfor tweet in tweetlist:\n\tapi_update_media(\"img/\"+random.choice(imgdir),tweet)\n\t\n\t#for every tweet it the tweetlist (there are 3), api_update_media--will post a tweet and an iamge.\n\t#Take our image: \"img/\"+[random.choice(imgdir)--randomly picks an img from the imgdir directory]. \n\t#Take a tweet from the tweelist: tweet.\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"300817159","text":"\r\n#!/usr/bin/env python3\r\n\r\n#bch5884 project1 code\r\n#author Hannah O'Day\r\n#uploaded to github repository: https://github.com/hannahoday/bch5884.git\r\n\r\nimport sys\r\n\r\n#reading pdb file from argv\r\n#asking user for geometric (G) or center of mass (M)\r\npdbfilename=sys.argv[1]\r\nchoice=input(\"This program will create a new file of name: 'centered2FA9noend.pdb'\\nTo select method of centering, Type 'G' for geometric center or 'M' for center by mass:\")\r\nf=open(pdbfilename)\r\nlines=f.readlines()\r\nf.close()\r\n\r\n#var records=list of lists for parsed pdb file\r\nrecords=[]\r\nmassdict={\"H\":1.01, \"C\":12.01,\"N\":14.01,\"O\":16.0, \"P\":30.97, \"S\":32.07,\"MG\":24.30}\r\nfor line in lines:\r\n atom=line[0:6].strip()\r\n integer=line[7:11].strip()\r\n name=line[13:16].strip()\r\n altloc=line[16].strip()\r\n resname=line[17:20].strip()\r\n chainID=line[21]\r\n resSeq=line[22:26].strip()\r\n icode=line[26]\r\n x=float(line[30:38])\r\n y=float(line[39:46])\r\n z=float(line[47:54])\r\n occ=line[55:60].strip()\r\n temp=line[61:66].strip()\r\n element=line[76:78].strip()\r\n mass=massdict[element]\r\n records.append([atom,integer,name,altloc,resname,chainID,resSeq,icode,x,y,z,occ,temp,element,mass])\r\n\r\n#setting var values to 0 for loop operations\r\nsumx=0\r\nsumy=0\r\nsumz=0\r\nlength=len(records)\r\nmass=0\r\navgx=0\r\navgy=0\r\navgz=0\r\n\r\n#center mass calculation\r\nif choice==\"M\":\r\n for record in records:\r\n sumx=sumx+(record[8]*record[14])\r\n sumy=sumy+(record[9]*record[14])\r\n sumz=sumz+(record[10]*record[14])\r\n mass=mass+record[14]\r\n avgx=sumx/mass\r\n avgy=sumy/mass\r\n avgz=sumz/mass\r\n\r\n#geometric calculation\r\nelif choice==\"G\":\r\n for record in records:\r\n sumx=sumx+record[8]\r\n sumy=sumy+record[9]\r\n sumz=sumz+record[10]\r\n avgx=sumx/length\r\n avgy=sumy/length\r\n avgz=sumz/length\r\n\r\n#changing coordinates based on center\r\n#setting new values to records\r\nfor record in records:\r\n record[8]=record[8]-avgx\r\n record[9]=record[9]-avgy\r\n record[10]=record[10]-avgz\r\n\r\n#creating new file\r\n#writing formatted string\r\nnewf=open(\"centered2FA9noend.pdb\",\"w\")\r\nfor record in records:\r\n newf.write(\"%-6s%5s %-3s%1s%-3s %1s%4s%1s %8.3f%8.3f%8.3f %5s%6s%12s\\n\" % (record[0],record[1],record[2],record[3],record[4],record[5],record[6],record[7],record[8],record[9],record[10],record[11],record[12],record[13]))\r\nnewf.close\r\n\r\n\r\n","sub_path":"project/project1.py","file_name":"project1.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"642976272","text":"# python tools/train.py configs/custom/models/retinanet/retina_r50_mosaic.py\r\n# python tools/train_cv.py configs/custom/models/retinanet/retina_r50_mosaic.py\r\n\r\n# python tools/inference.py configs/custom/models/retinanet/retina_r50_mosaic.py work_dirs/retinanet --epoch best_bbox_mAP_50_epoch_14\r\n\r\n\r\n_base_ = [\r\n \"retinanet_r50_fpn.py\",\r\n \"../../helper/dataset.py\",\r\n \"../../helper/runtime.py\",\r\n \"../../helper/schedule.py\",\r\n]\r\n\r\nimg_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)\r\nimg_scale = (1024, 1024)\r\n\r\ntrain_pipeline = [\r\n dict(type=\"Mosaic\", img_scale=img_scale, pad_val=128.0),\r\n dict(type=\"RandomAffine\", scaling_ratio_range=(0.1, 2), border=(-img_scale[0] // 2, -img_scale[1] // 2)),\r\n dict(type=\"MixUp\", img_scale=img_scale, ratio_range=(0.8, 1.6), pad_val=128.0),\r\n dict(\r\n type=\"PhotoMetricDistortion\",\r\n brightness_delta=32,\r\n contrast_range=(0.5, 1.5),\r\n saturation_range=(0.5, 1.5),\r\n hue_delta=18,\r\n ),\r\n dict(type=\"RandomFlip\", flip_ratio=0.5),\r\n dict(type=\"Resize\", keep_ratio=True),\r\n dict(type=\"Pad\", pad_to_square=True, pad_val=128.0),\r\n dict(type=\"Normalize\", **img_norm_cfg),\r\n dict(type=\"DefaultFormatBundle\"),\r\n dict(type=\"Collect\", keys=[\"img\", \"gt_bboxes\", \"gt_labels\"]),\r\n]\r\ndata_root = \"../../../dataset/\"\r\ndataset_type = \"CocoDataset\"\r\nclasses = (\r\n \"General trash\",\r\n \"Paper\",\r\n \"Paper pack\",\r\n \"Metal\",\r\n \"Glass\",\r\n \"Plastic\",\r\n \"Styrofoam\",\r\n \"Plastic bag\",\r\n \"Battery\",\r\n \"Clothing\",\r\n)\r\ndata = dict(\r\n train=dict(\r\n _delete_=True,\r\n type=\"MultiImageMixDataset\",\r\n dataset=dict(\r\n type=dataset_type,\r\n classes=classes,\r\n ann_file=data_root + \"train.json\",\r\n img_prefix=data_root,\r\n pipeline=[dict(type=\"LoadImageFromFile\"), dict(type=\"LoadAnnotations\", with_bbox=True)],\r\n filter_empty_gt=False,\r\n ),\r\n pipeline=train_pipeline,\r\n dynamic_scale=img_scale,\r\n )\r\n)\r\n\r\n\r\n# runtime\r\n# work_dir, wandb exp name\r\nexp = \"retinanet_resnet_mosaic\"\r\nwork_dir = f\"./work_dirs/{exp}\"\r\n\r\n# Wandb Log\r\nlog_config = dict(\r\n interval=500,\r\n hooks=[\r\n dict(type='TextLoggerHook'),\r\n dict(type='WandbLoggerHook',\r\n init_kwargs=dict(\r\n project='object-detection-recycling-trash',\r\n entity = 'boostcamp-2th-cv-02team',\r\n name = f\"{exp}\"\r\n ),\r\n )\r\n ])\r\n\r\nworkflow = [('train', 1), ('val', 1)] # random validation 기준 평가\r\n# workflow = [('train', 1)]\r\n\r\n# optimizer ----- \r\n# optimizer = dict(_delete_=True, type=\"SGD\", lr=0.002, momentum=0.9, weight_decay=0.0001)\r\n# optimizer_config = dict(grad_clip=None)\r\n# ------------------\r\n\r\n# learning policy\r\nlr_config = dict(_delete_=True, policy=\"step\", warmup=\"linear\", warmup_iters=500, warmup_ratio=0.001, step=[8, 11])\r\nrunner = dict(type=\"EpochBasedRunner\", max_epochs=12)\r\n\r\n# dataset\r\nevaluation = dict(classwise = True) # class 별 ap 확인 \r\ndata = dict(samples_per_gpu=4, workers_per_gpu=2)\r\n","sub_path":"template/mmdetection/configs/custom/models/retinanet/retina_r50_mosaic.py","file_name":"retina_r50_mosaic.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"114471062","text":"\"\"\"\nData handling between inputs, cache, and avwx core\n\"\"\"\n\n# pylint: disable=broad-except\n\n# stdlib\nimport asyncio as aio\nfrom dataclasses import asdict\nfrom datetime import datetime, timezone\n\n# library\nimport rollbar\n\n# module\nimport avwx\nfrom avwx_api import app\n\nERRORS = [\n \"Station Lookup Error: {} not found for {}. There might not be a current report in ADDS\",\n \"Report Parsing Error: Could not parse {} report. An error report has been sent to the admin\",\n \"Station Lookup Error: {} does not appear to be a valid station. Please contact the admin\",\n \"Report Lookup Error: No {} reports were found for {}. Either the station doesn't exist or there are no active reports\",\n \"Report Lookup Error: An unknown error occurred fetch the {} report. An error report has been sent to the admin\",\n \"Report Lookup Error: Unable to fetch report from {}. You might wish to use '?onfail=cache' to return the most recent report even if it's not up-to-date\",\n \"Station Error: {} does not publish reports\",\n]\n\n\nclass ReportHandler:\n \"\"\"\n Handles AVWX report parsers and data formatting\n \"\"\"\n\n report_type: str\n parser: avwx.base.AVWXBase\n\n option_keys: [str] = None\n\n # Report data is a list\n listed_data: bool = False\n cache: bool = True\n history: bool = False\n\n def __init__(self):\n if self.option_keys is None:\n self.option_keys = tuple()\n\n @staticmethod\n def _make_meta() -> dict:\n \"\"\"\n Create base metadata dict\n \"\"\"\n return {\n \"timestamp\": datetime.now(tz=timezone.utc),\n \"stations_updated\": avwx.station.__LAST_UPDATED__,\n }\n\n def _make_data(self, parser: avwx.base.AVWXBase) -> dict:\n \"\"\"\n Create the cached data representation from an updated parser\n \"\"\"\n data = {}\n if self.listed_data:\n data[\"data\"] = [asdict(r) for r in parser.data]\n data[\"units\"] = asdict(parser.units)\n else:\n data[\"data\"] = asdict(parser.data)\n data[\"data\"][\"units\"] = asdict(parser.units)\n if \"translate\" in self.option_keys:\n data[\"translate\"] = asdict(parser.translations)\n if \"summary\" in self.option_keys:\n data[\"summary\"] = parser.summary\n if \"speech\" in self.option_keys:\n data[\"speech\"] = parser.speech\n return data\n\n async def _update_parser(\n self, parser: avwx.base.AVWXBase, err_station: \"stringable\" = None\n ) -> (dict, int):\n \"\"\"\n Updates the data of a given parser and returns any errors\n\n Attempts to fetch five times before giving up\n \"\"\"\n report_type = parser.__class__.__name__.upper()\n state_info = {\n \"state\": \"fetch\",\n \"type\": report_type,\n \"station\": getattr(parser, \"station\", None),\n \"source\": parser.service,\n }\n # Update the parser's raw data\n try:\n for _ in range(3):\n try:\n if not await parser.async_update(timeout=2, disable_post=True):\n err = 0 if isinstance(err_station, str) else 3\n return (\n {\"error\": ERRORS[err].format(report_type, err_station)},\n 400,\n )\n break\n except TimeoutError:\n pass\n else:\n # msg = f\"Unable to call {parser.service.__class__.__name__}\"\n # rollbar.report_message(msg, extra_data=state_info)\n return (\n {\"error\": ERRORS[5].format(parser.service.__class__.__name__)},\n 502,\n )\n except aio.CancelledError:\n print(\"Cancelled Error\")\n return {\"error\": \"Server rebooting. Try again\"}, 503\n except ConnectionError as exc:\n print(\"Connection Error:\", exc)\n rollbar.report_exc_info(extra_data=state_info)\n return {\"error\": str(exc)}, 502\n except avwx.exceptions.SourceError as exc:\n print(\"Source Error:\", exc)\n rollbar.report_exc_info(extra_data=state_info)\n return {\"error\": str(exc)}, int(str(exc)[-3:])\n except avwx.exceptions.InvalidRequest as exc:\n print(\"Invalid Request:\", exc)\n return {\"error\": ERRORS[0].format(report_type, err_station)}, 400\n except Exception as exc:\n print(\"Unknown Fetching Error\", exc)\n rollbar.report_exc_info(extra_data=state_info)\n return {\"error\": ERRORS[4].format(report_type)}, 500\n # Parse the fetched data\n try:\n parser._post_update() # pylint: disable=protected-access\n except avwx.exceptions.BadStation as exc:\n print(\"Unknown Station:\", exc)\n return {\"error\": ERRORS[2].format(parser.station)}, 400\n except Exception as exc:\n print(\"Unknown Parsing Error\", exc)\n state_info[\"state\"] = \"parse\"\n state_info[\"raw\"] = parser.raw\n rollbar.report_exc_info(extra_data=state_info)\n return {\"error\": ERRORS[1].format(report_type), \"raw\": parser.raw}, 500\n return None, None\n\n async def _new_report(\n self, parser: avwx.base.AVWXBase, cache: bool = None, history: bool = None\n ) -> (dict, int):\n \"\"\"\n Fetch and parse report data for a given station\n \"\"\"\n # Conditional defaults\n cache = self.cache if cache is None else cache\n history = self.history if history is None else history\n # Fetch a new parsed report\n location_key = parser.icao or (parser.lat, parser.lon)\n error, code = await self._update_parser(parser, location_key)\n if error:\n return error, code\n # Retrieve report data\n data = self._make_data(parser)\n # Update the cache with the new report data\n coros = []\n if cache:\n coros.append(app.cache.update(self.report_type, location_key, data))\n if history:\n coros.append(app.history.add(self.report_type, parser.data))\n if coros:\n await aio.gather(*coros)\n return data, 200\n\n async def _station_cache_or_fetch(\n self,\n station: avwx.Station,\n force_cache: bool = False,\n use_cache: bool = None,\n add_history: bool = None,\n ):\n \"\"\"\n For a station, fetch data from the cache or return a new report\n \"\"\"\n data, code = None, 200\n cache = await app.cache.get(self.report_type, station.icao, force=force_cache)\n if cache is None or app.cache.has_expired(\n cache.get(\"timestamp\"), self.report_type\n ):\n data, code = await self._new_report(\n self.parser(station.icao), use_cache, add_history\n )\n else:\n data = cache\n return data, cache, code\n\n def _format_report(self, data: {str: object}, options: [str]) -> {str: object}:\n \"\"\"\n Formats the report/cache data into the expected response format\n \"\"\"\n ret = data.get(\"data\", data)\n if isinstance(ret, list):\n return {\"data\": [self._format_report(item, options) for item in ret]}\n for opt in self.option_keys:\n if opt in options:\n if opt == \"summary\" and self.report_type == \"taf\":\n for i in range(len(ret[\"forecast\"])):\n ret[\"forecast\"][i][\"summary\"] = data[\"summary\"][i]\n else:\n ret[opt] = data.get(opt)\n return ret\n\n async def fetch_report(\n self, station: avwx.Station, opts: [str], nofail: bool = False\n ) -> (dict, int):\n \"\"\"\n Returns weather data for the given report type, station, and options\n Also returns the appropriate HTTP response code\n\n Uses a cache to store recent report hashes which are (at most) two minutes old\n If nofail and a new report can't be fetched, the cache will be returned with a warning\n \"\"\"\n if not station.sends_reports:\n return {\"error\": ERRORS[6].format(station.icao)}, 204\n # Fetch an existing and up-to-date cache or make a new report\n try:\n data, cache, code = await self._station_cache_or_fetch(\n station, force_cache=True\n )\n return self._post_handle(data, code, cache, station, opts, nofail)\n except Exception as exc:\n print(\"Unknown Parsing Error\", exc)\n rollbar.report_exc_info(extra_data={\"state\": \"outer fetch\"})\n return {\"error\": ERRORS[1].format(self.report_type)}, 500\n\n def _post_handle(\n self,\n data: dict,\n code: int,\n cache: dict,\n station: avwx.Station,\n opts: [str],\n nofail: bool,\n ) -> (dict, int):\n \"\"\"\n Performs post parser update operations\n \"\"\"\n resp = {\"meta\": self._make_meta()}\n if \"timestamp\" in data:\n resp[\"meta\"][\"cache-timestamp\"] = data[\"timestamp\"]\n # Handle errors according to nofail argument\n if code != 200:\n if nofail:\n if cache is None:\n resp[\n \"error\"\n ] = \"No report or cache was found for the requested station\"\n return resp, 204\n data, code = cache, 200\n resp[\"meta\"].update(\n {\n \"cache-timestamp\": data[\"timestamp\"],\n \"warning\": \"Unable to fetch report. This cached data might be out of date. To return an error instead, set ?onfail=error\",\n }\n )\n else:\n resp.update(data)\n return resp, code\n # Format the return data\n resp.update(self._format_report(data, opts))\n # Add station info if requested\n if station and \"info\" in opts:\n resp[\"info\"] = asdict(station)\n return resp, code\n\n def _parse_given(self, report: str, opts: [str]) -> (dict, int):\n \"\"\"\n Attempts to parse a given report supplied by the user\n \"\"\"\n if len(report) < 4 or \"{\" in report or \"[\" in report:\n return ({\"error\": \"Could not find station at beginning of report\"}, 400)\n try:\n station = avwx.Station.from_icao(report[:4])\n except avwx.exceptions.BadStation:\n return {\"error\": ERRORS[2].format(station)}, 400\n report = report.replace(\"\\\\n\", \"\\n\")\n parser = self.parser.from_report(report)\n resp = asdict(parser.data)\n if \"translate\" in opts:\n resp[\"translations\"] = asdict(parser.translations)\n if \"summary\" in opts:\n if self.report_type == \"taf\":\n for i in range(len(parser.translations[\"forecast\"])):\n resp[\"forecast\"][i][\"summary\"] = parser.summary[i]\n else:\n resp[\"summary\"] = parser.summary\n if \"speech\" in opts:\n resp[\"speech\"] = parser.speech\n # Add station info if requested\n if \"info\" in opts:\n resp[\"info\"] = asdict(station)\n return resp, 200\n\n def parse_given(self, report: str, opts: [str]) -> (dict, int):\n \"\"\"\n Attempts to parse a given report supplied by the user\n \"\"\"\n try:\n data, code = self._parse_given(report, opts)\n data[\"meta\"] = self._make_meta()\n except Exception as exc:\n print(\"Unknown Parsing Error\", exc)\n rollbar.report_exc_info(extra_data={\"state\": \"given\", \"raw\": report})\n data, code = {\"error\": ERRORS[1].format(self.report_type)}, 500\n return data, code\n","sub_path":"avwx_api/handle/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":11854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"65614596","text":"from pg2avro import get_avro_schema, ColumnMapping, get_avro_row_dict\nfrom sqlalchemy import (\n Column,\n BIGINT,\n BOOLEAN,\n CHAR,\n DATE,\n INTEGER,\n NUMERIC,\n SMALLINT,\n TEXT,\n VARCHAR,\n TIME,\n)\nfrom sqlalchemy.dialects.postgresql import (\n ARRAY,\n INTERVAL,\n TIMESTAMP,\n ENUM,\n UUID,\n JSONB,\n JSON,\n DOUBLE_PRECISION,\n)\n\nfrom typing import Optional\n\n\ndef test_get_avro_schema_sqlalchemy():\n \"\"\"\n Test sqlalchemy integration.\n\n TODO: Cover all sql/postgres types.\n \"\"\"\n\n custom_enum_type = (\"value_1\", \"value_2\")\n\n columns = [\n Column(SMALLINT, name=\"smallint\", nullable=False),\n Column(BIGINT, name=\"bigint\", nullable=False),\n Column(INTEGER, name=\"integer\", nullable=False),\n Column(NUMERIC(10, 2), name=\"numeric\", nullable=False),\n Column(NUMERIC(10, 10), name=\"numeric_to_double\", nullable=False),\n Column(NUMERIC, name=\"numeric_defaults\", nullable=False),\n Column(NUMERIC, name=\"numeric_nullable\", nullable=True),\n Column(DOUBLE_PRECISION, name=\"double_precision\", nullable=False),\n Column(BOOLEAN, name=\"bool\", nullable=False),\n Column(DATE, name=\"date\", nullable=False),\n Column(TIME, name=\"time\", nullable=False),\n Column(TIMESTAMP, name=\"timestamp\", nullable=False),\n Column(CHAR, name=\"char\", nullable=False),\n Column(TEXT, name=\"text\", nullable=True),\n Column(VARCHAR(255), primary_key=True, name=\"varchar\", nullable=False),\n Column(ARRAY(VARCHAR), name=\"array\", nullable=False),\n Column(INTERVAL, name=\"interval\", nullable=False),\n Column(ENUM(name=\"some_enum\", *custom_enum_type), name=\"enum\", nullable=False),\n Column(UUID, name=\"uuid\", nullable=False),\n Column(JSONB, name=\"jsonb\", nullable=False),\n Column(JSON, name=\"json\", nullable=False),\n ]\n\n table_name = \"test_table\"\n namespace = \"test_namespace\"\n\n expected = {\n \"name\": table_name,\n \"namespace\": namespace,\n \"type\": \"record\",\n \"fields\": [\n {\"name\": \"smallint\", \"type\": \"int\"},\n {\"name\": \"bigint\", \"type\": \"long\"},\n {\"name\": \"integer\", \"type\": \"int\"},\n {\n \"name\": \"numeric\",\n \"type\": {\n \"logicalType\": \"decimal\",\n \"type\": \"bytes\",\n \"precision\": 10,\n \"scale\": 2,\n },\n },\n {\"name\": \"numeric_to_double\", \"type\": \"double\"},\n {\n \"name\": \"numeric_defaults\",\n \"type\": {\n \"logicalType\": \"decimal\",\n \"type\": \"bytes\",\n \"precision\": 38,\n \"scale\": 9,\n },\n },\n {\n \"name\": \"numeric_nullable\",\n \"type\": [\n \"null\",\n {\n \"logicalType\": \"decimal\",\n \"type\": \"bytes\",\n \"precision\": 38,\n \"scale\": 9,\n },\n ],\n },\n {\"name\": \"double_precision\", \"type\": \"double\"},\n {\"name\": \"bool\", \"type\": \"boolean\"},\n {\"name\": \"date\", \"type\": {\"logicalType\": \"date\", \"type\": \"int\"}},\n {\n \"name\": \"time\",\n \"type\": {\"logicalType\": \"timestamp-millis\", \"type\": \"int\"},\n },\n {\n \"name\": \"timestamp\",\n \"type\": {\"logicalType\": \"timestamp-millis\", \"type\": \"long\"},\n },\n {\"name\": \"char\", \"type\": \"string\"},\n {\"name\": \"text\", \"type\": [\"null\", \"string\"]},\n {\"name\": \"varchar\", \"type\": \"string\"},\n {\"name\": \"array\", \"type\": {\"items\": \"string\", \"type\": \"array\"}},\n {\"name\": \"interval\", \"type\": \"string\"},\n {\"name\": \"enum\", \"type\": \"string\"},\n {\"name\": \"uuid\", \"type\": \"string\"},\n {\"name\": \"jsonb\", \"type\": \"string\"},\n {\"name\": \"json\", \"type\": \"string\"},\n ],\n }\n\n actual = get_avro_schema(table_name, namespace, columns)\n\n assert expected == actual\n\n\ndef test_get_avro_schema_custom_mapping():\n \"\"\"\n Test custom integration using mapping class.\n\n TODO: Cover all sql/postgres types.\n \"\"\"\n\n class Col:\n def __init__(\n self,\n n: str,\n un: str,\n nul: bool,\n np: Optional[int] = None,\n ns: Optional[int] = None,\n ):\n self.n = n\n self.un = un\n self.nul = nul\n self.np = np\n self.ns = ns\n\n columns = [\n Col(n=\"smallint\", un=\"int2\", nul=False),\n Col(n=\"bigint\", un=\"int8\", nul=False),\n Col(n=\"integer\", un=\"int4\", nul=False),\n Col(n=\"numeric\", un=\"numeric\", nul=False, np=3, ns=7),\n Col(n=\"numeric_to_double\", un=\"numeric\", nul=False, np=10, ns=10),\n Col(n=\"numeric_defaults\", un=\"numeric\", nul=False),\n Col(n=\"numeric_nullable\", un=\"numeric\", nul=True),\n Col(n=\"double_precision\", un=\"float8\", nul=False),\n Col(n=\"real\", un=\"float4\", nul=False),\n Col(n=\"bool\", un=\"bool\", nul=False),\n Col(n=\"char\", un=\"char\", nul=False),\n Col(n=\"bpchar\", un=\"bpchar\", nul=False),\n Col(n=\"varchar\", un=\"varchar\", nul=False),\n Col(n=\"array\", un=\"_varchar\", nul=False),\n Col(n=\"array_n\", un=\"_varchar\", nul=True),\n Col(n=\"date\", un=\"date\", nul=False),\n Col(n=\"time\", un=\"time\", nul=False),\n Col(n=\"timestamp\", un=\"timestamp\", nul=False),\n Col(n=\"enum\", un=\"custom_type\", nul=False),\n Col(n=\"uuid\", un=\"uuid\", nul=False),\n Col(n=\"json\", un=\"json\", nul=False),\n Col(n=\"jsonb\", un=\"jsonb\", nul=False),\n ]\n\n table_name = \"test_table\"\n namespace = \"test_namespace\"\n\n expected = {\n \"name\": table_name,\n \"namespace\": namespace,\n \"type\": \"record\",\n \"fields\": [\n {\"name\": \"smallint\", \"type\": \"int\"},\n {\"name\": \"bigint\", \"type\": \"long\"},\n {\"name\": \"integer\", \"type\": \"int\"},\n {\n \"name\": \"numeric\",\n \"type\": {\n \"logicalType\": \"decimal\",\n \"type\": \"bytes\",\n \"precision\": 3,\n \"scale\": 7,\n },\n },\n {\"name\": \"numeric_to_double\", \"type\": \"double\"},\n {\n \"name\": \"numeric_defaults\",\n \"type\": {\n \"logicalType\": \"decimal\",\n \"type\": \"bytes\",\n \"precision\": 38,\n \"scale\": 9,\n },\n },\n {\n \"name\": \"numeric_nullable\",\n \"type\": [\n \"null\",\n {\n \"logicalType\": \"decimal\",\n \"type\": \"bytes\",\n \"precision\": 38,\n \"scale\": 9,\n },\n ],\n },\n {\"name\": \"double_precision\", \"type\": \"double\"},\n {\"name\": \"real\", \"type\": \"float\"},\n {\"name\": \"bool\", \"type\": \"boolean\"},\n {\"name\": \"char\", \"type\": \"string\"},\n {\"name\": \"bpchar\", \"type\": \"string\"},\n {\"name\": \"varchar\", \"type\": \"string\"},\n {\"name\": \"array\", \"type\": {\"items\": \"string\", \"type\": \"array\"}},\n {\"name\": \"array_n\", \"type\": [\"null\", {\"items\": \"string\", \"type\": \"array\"}]},\n {\"name\": \"date\", \"type\": {\"logicalType\": \"date\", \"type\": \"int\"}},\n {\n \"name\": \"time\",\n \"type\": {\"logicalType\": \"timestamp-millis\", \"type\": \"int\"},\n },\n {\n \"name\": \"timestamp\",\n \"type\": {\"logicalType\": \"timestamp-millis\", \"type\": \"long\"},\n },\n {\"name\": \"enum\", \"type\": \"string\"},\n {\"name\": \"uuid\", \"type\": \"string\"},\n {\"name\": \"json\", \"type\": \"string\"},\n {\"name\": \"jsonb\", \"type\": \"string\"},\n ],\n }\n\n actual = get_avro_schema(\n table_name,\n namespace,\n columns,\n ColumnMapping(\n name=\"n\",\n type=\"un\",\n nullable=\"nul\",\n numeric_precision=\"np\",\n numeric_scale=\"ns\",\n ),\n )\n\n assert expected == actual\n\n\ndef test_mapping_overrides():\n \"\"\"\n Test mapping overrides\n \"\"\"\n\n from pg2avro.pg2avro import Column\n\n table_name = \"test_table\"\n namespace = \"test_namespace\"\n\n columns = [\n Column(name=\"int_to_string\", type=\"int\"),\n Column(name=\"string_to_numeric\", type=\"string\"),\n Column(name=\"not_overriden\", type=\"int\"),\n Column(name=\"numeric_to_float\", type=\"numeric\"),\n Column(name=\"array_to_string\", type=\"_varchar\"),\n Column(name=\"string_to_array\", type=\"varchar\"),\n ]\n overrides = {\n \"int_to_string\": {\"pg_type\": \"string\", \"python_type\": str},\n \"string_to_numeric\": {\"pg_type\": \"numeric\", \"python_type\": float},\n \"not_matching_override_name\": {\"pg_type\": \"int\", \"python_type\": int},\n \"numeric_to_float\": {\"pg_type\": \"float8\", \"python_type\": float},\n \"array_to_string\": {\"pg_type\": \"string\", \"python_type\": str},\n \"string_to_array\": {\"pg_type\": \"_string\", \"python_type\": list},\n }\n\n expected_schema = {\n \"name\": table_name,\n \"namespace\": namespace,\n \"type\": \"record\",\n \"fields\": [\n {\"name\": \"int_to_string\", \"type\": [\"null\", \"string\"]},\n {\n \"name\": \"string_to_numeric\",\n \"type\": [\n \"null\",\n {\n \"type\": \"bytes\",\n \"logicalType\": \"decimal\",\n \"precision\": 38,\n \"scale\": 9,\n },\n ],\n },\n {\"name\": \"not_overriden\", \"type\": [\"null\", \"int\"]},\n {\"name\": \"numeric_to_float\", \"type\": [\"null\", \"double\"]},\n {\"name\": \"array_to_string\", \"type\": [\"null\", \"string\"]},\n {\n \"name\": \"string_to_array\",\n \"type\": [\"null\", {\"type\": \"array\", \"items\": \"string\"}],\n },\n ],\n }\n\n schema = get_avro_schema(\n table_name, namespace, columns, mapping_overrides=overrides\n )\n\n assert expected_schema == schema\n\n # Now data\n rows_data = [\n {\n \"int_to_string\": 1,\n \"string_to_numeric\": \"2.0\",\n \"not_overriden\": 3,\n \"numeric_to_float\": 0.12345678910,\n \"array_to_string\": [1, 2, \"a\", \"b\"],\n \"string_to_array\": \"asd\",\n },\n {\n \"int_to_string\": None,\n \"string_to_numeric\": None,\n \"not_overriden\": None,\n \"numeric_to_float\": None,\n \"array_to_string\": None,\n \"string_to_array\": None,\n },\n ]\n expected = [\n {\n \"int_to_string\": \"1\",\n \"string_to_numeric\": 2.0,\n \"not_overriden\": 3,\n \"numeric_to_float\": 0.12345678910,\n \"array_to_string\": \"[1, 2, 'a', 'b']\",\n \"string_to_array\": [\"a\", \"s\", \"d\"],\n },\n {\n \"int_to_string\": None,\n \"string_to_numeric\": None,\n \"not_overriden\": None,\n \"numeric_to_float\": None,\n \"array_to_string\": None,\n \"string_to_array\": None,\n },\n ]\n\n actual = [get_avro_row_dict(r, schema, overrides) for r in rows_data]\n\n assert expected == actual\n","sub_path":"tests/test_schema_types.py","file_name":"test_schema_types.py","file_ext":"py","file_size_in_byte":11721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"112045054","text":"from __future__ import absolute_import,unicode_literals\n\nimport io\nimport os\nimport sys\nimport json\nimport time\nimport types\nimport msgpack\nimport functools\nimport itertools\nimport threading\nimport traceback\n\nfrom binascii import hexlify\n\nimport synapse.exc as s_exc\n\nfrom synapse.exc import *\nfrom synapse.compat import enbase64, debase64, canstor\n\nclass NoValu:pass\nnovalu = NoValu()\n\ndef now():\n return int( time.time() * 1000 )\n\ndef guid():\n return hexlify(os.urandom(16)).decode('utf8')\n\ndef tufo(typ,**kwargs):\n return (typ,kwargs)\n\ndef msgenpack(obj):\n return msgpack.dumps(obj, use_bin_type=True, encoding='utf8')\n\ndef msgunpack(byts):\n return msgpack.loads(byts, use_list=False, encoding='utf8')\n\ndef msgpackfd(fd):\n unpk = msgpack.Unpacker(fd, use_list=False, encoding='utf8')\n for mesg in unpk:\n yield mesg\n\ndef vertup(vstr):\n '''\n Convert a version string to a tuple.\n\n Example:\n\n ver = vertup('1.3.30')\n\n '''\n return tuple([ int(x) for x in vstr.split('.') ])\n\ndef genpath(*paths):\n path = os.path.join(*paths)\n path = os.path.expanduser(path)\n path = os.path.expandvars(path)\n return os.path.abspath(path)\n\ndef reqpath(*paths):\n path = genpath(*paths)\n if not os.path.isfile(path):\n raise NoSuchFile(path)\n return path\n\ndef reqfile(*paths, **opts):\n path = genpath(*paths)\n if not os.path.isfile(path):\n raise NoSuchFile(path)\n opts.setdefault('mode','rb')\n return io.open(path,**opts)\n\ndef reqlines(*paths, **opts):\n '''\n Open a file and yield lines of text.\n\n Example:\n\n for line in reqlines('foo.txt'):\n dostuff(line)\n\n NOTE: This API is used as a performance optimization\n over the standard fd line iteration mechanism.\n '''\n opts.setdefault('mode','r')\n opts.setdefault('encoding','utf8')\n\n rem = None\n with reqfile(*paths,**opts) as fd:\n\n bufr = fd.read(10000000)\n while bufr:\n\n if rem != None:\n bufr = rem + bufr\n\n lines = bufr.split('\\n')\n rem = lines[-1]\n\n for line in lines[:-1]:\n yield line.strip()\n\n bufr = fd.read(10000000)\n\n if rem != None:\n bufr = rem + bufr\n\ndef reqbytes(*paths):\n with reqfile(*paths) as fd:\n return fd.read()\n\ndef genfile(*paths):\n '''\n Create or open ( for read/write ) a file path join.\n '''\n path = genpath(*paths)\n gendir( os.path.dirname(path) )\n if not os.path.isfile(path):\n return io.open(path,'w+b')\n return io.open(path,'r+b')\n\ndef gendir(*paths,**opts):\n mode = opts.get('mode',0o700)\n path = genpath(*paths)\n if not os.path.isdir(path):\n os.makedirs(path,mode=mode)\n return path\n\ndef reqdir(*paths):\n path = genpath(*paths)\n if not os.path.isdir(path):\n raise NoSuchDir(path=path)\n return path\n\ndef jsload(*paths):\n with genfile(*paths) as fd:\n byts = fd.read()\n if not byts:\n return None\n\n return json.loads(byts.decode('utf8'))\n\ndef gentask(func,*args,**kwargs):\n return (func,args,kwargs)\n\ndef jssave(js,*paths):\n path = genpath(*paths)\n with io.open(path,'wb') as fd:\n fd.write( json.dumps(js).encode('utf8') )\n\ndef verstr(vtup):\n '''\n Convert a version tuple to a string.\n '''\n return '.'.join([ str(v) for v in vtup ])\n\ndef excinfo(e):\n '''\n Populate err,errmsg,errtrace info from exc.\n '''\n tb = sys.exc_info()[2]\n path,line,name,sorc = traceback.extract_tb(tb)[-1]\n ret = {\n 'err':e.__class__.__name__,\n 'errmsg':str(e),\n 'errfile':path,\n 'errline':line,\n }\n\n if isinstance(e,SynErr):\n ret['errinfo'] = e.errinfo\n\n return ret\n\ndef synerr(excname,**info):\n '''\n Return a SynErr exception. If the given name\n is not known, fall back on the base class.\n '''\n info['excname'] = excname\n cls = getattr(s_exc,excname,s_exc.SynErr)\n return cls(**info)\n\ndef errinfo(name,mesg):\n return {\n 'err':name,\n 'errmsg':mesg,\n }\n\ndef chunks(item,size):\n '''\n Divide an iterable into chunks.\n '''\n # use islice if it's a generator\n if type(item) == types.GeneratorType:\n\n while True:\n\n chunk = tuple(itertools.islice(item,size))\n if not chunk:\n return\n\n yield chunk\n\n # otherwise, use normal slicing\n\n off = 0\n\n while True:\n\n chunk = item[off:off+size]\n if not chunk:\n return\n\n yield chunk\n\n off += size\n\ndef reqStorDict(x):\n '''\n Raises BadStorValu if any value in the dict is not compatible\n with being stored in a cortex.\n '''\n for k,v in x.items():\n if not canstor(v):\n raise BadStorValu(name=k,valu=v)\n\nclass TufoApi:\n '''\n TufoApi is a mixin class providing get/set APIs around a\n tufo being cached in memory.\n '''\n\n def __init__(self, core, myfo):\n self.core = core\n self.myfo = myfo\n\n def get(self, prop):\n '''\n Retrieve a property from the tufo.\n\n Example:\n\n foo = tapi.get('foo')\n\n '''\n form = self.myfo[1].get('tufo:form')\n return self.myfo[1].get('%s:%s' % (form,prop))\n\n def set(self, prop, valu):\n '''\n Set a property in the tufo ( and persist change to core ).\n\n Example:\n\n tapi.set('foo', 20)\n\n '''\n self.core.setTufoProp(self.myfo, prop, valu)\n\ndef firethread(f):\n '''\n A decorator for making a function fire a thread.\n '''\n @functools.wraps(f)\n def callmeth(*args,**kwargs):\n thr = worker(f,*args,**kwargs)\n return thr\n return callmeth\n\ndef worker(meth, *args, **kwargs):\n thr = threading.Thread(target=meth,args=args,kwargs=kwargs)\n thr.setDaemon(True)\n thr.start()\n return thr\n","sub_path":"synapse/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"196441336","text":"# CDDL fragment MACed Messages with Implicit Key\n#\n# COSE_Mac = [\n# Headers,\n# payload : bstr / nil,\n# tag : bstr\n# ]\n#\n\nfrom typing import Optional\n\nimport cbor2\n\nfrom cose import CoseMessage\nfrom cose.messages import cosemessage, maccommon\nfrom cose.attributes.algorithms import CoseAlgorithms\nfrom cose.keys.symmetric import SymmetricKey\n\n\n@cosemessage.CoseMessage.record_cbor_tag(17)\nclass Mac0Message(maccommon.MacCommon):\n context = \"MAC0\"\n cbor_tag = 17\n\n @classmethod\n def from_cose_obj(cls, cose_obj: list) -> 'Mac0Message':\n msg = super().from_cose_obj(cose_obj)\n msg.auth_tag = cose_obj.pop(0)\n\n return msg\n\n def __init__(self,\n phdr: Optional[dict] = None,\n uhdr: Optional[dict] = None,\n payload: bytes = b'',\n external_aad: bytes = b''):\n if phdr is None:\n phdr = {}\n if uhdr is None:\n uhdr = {}\n\n super().__init__(phdr, uhdr, payload, external_aad)\n\n def encode(self,\n key: SymmetricKey,\n alg: Optional[CoseAlgorithms] = None,\n tagged: bool = True,\n mac: bool = True) -> bytes:\n \"\"\" Encode and protect the COSE_Mac0 message. \"\"\"\n\n if mac:\n message = [self.encode_phdr(), self.encode_uhdr(), self.payload, self.compute_tag(alg=alg, key=key)]\n else:\n message = [self.encode_phdr(), self.encode_uhdr(), self.payload]\n\n if tagged:\n res = cbor2.dumps(cbor2.CBORTag(self.cbor_tag, message), default=self._special_cbor_encoder)\n else:\n res = cbor2.dumps(message, default=self._special_cbor_encoder)\n\n return res\n\n def __repr__(self) -> str:\n return f''\n","sub_path":"cose/messages/mac0message.py","file_name":"mac0message.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"179467493","text":"import Model\n\n\nclass AI:\n\n far = []\n destination = []\n has_attacked = []\n near = []\n wait = []\n waiting_time = []\n\n def longest_cooldown(self, hero):\n ret = 0\n for ability in hero.abilities:\n if ability.cooldown > ret:\n ret = ability.cooldown\n return ret\n\n def preprocess(self, world):\n print(\"preprocess\")\n mark_far = []\n mark_near = []\n for row in range(world.map.row_num):\n temp_far = []\n temp_near = []\n for col in range(world.map.column_num):\n temp_far.append(False)\n temp_near.append(False)\n mark_far.append(temp_far)\n mark_near.append(temp_near)\n for a in range(4):\n for objective_cell in world.map.objective_zone:\n if len(self.far) == a and not mark_far[objective_cell.row][objective_cell.column]:\n self.far.append(objective_cell)\n if len(self.near) == a and not mark_near[objective_cell.row][objective_cell.column]:\n self.near.append(objective_cell)\n if len(self.near) > a and len(self.far) > a:\n break\n source = world.map.my_respawn_zone[a]\n for objective_cell in world.map.objective_zone:\n new_len = len(world.get_path_move_directions(start_cell=source, end_cell=objective_cell))\n far_len = len(world.get_path_move_directions(start_cell=source, end_cell=self.far[a]))\n near_len = len(world.get_path_move_directions(start_cell=source, end_cell=self.near[a]))\n if new_len > far_len:\n if not mark_far[objective_cell.row][objective_cell.column]:\n self.far[a] = objective_cell\n elif new_len < near_len:\n if not mark_near[objective_cell.row][objective_cell.column]:\n self.near[a] = objective_cell\n mark_far[self.far[a].row][self.far[a].column] = True\n mark_near[self.near[a].row][self.near[a].column] = True\n self.destination.append(self.far[a])\n\n def pick(self, world):\n print(\"pick\")\n world.pick_hero(Model.HeroName.BLASTER)\n\n def next_cell(self, cur_cell, dir):\n if dir == Model.Direction.UP:\n cur_cell.row += 1\n elif dir == Model.Direction.DOWN:\n cur_cell.row -= 1\n elif dir == Model.Direction.LEFT:\n cur_cell.column -= 1\n else:\n cur_cell.column += 1\n\n def move(self, world):\n print(\"move\")\n for a in range(4):\n if self.destination[a] == world.my_heroes[a].current_cell:\n if self.destination[a] == self.far[a]:\n self.destination[a] = self.near[a]\n else:\n self.destination[a] = self.far[a]\n for a in range(4):\n hero_to_move = world.my_heroes[a]\n destination = self.destination[a]\n if hero_to_move.current_hp <= 0 or world.ap < hero_to_move.move_ap_cost or destination == hero_to_move.current_cell:\n continue\n start = hero_to_move.current_cell\n world.move_hero(hero=hero_to_move, direction=world.get_path_move_directions(start_cell=start, end_cell=destination)[0])\n\n def ok(self, world, cell):\n for hero in world.my_heroes:\n if cell == hero.current_cell:\n return False\n return True\n\n def can_hit(self, world, hero):\n first_opp_hero_cell = world.opp_heroes[0].current_cell\n if first_opp_hero_cell.column == -1 and first_opp_hero_cell.row == -1:\n return False\n for offensive_ability in hero.offensive_abilities:\n if not offensive_ability.is_ready or not world.ap >= offensive_ability.ap_cost:\n continue\n hero_cell = hero.current_cell\n for opp_hero in world.opp_heroes:\n if world.manhattan_distance(start_cell=world.get_impact_cell(ability=offensive_ability, start_cell=hero_cell, target_cell=opp_hero.current_cell), end_cell=hero_cell) <= (offensive_ability.range + offensive_ability.area_of_effect):\n return True\n return False\n\n def action(self, world):\n print(\"action\")\n for a in range(4):\n if self.destination[a] == world.my_heroes[a].current_cell:\n if self.destination[a] == self.far[a]:\n self.destination[a] = self.near[a]\n else:\n self.destination[a] = self.far[a]\n for a in range(4):\n my_hero = world.my_heroes[a]\n if my_hero.current_hp <= 0:\n continue\n destination = self.destination[a]\n dodge = my_hero.dodge_abilities[0]\n if my_hero.current_cell != destination and dodge.is_ready and self.ok(world, world.get_impact_cell(ability=dodge, start_cell=my_hero.current_cell, target_cell=destination)) and world.ap >= dodge.ap_cost:\n world.cast_ability(hero=my_hero, ability=dodge, cell=destination)\n world.ap -= dodge.ap_cost\n else:\n if world.opp_heroes[0].current_cell.column == -1 and world.opp_heroes[0].current_cell.row == -1:\n pass\n else:\n nearest_opp = world.opp_heroes[0]\n my_hero_cell = my_hero.current_cell\n for opp_hero in world.opp_heroes:\n if opp_hero.current_hp <= 0:\n continue\n if world.manhattan_distance(start_cell=my_hero_cell, end_cell=opp_hero.current_cell) < world.manhattan_distance(start_cell=my_hero_cell, end_cell=nearest_opp.current_cell):\n nearest_opp = opp_hero\n if nearest_opp.current_hp > 0:\n offensive_abilities = my_hero.offensive_abilities\n for b in range(len(offensive_abilities) - 1, -1, -1):\n attack = offensive_abilities[b]\n if attack.range < world.manhattan_distance(start_cell=my_hero_cell, end_cell=nearest_opp.current_cell) or not attack.is_ready or world.ap < attack.ap_cost:\n continue\n world.cast_ability(hero=my_hero, ability=attack, cell=nearest_opp.current_cell)\n world.ap -= attack.ap_cost\n","sub_path":"Farthest/AI.py","file_name":"AI.py","file_ext":"py","file_size_in_byte":6518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"87213955","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom apps.dashboard import dictfetchall\nfrom django.db import connection\n\n\ndef obj_to_dict(obj):\n ''' Convert object to dictonary where keys are names of attributes\n and values are values of attributes '''\n return dict((key, value) for key, value in obj.__dict__.iteritems() if not callable(value) and\n not key.startswith('__') and not key.startswith('_sa'))\n\n\ndef top_menu_banner(lang):\n html = ''\n try:\n with connection.cursor() as c:\n c.execute('''SELECT text, text_ru, text_en, link, image FROM banners WHERE active = 1 ORDER BY RAND() LIMIT 1;''')\n banner = dictfetchall(c)[0]\n except:\n banner = None\n\n if banner:\n button_title = u'дивитися умови'\n if lang == 'ru' and banner.get('text_ru'):\n banner['text'] = banner['text_ru']\n button_title = u'Смотреть условия'\n if lang == 'en' and banner.get('text_en'):\n banner['text'] = banner['text_en']\n button_title = u'view details'\n\n html = '

    ' % banner.get('image')\n html += '
    %s
    ' % banner['text']\n html += u'
    %s' % (banner.get('link'), button_title)\n html += '
    '\n return html\n","sub_path":"apps/sliders/templatetags/banners.py","file_name":"banners.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"214211996","text":"import os, string, secrets, sys, ast\n\nfrom flask import (\n\tFlask, render_template, url_for, session, redirect, request,\n\tflash,\n)\nfrom finnhub import Client as make_client\nfrom flaskr import algorithm\n\"\"\"\nElvis' Finnhub API keys\nSandbox API Key: sandbox_c0bfrg748v6to0roveg0\nRegular API Key: c0bfrg748v6to0rovefg\n\nThere are limits! See documentation:\nhttps://finnhub.io/docs/api\n\"\"\"\n\ndef create_app(test_config=None):\n\t\"\"\"\n\tApplication factory function to set up the Flask application. Defines \n\tthe endpoints/routes for the application.\n\n\t#### Endpoints\n\n\t##### `@app.route('/', methods=['GET', 'POST'])`\n\tReturns index/home page with fields for updating stock portfolio.\n\t- **GET:** Returns index page.\n\t- **POST:** Updates stock portfolio in `session` with form input then renders index page. \n\tReturns an error if stock symbol is invalid or the number of shares is not a positive integer.\n\n\t##### `@app.route('/about')`\n\tReturns About page.\n\n\t##### `@app.route('/compare/', methods=['GET', 'POST'])`\n\tReturns compare page with input fields for UIDs of profiles to compare and computes compatability.\n\t- **GET:** Returns compare page. If `code` is not ``, then the first input field\n\twill have its initial value set to `code`.\n\t- **POST:** Fetches profiles for the input UIDs from the SQLite database, computes the \n\tcompatability between the profiles, stores this in `session`, then redirects to the \n\tcompatability page. Returns an error if both input IDs are the same or a profile does not \n\texist for either UID in the SQLite database.\n\n\t##### `@app.route('/results')`\n\tGenerates a profile from stock portfolio stored in `session` and a UID, stores the profile + UID\n\tin the SQLite database, and returns the page displaying this information.\n\n\t- If no stock portfolio exists in `session`, this endpoint redirects to the index page.\n\t- Generating a profile / UID and persisting this information in the database is skipped \n\tif the current stock portfolio in `session` remains unchanged from the last time a profile \n\twas generated.\n\n\t##### `@app.route('/compat')`\n\tReturns page displaying compatability results.\n\n\t##### `@app.route('/remove/')`\n\tRemoves stock symbol `key` from `session` and redirects to index page.\n\n\t\"\"\"\n\n\tapp = Flask(__name__, instance_relative_config=True)\n\tfinnhub_client = make_client(api_key=\"c0bfrg748v6to0rovefg\")\n\n\t# Load config (if it exists) or take a test config\n\tif test_config is None:\n\t\tapp.config.from_mapping(\n\t\t\tSECRET_KEY=os.urandom(24),\n\t\t\tDATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),\n\t\t)\n\telse:\n\t\tapp.config.from_mapping(test_config)\n # Ensure the instance folder exists\n\ttry:\n\t\tos.makedirs(app.instance_path)\n\texcept OSError:\n\t\tpass\n\n\t# Initialize db\n\tfrom flaskr import db\n\tdb.init_app(app)\n\n\t# Fix browser caching for css\n\t@app.context_processor\n\tdef override_url_for():\n\t\treturn dict(url_for=dated_url_for)\n\n\tdef dated_url_for(endpoint, **values):\n\t\tif endpoint == 'static':\n\t\t\tfilename = values.get('filename', None)\n\t\t\tif filename:\n\t\t\t\tfile_path = os.path.join(app.root_path,\n\t\t\t\t\t\t\t\t\t endpoint, filename)\n\t\t\t\tvalues['q'] = int(os.stat(file_path).st_mtime)\n\t\treturn url_for(endpoint, **values)\n\n\t# Attempts to generate an unused UID within limit number of attempts.\n\t# If all attempts are expended (extremely unlikely to actually happen with default of 5),\n\t# the last generated UID is returned.\n\tdef generate_uid(limit=5):\n\t\tuid = \"\"\n\t\tattempts = 0\n\t\twhile attempts < limit:\n\t\t\tuid = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(10))\n\t\t\tif db.get_profile(uid) == None:\n\t\t\t\tbreak\n\t\t\tattempts += 1\n\t\treturn uid\n\n\t# Home page\n\t@app.route('/', methods=['GET', 'POST'])\n\tdef index():\n\t\tif request.method == 'POST':\n\t\t\t# DONE: input validation\n\t\t\tstock_symbol = request.form['stock'].upper()\n\t\t\tvolume = request.form['volume']\n\t\t\tsymbol_quote = finnhub_client.quote(stock_symbol)\n\t\t\tetf_country = finnhub_client.etfs_country_exp(stock_symbol)\n\t\t\terror = None\n\t\t\tif not volume.isdigit():\n\t\t\t\terror = \"Number of Shares must be a positive integer\"\n\t\t\telif int(volume) < 1:\n\t\t\t\terror = \"Number of Shares must be a positive integer\"\n\t\t\telif int(volume) > 1e20:\n\t\t\t\terror = \"Number of Shares too large\"\n\t\t\telif symbol_quote['c'] == 0:\n\t\t\t\terror = \"Invalid stock symbol: {}\".format(stock_symbol)\n\t\t\telif etf_country['symbol'] != '':\n\t\t\t\terror = \"Cannot process ETF: {}\".format(stock_symbol)\n\n\t\t\t# TODO: Send form results to DB, fetch all added stocks and display them\n\t\t\t# Code below uses Flask session to store data which can be moved to\n\t\t\t# DB later.\n\t\t\tif error is None:\n\t\t\t\tsession['updated'] = True\n\t\t\t\tif 'stock_dict' in session:\n\t\t\t\t\t(session['stock_dict'])[stock_symbol] = volume\n\t\t\t\t\tsession.modified = True\n\t\t\t\telse:\n\t\t\t\t\tsession['stock_dict'] = {stock_symbol: volume}\n\t\t\t\treturn render_template('index.html', stock_dict=session['stock_dict'])\n\n\t\t\tflash(error)\n\t\t\tif 'stock_dict' in session and session['stock_dict']:\n\t\t\t\treturn render_template('index.html', stock_dict=session['stock_dict'])\n\t\t\treturn render_template('index.html', stock_dict=None)\n\t\telse:\n\t\t\tif 'stock_dict' in session and session['stock_dict']:\n\t\t\t\treturn render_template('index.html', stock_dict=session['stock_dict'])\n\t\t\treturn render_template('index.html', stock_dict=None)\n\n\t# About page\n\t@app.route('/about')\n\tdef about():\n\t\treturn render_template('about.html')\n\n\t# Compare page\n\t@app.route('/compare/', methods=['GET', 'POST'])\n\tdef compare(code):\n\t\tif request.method == 'POST':\n\t\t\tuid1 = request.form['person1']\n\t\t\tuid2 = request.form['person2']\n\t\t\tperson1 = db.get_profile(uid1)\n\t\t\tperson2 = db.get_profile(uid2)\n\t\t\terror = None\n\n\t\t\tif uid1 == uid2:\n\t\t\t\terror = \"IDs cannot be the same!\"\n\t\t\telif person1==None:\n\t\t\t\terror = \"Invalid ID for first person\"\n\t\t\telif person2==None:\n\t\t\t\terror = \"Invalid ID for second person\"\n\n\t\t\tif error is None:\n\t\t\t\t# Convert db.get_profile string to dict\n\t\t\t\tp1 = ast.literal_eval(person1['profile']) # May still need sanitization\n\t\t\t\tp2 = ast.literal_eval(person2['profile'])\n\n\t\t\t\tsession['compatPercent'] = algorithm.compare_profiles(p1, p2)\n\t\t\t\tprint(session['compatPercent'])\n\t\t\t\tprint(\"Compatibility Percentage: \" + str(session['compatPercent']['COMPAT']), file=sys.stderr)\n\n\t\t\t\treturn redirect(url_for('compat'))\n\t\t\telse:\n\t\t\t\tflash(error)\n\t\t\t\treturn render_template('compare.html', code=\"\")\n\t\telse:\n\t\t\tif code == '':\n\t\t\t\treturn render_template('compare.html', code=\"\")\n\t\t\telse:\n\t\t\t\treturn render_template('compare.html', code=code)\n\n\t# Present_id page (generates session id or code)\n\t@app.route('/results')\n\tdef results():\n\t\tperson = {}\n\t\tif not 'stock_dict' in session:\n\t\t\treturn redirect(url_for('index'))\n\t\tif session['updated']:\n\t\t\tperson = algorithm.generate_profile(session['stock_dict'], finnhub_client)\n\t\t\tsession['person'] = person\n\n\t\t# If code has already been generated and the input portfolio is unchanged,\n\t\t# skip code generation and persisting to db\n\t\tif 'code' in session and not session['updated']:\n\t\t\treturn render_template('results.html', code=session['code'], warning=True, person=session['person'])\n\t\telse:\n\n\t\t\t# Generates a 10 character random string\n\t\t\tcode = generate_uid()\n\t\t\tsession['code'] = code\n\n\t\t\tdb.create_profile(code, person)\n\n\t\t\t# Person sends link to partner\n\t\t\tprint(session)\n\t\t\tsession['updated'] = False\n\t\t\treturn render_template('results.html', code=code, person=person)\n\n\t@app.route('/compat')\n\tdef compat():\n\t\tresults = session['compatPercent']\n\t\treturn render_template('compat.html', results=results)\n\n\t# Remove stock symbol from table\n\t@app.route('/remove/')\n\tdef remove(key):\n\t\tif 'stock_dict' in session:\n\t\t\tsession['stock_dict'].pop(key, None)\n\t\t\tsession['updated'] = True\n\t\t\tsession.modified = True\n\t\treturn redirect(url_for('index'))\n\n\treturn app\n","sub_path":"flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"323452944","text":"import datetime\r\nimport hashlib\r\n\r\nimport redis\r\n\r\nfrom lhwms.settings import REDIS_HOST\r\nfrom lhwms.settings import REDIS_PORT\r\n\r\n'''\r\n==========================================================\r\nredis连接池,redis key值生成,用于数据缓存 和数据分页key值\r\n==========================================================\r\n'''\r\n# 单例连接池对象, 通过模块导入,第一次会生成pyc文件,第二次导入直接引用pyc文件\r\n# redis用户查询条件库 连接池\r\npool_terms = redis.ConnectionPool(host=REDIS_HOST,\r\n port=REDIS_PORT, db=3,\r\n decode_responses=True)\r\n\r\n# redis用户查询结果 连接池\r\npool_result = redis.ConnectionPool(host=REDIS_HOST,\r\n port=REDIS_PORT, db=4,\r\n decode_responses=True)\r\n\r\n# redis用户导入数据缓存库 连接池\r\npool_import = redis.ConnectionPool(host=REDIS_HOST,\r\n port=REDIS_PORT, db=5,\r\n decode_responses=True)\r\n\r\n\r\ndef get_ufn(request):\r\n \"\"\"生成唯一文件名\"\"\"\r\n tk = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\r\n m = hashlib.md5()\r\n m.update(bytes(tk, encoding='utf8'))\r\n return m.hexdigest()\r\n\r\n\r\ndef get_key(request, model, query_mark):\r\n \"\"\"生成redis中的key值\"\"\"\r\n mname = model.__name__\r\n query_mark = str(query_mark)\r\n return ','.join([mname, query_mark]) # 序列拼接\r\n\r\n\r\ndef clean_querys(request, model, query_mark):\r\n \"\"\"清理用户查询结果和导入数据缓存\"\"\"\r\n rc_key = get_key(request, model, query_mark)\r\n rc_terms = redis.Redis(connection_pool=pool_terms) # redis对象,操作redis\r\n rc_result = redis.Redis(connection_pool=pool_result)\r\n rc_import = redis.Redis(connection_pool=pool_import)\r\n rc_terms.delete(rc_key)\r\n rc_result.delete(rc_key)\r\n rc_import.delete(rc_key)\r\n return True\r\n","sub_path":"lhwms/lhwms/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"608351430","text":"'''\nLists can be merged using the unpack operator (*)\n'''\n\nmy_first_list = [1, 2, 3]\nmy_second_list = [4, 5, 6]\nmy_merged_list = [*my_first_list, *my_second_list]\n\nprint(my_merged_list) # [1, 2, 3, 4, 5, 6]\nprint(*my_merged_list) # 1 2 3 4 5 6","sub_path":"lists_merge_using_unpack.py","file_name":"lists_merge_using_unpack.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"69131030","text":"import logging\n\nfrom basehandler import BaseHandler\nfrom django.utils import simplejson as json\nfrom cacheLib import storeCache\n\nclass SetVisibility(BaseHandler):\n def post(self):\n if self.user:\n info = json.loads(self.request.body)\n self.user.display_type = int(info['visibility'])\n storeCache(self.user, self.user.user_id)\n response_info = {'success': True}\n self.response.out.write(json.dumps(response_info))\n else:\n logging.critical('Unauthorized visibility set attempt')\n\n return\n","sub_path":"setvisibility.py","file_name":"setvisibility.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"274920320","text":"import json\nimport multiprocessing\nimport os\n\n\ndef worker(state, iteration):\n state[\"Key {}\".format(iteration)] = os.getpid()\n\nif __name__ == '__main__':\n manager = multiprocessing.Manager()\n state = manager.dict()\n jobs = [multiprocessing.Process(target=worker, args=(state, i)) for i in range(10)]\n for job in jobs:\n job.start()\n for job in jobs:\n job.join()\n print('Results:', state)\n","sub_path":"libraries_standard/multiprocessing_/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"263670096","text":"import math\nimport time\nfrom abc import abstractmethod\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nimport wandb\nimport yaml\nfrom torch import nn\nfrom torch.optim.lr_scheduler import OneCycleLR, CosineAnnealingWarmRestarts\n\nfrom point_vs.analysis.top_n import top_n\nfrom point_vs.utils import get_eta, format_time, print_with_overwrite, mkdir, \\\n to_numpy\n\n\nclass PointNeuralNetworkBase(nn.Module):\n \"\"\"Base (abstract) class for all point cloud based binary classifiers.\"\"\"\n\n def __init__(self, save_path, learning_rate, weight_decay=None,\n wandb_project=None, wandb_run=None, silent=False,\n use_1cycle=False, warm_restarts=False, **model_kwargs):\n super().__init__()\n self.batch = 0\n self.epoch = 0\n self.losses = []\n self.final_activation = nn.CrossEntropyLoss()\n self.feats_linear_layers = None\n self.edges_linear_layers = None\n self.save_path = Path(save_path).expanduser()\n self.linear_gap = model_kwargs.get('linear_gap', True)\n if not silent:\n mkdir(self.save_path)\n self.predictions_file = self.save_path / 'predictions.txt'\n\n self.loss_plot_file = self.save_path / 'loss.png'\n\n self.lr = learning_rate\n self.weight_decay = weight_decay\n self.translated_actives = model_kwargs.get('translated_actives', None)\n self.n_translated_actives = model_kwargs.get('n_translated_actives', 0)\n\n self.loss_log_file = self.save_path / 'loss.log'\n\n self.cross_entropy = nn.BCEWithLogitsLoss()\n\n self.wandb_project = wandb_project\n self.wandb_path = self.save_path / 'wandb_{}'.format(wandb_project)\n self.wandb_run = wandb_run\n\n self.n_layers = model_kwargs.get('num_layers', 12)\n self.layers = self.build_net(**model_kwargs)\n self.optimiser = torch.optim.Adam(\n self.parameters(), lr=self.lr, weight_decay=weight_decay)\n\n assert not (use_1cycle and warm_restarts), '1cycle nad warm restarts ' \\\n 'are mutually exclusive'\n\n self.use_1cycle = use_1cycle\n self.warm_restarts = warm_restarts\n\n self.global_iter = 0\n self.decoy_mean_pred, self.active_mean_pred = 0.5, 0.5\n self.log_interval = 10\n self.scheduler = None # will change this in training preamble\n\n if not silent:\n with open(save_path / 'model_kwargs.yaml', 'w') as f:\n yaml.dump(model_kwargs, f)\n\n pc = self.param_count\n print('Model parameters:', pc)\n if self.wandb_project is not None:\n wandb.log({'Parameters': pc})\n\n self.cuda()\n\n @abstractmethod\n def prepare_input(self, x):\n pass\n\n @abstractmethod\n def process_graph(self, graph):\n pass\n\n @abstractmethod\n def forward(self, x):\n pass\n\n def train_model(self, data_loader, epochs=1, epoch_end_validation_set=None,\n top1_on_end=False):\n \"\"\"Train the network.\n\n Trains the neural network. Displays training information and plots the\n loss. All figures and logs are saved to save_path.\n\n Arguments:\n data_loader: pytorch DataLoader object for training\n epochs: number of complete training cycles\n epoch_end_validation_set: DataLoader on which to perform inference\n at the end of each epoch (if supplied)\n top1_on_end:\n \"\"\"\n start_time = self.training_setup(data_loader=data_loader, epochs=epochs)\n for self.epoch in range(self.init_epoch, epochs):\n for self.batch, graph in enumerate(data_loader):\n y_pred, y_true, ligands, receptors = self.process_graph(graph)\n self.get_mean_preds(y_true, y_pred)\n loss_ = self.backprop(y_true, y_pred)\n if self.scheduler is not None:\n self.scheduler.step()\n self.record_and_display_info(\n start_time=start_time,\n epochs=epochs,\n data_loader=data_loader,\n loss=loss_,\n record_type='train'\n )\n self.on_epoch_end(\n epoch_end_validation_set=epoch_end_validation_set,\n epochs=epochs,\n top1_on_end=top1_on_end)\n\n def val(self, data_loader, predictions_file=None, top1_on_end=False):\n \"\"\"Use trained network to perform inference on the test set.\n\n Uses the neural network (in Session.network), to perform predictions\n on the structures found in , and saves this output\n to /predictions_.txt.\n\n Arguments:\n data_loader:\n predictions_file:\n top1_on_end:\n \"\"\"\n start_time = time.time()\n if predictions_file is None:\n predictions_file = self.predictions_file\n predictions_file = Path(predictions_file).expanduser()\n if predictions_file.is_file():\n predictions_file.unlink()\n predictions = ''\n with torch.no_grad():\n for self.batch, graph in enumerate(\n data_loader):\n y_pred, y_true, ligands, receptors = self.process_graph(graph)\n\n y_true_np = to_numpy(y_true).reshape((-1,))\n y_pred_np = to_numpy(nn.Sigmoid()(y_pred)).reshape((-1,))\n\n self.get_mean_preds(y_true, y_pred)\n self.record_and_display_info(\n start_time, None, data_loader, None, record_type='test')\n\n predictions += '\\n'.join(['{0} | {1:.7f} {2} {3}'.format(\n int(y_true_np[i]),\n y_pred_np[i],\n receptors[i],\n ligands[i]) for i in range(len(receptors))]) + '\\n'\n\n predictions = self.write_predictions(\n predictions,\n predictions_file,\n data_loader\n )\n\n if top1_on_end:\n try:\n top_1 = top_n(predictions_file)\n wandb.log({\n 'Validation Top1 at end of epoch {}'.format(self.epoch + 1):\n top_1,\n 'Validation Top1'.format(self.epoch + 1):\n top_1,\n 'Epoch': self.epoch + 1\n })\n except Exception:\n pass # wandb has not been initialised so ignore\n\n def get_loss(self, y_true, y_pred):\n return self.cross_entropy(y_pred, y_true.cuda())\n\n def training_setup(self, data_loader, epochs):\n start_time = time.time()\n self.train()\n if self.use_1cycle:\n print('Using 1cycle')\n self.scheduler = OneCycleLR(\n self.optimiser, max_lr=self.lr,\n steps_per_epoch=epochs * len(data_loader), epochs=1)\n print('Using 1cycle')\n elif self.warm_restarts:\n print('Using CosineAnnealingWarmRestarts')\n self.scheduler = CosineAnnealingWarmRestarts(\n self.optimiser, T_0=len(data_loader), T_mult=1, eta_min=0)\n else:\n print('Using a flat learning rate')\n print()\n print()\n self.init_epoch = self.epoch\n self.total_iters = epochs * len(data_loader)\n return start_time\n\n def get_mean_preds(self, y_true, y_pred):\n y_true_np = to_numpy(y_true).reshape((-1,))\n y_pred_np = to_numpy(nn.Sigmoid()(y_pred)).reshape((-1,))\n\n active_idx = (np.where(y_true_np > 0.5),)\n decoy_idx = (np.where(y_true_np < 0.5),)\n\n is_actives = bool(sum(y_true_np))\n is_decoys = not bool(np.product(y_true_np))\n\n if is_actives:\n self.active_mean_pred = np.mean(y_pred_np[active_idx])\n if is_decoys:\n self.decoy_mean_pred = np.mean(y_pred_np[decoy_idx])\n\n def backprop(self, y_true, y_pred):\n loss = self.get_loss(y_true, y_pred)\n self.optimiser.zero_grad()\n loss.backward()\n torch.nn.utils.clip_grad_value_(self.parameters(), 1.0)\n self.optimiser.step()\n loss_ = float(to_numpy(loss))\n if math.isnan(loss_):\n if hasattr(self, '_get_min_max'):\n print(self._get_min_max())\n raise RuntimeError('We have hit a NaN loss value.')\n self.losses.append(loss_)\n return loss_\n\n def record_and_display_info(\n self, start_time, epochs, data_loader, loss, record_type='train'):\n lr = self.optimiser.param_groups[0]['lr']\n if not (self.batch + 1) % self.log_interval or \\\n self.batch == self.total_iters - 1:\n self.save_loss(self.log_interval)\n self.global_iter += 1\n\n eta = get_eta(start_time, self.global_iter,\n self.total_iters - (len(data_loader) * self.init_epoch))\n time_elapsed = format_time(time.time() - start_time)\n\n if record_type == 'train':\n wandb_update_dict = {\n 'Time remaining (train)': eta,\n 'Binary crossentropy (train)': loss,\n 'Batch (train)':\n (self.epoch * len(data_loader) + self.batch + 1),\n 'Mean active prediction (train)': self.active_mean_pred,\n 'Mean decoy prediction (train)': self.decoy_mean_pred,\n 'Examples seen (train)':\n self.epoch * len(\n data_loader) * data_loader.batch_size +\n data_loader.batch_size * self.batch,\n 'Learning rate (train)': lr\n }\n print_with_overwrite(\n (\n 'Epoch:',\n '{0}/{1}'.format(self.epoch + 1, epochs),\n '|', 'Batch:', '{0}/{1}'.format(\n self.batch + 1, len(data_loader)),\n 'LR:', '{0:.3e}'.format(lr)),\n ('Time elapsed:', time_elapsed, '|',\n 'Time remaining:', eta),\n ('Loss: {0:.4f}'.format(loss), '|',\n 'Mean active: {0:.4f}'.format(self.active_mean_pred),\n '|', 'Mean decoy: {0:.4f}'.format(self.decoy_mean_pred))\n )\n else:\n wandb_update_dict = {\n 'Time remaining (validation)': eta,\n 'Batch': self.batch + 1,\n 'Mean active prediction (validation)':\n self.active_mean_pred,\n 'Mean decoy prediction (validation)':\n self.decoy_mean_pred,\n }\n print_with_overwrite(\n ('Inference on: {}'.format(data_loader.dataset.base_path),\n '|', 'Iteration:', '{0}/{1}'.format(\n self.batch + 1, len(data_loader))),\n ('Time elapsed:', time_elapsed, '|',\n 'Time remaining:', eta),\n ('Mean active: {0:.4f}'.format(self.active_mean_pred), '|',\n 'Mean decoy: {0:.4f}'.format(self.decoy_mean_pred))\n )\n try:\n try:\n wandb.log(wandb_update_dict)\n except wandb.errors.error.Error:\n pass # wandb has not been initialised so ignore\n except AttributeError:\n # New versions of wandb have different structure\n pass\n\n def on_epoch_end(self, epoch_end_validation_set, epochs, top1_on_end):\n # save after each epoch\n self.save()\n\n # end of epoch validation if requested\n if epoch_end_validation_set is not None and self.epoch < epochs - 1:\n epoch_end_predictions_fname = Path(\n self.predictions_file.parent,\n 'predictions_epoch_{}.txt'.format(self.epoch + 1))\n self.val(\n epoch_end_validation_set,\n predictions_file=epoch_end_predictions_fname,\n top1_on_end=top1_on_end)\n self.train()\n\n def write_predictions(self, predictions_str, predictions_file, data_loader):\n # Periodically write predictions to disk\n if not (self.batch + 1) % self.log_interval or self.batch == len(\n data_loader) - 1:\n with open(predictions_file, 'a') as f:\n f.write(predictions_str)\n return ''\n return predictions_str\n\n def save(self, save_path=None):\n \"\"\"Save all network attributes, including internal states.\"\"\"\n\n if save_path is None:\n fname = 'ckpt_epoch_{}.pt'.format(self.epoch + 1)\n save_path = self.save_path / 'checkpoints' / fname\n\n mkdir(save_path.parent)\n torch.save({\n 'learning_rate': self.lr,\n 'weight_decay': self.weight_decay,\n 'epoch': self.epoch + 1,\n 'losses': self.losses,\n 'model_state_dict': self.state_dict(),\n 'optimiser_state_dict': self.optimiser.state_dict()\n }, save_path)\n\n def load_weights(self, checkpoint_file):\n checkpoint = torch.load(str(Path(checkpoint_file).expanduser()))\n self.load_state_dict(checkpoint['model_state_dict'])\n self.optimiser.load_state_dict(checkpoint['optimiser_state_dict'])\n self.epoch = checkpoint['epoch']\n if not self.epoch:\n self.epoch += 1\n self.losses = checkpoint['losses']\n print('Sucesfully loaded weights from', checkpoint_file)\n\n def save_loss(self, save_interval):\n \"\"\"Save the loss information to disk.\n\n Arguments:\n save_interval: how often the loss is being recorded (in batches).\n \"\"\"\n log_file = self.save_path / 'loss.log'\n start_idx = save_interval * (self.batch // save_interval)\n with open(log_file, 'a') as f:\n f.write('\\n'.join(\n [str(idx + start_idx + 1) + ' ' + str(loss) for idx, loss in\n enumerate(self.losses[-save_interval:])]) + '\\n')\n\n @property\n def param_count(self):\n return sum(\n [torch.numel(t) for t in self.parameters() if t.requires_grad])\n","sub_path":"point_vs/models/point_neural_network_base.py","file_name":"point_neural_network_base.py","file_ext":"py","file_size_in_byte":14181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"609670323","text":"\"\"\"\nThis demo shows how to implement a scrolling line on an HD44780 LCD\n\"\"\"\n\nimport sys\nsys.path.append( \"../..\" )\nimport hwpy\nprint( __doc__)\n\n\n# Initialize an i2c hardware bus (by default pins BCM2(SDA1) and BCM3(SCL1) are used\ni2c = hwpy.i2c_hardware()\n# When these pins are already in use:\n# i2c = hwpy.i2c_hardware(2) BCM0(SDA2) and BCM1(SCL2)\n# When these are also not available, you can create 2 gpoc's and use hwpy.i2c_from_scl_sda\n\n# Initialize a PCF8574 (The address is usually 0x07)\nport = hwpy.pcf8574(i2c, 0x07)\n\n# Initialize an HD44780 from the PCF, 16X12 is the size of the LCD in characters\nlcd = hwpy.hd44780.from_pcf8574(port, hwpy.xy(16,2))\n\nstring = \"This is a pretty long text to display\"\ncurrent_start = 0\ncounter = 0\ni = 0\nwhile True:\n # Return the cursor to the top left\n lcd.cursor(hwpy.xy(0,0))\n\n # Clear the first row and return to the top left\n lcd.write(\" \" * 16 + \"\\r\")\n\n # Write the current part of the string\n lcd.write(string[current_start:min(len(string), current_start + 16)] + \"\\n\")\n\n\n # Move the start of the display 1 character, resetting it to 0 when the end is reached\n current_start = (current_start + 1) % len(string)\n\n # Roughly every second, increment the counter and show it\n i += 1\n if i % 4 == 0:\n counter += 1\n # Write the counter to the second row\n lcd.write(str(counter))\n\n hwpy.wait_ms(200)\n\n","sub_path":"demo/rapi/pcf8574-hw-hd44780-scrolling.py","file_name":"pcf8574-hw-hd44780-scrolling.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"557379492","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/7/21\n# @Author : RoyYoung\n\n\"\"\"\noutput类,存放output列表\n\"\"\"\n\n\nclass Output(object):\n def __init__(self, str):\n self.output = []\n temp = str[2:]\n count = len(temp) // 6\n\n for i in range(count):\n self.output.append(temp[i * 6:(i + 1) * 6].strip().encode('cp1252').decode('gbk'))\n\n self.print()\n\n def generate(self):\n str = \" \"\n for i in range(len(self.output)):\n str += \"%-6s\" % self.output[i].encode('gbk').decode('cp1252')\n\n # 每行输出13个\n if (i + 1) % 13 == 0 and (i + 1) != len(self.output):\n str += \"\\n \"\n str += \"\\n\"\n return str\n\n def print(self):\n print(self.output)\n","sub_path":"entity/Output.py","file_name":"Output.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"284070423","text":"# Write your code here :-)\nimport time\nimport board\nimport analogio\nfrom simpleio import map_range\nimport neopixel\nfrom adafruit_circuitplayground import cp\n\nwhite = (255, 255, 255)\ndark = (0,0,0)\n\npreReading = False\n\nbutton_pressed = False\nledState = False\n\naccl_vals = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\navg_accl = 0\naccl_th = 15\n\nledState = False\nmovement = False\ntimeOut = time.monotonic()\n\naccl_time = time.monotonic()\naccl_int = 1\n\nbutton_time = time.monotonic()\nbutton_int = 0.1\n\ntimeInterval = 1\n\nwhile True:\n\n # gather input from button and acceleration\n buttonInput = cp.button_a\n\n if time.monotonic() >= button_time:\n button_time += button_int\n print(\"reading the button\")\n # check for change in the button value\n if buttonInput != preReading:\n preReading = buttonInput\n if buttonInput:\n button_pressed = True\n\n if time.monotonic() >= accl_time:\n # resets the next time to read the accelerometer\n accl_time += accl_int\n print(\"reading the accelerometer...\")\n # use time.monotonic to decide when to get input/sec and average after\n x, y, z = cp.acceleration\n accl = (x, y, z)\n # print((x, y, z))\n # add all abs value of xyz values\n total_accl = 0\n for a in accl:\n total_accl += abs(a)\n\n # Append the new value pop an old value\n accl_vals.append(total_accl)\n accl_vals.pop(0)\n\n # calculate the mean\n avg_accl = sum(accl_vals)/len(accl_vals)\n print((avg_accl,))\n\n # is the avg_accl > threshold?\n if avg_accl >= accl_th:\n movement = True\n else:\n movement = False\n\n\n # depending on the amount of movement or the button state set the ledstate\n # print(movement)\n if movement:\n ledState = True\n # start timeout timer\n timeOut = time.monotonic() + timeInterval\n #button_pressed = False\n else:\n\n if time.monotonic() == timeOut:\n ledState = False\n\n if button_pressed:\n ledState = not ledState\n if ledState:\n timeOut = time.monotonic() + 20\n button_pressed = False\n accl_vals = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n avg_accl = 0\n\n # DO THE OUTPUT BASED ON LedState\n if ledState:\n cp.pixels.fill(white)\n cp.pixels.brightness = 0.5\n else:\n cp.pixels.fill(dark)\n\n # this is why it is not working...\n # time.sleep(1)\n","sub_path":"MidTerms Project/FinalCode.py","file_name":"FinalCode.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"205442803","text":"import logging\n\nimport requests\nfrom django.contrib.auth.backends import ModelBackend\nfrom django.core.exceptions import PermissionDenied\n\nfrom django_auth_adfs.adfs import exchange_auth_code, process_access_token\nfrom django_auth_adfs.config import provider_config\n\nlogger = logging.getLogger(\"django_auth_adfs\")\n\n\nclass AdfsAuthCodeBackend(ModelBackend):\n \"\"\"\n Authentication backend to allow authenticating users against a\n Microsoft ADFS server with an authorization code.\n \"\"\"\n\n def authenticate(self, request=None, authorization_code=None, **kwargs):\n # If loaded data is too old, reload it again\n provider_config.load_config()\n\n # If there's no token or code, we pass control to the next authentication backend\n if authorization_code is None or authorization_code == '':\n logger.debug(\"django_auth_adfs authentication backend was called but no authorization code was received\")\n return\n try:\n adfs_response = exchange_auth_code(authorization_code, request)\n access_token = adfs_response[\"access_token\"]\n user = process_access_token(self, access_token, adfs_response)\n except (requests.HTTPError, ValueError):\n raise PermissionDenied\n return user\n\n\nclass AdfsAccessTokenBackend(ModelBackend):\n \"\"\"\n Authentication backend to allow authenticating users against a\n Microsoft ADFS server with an access token retrieved by the client.\n \"\"\"\n\n def authenticate(self, request=None, access_token=None, **kwargs):\n # If loaded data is too old, reload it again\n provider_config.load_config()\n\n # If there's no token or code, we pass control to the next authentication backend\n if access_token is None or access_token == '':\n logger.debug(\"django_auth_adfs authentication backend was called but no authorization code was received\")\n return\n\n access_token = access_token.decode()\n try:\n user = process_access_token(self, access_token)\n except ValueError:\n raise PermissionDenied\n return user\n\n\nclass AdfsBackend(AdfsAuthCodeBackend):\n \"\"\" Backwards compatible class name \"\"\"\n pass\n","sub_path":"django_auth_adfs/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"209315766","text":"import argparse\n\n\ndef modular_inverse(num, m):\n \"\"\"\n Calculates the modular inverse of a number with a given modulus\n\n :param num: number to find modular inverse for\n :param m: number to regard as mod\n :return: modular inverse for num (mod m)\n \"\"\"\n\n x = 0\n y = 1\n lx = 1\n ly = 0\n oa = num\n ob = m\n\n while m != 0:\n q = num // m\n (num, m) = (m, num % m)\n (x, lx) = ((lx - (q * x)), x)\n (y, ly) = ((ly - (q * y)), y)\n\n if lx < 0:\n lx += ob\n if ly < 0:\n ly += oa\n return lx\n\n\ndef euler_phi(modulus):\n \"\"\"\n Calculates the value of the Euler totient function for a given number\n\n :param modulus: number to find the Euler function value\n :return: phi(given number)\n \"\"\"\n result = modulus\n p = 2\n\n while p * p <= modulus:\n if modulus % p == 0:\n while modulus % p == 0:\n modulus //= p\n result *= (1 - (1 / p))\n p += 1\n\n if modulus > 1:\n result *= (1 - (1 / modulus))\n\n return int(result)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-e\", \"--exponent\",\n type=int,\n help=\"specifying the exponent\")\n parser.add_argument(\"-n\", \"--modulus\",\n type=int,\n help=\"specifying the modulus\")\n parser.add_argument(\"-c\", \"--ciphertext\",\n type=int,\n help=\"specifying the ciphertext to break\")\n\n args = parser.parse_args()\n\n phi_n = euler_phi(args.modulus)\n decr_key = modular_inverse(args.exponent, phi_n)\n message = (args.ciphertext ** decr_key) % args.modulus\n print(message)\n","sub_path":"ex02/out/src/rsa/crack_rsa.py","file_name":"crack_rsa.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"359324533","text":"# coding=utf8\n\nimport os\nimport random\n\nfrom analysis import *\n\n\nclass validate_config:\n def validate_weight(self, path, press_weight=0.5, flight_weight=0.5):\n data_list = [DataReader(os.path.join(path, i)) for i in os.listdir(path)]\n train_index_list = [random.sample([0, 1, 2], 2) for _ in data_list]\n test_index_list = [int(({0, 1, 2} - set(i)).pop()) for i in train_index_list]\n people_num = len(data_list)\n evaluation = 0\n tmp = 0\n for i in range(people_num):\n tmp = 0\n for j in range(people_num):\n if i != j:\n a = PressAnalysis()\n a.loadTwoOriginData(data_list[i].getIndexData(train_index_list[i][0]),\n data_list[i].getIndexData(train_index_list[i][1]))\n a.loadTestData(data_list[j].getIndexData(test_index_list[j]))\n tmp += a.similarMatch(press_weight=press_weight, flight_weight=flight_weight)\n a = PressAnalysis()\n a.loadTwoOriginData(data_list[i].getIndexData(train_index_list[i][0]),\n data_list[i].getIndexData(train_index_list[i][1]))\n a.loadTestData(data_list[i].getIndexData(test_index_list[i]))\n evaluation += a.similarMatch(press_weight=press_weight, flight_weight=flight_weight) / tmp\n return evaluation\n\n def validate_threshold(self):\n pass\n","sub_path":"validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"21649292","text":"print(\"\"\"================================================================\n Лабораторна робота №2. Завдання 2. Варіант 23\n Організація циклу за допомогою оператора while\n Створив: Шуліка О. О. КМ-83 \n================================================================\"\"\")\n\n\ndef get_a():\n try:\n a_str = input(\"Введіть значення А(>1): \")\n a = float(a_str)\n if a <= 1:\n print(\"Помилка! Введіть значення, що більше числа 1.\")\n return get_a()\n else:\n return a\n except ValueError:\n print(\"Неправильний тип введених данних! Спробуйте ще раз\")\n return get_a()\n\n\nstatus = \"y\"\nwhile status == \"y\":\n A = get_a()\n K = 1\n result = 1.0\n\n while result < A:\n K += 1\n result += 1/K\n\n result -= 1/K\n\n if result.is_integer():\n msg = \", а значення суми - {}\".format(int(result))\n else:\n msg = \", а значення суми - {0:.3f}\".format(result)\n\n print(\"Найбільше значення числа K для якого виконується умова: \", K - 1, msg, sep=\"\")\n\n status = input(\"Для повторного запуску програми, введіть y: \")\n\nprint(\"Завершення програми...\")\n","sub_path":"Лабы Программирование/Лаб 2/Задание 2.py","file_name":"Задание 2.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"463501160","text":"#!/usr/bin/python3\n'prints the State object with the name passed as argument'\nfrom sys import argv\nimport sys\nfrom relationship_state import Base, State\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom relationship_city import City\n\nif __name__ == \"__main__\":\n engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.\n format(sys.argv[1],\n sys.argv[2],\n sys.argv[3]),\n pool_pre_ping=True)\n\n Base.metadata.create_all(engine)\n\n Session = sessionmaker(bind=engine)\n session = Session()\n addstate = State(name='California')\n addcity = City(name='San Francisco')\n addcity.state = addstate\n session.add(addstate)\n session.add(addcity)\n session.commit()\n session.close()\n","sub_path":"0x0F-python-object_relational_mapping/100-relationship_states_cities.py","file_name":"100-relationship_states_cities.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"211350404","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n curr = l1\n n1 =\"\"\n dummy =ListNode(-1)\n newcurr =dummy\n if(l1 is None and l2 is None):\n return 0\n elif(l1 is None):\n n1=0\n elif(l2 is None):\n n2=0\n while(curr is not None):\n n1=n1+str(curr.val)\n #n1 = n1+curr.val \n curr = curr.next\n n2=\"\"\n\n curr = l2\n while(curr is not None):\n n2=n2+str(curr.val)\n curr= curr.next\n print(n1, n2)\n sum = int(n1)+int(n2)\n print(sum)\n if(sum==0):\n dummy.next =ListNode(sum)\n return dummy.next\n while(sum>0):\n n = sum%10\n newcurr.next = ListNode(n)\n newcurr = newcurr.next\n sum = sum//10\n newcurr.next = None\n return dummy.next\n \n \n \n \n \n","sub_path":"Add Two Numbers.py","file_name":"Add Two Numbers.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"540533558","text":"import requests\nimport threading\nimport time\nimport os\nimport re\nfrom bs4 import BeautifulSoup \nimport pandas as pd\n\n\nurls = 'https://weibo.cn/comment/HsLJ5iFsN?&page={}'\ncookie = 'ALF=1559372930; _T_WM=97578540503; SCF=AkfxmsDO36V0ByxhHzwJYmxhvCSOrQI1H8EVDnELA4ztDnL37O-hwNO_ffPYoNb2ZeFQnhZDKs7YS0_GZeYYTxI.; SUB=_2A25x3RtpDeRhGeVH4lQT9ybNzzmIHXVTIaUhrDV6PUJbktANLWaskW1NTw8TBGF7XrOSNv_EhBTLeT7bIJ7gwCmv; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFh5eWnz0mbsg9.zV-zHp5k5JpX5KzhUgL.Foe41KqES0npSh-2dJLoI79hxXnEe0et; SUHB=0u5hQBPdnYYYZ3; SSOLoginState=1557752633; MLOGIN=1; M_WEIBOCN_PARAMS=oid%3D4359994184552807%26lfid%3D2304132656274875_-_WEIBO_SECOND_PROFILE_WEIBO%26luicode%3D20000174'\n\nheaders = {'cookie': cookie,'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}\n\nreg = re.compile(']*>')\n\ndef get_comment(url):\n html = requests.get(url, headers=headers).text\n soup = BeautifulSoup(html, 'lxml')\n tags = soup.find_all('div', class_='c', id=re.compile(\"C_\"))\n for tag in tags:\n try:\n comment = reg.sub('', tag.find_all('span', 'ctt')[0].text)\n if (re.search('(@[A-Za-z0-9\\u4e00-\\u9fa5]+|转发微博)', comment) and re.search(':', comment) is None): \n continue\n a_emoji = re.findall('\".{4}\"',= 3:\n # alias str as unicode for python3 and above\n unicode = str\n\n\n# path to settings.json relative root dir\nSETTINGS_FILE = \"settings.json\"\n# path to dir containing traffic configurations relative root dir\nCONFIGS_DIR = \"configs\"\n\n\ndef get_root_dir():\n return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\ndef get_test_config_path(config_name):\n return os.path.join(\n os.path.dirname(get_root_dir()), CONFIGS_DIR, config_name\n )\n\n\ndef dict_items(d):\n try:\n # python 3\n return d.items()\n except Exception:\n # python 2\n return d.iteritems()\n\n\ndef object_dict_items(ob):\n return dict_items(ob.__dict__)\n\n\ndef byteify(val):\n if isinstance(val, dict):\n return {byteify(key): byteify(value) for key, value in dict_items(val)}\n elif isinstance(val, list):\n return [byteify(element) for element in val]\n # change u'string' to 'string' only for python2\n elif isinstance(val, unicode) and sys.version_info[0] == 2:\n return val.encode(\"utf-8\")\n else:\n return val\n\n\ndef load_dict_from_json_file(path):\n \"\"\"\n Safely load dictionary from JSON file in both python2 and python3\n \"\"\"\n with open(path, \"r\") as fp:\n return json.load(fp, object_hook=byteify)\n\n\nclass Settings(object):\n \"\"\"\n Singleton for global settings\n \"\"\"\n\n def __init__(self):\n # these not be defined and are here only for documentation\n self.username = None\n self.location = None\n self.ports = None\n self.speed = None\n self.media = None\n self.timeout_seconds = None\n self.interval_seconds = None\n self.log_level = None\n self.dynamic_stats_output = None\n self.license_servers = None\n self.ext = None\n\n self.load_from_settings_file()\n\n def load_from_settings_file(self):\n self.__dict__ = load_dict_from_json_file(self.get_settings_path())\n # overwrite with custom settings if it exists\n custom = os.environ.get(\"SETTINGS_FILE\", None)\n if custom is not None and os.path.exists(custom):\n self.__dict__ = load_dict_from_json_file(custom)\n\n def get_settings_path(self):\n return os.path.join(get_root_dir(), SETTINGS_FILE)\n\n def register_pytest_command_line_options(self, parser):\n for key, val in object_dict_items(self):\n parser.addoption(\"--%s\" % key, action=\"store\", default=None)\n\n def load_from_pytest_command_line(self, config):\n for key, val in object_dict_items(self):\n new_val = config.getoption(key)\n if new_val is not None:\n if key in [\"license_servers\", \"ports\"]:\n # items in a list are expected to be passed in as a string\n # where each item is separated by whitespace\n setattr(self, key, new_val.split())\n else:\n setattr(self, key, new_val)\n\n\n# shared global settings\nsettings = Settings()\n\n\ndef start_traffic(api, cfg, start_capture=True):\n \"\"\"\n Applies configuration, and starts flows.\n \"\"\"\n print(\"Setting config ...\")\n api.set_config(cfg)\n # assert(len(response.errors)) == 0\n\n capture_names = get_capture_port_names(cfg)\n if capture_names and start_capture:\n print(\"Starting capture on ports %s ...\" % str(capture_names))\n cs = api.capture_state()\n cs.state = cs.START\n api.set_capture_state(cs)\n print(\"Starting all protocols ...\")\n ps = api.protocol_state()\n ps.state = ps.START\n api.set_protocol_state(ps)\n\n print(\"Starting transmit on all flows ...\")\n ts = api.transmit_state()\n ts.state = ts.START\n api.set_transmit_state(ts)\n\n\ndef stop_traffic(api, cfg, stop_capture=True):\n \"\"\"\n Stops flows\n \"\"\"\n print(\"Stopping transmit on all flows ...\")\n ts = api.transmit_state()\n ts.state = ts.STOP\n api.set_transmit_state(ts)\n\n print(\"Starting all protocols ...\")\n ps = api.protocol_state()\n ps.state = ps.STOP\n api.set_protocol_state(ps)\n\n capture_names = get_capture_port_names(cfg)\n if capture_names and stop_capture:\n print(\"Stopping capture on ports %s ...\" % str(capture_names))\n cs = api.capture_state()\n cs.state = cs.STOP\n api.set_capture_state(cs)\n\n\ndef seconds_elapsed(start_seconds):\n return int(round(time.time() - start_seconds))\n\n\ndef timed_out(start_seconds, timeout):\n return seconds_elapsed(start_seconds) > timeout\n\n\ndef wait_for(func, condition_str, interval_seconds=None, timeout_seconds=None):\n \"\"\"\n Keeps calling the `func` until it returns true or `timeout_seconds` occurs\n every `interval_seconds`. `condition_str` should be a constant string\n implying the actual condition being tested.\n Usage\n -----\n If we wanted to poll for current seconds to be divisible by `n`, we would\n implement something similar to following:\n ```\n import time\n def wait_for_seconds(n, **kwargs):\n condition_str = 'seconds to be divisible by %d' % n\n def condition_satisfied():\n return int(time.time()) % n == 0\n poll_until(condition_satisfied, condition_str, **kwargs)\n ```\n \"\"\"\n if interval_seconds is None:\n interval_seconds = settings.interval_seconds\n if timeout_seconds is None:\n timeout_seconds = settings.timeout_seconds\n start_seconds = int(time.time())\n\n print(\"\\n\\nWaiting for %s ...\" % condition_str)\n while True:\n res = func()\n if res:\n print(\"Done waiting for %s\" % condition_str)\n break\n if res is None:\n raise Exception(\"Wait aborted for %s\" % condition_str)\n if timed_out(start_seconds, timeout_seconds):\n msg = \"Time out occurred while waiting for %s\" % condition_str\n raise Exception(msg)\n\n time.sleep(interval_seconds)\n\n\ndef get_all_stats(api, print_output=True):\n \"\"\"\n Returns all port and flow stats\n \"\"\"\n print(\"Fetching all port stats ...\")\n request = api.metrics_request()\n request.choice = request.PORT\n request.port\n port_results = api.get_metrics(request).port_metrics\n if port_results is None:\n port_results = []\n\n print(\"Fetching all flow stats ...\")\n request = api.metrics_request()\n request.choice = request.FLOW\n request.flow\n flow_results = api.get_metrics(request).flow_metrics\n if flow_results is None:\n flow_results = []\n\n if print_output:\n print_stats(port_stats=port_results, flow_stats=flow_results)\n\n return port_results, flow_results\n\n\ndef total_frames_ok(port_results, flow_results, expected):\n port_tx = sum([p.frames_tx for p in port_results])\n port_rx = sum([p.frames_rx for p in port_results])\n flow_rx = sum([f.frames_rx for f in flow_results])\n\n return port_tx == port_rx == flow_rx == expected\n\n\ndef total_bytes_ok(port_results, flow_results, expected):\n port_tx = sum([p.bytes_tx for p in port_results])\n port_rx = sum([p.bytes_rx for p in port_results])\n flow_rx = sum([f.bytes_rx for f in flow_results])\n\n return port_tx == port_rx == flow_rx == expected\n\n\ndef new_logs_dir(prefix=\"logs\"):\n \"\"\"\n creates a new dir with prefix and current timestamp\n \"\"\"\n file_name = (\n prefix + \"-\" + datetime.strftime(datetime.now(), \"%Y%m%d-%H%M%S\")\n )\n logs_dir = os.path.join(get_root_dir(), \"logs\")\n csv_dir = os.path.join(logs_dir, file_name)\n # don't use exist_ok - since it's not supported in python2\n if not os.path.exists(csv_dir):\n os.makedirs(csv_dir)\n return csv_dir\n\n\ndef append_csv_row(dirname, filename, column_names, result_dict):\n \"\"\"\n creates a new csv with column names if it doesn't exist and appends a\n single row specified by result_dict\n \"\"\"\n path = os.path.join(dirname, filename)\n\n with open(path, \"a\") as fp:\n csv_writer = csv.writer(fp)\n if os.path.getsize(path) == 0:\n csv_writer.writerow(column_names)\n\n csv_writer.writerow([result_dict[key] for key in column_names])\n\n\ndef print_stats(port_stats=None, flow_stats=None, clear_screen=None):\n if clear_screen is None:\n clear_screen = settings.dynamic_stats_output\n\n if clear_screen:\n os.system(\"clear\")\n\n if port_stats is not None:\n row_format = \"{:>15}\" * 6\n border = \"-\" * (15 * 6 + 5)\n print(\"\\nPort Stats\")\n print(border)\n print(\n row_format.format(\n \"Port\",\n \"Tx Frames\",\n \"Tx Bytes\",\n \"Rx Frames\",\n \"Rx Bytes\",\n \"Tx FPS\",\n )\n )\n for stat in port_stats:\n print(\n row_format.format(\n stat.name,\n stat.frames_tx,\n stat.bytes_tx,\n stat.frames_rx,\n stat.bytes_rx,\n stat.frames_tx_rate,\n )\n )\n print(border)\n print(\"\")\n print(\"\")\n\n if flow_stats is not None:\n row_format = \"{:>15}\" * 3\n border = \"-\" * (15 * 3 + 5)\n print(\"Flow Stats\")\n print(border)\n print(row_format.format(\"Flow\", \"Rx Frames\", \"Rx Bytes\"))\n for stat in flow_stats:\n print(row_format.format(stat.name, stat.frames_rx, stat.bytes_rx))\n print(border)\n print(\"\")\n print(\"\")\n\n\ndef get_value(field):\n \"\"\"\n Returns the values based on valuetype\n \"\"\"\n if field.ValueType == \"singleValue\":\n return field.SingleValue\n elif field.ValueType in [\"increment\", \"decrement\"]:\n return field.StartValue, field.StepValue, field.CountValue\n elif field.ValueType in [\"repeatableRandomRange\"]:\n return (\n field.MinValue,\n field.MaxValue,\n field.StepValue,\n field.Seed,\n field.CountValue,\n )\n else:\n return field.ValueList\n\n\ndef get_packet_information(api, flow_name, packet_header):\n \"\"\"\n Takes any packet_header or header position\n for ex ethernet, ipv4, udp, tcp and returns\n the packet information of that header\n if string is passed the header is filtered by name\n if int is passed header is filtered by index\n \"\"\"\n trafficItem = api._ixnetwork.Traffic.TrafficItem.find(Name=flow_name)\n configElement = trafficItem.ConfigElement.find()\n pckt_info = {}\n if isinstance(packet_header, int):\n stack = configElement.Stack.find()[packet_header]\n else:\n stack = configElement.Stack.find(StackTypeId=packet_header)\n for field in stack.Field.find():\n value = get_value(field)\n pckt_info[field.DisplayName] = value\n pckt_info[field.FieldTypeId] = value\n return pckt_info\n\n\ndef validate_config(api, flow_name, packet_header, **kwargs):\n \"\"\"\n validate config with key and values pairs against\n packet header.\n ex:\n attrs = {\n 'Destination MAC Address': '00:0C:29:E3:53:EA',\n 'Source MAC Address': '00:0C:29:E3:53:F4',\n 'Ethernet-Type': '8100',\n }\n validate_config(api, 'ethernet', **attrs)\n or\n validate_config(api, 0, **attrs) \n \"\"\"\n packet_info = get_packet_information(api, flow_name, packet_header)\n for key in kwargs:\n assert packet_info[key] == kwargs[key]\n\n\ndef is_traffic_stopped(api, flow_names=[]):\n \"\"\"\n Returns true if traffic in stop state\n \"\"\"\n fq = api.metrics_request()\n fq.flow.flow_names = flow_names\n metrics = api.get_metrics(fq).flow_metrics\n return all([m.transmit == \"stopped\" for m in metrics])\n\n\ndef value_list_with_packet_count(value_list, packet_count):\n \"\"\"\n Example:\n value_list_with_packet_count(['10.1.1.1', '10.1.1.3'], 6)\n returns: ['10.1.1.1', '10.1.1.3', '10.1.1.1', '10.1.1.3',\n '10.1.1.1', '10.1.1.3']\n \"\"\"\n ret_value = value_list * packet_count\n return ret_value[:packet_count]\n\n\ndef mac_or_ip_to_num(mac_or_ip_addr, mac=True):\n \"\"\"\n Example:\n mac_or_ip_to_num('00:0C:29:E3:53:EA')\n returns: 52242371562\n mac_or_ip_to_num('10.1.1.1', False)\n returns: 167837953\n \"\"\"\n sep = \":\" if mac else \".\"\n addr = []\n if mac:\n addr = mac_or_ip_addr.split(sep)\n else:\n addr = [\"{:02x}\".format(int(i)) for i in mac_or_ip_addr.split(sep)]\n return int(\"\".join(addr), 16)\n\n\ndef num_to_mac_or_ip(mac_or_ip_addr, mac=True):\n \"\"\"\n Example:\n num_to_mac_or_ip(52242371562)\n returns: '00:0C:29:E3:53:EA'\n num_to_mac_or_ip(167837953, False)\n returns: '10.1.1.1'\n \"\"\"\n sep = \":\" if mac else \".\"\n fmt = \"{:012x}\" if mac else \"{:08x}\"\n rng = 12 if mac else 8\n mac_or_ip = fmt.format(mac_or_ip_addr)\n addr = []\n for i in range(0, rng, 2):\n if mac:\n addr.append(mac_or_ip[i] + mac_or_ip[i + 1])\n else:\n addr.append(str(int(mac_or_ip[i] + mac_or_ip[i + 1], 16)))\n return sep.join(addr)\n\n\ndef mac_or_ip_addr_from_counter_pattern(start_addr, step, count, up, mac=True):\n \"\"\"\n Example:\n mac_or_ip_addr_from_counter_pattern('10.1.1.1', '0.0.1.1', 2, True, False)\n returns: ['00:0C:29:E3:53:EA', '00:0C:29:E3:54:EA']\n mac_or_ip_addr_from_counter_pattern('10.1.1.1', '0.0.1.1', 2, True, False)\n teturns: ['10.1.1.1', '10.1.2.2']\n \"\"\"\n addr_list = []\n for num in range(count):\n addr_list.append(start_addr)\n if up:\n start_addr = mac_or_ip_to_num(start_addr, mac) + mac_or_ip_to_num(\n step, mac\n )\n else:\n start_addr = mac_or_ip_to_num(start_addr, mac) - mac_or_ip_to_num(\n step, mac\n )\n start_addr = num_to_mac_or_ip(start_addr, mac)\n return addr_list\n\n\ndef is_stats_accumulated(api, packets):\n \"\"\"\n Returns true if stats gets accumulated\n \"\"\"\n port_results, flow_results = get_all_stats(api)\n frames_ok = total_frames_ok(port_results, flow_results, packets)\n return frames_ok\n\n\ndef get_capture_port_names(cfg):\n \"\"\"\n Returns name of ports for which capture is enabled.\n \"\"\"\n names = []\n if cfg.captures:\n for cap in cfg.captures:\n if cap.port_names:\n for name in cap.port_names:\n if name not in names:\n names.append(name)\n\n return names\n\n\ndef get_all_captures(api, cfg):\n \"\"\"\n Returns a dictionary where port name is the key and value is a list of\n frames where each frame is represented as a list of bytes.\n \"\"\"\n cap_dict = {}\n for name in get_capture_port_names(cfg):\n print(\"Fetching captures from port %s\" % name)\n request = api.capture_request()\n request.port_name = name\n pcap_bytes = api.get_capture(request)\n\n cap_dict[name] = []\n for ts, pkt in dpkt.pcapng.Reader(pcap_bytes):\n if sys.version_info[0] == 2:\n cap_dict[name].append([ord(b) for b in pkt])\n else:\n cap_dict[name].append(list(pkt))\n\n return cap_dict\n\n\ndef flow_transmit_matches(flow_results, state):\n return len(flow_results) == all(\n [f.transmit == state for f in flow_results]\n )\n\n\ndef to_hex(lst):\n \"\"\"\n Takes lst of data from packet capture and converts to hex\n Ex: [11,184] is converted to 0xbb8\n [0,30] is converted to 0x1e\n \"\"\"\n from functools import reduce\n\n value = reduce(lambda x, y: hex(x) + hex(y), lst)\n value = value[0:2] + value[2:].replace(\"0x\", \"\").lstrip(\"0\")\n return value\n","sub_path":"tests/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":15709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"423179191","text":"import config\nimport myfunc\n#檔案存放路徑\npath=\"D:\\\\project\\\\md-sql-field-description\\\\result\\\\\"\n#要Create 的表格 markdown檔清單\nfilenamels=[\"SQL-Table-Employee_id.md\"]\nsqlConn=myfunc.SqlConn(config.db)\nmdFieldDesc=myfunc.MdFieldDesc(path)\n#DROP同名表格並重建\nsqlConn.createTable(mdFieldDesc.setMdTableDesc(filenamels).getMdTableDesc())\n","sub_path":"md2sqlTable.py","file_name":"md2sqlTable.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"389940298","text":"#AUTOR: GABRIELA MARIEL VARGAS FRANCO A01745775\r\n#endoding: UTF-8\r\n#Leer un número entre 1 y 10 e imprima el número en Romano correspondiente\r\n#Calcula y guarda en la varibale CalcularRomano\r\nc=\"IV\"\r\ncin=\"V\"\r\nnu=\"IX\"\r\nd=\"X\"\r\ndef calcularRomano(numero):\r\n#Comparación de numeros\r\n if numero>=1 and numero<=3:\r\n calcularRomano=(numero*\"I\")\r\n elif numero==4:\r\n calcularRomano=c\r\n elif numero==5:\r\n calcularRomano=cin\r\n elif numero>=6 and numero<=8:\r\n calcularRomano=(cin)+((numero-5)*\"I\")\r\n elif numero==9:\r\n calcularRomano=nu\r\n elif numero==10:\r\n calcularRomano=d\r\n else:\r\n calcularRomano=\"Error\"\r\n#Regresa calcularRomano\r\n return calcularRomano\r\n\r\n\r\ndef main():\r\n numero=int(input(\"Leer numero decimal: \"))\r\n cR=calcularRomano(numero)\r\n#Imprime el numero romano correspondiente\r\n print(\"Numero en romano:\", cR)\r\n\r\nmain()\r\n\r\n\r\n\r\n\r\n","sub_path":"Romanos.py","file_name":"Romanos.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"506836420","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('game', '0005_tick'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Ship',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ('hull', models.IntegerField()),\n ('worth', models.IntegerField()),\n ('owner', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.RemoveField(\n model_name='system',\n name='focus',\n ),\n ]\n","sub_path":"game/migrations/0006_auto_20150418_1932.py","file_name":"0006_auto_20150418_1932.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"418529203","text":"import logging\nfrom http.cookies import SimpleCookie\n\nfrom cryptojwt.exception import UnknownAlgorithm\n\nlogger = logging.getLogger(__name__)\n\nOAUTH2_NOCACHE_HEADERS = [\n ('Pragma', 'no-cache'),\n ('Cache-Control', 'no-store'),\n]\n\n\ndef new_cookie(endpoint_context, user, **kwargs):\n if endpoint_context.cookie_dealer:\n return endpoint_context.cookie_dealer.create_cookie(\n user, typ=\"sso\", ttl=endpoint_context.sso_ttl)\n else:\n return None\n\n\nDEF_SIGN_ALG = {\"id_token\": \"RS256\",\n \"userinfo\": \"RS256\",\n \"request_object\": \"RS256\",\n \"client_secret_jwt\": \"HS256\",\n \"private_key_jwt\": \"RS256\"}\n\n\ndef get_sign_and_encrypt_algorithms(endpoint_context, client_info, payload_type,\n sign=False, encrypt=False):\n args = {'sign': sign, 'encrypt': encrypt}\n if sign:\n try:\n args['sign_alg'] = client_info[\n \"{}_signed_response_alg\".format(payload_type)]\n except KeyError: # Fall back to default\n try:\n args['sign_alg'] = endpoint_context.jwx_def[\"signing_alg\"][payload_type]\n except KeyError:\n args['sign_alg'] = DEF_SIGN_ALG[payload_type]\n\n if encrypt:\n try:\n args['enc_alg'] = client_info[\n \"%s_encrypted_response_alg\" % payload_type]\n except KeyError:\n try:\n args['enc_alg'] = endpoint_context.jwx_def[\"encryption_alg\"][\n payload_type]\n except KeyError:\n raise UnknownAlgorithm(\n \"Don't know which encryption algorithm to use\")\n\n try:\n args['enc_enc'] = client_info[\n \"%s_encrypted_response_enc\" % payload_type]\n except KeyError:\n try:\n args['enc_enc'] = endpoint_context.jwx_def[\"encryption_enc\"][\n payload_type]\n except KeyError:\n raise UnknownAlgorithm(\n \"Don't know which encryption algorithm to use\")\n\n return args\n\n\ndef build_endpoints(conf, endpoint_context, client_authn_method, issuer):\n \"\"\"\n conf typically contains::\n\n 'provider_config': {\n 'path': '.well-known/openid-configuration',\n 'class': ProviderConfiguration,\n 'kwargs': {}\n },\n\n :param conf:\n :param endpoint_context:\n :param client_authn_method:\n :param issuer:\n :return:\n \"\"\"\n\n if issuer.endswith('/'):\n _url = issuer[:-1]\n else:\n _url = issuer\n\n endpoint = {}\n for name, spec in conf.items():\n try:\n kwargs = spec['kwargs']\n except KeyError:\n kwargs = {}\n\n _instance = spec['class'](endpoint_context=endpoint_context, **kwargs)\n _instance.endpoint_path = spec['path'].format(_url)\n\n try:\n _client_authn_method = kwargs['client_authn_method']\n except KeyError:\n _instance.client_auth_method = client_authn_method\n else:\n _instance.client_auth_method = _client_authn_method\n\n endpoint[name] = _instance\n\n return endpoint\n\n\n","sub_path":"src/oidcendpoint/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"329822201","text":"from numpy import poly1d\nfrom numpy import arange\nfrom numpy import asarray\nimport math\nimport functools\nfrom trajectory import *\n\ndef interp(q1,q2,u):\n \"\"\"Interpolates a segment between the vectors q1 and q2 using the\n parameter u. Can also be used for extrapolation\"\"\"\n res = [0]*len(q1)\n for i in range(len(q1)):\n res[i] = q1[i]+u*(q2[i]-q1[i])\n return res\n\ndef finterp(q1,q2,ut,t):\n return interp(q1,q2,ut(t))\n\ndef NonlinearInterpolation(q1,q2,ut):\n return functools.partial(finterp,q1,q2,ut)\n\ndef choose(n,k):\n \"\"\"Returns (n choose k).\n \"\"\"\n assert(k<=n and k==int(k) and n==int(n)),\"n=%f, k=%f\"%(n,k)\n k = min(k,n-k)\n if k==0:\n c = 1\n else:\n c = n\n for i in xrange(1,k):\n c*=n-i\n for i in xrange(1,k):\n c//=i+1\n return c \n\ndef shiftPoly(p,dx):\n \"\"\"Returns the polynomial representing p(x+dx)\"\"\"\n if hasattr(p,'order'):\n #assume it's an poly1d\n return shiftPoly(p.c,dx)\n #order is m\n #order of entry i is m-i\n #entry for order k is m-k\n m = len(p)-1\n p2 = [0]*len(p)\n for i in range(len(p)):\n k = m-i\n for j in range(k+1):\n #get the x^j'th coefficient \n p2[i+j] += p[i]*choose(k,j)*pow(dx,j)\n return poly1d(p2)\n\nclass ParabolicRamp1D:\n @staticmethod\n def __makePLP(x0,dx0,a1,v,a2,t1,t2,ttotal):\n s1 = poly1d([a1*0.5,dx0,x0])\n x1 = s1(t1)\n s2 = shiftPoly(poly1d([v,x1]), -t1)\n x2 = s2(t2)\n v2 = s2.deriv()(t2)\n s3 = shiftPoly(poly1d([a2*0.5,v2,x2]),-t2)\n return PiecewiseTrajectory([s1,s2,s3],[0,t1,t2,ttotal])\n\n @staticmethod\n def __makePP(x0,dx0,a1,a2,t1,ttotal):\n s1 = poly1d([a1*0.5,dx0,x0])\n x1 = s1(t1)\n v1 = s1.deriv()(t1)\n s2 = shiftPoly(poly1d([a2*0.5,v1,x1]),-t1)\n return PiecewiseTrajectory([s1,s2],[0,t1,ttotal])\n\n @staticmethod\n def solveBrakingTrajectory(x0,v0,dmax):\n if v0 > 0:\n return PiecewiseTrajectory([poly1d([-dmax*0.5,v0,x0])],[0,v0/dmax])\n else:\n return PiecewiseTrajectory([poly1d([dmax*0.5,v0,x0])],[0,-v0/dmax])\n\n @staticmethod\n def solveMinTime(xv0,xv1,amax,vmax,dmax=None):\n if dmax==None:\n dmax = amax\n x0 = xv0\n v0 = 0\n x1 = xv1\n v1 = 0\n if hasattr(xv0,\"__iter__\"):\n x0 = xv0[0]\n v0 = xv0[1]\n if hasattr(xv1,\"__iter__\"):\n x1 = xv1[0]\n v1 = xv1[1]\n\n #create new parabolic ramp with these characteristics\n if v0 != 0 or v1 != 0:\n raise ValueError(\"Haven't implemented nonzero velocities yet\")\n plp = ParabolicRamp1D. __solveMinTimePLP((x0,v0),(x1,v1),amax,vmax,dmax)\n if plp == None:\n (a1,t1,a2,ttotal) = ParabolicRamp1D.__solveMinTimePP((x0,v0),(x1,v1),amax,dmax)\n return ParabolicRamp1D.__makePP(x0,v0,a1,a2,t1,ttotal)\n else:\n (a1,t1,v,t2,a2,ttotal) = plp\n return ParabolicRamp1D.__makePLP(x0,v0,a1,v,a2,t1,t2,ttotal)\n\n @staticmethod\n def solveMinAccel(xv0,xv1,endtime,amax,vmax,dmax=None):\n if dmax==None:\n dmax = amax\n x0 = xv0\n v0 = 0\n x1 = xv1\n v1 = 0\n if hasattr(xv0,\"__iter__\"):\n x0 = xv0[0]\n v0 = xv0[1]\n if hasattr(xv1,\"__iter__\"):\n x1 = xv1[0]\n v1 = xv1[1]\n\n #create new parabolic ramp with these characteristics\n if v0 != 0 or v1 != 0:\n raise ValueError(\"Haven't implemented nonzero velocities yet\")\n plp = ParabolicRamp1D. __solveMinAccelPLP((x0,v0),(x1,v1),endtime,amax,vmax,dmax)\n if plp == None:\n (a1,t1,a2,ttotal) = ParabolicRamp1D.__solveMinAccelPP((x0,v0),endTime,(x1,v1),amax,dmax)\n return ParabolicRamp1D.__makePP(x0,v0,a1,a2,t1,ttotal)\n else:\n (a1,t1,v,t2,a2,ttotal) = plp\n return ParabolicRamp1D.__makePLP(x0,v0,a1,v,a2,t1,t2,ttotal) \n\n @staticmethod\n def __solveMinTimePP(xv0,xv1,amax,dmax):\n if xv0[1] != 0 or xv1[1] != 0:\n raise ValueError(\"Haven't implemented nonzero velocities yet\") \n if xv1[0] < xv0[0]:\n #swap\n (a1,t1,a2,ttotal) = ParabolicRamp1D.__solveMinTimePP((-xv0[0],-xv0[1]),(-xv1[0],-xv1[1]),amax,dmax)\n return (-a1,t1,-a2,ttotal)\n # y1(t) = x0 + t^2 a/2\n # y2(t) = x1 - (T-t)^2 d/2\n # y1'(t1) = y2'(t1) => a t1 = (T-t1)d\n # => (a+d)/d t1 = T => T-t1 = a/d t1\n # y1(t1) = y2(t1) => x0 + t1^2 a/2 = x1 - (T-t)^2 d/2\n # => t1^2 (a/2 + a^2/2d) = x1 - x0\n t1sq = (xv1[0]-xv0[0])*2.0/(amax + amax*amax/dmax)\n t1 = math.sqrt(t1sq)\n ttotal = (amax+dmax)/dmax*t1\n #print(\"a1=%f, t1=%f, a2=%f, T=%f\"%(amax,t1,-dmax,ttotal))\n return (amax,t1,-dmax,ttotal)\n\n @staticmethod\n def __solveMinTimePLP(xv0,xv1,amax,vmax,dmax):\n if xv0[1] != 0 or xv1[1] != 0:\n raise ValueError(\"Haven't implemented nonzero velocities yet\") \n if xv1[0] < xv0[0]:\n #swap\n (a1,t1,v,t2,a2,ttotal) = ParabolicRamp1D.__solveMinTimePLP((-xv0[0],-xv0[1]),(-xv1[0],-xv1[1]),amax,vmax,dmax)\n return (-a1,t1,-v,t2,-a2,ttotal)\n t1 = vmax/amax\n Tmt2 = vmax/dmax\n t2mt1 = (xv1[0]-xv0[0])/vmax - vmax*0.5/amax - vmax*0.5/dmax\n if t2mt1 < 0:\n return None\n #print(\"a1=%f, t1=%f, v=%f, t2=%f, a2=%f, T=%f\"%(amax,t1,vmax,t2mt1+t1,-dmax,Tmt2+t2mt1+t1))\n return (amax,t1,vmax,t2mt1+t1,-dmax,Tmt2+t2mt1+t1)\n\n @staticmethod\n def __solveMinAccelPP(xv0,xv1,endtime,amax,dmax):\n if xv0[1] != 0 or xv1[1] != 0:\n raise ValueError(\"Haven't implemented nonzero velocities yet\") \n if xv1[0] < xv0[0]:\n #swap\n (a1,t1,a2,ttotal) = ParabolicRamp1D.__solveMinAccelPP((-xv0[0],-xv0[1]),(-xv1[0],-xv1[1]),endtime,amax,dmax)\n return (-a1,t1,-a2,ttotal)\n # y1(t) = x0 + t^2 a/2\n # y2(t) = x1 - (T-t)^2 d/2\n # y1'(t1) = y2'(t1) => a t1 = (T-t1)d\n # constrain a/d = amax/dmax = y\n # => (a+d)/d t1 = T => t1 = d/(d+a)*T\n # y1(t1) = y2(t1) => x0 + t1^2 a/2 = x1 - (T-t1)^2 d/2\n t1 = endtime * dmax / (amax+dmax) #proportional to the ratio of dec/acc\n ttotal = endtime\n a = 2.0*(x1-x0)/(t1*t1*(1.+amax*amax/dmax*dmax))\n d = dmax*a/amax\n #print(\"a1=%f, t1=%f, a2=%f, T=%f\"%(a,t1,-d,ttotal))\n return (a,t1,-d,ttotal)\n\nclass ParabolicRampND:\n @staticmethod\n def solveBrakingTrajectory(x0,v0,dmax):\n if len(x0)!=len(v0):\n raise ValueError(\"Incorrect size of velocities\")\n if len(x0)!=len(dmax):\n raise ValueError(\"Incorrect size of deceleration bound\")\n segs = []*len(x0)\n for i in xrange(len(x0)):\n segs[i]=ParabolicRamp1D.solveBrakingTrajectory(x0[i],v0[i],dmax[i])\n return PiecewiseTrajectory.stack(segs)\n\n @staticmethod\n def solveMinTime(x0,v0,x1,v1,amax,vmax,dmax=None):\n if dmax==None:\n dmax = amax\n\n mins = [ParabolicRamp1D.solveMinTime((x0[i],v0[i]),(x1[i],v1[i]),amax[i],vmax[i],dmax[i]) for i in xrange(len(x0))]\n mints = [s.endTime for s in mints]\n mint = min(mints)\n imint = mints.index(mint)\n segs = []*len(x0)\n for i in xrange(len(x0)):\n if i != imint:\n segs[i] = ParabolicRamp1D.solveMinAccel((x0[i],v0[i]),(x1[i],v1[i]),mint,amax[i],vmax[i],dmax[i])\n else:\n segs[i] = mins[i]\n return PiecewiseTrajectory.stack(segs)\n\n @staticmethod\n def solveMinAccel(x0,v0,x1,v1,dt,amax,vmax,dmax=None):\n if dmax==None:\n dmax = amax\n\n segs = []*len(x0)\n for i in xrange(len(x0)):\n segs[i] = ParabolicRamp1D.solveMinAccel((x0[i],v0[i]),(x1[i],v1[i]),dt,amax[i],vmax[i],dmax[i])\n return PiecewiseTrajectory.stack(segs)\n\nclass RampSolver:\n def __init__(self,amax,vmax,dmax=None,type=\"mintime\"):\n self.amax = amax\n self.vmax = vmax\n self.type = type\n if self.type != \"mintime\" and self.type != \"fixedtime\":\n raise ValueError(\"Can only have mintime or fixedtime types\")\n if dmax == None:\n self.dmax = amax\n else:\n self.dmax = dmax\n\n def __call__(self,xv0,xv1,dt=None):\n if hasattr(self.amax,'__iter__'):\n if self.type == \"mintime\":\n return ParabolicRampND.solveMinTime(xv0[0],xv0[1],xv1[0],xv1[1],amax,vmax,dmax)\n else:\n return ParabolicRampND.solveMinAccel(xv0[0],xv0[1],xv1[0],xv1[1],dt,amax,vmax,dmax)\n else:\n if self.type == \"mintime\":\n return ParabolicRamp1D.solveMinTime(xv0,xv1,amax,vmax,dmax)\n else:\n return ParabolicRamp1D.solveMinAccel(xv0,xv1,dt,amax,vmax,dmax)\n\n\ndef testRamp():\n f = ParabolicRamp1D.solveMinTime(0.0,1.0,amax=3.0,vmax=5.0,dmax=5.0)\n print(\"Result: [%f,%f]\"%(f.startTime(),f.endTime()))\n plot = open(\"parabolicramp_test.csv\",\"w\")\n #plot.write(\"#time,value\\n\")\n #for t in arange(f.startTime(),f.endTime()+1.0,0.001):\n # plot.write(\"%f,%f\\n\"%(t,f(t)))\n #plot.close()\n plot.write(\"#time,f(t),v1,v2,v3\\n\")\n for t in arange(f.startTime()-1.0,f.endTime()+1.0,0.001):\n plot.write(\"%f,%f,\"%(t,f(t)))\n plot.write(','.join([str(s(t)) for s in f.segments]))\n plot.write('\\n')\n plot.close()\n\nif __name__==\"__main__\":\n testRamp()\n","sub_path":"Archived/Drivers/StaubliTX90L/TrajClient3/python/parabolicramp.py","file_name":"parabolicramp.py","file_ext":"py","file_size_in_byte":9679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"65562577","text":"#\n# Copyright 2020-2023 - Swiss Data Science Center (SDSC)\n# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and\n# Eidgenössische Technische Hochschule Zürich (ETHZ).\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Renku service project related job tests.\"\"\"\nimport pytest\n\nfrom renku.ui.service.jobs.delayed_ctrl import delayed_ctrl_job\nfrom renku.ui.service.serializers.cache import ProjectMigrateRequest\nfrom tests.utils import retry_failed\n\n\n@pytest.mark.service\n@pytest.mark.integration\n@retry_failed\ndef test_delay_migration_job(svc_client_cache, it_remote_old_repo_url_temp_branch, view_user_data):\n \"\"\"Verify delayed project migration.\"\"\"\n\n it_remote_repo_url, branch = it_remote_old_repo_url_temp_branch\n\n context = ProjectMigrateRequest().load(\n {\"git_url\": it_remote_repo_url, \"branch\": branch, \"skip_docker_update\": True}\n )\n\n _, _, cache = svc_client_cache\n renku_module = \"renku.ui.service.controllers.cache_migrate_project\"\n renku_ctrl = \"MigrateProjectCtrl\"\n\n user = cache.ensure_user(view_user_data)\n job = cache.make_job(\n user, job_data={\"ctrl_context\": {**context, \"renku_module\": renku_module, \"renku_ctrl\": renku_ctrl}}\n )\n\n updated_job = delayed_ctrl_job(context, view_user_data, job.job_id, renku_module, renku_ctrl)\n assert updated_job\n assert {\"docker_migrated\", \"was_migrated\", \"template_migrated\", \"messages\"}.issubset(\n updated_job.ctrl_result[\"result\"].keys()\n )\n assert updated_job.ctrl_result[\"result\"][\"was_migrated\"]\n","sub_path":"tests/service/jobs/test_project.py","file_name":"test_project.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"208098221","text":"import pygame as pg\nfrom . import load_screen\nfrom .. import constants as c\nfrom .. import music_sound\nfrom ..Classes import labels\n\n\nclass InputBox(load_screen.LoadScreen):\n\n \"\"\"\n State of Input Box\n \"\"\"\n\n def __init__(self):\n\n \"\"\"\n Initializes the state\n \"\"\"\n\n load_screen.LoadScreen.__init__(self)\n\n def startup(self, current_time, persist):\n\n \"\"\"\n Called every time the game's state becomes this one. Initializes\n certain values\n \"\"\"\n\n self.start_time = current_time\n self.persist = persist\n self.game_info = self.persist\n self.next = self.set_next_state()\n info_state = self.set_overhead_info_state()\n self.overhead_labels = labels.OverheadLabels(self.game_info, info_state)\n self.sound_manager = music_sound.Sound(self.overhead_labels)\n\n def set_next_state(self):\n\n \"\"\"\n Sets the next state\n \"\"\"\n\n return c.LOAD_SCREEN\n\n def set_overhead_info_state(self):\n\n \"\"\"\n Sets the state to send to the overhead info object\n \"\"\"\n\n return c.INPUT_BOX\n\n def update(self, surface, keys, current_time):\n\n \"\"\"\n Updates the Input Box\n \"\"\"\n name = \"\"\n font = pg.font.Font(None, 50)\n done = False\n while not done:\n for evt in pg.event.get():\n if evt.type == pg.KEYDOWN:\n if evt.unicode.isalpha():\n name += evt.unicode\n elif evt.key == pg.K_BACKSPACE:\n name = name[:-1]\n elif evt.key == pg.K_RETURN:\n done = True\n c.NOMBRE = name\n break\n elif evt.type == pg.QUIT:\n return\n\n surface.fill(c.BLACK)\n self.overhead_labels.update(self.game_info)\n self.overhead_labels.draw(surface)\n block = font.render(name, True, c.WHITE)\n rect = block.get_rect()\n rect.center = surface.get_rect().center\n surface.blit(block, rect)\n pg.display.flip()\n self.done = True\n","sub_path":"TRABAJO_FINAL_GRUPO_7/Code/States/input_box.py","file_name":"input_box.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"500049335","text":"# coding:utf-8\n\n\nclass Solution:\n\n def twoSum(self, nums, target):\n result = []\n count = len(nums)\n for i in range(count - 1):\n for j in range(i + 1, count):\n if nums[i] + nums[j] == target:\n result = [i, j]\n break\n return result\n\n\nsolution = Solution()\nnums = [2, 4, 3]\ntarget = 6\nret = solution.twoSum(nums, target)\nprint(ret)\n","sub_path":"src/0001-two-sum/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"522006628","text":"from aiohttp import web\nfrom random import randrange\n\nasync def serve_random_json(request):\n payload = {\n \"values\": [randrange(10) for x in range(0, 10)]\n }\n return web.json_response(payload)\n\nasync def greet(request):\n payload = {\n \"greeting\": \"hello\"\n }\n return web.json_response(payload)\n\nif __name__ == \"__main__\":\n print(\"wtf\")\n app = web.Application()\n app.router.add_get(\"/\", greet)\n app.router.add_get(\"/api/example\", serve_random_json)\n\n web.run_app(app, host=\"0.0.0.0\", port=3009)\n\n","sub_path":"backend/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"122741188","text":"#!/usr/bin/env python3\n\n\"\"\"\nCompare LBL and C-K gas transmittance\n\"\"\"\n\nimport os\nimport sys\nimport matplotlib.pyplot as plt\nfrom netCDF4 import Dataset\nfrom pyhdf.SD import SD, SDC\nfrom scipy.interpolate import interp1d\nimport numpy as np\nimport matplotlib.ticker as plticker\n\ndef get_rsr(inFile):\n \"\"\"\n Read in OCI RSR File\n \"\"\"\n hdf = SD(inFile, SDC.READ)\n rsr = hdf.select('RSR')[:]\n wav_rsr = hdf.select('rsrwave')[:]\n wav_oci = hdf.select('wave')[:]\n hdf.end()\n\n return rsr.T, wav_rsr, wav_oci\n\n#------------------------------------ M A I N ------------------------------------\n\nif __name__ == \"__main__\":\n iscan = 600\n icross = 1000\n inRoot = '../outputs'\n lblFile = '{}/hyperTest_LBL_Thuillier_g5nr.nc4'.format(inRoot)\n inRoot = '/nobackup/PACE/LevelC2/Y2006/M03/D24/v2.0'\n geoFile = '{}/OCI2020084005000.L1B_PACE.nc'.format(inRoot)\n inRoot = '/nobackup/PACE/LevelC/Y2006/M03/D24/v2.0'\n ckFile = '{}/pace-g5nr.lc.gas.20060324_005000.nc4'.format(inRoot)\n rsrFile = 'OCI_RSR_v0.hdf'\n outFile_comparison = 'rsr_v0/l1b_trans_comparison.pdf'\n outFile_difference = 'rsr_v0/l1b_trans_difference.pdf'\n outFile_RSR = 'rsr_v0/l1b_trans_RSR.pdf'\n\n lbl = Dataset(lblFile)\n ck = Dataset(ckFile)\n geo = Dataset(geoFile)\n\n # get angle\n vza = geo.groups['geolocation_data'].variables['sensor_zenith'][iscan,icross]\n cvza = np.cos(np.radians(vza))\n\n # get LBL trans\n alpha_lbl = lbl.variables['ROD'][:]\n toa_lbl = np.exp(-1.*alpha_lbl/cvza)\n wav_lbl = np.array(lbl.variables['channels'][:])\n\n # lbl solar irradiance\n F0 = lbl.variables['solar_irradiance'][:]\n\n # flip this so goes from low to high wavelength\n toa_lbl = toa_lbl[::-1]\n wav_lbl = wav_lbl[::-1]\n F0 = F0[::-1]\n\n # get CK transmittance\n # already integrated over RSR\n wav_blue = ck.variables['blue_wavelength'][:]\n wav_red = ck.variables['red_wavelength'][:]\n wav_swir = ck.variables['SWIR_wavelength'][:]\n\n t_blue = ck.variables['TRANS_H2O_blue'][iscan,icross,:]\n t_red = ck.variables['TRANS_H2O_red'][iscan,icross,:]\n t_swir = ck.variables['TRANS_H2O_SWIR'][iscan,icross,:]\n\n ck_smooth = np.ma.append(t_blue,t_red)\n ck_smooth = np.ma.append(ck_smooth,t_swir)\n wav_ck = np.append(wav_blue,wav_red)\n wav_ck = np.append(wav_ck,wav_swir)\n\n # integrate over RSR\n # Read in OCI RSR\n inFile = '../{}'.format(rsrFile)\n rsr, wav_rsr, wav_oci = get_rsr(inFile)\n noci = len(wav_oci)\n rsr_f = interp1d(wav_rsr,rsr,kind='linear',fill_value=\"extrapolate\")\n\n # smooth lbl\n istart_lbl = 1\n rsr_int = rsr_f(wav_lbl)\n lbl_smooth = np.ma.masked_all(noci)\n for ich in range(istart_lbl,noci):\n norm = np.trapz(rsr_int[ich,:]*F0,wav_lbl)\n if norm != 0:\n lbl_smooth[ich] = np.trapz(F0*toa_lbl*rsr_int[ich,:],wav_lbl)/norm\n\n\n # put in same order as L1B\n # realias 1038 to 1040\n i = wav_oci == 1038\n wav_oci[i] = 1040\n lbl_l1b = np.ma.zeros(ck_smooth.shape)\n for ich, ch in enumerate(wav_oci):\n for i,lch in enumerate(wav_ck):\n if float(ch) == lch:\n lbl_l1b[i] = lbl_smooth[ich]\n lbl_l1b.mask = ck_smooth.mask\n sys.exit() \n # ------\n # plotting part comparison\n # -------\n loc = plticker.MultipleLocator(base=50.0)\n xlim = [490,wav_lbl.max()]\n # create figure\n fig = plt.figure()\n\n ax = fig.add_subplot(2,1,1)\n\n # lbl\n ax.plot(wav_lbl,toa_lbl,label='LBL')\n # ck\n ax.plot(wav_ck,toa_ck,'o',label='C-K',markersize=1)\n\n # formatting\n ax.legend()\n ax.set_xlabel('wavelength [nm]')\n ax.set_ylabel('TOA Reflectance')\n ax.set_title('Original')\n ax.set_xlim(xlim)\n\n\n # ---- smoothed ----\n ax = fig.add_subplot(2,1,2)\n\n # lbl\n ax.plot(wav_oci,lbl_smooth,'o',label='LBL',markersize=2)\n # ck\n ax.plot(wav_oci,ck_smooth,'o',label='C-K',markersize=1)\n\n # formatting\n ax.set_xlabel('wavelength [nm]')\n ax.set_ylabel('TOA Reflectance')\n ax.set_title('Smooth')\n ax.set_xlim(xlim)\n\n plt.tight_layout()\n plt.savefig(outFile_comparison,bbox_inches='tight')\n# plt.show()\n plt.close()\n\n # ------\n # plotting part RSR\n # -------\n\n # create figure\n fig = plt.figure()\n rsr_int = rsr_f(wav_lbl)\n ax = fig.add_subplot(2,1,1)\n for ich in range(noci):\n ax.plot(wav_lbl,rsr_int[ich,:],'k-')\n\n #formatting\n ax.set_xlabel('wavelength [nm]')\n ax.set_ylabel('OCI Spectral Response Function')\n ax.set_xlim((550,900))\n plt.tight_layout()\n plt.savefig(outFile_RSR,bbox_inches='tight')\n# plt.show()\n plt.close()\n\n # -------\n # plotting part difference\n # --------\n\n # create figure\n fig = plt.figure()\n\n # smooth\n ax = fig.add_subplot(2,1,1)\n diff = 100.*(ck_smooth-lbl_smooth)/lbl_smooth\n ax.plot(wav_oci,diff,'o',label='smooth',markersize=1)\n ax.plot(xlim,[-0.5,-0.5],'k:',linewidth=0.5)\n ax.plot(xlim,[0.5,0.5],'k:',linewidth=0.5)\n\n # formatting\n ax.set_xlabel('wavelength [nm]')\n ax.set_ylabel('CK - LBL [%]')\n ax.set_title('Smooth')\n ax.set_xlim(xlim)\n ax.yaxis.grid()\n ax.xaxis.set_minor_locator(loc)\n plt.tight_layout()\n plt.savefig(outFile_difference,bbox_inches='tight')\n# plt.show()\n plt.close()\n","sub_path":"src/Components/missions/PACE/hyperTest/plotting/compare_lbl_l1b_trans.py","file_name":"compare_lbl_l1b_trans.py","file_ext":"py","file_size_in_byte":5298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"651440700","text":"import tkinter as tk\nfrom tkinter import font as tkfont\nimport main as M\nfrom tzlocal import get_localzone\n\nclass App(tk.Tk):\n\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n\n self.title('Maastricht University Events')\n self.geometry('800x800')\n\n self.title_font = tkfont.Font(family='Helvetica', size=18, weight=\"bold\")\n self.header_font = tkfont.Font(family='Helvetica', size=14)\n self.paragraph_font = tkfont.Font(family='Helvetica', size=11)\n\n tk.Label(text=\"Event Selector\", font=self.title_font, anchor=\"w\").grid(row=0, column=0)\n tk.Label(text=\"Select events of Maastricht University\", font=self.header_font).grid(row=1, column=0)\n\n tk.Label(text=\"Select the organisation\", font=self.title_font).grid(row=0, column=0)\n\n scrollbar = tk.Scrollbar(self)\n\n self.listbox = tk.Listbox(self, name=\"organisationsListbox\", selectmode=tk.MULTIPLE, selectbackground='black', activestyle='none', width=50)\n self.listbox.bind('<>', self.selectEvents)\n self.listbox.config(yscrollcommand=scrollbar.set)\n self.listbox.grid(row=2, column=0)\n\n self.available_organisation = {\n \"Aachen-Maastricht Institute for Biobased Materials\": \"8054\",\n \"Alumni\": \"5038\",\n \"Campus Brussels\": \"5632\",\n \"Campus Venlo\": \"8154\",\n \"Department of Data Science and Knowledge Engineering\": \"5500\",\n \"Faculty of Arts and Social Sciences\": \"158\",\n \"Faculty of Health, Medicine and Life Sciences\": \"3566\",\n \"Faculty of Law\": \"160\",\n \"Faculty of Science and Engineering\": \"173\",\n \"Maastricht Science Programme\": \"169\",\n \"School of Business and Economics\": \"159\",\n \"Sciences\": \"2957\",\n \"University College Maastricht\": \"5760\",\n \"University College Venlo\": \"4081\"\n }\n\n for org in self.available_organisation.keys():\n self.listbox.insert(tk.END, org)\n\n scrollbar.config(command=self.listbox.yview)\n scrollbar.grid(row=2, column=1, sticky=tk.N+tk.S)\n\n vsb = tk.Scrollbar(orient=\"vertical\")\n self.text = tk.Text(self, width=90, height=20, yscrollcommand=vsb.set)\n vsb.config(command=self.text.yview)\n self.text.grid(row=4, column=0, pady=(65, 75))\n vsb.grid(row=4, column=1, sticky=tk.N+tk.S)\n\n def selectEvents(self, evt):\n\n #Reset the text field\n self.text.delete(1.0,tk.END)\n\n w = evt.widget\n\n if len(w.curselection()) == 0:\n return\n\n orgs = []\n for org in w.curselection():\n index = int(org)\n value = w.get(index)\n orgs.append(self.available_organisation[value])\n\n initial_url = 'https://www.maastrichtuniversity.nl/events'\n for org in orgs:\n initial_url += '/organisation/'+str(org)\n initial_url += '?page=0'\n\n self.events = M.scrapeEvents(initial_url)\n self.selected_events = [tk.IntVar() for _ in range(len(self.events))]\n\n tk.Label(text=\"Events\", font=self.header_font).grid(row=3, column=0, pady=(20, 10))\n\n for i, event in enumerate(self.events):\n bg = 'grey'\n if i % 2 == 0:\n bg = 'white'\n\n txt = format('Subject: ', '<15s')+event['subject']+'\\n'+ \\\n format('Start time: ', '<15s')+event['start_time'].astimezone(get_localzone()).strftime('%d %b %Y %H:%M')+'\\n'+ \\\n format('End time:' , '<15s')+event['end_time'].astimezone(get_localzone()).strftime('%d %b %Y %H:%M')+'\\n'+ \\\n format('URL to event: ', '<15s')+event['total_url']\n\n\n cb = tk.Checkbutton(text=txt, bg=bg, font=self.paragraph_font, variable=self.selected_events[i], anchor=\"w\", width=77, justify=tk.LEFT)\n self.text.window_create(\"end\", window=cb)\n self.text.insert(\"end\", \"\\n\") # to force one checkbox per line\n\n self.send_btn = tk.Button(text=\"Create event calendar\", font=self.paragraph_font, command=self.makeCalendar)\n self.send_btn.grid(row=5, column=0)\n\n def makeCalendar(self):\n tmp_events = [e.get() for e in self.selected_events]\n actual_events = []\n for i, evt in enumerate(tmp_events):\n if bool(evt) == 1:\n actual_events.append(self.events[i])\n\n M.createCalendar(actual_events)\n\n tmp_lb = tk.Label(text='Your event calendar has been created! Check for a .ics-file in the folder.', font=self.paragraph_font)\n tmp_lb.grid(row=6, column=0)\n tmp_lb.after(3000, lambda:tmp_lb.destroy())\n\n\n\ndef printEvent(event):\n print(format('Subject:', '<15s'), event['subject'])\n print(format('Start time:', '<15s'), event['start_time'].astimezone(get_localzone()).strftime('%d %b %Y %H:%M'))\n print(format('End time:', '<15s'), event['end_time'].astimezone(get_localzone()).strftime('%d %b %Y %H:%M'))\n try:\n print(format('Description:', '<15s'), event['description'])\n except:\n pass\n print(format('URL to event:', '<15s'), event['total_url'])\n print()\n\nif __name__ == \"__main__\":\n app = App()\n app.mainloop()\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":5219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"191354412","text":"#EIA Inventory Data for Crude\nimport json\nimport requests\nimport os\n\nurl_eia = os.environ.get('EIA_API_CRUDE')\nurl_database = os.environ.get('LINK_OIL_INVENTORY')\ntoken = os.environ.get('PA_API_TOKEN')\n\n#Retrieve crude inventory data from EIA website\nurl = url_eia\nresp = requests.get(url)\n\n#Format data into useable json format\ndata_crude = json.loads(resp.text)\n\n#Check data in database against latest data from EIA and update if needed\n#Most recent datapoint and format date to be same as in database\nyear = data_crude['series'][0]['data'][0][0][:4]\nmonth = data_crude['series'][0]['data'][0][0][4:6]\nday = data_crude['series'][0]['data'][0][0][6:8]\ncurrent_date = year + '-' + month + '-' + day\n\nprint('EIA crude inventory: ', data_crude['series'][0]['data'][0][1])\nprint('EIA date: ', current_date)\n\n#Get the last datapoint from database\nurl = url_database\ndata = requests.get(url)\ninventory = json.loads(data.text)\nlast_date = inventory[-1]['date']\nprint('database date: ', last_date)\n\n#Update the database if current_date != last_date\nif current_date == last_date:\n print('current_date:', current_date, 'is equal to last_date:', last_date, '- Database not updated')\n\nelse:\n headers = {'Authorization': token}\n\n payload = {\n 'date': current_date,\n 'oil_inventory': data_crude['series'][0]['data'][0][1],\n }\n\n resp = requests.post(url, headers=headers, data=payload)\n print(resp)\n","sub_path":"EIA_Inventory_Crude.py","file_name":"EIA_Inventory_Crude.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"58590362","text":"import os\nimport cv2\nimport sys\nimport pickle\n\nimport numpy as np\nimport torch.utils.data as data\n\nfrom PIL import Image\nfrom tqdm import tqdm\n\n# adapted VOC eval script to compute detection APs\n# from .klass_voc_eval import voc_eval\nfrom .voc_eval import voc_eval\ndef pickle_load(fname):\n with open(fname, 'rb') as pf:\n data = pickle.load(pf)\n print('Loaded {}.'.format(fname))\n return data\n\ndef pickle_save(fname, data):\n with open(fname, 'wb') as pf:\n pickle.dump(data, pf)\n print('Saved to {}.'.format(fname))\n\nclass PP(data.Dataset):\n\n \"\"\"Loader for Microsoft's Common Objects in Context (MS-COCO) dataset\n\n Arguments:\n\n \"\"\"\n\n def __init__(self, params, image_set, preproc=None, task='general', caching=True, run=False):\n self.params = params\n\n if image_set not in ['train', 'val', 'test']:\n sys.exit('Unknown image_set %s'%(image_set))\n\n self.image_set = image_set # train/val/test\n self.dataset = params['name'] + '_' + image_set\n self.data_path = params['data_path']\n self.min_size = params['min_size'] # min object size, discarded if smaller\n\n self.preproc = preproc\n self.task = task\n self.caching = caching\n\n # if 'test' will only return image in get_item, no annotation\n self.phase = image_set # train/val/test\n\n if task in params:\n # self.ann_folder = params[task]['folder']\n self.classes = params[task]['classes'] # e.g., params['vehicle']['classes']\n self.labels = params[task]['labels']\n else:\n sys.exit('Unknown task: %s'%(task))\n\n self.cls2ind = dict(zip(self.classes, range(len(self.classes))))\n self.ind2cls = {v:k for k,v in self.cls2ind.items() }\n\n print('\\n PP DATASET:', self.dataset, self.data_path)\n print('Task:', task)\n print(self.classes)\n print(self.labels)\n\n if not run: \n if self.params['reload'] or not self.load_from_cache():\n self.load_image_paths_and_annots()\n # self.image_list: full path of all images in the dataset\n # self.annotations: dict to store all annotations, keyed on full image path\n print('Number of images:', len(self.image_list))\n\n def __len__(self):\n return len(self.image_list)\n\n def num_classes(self):\n return len(self.classes)\n\n # def image_path(self, video_name, img_file):\n # return self.data_path + 'images/' + video_name + '/' + img_file\n\n def __getitem__(self, index):\n image_path = self.image_list[index]\n img = cv2.imread(image_path, cv2.IMREAD_COLOR)\n\n # return only the image\n if self.phase == 'test':\n if self.preproc is not None:\n img = self.preproc(img)\n return img\n\n # numpy array of [[xmin,ymin, xmax,ymax, class_id] ... ]\n objects = self.annotations[image_path]\n\n if self.preproc is not None:\n img, objects = self.preproc(img, objects)\n\n return img, objects\n\n\n def pull_image(self, index):\n '''Load and return image at 'index' as OpenCV image\n '''\n image_path = self.image_list[index]\n return cv2.imread(image_path, cv2.IMREAD_COLOR)\n\n def pull_images(self, index, batch_size):\n '''Load and return image at 'index' as OpenCV image\n '''\n assert index + batch_size <= len(self.image_list), 'pull_images(): attempting to pull more images than available!'\n result = []\n impaths = []\n for i in range(index, index+batch_size):\n image_path = self.image_list[i]\n result.append( cv2.imread(image_path, cv2.IMREAD_COLOR) )\n impaths.append( image_path )\n return result, impaths\n # return cv2.imread(image_path, cv2.IMREAD_COLOR)\n\n def load_image_paths_and_annots(self):\n set_file = os.path.join(self.data_path, '{}.txt'.format(self.dataset) )\n label_dir = os.path.join(self.data_path, 'labels')\n # set_file = self.data_path + 'sets/' + self.dataset + '.txt'\n with open(set_file) as fp:\n lines = fp.readlines()\n\n self.annotations = {}\n for line in tqdm(lines):\n image_path = line.strip()\n image_id = os.path.basename( image_path ).split('.')[0]\n label_path = os.path.join(label_dir, '{}.txt'.format(image_id))\n assert os.path.exists(image_path),'Img {} does not exist!'.format(image_path)\n assert os.path.exists(label_path),'Label file {} does not exist!'.format(label_path)\n iw, ih = Image.open(image_path).size\n with open(label_path, 'r') as f:\n label_lines = [l.strip() for l in f.readlines()]\n annot_boxes = []\n for lab in label_lines:\n classid, x_norm, y_norm, w_norm, h_norm = lab.split()\n w = float(w_norm) * iw\n h = float(h_norm) * ih\n x = float(x_norm) * iw\n y = float(y_norm) * ih\n\n xmin = max(0.0, x - w/2.)\n ymin = max(0.0, y - h/2.)\n xmax = min(iw-1.0, x + w/2.)\n ymax = min(ih-1.0, y +h/2.)\n if xmax - xmin < self.min_size[1]: continue\n if ymax - ymin < self.min_size[0]: continue\n annot_boxes.append([ xmin, ymin, xmax, ymax, int(classid)+1 ])\n \n if len( annot_boxes ) == 0: continue\n \n self.annotations[image_path] = np.array(annot_boxes)\n \n self.image_list = list(self.annotations.keys())\n\n if self.caching and self.params['cache_dir']:\n pickle_save(self.cache_file_path(), (self.image_list, self.annotations))\n\n def cache_file_path(self):\n if not self.params['cache_dir']: return ''\n\n if not os.path.exists(self.params['cache_dir']):\n os.makedirs(self.params['cache_dir'], exist_ok=True)\n print('os.makedirs:', self.params['cache_dir'])\n\n return self.params['cache_dir'] + self.dataset + '-' + self.task + '.pkl'\n\n def load_from_cache(self):\n if not self.params['cache_dir']: # None\n return False\n\n cache_file = self.cache_file_path()\n if os.path.exists(cache_file):\n self.image_list, self.annotations = pickle_load(cache_file)\n print('Loaded annotations from cache', cache_file)\n print('Number of images with annotations:', len(self.image_list))\n return True\n\n return False\n\n def evaluate_detections(self, detections_dict):\n # raise NotImplementedError('TODO: we need to eval coco and not voc')\n aps = []\n print('--------------------------------')\n print('Class : \\t AP (100)')\n print('--------------------------------')\n for cid, classname in enumerate(self.classes):\n if classname == '__background__': continue\n\n rec, prec, ap = voc_eval(detections_dict, self.annotations, cid, ovthresh=0.5)\n\n aps += [ap]\n print('{} : \\t{:.2f}'.format(classname, 100*ap))\n\n mAP = 100*np.mean(aps)\n print('--------------------------------')\n print('mAP: \\t{:.2f}'.format(mAP))\n print('--------------------------------')\n\n return aps, mAP\n\n\n## test\n# if __name__ == '__main__':\n#","sub_path":"datasets_handler/pp.py","file_name":"pp.py","file_ext":"py","file_size_in_byte":7410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"488842928","text":"import numpy as np\nimport pandas as pd\nimport config\nfrom sklearn import ensemble\nfrom sklearn import metrics\nfrom sklearn import model_selection\n\nif __name__ == \"__main__\":\n # read the training data\n df = pd.read_csv(config.TRAINING_FILE)\n\n # predictors\n X = df.drop(\"price_range\", axis=1).values\n y = df.price_range.values\n\n # define model here, n_jobs=-1 => use all cores\n classifier = ensemble.RandomForestClassifier(n_jobs=-1)\n\n # define a grid of parameters (dictionaries)\n param_grid = {\n \"n_estimators\": [100, 200, 250, 300, 400, 500],\n \"max_depth\": [1,2,5, 7, 11, 15],\n \"criterion\": [\"gini\", \"entropy\"]\n }\n\n # initialize grid search\n # cv = 5, we are using 5 fold cv (not stratified)\n\n model = model_selection.GridSearchCV(\n estimator=classifier,\n param_grid = param_grid,\n scoring = \"accuracy\",\n verbose = 10,\n n_jobs =-1,\n cv = 5)\n\n # fit the model\n model.fit(X,y)\n print(f\"Best Score: {model.best_score_}\")\n print(\"Best parameters set:\")\n best_parameters = model.best_estimator_.get_params()\n for param_name in sorted(param_grid.keys()):\n print(f\"\\t{param_name}: {best_parameters[param_name]}\")\n\n ","sub_path":"src/mobile-price-range/rf_grid_search.py","file_name":"rf_grid_search.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"543502948","text":"'''\nhttps://www.interviewbit.com/problems/coin-sum-infinite/\nCoin Sum Infinite\n\nYou are given a set of coins S. In how many ways can you make sum N assuming you have infinite amount of each coin in the set.\n\nNote : Coins in set S will be unique. Expected space complexity of this problem is O(N).\n\nExample :\n\nInput :\n\tS = [1, 2, 3]\n\tN = 4\n\nReturn : 4\n\nExplanation : The 4 possible ways are\n{1, 1, 1, 1}\n{1, 1, 2}\n{2, 2}\n{1, 3}\nNote that the answer can overflow. So, give us the answer % 1000007\n'''\n\n\nclass Solution:\n # @param A : list of integers\n # @param B : integer\n # @return an integer\n def coinchange2(self, A, B):\n if type(B) is not int or B < 0:\n return 0\n mem = [0] * (B + 1)\n mem[0] = 1\n for i in range(len(A)):\n amount = A[i]\n for j in range(B + 1):\n if j - amount >= 0 and j - amount < len(mem):\n mem[j] += mem[j - amount]\n return mem[-1] % 1000007\n\n\n\nprint(Solution().coinchange2([1, 2, 3], 6))","sub_path":"coin_sum_infinite.py","file_name":"coin_sum_infinite.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"416464270","text":"\"\"\" taylor_expansion.py\nTaylor Series Approximation for given function using sympy notation.\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sympy.functions import sin,cos,exp\nimport sympy as sy\nplt.rcParams[\"figure.figsize\"] = (12,8) # w, h\n\ndef factorial(k):\n if k == 0:\n return 1\n acc = k\n while k >1 :\n k -= 1\n acc = acc * k\n return acc\n\n\ndef taylor(func, x_0, n):\n \"\"\"\n func: function to be expanded\n x_0: about x_0\n n: order\n \"\"\"\n x = sy.Symbol('x')\n p = 0;\n # n denotes upper index\n for i in range(n+1):\n p += (func.diff(x,i).subs(x,x_0)) * ((x-x_0)**i) / factorial(i)\n return p\n\n\n# approximation of first 'n' terms\ndef plot(function, x_upper_bound=None, appr_order=None, no_approx=False):\n \"\"\"\n function: simpy function to be passed\n appr_order: degree of approximation polynom\n x_upper_bound: Boundaries of x during the visualization \n no_approx: Only plot the original function, mutually exclusive with above arguments\n \"\"\"\n x = sy.Symbol('x')\n if not no_approx:\n # approximation function,\n appr_function = taylor(function, 0, appr_order)\n x1 = np.linspace(-1 * x_upper_bound, x_upper_bound)\n y1 = []\n for k in x1:\n y1.append(appr_function.subs(x,k))\n plt.plot(x1,y1, label=\"approximation value\")\n plt.suptitle('Taylor Series Expansion for '+ str(function) +' \\n order: ' + str(appr_order))\n\n x_2 = np.linspace(-1*x_upper_bound,x_upper_bound)\n y_2 = []\n for k in x_2:\n y_2.append(function.subs(x,k))\n\n plt.plot(x_2, y_2, label=\"real value\")\n plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n return plt.show()\n\ndef demo():\n x = sy.Symbol('x')\n plot(appr_order=3, x_upper_bound=4, function=sin(x))\n plot(appr_order=3, x_upper_bound=4, function=exp(x))\n plot(appr_order=5, x_upper_bound=4, function=x**2+x**3-3)\n plot(appr_order=7, x_upper_bound=10, function=sin(x))\n \n\nif __name__ == '__main__':\n demo()\n","sub_path":"taylor_expansion.py","file_name":"taylor_expansion.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"107992825","text":"import os\nfrom pathlib import Path\nimport re\nfrom tensorflow import keras, logging\n\nimport vanilla_convolutional_autoencoder\nimport variational_convolutional_autoencoder\n\nfrom dotenv import load_dotenv\nload_dotenv()\n\n# logging.set_verbosity(logging.ERROR)\n\n# Generators\ntrain_generator = keras.preprocessing.image.ImageDataGenerator(\n data_format='channels_last',\n rescale=1. / 255,\n rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True\n)\n\ntrain_batches = train_generator.flow_from_directory(\n batch_size=32,\n directory=os.getenv('DATASET_DOWNLOAD_PATH')+'/Images/train',\n target_size=[224, 224],\n class_mode='input'\n)\n\nval_generator = keras.preprocessing.image.ImageDataGenerator(\n data_format='channels_last',\n rescale=1. / 255,\n)\n\nval_batches = val_generator.flow_from_directory(\n batch_size=32,\n directory=os.getenv('DATASET_DOWNLOAD_PATH')+'/Images/validation',\n target_size=[224, 224],\n class_mode='input'\n)\n\n# Callback to save weights, based on val_acc\nmodel_checkpoint_callback = keras.callbacks.ModelCheckpoint(\n './checkpoints/{epoch:02d}_{val_loss:.4f}.h5',\n save_weights_only=False,\n verbose=1,\n monitor='val_loss',\n save_best_only=True,\n mode='min'\n)\n\n# Callbackto plot data on TensorBoard\ntensorboard_callback = keras.callbacks.TensorBoard(\n log_dir='./logs/autoencoder',\n histogram_freq=0,\n batch_size=32\n)\n\n# Callback to reduce learning rate after plateaus\nreduce_lr_callback = keras.callbacks.ReduceLROnPlateau(\n monitor='val_acc',\n factor=0.5,\n patience=5,\n min_lr=1e-6\n)\n\nearly_stopping_callback = keras.callbacks.EarlyStopping(\n monitor='val_loss',\n patience=20,\n mode='min',\n)\n\n# Model\ninput_shape = [224, 224, 3]\nlatent_space_shape = [100]\n\n# autoencoder = vanilla_convolutional_autoencoder.get_model(input_shape, latent_space_shape)\nautoencoder = variational_convolutional_autoencoder.get_model(input_shape, latent_space_shape)\n\nautoencoder.summary()\n\nif Path('./checkpoints/').exists():\n epoch_number_array = []\n val_loss_array = []\n file_name_array = []\n for file in os.listdir('./checkpoints/'):\n epoch, val_loss = re.search(r'(\\d\\d)_(\\d\\.\\d{4})\\.h5', file).group(1,2)\n epoch_number_array.append(int(epoch))\n val_loss_array.append(float(val_loss))\n file_name_array.append(file)\n\n if len(val_loss_array) == 0:\n INITIAL_EPOCH = 0\n else:\n lowest_loss = val_loss_array.index(min(val_loss_array))\n INITIAL_EPOCH = epoch_number_array[lowest_loss]\n model_checkpoint_callback.best = val_loss_array[lowest_loss]\n autoencoder.load_weights('./checkpoints/'+file_name_array[lowest_loss])\nelse:\n os.makedirs('./checkpoints/')\n INITIAL_EPOCH = 0\n\n# Prepare model to run\nautoencoder.compile(optimizer = keras.optimizers.Adam(), loss = 'kullback_leibler_divergence')\n\n# Starts training the model\nautoencoder.fit_generator(train_batches,\n epochs=100,\n verbose=1,\n validation_data=val_batches,\n validation_steps=len(val_batches),\n # Keras multiprocessing has a memory leak, don't use for now\n # use_multiprocessing=True,\n # workers=4,\n callbacks=[model_checkpoint_callback, tensorboard_callback, reduce_lr_callback, early_stopping_callback]\n )\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"164397211","text":"from analysis.util import csv_parser, d_sort, format_as_date\nfrom analysis.data_manager import DataManager\n\n\nclass Application(object):\n def __init__(self):\n self.dm = DataManager()\n\n def run(self, args):\n symbol = args[1]\n start = format_as_date(args[2])\n end = format_as_date(args[3])\n data = self.dm.fetch_range(symbol, start, end)\n res = thirty_day_average_high_low_spread(symbol, data)\n print(res)\n\n\ndef thirty_day_average_high_low_spread(symbol, data):\n for item in data:\n #do something\n continue\n return data\n\n\ndef single_day_worker(args):\n all_stocks = csv_parser(args[1])\n\n keys = list(all_stocks.keys())\n for key in keys:\n if int(all_stocks[key][\"vol\"]) < 500000:\n del all_stocks[key]\n continue\n\n if float(all_stocks[key][\"close\"]) > 10.0:\n del all_stocks[key]\n continue\n\n del all_stocks[key][\"date\"]\n\n stock_list_alphabetical = d_sort(all_stocks.keys(), all_stocks)\n\n output = \"\"\n\n for stock in stock_list_alphabetical:\n output += (str(stock[\"ticker\"] + \"\\t\" +\n stock[\"close\"] + \"\\t\" + stock[\"vol\"]) + \"\\n\")\n\n output += str(len(all_stocks)) + \" stocks.\"\n\n ofp = open(\"pennies.txt\", \"w\")\n ofp.write(output)\n ofp.close()\n","sub_path":"analysis/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"453088343","text":"def isIsomorphic1(s, t):\n d1,d2 = {},{}\n for i,val in enumerate(s):\n d1[val] = d1.get(val,[]) + [i]\n for i,val in enumerate(t):\n d2[val] = d2.get(val,[]) + [i]\n return sorted(d1.values()) == sorted(d2.values())\n\n\nres = isIsomorphic1(\"egg\",\"bar\")\nprint(res)","sub_path":"leetcode205.py","file_name":"leetcode205.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"33700420","text":"#!/usr/bin/python3\n# coding=utf-8\n#\n# Copyright © 2018 UnravelTEC\n# Michael Maier \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n# If you want to relicense this code under another license, please contact info+github@unraveltec.com.\n\n# hints from https://www.raspberrypi.org/forums/viewtopic.php?p=600515#p600515\n\nimport time,math\nimport sys\nimport os, signal\nimport paho.mqtt.client as mqtt\nimport subprocess \nimport json\n\nimport sdnotify\n\nfrom argparse import ArgumentParser, RawTextHelpFormatter\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n sys.stderr.flush()\n\nparser = ArgumentParser(description='send iostats output as ut mqtt messages.\\n\\nDefaults in {curly braces}',formatter_class=RawTextHelpFormatter)\nparser.add_argument(\"-o\", \"--brokerhost\", dest=\"brokerhost\", type=str, default='localhost',\n help=\"subscribe to mqtt broker (addr: {localhost})\", metavar=\"addr\")\nparser.add_argument(\"-i\", \"--interval\", dest=\"interval\", type=float, default=3,\n help=\"measurement interval in s (float, default 3)\", metavar=\"x\")\n\nparser.add_argument(\"-D\", \"--debug\", dest=\"debug\", action='store_true',\n help=\"print debug messages\")\nargs = parser.parse_args()\n\nMEAS_INTERVAL = args.interval\n\nn = sdnotify.SystemdNotifier()\n\nhostname = os.uname()[1]\ntopic = hostname + '/system/io'\nprint('topic: ' + topic)\n\nbrokerhost = args.brokerhost\n\nDEBUG = args.debug\n\ndef exit_gracefully(a,b):\n print(\"exiting gracefully...\")\n client.disconnect()\n exit(0)\n\ndef exit_hard():\n print(\"exiting hard...\")\n exit(1)\n\nsignal.signal(signal.SIGINT, exit_gracefully)\nsignal.signal(signal.SIGTERM, exit_gracefully)\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n\nclient = mqtt.Client(client_id=\"iostats\", clean_session=True)\nclient.connect(brokerhost,1883,60)\nclient.on_connect = on_connect\n\ndef mqttReconnect():\n print('attempting reconnect')\n success = False\n while not success:\n try:\n client.reconnect()\n success = True\n print('reconnect successful')\n except ConnectionRefusedError as e:\n eprint('ConnectionRefusedError', e, '\\nnext attempt in 3s')\n time.sleep(3)\n\nMQTT_ERR_SUCCESS = mqtt.MQTT_ERR_SUCCESS\ndef mqttPub(topic, payload_json):\n DEBUG and print(payload_json)\n ret = client.publish(topic, json.dumps(payload_json, separators=(',', ':'), sort_keys=True), retain=True)\n if ret[0] == MQTT_ERR_SUCCESS:\n n.notify(\"WATCHDOG=1\")\n elif ret[0] == mqtt.MQTT_ERR_NO_CONN:\n eprint('no mqtt connnection')\n mqttReconnect()\n else:\n eprint('mqtt publishing not successful,', ret)\n\nwhile 1:\n run_started_at = time.time()\n \n iostats = json.loads(subprocess.check_output(['iostat', '-y', '-d', '-o', 'JSON', '-x']).decode('utf-8'))\n if not 'sysstat' in iostats or not 'hosts' in iostats['sysstat'] or not len(iostats['sysstat']['hosts']) or not 'statistics' in iostats['sysstat']['hosts'][0] or not len(iostats['sysstat']['hosts'][0]['statistics']) or not 'disk' in iostats['sysstat']['hosts'][0]['statistics'][0] or not len(iostats['sysstat']['hosts'][0]['statistics'][0]['disk']):\n eprint('json output structure unknown')\n exit_hard()\n\n for diskstats in iostats['sysstat']['hosts'][0]['statistics'][0]['disk']:\n DEBUG and print(diskstats)\n payload = { \n \"tags\": { \"device\": diskstats['disk_device'] },\n \"values\": {\n \"readops_ps\": diskstats['r/s'],\n \"writeops_ps\": diskstats['w/s'],\n \"readKB_ps\": diskstats['rkB/s'] if 'rkB/s' in diskstats else diskstats['rMB/s'] * 1000,\n \"writtenKB_ps\": diskstats['wkB/s'] if 'wkB/s' in diskstats else diskstats['wMB/s'] * 1000,\n \"reads_queued_ps\": diskstats[\"rrqm/s\"],\n \"writes_queued_ps\": diskstats[\"wrqm/s\"],\n \"avg_read_time_ms\": diskstats[\"r_await\"],\n \"avg_write_time_ms\": diskstats[\"w_await\"],\n \"avg_rreqsize_KB\": diskstats[\"rareq-sz\"],\n \"avg_wreqsize_KB\": diskstats[\"wareq-sz\"],\n \"avg_queue_size\": diskstats['aqu-sz']\n },\n \"UTS\": round(time.time(),3)\n }\n \n mqttPub(topic, payload)\n\n run_finished_at = time.time()\n run_duration = run_finished_at - run_started_at\n\n DEBUG and print(\"duration of run: {:10.4f}s.\".format(run_duration))\n\n to_wait = MEAS_INTERVAL - run_duration\n if to_wait > 0:\n DEBUG and print(\"wait for \"+str(to_wait)+\"s\")\n time.sleep(to_wait - 0.002)\n else:\n DEBUG and print(\"no wait, {0:4f}ms over\".format(- to_wait*1000))\n\n","sub_path":"stage3/01-tweaks/rootfs/usr/local/bin/iostats2mqtt.py","file_name":"iostats2mqtt.py","file_ext":"py","file_size_in_byte":5161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"34526180","text":"\"\"\"Script to scrape content off of Hugo's Website.\"\"\"\n\nimport re\nimport requests\nimport os\nimport sys\n\n\ndef PdfDownloader(url):\n \"\"\"Download a PDF from the URL.\"\"\"\n fileName = url.split('/')[-1]\n if fileName in os.listdir(os.getcwd()):\n return\n response = requests.get(url, stream=True)\n print(\"Downloading \" + fileName)\n try:\n with open(fileName, 'wb') as file:\n i = 1\n for chunk in response.iter_content(chunk_size=1):\n print(\"\\rDownloaded \" + str(i) + \" bytes\", end='')\n sys.stdout.flush()\n file.write(chunk)\n i += 1\n print(\"\\nDOWNLOAD COMPLETE\\n\")\n except KeyboardInterrupt:\n print(\"\\rDOWNLOAD INTERRUPTED\")\n os.remove(fileName)\n exit(1)\n\n\n# Get HTML from site\nurl = \"http://info.usherbrooke.ca/hlarochelle/neural_networks/content.html\"\nresponse = requests.get(url)\n\n# Get all the links\nlinks = re.compile(r'href=\"(\\S+)\"').findall(response.text)\n# Get all pdf links from site\nnewLinks = []\nfor link in links:\n if link[-3:] == 'pdf' and link[:4] == \"http\" and 'usherbrooke' in link:\n newLinks.append(link)\nif \"pdf\" not in os.listdir(os.getcwd()):\n os.mkdir(\"pdf\")\nos.chdir(\"./pdf\")\n\nfor link in newLinks:\n PdfDownloader(link)\n","sub_path":"ScrapeHugo.py","file_name":"ScrapeHugo.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"85556985","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import genfromtxt\nfrom keras import backend as K\nfrom collections import defaultdict\n\nimport sys, os, cv2, glob, shutil, gdal\nsys.path.insert(1, 'keras-deeplab-v3-plus')\nsys.path.insert(2, '../postprocessing')\nfrom model_cfm_dual_wide_x65 import Deeplabv3\nfrom AdamAccumulate import AdamAccumulate\n\n#Only make first GPU visible on multi-gpu setups\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\nfrom skimage.transform import resize\nfrom skimage.io import imread, imsave\nimport error_analysis\nfrom scipy.spatial import distance\nfrom matplotlib.lines import Line2D\nfrom pyproj import Proj, transform\n\t\t\nfrom aug_generators_dual import create_unaugmented_data_patches_from_rgb_image\n\t\t\t\t\nfull_size = 256\nimg_size = 224\nstride = 16\nK.set_image_data_format('channels_last') # TF dimension ordering in this code\n\n\ndef deviation(gt, pr, smooth=1e-6, per_image=True):\n\tmismatch = np.sum(np.abs(gt[:,:,:,1] - pr[:,:,:,1]), axis=(1, 2)) #(B)\n\tlength = np.sum(pr[:,:,:,0], axis=(1, 2)) #(B)\n\tdeviation = mismatch / (length + smooth) #(B)\n\tmean_deviation = np.mean(deviation) * 3.0 #- (account for line thickness of 3 at 224)\n\treturn mean_deviation\n\n\ndef calculate_mean_deviation(pred, mask):\n\t\"\"\"Calculates mean deviation between two lines represented by nonzero pixels in pred and mask\"\"\"\n\t#Generate Nx2 matrix of pixels that represent the front\n\tx1, y1 = np.nonzero(pred)\n\tx2, y2 = np.nonzero(mask)\n\tpred_coords = np.array(list(zip(x1, y1)))\n\tmask_coords = np.array(list(zip(x2, y2)))\n\t\n\t#Return NaN if front is not detected in either pred or mask\n\tif pred_coords.shape[0] == 0 or mask_coords.shape[0] == 0:\n\t\treturn np.nan, np.array([])\n\t\n\t#Generate the pairwise distances between each point and the closest point in the other array\n\tdistances1 = distance.cdist(pred_coords, mask_coords).min(axis=1)\n\tdistances2 = distance.cdist(mask_coords, pred_coords).min(axis=1)\n\tdistances = np.concatenate((distances1, distances2))\n\t\n\t#Calculate the average distance between each point and the closest point in the other array\n\tmean_deviation = np.mean(distances)\n\treturn mean_deviation, distances\n\ndef calculate_edge_iou(gt, pr, smooth=1e-6, per_image=True):\n\tintersection = np.sum(gt[:,:,:] * pr[:,:,:], axis=(1, 2)) #(B)\n\tunion = np.sum(gt[:,:,:] + pr[:,:,:] >= 1.0, axis=(1, 2)) #(B)\n\tiou_score = intersection / (union + smooth) #(B)\n\tmean_iou_score = np.mean(iou_score) #- (account for line thickness of 3 at 224)\n\treturn mean_iou_score\n\t\ndef predict_edge(model, img_3_uint8, mask_uint8, fjord_boundary, pred_norm_image, full_size, img_size, stride):\n\t\"\"\"Takes in a neural network model, input image, mask, fjord boundary mask, and windowded normalization image to create prediction output.\n\t\tUses the full original size, image patch size, and stride legnth as additional variables.\"\"\"\n\t#Rescale mask while perserving continuity of edges\n\timg_3_f64 = resize(img_3_uint8, (full_size, full_size), preserve_range=True) #np.float64 [0.0, 65535.0]\n\tmask_f64 = resize(mask_uint8, (full_size, full_size), order=0, preserve_range=True) #np.float64 [0.0, 65535.0]\n\tfjord_boundary_final_f32 = resize(fjord_boundary, (full_size, full_size), order=0, preserve_range=True) #np.float64 [0.0, 255.0]\n\t\n\t#Ensure correct scaling and no clipping of data values\n\timg_max = img_3_f64.max()\n\timg_min = img_3_f64.min()\n\timg_range = img_max - img_min\n\tif (img_max != 0.0 and img_range > 255.0):\n\t\timg_3_f64 = np.round(img_3_f64 / img_max * 255.0).astype(np.float32) #np.float32 [0, 65535.0]\n\telse:\n\t\timg_3_f64 = img_3_f64.astype(np.float32)\n\timg_final_f32 = img_3_f64 #np.float32 [0.0, 255.0]\n\tmask_uint8 = (mask_f64 / mask_f64.max() * 255).astype(np.uint8)\n\t\t\t\n\t#Calculate edge from original resolution mask\n\tthickness = 3\n\tkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (thickness, thickness))\n\tmask_edge_f64 = cv2.Canny(mask_uint8, 250, 255 * 2).astype('float64') #thresholds = Use diagonals to detect strong edges, then connect anything with at least a single edge\n\tmask_edge_f32 = cv2.dilate(mask_edge_f64, kernel, iterations = 1).astype(np.float32) #np.float32 [0.0, 255.0]\n\tmask_final_f32 = mask_edge_f32 / mask_edge_f32.max()\t\t\t\t\t \n\t\n\t#Generate image patches (test time augmentation) to ensure confident predictions\n\tpatches = create_unaugmented_data_patches_from_rgb_image(img_final_f32, None, window_shape=(img_size, img_size, 3), stride=stride)\n\t\n\t#Predict results\n\tresults = model.predict(patches, batch_size=16, verbose=1)\n\t\n\t#Initilize outputs\n\traw_image_final_f32 = img_final_f32 / 255.0\n\tpred_image = np.zeros((full_size, full_size, 3))\n\t\n\t#Reassemble original resolution image by each 3x3 set of overlapping windows.\n\tstrides = int((full_size - img_size) / stride + 1) #(256-224 / 16 + 1) = 3\n\tfor x in range(strides):\n\t\tfor y in range(strides):\n\t\t\tx_start = x * stride\n\t\t\tx_end = x_start + img_size\n\t\t\ty_start = y * stride\n\t\t\ty_end = y_start + img_size\n\t\t\t\n\t\t\tpred_patch = results[x*strides + y,:,:,0:2]\n\t\t\tpred_image[x_start:x_end, y_start:y_end, 0:2] += pred_patch\n\t\t\t\n\t#Normalize output by dividing by number of patches each pixel is included in\n\tpred_image = np.nan_to_num(pred_image)\n\tpred_image_final_f32 = (pred_image / pred_norm_image).astype(np.float32)\n\t\n\treturn raw_image_final_f32, pred_image_final_f32, mask_final_f32, fjord_boundary_final_f32\n\ndef predict(model, img_3_uint8, mask_uint8, fjord_boundary, pred_norm_image, full_size, img_size, stride):\n\t\"\"\"Takes in a neural network model, input image, mask, fjord boundary mask, and windowded normalization image to create prediction output.\n\t\tUses the full original size, image patch size, and stride legnth as additional variables.\"\"\"\n\t#Rescale mask while perserving continuity of edges\n\tthickness = 3\n\tkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (thickness, thickness))\n\tmask_uint8_dilated = cv2.dilate(mask_uint8.astype('float64'), kernel, iterations = 1).astype(np.uint8) #np.uint8 [0, 255]\n\t\n\taugs = aug_validation(img_size=full_size)\n\tdat = augs(image=img_3_uint8, mask=mask_uint8_dilated)\n\timg_3_aug_f32 = dat['image'].astype('float32') #np.float32 [0.0, 255.0]\n\tmask_aug_f32 = dat['mask'].astype('float32') #np.float32 [0.0, 255.0]\n\t\n\t#Reskeletonize mask once at desired resolution to ensure single pixel wide target\n\tmask_rescaled_f32 = np.where(mask_aug_f32[:,:,0] > 127.0, 1.0, 0.0)\n\tmask_final_f32 = skeletonize(mask_rescaled_f32) #np.float32 [0.0, 1.0]\n\t\n\t#Resize fjord boundary\n\tdat = augs(image=fjord_boundary)\n\tfjord_boundary_final_f32 = dat['image'].astype('float32') #np.float32 [0.0, 1.0]\n\t\n\t#Ensure correct scaling and no clipping of data values\n\n\timg_max = img_3_aug_f32.max()\n\timg_min = img_3_aug_f32.min()\n\timg_range = img_max - img_min\n\tif (img_max != 0.0 and img_range > 255.0):\n\t\timg_3_aug_f32 = np.round(img_3_aug_f32 / img_max * 255.0) #np.float32 [0, 65535.0]\n\telse:\n\t\timg_3_aug_f32 = img_3_aug_f32.astype(np.float32)\n\timg_final_f32 = img_3_aug_f32.astype(np.float32) #np.float32 [0.0, 255.0]\n\t\n\t#Generate image patches (test time augmentation) to ensure confident predictions\n\tpatches = create_unaugmented_data_patches_from_rgb_image(img_final_f32, None, window_shape=(img_size, img_size, 3), stride=stride)\n\t\n\t#Predict results\n\tresults = model.predict(patches, batch_size=16, verbose=1)\n\t\n\t#Initilize outputs\n\traw_image_final_f32 = img_final_f32 / 255.0\n\tpred_image = np.zeros((full_size, full_size, 3))\n\t\n\t#Reassemble original resolution image by each 3x3 set of overlapping windows.\n\tstrides = int((full_size - img_size) / stride + 1) #(256-224 / 16 + 1) = 3\n\tfor x in range(strides):\n\t\tfor y in range(strides):\n\t\t\tx_start = x * stride\n\t\t\tx_end = x_start + img_size\n\t\t\ty_start = y * stride\n\t\t\ty_end = y_start + img_size\n\t\t\t\n\t\t\tpred_patch = results[x*strides + y,:,:,0:2]\n\t\t\tpred_image[x_start:x_end, y_start:y_end, 0:2] += pred_patch\n\t\t\t\n\t#Normalize output by dividing by number of patches each pixel is included in\n\tpred_image = np.nan_to_num(pred_image)\n\tpred_image_final_f32 = (pred_image / pred_norm_image).astype(np.float32)\n\t\n\treturn raw_image_final_f32, pred_image_final_f32, mask_final_f32, fjord_boundary_final_f32\n\n\ndef plot_validation_results(image_name_base, raw_image, original_raw, pred_image, polyline_image, empty_image, distances_meters, mask_image, index, dest_path, saving, scaling, edge_iou, fjord_boundary_image):\n\t\"\"\"Plots a standardized set of 6 plots for validation of the neural network, and quantifies its error per image.\"\"\"\n\t#Set figure size for 1600x900 resolution, tight layout\n\tplt.rcParams[\"figure.figsize\"] = (16,9)\n\t\n\t#Initialize plots\n\thist_bins = 10\n\tf, axarr = plt.subplots(2, 3, num=index)\n\tf.suptitle(image_name_base, fontsize=18, weight='bold')\n\t\n\t#Create the color key for each subplots' legends\t\n\tpreprocess_legend = [Line2D([0], [0], color='#ff0000', lw=4),\n\t\t\t\t\t Line2D([0], [0], color='#00ff00', lw=4),\n\t Line2D([0], [0], color='#0000ff', lw=4)]\n\tnn_legend = [Line2D([0], [0], color='#00ff00', lw=4),\n\t Line2D([0], [0], color='#ff0000', lw=4)]\n\tfront_legend = [Line2D([0], [0], color='#ff0000', lw=4)]\n\tcomparison_legend = [Line2D([0], [0], color='#ff0000', lw=4),\n\t\t\t\t\t Line2D([0], [0], color='#00ff00', lw=4)]\n\t\n\t#Begin plotting the 2x3 validation results output\n\toriginal_raw_gray = np.stack((original_raw[:,:,0], original_raw[:,:,0], original_raw[:,:,0]), axis=-1)\n\traw_image_gray = np.stack((raw_image[:,:,0], raw_image[:,:,0], raw_image[:,:,0]), axis=-1)\n\taxarr[0,0].imshow(np.clip(original_raw_gray, 0.0, 1.0))\n\taxarr[0,0].set_title(r'$/bf{a)}$ Raw Subset')\n\t\n\traw_image = np.clip(raw_image, 0.0, 1.0)\n\taxarr[0,1].imshow(raw_image)\n\taxarr[0,1].set_title(r'$/bf{b)}$ Preprocessed Input')\n\taxarr[0,1].legend(preprocess_legend, ['Raw', 'HDR', 'S/H'], prop={'weight': 'normal'}, facecolor='#eeeeee', loc='upper center', bbox_to_anchor=(0.5, 0.0), shadow=True, ncol=3)\n\taxarr[0,1].axis('off')\n\t\n\tpred_image = np.clip(pred_image, 0.0, 1.0)\n\taxarr[0,2].imshow(pred_image)\n\taxarr[0,2].set_title(r'$/bf{c)}$ NN Output')\n\taxarr[0,2].legend(nn_legend, ['Land/Ice', 'Front'], prop={'weight': 'normal'}, facecolor='#eeeeee', loc='upper center', bbox_to_anchor=(0.5, 0.0), shadow=True, ncol=2)\n\taxarr[0,2].axis('off')\n\t\n\textracted_front = np.clip(np.stack((polyline_image[:,:,0], empty_image, empty_image), axis=-1) + raw_image * 0.8, 0.0, 1.0)\n\taxarr[1,0].imshow(extracted_front)\n\taxarr[1,0].set_title(r'$/bf{d)}$ Extracted Front')\n\taxarr[1,0].legend(front_legend, ['Front'], prop={'weight': 'normal'}, facecolor='#eeeeee', loc='upper center', bbox_to_anchor=(0.5, 0.0), shadow=True, ncol=1)\n\taxarr[1,0].axis('off')\n\t\n\toverlay = np.clip(np.stack((polyline_image[:,:,0], mask_image, empty_image), axis=-1) + raw_image_gray * 0.8, 0.0, 1.0)\n\taxarr[1,1].imshow(overlay)\n\taxarr[1,1].set_title(r'$/bf{e)}$ NN vs Ground Truth Front')\n\taxarr[1,1].set_xlabel('Jaccard Index: {:.4f}'.format(edge_iou))\n\taxarr[1,1].legend(comparison_legend, ['NN', 'GT'], prop={'weight': 'normal'}, facecolor='#eeeeee', loc='upper center', bbox_to_anchor=(0.5, -0.05), shadow=True, ncol=3)\n\taxarr[1,1].tick_params(axis='both', which='both', bottom='off', top='off', labelbottom='off', right='off', left='off', labelleft='off') # labels along the bottom edge are off\n\t\n\t# which = both major and minor ticks are affected\n\taxarr[1,2].hist(distances_meters, bins=hist_bins, range=[0.0, 8.0 * scaling])\n\taxarr[1,2].set_xlabel('Distance to nearest point (mean=' + '{:.2f}m)'.format(np.mean(distances_meters)))\n\taxarr[1,2].set_ylabel('Number of points')\n\taxarr[1,2].set_title(r'$/bf{f)}$ Per-pixel Pairwise Error (meters)')\n\t\n\t\n\t#Refresh plot if necessary\n\tplt.subplots_adjust(top = 0.90, bottom = 0.075, right = 0.975, left = 0.025, hspace = 0.3, wspace = 0.2)\n\tf.canvas.draw()\n\tf.canvas.flush_events()\n\t\n\t#Save figure\n\tif saving:\n\t\tplt.savefig(os.path.join(dest_path, image_name_base + '_' + index + '_validation.png'))\n\t\timsave(os.path.join(dest_path, image_name_base + '_' + index + '_original_raw.png'), original_raw_gray)\n\t\timsave(os.path.join(dest_path, image_name_base + '_' + index + '_subset_raw.png'), raw_image)\n\t\timsave(os.path.join(dest_path, image_name_base + '_' + index + '_pred.png'), pred_image)\n\t\timsave(os.path.join(dest_path, image_name_base + '_' + index + '_front_only.png'), polyline_image)\n\t\timsave(os.path.join(dest_path, image_name_base + '_' + index + '_overlay_front.png'), extracted_front)\n\t\timsave(os.path.join(dest_path, image_name_base + '_' + index + '_overlay_comparison.png'), overlay)\n\t\t\n\n\ndef plot_histogram(distances, name, dest_path, saving, scaling):\n\t\"\"\"Plots a standardized set of 6 plots for validation of the neural network, and quantifies its error per image.\"\"\"\n\t#Initialize plots\n\thist_bins = 20\n\tf, axarr = plt.subplots(1, 1, num=name)\n\tf.suptitle('Validation Set: Per-point Distance from True Front', fontsize=16)\n\t\n\taxarr.hist(distances, bins=hist_bins, range=[0.0, 20.0 * scaling])\n\taxarr.set_xlabel('Distance to nearest point (meters)')\n\taxarr.set_ylabel('Number of points')\n\tplt.figtext(0.5, 0.00, r'Mean Distance = {:.2f}m'.format(np.mean(distances)), wrap=True, horizontalalignment='center', fontsize=14, weight='bold')\n\t\t\n\t#Set figure size for 1600x900 resolution, tight layout\n\tplt.rcParams[\"figure.figsize\"] = (8,4.5)\n\tplt.subplots_adjust(top = 0.90, bottom = 0.15, right = 0.90, left = 0.1, hspace = 0.25, wspace = 0.25)\n\t\n\t#Refresh plot if necessary\n\tf.canvas.draw()\n\tf.canvas.flush_events()\n\t\n\t#Save figure\n\tif saving:\n\t\tplt.savefig(os.path.join(dest_path, name + '.png'))\n\t\t\n\ndef plot_scatter(data, name, dest_path, saving):\n\t\"\"\"Plots a standardized set of 6 plots for validation of the neural network, and quantifies its error per image.\"\"\"\n\t#Initialize plots\n\tf, axarr = plt.subplots(1, 1, num=name)\n\tf.suptitle('Validation Set: Per-point Distance from True Front', fontsize=16)\n\t\n\taxarr.scatter(data[:,0], data[:,1])\n\taxarr.set_xlabel('Resolution (meters per pixel)')\n\taxarr.set_ylabel('Average Mean Distance')\n\t\t\n\t#Set figure size for 1600x900 resolution, tight layout\n\tplt.rcParams[\"figure.figsize\"] = (8,4.5)\n\tplt.subplots_adjust(top = 0.90, bottom = 0.15, right = 0.90, left = 0.1, hspace = 0.25, wspace = 0.25)\n\t\n\t#Refresh plot if necessary\n\tf.canvas.draw()\n\tf.canvas.flush_events()\n\t\n\t#Save figure\n\tif saving:\n\t\tplt.savefig(os.path.join(dest_path, name + '.png'))\n\n\ndef remove_small_components(image:np.ndarray):\n\timage = image.astype('uint8')\n\t#find all your connected components (white blobs in your image)\n\tnb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=8)\n\t#connectedComponentswithStats yields every seperated component with information on each of them, such as size\n\tsizes = stats[:,cv2.CC_STAT_AREA]\n\tordering = np.argsort(-sizes)\n\t#print(sizes, ordering)\n\t\n\tmin_size_floor = output.size * 0.0001\n\tif len(ordering) > 1:\n\t\tmin_size = sizes[ordering[1]] * 0.5\n\t# print(min_size)\n\t#your answer image\n\tlargeComponents = np.zeros((output.shape))\n\t#for every component in the image, you keep it only if it's above min_size\n\t#Skip first, since it's the background color\n\tbounding_boxes = [[0, 0, image.shape[0], image.shape[1]]]\n\tfor i in range(1, len(sizes)):\n\t\t# print(sizes, ordering[i])\n\t\tif sizes[ordering[i]] >= min_size_floor and sizes[ordering[i]] >= min_size:\n\t\t\tmask_indices = output == ordering[i]\n\t\t\tx, y = np.nonzero(mask_indices)\n\t\t\tmin_x = min(x)\n\t\t\tdelta_x = max(x) - min_x\n\t\t\tmin_y = min(y)\n\t\t\tdelta_y = max(y) - min_y\n\t\t\tbounding_boxes.append([min_x, min_y, delta_x, delta_y])\n\t\t\tlargeComponents[mask_indices] = image[mask_indices]\n#\t\t\tbounding_boxes = \n\treturn largeComponents.astype(np.float32), bounding_boxes\n\n\ndef mask_fjord_boundary(fjord_boundary_final_f32, kernel, iterations, raw_image_gray_uint8, pred_image_gray_uint8, mask=True):\n\t\"\"\" Helper funcction for performing optimiation on fjord boundaries.\n\t\tErodes a single fjord boundary mask.\"\"\"\n\tfjord_boundary_eroded_f32 = cv2.erode(fjord_boundary_final_f32.astype('float64'), kernel, iterations = iterations).astype(np.float32) #np.float32 [0.0, 255.0]\n\tfjord_boundary_eroded_f32 = np.where(fjord_boundary_eroded_f32 > 0.5, 1.0, 0.0)\n\t\n\tif mask:\n\t\tmasked_pred_uint8 = pred_image_gray_uint8 * fjord_boundary_eroded_f32.astype(np.uint8)\n\t\tresults_polyline = error_analysis.extract_front_indicators(raw_image_gray_uint8, masked_pred_uint8, 0, [256, 256])\n\t\t\n\t\t#If edge is detected, replace coarse edge mask in prediction image with connected polyline edge\n\t\tif not results_polyline is None:\n\t\t\tpolyline_image = (results_polyline[0] / 255.0)\n\t\t\tbounding_boxes = [[0, 0, full_size, full_size]]\n\t\telse:\n\t\t\tpolyline_image = np.zeros((full_size, full_size, 3))\n\t\t\tbounding_boxes = [[0, 0, full_size, full_size]]\n\t\t\n\t\t#Determine number of masked pixels\n\t\tx1, y2 = np.nonzero(polyline_image[:,:,0])\n\t\tnum_masked_pixels = x1.shape[0]\n\telse:\n\t\tresults_polyline = error_analysis.extract_front_indicators(raw_image_gray_uint8, pred_image_gray_uint8, 0, [256, 256])\n\t\t\n\t\t#If edge is detected, replace coarse edge mask in prediction image with connected polyline edge\n\t\tif not results_polyline is None:\n\t\t\tpolyline_image = (results_polyline[0] / 255.0)\n\t\t\tpolyline_image[:,:,0] *= fjord_boundary_eroded_f32.astype(np.uint8)\n\t\t\tpolyline_image[:,:,0], bounding_boxes = remove_small_components(polyline_image[:,:,0])\n\t\telse:\n\t\t\tpolyline_image = np.zeros((full_size, full_size, 3))\n\t\t\tbounding_boxes = [[0, 0, full_size, full_size]]\n\t\t\n\t\t#Determine number of masked pixels\n\t\tx1, y2 = np.nonzero(polyline_image[:,:,0])\n\t\tnum_masked_pixels = x1.shape[0]\n\treturn num_masked_pixels, polyline_image, fjord_boundary_eroded_f32, bounding_boxes\n\ndef mask_polyline(raw_image, pred_image, fjord_boundary_final_f32, kernel, recursion=True):\n\t\"\"\" Perform optimiation on fjord boundaries.\n\t\tContinuously erode fjord boundary mask until fjord edges are masked.\n\t\tThis is detected by looking for large increases in pixels being masked,\n\t\tfollowed by few pixels being masked.\"\"\"\n\t\t\t\n\tnum_masked_pixels_array = np.array([])\n\tmasked_pixels_diff = np.array([0])\n\titeration_limit = 6 #limit of 6 pixels of erosion - otherwise, too much front detail is lost anyways\n\traw_gray_uint8 = (raw_image[:,:,0] * 255.0).astype(np.uint8)\n\tpred_gray_uint8 = (pred_image * 255.0).astype(np.uint8)\n\tfor j in range(iteration_limit):\n\t\tresults_masking = mask_fjord_boundary(fjord_boundary_final_f32, kernel, j, raw_gray_uint8, pred_gray_uint8)\n\t\tnum_masked_pixels = results_masking[0]\n\t\tnum_masked_pixels_array = np.append(num_masked_pixels_array, num_masked_pixels)\n\t\tif j > 0:\n\t\t\tmasked_pixels_diff = np.append(masked_pixels_diff, num_masked_pixels_array[j] - num_masked_pixels_array[j - 1])\n\t\n\t#Find where the marginal increase in masked pixels decreases the most (i.e., find where increase j gives diminishing returns).\n\t#Use 1st derivative of number of masked pixels with respect to iteration j.\n\t#Find a minima (not even guarenteed to be local min) using argmin of (d/dj)(number of masked pixels)\n\t#Additionally, check ahead one iteration to ensure we get a better minima\n\t#Unable to use second derivative since it never crosses 0 (number of masked pixels is a monotonically decreasing function)\n\tmaximal_erosions = np.argmin(masked_pixels_diff)\n\toriginal_maximal_erosions = maximal_erosions\n\tthreshold = 0.4\n\twhile maximal_erosions < iteration_limit - 1 and masked_pixels_diff[maximal_erosions + 1] < masked_pixels_diff[original_maximal_erosions] * threshold:\n\t\tmaximal_erosions += 1\n\t\tthreshold = threshold / 2\n\t\n\t#Redo fjord masking with known maximal erosion number\n\tresults_masking = mask_fjord_boundary(fjord_boundary_final_f32, kernel, maximal_erosions, raw_gray_uint8, pred_gray_uint8, mask=False)\n\tpolyline_image = results_masking[1]\n\tfjord_boundary_eroded = results_masking[2]\n\tbounding_boxes = results_masking[3]\n\t\n\treturn polyline_image, fjord_boundary_eroded, bounding_boxes\n\ndef mask_bounding_box(bounding_boxes, image):\n\tbounding_box = bounding_boxes[1]\n\tsub_x1 = max(bounding_box[0] - 8, 0)\n\tsub_x2 = min(bounding_box[0] + bounding_box[2] + 8, image.shape[0])\n\tsub_y1 = max(bounding_box[1] - 8, 0)\n\tsub_y2 = min(bounding_box[1] + bounding_box[3] + 8, image.shape[1])\n\t\n\tmask = np.zeros((image.shape[0], image.shape[1])) \n\tmask[sub_x1:sub_x2, sub_y1:sub_y2] = 1.0\n\t\n\tmasked_image = None\n\tif len(image.shape) > 2:\n\t\tmasked_image = image * np.stack((mask, mask, mask), axis=-1)\n\telse:\n\t\tmasked_image = image * mask\n\t\n\treturn masked_image\n\ndef compile_model():\n\t\"\"\"Compile the CALFIN Neural Network model and loads pretrained weights.\"\"\"\n\tprint('-'*30)\n\tprint('Creating and compiling model...')\n\tprint('-'*30)\n\timg_shape = (img_size, img_size, 3)\n\tmodel = Deeplabv3(input_shape=img_shape, classes=16, OS=16, backbone='xception', weights=None)\n\t\n\tmodel.compile(optimizer=AdamAccumulate(lr=1e-4, accum_iters=2))\n\tmodel.summary()\n\tmodel.load_weights('cfm_weights_patched_dual_wide_x65_224_e65_iou0.5136.h5')\n\t\n\treturn model\n\n\nif __name__ == '__main__':\n\t#initialize once, run many times\n\tcreate_model = False\n\tif create_model:\n\t\ttry:\n\t\t model\n\t\texcept NameError:\n\t\t model = compile_model()\n\t\t\n\t#Initialize plots\n\tplt.close('all')\n\tfont = {'family' : 'normal',\n\t 'size' : 14}\n\t\n\tplt.rc('font', **font)\n\t\n\t#Validate Mohajerani et al. performance on selected CALFIN data\n\tvalidate = True\n\tif validate:\n\t\tprint('-'*30)\n\t\tprint('Validating intercomparison data...')\n\t\tprint('-'*30)\n\n\n\t\tvalidation_files = []\n\t\tcalfin_path = r\"../training/data/validation\"\n\t\tvalidation_files = glob.glob(r\"../training/data/validation/*B[0-9].png\")\n\t\tfjord_boundaries_path = r\"../training/data/fjord_boundaries\"\n\t\ttif_source_path = r\"../preprocessing/CalvingFronts/tif\"\n\t\tdest_path = r\"../outputs/validation\"\n\t\tsave_path = r\"../processing/landsat_preds\"\n\t\t\n\t\tcoordinates_path = r'D:/Daniel/Documents/Github/CALFIN Repo Intercomp/postprocessing/output_helheim_calfin'\n\t\tfor csv_path in glob.glob(os.path.join(coordinates_path, '*')):\n\t\t\tcoordinates = genfromtxt(csv_path, delimiter=',')\n\t\t\tcsv_name = os.path.basename(csv_path)\n\t\t\tcsv_name_parts = csv_name.split()\n\t\t\tdomain = csv_name_parts[0]\n\t\t\tlandsat_name = csv_name_parts[1]\n\t\t\tlandsat_name_parts = landsat_name.split('_')\n\t\t\tsatellite = landsat_name_parts[0]\n\t\t\tlevel = landsat_name_parts[1]\n\t\t\tpath_row = landsat_name_parts[2]\n\t\t\tdate = landsat_name_parts[3]\n\t\t\tpath = path_row[0:3]\n\t\t\trow = path_row[3:6]\n\t\t\tyear = date[0:4]\n\t\t\tmonth = date[4:6]\n\t\t\tday = date[6:]\n\t\t\ttier = landsat_name_parts[6]\n\t\t\tband = landsat_name_parts[7]\n\t\t\tdate_string = '-'.join([year, month, day])\n\t\t\tpath_row_string = '-'.join([path, row])\n\t\t\t#Akullikassaap_LE07_L1TP_2000-03-17_014-009_T1_B4.png\n\t\t\tcalfin_name = '_'.join([domain, satellite, level, date_string, path_row_string, tier, band])\n\t\t\tcalfin_raw_path = os.path.join(calfin_path, calfin_name + '.png')\n\t\t\tcalfin_mask_path = os.path.join(calfin_path, calfin_name + '_mask.png')\n\t\t\tcalfin_tif_path = os.path.join(tif_source_path, domain, year, calfin_name + '.tif')\n\t\t\t\n\t\t\tprint(calfin_raw_path, calfin_mask_path, calfin_tif_path)\n\t\t\t#install pyproj from pip instead of conda on windows to avoid undefined epsg\n\t\t\tinProj = Proj('epsg:3413')\n\t\t\toutProj = Proj('epsg:32624')\n\t\t\ttransformed_coordinates = transform(inProj,outProj,coordinates[:,0], coordinates[:,1])\n\t\t\tprint(csv_path)\n\t\t\tplt.figure()\n\t\t\tplt.plot(transformed_coordinates[0], transformed_coordinates[1])\n\t\t\tplt.show()\n\t\t\t\n#\t\t\tvalidation_files += raw_file_path\n\t\t\t\t","sub_path":"postprocessing/intercomp_compare.py","file_name":"intercomp_compare.py","file_ext":"py","file_size_in_byte":23260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"646235069","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport argparse\nimport codecs\nimport pprint\nimport time\nfrom collections import defaultdict\nfrom itertools import chain\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\nfrom logger import Logger\n\nparser = argparse.ArgumentParser(description='Byte-level CNN text autoencoder.')\nparser.add_argument('--resume-training', type=str, default='',\n help='path to a training directory (loads the model and the optimizer)')\nparser.add_argument('--resume-training-force-args', type=str, default='',\n help='list of input args to be overwritten when resuming (e.g., # of epochs)')\nparser.add_argument('--data', type=str, default='./data/ptb.',\n help='name of the dataset')\nparser.add_argument('--model', type=str, default='ByteCNN',\n help='model class')\nparser.add_argument('--model-kwargs', type=str, default='',\n help='model kwargs')\nparser.add_argument('--lr', type=float, default=0.001,\n help='initial learning rate')\n# Default from the Byte-level CNN paper: half lr every 10 epochs\nparser.add_argument('--lr-lambda', type=str, default='lambda epoch: 0.5 ** (epoch // 10)',\n help='learning rate based on base lr and iteration')\nparser.add_argument('--epochs', type=int, default=40,\n help='upper epoch limit')\nparser.add_argument('--batch-size', type=int, default=128, metavar='N',\n help='batch size')\nparser.add_argument('--eval-batch-size', type=int, default=10, metavar='N',\n help='batch size')\nparser.add_argument('--optimizer', default='sgd',\n choices=('sgd', 'adam', 'adagrad', 'adadelta'),\n help='optimization method')\nparser.add_argument('--optimizer-kwargs', type=str, default='momentum=0.9,weight_decay=0.00001',\n help='kwargs for the optimizer (e.g., momentum=0.9)')\nparser.add_argument('--seed', type=int, default=1111,\n help='random seed')\nparser.add_argument('--cuda', action='store_true',\n help='use CUDA')\nparser.add_argument('--save-state', action='store_true',\n help='save training state after each epoch')\nparser.add_argument('--log-interval', type=int, default=200, metavar='N',\n help='report interval')\nparser.add_argument('--logdir', type=str, default=None,\n help='path to save the final model')\n# parser.add_argument('--save', type=str, default='model.pt',\n# help='path to save the final model')\nparser.add_argument('--log-weights', action='store_true',\n help=\"log weights' histograms\")\nparser.add_argument('--log-grads', action='store_true',\n help=\"log gradients' histograms\")\nargs = parser.parse_args()\n\n\nclass UTF8File(object):\n EOS = 0 # ASCII null symbol\n EMPTY = 7 # XXX\n def __init__(self, path, cuda, rng=None):\n self.cuda = cuda\n self.rng = np.random.RandomState(rng)\n\n lines_by_len = defaultdict(list)\n with codecs.open(path, 'r', 'utf-8') as f:\n for line in f:\n bytes_ = [ord(c) for c in line.strip().encode('utf-8')] + [self.EOS]\n bytes_ += [self.EMPTY] * (int(2 ** np.ceil(np.log2(len(bytes_)))) - len(bytes_))\n lines_by_len[len(bytes_)].append(bytes_)\n # Convert to ndarrays\n self.lines = {k: np.asarray(v, dtype=np.int32) \\\n for k,v in lines_by_len.items()}\n\n def get_num_batches(self, bsz):\n return sum(arr.shape[0] // bsz for arr in self.lines.values())\n\n def iter_epoch(self, bsz, evaluation=False):\n if evaluation:\n for len_, data in self.lines.items():\n for batch in np.array_split(data, max(1, data.shape[0] // bsz)):\n batch_tensor = torch.from_numpy(batch).long()\n yield batch_tensor.cuda() if self.cuda else batch_tensor\n else:\n batch_inds = []\n for len_, data in self.lines.items():\n num_batches = data.shape[0] // bsz\n if num_batches == 0:\n continue\n all_inds = np.random.permutation(data.shape[0])\n all_inds = all_inds[:(bsz * num_batches)]\n batch_inds += [(len_,inds) \\\n for inds in np.split(all_inds, num_batches)]\n np.random.shuffle(batch_inds)\n for len_, inds in batch_inds:\n batch_tensor = torch.from_numpy(self.lines[len_][inds]).long()\n yield batch_tensor.cuda() if self.cuda else batch_tensor\n\n def sample_batch(self):\n sample = 'On a beautiful morning, a busty Amazon rode through a forest.'\n bytes_ = np.asarray([[ord(c) for c in sample] + [self.EOS] + [self.EMPTY] * 2], dtype=np.int32)\n assert bytes_.shape[1] == 64, bytes_.shape\n batch_tensor = torch.from_numpy(bytes_).long()\n yield batch_tensor.cuda() if self.cuda else batch_tensor\n\n\nclass UTF8Corpus(object):\n def __init__(self, path, cuda, rng=None):\n self.train = UTF8File(path + 'train.txt', cuda, rng=rng)\n self.valid = UTF8File(path + 'valid.txt', cuda, rng=rng)\n self.test = UTF8File(path + 'test.txt', cuda, rng=rng)\n\n\nclass ExpandConv1d(nn.Module):\n def __init__(self, *args, **kwargs):\n super(ExpandConv1d, self).__init__()\n self.conv1d = nn.Conv1d(*args, **kwargs)\n\n def forward(self, x):\n # Output of conv1d: (N,Cout,Lout)\n x = self.conv1d(x)\n bsz, c, l = x.size()\n x = x.view(bsz, c // 2, 2, l).transpose(2, 3).contiguous()\n return x.view(bsz, c // 2, 2 * l).contiguous()\n\n\nclass Residual(nn.Module):\n def __init__(self, layer_proto, out_relu=True):\n super(Residual, self).__init__()\n self.layer1 = layer_proto()\n self.relu = nn.ReLU()\n self.layer2 = layer_proto()\n self.out_relu = out_relu\n\n def forward(self, x):\n residual = x\n out = self.layer1(x)\n # out = self.bn1(out)\n out = self.relu(out)\n out = self.layer2(out)\n # out = self.bn2(out)\n\n out += residual\n if self.out_relu:\n out = self.relu(out)\n return out\n\n\nclass ByteCNNEncoder(nn.Module):\n def __init__(self, n, emsize):\n super(ByteCNNEncoder, self).__init__()\n self.n = n\n self.emsize = emsize\n assert n % 2 == 0, 'n should be a multiple of 2'\n conv_kwargs = dict(kernel_size=3, stride=1, padding=1, bias=False)\n conv_proto = lambda: nn.Conv1d(emsize, emsize, **conv_kwargs)\n linear_proto = lambda: nn.Linear(emsize*4, emsize*4)\n residual_list = lambda proto, k: [Residual(proto) for _ in xrange(k)]\n\n self.embedding = nn.Embedding(emsize, emsize, padding_idx=UTF8File.EMPTY)\n self.prefix = nn.Sequential(*(residual_list(conv_proto, n//2)))\n self.recurrent = nn.Sequential(*(residual_list(conv_proto, n//2) + \\\n [nn.MaxPool1d(kernel_size=2)]))\n self.postfix = nn.Sequential(*(residual_list(linear_proto, n//2-1) + \\\n [Residual(linear_proto, out_relu=False)]))\n\n def forward(self, x, r):\n x = self.embedding(x).transpose(1, 2)\n x = self.prefix(x)\n\n for _ in xrange(r-2):\n x = self.recurrent(x)\n\n bsz = x.size(0)\n return self.postfix(x.view(bsz, -1))\n\n def num_recurrences(self, x):\n rfloat = np.log2(x.size(-1))\n r = int(rfloat)\n assert float(r) == rfloat\n return r\n\n\nclass ByteCNNDecoder(nn.Module):\n def __init__(self, n, emsize):\n super(ByteCNNDecoder, self).__init__()\n self.n = n\n self.emsize = emsize\n assert n % 2 == 0, 'n should be a multiple of 2'\n conv_kwargs = dict(kernel_size=3, stride=1, padding=1, bias=False)\n conv_proto = lambda: nn.Conv1d(emsize, emsize, **conv_kwargs)\n expand_proto = lambda: ExpandConv1d(emsize, emsize*2, **conv_kwargs)\n linear_proto = lambda: nn.Linear(emsize*4, emsize*4)\n residual_list = lambda proto, k: [Residual(proto) for _ in xrange(k)]\n\n self.prefix = nn.Sequential(*(residual_list(linear_proto, n//2)))\n self.recurrent = nn.Sequential(\n *([expand_proto(), nn.ReLU(), conv_proto(), nn.ReLU()] + \\\n residual_list(conv_proto, n//2-1)))\n self.postfix = nn.Sequential(*(residual_list(conv_proto, n//2)))\n\n def forward(self, x, r):\n x = self.prefix(x)\n x = x.view(x.size(0), self.emsize, 4)\n\n for _ in xrange(r-2):\n x = self.recurrent(x)\n\n return self.postfix(x)\n\n\nclass ByteCNN(nn.Module):\n save_best = True\n def __init__(self, n=8, emsize=256): ## XXX Check default emsize\n super(ByteCNN, self).__init__()\n self.n = n\n self.emsize = emsize\n self.encoder = ByteCNNEncoder(n, emsize)\n self.decoder = ByteCNNDecoder(n, emsize)\n self.log_softmax = nn.LogSoftmax()\n #self.criterion = nn.NLLLoss()\n self.criterion = nn.CrossEntropyLoss(ignore_index=UTF8File.EMPTY)\n\n def forward(self, x):\n r = self.encoder.num_recurrences(x)\n x = self.encoder(x, r)\n x = self.decoder(x, r)\n return self.log_softmax(x)\n\n def train_on(self, batch_iterator, optimizer, logger=None):\n self.train()\n losses = []\n errs = []\n for batch, src in enumerate(batch_iterator):\n self.zero_grad()\n src = Variable(src)\n r = self.encoder.num_recurrences(src)\n features = self.encoder(src, r)\n tgt = self.decoder(features, r)\n loss = self.criterion(\n tgt.transpose(1, 2).contiguous().view(-1, tgt.size(1)),\n src.view(-1))\n loss.backward()\n optimizer.step()\n\n _, predictions = tgt.data.max(dim=1)\n mask = (src.data != UTF8File.EMPTY)\n err_rate = 100. * (predictions[mask] != src.data[mask]).sum() / mask.sum()\n losses.append(loss.data[0])\n errs.append(err_rate)\n logger.train_log(batch, {'loss': loss.data[0], 'acc': 100. - err_rate,},\n named_params=self.named_parameters)\n return losses, errs\n\n def eval_on(self, batch_iterator):\n self.eval()\n errs = 0\n samples = 0\n total_loss = 0\n batch_cnt = 0\n for src in batch_iterator:\n src = Variable(src, volatile=True)\n r = self.encoder.num_recurrences(src)\n features = self.encoder(src, r)\n tgt = self.decoder(features, r)\n total_loss += self.criterion(\n tgt.transpose(1, 2).contiguous().view(-1, tgt.size(1)),\n src.view(-1))\n\n _, predictions = tgt.data.max(dim=1)\n mask = (src.data != UTF8File.EMPTY)\n errs += (predictions[mask] != src.data[mask]).sum()\n samples += mask.sum()\n batch_cnt += 1\n return {'loss': total_loss.data[0]/batch_cnt, 'acc': 100 - 100. * errs / samples}\n\n def try_on(self, batch_iterator):\n self.eval()\n decoded = []\n for src in batch_iterator:\n src = Variable(src, volatile=True)\n r = self.encoder.num_recurrences(src)\n features = self.encoder(src, r)\n tgt = self.decoder(features, r)\n _, predictions = tgt.data.max(dim=1)\n\n # Make into strings and append to decoded\n for pred in predictions:\n pred = list(pred.cpu().numpy())\n pred = pred[:pred.index(UTF8File.EOS)] if UTF8File.EOS in pred else pred\n pred = repr(''.join([chr(c) for c in pred]))\n decoded.append(pred)\n return decoded\n\n @staticmethod\n def load_model(path):\n \"\"\"Load a model\"\"\"\n model_pt = os.path.join(path, 'model.pt')\n model_info = os.path.join(path, 'model.info')\n \n with open(model_info, 'r') as f:\n p = defaultdict(str)\n p.update(dict(line.strip().split('=', 1) for line in f))\n \n # Read and pop one by one, then raise if something's left\n model_class = eval(p['model_class'])\n del p['model_class']\n model_kwargs = eval(\"dict(%s)\" % p['model_kwargs'])\n del p['model_kwargs']\n if len(p) > 0:\n raise ValueError('Unknown model params: ' + ', '.join(p.keys()))\n \n assert p['model_class'] == 'ByteCNN', \\\n 'Tried to load %s as ByteCNN' % p['model_class'] \n model = model_class(**model_kwargs)\n with open(model_pt, 'rb') as f:\n model.load_state_dict(torch.load(f))\n return model\n\n\n###############################################################################\n# Resume old training?\n###############################################################################\n\nforced_args = None\nif args.resume_training != '':\n # Overwrite the args with loaded ones, build the model, optimizer, corpus\n # This will allow to keep things similar, e.g., initialize corpus with\n # a proper random seed (which will later get overwritten)\n resume_path = args.resume_training\n print('\\nResuming training of %s' % resume_path)\n state = Logger.load_training_state(resume_path)\n state['args'].__dict__['resume_training'] = resume_path # XXX\n\n if args.resume_training_force_args != '':\n forced_args = eval('dict(%s)' % args.resume_training_force_args)\n print('\\nForcing args: %s' % forced_args)\n print('\\nWarning: Some args (e.g., --optimizer-kwargs) will be ignored. '\n 'Some loaded components, as the optimizer, are already constructed.')\n for k,v in forced_args.items():\n assert hasattr(state['args'], k)\n setattr(state['args'], k, v)\n args = state['args']\n print('\\nWarning: Ignoring other input arguments!\\n')\n\n# Set the random seed manually for reproducibility.\ntorch.manual_seed(args.seed)\nif torch.cuda.is_available():\n if not args.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably \"\n \"run with --cuda\")\n else:\n torch.cuda.manual_seed(args.seed)\n\n###############################################################################\n# Load data\n###############################################################################\n\ndataset = UTF8Corpus(args.data, cuda=args.cuda)\n\n###############################################################################\n# Build the model\n###############################################################################\n\n# Evaluate this early to know which data options to use\nmodel_kwargs = eval(\"dict(%s)\" % (args.model_kwargs,))\nmodel = ByteCNN(**model_kwargs)\n\nif args.cuda:\n model.cuda()\n\nmodel_parameters = filter(lambda p: p.requires_grad, model.parameters())\nnum_params = sum([np.prod(p.size()) for p in model_parameters])\nprint(\"Model summary:\\n%s\" % (model,))\nprint(\"Model params:\\n%s\" % (\"\\n\".join(\n [\"%s: %s\" % (p[0], p[1].size()) for p in model.named_parameters()])))\nprint(\"Number of params: %.2fM\" % (num_params / 10.0**6))\n\n###############################################################################\n# Setup training\n###############################################################################\n\noptimizer_proto = {'sgd': optim.SGD, 'adam': optim.Adam,\n 'adagrad': optim.Adagrad, 'adadelta': optim.Adadelta}\noptimizer_kwargs = eval(\"dict(%s)\" % args.optimizer_kwargs)\noptimizer_kwargs['lr'] = args.lr\noptimizer = optimizer_proto[args.optimizer](\n model.parameters(), **optimizer_kwargs)\n\nif args.lr_lambda:\n # TODO Check how it behaves on resuming training\n lr_decay = torch.optim.lr_scheduler.LambdaLR(\n optimizer, lr_lambda=eval(args.lr_lambda))\nelse:\n lr_decay = None\n\nif args.resume_training != '':\n # State has been loaded before model construction\n logger = state['logger']\n state = logger.set_training_state(state, optimizer)\n optimizer = state['optimizer']\n\n if forced_args and forced_args.has_key('lr'):\n optimizer.param_groups[0]['lr'] = forced_args['lr']\n logger.lr = forced_args['lr']\n\n model.load_state_dict(logger.load_model_state_dict(current=True))\n first_epoch = logger.epoch + 1\nelse:\n logger = Logger(optimizer.param_groups[0]['lr'], args.log_interval,\n dataset.train.get_num_batches(args.batch_size), logdir=args.logdir,\n log_weights=args.log_weights, log_grads=args.log_grads)\n logger.save_model_info(dict(model=(args.model, model_kwargs)))\n first_epoch = 1\nprint(logger.logdir)\n\n###############################################################################\n# Training code\n###############################################################################\nlogger.save_model_state_dict(model.state_dict())\n\n# At any point you can hit Ctrl + C to break out of training early.\ntry:\n for epoch in range(first_epoch, args.epochs+1):\n logger.mark_epoch_start(epoch)\n\n model.train_on(dataset.train.iter_epoch(args.batch_size),\n optimizer, logger)\n val_loss = model.eval_on(dataset.valid.iter_epoch(args.batch_size,\n evaluation=True))\n print(model.try_on(dataset.valid.sample_batch())[0])\n logger.valid_log(val_loss)\n\n # Save the model if the validation loss is the best we've seen so far.\n if args.save_state:\n logger.save_model_state_dict(model.state_dict(), current=True)\n logger.save_training_state(optimizer, args)\n\n # XXX\n # if model.save_best and False: # not best_val_loss or val_loss['nll_per_w'] < best_val_loss:\n # logger.save_model_state_dict(model.state_dict())\n # best_val_loss = val_loss['nll_per_w']\n\n if lr_decay is not None:\n lr_decay.step()\n logger.lr = optimizer.param_groups[0]['lr']\n\n\n\nexcept KeyboardInterrupt:\n print('-' * 89)\n print('Exiting from training early')\n\n\n# Load the best saved model.\n# model = logger.load_model()\nmodel.load_state_dict(logger.load_model_state_dict())\n\n# Run on all data\n# train_loss = model.eval_on(\n# corpus.train.iter_epoch(eval_batch_size, args.bptt, evaluation=True))\n# valid_loss = model.eval_on(\n# corpus.valid.iter_epoch(eval_batch_size, args.bptt, evaluation=True))\n# results = dict(train=train_loss, valid=valid_loss, test=test_loss)\n\ntest_loss = model.eval_on(\n dataset.test.iter_epoch(args.eval_batch_size, evaluation=True))\nresults = dict(test=test_loss)\n\nlogger.final_log(results)\n\n# Run on test data.\n#corpus.valid.iter_epoch(eval_batch_size, args.bptt, evaluation=True)\n#test_loss = model.eval_on(\n# dataset.test.iter_epoch(eval_batch_size, args.bptt, evaluation=True))\n#print('=' * 89)\n#print('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(\n# test_loss, math.exp(test_loss)))\n#print('=' * 89)\n\n# def logging_callback(batch, batch_loss):\n# global total_loss\n# global minibatch_start_time\n# total_loss += batch_loss\n# if batch % args.log_interval == 0 and batch > 0:\n# cur_loss = total_loss[0] / args.log_interval\n# elapsed = (time.time() - minibatch_start_time\n# ) * 1000 / args.log_interval\n# print('| epoch {:3d} | {:5d}/{:5d} batches | lr {:02.5f} | '\n# 'ms/batch {:5.2f} | loss {:5.2f} | ppl {:8.2f}'.format(\n# epoch, batch, num_batches, optimizer.param_groups[0]['lr'],\n# elapsed, cur_loss, math.exp(cur_loss)))\n# total_loss = 0\n# minibatch_start_time = time.time()\n\n","sub_path":"byte.py","file_name":"byte.py","file_ext":"py","file_size_in_byte":19919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"14826608","text":"import numpy as np\nfrom assignment_2.pos_tagger import POSTagger\n\n\nclass HMMTagger(POSTagger):\n def __init__(self):\n self.state_transition_counts = {} # dictionary of dictionaries\n self.state_emission_counts = {} # dictionary of dictionaries\n\n self.state_transitions = {} # dictionary of dictionaries\n self.state_emissions = {} # dictionary of dictionaries\n\n self.pos_index = {} # pos tag to int mapping\n self.inv_pos_index = {} # int to pos tag mapping\n\n self.token_freq = {} # count for each token\n\n def train(self, sentences):\n \"\"\"\n Trains HMM pos tagger\n\n Parameters:\n sentences -- list of list of tuples\n \"\"\"\n num_sentences = 0\n for sent in sentences:\n self.update(sent)\n num_sentences += 1\n\n self.compute_model()\n print('Trained on {} sentences'.format(num_sentences))\n\n def iterative_train(self, reader, file_path, train_size):\n \"\"\"\n Trains HMM pos tagger. Gets one sentence at a time\n\n Parameters:\n reader -- instance, TigerCorpusReader\n file_path -- path to corpus\n train_size -- size of the training set\n \"\"\"\n num_sentences = 0\n for sent in reader.read(file_path):\n self.update(sent)\n num_sentences += 1\n if num_sentences == train_size:\n break\n\n self.compute_model()\n print('Trained on {} sentences'.format(num_sentences))\n\n def compute_model(self):\n \"\"\"\n Computes state transition and emission probabilities Applies add one smoothing for\n emission probabilities to deal with unseen tokens during training. Creates pos to index\n and index to pas mapping.\n \"\"\"\n for prev_tag in self.state_transition_counts:\n self.state_transitions[prev_tag] = {}\n total = sum(self.state_transition_counts[prev_tag].values())\n for tag in self.state_transition_counts[prev_tag]:\n self.state_transitions[prev_tag][tag] = self.state_transition_counts[prev_tag][tag] / total\n\n for tag in self.state_emission_counts:\n self.state_emissions[tag] = {}\n total = sum(self.state_emission_counts[tag].values())\n for token in self.state_emission_counts[tag]:\n self.state_emissions[tag][token] = \\\n (self.state_emission_counts[tag][token] + 1) / (total + len(self.token_freq) + 1)\n\n # Smoothing\n self.state_emissions[tag]['unkwn'] = 1 / (total + len(self.token_freq) + 1)\n\n for idx, tag in enumerate(self.state_transitions):\n if tag not in self.pos_index:\n self.pos_index[tag] = idx\n self.inv_pos_index[idx] = tag\n\n def update(self, sentence):\n \"\"\"\n Given a sentence from training set Updates state transition,\n state emission and token frequency count\n\n Parameters:\n sentence -- list of tuples [ (token, tag) ... (token, tag) ]\n \"\"\"\n for i in range(len(sentence) + 1):\n if i == len(sentence):\n token = ''\n prev_tag = sentence[i - 1][1]\n tag = ''\n else:\n token = sentence[i][0]\n if i == 0:\n prev_tag = ''\n else:\n prev_tag = sentence[i - 1][1]\n tag = sentence[i][1]\n\n self.update_state_transitions(prev_tag, tag)\n self.update_emissions(tag, token)\n if token != '':\n self.update_token_freq(token)\n\n def update_token_freq(self, token):\n \"\"\"\n Updates token frequency count\n\n Parameters:\n token -- string, word\n \"\"\"\n if token in self.token_freq:\n self.token_freq[token] += 1\n else:\n self.token_freq[token] = 1\n\n def update_emissions(self, tag, token):\n \"\"\"\n Updates emission probabiltry for the given tag and token pair\n\n Parameters:\n tag -- string, pos\n token -- string, word\n \"\"\"\n if tag in self.state_emission_counts:\n if token in self.state_emission_counts[tag]:\n self.state_emission_counts[tag][token] += 1\n else:\n self.state_emission_counts[tag][token] = 1\n else:\n self.state_emission_counts[tag] = {}\n self.state_emission_counts[tag][token] = 1\n\n def update_state_transitions(self, prev_tag, tag):\n \"\"\"\n Updates transition probabiltry from prev_tag to tag\n\n Parameters:\n prev_tag -- string, pos\n tag -- string, pos\n \"\"\"\n if prev_tag in self.state_transition_counts:\n if tag in self.state_transition_counts[prev_tag]:\n self.state_transition_counts[prev_tag][tag] += 1\n else:\n self.state_transition_counts[prev_tag][tag] = 1\n else:\n self.state_transition_counts[prev_tag] = {}\n self.state_transition_counts[prev_tag][tag] = 1\n\n def predict(self, sentence):\n \"\"\"\n Predict most likely tag sequence\n\n Parameters:\n sentence -- list, [token1, token2, ... ]\n Returns:\n Most likely tag sequence for the sentence\n \"\"\"\n tagged_sentence, _ = self.viterbi(sentence)\n return tagged_sentence\n\n def viterbi(self, sentence):\n \"\"\"\n TODO: reimplement backtracking\n A sentence is a list of tuples. Here our goal is to infer the most likely tag sequence\n for the given sentence, therefore, input sentence will be just list of tokens\n\n Parameters:\n sentence -- list\n Returns:\n tagged_sentence -- list of tuples, [ (token, tag) ... (token, tag) ]\n \"\"\"\n delta = np.zeros(shape=(len(self.state_transitions), len(sentence)), dtype=float)\n tagged_sentence = []\n\n for next_tag in self.state_transitions:\n if next_tag != '':\n if next_tag in self.state_transitions['']:\n a = self.a('', next_tag)\n else:\n a = 0.\n\n if sentence[0] not in self.state_emissions[next_tag]:\n b = self.b(next_tag, 'unkwn')\n else:\n b = self.b(next_tag, sentence[0])\n\n idx = self.pos_index[next_tag]\n delta[idx, 0] = a * b\n\n ml_tag = self.inv_pos_index[np.argmax(delta[:, 0])] # holds most likely tag at the specific time step\n tagged_sentence.append((sentence[0], ml_tag))\n\n for j in range(1, len(sentence)):\n for next_tag in self.state_transitions:\n if next_tag != '':\n next_tag_idx = self.pos_index[next_tag]\n if sentence[j] not in self.state_emissions[next_tag]:\n b = self.b(next_tag, 'unkwn')\n else:\n b = self.b(next_tag, sentence[j])\n\n for tag in self.state_transitions:\n if next_tag in self.state_transitions[tag]:\n a = self.a(tag, next_tag)\n else:\n a = 0.\n tag_idx = self.pos_index[tag]\n temp = delta[tag_idx, j - 1] * a * b\n if temp > delta[next_tag_idx, j]:\n delta[next_tag_idx, j] = temp\n\n ml_tag = self.inv_pos_index[np.argmax(delta[:, j])]\n tagged_sentence.append((sentence[j], ml_tag))\n\n return tagged_sentence, delta\n\n def b(self, tag, token):\n \"\"\"\n Returns probabilty of emitting the token given the tag\n\n Parameters:\n tag -- string, pos\n token -- string, word\n Returns:\n emission probability\n \"\"\"\n return self.state_emissions[tag][token]\n\n def a(self, tag, next_tag):\n \"\"\"\n Returns transitions probabilty from tag to next_tag\n\n Parameters:\n tag -- string, pos\n next_tag -- string, pos\n Returns:\n state transition probability\n \"\"\"\n return self.state_transitions[tag][next_tag]\n\n def to_string(self):\n \"\"\"\n Forms a formated string containing all state transition and\n emission probabilities\n\n Returns:\n string -- string\n \"\"\"\n string = ''\n string += '{:s}\\n'.format('=' * 50)\n string += 'State transition probabilities for {:d} tags:\\n'.format(len(self.state_transitions))\n for prev_tag in self.state_transitions:\n string += '{:s}: '.format(prev_tag)\n for tag in self.state_transitions[prev_tag]:\n string += '{:s}({:f}) '.format(tag, self.state_transitions[prev_tag][tag])\n string += '\\n'\n\n string += '{:s}\\n'.format('=' * 50)\n string += 'State emission probabilities for {:d} tokens:\\n'.format(len(self.state_emissions))\n for tag in self.state_emissions:\n string += '{:s}: '.format(tag)\n for token in self.state_emissions[tag]:\n string += '{:s}({:f}) '.format(token, self.state_emissions[tag][token])\n string += '\\n'\n\n return string\n\n def print_array(self, delta, i):\n \"\"\"\n Parameters:\n delta -- 2D array of float\n i -- integer\n \"\"\"\n print('{}: '.format(i))\n for k in range(delta.shape[1]):\n if delta[i, k] > np.NINF:\n print('{:s}:{:f} '.format(self.inv_pos_index[k], delta[i, k]))\n print()\n\n def delta(self, s, j, delta):\n \"\"\"\n Parameters:\n s -- string\n i -- integer\n delta -- dictionary of dictionaries { int: {string: float} ...}\n Returns:\n \"\"\"\n if j in delta:\n if s in delta[j]:\n return float(delta[s])\n return 0.\n","sub_path":"assignment_2/hmm_tagger.py","file_name":"hmm_tagger.py","file_ext":"py","file_size_in_byte":10228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"74791885","text":"import timeit\nimport json\nimport os, sys\n\nclass Solution:\n\n def __init__(self):\n self.REPO_OWNER = \"\"\n self.REPO_URL = \"\"\n self.FILENAME = \"\"\n self.DAY = 18\n self.YEAR = 2020\n\n def part_1(self):\n pass\n\n def part_2(self):\n pass\n\n def assert_solution(self, number_of_runs=1000):\n\n with open(os.path.dirname(__file__) + '/solution.txt', \"r\") as r:\n solution_1, solution_2 = r.readline().split(\",\")\n print(f\"Running the solutions of {self.REPO_OWNER}({self.REPO_URL})\")\n\n assert solution_1 == str(self.part_1()), f\"Answer incorrect: answer is {solution_1}, your answer is {str(self.part_1())}\"\n assert solution_2 == str(self.part_2()), f\"Answer incorrect: answer is {solution_2}, your answer is {str(self.part_2())}\"\n print(\"Solutions to both parts of the problem are correct\")\n\n time_part1 = timeit.timeit(self.part_1, number=number_of_runs) / number_of_runs\n print(f\"Finished timing part 1: {time_part1}\")\n time_part2 = timeit.timeit(self.part_2, number=number_of_runs) / number_of_runs\n print(f\"Finished timing part 2: {time_part2}\")\n self.save_times(time_part1, time_part2)\n \n def format_run_time(self, s):\n if s <= 1:\n return str(round(s *1000, 4)) + \" (ms)\"\n elif s <= 0.001:\n return str(round(s *1000000, 4)) + \" (μs)\"\n elif s <= 0.000001:\n return str(round(s *1000000000, 4)) + \" (ns)\"\n else:\n return str(round(s, 4)) + \" (s)\"\n\n\n def save_times(self, time_part1, time_part2):\n\n with open(os.path.dirname(__file__) + '/scores.json', 'r') as r:\n scores = json.load(r)\n\n repo_times = {\n \"time_part_1\" : time_part1,\n \"time_part_2\" : time_part2,\n \"time_mean\" : (time_part1 + time_part2) / 2,\n \"url\" : self.REPO_URL,\n \"filename\" : self.FILENAME\n }\n\n scores[self.REPO_OWNER] = repo_times\n with open(os.path.dirname(__file__) + '/scores.json', 'w') as f:\n json.dump(scores, f)\n \n readmd = f'## Scoring for day {self.DAY} of the advent of code {self.YEAR}\\n| Github repo | Score part 1 | Score part 2 | Filename |\\n| ------------- | ------------- | ------------- | ------------- |\\n'\n\n for w in sorted(scores, key=lambda x: scores[x]['time_mean']):\n sp1 = self.format_run_time(scores[w]['time_part_1'])\n sp2 = self.format_run_time(scores[w]['time_part_2'])\n readmd += f\"| [{w}]({scores[w]['url']}) | {sp1} | {sp2} | [{os.path.basename(scores[w]['filename'])}]({scores[w]['filename']}) |\\n\"\n \n with open('README.md', 'w') as writer:\n writer.write(readmd)\n print(\"Saved run to README.md\")","sub_path":"2020/day 18/baseclass.py","file_name":"baseclass.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"136491775","text":"# Copyright 2017 The Bazel Authors. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Bazel rules for creating tvOS applications and bundles.\n\nDO NOT load this file directly; use the macro in\n@build_bazel_rules_apple//apple:tvos.bzl instead. Bazel rules receive their name at\n*definition* time based on the name of the global to which they are assigned.\nWe want the user to call macros that have the same name, to get automatic\nbinary creation, entitlements support, and other features--which requires a\nwrapping macro because rules cannot invoke other rules.\n\"\"\"\n\nload(\"@build_bazel_rules_apple//apple/bundling:binary_support.bzl\", \"binary_support\")\nload(\"@build_bazel_rules_apple//apple/bundling:bundler.bzl\", \"bundler\")\nload(\"@build_bazel_rules_apple//apple/bundling:bundling_support.bzl\",\n \"bundling_support\")\nload(\"@build_bazel_rules_apple//apple/bundling:product_support.bzl\",\n \"apple_product_type\")\nload(\"@build_bazel_rules_apple//apple/bundling:rule_factory.bzl\",\n \"rule_factory\")\nload(\"@build_bazel_rules_apple//apple/bundling:run_actions.bzl\", \"run_actions\")\nload(\"@build_bazel_rules_apple//apple:providers.bzl\",\n \"AppleBundleInfo\",\n \"AppleResourceSet\",\n \"TvosApplicationBundleInfo\",\n \"TvosExtensionBundleInfo\")\n\n\ndef _tvos_application_impl(ctx):\n \"\"\"Implementation of the `tvos_application` Skylark rule.\"\"\"\n\n app_icons = ctx.files.app_icons\n if app_icons:\n bundling_support.ensure_single_xcassets_type(\n \"app_icons\", app_icons, \"brandassets\")\n launch_images = ctx.files.launch_images\n if launch_images:\n bundling_support.ensure_single_xcassets_type(\n \"launch_images\", launch_images, \"launchimage\")\n\n # Collect asset catalogs and launch images, if any are present.\n additional_resource_sets = []\n additional_resources = depset(app_icons + launch_images)\n if additional_resources:\n additional_resource_sets.append(AppleResourceSet(\n resources=additional_resources,\n ))\n\n # If a settings bundle was provided, pass in its files as if they were\n # objc_bundle imports, but forcing the \"Settings.bundle\" name.\n settings_bundle = ctx.attr.settings_bundle\n if settings_bundle:\n additional_resource_sets.append(AppleResourceSet(\n bundle_dir=\"Settings.bundle\",\n objc_bundle_imports=[\n bf.file for bf in settings_bundle.objc.bundle_file\n ]\n ))\n\n # TODO(b/32910122): Obtain framework information from extensions.\n embedded_bundles = [\n bundling_support.embedded_bundle(\n \"PlugIns\", extension, verify_has_child_plist=True)\n for extension in ctx.attr.extensions\n ]\n\n binary_artifact = binary_support.get_binary_provider(\n ctx.attr.deps, apple_common.AppleExecutableBinary).binary\n deps_objc_provider = binary_support.get_binary_provider(\n ctx.attr.deps, apple_common.AppleExecutableBinary).objc\n additional_providers, legacy_providers = bundler.run(\n ctx,\n \"TvosExtensionArchive\", \"tvOS application\",\n ctx.attr.bundle_id,\n binary_artifact=binary_artifact,\n additional_resource_sets=additional_resource_sets,\n embedded_bundles=embedded_bundles,\n deps_objc_providers=[deps_objc_provider],\n extra_runfiles=run_actions.start_simulator(ctx),\n )\n\n return struct(\n providers=[\n TvosApplicationBundleInfo(),\n ] + additional_providers,\n **legacy_providers\n )\n\n\ntvos_application = rule_factory.make_bundling_rule(\n _tvos_application_impl,\n additional_attrs={\n \"app_icons\": attr.label_list(allow_files=True),\n \"extensions\": attr.label_list(\n providers=[[AppleBundleInfo, TvosExtensionBundleInfo]],\n ),\n \"launch_images\": attr.label_list(allow_files=True),\n \"settings_bundle\": attr.label(providers=[[\"objc\"]]),\n },\n archive_extension=\".ipa\",\n bundles_frameworks=True,\n code_signing=rule_factory.code_signing(\".mobileprovision\"),\n device_families=rule_factory.device_families(allowed=[\"tv\"]),\n needs_pkginfo=True,\n executable=True,\n path_formats=rule_factory.simple_path_formats(\n path_in_archive_format=\"Payload/%s\"\n ),\n platform_type=apple_common.platform_type.tvos,\n product_type=rule_factory.product_type(\n apple_product_type.application, private=True,\n ),\n)\n\n\ndef _tvos_extension_impl(ctx):\n \"\"\"Implementation of the `tvos_extension` Skylark rule.\"\"\"\n binary_artifact = binary_support.get_binary_provider(\n ctx.attr.deps, apple_common.AppleExecutableBinary).binary\n deps_objc_provider = binary_support.get_binary_provider(\n ctx.attr.deps, apple_common.AppleExecutableBinary).objc\n additional_providers, legacy_providers = bundler.run(\n ctx,\n \"TvosExtensionArchive\", \"tvOS extension\",\n ctx.attr.bundle_id,\n binary_artifact=binary_artifact,\n deps_objc_providers=[deps_objc_provider],\n )\n\n return struct(\n providers=[\n TvosExtensionBundleInfo(),\n ] + additional_providers,\n **legacy_providers\n )\n\n\ntvos_extension = rule_factory.make_bundling_rule(\n _tvos_extension_impl,\n archive_extension=\".zip\",\n code_signing=rule_factory.code_signing(\".mobileprovision\"),\n device_families=rule_factory.device_families(allowed=[\"tv\"]),\n path_formats=rule_factory.simple_path_formats(path_in_archive_format=\"%s\"),\n platform_type=apple_common.platform_type.tvos,\n product_type=rule_factory.product_type(\n apple_product_type.app_extension, private=True,\n ),\n)\n","sub_path":"apple/bundling/tvos_rules.bzl","file_name":"tvos_rules.bzl","file_ext":"bzl","file_size_in_byte":5962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"553796825","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom setuptools import setup\n\n\nrequirements = [\n 'pyautogui',\n 'numba',\n 'PyQt5'\n]\ntest_requirements = [\n 'pyautogui',\n 'PyQt5'\n]\n\nsetup(\n name='labelImg',\n version='1.3.4',\n description=\"LabelImg is a graphical image annotation tool and label object bounding boxes in images\",\n author=\"TzuTa Lin\",\n author_email='tzu.ta.lin@gmail.com',\n url='https://github.com/vanderschuea/roLabelImg',\n packages=[\n 'labelImg', 'labelImg.labelimg'\n ],\n package_dir={'labelImg': '.'},\n entry_points={\n 'console_scripts': [\n 'labelImg=labelImg:main'\n ]\n },\n include_package_data=True,\n install_requires=requirements,\n license=\"MIT license\",\n zip_safe=False,\n keywords='labelImg',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3.6',\n ],\n test_suite='tests',\n tests_require=test_requirements\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"309143155","text":"from pages import ContactsPage\nfrom pages import GroupListPage\nfrom pages import MessagePage\nfrom preconditions.BasePreconditions import WorkbenchPreconditions\n\n\ndef delete_all_group_chat():\n \"\"\"删除所有群聊\"\"\"\n WorkbenchPreconditions.select_mobile('IOS-移动')\n try:\n mp = MessagePage()\n mp.open_contacts_page()\n cp = ContactsPage()\n cp.wait_for_page_load()\n cp.open_group_chat_list()\n glp = GroupListPage()\n glp.wait_for_page_load()\n glp.delete_all_group_chat()\n finally:\n WorkbenchPreconditions.disconnect_mobile('IOS-移动')\n\n\nif __name__ == '__main__':\n delete_all_group_chat()\n","sub_path":"clear_group.py","file_name":"clear_group.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"334341659","text":"# Copyright 2013 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport logging\nimport os\n\nimport fabric.exceptions\n\nfrom shotgun.driver import Driver\nfrom shotgun import utils\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Manager(object):\n def __init__(self, conf):\n logger.debug(\"Initializing snapshot manager\")\n self.conf = conf\n\n def snapshot(self):\n logger.debug(\"Making snapshot\")\n utils.execute(\"rm -rf {0}\".format(os.path.dirname(self.conf.target)))\n for obj_data in self.conf.objects:\n logger.debug(\"Dumping: %s\", obj_data)\n self.action_single(obj_data, action='snapshot')\n\n logger.debug(\"Dumping shotgun log and archiving dump directory: %s\",\n self.conf.target)\n self.action_single(self.conf.self_log_object, action='snapshot')\n\n utils.compress(self.conf.target, self.conf.compression_level)\n\n with open(self.conf.lastdump, \"w\") as fo:\n fo.write(\"{0}.tar.xz\".format(self.conf.target))\n return \"{0}.tar.xz\".format(self.conf.target)\n\n def action_single(self, object, action='snapshot'):\n driver = Driver.getDriver(object, self.conf)\n try:\n return getattr(driver, action)()\n except fabric.exceptions.NetworkError:\n self.conf.on_network_error(object)\n\n def report(self):\n logger.debug(\"Making report\")\n for obj_data in self.conf.objects:\n logger.debug(\"Gathering report for: %s\", obj_data)\n for report in self.action_single(obj_data, action='report'):\n yield report\n","sub_path":"shotgun/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"625278654","text":"from flask import render_template, session, redirect, url_for, current_app\nfrom .. import db\nfrom ..models import User\nfrom ..email import send_email\nfrom . import main\nfrom .forms import NameForm\n\n\n@main.route('/', methods=['GET', 'POST'])\ndef index():\n form = NameForm()\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.name.data).first()\n if user is None:\n user = User(username=form.name.data)\n db.session.add(user)\n session['known'] = False\n if current_app.config['FLASKY_ADMIN']:\n send_email(current_app.config['FLASKY_ADMIN'], 'New User',\n 'mail/new_user', user=user)\n else:\n session['known'] = True\n session['name'] = form.name.data\n return redirect(url_for('.index'))\n return render_template('index.html',\n form=form, name=session.get('name'),\n known=session.get('known', False))\n\n\"\"\"\nurl_for() 函数的第一个参数是路由的端点名,在程序的路由中,默认为视图函数的名字。\n例如,在单脚本程序中, index() 视图函数的 URL 可使用 url_for('index') 获取。\n\n在蓝本中就不一样了,Flask 会为蓝本中的全部端点加上一个命名空间,这样就可以在不同的蓝本中使用相同的端点名定义视图函数,而不会产生冲突。\n命名空间就是蓝本的名字( Blueprint 构造函数的第一个参数),所以视图函数 index() 注册的端点名是 main.index ,其 URL 使用 url_for('main.index') 获取。\n\nurl_for() 函数还支持一种简写的端点形式,在蓝本中可以省略蓝本名,例如 url_for('.index')\n在这种写法中,命名空间是当前请求所在的蓝本。这意味着同一蓝本中的重定向可以使用简写形式,但跨蓝本的重定向必须使用带有命名空间的端点名\n\"\"\"\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"517125637","text":"import numpy as np\nimport unittest\nimport lsst.sims.featureScheduler as fs\nimport lsst.utils.tests\n\n\nclass TestFeatures(unittest.TestCase):\n\n def testPair_in_night(self):\n pin = fs.Pair_in_night(gap_min=25., gap_max=45.)\n self.assertEqual(np.max(pin.feature), 0.)\n\n indx = np.array([1000])\n\n delta = 30./60./24.\n\n # Add 1st observation, feature should still be zero\n obs = fs.empty_observation()\n obs['filter'] = 'r'\n obs['mjd'] = 59000.\n pin.add_observation(obs, indx=indx)\n self.assertEqual(np.max(pin.feature), 0.)\n\n # Add 2nd observation\n obs['mjd'] += delta\n pin.add_observation(obs, indx=indx)\n self.assertEqual(np.max(pin.feature), 1.)\n\n obs['mjd'] += delta\n pin.add_observation(obs, indx=indx)\n self.assertEqual(np.max(pin.feature), 2.)\n\n # XXX--test that it clears if a new night rolls over\n\n\nclass TestMemory(lsst.utils.tests.MemoryTestCase):\n pass\n\n\ndef setup_module(module):\n lsst.utils.tests.init()\n\n\nif __name__ == \"__main__\":\n lsst.utils.tests.init()\n unittest.main()\n","sub_path":"tests/testFeatures.py","file_name":"testFeatures.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"332699723","text":"import urllib.request\nimport pandas as pd\nfrom scipy import stats\nimport datetime as dt\nimport pandas_datareader.data as web\nimport numpy as np\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nimport matplotlib.pyplot as plt\n\n\nclass CreateVix():\n\n def __init__(self):\n self.get_vix_spot()\n self.get_vix_3m()\n self.get_uvxy()\n\n def get_vix_spot(self):\n # we import the other the data from yahoo finance\n vix_spot = web.DataReader(\"^VIX\", 'yahoo', start = dt.datetime(2012,12,31))\n\n # formatting column names\n vix_spot.columns = vix_spot.columns.str.lower().str.replace(\" \",\"_\")\n\n # dropping unnecessaries and changing colnames\n vix_spot = vix_spot[['close','high']]\n vix_spot.rename(columns = {'close':'spot_close','high':'spot_high'}, inplace = True)\n\n self.vix_spot = vix_spot\n\n def get_vix_3m(self):\n\n # ^vix3m is imported from csv data from cboe website\n # However, the data for today is not updated frequently...\n\n vix_3m = pd.read_csv(urllib.request.urlopen(\n 'http://www.cboe.com/publish/scheduledtask/mktdata/datahouse/vix3mdailyprices.csv'),\n skiprows = 2, index_col = 0)\n vix_3m = vix_3m.loc['12/31/2012':,:]\n\n # change the type of index to datetime\n vix_3m.index = pd.to_datetime(pd.Series(vix_3m.index), format = \"%m/%d/%Y\")\n\n # formatting column names\n vix_3m.columns = vix_3m.columns.str.lower().str.replace(\" \",\"_\")\n\n # if it is during the trading hours, we get the last row of vix_3m from yahoo finance\n if dt.datetime.today().weekday() in range(5):\n if vix_3m.tail(1).index[0] ==(dt.datetime.now()- dt.timedelta(days = 1)).strftime(\"%m/%d/%Y\"):\n last_line_vix3m = web.DataReader(\"^VIX3M\", 'yahoo')\n last_line_vix3m.columns = last_line_vix3m.columns.str.lower().str.replace(\" \",\"_\")\n last_line_vix3m = last_line_vix3m[['open', 'high','low', 'close']]\n vix_3m = pd.concat([vix_3m, last_line_vix3m])\n\n # we are going to create variables that will compare opening price to highest price which will be denoted as \"oh\"\n # we are going to create variables that will compare closing price to highest price which will be denoted as \"ch\"\n # we are going to create variables that will compare highest price to lowest price which will be denoted as \"lh\"\n\n\n vix_3m['oh'] = (vix_3m['high'] - vix_3m['open'])/(vix_3m['open'])\n vix_3m['ch'] = (vix_3m['high'] - vix_3m['close'])/(vix_3m['close'])\n vix_3m['lh']= (vix_3m['high'] - vix_3m['low'])/(vix_3m['low'])\n\n # ohl and chl in previous trading days\n # ohl1 : ohl of the last trading day\n for a,b,c,m, n in zip(np.repeat(\"oh_\", 10),np.repeat(\"ch_\", 10),np.repeat(\"lh_\", 10),list('0123456789'), range(9)):\n name1 = a+m\n name2 = b+m\n name3 = c+m\n\n\n vix_3m[name1] = np.nan\n vix_3m[name2]= np.nan\n vix_3m[name3] = np.nan\n vix_3m[name1] = vix_3m['oh'] - vix_3m['oh'].rolling(window = n+2, min_periods=n+2).mean()\n vix_3m[name2]= vix_3m['ch']- vix_3m['ch'].rolling(window = n+2, min_periods=n+2).mean()\n vix_3m[name3]= vix_3m['lh']- vix_3m['ch'].rolling(window = n+2, min_periods=n+2).mean()\n\n self.vix_3m = vix_3m\n\n\n\n def get_uvxy(self):\n uvxy = web.DataReader(\"UVXY\", 'yahoo', start = dt.datetime(2012,12,31))\n uvxy.columns = uvxy.columns.str.lower().str.replace(\" \",\"_\")\n\n # the structure changed as of 2/27/2018\n\n\n # uvxy.change is the price change in percentage\n # c1 = change from last day\n # c2 = change from two days ago\n # c3 = change from three days ago\n cs = ['c1','c2','c3']\n\n for r in range(len(cs)):\n uvxy[cs[r]] = np.nan\n for i in range(len(uvxy)-(r+1)):\n uvxy[cs[r]][i+(r+1)] = round((uvxy['adj_close'][i+(r+1)] - uvxy['adj_close'][i])/uvxy['adj_close'][i]*100 ,2)\n\n\n\n for d, m, n in zip(np.repeat(\"diff_from_min_\", 8), list('23456789'), range(7) ):\n name = d+m\n uvxy[name] = (uvxy['adj_close'] - uvxy['adj_close'].rolling(window = n+2, min_periods = n+2).min())/uvxy['adj_close'].rolling(window = n+2, min_periods = n+2).min()\n\n\n # diff_from_max\n # diff_from_max1 = 5 days / 5\n # diff_from_max2 = 15 days / 15\n\n uvxy['diff_from_max1'] = np.nan\n uvxy['diff_from_max2'] = np.nan\n\n uvxy['diff_from_max1'] = uvxy['high'].rolling(window = 5, min_periods = 5).max()/uvxy['adj_close']\n uvxy['diff_from_max2'] = uvxy['high'].rolling(window = 15, min_periods = 15).max()/uvxy['adj_close']\n\n\n # we need to take logarithm to make it normally distributed\n uvxy['diff_from_min'] = (uvxy['adj_close'] - uvxy['low'].rolling(window = 5, min_periods = 5).min())/uvxy['low'].rolling(window = 5, min_periods = 5).min()\n uvxy['diff_from_min'] = np.log(uvxy['diff_from_min'] - uvxy['diff_from_min'].min() + 1)\n self.uvxy = uvxy\n","sub_path":"DeepLearningAnalysis/src/sp/create_vix.py","file_name":"create_vix.py","file_ext":"py","file_size_in_byte":5192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"436449390","text":"\"\"\"\nAuthor: Mihai Andries\nWebsite: https://gitlab.com/mandries/binvox2mesh\n\"\"\"\n\nimport numpy as np\nimport trimesh\nimport trimesh.voxel.ops as tv # for converting voxel grids to meshes (to import objects into simulators)\nimport time # to know how long it takes for the code to run\nimport os # to walk through directories, to rename files\nimport sys\n\nimport binvox_rw # to manipulate binvox files\n\n# Parses a file of type BINVOX\n# Returns a voxel grid, generated using the binvox_rw.py package\ndef parse_BINVOX_file_into_voxel_grid(filename):\n filereader = open(filename, 'rb')\n binvox_model = binvox_rw.read_as_3d_array(filereader)\n voxelgrid = binvox_model.data\n return voxelgrid\n\nif __name__ == \"__main__\":\n \n print(\"Usage: \")\n print(\"python binvox2mesh.py \")\n \n filename = sys.argv[1]\n \n # Load the voxelgrid from file\n voxelgrid = parse_BINVOX_file_into_voxel_grid(filename)\n\n # Generate a folder to store the images\n print(\"Generating a folder to save the mesh\")\n directory = \"./binvox2mesh_\" + filename\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n mesh = tv.matrix_to_marching_cubes(\n matrix=voxelgrid,\n pitch=1.0)\n\n print(\"Merging vertices closer than a pre-set constant...\")\n mesh.merge_vertices()\n print(\"Removing duplicate faces...\")\n mesh.remove_duplicate_faces()\n print(\"Scaling...\")\n mesh.apply_scale(scaling=1.0)\n print(\"Making the mesh watertight...\")\n trimesh.repair.fill_holes(mesh)\n print(\"Fixing inversion and winding...\")\n trimesh.repair.fix_inversion(mesh)\n trimesh.repair.fix_winding(mesh)\n\n print(\"Generating the STL mesh file\")\n trimesh.exchange.export.export_mesh(\n mesh=mesh,\n file_obj=directory + \"/mesh.stl\",\n file_type=\"stl\"\n )\n","sub_path":"code/ImageProcessingPipeline/binvox2mesh.py","file_name":"binvox2mesh.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"128563524","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 3 12:27:16 2018\n\n@author: James Jiang\n\"\"\"\n\nall_lines = [line.rstrip('\\n') for line in open('Data.txt')]\n\ntotal = 0\n\nfor line in all_lines:\n subtotal = 0\n i = 0\n while i in range(len(line)):\n if line[i] == '\\\\':\n if line[i + 1] in ['\"', '\\\\']:\n subtotal += 1\n i += 2\n elif line[i + 1] == 'x':\n subtotal += 3\n i += 4\n else:\n i += 1\n total += subtotal + 2\n \nprint(total)\n","sub_path":"python/2015day8part1.py","file_name":"2015day8part1.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"493594476","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\nimport time\nimport numpy as np\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import KFold\nfrom sklearn import svm\nfrom grakel import datasets\nfrom grakel import GraphKernel\n\n\nkernels = {\n \"Shortest Path\": [{\"name\": \"shortest_path\", \"with_labels\": False}],\n\n \"Graphlet Sampling\": [{\"name\": \"graphlet_sampling\",\n \"sampling\": {\"n_samples\": 500}}],\n\n \"Weisfeiler-Lehman/Subtree\": [{\"name\": \"weisfeiler_lehman\", \"niter\": 5},\n {\"name\": \"subtree_wl\"}],\n\n \"Pyramid match\": [{\"name\": \"pyramid_match\", \"d\": 6, \"L\": 4, \"with_labels\": False}],\n\n \"Core Shortest Path\": [{\"name\": \"core_framework\"},\n {\"name\": \"shortest_path\", \"with_labels\": False}],\n\n \"Core Graphlet Sampling\": [{\"name\": \"core_framework\"},\n {\"name\": \"graphlet_sampling\", \"sampling\": {\"n_samples\": 500}}],\n\n \"Core Weisfeiler-Lehman/Subtree\": [{\"name\": \"core_framework\"},\n {\"name\": \"weisfeiler_lehman\", \"niter\": 5},\n {\"name\": \"subtree_wl\"}],\n\n \"Core Pyramid match\": [{\"name\": \"core_framework\"},\n {\"name\": \"pyramid_match\", \"d\": 6, \"L\": 4, \"with_labels\": False}]\n}\n\nDatasets = [\"IMDB-BINARY\", \"IMDB-MULTI\", \"REDDIT-BINARY\", \"REDDIT-MULTI-5K\", \"REDDIT-MULTI-12K\"]\nMethods = sorted(list(kernels.keys()))\n\nfor j, d in enumerate(Datasets):\n print(d)\n dataset_d = datasets.fetch_dataset(d, verbose=False, data_home=\"../dataset\", produce_labels_nodes=True)\n G, y = np.asarray(dataset_d.data), np.asarray(dataset_d.target)\n\n stats = {m: {\"acc\": list(), \"time\": list()} for m in Methods}\n\n kfold = KFold(n_splits=10, random_state=50, shuffle=True)\n\n for train_idx, test_idx in kfold.split(G, y):\n train_g, train_y = G[train_idx], y[train_idx]\n test_g, test_y = G[test_idx], y[test_idx]\n\n for i, k in enumerate(Methods):\n gk = GraphKernel(kernel=kernels[k], normalize=True)\n\n start = time.time()\n k_train = gk.fit_transform(train_g)\n k_test = gk.transform(test_g)\n end = time.time()\n\n clf = svm.SVC(kernel='precomputed')\n clf.fit(k_train, train_y)\n\n pred_y = clf.predict(k_test)\n\n stats[k][\"acc\"].append(accuracy_score(test_y, pred_y))\n stats[k][\"time\"].append(end - start)\n\n for m in Methods:\n print(\"kernel: \", m,\n \"time: \", np.round(np.mean(stats[m][\"time\"]), 2), \"~\", np.round(np.std(stats[m][\"time\"]), 2),\n \"acc: \", np.round(np.mean(stats[m][\"acc\"]), 2), \"~\", np.round(np.std(stats[m][\"acc\"]), 2))\n","sub_path":"src/social.py","file_name":"social.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"568961940","text":"\nimport re\nimport json\nimport csv\nimport pandas as pd\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.layers.recurrent import LSTM\nfrom keras.preprocessing.text import text_to_word_sequence\n\njoke_paths = [\"joke-dataset/wocka.json\", \"joke-dataset/stupidstuff.json\", \"joke-dataset/reddit_jokes.json\"]\nnon_joke_paths = [\"sentence-dataset/sentences.csv\"]\nWORD_EMBEDDINGS_PATH = 'word-embeddings/saved_glovedata.json'\n\nMIN_JOKE_LENGTH = 10\nMAX_JOKE_LENGTH = 40\n\n\njoke_vocabulary = {}\n\ndef loadJokes():\n training_jokes = []\n test_jokes = []\n i = 0\n for filename in sorted(joke_paths):\n with open(filename) as f:\n joke_data = json.load(f)\n for joke in joke_data:\n\n if filename == joke_paths[0]:\n joke_rating = -1\n joke_id = joke[\"id\"]\n joke_body = joke[\"body\"]\n\n elif filename == joke_paths[1]:\n joke_rating = float(joke[\"rating\"]) * 2\n joke_id = joke[\"id\"]\n joke_body = joke[\"body\"]\n\n elif filename == joke_paths[2]:\n joke_body = joke[\"title\"] + joke[\"body\"]\n joke_id = joke[\"id\"]\n score = float(joke[\"score\"]) / 10\n joke_rating = min([score, 10])\n\n else:\n print(\"error?\")\n\n joke_body = text_to_word_sequence(joke_body)\n joke_length = len(joke_body)\n if joke_length < MAX_JOKE_LENGTH and joke_length > MIN_JOKE_LENGTH:\n for word in joke_body:\n if joke_vocabulary.get(word) == None:\n joke_vocabulary[word] = i\n i = i + 1\n if joke_rating == 0:\n if np.random.rand() > .01:\n joke_rating = np.random.rand() * 10\n elif joke_rating < 1.5:\n joke_rating += np.random.rand() * 5\n if filename == joke_paths[0]:\n test_jokes.append([joke_body, joke_rating])\n else:\n if np.random.rand() > 0.7:\n test_jokes.append([joke_body, joke_rating])\n else:\n\n training_jokes.append([joke_body, joke_rating])\n return [training_jokes, test_jokes]\n\ndef nonJokes():\n non_jokes = []\n for filename in sorted(non_joke_paths):\n with open(filename) as f:\n reader = csv.reader(f)\n for line in reader:\n if len(str(line)) > 45:\n non_jokes.append(line)\n return non_jokes\n\ndef loadGloveModel():\n try: # letting it just load each time until I find a better way to save my dict of np arrays\n print(\"Trying to load pre-saved Glove Model\")\n with open(WORD_EMBEDDINGS_PATH, 'r') as fp:\n model = json.load(fp)\n return model\n except:\n print(\"Reloading Glove Model from Scratch...\")\n gloveFile = \"word-embeddings/glove.mod.300d.txt\"\n f = open(gloveFile,'r')\n model = {}\n for i, line in enumerate(f):\n splitLine = line.split()\n word = splitLine[0]\n embedding = np.array(splitLine[1:], dtype=float)\n model[word] = embedding\n if i%100000 == 0:\n print('read in %d words', i)\n # with open(WORD_EMBEDDINGS_PATH, 'w') as fp:\n # json.dump(model, fp)\n # print(\"Saved \", len(model), \" words to file system!\")\n print(\"Done. \", len(model), \" words loaded!\")\n return model\n\n[training_jokes, test_jokes] = loadJokes()\n#non_jokes = nonJokes()\n\nprint(\"we have \", len(training_jokes), \" training jokes\")\nprint(\"we have \", len(test_jokes), \" test jokes\")\n#print(\"we have \", len(non_jokes), \" non-jokes\")\n\n# print(len(joke_vocabulary)) = 248676, log base 2 < 18\n\n#for word in joke_vocabulary: # only adding words that I have encodings for, otherwise just skipping them lol - probably best fixed with preprocessing\n\n# joke_vocabulary[word] = list('{0:018b}'.format(8))\n\njoke_vocabulary = loadGloveModel()\n\ntraining_joke_bodies = []\ntraining_joke_ratings = []\nfor joke_info in training_jokes:\n if joke_info[1] > 2:\n training_joke_ratings.append(np.array([1, 0]))\n else:\n training_joke_ratings.append(np.array([0, 1]))\n # training_joke_ratings.append(joke_info[1])\n embedded_joke = []\n for word in joke_info[0]:\n try:\n encoding = joke_vocabulary[word]\n embedded_joke.append(encoding)\n except KeyError:\n pass\n while len(embedded_joke) < MAX_JOKE_LENGTH:\n embedded_joke.append(joke_vocabulary['...'])\n embedded_joke = np.array(embedded_joke)\n training_joke_bodies.append(embedded_joke)\ntraining_joke_bodies = np.array(training_joke_bodies)\ntraining_joke_ratings = np.array(training_joke_ratings)#.reshape((len(training_joke_ratings), 1, 1))\n\ntest_joke_bodies = []\ntest_joke_ratings = []\nfor joke_info in test_jokes:\n if joke_info[1] > 2:\n test_joke_ratings.append(np.array([1, 0]))\n else:\n test_joke_ratings.append(np.array([0, 1]))\n #test_joke_ratings.append(joke_info[1])\n embedded_joke = []\n for word in joke_info[0]:\n try:\n # only adding words that I have encodings for, otherwise just skipping them lol - probably best fixed with preprocessing\n encoding = joke_vocabulary[word]\n embedded_joke.append(encoding)\n except KeyError:\n pass\n while len(embedded_joke) < MAX_JOKE_LENGTH:\n embedded_joke.append(joke_vocabulary['...'])\n embedded_joke = np.array(embedded_joke)\n test_joke_bodies.append(embedded_joke)\ntest_joke_bodies = np.array(test_joke_bodies)\ntest_joke_ratings = np.array(test_joke_ratings)#.reshape((len(test_joke_ratings), 1, 1))\n\nprint('hi')\nprint(training_joke_bodies.shape)\nprint(training_joke_ratings.shape)\nprint(test_joke_bodies.shape)\nprint(test_joke_ratings.shape)\nprint(training_joke_bodies[0].shape, training_joke_bodies[5].shape, training_joke_bodies[30].shape)\n\n\nprint('0: ', len(training_joke_ratings[(training_joke_ratings == 0)]))\nprint('0-1: ', len(training_joke_ratings[( training_joke_ratings > 0 ) & (training_joke_ratings < 1)]))\nprint('1-2: ', len(training_joke_ratings[( training_joke_ratings >= 1 ) & (training_joke_ratings < 2)]))\nprint('2-3: ', len(training_joke_ratings[( training_joke_ratings >= 2 ) & (training_joke_ratings < 3)]))\nprint('3-4: ', len(training_joke_ratings[( training_joke_ratings >= 3 ) & (training_joke_ratings < 4)]))\nprint('4-5: ', len(training_joke_ratings[( training_joke_ratings >= 4 ) & (training_joke_ratings < 5)]))\nprint('5-6: ', len(training_joke_ratings[( training_joke_ratings >= 5 ) & (training_joke_ratings < 6)]))\nprint('6-7: ', len(training_joke_ratings[( training_joke_ratings >= 6 ) & (training_joke_ratings < 7)]))\nprint('7-8: ', len(training_joke_ratings[( training_joke_ratings >= 7 ) & (training_joke_ratings < 8)]))\nprint('8-9: ', len(training_joke_ratings[( training_joke_ratings >= 8 ) & (training_joke_ratings < 9)]))\nprint('9-10: ', len(training_joke_ratings[(training_joke_ratings >= 9)]))\n#\"\"\"\n\nin_out_neurons = (None, 300)\nhidden_neurons = 500\n\nmodel = Sequential()\n#model.add(LSTM(hidden_neurons, input_shape=in_out_neurons, return_sequences=True))\nmodel.add(LSTM(hidden_neurons, input_shape=(40, 300)))\n#model.add(LSTM(hidden_neurons, return_sequences=False))\nmodel.add(Dense(2))\n#model.add(Activation(\"relu\"))\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"rmsprop\")\n\n\n\n#(training_joke_bodies, training_joke_ratings), (test_joke_bodies, test_joke_ratings) = train_test_split(data) # retrieve data\nmodel.fit(training_joke_bodies, training_joke_ratings, batch_size=700, epochs=10, validation_split=0.05)\n\npredicted = model.predict(test_joke_bodies)\n#rmse = np.sqrt(((predicted - y_test) ** 2).mean(axis=0))\n\nwith open('results.txt', 'w') as f:\n for i, line in enumerate(predicted):\n original_joke = test_jokes[i]\n joke_text = original_joke[0]\n original_rating = original_joke[1]\n f.write('Joke: {}\\nTheir Rating: {} ::: Our Rating: {}\\n\\n'.format(joke_text, original_rating, line))\n\n\n# and maybe plot it\n#pd.DataFrame(predicted).to_csv(\"predicted.csv\")\n#pd.DataFrame(test_joke_ratings).to_csv(\"test_data.csv\")\n\n#\"\"\"\n\n\n\"\"\"\nimport pandas as pd\nfrom random import random\n\nflow = (list(range(1,10,1)) + list(range(10,1,-1)))*100\npdata = pd.DataFrame({\"a\":flow, \"b\":flow})\npdata.b = pdata.b.shift(9)\ndata = pdata.iloc[10:] * random() # some noise\n\nimport numpy as np\n\ndef _load_data(data, n_prev = 100):\n #data should be pd.DataFrame()\n\n docX, docY = [], []\n for i in range(len(data)-n_prev):\n docX.append(data.iloc[i:i+n_prev].as_matrix())\n docY.append(data.iloc[i+n_prev].as_matrix())\n alsX = np.array(docX)\n alsY = np.array(docY)\n\n return alsX, alsY\n\ndef train_test_split(df, test_size=0.1):\n #This just splits data to training and testing parts\n \n ntrn = round(len(df) * (1 - test_size))\n\n X_train, y_train = _load_data(df.iloc[0:ntrn])\n X_test, y_test = _load_data(df.iloc[ntrn:])\n\n return (X_train, y_train), (X_test, y_test)\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.layers.recurrent import LSTM\n\nin_out_neurons = 2\nhidden_neurons = 50\n\nmodel = Sequential()\nmodel.add(LSTM(hidden_neurons, input_dim=in_out_neurons, return_sequences=False))\nmodel.add(Dense(in_out_neurons, input_dim=hidden_neurons))\nmodel.add(Activation(\"relu\"))\nmodel.compile(loss=\"mean_squared_error\", optimizer=\"rmsprop\")\n\n\n(X_train, y_train), (X_test, y_test) = train_test_split(data) # retrieve data\nprint(X_train.shape, y_train.shape)\nprint(X_test.shape, y_test.shape)\nmodel.fit(X_train, y_train, batch_size=700, epochs=10, validation_split=0.05)\n\npredicted = model.predict(X_test)\nrmse = np.sqrt(((predicted - y_test) ** 2).mean(axis=0))\n\n# and maybe plot it\npd.DataFrame(predicted).to_csv(\"predicted.csv\")\npd.DataFrame(y_test).to_csv(\"test_data.csv\")\n\"\"\"","sub_path":"RNN for humorset-classification.py","file_name":"RNN for humorset-classification.py","file_ext":"py","file_size_in_byte":10262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"1141140","text":"import os\nimport sqlite3\nfrom enum import Enum\nimport nltk\nfrom nltk import ne_chunk, pos_tag, word_tokenize\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import TweetTokenizer\nfrom nltk.tree import Tree\nimport shutil\n\n\nclass DbControl(object):\n dbname = '.\\\\words.sqlite'\n\n def __init__(self):\n self.db = sqlite3.connect(self.dbname)\n self.cursor = self.db.cursor()\n\n # words table opereate\n def words_add(self, word_weight):\n self.cursor.executemany(\"insert into words values(?,?)\", word_weight)\n self.db.commit()\n # PASSED\n\n def words_clear(self):\n self.cursor.execute(\"delete from words\")\n self.db.commit()\n # PASSED\n\n def words_gettable(self):\n self.cursor.execute(\"SELECT * FROM words;\")\n words = self.cursor.fetchall()\n return [w for w in words]\n # PASSED\n\n def words_updateweights(self, weights):\n std_weights = [[w[1], w[0]] for w in weights]\n self.cursor.executemany(\n \"update words set weights=? where word=?\", std_weights)\n self.db.commit()\n # PASSED\n # words table opereate\n\n # wordof OP\n def wordof_getarticleid(self, word):\n self.cursor.execute(\n \"select articleid from unlearnedin where word=?\", [word])\n return set(self.cursor.fetchall())\n # PASSED\n\n def wordof_getwords(self, articleid):\n self.cursor.execute(\n \"SELECT word FROM unlearnedin WHERE articleid=? \", [articleid])\n return self.cursor.fetchall()\n # PASSED\n def wordof_getweights(self, articleid):\n self.cursor.execute(\n \"SELECT unlearnedin.word,words.weights FROM unlearnedin inner join words on words.word=unlearnedin.word WHERE articleid=? \", [articleid])\n return self.cursor.fetchall()\n #PASSED\n def wordof_add(self, words, articleid):\n for w in words:\n self.cursor.execute(\n \"INSERT INTO unlearnedin VALUES(?,?)\", (w, articleid))\n self.db.commit()\n # PASSED\n # wordof OP\n\n # ARTICLES OP\n def articles_updateweight(self,articleids):\n self.cursor.executemany(\"update articles set weight=cast((unlearned*1.0/(learned+unlearned+over)*100) as int) where articleid=?\",articleids)\n self.db.commit()\n def articles_newlearn1(self, articleids):\n self.cursor.executemany(\n \"update articles set unlearned=unlearned-1,learned=learned+1 where articleid=?\", articleids)\n self.db.commit()\n self.articles_updateweight(articleids)\n\n def articles_newunlearn1(self, articleids):\n self.cursor.executemany(\n \"update articles set unlearned=unlearned+1,learned=learned-1 where articleid=?\", articleids)\n self.db.commit()\n self.articles_updateweight(articleids)\n # PASS\n\n def articles_get(self):\n self.cursor.execute(\"SELECT * FROM articles\")\n arts = list(self.cursor.fetchall())\n for index, art in enumerate(arts):\n arts[index] = [x if not x is None else 0 for x in art]\n return arts\n # 0|articleid|INTEGER|0||1\n # 1|title|TEXT|1||0\n # 2|weight|INTEGER|0||0\n # 3|unlearned|INTEGER|0||0\n # 4|learned|INTEGER|0||0\n # 5|over|INTEGER|0||0\n # PASSED\n\n # ARTICLES OP\n # ARTICLE OP\n\n def article_get(self, articleid):\n self.cursor.execute(\n \"SELECT title,weight,unlearned,learned,over FROM articles WHERE articleid=? LIMIT 1\", [articleid])\n return self.cursor.fetchone()\n # PASSED\n\n def article_getid(self, title):\n self.cursor.execute(\n \"SELECT articleid FROM articles WHERE title=? LIMIT 1\", [title])\n return self.cursor.fetchone()[0]\n # PASSED\n\n def article_add(self, title, unlearn, learn, over):\n weight = int(unlearn/(learn+unlearn+over)*100) # FIXME depart weigh\n self.cursor.execute(\"INSERT INTO articles(title,weight,learned,unlearned,over) VALUES(?,?,?,?,?)\",\n (title, weight, learn, unlearn, over))\n self.db.commit()\n idd = self.article_getid(title)\n return idd\n # ARTICLE OP\n\n def add_article_x(self, title, weight, unlearnedword, learned, unlearned, over):\n self.cursor.execute(\"INSERT INTO articles(title,weight,learned,unlearned,over) VALUES(?,?,?,?,?)\",\n (title, weight, learned, unlearned, over))\n self.db.commit()\n self.cursor.execute(\n \"SELECT articleid FROM articles WHERE title='?' LIMIT 1\", title)\n arti = self.cursor.fetchone()\n for w in unlearnedword:\n self.cursor.execute(\n \"INSERT INTO unlearnedin VALUES(?,?)\", (arti, w))\n self.db.commit()\n\n def add_article(self, title, weight, unlearn, learn, over):\n self.cursor.execute(\"INSERT INTO articles(title,weight,learned,unlearned,over) VALUES(?,?,?,?,?)\",\n (title, weight, learn, unlearn, over))\n self.db.commit()\n idd = self.article_getid(title)\n return idd\n\n def add_article_words(self, words, articleid):\n for w in words:\n self.cursor.execute(\n \"INSERT INTO unlearnedin VALUES(?,?)\", (w, articleid))\n self.db.commit()\n\n\nclass nltkhelper:\n lemmatizer = WordNetLemmatizer()\n tokenizer = TweetTokenizer()\n # TESTED\n @staticmethod\n def tokenize(sent):\n return nltkhelper.tokenizer.tokenize(sent)\n\n @staticmethod\n def pos_tag(sent):\n return nltk.pos_tag(sent, tagset='universal')\n\n @staticmethod\n def peek_tag(sent):\n return ne_chunk(nltk.pos_tag(sent))\n\n @staticmethod\n def lemmatize(word, p):\n return nltkhelper.lemmatizer.lemmatize(word.lower(), p).lower()\n\n @staticmethod\n def get_pos(tag):\n if tag in ['NOUN', 'VERB', 'ADJ', 'ADV']:\n if tag == 'ADV':\n return 'r'\n else:\n return tag[0].lower()\n else:\n return ' '\n\n\nclass DiskOP():\n @staticmethod\n def list_read(filename):\n lis = list()\n f = open(filename, 'r', encoding='utf-8')\n for line in f:\n lis.append(line[:-1].lower())\n f.close()\n\n @staticmethod\n def list_write(filename, lis):\n f = open(filename, \"w\", encoding=\"utf-8\")\n for item in lis:\n f.write(\"{}\\n\".format(item))\n f.close()\n\n @staticmethod\n def tuplelist_write(filename, tuples):\n f = open(filename, \"w\", encoding=\"utf-8\")\n for item in tuples:\n f.write(\"{}\\t{}\\n\".format(item[0], item[1]))\n f.close()\n\n @staticmethod\n def tuplelist_read(filename):\n lis = list()\n f = open(filename, \"r\", encoding=\"utf-8\")\n for line in f:\n items = line[:-1].split(\"\\t\")\n lis.append((items[0], items[1]))\n f.close()\n return lis\n\n @staticmethod\n def read_wordtables(filenames):\n set1 = list()\n for name in filenames:\n f = open(name, 'r')\n for line in f:\n set1.append(line[:-1].lower())\n f.close()\n return set1\n\n @staticmethod\n def write_wordtable(filename, words):\n f = open(filename, \"w\", encoding=\"utf-8\")\n for word in words:\n f.write(\"{}\\n\".format(word))\n f.close()\n\n @staticmethod\n def read_weighttable(filename):\n fs = open(filename, 'r', encoding='utf-8')\n dic = dict()\n for line in fs:\n words = line.split(\"\\t\")\n dic[words[0]] = int(words[1][:-1])\n return dic\n\n @staticmethod\n def write_weighttable(filename, dic):\n f = open(filename, \"w\", encoding='utf-8')\n for word in dic:\n f.write(\"{}\\t{}\\n\".format(word, dic[word]))\n f.close()\n\n @staticmethod\n def read_txt_lines(filename):\n file = open(filename, 'r', encoding='utf-8')\n lines = file.readlines()\n file.close()\n return lines\n\n @staticmethod\n def article_path(idd):\n formattedfilepath = \".\\\\formatted article\\\\\"\n return \"{}{}.txt\".format(formattedfilepath, idd)\n\n @staticmethod\n def moveToFolder(self, filepath, idd):\n shutil.copy(filepath, article_path(idd))\n\n @staticmethod\n def article_read(idd):\n return DiskOP.tuplelist_read(DiskOP.article_path(idd))\n # fs = open(DiskOP.article_path(idd), 'r', encoding='utf-8')\n # lis = list()\n # for line in fs:\n # words = line.split(\"\\t\")\n # lis.append((words[0], words[1][:-1]))\n # return lis\n\n @staticmethod\n def article_write(idd, tokens):\n f = open(DiskOP.article_path(idd), \"w\", encoding='utf-8')\n for word in tokens:\n f.write(\"{}\\t{}\\n\".format(word[0], word[1]))\n f.close()\n\n\ndef testdbcontroler():\n db = DbControl()\n # idd = db.add_article(\"test2\", 2/(2+3+5)*100, 2, 3, 5)[0]\n # print(idd)\n # db.wordof_add(['comfort', 'tissue', ], idd)\n # words = db.words_gettable()\n # art = db.article_get(28)\n # print(art)\n # words = db.wordof_getwords(31)\n # print(words)\n # print(len(words))\n arts = db.wordof_getweights(1)\n print(arts)\n\n\ndef testnltkhelper():\n tokens = nltkhelper.tokenize('i am a good boy.\\nyou too\\n')\n tokens = nltkhelper.peek_tag(tokens)\n\n print(tokens)\n # tokens_tags = nltkhelper.peek_tag(tokens)\n # print(tokens_tags)\n # word = nltkhelper.lemmatize('plays', 'v')\n # print(word)\n\n\ndef test_update_weight():\n db = DbControl()\n li = db.wordof_getwords(6)\n print(li)\n\n\nif __name__ == \"__main__\":\n testdbcontroler()\n # testnltkhelper()\n # testnltkhelper()\n # DiskOP.write_wordtable('./aa.txt',['hh'])\n","sub_path":"BasicOP.py","file_name":"BasicOP.py","file_ext":"py","file_size_in_byte":9784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"226747890","text":"# encoding: utf-8\n# !/usr/bin/python\n\nfrom datetime import datetime\nfrom redis import Redis\nfrom functools import wraps\nfrom flask import session, g, make_response, Blueprint, jsonify, request, redirect\nfrom flask_login import LoginManager, UserMixin, login_required\nfrom apscheduler.schedulers.background import BackgroundScheduler\nimport apscheduler.events\nfrom Tools.Mysql_db import DB\nfrom Tools.MyEmail import MyEmailManager\nfrom Class.Control import ControlManager\nfrom Function.Common import *\n\n\n__author__ = 'zhouheng'\n\nTIME_FORMAT = \"%Y-%m-%d %H:%M:%S\"\n\ndb = DB()\nip = IPManager()\ncontrol = ControlManager()\nmy_email = MyEmailManager(\"/home/msg/conf/\")\ndms_scheduler = BackgroundScheduler()\nredis = Redis(host=redis_host)\n# job_store = SQLAlchemyJobStore(url=db.url)\n# dms_scheduler.add_jobstore(job_store)\n\n\ndef err_listener(ev):\n with open(\"dms_task.log\", \"a\") as wr:\n wr.write(\"----------%s----------\\n\" % datetime.now().strftime(TIME_FORMAT))\n if isinstance(ev, apscheduler.events.JobSubmissionEvent):\n wr.write(\"Job Submission Event\\n\")\n wr.write(\"code: %s\\n\" % ev.code)\n wr.write(\"job_id: %s\\n\" % ev.job_id)\n wr.write(\"scheduled_run_times: %s\\n\" % ev.scheduled_run_times)\n elif isinstance(ev, apscheduler.events.JobExecutionEvent):\n wr.write(\"Job Execution Event\\n\")\n wr.write(\"code: %s\\n\" % ev.code)\n wr.write(\"job_id: %s\\n\" % ev.job_id)\n wr.write(\"scheduled_run_time: %s\\n\" % ev.scheduled_run_time)\n print(ev.scheduled_run_time)\n wr.write(\"retval: %s\\n\" % ev.retval)\n wr.write(\"exception: %s\\n\" % ev.exception)\n wr.write(\"traceback: %s\\n\" % ev.traceback)\n elif isinstance(ev, apscheduler.events.JobEvent):\n wr.write(\"Job Event\\n\")\n wr.write(\"code: %s\\n\" % ev.code)\n wr.write(\"job_id: %s\\n\" % ev.job_id)\n elif isinstance(ev, apscheduler.events.SchedulerEvent):\n wr.write(\"Scheduler Event\\n\")\n wr.write(\"code: %s\\n\" % ev.code)\n wr.write(\"alias: %s\\n\" % ev.alias)\n wr.write(\"----------end----------\\n\")\n\ndms_scheduler.add_listener(err_listener)\n\n\nclass User(UserMixin):\n user_name = \"\"\n\n def get_id(self):\n return self.user_name\n\nlogin_manager = LoginManager()\nlogin_manager.session_protection = 'strong'\n\n\n@login_manager.user_loader\ndef load_user(user_name):\n user = User()\n user.user_name = user_name\n if \"role\" in session:\n user.role = session[\"role\"]\n else:\n select_sql = \"SELECT role FROM sys_user WHERE user_name='%s';\" % user_name\n print(select_sql)\n result = db.execute(select_sql)\n if result > 0:\n user.role = db.fetchone()[0]\n session[\"role\"] = user.role\n else:\n user.role = 0\n session[\"role\"] = user.role\n return user\n\n\nlogin_manager.login_view = \"dms_view.index\"\nweb_prefix = web_prefix_url\napi_url_prefix = web_prefix + \"/dev/api\"\nstatus_url_prefix = web_prefix + \"/dev/api/status\"\ntest_url_prefix = web_prefix + \"/dev/api/test\"\nbug_url_prefix = web_prefix + \"/dev/problem\"\nright_url_prefix = web_prefix + \"/dev/right\"\nparam_url_prefix = web_prefix + \"/dev/param\"\ndev_url_prefix = web_prefix + \"/dev\"\ndms_url_prefix = web_prefix + \"\"\ndata_url_prefix = web_prefix + \"/data\"\nlog_url_prefix = web_prefix + \"/log\"\ntools_url_prefix = web_prefix + \"/tools\"\nrelease_url_prefix = web_prefix + \"/dev/release\"\ndyups_url_prefix = web_prefix + \"/dev/dyups\"\ngithub_url_prefix = web_prefix + \"/github\"\nchat_url_prefix = web_prefix + \"/chat\"\nothers_url_prefix = web_prefix + \"/others\"\npay_url_prefix = web_prefix + \"/wx/pay\"\njingdu_url_prefix = web_prefix + \"/jd\"\neditor_url_prefix = web_prefix + \"/editor\"\narticle_url_prefix = web_prefix + \"/article\"\nmessage_url_prefix = web_prefix + \"/message\"\nshort_link_prefix = web_prefix + \"/s\"\n\ndata_dir = \"/geneac/dmsdata\"\n\neditor_data_dir = data_dir + \"/editor\"\n\nimport os\nif os.path.isdir(data_dir) is False:\n os.mkdir(data_dir)\n\nif os.path.isdir(editor_data_dir) is False:\n os.mkdir(editor_data_dir)\n\n\ndef company_ip_required(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if \"request_IP\" not in g:\n return make_response(u\"因为一些原因页面丢失了\", 404)\n if g.request_IP not in range(company_ips[0], company_ips[1]) and g.user_name != \"zh_test\":\n return make_response(u\"因为一些原因页面不知道去哪了\", 404)\n return f(*args, **kwargs)\n return decorated_function\n\n\nblues = {}\ndms_job = []\n\n\ndef create_blue(blue_name, url_prefix=\"/\", auth_required=True, special_protocol=False):\n add_blue = Blueprint(blue_name, __name__)\n if auth_required:\n @add_blue.before_request\n @login_required\n def before_request():\n if special_protocol is True:\n r_protocol = request.headers.get(\"X-Request-Protocol\", \"http\")\n if r_protocol not in request_special_protocol:\n redirect_url = \"%s://%s%s\" % (request_special_protocol[0], request.host, request.full_path)\n return redirect(redirect_url)\n\n g.role_value = control.role_value\n\n @add_blue.route(\"/ping/\", methods=[\"GET\"])\n def ping():\n from time import sleep\n sleep(5)\n return jsonify({\"status\": True, \"message\": \"ping %s success\" % request.path})\n\n if blue_name not in blues:\n blues[blue_name] = [add_blue, url_prefix]\n return add_blue\n\n\n # @login_manager.unauthorized_callback\n # def unauthorized_callback_func():\n # if request.is_xhr:\n # return make_response(\"登录状态已过期,需要重新登录\", 302)","sub_path":"Web/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"522249144","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2020/1/30 18:04\n\n@Project -> File: gaussian-process-regression -> kernels.py\n\n@Author: luolei\n\n@Email: dreisteine262@163.com\n\n@Describe: 高斯过程核函数\n\"\"\"\n\nimport numpy as np\n\n\ndef _RBF_kernel(x_a, x_b, sigma = None, l = None):\n\t\"\"\"\n\tRBF高斯核函数, 又名Exponetiated Quadratic, 公式为:\n\tk = sigma^2 * exp(-norm(x_a - x_b)^2 / (2 * l^2))\n\t:param x_a: float, 样本值位置a\n\t:param x_b: float, 样本值位置b\n\t:param sigma: float, 方差参数\n\t:param l: float, 长度参数length\n\t\"\"\"\n\tif sigma is None:\n\t\tsigma = 0.8\n\tif l is None:\n\t\tl = 0.5\n\t\t\n\tn = np.linalg.norm(x_a - x_b)\n\tk = pow(sigma, 2) * np.exp(- pow(n, 2) / (2 * pow(l, 2)))\n\treturn k\n\n\ndef _periodic_kernel(x_a, x_b, sigma = None, l = None, p = None):\n\t\"\"\"\n\t周期性核函数, 公式为:\n\tk = sigma^2 * np.exp(-(2 / l^2) * sin(pi / p * |x_a - x_b|)^2)\n\t:param x_a: float, 样本值位置a\n\t:param x_b: float, 样本值位置b\n\t:param sigma: float, 方差参数\n\t:param l: float > 0.0, 长度参数length\n\t:param p: flaot > 0.0, 周期参数\n\t\"\"\"\n\tif sigma is None:\n\t\tsigma = 0.8\n\tif l is None:\n\t\tl = 0.5\n\tif p is None:\n\t\tp = 0.5\n\t\n\tsin = np.sin(np.pi / p * np.abs(x_a - x_b))\n\tk = pow(sigma, 2) * np.exp(-2 / pow(l, 2) * pow(sin, 2))\n\treturn k\n\n\ndef _linear_kernel(x_a, x_b, sigma = None, sigma_b = None, c = None):\n\t\"\"\"\n\t线性核函数, 公式为:\n\tk = sigma_b^2 + sigma^2 * (x_a - c)(x_b - c)\n\t:param x_a: float, 样本值位置a\n\t:param x_b: float, 样本值位置b\n\t:param sigma: float, 方差参数\n\t:param sigma_b: float, 方差参数b\n\t:param c: float, offset参数\n\t\"\"\"\n\tif sigma is None:\n\t\tsigma = 0.8\n\tif sigma_b is None:\n\t\tsigma_b = 0.5\n\tif c is None:\n\t\tc = 0.5\n\t\n\tk = pow(sigma_b, 2) + pow(sigma, 2) * (x_a - c) * (x_b - c)\n\treturn k\n\n\ndef kernel_func(x_a, x_b, kernel_name, kernel_params):\n\t# 参数设置.\n\t# 如果params里面有设置则使用设置, 否则默认为None.\n\tfor p_name in ['sigma', 'sigma_b', 'l', 'c', 'p']:\n\t\tif p_name in kernel_params.keys():\n\t\t\tpass\n\t\telse:\n\t\t\tkernel_params[p_name] = None\n\t\n\tif kernel_name == 'RBF':\n\t\tk = _RBF_kernel(x_a, x_b, sigma = kernel_params['sigma'], l = kernel_params['l'])\n\t\treturn k\n\telif kernel_name == 'linear':\n\t\tk = _linear_kernel(x_a, x_b, sigma = kernel_params['sigma'], sigma_b = kernel_params['sigma_b'], c = kernel_params['c'])\n\t\treturn k\n\telif kernel_name == 'periodic':\n\t\tk = _periodic_kernel(x_a, x_b, sigma = kernel_params['sigma'], l = kernel_params['l'], p = kernel_params['p'])\n\t\treturn k\n\telse:\n\t\traise ValueError('Unknown kernel func name \"{}\".'.format(kernel_name))\n\n\n\n","sub_path":"mod/gaussian_process/kernels.py","file_name":"kernels.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"206282323","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*\n\n\"\"\"Python 练习册 仓库地址https://github.com/ObertShen/py_practice\"\"\"\n\n__author__ = 'Shen'\n\nimport os\nimport urllib\nfrom urlparse import urlsplit\n\nfrom bs4 import BeautifulSoup\n\n\ndef catch_tieba_pics(url):\n \"\"\"根据提供的贴吧url来抓取其中的图片\"\"\"\n content = urllib.urlopen(url)\n soup = BeautifulSoup(content, 'lxml')\n for i in soup.find_all('img', {\"class\": \"BDE_Image\"}):\n download_pic(i['src'])\n\n\ndef download_pic(url):\n \"\"\"根据提供的文件获取地址下载文件\"\"\"\n image_content = urllib.urlopen(url).read()\n file_name = os.path.basename(urlsplit(url)[2])\n with open(file_name, 'wb') as output:\n output.write(image_content)\n\n\n\nif __name__ == '__main__':\n catch_tieba_pics('http://tieba.baidu.com/p/2166231880')\n\n\n\n\n","sub_path":"ObertShen/0013/tiebaimgcrawler.py","file_name":"tiebaimgcrawler.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"4795560","text":"import asyncio\nimport asyncpg\n\nfrom data import config\n\n\nclass Database:\n def __init__(self, loop: asyncio.AbstractEventLoop):\n self.pool: asyncio.pool.Pool = loop.run_until_complete(\n asyncpg.create_pool(\n user=config.PGUSER,\n password=config.PGPASSWORD,\n host=config.ip\n )\n )\n\n async def create_table_users(self):\n \"\"\"Создаем таблицу пользователей\"\"\"\n sql = \"\"\"\n CREATE TABLE IF NOT EXISTS users (\n id SERIAL PRIMARY KEY,\n user_id INT NOT NULL UNIQUE ,\n name VARCHAR(255),\n referer INT NOT NULL,\n count_referals INT,\n discount INT);\n \"\"\"\n await self.pool.execute(sql)\n\n async def create_table_products(self):\n \"\"\"Создаем таблицу товаров\"\"\"\n sql = \"\"\"\n CREATE TABLE IF NOT EXISTS products (\n id SERIAL PRIMARY KEY,\n quantity INT,\n title VARCHAR(1000),\n description TEXT,\n price INT NOT NULL,\n price_dollar INT NOT NULL,\n photo_id VARCHAR(500),\n photo_url VARCHAR(1000));\n \"\"\"\n await self.pool.execute(sql)\n\n async def create_table_orders(self):\n \"\"\"Создаем таблицу заказов\"\"\"\n sql = \"\"\"\n CREATE TABLE IF NOT EXISTS orders (\n id SERIAL PRIMARY KEY,\n order_id bigint,\n quantity INT,\n user_id INT,\n user_fn VARCHAR(255),\n user_username VARCHAR(255),\n invoice_payload INT,\n country_code VARCHAR(10),\n state_prod VARCHAR(255),\n city VARCHAR(255),\n street_line1 VARCHAR(1000),\n street_line2 VARCHAR(1000),\n post_code INT,\n title VARCHAR(1000),\n price INT NOT NULL,\n discount INT);\n \"\"\"\n await self.pool.execute(sql)\n\n @staticmethod\n def format_args(sql, parameters: dict):\n sql += ' AND '.join([\n f'{item} = ${num}' for num, item in enumerate(parameters, start=1)\n ])\n return sql, tuple(parameters.values())\n\n async def add_user(self, user_id: int, referer: int, name: str):\n \"\"\"Добавляем пользователя в бд\"\"\"\n try:\n sql = \"INSERT INTO users (user_id, name, referer, count_referals, discount) VALUES ($1, $2, $3, $4, $5)\"\n await self.pool.execute(sql, user_id, name, referer, 0, 0)\n except asyncpg.exceptions.UniqueViolationError:\n print('Пользователь с таким user_id уже существует')\n\n async def select_all_users(self):\n \"\"\"Выбираем всех пользователей\"\"\"\n sql = 'SELECT * FROM users'\n return await self.pool.fetch(sql)\n\n async def select_all_user_id(self):\n \"\"\"Выбираем все id Пользователей\"\"\"\n all_users = await self.pool.fetch('SELECT user_id FROM users')\n all_users_id = [id['user_id'] for id in all_users]\n return all_users_id\n\n async def select_user(self, user_id):\n \"\"\"Выбираем одного пользователя\"\"\"\n return await self.pool.fetchrow(f'SELECT * FROM users WHERE user_id = {user_id}')\n\n async def count_users(self):\n \"\"\"Достаем количество пользователей\"\"\"\n return await self.pool.fetchval('SELECT COUNT(*) FROM users')\n\n async def add_referal(self, user_id):\n \"\"\"Добавляем реферала пользователю\"\"\"\n count_ref = await self.pool.fetchval(f'SELECT count_referals FROM users WHERE user_id = {user_id}')\n count_ref += 1\n await self.pool.execute(f\"UPDATE users SET count_referals = {count_ref} WHERE user_id = {user_id}\")\n print(f'Количчесво рефералов у пользователя с user_id = {user_id} --{count_ref}')\n\n async def add_discount(self, user_id):\n \"\"\"Добавляем 10$ за каждого реферала\"\"\"\n discount = await self.pool.fetchval(f'SELECT discount FROM users WHERE user_id = {user_id}')\n discount += 1000\n await self.pool.execute(f\"UPDATE users SET discount = {discount} WHERE user_id = {user_id}\")\n print(f'Баланс с рефералов пользователя с user_id = {user_id} для покупок {discount}')\n\n async def reduce_discount(self, user_id, amount):\n \"\"\"Уменьшаем реферальный баланс\"\"\"\n discount = await self.pool.fetchval(f'SELECT discount FROM users WHERE user_id = {user_id}')\n discount -= amount\n await self.pool.execute(f\"UPDATE users SET discount = {discount} WHERE user_id = {user_id}\")\n\n async def add_product(self, title, description, price, price_dollar, photo_id, photo_url, quantity):\n \"\"\"обавляем товар\"\"\"\n sql = \"INSERT INTO products (title, description, price, price_dollar, photo_id, photo_url, quantity) VALUES ($1, $2, $3, $4, $5, $6, $7)\"\n await self.pool.execute(sql, title, description, price, price_dollar, photo_id, photo_url, quantity)\n\n async def select_all_products(self):\n \"\"\"Достаем все товары отсортированные по названию\"\"\"\n sql = 'SELECT * FROM products ORDER BY title'\n return await self.pool.fetch(sql)\n\n async def select_product(self, id):\n \"\"\"Выбираем товар по id\"\"\"\n return await self.pool.fetchrow(f'SELECT * FROM products WHERE id = {id}')\n\n async def delete_product(self, product_id: int):\n \"\"\"Удаляем товар\"\"\"\n return await self.pool.execute(f'DELETE FROM products WHERE id = {product_id}')\n\n async def select_product_by_beginning_of_name(self, user_input: str):\n \"\"\"Достаем товары по части названия\"\"\"\n return await self.pool.fetch(f\"SELECT * FROM products WHERE title ~~* '%{user_input}%' ORDER BY title\")\n\n async def add_order(self, order_id, quantity, user_id, user_fn, user_username, invoice_payload, country_code,\n state_prod, city, street_line1, street_line2, post_code, title, price, discount):\n \"\"\"Добавляем заказ\"\"\"\n sql = \"INSERT INTO orders (order_id, quantity, user_id, user_fn, user_username, invoice_payload, country_code, state_prod, city, street_line1, street_line2, post_code, title, price, discount) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)\"\n await self.pool.execute(sql, order_id, quantity, user_id, user_fn, user_username, invoice_payload, country_code,\n state_prod, city, street_line1, street_line2, post_code, title, price, discount)\n\n# db = Database(loop=asyncio.get_event_loop())\n","sub_path":"utils/db_api/postgresql.py","file_name":"postgresql.py","file_ext":"py","file_size_in_byte":6836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"260196698","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nDIR_PATH = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.join(DIR_PATH, \"..\", \"define\"))\nsys.path.append(os.path.join(DIR_PATH, \"..\", \"engine\"))\n\nfrom define import *\nfrom engine.engineobject import EngineObjectPoly\n\n\n\nclass Bac(EngineObjectPoly):\n\tdef __init__(self,engine,posinit,color):\n\t\tEngineObjectPoly.__init__(self,\n\t\t\tengine\t\t\t= engine,\n\t\t\tcolltype\t\t= COLLTYPE_BAC,\n\t\t\tposinit\t\t\t= posinit,\n\t\t\tmass\t\t\t= MASS_INF,\n\t\t\tcolor\t\t\t= color,\n\t\t\tpoly_points\t\t= map(lambda p: mm_to_px(*p),[(0,0),(700,0),(700,300-25),(0,300-25)])\n\t\t)\n\t\tself.nbFruit = 0\n\n\tdef __repr__(self):\n\t\treturn \"Bac %s \" % (self.posinit,)\n","sub_path":"simulateur/objects/bac.py","file_name":"bac.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"385501742","text":"# -*- coding: utf-8\n\n\"\"\"\n@File : t_fitctrdm.py\n@Author : Zitong Lu\n@Contact : zitonglu1996@gmail.com\n@License : MIT License\n\"\"\"\n\nimport numpy as np\nimport unittest\nfrom pyctrsa.ctsimilarity.fitctrdm import ctsimilarities_cal\n\nclass test_fitctrdm_cal(unittest.TestCase):\n\n def test_ctsimilarities_cal(self):\n\n CTRDMs = np.random.rand(10, 10, 16, 16)\n Model_RDM = np.random.rand(16, 16)\n CTSimilarities = ctsimilarities_cal(CTRDMs, Model_RDM)\n self.assertEqual(CTSimilarities.shape[0], 10)\n self.assertEqual(len(CTSimilarities.shape), 3)\n\n CTRDMs = np.random.rand(8, 10, 10, 16, 16)\n CTSimilarities = ctsimilarities_cal(CTRDMs, Model_RDM)\n self.assertEqual(CTSimilarities.shape[0], 8)\n self.assertEqual(len(CTSimilarities.shape), 4)","sub_path":"test/t_fitctrdm.py","file_name":"t_fitctrdm.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"425269584","text":"import cv2\nimport numpy as np\nfrom lanelines.features import extract\nfrom lanelines.curves import get_xy, quadratic_ransac_fit, lane_overlay, blend\n\n\ndef process(image, cal_data, pt_data, clf, state):\n undistorted = cv2.undistort(image, cal_data['matrix'], cal_data['distortion'])\n transformed = cv2.warpPerspective(undistorted, pt_data['matrix'],\n tuple(pt_data['target_size']), flags=cv2.INTER_LANCZOS4)\n\n features = extract(transformed)\n res = clf.predict(features.reshape(-1, features.shape[-1]))\n xy = get_xy(res.reshape(transformed.shape[:2]))\n try:\n coefficients_0, inliers_0 = quadratic_ransac_fit(xy[:, 0], xy[:, 1])\n coefficients_1, _ = quadratic_ransac_fit(xy[np.logical_not(inliers_0), 0],\n xy[np.logical_not(inliers_0), 1])\n state.add_measurements(coefficients_0[0], coefficients_1[0])\n except ValueError:\n state.add_error(res)\n\n alpha, lanes = lane_overlay(state.left_lane, state.right_lane, transformed.shape[:2])\n inverse_transform = np.linalg.inv(pt_data['matrix'])\n alpha = cv2.warpPerspective(alpha, inverse_transform, (image.shape[1], image.shape[0]), flags=cv2.INTER_LANCZOS4)\n lanes = cv2.warpPerspective(lanes, inverse_transform, (image.shape[1], image.shape[0]), flags=cv2.INTER_LANCZOS4)\n result = blend(image, lanes, alpha, 0.25)\n cv2.putText(result, 'Curvature: %6.2fm' % state.curvature, (50, 100),\n cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 1, cv2.LINE_AA)\n cv2.putText(result, 'Displacement: %6.2fm' % state.displacement, (50, 150),\n cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 1, cv2.LINE_AA)\n return result\n","sub_path":"lanelines/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"387281179","text":"import hou\nimport cPickle\n\nclass kCameraImporter:\n def __init__(self,*args):\n self.importCameraData()\n\n \n def getFilePath(self, *args):\n file=hou.ui.selectFile(None,\"Import kCamera\",False,hou.fileType.Any,\"*.kCamera\",\"\",False,False,hou.fileChooserMode.Write)\n \n if file ==\"\":\n return None\n else :\n file=file.partition(\"/\")\n\n if file[0]==\"$HOME\" :\n prefix=str(hou.getenv(\"HOME\"))\n elif file[0] == \"$HIP\" :\n prefix=str(hou.getenv(\"HIP\"))\n elif file[0] == \"$JOB\":\n prefix=str(hou.getenv(\"JOB\"))\n else:\n prefix=str(\"\")\n\n return \"%s/%s\" %(prefix,file[2])\n \n \n def importCameraData(self, *args):\n fileLocation = self.getFilePath()\n \n try:\n f = open(fileLocation, 'rb')\n except TypeError:\n nuke.warning(\"No file selected..\")\n return\n \n kCamData = []\n \n for i in range(2):\n kCamData.append(cPickle.load(f))\n f.close() \n \n self.buildCamera(kCamData)\n \n def buildCamera(self, kCamData, *args):\n hObject = hou.node('/obj')\n cam = object.createNode('cam')\n \n ","sub_path":"Houdini/kTHoudini/kT_kCamera/kT_kCameraHoudiniImporter.py","file_name":"kT_kCameraHoudiniImporter.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"577655990","text":"\"\"\"\nAR_ExportOBJ\n\nAuthor: Arttu Rautio (aturtur)\nWebsite: http://aturtur.com/\nName-US: AR_ExportOBJ\nVersion: 1.2.0\nDescription-US: Exports top level objects individually to OBJ file. Supports object selection\n\nWritten for Maxon Cinema 4D R25.010\nPython version 3.9.1\n\nChange log:\n1.2.0 (17.11.2022) - Progress bar\n1.1.0 (17.10.2020) - Updated for R25, added support for selected objects\n\"\"\"\n\n# Libraries\nimport c4d\nimport os\nfrom c4d import plugins\nfrom c4d import utils as u\n\n# Functions\ndef ExportObject(obj, fn):\n doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document\n tempDoc = c4d.documents.IsolateObjects(doc, [obj]) # Isolate object to temp doc\n name = obj.GetName() # Get object's name\n separator = os.sep # Get folder separator\n path = os.path.splitext(fn)[0]+separator+name+\".obj\" # File name\n c4d.documents.SaveDocument(tempDoc, path, c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST, 1030178) # Export OBJ-file\n tempDoc.Flush() # Flush temp doc\n\ndef main():\n fn = c4d.storage.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, \"Folder to export\", c4d.FILESELECT_DIRECTORY)\n if not fn: return # If cancelled stop the script\n doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document\n objects = doc.GetObjects() # Get objects\n selected = doc.GetActiveObjects(0) # Get selected objects\n\n plug = plugins.FindPlugin(1030178, c4d.PLUGINTYPE_SCENESAVER)\n if plug is None:\n return\n data = {}\n if plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, data):\n if \"imexporter\" not in data:\n return\n objExport = data[\"imexporter\"]\n if objExport is None:\n return\n\n if len(selected) == 0: # If there's no selected objects\n for i, obj in enumerate(objects): # Iterate through objects\n progress = u.RangeMap(i, 0, len(objects), 0, 100, True)\n c4d.StatusSetText(\"Exporting %s of %s\" % (i,len(objects)))\n c4d.StatusSetBar(progress)\n c4d.DrawViews(c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW|c4d.DRAWFLAGS_NO_THREAD|c4d.DRAWFLAGS_STATICBREAK)\n ExportObject(obj, fn) # Export object\n c4d.GeSyncMessage(c4d.EVMSG_UPDATEBASEDRAW)\n else: # If there's selected objects\n for i, obj in enumerate(selected): # Iterate through selected objects\n progress = u.RangeMap(i, 0, len(selected), 0, 100, True)\n c4d.StatusSetText(\"Exporting %s of %s\" % (i,len(selected)))\n c4d.StatusSetBar(progress)\n c4d.DrawViews(c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW|c4d.DRAWFLAGS_NO_THREAD|c4d.DRAWFLAGS_STATICBREAK)\n ExportObject(obj, fn) # Export object\n c4d.GeSyncMessage(c4d.EVMSG_UPDATEBASEDRAW)\n c4d.StatusClear() # Clear status\n c4d.EventAdd() # Refresh Cinema 4D\n\n# Execute main()\nif __name__=='__main__':\n main()","sub_path":"AR_Scripts_1.74/Export/AR_ExportOBJ.py","file_name":"AR_ExportOBJ.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"161533242","text":"import requests\r\n\r\n\r\nurl = 'http://www.baidu.com'\r\nproxies = {\r\n \"http\": \"http://12.34.56.78:9000\",\r\n \"https\": \"https://12.34.56.78:9000\"\r\n}\r\ntry:\r\n response = requests.get(url, proxies=proxies, timeout=0.2)\r\n print(response.content.decode())\r\nexcept :\r\n print('ip无效')\r\n","sub_path":"Project/爬虫/1.爬虫常用库/数据获取/requests库/8.requests_peoxies.py","file_name":"8.requests_peoxies.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"470614417","text":"import exceptions\n\nclass UnitsError(exceptions.Exception):\n pass\n\nclass Units(object):\n\n byte=0\n g_byte=1\n m_byte=2\n k_byte=3\n t_byte=4\n second=5\n percentage=6\n kB = 7\n\n def __init__(self):\n self.units_types = {\n 'byte':[Units.byte,\n Units.g_byte,\n Units.m_byte,\n Units.k_byte,\n Units.t_byte,\n Units.kB],\n 'time':[Units.second],\n 'other':[Units.percentage]\n }\n\n self.string_units = {\n Units.byte: 'byte',\n Units.g_byte: 'GB',\n Units.m_byte: 'MB',\n Units.k_byte: 'KB',\n Units.t_byte: 'TB',\n Units.second: 'second',\n Units.percentage: '%',\n Units.kB: 'kB'\n }\n\n def is_unit(self, unit_type):\n if int(unit_type) in self.string_units.keys():\n return True\n return False\n\n def get_units(self):\n units = []\n for x in self.units_types.values():\n units.extend(x)\n return units\n\n def get_string_units(self):\n return self.string_units\n\n def get_string_unit(self, unit_type):\n if self.is_unit(unit_type):\n return self.string_units[unit_type]\n else:\n msg = 'The specified unit %s is wrong' % str(unit_type)\n raise UnitsError(msg)\n","sub_path":"packages/sensor-api/sources/api/units.py","file_name":"units.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"102645003","text":"'''\n@ project: LibrarySeats\n@ file: function\n@ user: 罗申申\n@ email: luoshenshen@buaa.edu.cn\n@ tool: PyCharm\n@ time: 2021/5/24 1:44\n'''\nimport requests\nimport time\nimport browser_tools\nimport re\nimport js_code\nimport baidu\nimport timer\nfrom aip import AipOcr\n\nrequests.packages.urllib3.disable_warnings()\nrequests_with_session = requests.Session()\n\n\ndef session_get(url, header):\n requests.adapters.DEFAULT_RETRIES = 5\n return requests_with_session.get(url=url, headers=header, allow_redirects=False, verify=False)\n\n\ndef floors(floor):\n floor = str(floor)\n if floor == \"21\":\n floor = str(10073)\n elif floor == \"22\":\n floor = str(10065)\n elif floor == \"23\":\n floor = str(10071)\n elif floor == \"24\":\n floor = str(10072)\n elif floor == \"31\":\n floor = str(10080)\n elif floor == \"32\":\n floor = str(10081)\n elif floor == \"33\":\n floor = str(10082)\n elif floor == \"34\":\n floor = str(10083)\n elif floor == \"35\":\n floor = str(10084)\n elif floor == \"41\":\n floor = str(10085)\n elif floor == \"42\":\n floor = str(10086)\n elif floor == \"43\":\n floor = str(10087)\n elif floor == \"44\":\n floor = str(10088)\n elif floor == \"45\":\n floor = str(10089)\n elif floor == \"51\":\n floor = str(10090)\n elif floor == \"52\":\n floor = str(10091)\n elif floor == \"53\":\n floor = str(10092)\n elif floor == \"61\":\n floor = str(11019)\n elif floor == \"62\":\n floor = str(11033)\n elif floor == \"63\":\n floor = str(11040)\n elif floor == \"64\":\n floor = str(11300)\n elif floor == \"71\":\n floor = str(11054)\n elif floor == \"72\":\n floor = str(11061)\n elif floor == \"73\":\n floor = str(11068)\n elif floor == \"81\":\n floor = str(11075)\n elif floor == \"82\":\n floor = str(11096)\n elif floor == \"83\":\n floor = str(11117)\n elif floor == \"84\":\n floor = str(11131)\n elif floor == \"85\":\n floor = str(11138)\n elif floor == \"91\":\n floor = str(11082)\n elif floor == \"92\":\n floor = str(11103)\n elif floor == \"93\":\n floor = str(11124)\n return str(floor)\n\n\ndef get_floor_url(url, floor):\n return url + str(floor) + '.html&' + str(int(time.time()))\n\n\ndef get_tomorrow_floor_url(url, floor):\n return url + str(floor)\n\n\ndef get_seat(html):\n xys = re.findall('data-key=\"(.*)\" style=\"left:', html)\n seats = re.findall('(.*)', html)\n return xys, seats\n\n\ndef fecth(cookie,floor,key,flag):\n floor = floors(floor)\n if flag == False:\n times = time.time()\n url = get_floor_url(browser_tools.floor_url, floor)\n result = session_get(url, browser_tools.get_layout_header(cookie,times))\n js_result = js_code.obtain_js(result.text)\n if len(js_result) <= 1:\n return \"已选中座位或者不在选座时间!\"\n request_js = js_result[1]\n need_js = re.findall(r\"layout/(.+?).js\", request_js)\n print(\"选座js已获取:\" + need_js[0])\n verify_code = js_code.verify_code_get(need_js[0],cookie,times)\n js = str(verify_code)\n print(\"选座js匹配验证码:\" + verify_code)\n xys, seats = get_seat(result.text)\n keys = {}\n for i, j in zip(xys, seats):\n keys.update({str(j): str(i)})\n key = str(key)\n seats = keys.pop(key)\n result = ''\n while ('预定' not in result) or ('退选' not in result) or ('释放' not in result):\n target_url = browser_tools.today_url + str(floor) + '&' + str(js) + '=' + str(seats) + '&yzm='\n result = str(session_get(target_url, browser_tools.get_today_header(cookie,times)).text)\n if ('预定' in result) or ('退选' in result) or ('释放' in result) or ('成功' in result):\n return result\n\n else:\n url = get_floor_url(browser_tools.floor_url, floor)\n result = session_get(url, browser_tools.get_layout_header(cookie,time.time()))\n xys, seats = get_seat(result.text)\n keys = {}\n for i, j in zip(xys, seats):\n keys.update({str(j): str(i)})\n seats = keys.pop(key)\n alive = 0\n hour, min, sec = timer.times()\n while int(hour) < int(19) and ((int(19 - hour) * 3600 + int((49 - min)) * 60 + (59 - sec)) > 0):\n time.sleep(0.5)\n alive += 1\n if alive == 360:\n session_get(url, browser_tools.get_layout_header(cookie,time.time()))\n alive = 0\n hour, min, sec = timer.times()\n while int(min) <= int(49) and (int(19 - hour) * 3600 + int((49 - min)) * 60 + (59 - sec)) > 0:\n time.sleep(0.5)\n alive += 1\n if alive == 360:\n session_get(url, browser_tools.get_layout_header(cookie,time.time()))\n alive = 0\n hour, min, sec = timer.times()\n #最后一次刷新\n tomorrow_result = session_get(browser_tools.tomorrow, browser_tools.get_tomorrow_header(cookie))\n # 获取js验证\n js_result = js_code.obtain_js(tomorrow_result.text)\n print(\"提前发起主动锁定...\")\n while len(js_result) == 1:\n tomorrow_result = session_get(browser_tools.tomorrow, browser_tools.get_tomorrow_header(cookie))\n # 获取js验证\n js_result = js_code.obtain_js(tomorrow_result.text)\n\n request_js = js_result[1]\n need_js = re.findall(r\"layout/(.+?).js\", request_js)\n verify_code = js_code.verify_code_get(need_js[0],cookie,time)\n js = str(verify_code)\n client = AipOcr(baidu.APP_ID, baidu.API_KEY, baidu.SECRET_KEY)\n options = {}\n options[\"detect_language\"] = \"true\"\n result = ''\n while '成功' not in result or '失败' not in result or '满' not in result:\n #获取验证码链接\n img_url = browser_tools.img_url\n hr = session_get(img_url, header=browser_tools.tomorrow_imgs_header(cookie)).headers\n if 'Location' in hr.keys():\n img_url = hr.pop('Location')\n word = client.webImageUrl(img_url, options)\n #判断合法性\n if len(word.get('words_result')) == 0:\n continue\n li = word.get('words_result')\n if len(li[0][\"words\"]) != 4:\n continue\n code = li[0][\"words\"]\n print('(o゜▽゜)o☆[BINGO!]', \"\\tCNN卷积神经网络自动判别验证码为:\", code)\n # 各种安全已经验证,开始抢座\n target_url = browser_tools.tomorrow_url + str(floor) + '&' + str(js) + '=' + str(seats) + '&yzm=' + code\n result = session_get(target_url, browser_tools.get_today_header(cookie,time.time())).text\n print(\"选座结果:\",result)\n if '成功' in result or '失败' in result or '满' in result:\n return result","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":6984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"305654437","text":"import mysql.connector\nfrom collections import OrderedDict\n\nclass CursorBase:\n\n user = \"\"\n password = \"\"\n database = \"\"\n host = \"\"\n\n def __init__(self):\n pass\n\n\n @classmethod\n def open_connection(cls):\n conn = mysql.connector.connect(\n user = cls.user,\n password = cls.password,\n host = cls.host,\n database = cls.database)\n return conn\n\n\n @classmethod\n def create_cursor(cls):\n conn = cls.open_connection()\n cursor = conn.cursor()\n return conn, cursor\n\n\n @staticmethod\n def close(conn, cursor):\n cursor.close()\n conn.close()\n\n\n @staticmethod\n def record_to_ordereddict(record, column_names):\n od = OrderedDict()\n for i, col in enumerate(column_names):\n od[col] = record[i]\n return od\n\n\n @staticmethod\n def parse_records(records, column_names):\n parsed = []\n for record in records:\n parsed.append(CursorBase.record_to_ordereddict(record,\n column_names))\n return parsed\n\n\n @staticmethod\n def create_empty_ordereddict(describe):\n empty_od = OrderedDict()\n empty_od[\"id\"] = 0\n\n for col in describe:\n if str(col[0]) == \"id\":\n continue\n dtype = \"text\"\n val = \"\"\n if \"int\" in str(col[1]):\n dtype = \"int\"\n val = \"\"\n elif \"decimal\" in str(col[1]):\n dtype = \"float\"\n val = \"\"\n else:\n val = \"\"\n if col[4] != None:\n if dtype == \"int\":\n val = int(col[4])\n elif dtype == \"float\":\n val = float(col[4])\n elif dtype == \"text\":\n val = str(col[4])\n empty_od[str(col[0])] = val\n\n return empty_od\n\n\n @staticmethod\n def clean_value(value):\n if isinstance(value, str):\n value = value.strip()\n return value\n\n\n @classmethod\n def describe(cls, table_name, cursor=None):\n sql = \"DESCRIBE `{:s}`\".format(table_name)\n if cursor == None:\n conn, c = cls.create_cursor()\n else:\n conn = None\n c = cursor\n c.execute(sql)\n raw = c.fetchall()\n if cursor == None:\n cls.close(conn, c)\n return raw\n\n\n @classmethod\n def column_names(cls, table_name):\n conn, c = cls.create_cursor()\n describe = cls.describe(table_name, cursor=c)\n column_names = [str(col[0]).strip() for col in describe]\n cls.close(conn, c)\n return column_names\n\n\n @classmethod\n def empty_ordereddict(cls, table_name, fields=[], cursor=None):\n describe = cls.describe(table_name, cursor=cursor)\n if len(fields) > 0:\n describe_trunc = []\n for field in fields:\n for dfield in describe:\n if field == dfield[0]:\n describe_trunc.append(dfield)\n describe = describe_trunc\n return cls.create_empty_ordereddict(describe)\n\n\n @classmethod\n def select(cls, table_name, fields=[], clauses=\"\"):\n sql = \"SELECT \"\n if len(fields) == 0:\n sql+= \"*\"\n else:\n sql+= \", \".join(\"`{:s}`\".format(field) for field in fields)\n sql+= \" FROM `{:s}` \".format(table_name) + clauses\n\n conn, cursor = cls.create_cursor()\n cursor.execute(sql)\n records = cursor.fetchall()\n column_names = cursor.column_names\n\n result = cls.parse_records(records, column_names)\n if len(result) == 0:\n result = [cls.empty_ordereddict(table_name, fields=fields,\n cursor=cursor)]\n\n cls.close(conn, cursor)\n return result\n\n\n @classmethod\n def select_all(cls, table_name, clauses=\"\"):\n return cls.select(table_name, clauses=clauses)\n\n\n @staticmethod\n def values_dict_to_tuple(values_dict):\n return tuple([CursorBase.clean_value(values_dict[key])\n for key in values_dict\n if key != \"id\"])\n\n\n @classmethod\n def update_row(cls, table_name, where_clause, values_dict, id_col=\"id\"):\n conn, cursor = cls.create_cursor()\n cursor.execute(\"SELECT {:s} FROM {:s} {:s}\".format(\n id_col, table_name, where_clause))\n update_id = int(cursor.fetchone()[0])\n sql = \"UPDATE `{:s}` SET \".format(table_name)\n values = cls.values_dict_to_tuple(values_dict)\n for key in values_dict:\n if key == \"id\":\n continue\n sql += \"{:s}=%s, \".format(key)\n sql = sql[:-2] + \" \" + where_clause\n cursor.execute(sql, tuple(values))\n conn.commit()\n cls.close(conn, cursor)\n return update_id\n\n\n @classmethod\n def insert_row(cls, table_name, values_dict):\n sql = \"INSERT INTO {:s} (\".format(table_name)\n values = cls.values_dict_to_tuple(values_dict)\n values_sql = \"(\"\n for key in values_dict:\n if key == \"id\":\n continue\n sql += \"{:s}, \".format(str(key))\n values_sql+= \"%s, \"\n sql = sql[:-2] + \") VALUES \"\n sql+= values_sql[:-2] + \")\"\n conn, cursor = cls.create_cursor()\n cursor.execute(sql, tuple(values))\n conn.commit()\n last_id = cls.last_insert_id(table_name, cursor=cursor)\n cls.close(conn, cursor)\n return last_id\n\n\n @classmethod\n def call_procedure(cls, procedure, args=(), commit=False):\n conn, cursor = cls.create_cursor()\n\n if len(args) == 0:\n res = cursor.callproc(procedure)\n else:\n res = cursor.callproc(procedure, args)\n\n if commit:\n conn.commit()\n\n cls.close(conn, cursor)\n return res\n\n\n @classmethod\n def last_insert_id(cls, table_name, cursor=None):\n no_cursor = False\n if cursor == None:\n no_cursor = True\n conn, cursor = cls.create_cursor()\n cursor.execute(\"SELECT last_insert_id();\")\n record = cursor.fetchone()\n if no_cursor:\n cls.close(conn, cursor)\n return int(record[0])\n\n\n\n\n\n","sub_path":"web-interface/app/application/src/db/base/cursor.py","file_name":"cursor.py","file_ext":"py","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"425061559","text":"#1Запустите программу п.2 так, чтобы она\n#выводила свои результаты не на экран, а в текстовый файл.\n\nname = input(\"Введите Имя.фамилию.отчество: \")\n\nname2 = (' '.join(name.split(' ')[:-1]))\nname3 = (' '.join(name2.split(' ')[:-1]))\n\nsurname = (' '.join(name.split(' ')[:-1]))\nsurname2 = surname[surname.find(\" \") + 1 : ]\n\npatronymic = name[name.find(\" \") + 1 : ]\npatronymic2 = patronymic[patronymic.find(\" \") + 1 : ]\n\nl = [name3, surname2, patronymic2]\n\nFile = open('file.txt', 'w')\n\nfor index in l:\n\n\tFile.write(index + '\\n')\n\nFile.close()","sub_path":"[nezdal]lab16_17.py","file_name":"[nezdal]lab16_17.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"85725316","text":"import os\nimport pickle\nimport numpy as np\n\nfrom config import LEARN_FOLDER, TRAIN_FOLDER, VALIDATION_FOLDER\n\n\ndef train_validation_split():\n os.makedirs(TRAIN_FOLDER, exist_ok=True)\n os.makedirs(VALIDATION_FOLDER, exist_ok=True)\n\n with open(os.path.join(LEARN_FOLDER, 'sequences.pkl'), 'rb') as f:\n x_lrn = pickle.load(f)\n with open(os.path.join(LEARN_FOLDER, 'sentences.pkl'), 'rb') as f:\n s_lrn = pickle.load(f)\n with open(os.path.join(LEARN_FOLDER, 'labels.pkl'), 'rb') as f:\n y_lrn = pickle.load(f)\n\n N = len(x_lrn)\n np.random.seed(18)\n order = np.random.permutation(N)\n x_lrn = np.array([x_lrn[i] for i in order])\n s_lrn = np.array([s_lrn[i] for i in order])\n y_lrn = np.array([y_lrn[i] for i in order])\n\n msk = np.random.random(N) < 0.85\n x_trn = x_lrn[msk].tolist()\n x_vld = x_lrn[~msk].tolist()\n\n s_trn = s_lrn[msk].tolist()\n s_vld = s_lrn[~msk].tolist()\n\n y_trn = y_lrn[msk].tolist()\n y_vld = y_lrn[~msk].tolist()\n\n with open(os.path.join(TRAIN_FOLDER, 'sequences.pkl'), 'wb') as f:\n pickle.dump(x_trn, f)\n with open(os.path.join(TRAIN_FOLDER, 'sentences.pkl'), 'wb') as f:\n pickle.dump(s_trn, f)\n with open(os.path.join(TRAIN_FOLDER, 'labels.pkl'), 'wb') as f:\n pickle.dump(y_trn, f)\n with open(os.path.join(VALIDATION_FOLDER, 'sequences.pkl'), 'wb') as f:\n pickle.dump(x_vld, f)\n with open(os.path.join(VALIDATION_FOLDER, 'sentences.pkl'), 'wb') as f:\n pickle.dump(s_vld, f)\n with open(os.path.join(VALIDATION_FOLDER, 'labels.pkl'), 'wb') as f:\n pickle.dump(y_vld, f)\n return\n\n\nif __name__ == '__main__':\n train_validation_split()\n","sub_path":"src/dataset_creation.py","file_name":"dataset_creation.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"545504996","text":"from baza import Baza\nfrom finance import Finance\nfrom PyQt5 import QtWidgets\nimport sys\n\nclass Main():\n def __init__(self):\n super().__init__()\n self.setup()\n app = QtWidgets.QApplication(sys.argv)\n self.window=Finance()\n self.window.show()\n sys.exit(app.exec_())\n\n def setup(self):\n self.baza_ime='FinanceDataBase'\n self.SQL_baza='FinanceDataBase.db'\n self.baza = Baza(self.baza_ime)\n self.baza.beri_iz_SQL(self.SQL_baza)\n\n\n\n\n\n\nif __name__ == \"__main__\":\n Main()\n\n","sub_path":"Finance/Program na novo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"107212577","text":"import xmltodict\r\nfrom ratings.models import User, Trip, Lodging, Air, Restaurant\r\nfrom django.forms import model_to_dict\r\n\r\n\r\n# create_ functions help create model instances from data provided in dicts\r\n\r\n\r\ndef create_user(profile):\r\n instance = {}\r\n instance['user_id'] = profile['@ref'].decode('utf-8')\r\n instance['public_display_name'] = profile['public_display_name'].decode('utf-8')\r\n instance['profile_url'] = profile['profile_url'].decode('utf-8')\r\n return User(**instance)\r\n\r\n\r\ndef create_trip(trip, user_id):\r\n instance = {}\r\n instance['user'] = User.objects.get(user_id=user_id)\r\n instance['trip_id'] = trip['id'].decode('utf-8')\r\n instance['display_name'] = trip['display_name'].decode('utf-8')\r\n instance['primary_location'] = trip['primary_location'].decode('utf-8')\r\n instance['image_url'] = trip['image_url'].decode('utf-8')\r\n instance['relative_url'] = trip['relative_url'].decode('utf-8')\r\n instance['start_date'] = trip['start_date'].decode('utf-8')\r\n instance['end_date'] = trip['end_date'].decode('utf-8')\r\n instance['notes'] = ''\r\n instance['tripit_last_modified'] = trip['last_modified'].decode('utf-8')\r\n\r\n return Trip(**instance)\r\n\r\n\r\ndef create_lodging(lodging):\r\n instance = {}\r\n instance['trip'] = Trip.objects.get(trip_id=lodging['trip_id'])\r\n instance['lodge_id'] = lodging['id'].decode('utf-8')\r\n instance['display_name'] = lodging['display_name'].decode('utf-8')\r\n instance['relative_url'] = lodging['relative_url'].decode('utf-8')\r\n instance['room_type'] = lodging['room_type'].decode('utf-8')\r\n instance['supplier_name'] = lodging['supplier_name'].decode('utf-8')\r\n instance['start_date'] = lodging['StartDateTime']['date'].decode('utf-8')\r\n instance['end_date'] = lodging['EndDateTime']['date'].decode('utf-8')\r\n instance['notes'] = ''\r\n instance['tripit_last_modified'] = lodging['last_modified'].decode('utf-8')\r\n return Lodging(**instance)\r\n\r\n\r\ndef create_air(air):\r\n instance = {}\r\n instance['trip'] = Trip.objects.get(trip_id=air['trip_id'])\r\n instance['air_id'] = air['id'].decode('utf-8')\r\n instance['display_name'] = air['display_name'].decode('utf-8')\r\n instance['relative_url'] = air['relative_url'].decode('utf-8')\r\n instance['booking_site_name'] = air['booking_site_name'].decode('utf-8')\r\n instance['notes'] = ''\r\n instance['tripit_last_modified'] = air['last_modified'].decode('utf-8')\r\n return Air(**instance)\r\n\r\n\r\ndef create_restaurant(rest):\r\n instance = {}\r\n instance['trip'] = Trip.objects.get(trip_id=rest['trip_id'])\r\n instance['rest_id'] = rest['id'].decode('utf-8')\r\n instance['display_name'] = rest['display_name'].decode('utf-8')\r\n instance['relative_url'] = rest['relative_url'].decode('utf-8')\r\n instance['number_patrons'] = int(rest['number_patrons'])\r\n instance['booking_site_name'] = rest['booking_site_name'].decode('utf-8')\r\n instance['supplier_name'] = rest['supplier_name'].decode('utf-8')\r\n instance['date'] = rest['DateTime']['date'].decode('utf-8')\r\n instance['time'] = rest['DateTime']['time'].decode('utf-8')\r\n instance['utc_offset'] = rest['DateTime']['utc_offset'].decode('utf-8')\r\n instance['notes'] = ''\r\n instance['tripit_last_modified'] = rest['last_modified'].decode('utf-8')\r\n return Restaurant(**instance)\r\n\r\n\r\n# utility function to save activity info to database, given a trip\r\n\r\ndef save_activity_data(trip, activity_name, collection, exclusions=[]):\r\n model_utils = {\r\n 'LodgingObject': create_lodging,\r\n 'RestaurantObject': create_restaurant,\r\n 'AirObject': create_air\r\n }\r\n\r\n if(activity_name in trip):\r\n if(isinstance(trip[activity_name], list)):\r\n for obj in trip[activity_name]:\r\n model_instance = model_utils[activity_name](obj)\r\n model_instance.save()\r\n resp_data = model_to_dict(model_instance, exclude=exclusions)\r\n collection.append(resp_data)\r\n else:\r\n model_instance = model_utils[activity_name](trip[activity_name])\r\n model_instance.save()\r\n resp_data = model_to_dict(model_instance, exclude=exclusions)\r\n collection.append(resp_data)\r\n\r\n\r\n# utility function to save trip data into database\r\n\r\ndef save_trip_data(tripit_api, trip, user_id, trips_collection):\r\n tripit_api.get_trip(trip['id'], {'include_objects': 'true'})\r\n resp = xmltodict.parse(tripit_api.response)\r\n trip_obj = resp['Response']\r\n new_trip = create_trip(trip_obj['Trip'], user_id)\r\n new_trip.save()\r\n trip_dict = model_to_dict(new_trip, exclude=['id', 'user', 'tripit_last_modified'])\r\n trips_collection.append(trip_dict)\r\n\r\n db_exclusions = ['id', 'trip', 'tripit_last_modified']\r\n trip_dict['LodgingObject'] = []\r\n trip_dict['RestaurantObject'] = []\r\n trip_dict['AirObject'] = []\r\n\r\n save_activity_data(trip_obj, 'LodgingObject', trip_dict['LodgingObject'], db_exclusions)\r\n save_activity_data(trip_obj, 'RestaurantObject', trip_dict['RestaurantObject'], db_exclusions)\r\n save_activity_data(trip_obj, 'AirObject', trip_dict['AirObject'], db_exclusions)\r\n","sub_path":"ratings/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"56520000","text":"from datetime import datetime\nfrom datetime import datetime, timedelta\nfrom email.utils import parsedate_tz\nfrom cassandra.cluster import Cluster\nfrom cassandra.query import BatchStatement, SimpleStatement\nfrom cassandra.query import named_tuple_factory, ValueSequence\nfrom . import config\nimport re\n\ndef createCassandraConnection():\n cluster = Cluster(['34.208.209.148'])\n session = cluster.connect()\n session.execute('USE '+config.cassandra_keyspace+';')\n # session.execute('DROP TABLE IF EXISTS '+config.cassandra_table+'')\n # session.execute(config.cassandra_createTableQuery)\n return session\n\n#return RFC822 compliant string date to UTC date object\ndef to_datetime(datestring):\n time_tuple = parsedate_tz(datestring.strip())\n dt = datetime(*time_tuple[:6])\n return dt - timedelta(seconds=time_tuple[-1])\n\ndef insertIntoCassandra(data, session):\n for tweet in data[\"results\"]:\n hashtagList=[]\n tweet_date= to_datetime(tweet[\"created_at\"])\n tweet_id= tweet[\"id\"]\n tweet_text=tweet[\"text\"]\n tweet_text = re.sub(r\"(?:\\@|https?\\://)\\S+\", \"\", tweet_text)\n place = tweet[\"place\"]\n hashtags = tweet[\"entities\"][\"hashtags\"]\n for hashtag in hashtags:\n hashtagList.append(hashtag['text'])\n retweet_count = tweet[\"retweet_count\"]\n\n batch = BatchStatement()\n insert_data = session.prepare('INSERT INTO '+config.cassandra_table+' (tweetID, tweetDate, retweetCount, tweet, hashtags) VALUES (?, ?, ?, ?, ?)')\n batch.add(insert_data, (tweet_id, tweet_date, retweet_count, tweet_text, hashtagList))\n session.execute(batch)\n\n\n\ndef readTopicsFromCassandra(month):\n year = '2016'\n session = createCassandraConnection()\n session.row_factory = named_tuple_factory\n query = session.prepare('SELECT topic,topics FROM '+ config.cassandra_topic_table + ' WHERE month = ? and year = ? ALLOW FILTERING')\n rows = session.execute(query, [month, year])\n return rows\n","sub_path":"Django_web/topics/CassandraManager.py","file_name":"CassandraManager.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"356692763","text":"import random\r\nimport re\r\nfrom urllib.parse import parse_qs\r\n\r\nimport requests\r\n\r\nimport common\r\n\r\n\r\nclass CC:\r\n STAT_FAIL = 0\r\n STAT_SUCCESS = 1\r\n STAT_CLOSE = 2\r\n\r\n LOGIN_URL = '%s://%s/Login.aspx'\r\n SIGNIN_URL = '%s://%s/sSign.aspx'\r\n SIGNIN_MOBILE_PORTAL_URL = '%s://%s/m/SignM.aspx'\r\n SIGNIN_MOBILE_URL = '%s://%s/m/SignCct.aspx'\r\n\r\n def __init__(self, host=None, auth=None, protocol='http'):\r\n if host is None:\r\n host = 'cc.szpt.edu.cn'\r\n self._session = requests.session()\r\n self._session.auth = auth\r\n\r\n self.LOGIN_URL = self.LOGIN_URL % (protocol, host)\r\n self.SIGNIN_URL = self.SIGNIN_URL % (protocol, host)\r\n self.SIGNIN_MOBILE_PORTAL_URL = self.SIGNIN_MOBILE_PORTAL_URL % (protocol, host)\r\n self.SIGNIN_MOBILE_URL = self.SIGNIN_MOBILE_URL % (protocol, host)\r\n\r\n def extract_form(self, content, index=0):\r\n fs = common.extract_forms(content)\r\n if len(fs) > index:\r\n f = fs[index]\r\n data = common.generate_data(f['inputs'])\r\n return data\r\n else:\r\n return None\r\n\r\n def login(self, username, password):\r\n resp = self._session.get(self.LOGIN_URL)\r\n data = self.extract_form(resp.text)\r\n if data is not None:\r\n data['TextBoxTeacherName'] = username\r\n data['TextBoxPassword'] = password\r\n resp = self._session.post(self.LOGIN_URL, data)\r\n return 'Logined' in resp.url\r\n else:\r\n return False\r\n\r\n def signin(self):\r\n resp = self._session.get(self.SIGNIN_URL)\r\n data = self.extract_form(resp.text)\r\n if data is not None:\r\n resp = self._session.post(self.SIGNIN_URL, data)\r\n if '签到成功' in resp.text:\r\n return CC.STAT_SUCCESS\r\n elif '签到未开通' in resp.text:\r\n return CC.STAT_CLOSE\r\n else:\r\n return CC.STAT_FAIL\r\n else:\r\n return CC.STAT_FAIL\r\n\r\n def signin_vpn(self):\r\n resp = self._session.get(self.SIGNIN_URL)\r\n data = self.extract_form(resp.text)\r\n if data is not None:\r\n resp = self._session.post(self.SIGNIN_URL, data)\r\n positions = []\r\n indexes = re.findall(r'', resp.text)\r\n for index in indexes:\r\n position = re.findall(r'---- (\\d+) ----' % (index), resp.text)\r\n if len(position) != 0:\r\n positions.append(position[0])\r\n\r\n if len(positions) != 0:\r\n data = self.extract_form(resp.text)\r\n data['TextBoxDesk'] = positions[random.randint(0, len(positions) - 1)]\r\n resp = self._session.post(self.SIGNIN_URL, data)\r\n if '签到成功' in resp.text:\r\n return CC.STAT_SUCCESS\r\n elif '签到未开通' in resp.text:\r\n return CC.STAT_CLOSE\r\n else:\r\n return CC.STAT_FAIL\r\n else:\r\n return CC.STAT_FAIL\r\n\r\n def signin_mobile(self, username):\r\n resp = self._session.get(self.SIGNIN_MOBILE_PORTAL_URL)\r\n data = self.extract_form(resp.text)\r\n if data is not None:\r\n data['TextBoxNameNo'] = username\r\n resp = self._session.post(self.SIGNIN_MOBILE_PORTAL_URL, data)\r\n content = resp.text\r\n if 'SignCct' in content:\r\n return self._signin_mobile(resp)\r\n elif '老师尚未开通签到' in content:\r\n return CC.STAT_CLOSE\r\n else:\r\n return CC.STAT_FAIL\r\n else:\r\n return CC.STAT_FAIL\r\n\r\n def _signin_mobile(self, resp_portal):\r\n content = resp_portal.text\r\n\r\n reg_params = re.compile(\"window.location.href='SignCct\\.aspx\\?(.*?)'\")\r\n params = reg_params.findall(content)\r\n if len(params) >= 1:\r\n params = parse_qs(params[0])\r\n params = dict([(k, v[0]) for k, v in params.items()])\r\n\r\n resp = self._session.get(self.SIGNIN_MOBILE_URL, params=params)\r\n content = resp.text\r\n data = self.extract_form(content)\r\n positions = []\r\n\r\n reg_index = re.compile(\r\n r'')\r\n indexes = reg_index.findall(content)\r\n for index in indexes:\r\n reg_position = re.compile(r'-\\D*(\\d\\.\\d\\.\\d)\\D*?-' % index)\r\n position = reg_position.findall(content)\r\n if len(position) > 0:\r\n positions.append(position[0])\r\n\r\n if len(positions) != 0:\r\n position = positions[random.randint(0, len(positions) - 1)]\r\n data['TextBoxDesk'] = position\r\n resp = self._session.post(self.SIGNIN_MOBILE_URL, data, params=params)\r\n if '签到成功' in resp.text:\r\n return CC.STAT_SUCCESS\r\n else:\r\n return CC.STAT_FAIL\r\n else:\r\n return CC.STAT_FAIL\r\n","sub_path":"cc.py","file_name":"cc.py","file_ext":"py","file_size_in_byte":5171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"636611477","text":"import math\nimport os\nfrom typing import Callable, Dict\nimport logging\n\nfrom matplotlib.offsetbox import AnnotationBbox, OffsetImage\nfrom PIL import Image\nfrom PyQt5 import QtCore, QtGui, QtWidgets, uic\n\nfrom connections.connection import Connection\nfrom util.detail import LOCAL, BUNDLED_DATA, LOGGER, qtSignalLogHandler, GIT_HASH\nfrom util.event_stats import Event\nfrom profiles.rocket_profile import RocketProfile\n\nfrom .mapping import map_data, mapbox_utils\nfrom .mapping.mapping_thread import MappingThread\nfrom main_window.main_app import MainApp\nfrom main_window.mplwidget import MplWidget\n\nqtCreatorFile = os.path.join(BUNDLED_DATA, \"qt_files\", \"comp_app.ui\")\n\nUi_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)\n\n# The marker image, used to show where the rocket is on the map UI\nMAP_MARKER = Image.open(mapbox_utils.MARKER_PATH).resize((12, 12), Image.LANCZOS)\n\nLABLES_UPDATED_EVENT = Event('lables_updated')\nMAP_UPDATED_EVENT = Event('map_updated')\n\n\nclass CompApp(MainApp, Ui_MainWindow):\n\n def __init__(self, connections: Dict[str, Connection], rocket_profile: RocketProfile) -> None:\n \"\"\"\n\n :param connection:\n :type connection: Connection\n :param rocket_profile:\n :type rocket_profile: RocketProfile\n \"\"\"\n super().__init__(connections, rocket_profile)\n\n self.map = map_data.MapData()\n\n self.im = None # Plot im\n\n # Attach functions for static buttons\n self.sendButton.clicked.connect(self.send_button_pressed)\n self.commandEdit.returnPressed.connect(self.send_button_pressed)\n self.actionSave.triggered.connect(self.save_file)\n self.actionSave.setShortcut(\"Ctrl+S\")\n self.actionReset.triggered.connect(self.reset_view)\n\n # Hook-up logger to UI text output\n # Note: Currently doesnt print logs from other processes (e.g. mapping process)\n log_format = logging.Formatter(\"[%(asctime)s] (%(levelname)s) %(message)s\")\n log_handler = qtSignalLogHandler(exception_traces=False)\n log_handler.setLevel(logging.INFO)\n log_handler.setFormatter(log_format)\n log_handler.qt_signal.connect(self.print_to_ui)\n LOGGER.addHandler(log_handler)\n\n self.setup_buttons()\n self.setup_labels()\n self.setup_subwindow().showMaximized()\n\n self.setWindowIcon(QtGui.QIcon(mapbox_utils.MARKER_PATH))\n\n self.original_geometry = self.saveGeometry()\n self.original_state = self.saveState()\n self.settings = QtCore.QSettings('UBCRocket', 'UBCRGS')\n self.restore_view()\n\n # Init and connection of MappingThread\n self.MappingThread = MappingThread(self.connections, self.map, self.rocket_data, self.rocket_profile)\n self.MappingThread.sig_received.connect(self.receive_map)\n self.MappingThread.start()\n\n LOGGER.info(f\"Successfully started app (version = {GIT_HASH})\")\n\n def setup_buttons(self):\n \"\"\"Create all of the buttons for the loaded rocket profile.\"\"\"\n\n grid_width = math.ceil(math.sqrt(len(self.rocket_profile.buttons)))\n\n # Trying to replicate PyQt's generated code from a .ui file as closely as possible. This is why setattr is\n # being used to keep all of the buttons as named attributes of MainApp and not elements of a list.\n row = 0\n col = 0\n for button in self.rocket_profile.buttons:\n qt_button = QtWidgets.QPushButton(self.centralwidget)\n setattr(self, button + \"Button\", qt_button)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)\n sizePolicy.setHeightForWidth(getattr(self, button + \"Button\").sizePolicy().hasHeightForWidth())\n qt_button.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setPointSize(16)\n font.setKerning(True)\n qt_button.setFont(font)\n qt_button.setObjectName(f\"{button}Button\")\n self.commandButtonGrid.addWidget(qt_button, row, col, 1, 1)\n if col + 1 < grid_width:\n col += 1\n else:\n col = 0\n row += 1\n # A .py file created from a .ui file will have the labels all defined at the end, for some reason. Two for loops\n # are being used to be consistent with the PyQt5 conventions.\n for button in self.rocket_profile.buttons:\n getattr(self, button + \"Button\").setText(QtCore.QCoreApplication.translate('MainWindow', button))\n\n def gen_send_command(cmd: str) -> Callable[[], None]:\n \"\"\"Creates a function that sends the given command to the console.\"\"\"\n\n def send() -> None:\n self.send_command(cmd)\n\n return send\n\n # Connecting to a more traditional lambda expression would not work in this for loop. It would cause all of the\n # buttons to map to the last command in the list, hence the workaround with the higher order function.\n for button, command in self.rocket_profile.buttons.items():\n getattr(self, button + \"Button\").clicked.connect(gen_send_command(command))\n\n def setup_labels(self):\n \"\"\"Create all of the data labels for the loaded rocket profile.\"\"\"\n\n # Trying to replicate PyQt's generated code from a .ui file as closely as possible. This is why setattr is\n # being used to keep all of the buttons as named labels of MainApp and not elements of a list.\n for label in self.rocket_profile.labels:\n name = label.name\n\n qt_text = QtWidgets.QLabel(self.centralwidget)\n setattr(self, name + \"Text\", qt_text)\n qt_text.setObjectName(f\"{name}Text\")\n\n qt_label = QtWidgets.QLabel(self.centralwidget)\n setattr(self, name + \"Label\", qt_label)\n qt_label.setObjectName(f\"{name}Label\")\n\n self.dataLabelFormLayout.addRow(qt_text, qt_label)\n\n # A .py file created from a .ui file will have the labels all defined at the end, for some reason. Two for loops\n # are being used to be consistent with the PyQt5 conventions.\n for label in self.rocket_profile.labels:\n name = label.name\n getattr(self, name + \"Text\").setText(QtCore.QCoreApplication.translate(\"MainWindow\", label.display_name + \":\"))\n getattr(self, name + \"Label\").setText(QtCore.QCoreApplication.translate(\"MainWindow\", \"\"))\n\n def setup_subwindow(self):\n self.plotWidget = MplWidget()\n # Hook-up Matplotlib callbacks\n self.plotWidget.canvas.fig.canvas.mpl_connect('resize_event', self.map_resized_event)\n # TODO: Also have access to click, scroll, keyboard, etc. Would be good to implement map manipulation.\n\n sub = QtWidgets.QMdiSubWindow()\n sub.layout().setContentsMargins(0, 0, 0, 0)\n sub.setWidget(self.plotWidget)\n sub.setWindowTitle(\"Data Plot\")\n sub.setWindowIcon(QtGui.QIcon(mapbox_utils.MARKER_PATH))\n\n self.mdiArea.addSubWindow(sub)\n sub.show()\n\n return sub\n\n def receive_data(self) -> None:\n \"\"\"\n This is called when new data is available to be displayed.\n :return:\n :rtype:\n \"\"\"\n\n for label in self.rocket_profile.labels:\n try:\n getattr(self, label.name + \"Label\").setText(\n label.update(self.rocket_data)\n )\n except:\n LOGGER.exception(f'Failed to update {label.name}Label:')\n\n LABLES_UPDATED_EVENT.increment()\n\n def send_button_pressed(self) -> None:\n \"\"\"\n\n \"\"\"\n word = self.commandEdit.text()\n self.send_command(word)\n self.commandEdit.setText(\"\")\n\n def print_to_ui(self, text) -> None:\n \"\"\"\n This is called when a thread wants to show a message in the UI\n :param text:\n :type text:\n \"\"\"\n current_text = self.consoleText.toPlainText()\n\n if len(current_text) == 0:\n new_text = text\n\n else:\n lines = current_text.split('\\n')\n lines.append(text)\n\n # Limit to 100 lines\n lines = lines[-100:]\n\n new_text = \"\\n\".join(lines)\n\n self.consoleText.setPlainText(new_text)\n self.consoleText.moveCursor(QtGui.QTextCursor.End)\n\n def send_command(self, command) -> None:\n \"\"\"\n Call this to send a command\n :param command:\n :type command:\n \"\"\"\n self.print_to_ui(command)\n super().send_command(command)\n\n def save_file(self) -> None:\n \"\"\"\n\n \"\"\"\n result = QtWidgets.QFileDialog.getSaveFileName(None, 'Save File', directory=LOCAL, filter='.csv')\n if result[0]:\n if result[0][-len(result[1]):] == result[1]:\n name = result[0]\n else:\n name = result[0] + result[1]\n\n self.rocket_data.save(name)\n\n def reset_view(self) -> None:\n original_position = self.geometry().center()\n self.restoreGeometry(self.original_geometry)\n self.restoreState(self.original_state)\n\n # Workaround for known Qt issue. See section on X11 in https://doc.qt.io/qt-5/restoring-geometry.html\n geometry = self.frameGeometry()\n geometry.moveCenter(original_position)\n self.move(geometry.topLeft())\n\n for sub in self.mdiArea.subWindowList():\n sub.close()\n sub.deleteLater() # Required to prevent memory leak. Also deletes window sub-objects (plot widget, etc.)\n\n self.setup_subwindow().showMaximized()\n\n def save_view(self):\n self.settings.setValue('geometry', self.saveGeometry())\n self.settings.setValue('windowState', self.saveState())\n\n def restore_view(self):\n geometry = self.settings.value(\"geometry\")\n if geometry is not None:\n self.restoreGeometry(geometry)\n\n state = self.settings.value(\"windowState\")\n if state is not None:\n self.restoreState(state)\n\n def receive_map(self) -> None:\n \"\"\"\n Updates the UI when a new map is available for display\n \"\"\"\n children = self.plotWidget.canvas.ax.get_children()\n for c in children:\n if isinstance(c, AnnotationBbox):\n c.remove()\n\n zoom, radius, map_image, mark = self.map.get_map_value()\n\n # plotMap UI modification\n self.plotWidget.canvas.ax.set_axis_off()\n self.plotWidget.canvas.ax.set_ylim(map_image.shape[0], 0)\n self.plotWidget.canvas.ax.set_xlim(0, map_image.shape[1])\n\n # Removes pesky white boarder\n self.plotWidget.canvas.fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)\n\n if self.im:\n # Required because plotting images over old ones creates memory leak\n # NOTE: im.set_data() can also be used\n self.im.remove()\n\n self.im = self.plotWidget.canvas.ax.imshow(map_image)\n\n # updateMark UI modification\n annotation_box = AnnotationBbox(OffsetImage(MAP_MARKER), mark, frameon=False)\n self.plotWidget.canvas.ax.add_artist(annotation_box)\n\n # For debugging marker position\n #self.plotWidget.canvas.ax.plot(mark[0], mark[1], marker='o', markersize=3, color=\"red\")\n\n self.plotWidget.canvas.draw()\n\n MAP_UPDATED_EVENT.increment()\n\n def map_resized_event(self, event) -> None:\n \"\"\"\n Called whenever the map plot is resized, also is called once at the start\n :param event:\n :type event:\n \"\"\"\n self.MappingThread.setDesiredMapSize(event.width, event.height)\n\n def shutdown(self):\n self.save_view()\n self.MappingThread.shutdown()\n super().shutdown()\n\n\n","sub_path":"main_window/competition/comp_app.py","file_name":"comp_app.py","file_ext":"py","file_size_in_byte":11788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"380263620","text":"import boto3\n\nsqs_client = boto3.client('sqs')\nqueue_url = 'https://sqs.us-west-2.amazonaws.com/661219094067/identified-face-queue'\nsqs = boto3.resource('sqs')\nqueueName = 'identified-face-queue'\n\nqueue = sqs.get_queue_by_name(QueueName=queueName)\n\n\ndef read_messages_from_queue():\n name_set = set()\n print('reading from queue url', queue.url)\n\n for message in queue.receive_messages(MessageAttributeNames=['Face']):\n print('read')\n if message.message_attributes is not None:\n name = message.message_attributes.get('Face').get('StringValue')\n print('from queue', name)\n name = name.replace('_', \" \")\n if name not in name_set:\n name_set.add(name)\n\n message.delete()\n return name_set\n\n\ndef process_messages_from_queue():\n print('deleting from sqs...')\n name_set = set()\n messages = []\n while True:\n resp = sqs_client.receive_message(\n QueueUrl=queue_url,\n AttributeNames=['All'],\n MessageAttributeNames=['All'],\n MaxNumberOfMessages=10\n )\n\n try:\n messages.extend(resp['Messages'])\n except KeyError:\n break\n\n for message in messages:\n name = message['MessageAttributes']['Face']['StringValue']\n name = name.replace('_', \" \")\n if name not in name_set:\n name_set.add(name)\n\n entries = [\n {'Id': msg['MessageId'], 'ReceiptHandle': msg['ReceiptHandle']}\n for msg in resp['Messages']\n ]\n\n resp = sqs_client.delete_message_batch(\n QueueUrl=queue_url, Entries=entries\n )\n\n if len(resp['Successful']) != len(entries):\n raise RuntimeError(\n f\"Failed to delete messages: entries={entries!r} resp={resp!r}\"\n )\n\n print('{} messages deleted'.format(len(messages)))\n\n return name_set","sub_path":"lambda_services/queus_to_sns.py","file_name":"queus_to_sns.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"185811969","text":"import pdbr\n# from augmentation_policies import augmentation_policies\nimport numpy as np\nfrom typing import Callable\n\nfrom audiomentations import (AddGaussianNoise, AddImpulseResponse,\n AddShortNoises, Compose, FrequencyMask,\n PitchShift, TimeMask, TimeStretch)\n\naugmentation_list = [AddGaussianNoise, AddShortNoises, FrequencyMask, TimeMask ]\n# augmentation_list = [AddGaussianNoise]\n\nclass ComposeAugmentationPolices:\n def __init__(self, probabilities, augmentation_list=augmentation_list):\n self.probabilities = probabilities\n self.augmentation_list = augmentation_list\n self.short_noises_path = \"/jmain01/home/JAD007/txk02/aaa18-txk02/Conv-TasNet/src/mini_data/train_noise\"\n\n def __call__(self) -> Callable:\n composed_augmentations = []\n for i in range(len(self.probabilities)):\n if self.augmentation_list[i].__name__ == 'AddShortNoises':\n composed_augmentations.append(Compose([self.augmentation_list[i](self.short_noises_path, p=self.probabilities[i])]))\n else: composed_augmentations.append(Compose([self.augmentation_list[i](p=self.probabilities[i])]))\n return composed_augmentations\n\nclass AugmentWithPolicies(object):\n def __init__(self, policies):\n self.policies = policies\n\n def __call__(self,audio):\n audios = [policy(audio.copy(), sample_rate=8000) for policy in self.policies] \n return audios\n\n# augmentation_policies = ComposeAugmentationPolices([0.3, 0.6, 0.1], augmentation_list=augmentation_list)\n# augmentation_function = AugmentWithPolicies(augmentation_policies())\n# audio = np.random.randn(8000)\n# aug_audio = np.array(augmentation_function(audio))\n# print(aug_audio)\n\n","sub_path":"src/augment_with_policies.py","file_name":"augment_with_policies.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"424511011","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n# github: https://github.com/houm01\n\nfrom selenium import webdriver\n\n\ndrive = webdriver.Chrome() # 调用Chrome浏览器\ndrive.get('https://www.zhihu.com')\nprint(drive.page_source) # 查看网页源代码\n\n","sub_path":"python_test/crawler/selenium_demo.py","file_name":"selenium_demo.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"332098018","text":"import os\n\n\ndef set_relative_file_path(local_dir, file_path, file_name, file_dirname):\n \"\"\" 图片/附件设置为相对地址 \"\"\"\n\n relative_path = file_path.replace(local_dir, '')\n print('relative_path: %s', relative_path)\n layer_count = len(relative_path.split('/'))\n if layer_count == 2:\n new_file_path = os.path.join('./', file_dirname, file_name).replace('\\\\', '/')\n return new_file_path\n relative = ''\n if layer_count > 2:\n sub_count = layer_count - 2\n for i in range(sub_count):\n relative = os.path.join(relative, '../')\n new_file_path = os.path.join(relative, file_dirname, file_name).replace('\\\\', '/')\n return new_file_path\n\n\ndef main():\n print(\"current\", \"D:\\dev_data\\youdaonote-pull\",)\n return\n","sub_path":"Python/YoudaoNotePuller/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"407495374","text":"import matplotlib as mpl\nmpl.use('agg')\n\nimport os\nimport numpy as np\nimport healpy as hp\nimport pylab as plt\nfrom glob import glob\nfrom ccgpack import sky2patch,ch_mkdir,pop_percent\n\nn_train = 30\nn_test = 22\n\ncmap = plt.cm.jet\ncmap.set_under('w')\ncmap.set_bad('gray',1.)\nnside = 2048\n\ndef kelvin_check(m):\n if m.std()>1e-2:\n return 1e-6*m\n return m\n \ndef build_map(inmap,output,i,ntot,\n ns=1,g=0,sml=5.,\n lmax= 3*2048,prefix=''): \n ch_mkdir(dest)\n dont = 1\n npatch = 12*ns**2\n for j in range(npatch):\n if not os.path.exists(output+prefix+str(i*npatch+j)+'.npy'):\n dont = 0\n if dont:\n return\n \n if sml!=0: \n s = hp.read_map(inmap,nest=0,verbose=0)\n if g:\n s = kelvin_check(s)\n s = hp.smoothing(s,np.radians(sml/60.),lmax=lmax,verbose=0)\n s = hp.reorder(s , r2n=1)\n else:\n s = hp.read_map(inmap,nest=1,verbose=0)\n patches = sky2patch(s,ns)\n for j in range(npatch):\n pop_percent(i*npatch+j,ntot*npatch)\n np.save(output+prefix+str(i*npatch+j),patches[j])\n plt.imshow(patches[j], cmap=cmap)\n plt.savefig(output+prefix+str(i*npatch+j)+'.jpg')\n plt.close()\n \n\nprint('String maps:')\ndest = '../data/string_p/'\nntot = 3\nfor i in range(ntot):\n inmap = '../data/string/map1n_allz_rtaapixlw_2048_'+str(i+1)+'.fits'\n build_map(inmap,dest,i,ntot)\n\n#print('Healpix Gaussian maps:')\n#dest = '../data/training_set/healpix_p/'\n#ntot = 10\n#for i in range(ntot):\n# inmap = '../data/healpix/map_2048_'+str(i)+'.fits'\n# build_map(inmap,dest,i,ntot,g=1)\n\nprint('FFP10 gaussian maps:')\ndest = '../data/ffp10_p/'\nntot = 42\nfor i in range(ntot):\n inmap = '../data/ffp10/ffp10_lensed_scl_cmb_100_mc_'+str(i).zfill(4)+'.fits'\n build_map(inmap,dest,i,ntot,g=1)\n\nprint('OBSERVATIONS:') \ndest = '../data/observations_p/'\nmlist = glob('../data/observations/*.fits')\nfor inmap in mlist:\n prefix = inmap.split('/')[-1][:-5]\n print('Observation: '+prefix)\n build_map(inmap,dest,i=0,ntot=1,g=1,prefix=prefix)\n\nprint('MASK:') \ndest = '../data/mask/'\ninmap = '../data/mask/COM_Mask_CMB-common-Mask-Int_2048_R3.00.fits'\nbuild_map(inmap,dest,i=0,ntot=1,sml=0)\n","sub_path":"cosmic_string/0-initiation/data_builder.py","file_name":"data_builder.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"81873912","text":"from flask import Flask, request\nfrom flask_restful import Resource, Api, reqparse\nfrom json import dumps\n\nimport requests\nfrom bs4 import BeautifulSoup\n\napp = Flask(__name__)\napi = Api(app)\n\ndef scrapeTaste(url):\n try:\n res = requests.get(url)\n except requests.exceptions.RequestException as e:\n return 0\n\n html = res.content\n soup = BeautifulSoup(html, 'html.parser')\n\n title = soup.find('h1').get_text()\n img = soup.select_one('figure.lead-image-block img[src]')['src']\n ingredients = []\n for i in soup.select('section.recipe-ingredients-section div.ingredient-description'):\n ingredients.append(i.text)\n\n method = []\n for i in soup.select('section.recipe-method-section div.recipe-method-step-content'):\n method.append(i.text)\n\n data = {\n url: {\n 'title': title,\n 'image': img,\n 'ingredients': ingredients,\n 'method': method\n }\n }\n\n return data\n\nclass scrapeRecipe(Resource):\n def post(self):\n try:\n parser = reqparse.RequestParser()\n parser.add_argument('url', type=str, help='This is the url for the website')\n args = parser.parse_args()\n\n _userURL = args['url']\n print(args['url'])\n\n if not args['url']:\n return {'error': 'No url supplied'}\n else:\n res = scrapeTaste(args['url'])\n if res == 0:\n return {'error': 'No valid url supplied'}\n else:\n return {'status': 'success', 'data': res}\n except Exception as e:\n return {'error': str(e)}\n\napi.add_resource(scrapeRecipe, '/addrecipe')\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n# scrapeTaste('http://www.taste.com.au/recipes/moroccan-chicken-bowl/QR30rnEH')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"647921351","text":"#comments = [\n# \"Implementation note\",\n# \"Changed\",\n# \"ABC for generator\",\n#]\n#第一版:我们接到一个需求:有一个列表,里面装着很多用户评论,为了在页面正常展示,需要将所有超过一定长度的评论用省略号替代,请写出 一个add_ellipsis 函数方法来实现\n#第二版:我们接到一个需求:有一个列表,里面装着很多用户评论,为了在页面正常展示,需要将所有超过一定长度的评论用省略号替代,如果有一天,我们拿到的评论不再是被继续装在列表里,而是在不可变的元组里呢?\n#请写出 一个add_ellipsis 函数方法来实现\n\n\ncomments = (\n \"Implementation note\",\n \"Changed\",\n \"ABC for generator\",\n)\n\n\ndef add_ellipsis(comments, n=10):\n for i in comments:\n if len(i) > n:\n yield i[:n] + '...'\n else:\n yield i\n # return (i[:n] + '...' if len(i) > n else i for i in comments)\n\n\nprint('\\n'.join(add_ellipsis(comments)))\nprint('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\nprint('\\n'.join(add_ellipsis(comments, 7)))","sub_path":"P17082-袁杰/04/P17082-zuoye_v2.py","file_name":"P17082-zuoye_v2.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"244693366","text":"import unittest\nfrom memoization import cached, CachingAlgorithmFlag, _memoization\nfrom itertools import chain\nfrom threading import Thread\nimport random\nfrom threading import Lock\nimport weakref\nimport gc\nimport time\n\n\nmake_key = _memoization._make_key # bind make_key function\nexec_times = {} # executed time of each tested function\nlock = Lock() # for multi-threading tests\nrandom.seed(100) # set seed to ensure that test results are reproducible\n\nfor i in range(1, 12):\n exec_times['f' + str(i)] = 0 # init to zero\n\n\n################################################################################\n# Tested functions\n################################################################################\n\n@cached\ndef f1(x):\n exec_times['f1'] += 1\n return x\n\n\n@cached()\ndef f2(x):\n exec_times['f2'] += 1\n return x\n\n\n@cached(max_size=5, algorithm=CachingAlgorithmFlag.FIFO, thread_safe=False)\ndef f3(x):\n exec_times['f3'] += 1\n return x\n\n\n@cached(max_size=5, algorithm=CachingAlgorithmFlag.LRU, thread_safe=False)\ndef f4(x):\n exec_times['f4'] += 1\n return x\n\n\n@cached(max_size=5, algorithm=CachingAlgorithmFlag.LFU, thread_safe=False)\ndef f5(x):\n exec_times['f5'] += 1\n return x\n\n\n@cached(max_size=5, algorithm=CachingAlgorithmFlag.FIFO, thread_safe=True)\ndef f6(x):\n with lock:\n exec_times['f6'] += 1\n return x\n\n\n@cached(max_size=5, algorithm=CachingAlgorithmFlag.LRU, thread_safe=True)\ndef f7(x):\n with lock:\n exec_times['f7'] += 1\n return x\n\n\n@cached(max_size=5, algorithm=CachingAlgorithmFlag.LFU, thread_safe=True)\ndef f8(x):\n with lock:\n exec_times['f8'] += 1\n return x\n\n\n@cached(max_size=5, algorithm=CachingAlgorithmFlag.FIFO, thread_safe=False, ttl=0.5)\ndef f9(x):\n exec_times['f9'] += 1\n return x\n\n\n@cached(max_size=5, algorithm=CachingAlgorithmFlag.LRU, thread_safe=False, ttl=0.5)\ndef f10(x):\n exec_times['f10'] += 1\n return x\n\n\n@cached(max_size=5, algorithm=CachingAlgorithmFlag.LFU, thread_safe=False, ttl=0.5)\ndef f11(x):\n exec_times['f11'] += 1\n return x\n\n\n################################################################################\n# Test entry point\n################################################################################\n\nclass TestMemoization(unittest.TestCase):\n def test_memoization_with_default_arguments(self):\n for _ in range(5):\n f1(10)\n f2(10)\n f1(20)\n f2(20)\n\n self.assertEqual(exec_times['f1'], 2)\n self.assertEqual(exec_times['f2'], 2)\n\n for info in f1.cache_info(), f2.cache_info():\n self.assertIsNone(info.max_size)\n self.assertEqual(info.algorithm, CachingAlgorithmFlag.LRU)\n self.assertIsNone(info.ttl)\n self.assertTrue(info.thread_safe)\n\n self.assertEqual(info.hits, 4)\n self.assertEqual(info.misses, 2)\n self.assertEqual(info.current_size, 2)\n for f in f1, f2:\n keys = make_key((10,), None), make_key((20,), None)\n for key in keys:\n self.assertIn(key, f._cache)\n\n def test_memoization_with_FIFO(self):\n self.assertTrue(hasattr(f3, '_fifo_root'))\n self._fifo_test(f3)\n f3.cache_clear()\n self._check_empty_cache_after_clearing(f3)\n\n def test_memoization_with_LRU(self):\n self.assertTrue(hasattr(f4, '_lru_root'))\n self._lru_test(f4)\n f4.cache_clear()\n self._check_empty_cache_after_clearing(f4)\n\n def test_memoization_with_LFU(self):\n self.assertTrue(hasattr(f5, '_lfu_root'))\n self._lfu_test(f5)\n self._check_lfu_cache_clearing(f5)\n\n def test_memoization_with_FIFO_multithread(self):\n self.assertTrue(hasattr(f6, '_fifo_root'))\n self._general_multithreading_test(f6, CachingAlgorithmFlag.FIFO)\n self._fifo_test(f6)\n f6.cache_clear()\n self._check_empty_cache_after_clearing(f6)\n\n def test_memoization_with_LRU_multithread(self):\n self.assertTrue(hasattr(f7, '_lru_root'))\n self._general_multithreading_test(f7, CachingAlgorithmFlag.LRU)\n self._lru_test(f7)\n f7.cache_clear()\n self._check_empty_cache_after_clearing(f7)\n\n def test_memoization_with_LFU_multithread(self):\n self.assertTrue(hasattr(f8, '_lfu_root'))\n self._general_multithreading_test(f8, CachingAlgorithmFlag.LFU)\n self._lfu_test(f8)\n self._check_lfu_cache_clearing(f8)\n\n def test_memoization_with_FIFO_TTL(self):\n self.assertTrue(hasattr(f9, '_fifo_root'))\n self._general_ttl_test(f9)\n f9.cache_clear()\n self._check_empty_cache_after_clearing(f9)\n\n def test_memoization_with_LRU_TTL(self):\n self.assertTrue(hasattr(f10, '_lru_root'))\n self._general_ttl_test(f10)\n f10.cache_clear()\n self._check_empty_cache_after_clearing(f10)\n\n def test_memoization_with_LFU_TTL(self):\n self.assertTrue(hasattr(f11, '_lfu_root'))\n self._general_ttl_test(f11)\n self._check_lfu_cache_clearing(f11)\n\n def test_memoization_for_unhashable_arguments_with_FIFO(self):\n self._general_unhashable_arguments_test(f3)\n f3.cache_clear()\n self._check_empty_cache_after_clearing(f3)\n\n def test_memoization_for_unhashable_arguments_with_LRU(self):\n self._general_unhashable_arguments_test(f4)\n f4.cache_clear()\n self._check_empty_cache_after_clearing(f4)\n\n def test_memoization_for_unhashable_arguments_with_LFU(self):\n self._general_unhashable_arguments_test(f5)\n self._check_lfu_cache_clearing(f5)\n\n\n def _general_test(self, tested_function, algorithm, hits, misses, in_cache, not_in_cache):\n # clear\n exec_times[tested_function.__name__] = 0\n tested_function.cache_clear()\n\n for i in range(20):\n tested_function(i)\n tested_function(99)\n\n self.assertEqual(exec_times[tested_function.__name__], 21)\n info = tested_function.cache_info()\n self.assertEqual(info.max_size, 5)\n self.assertEqual(info.algorithm, algorithm)\n self.assertIsNone(info.ttl)\n self.assertIsNotNone(info.thread_safe)\n\n self.assertEqual(info.hits, 0)\n self.assertEqual(info.misses, 21)\n self.assertEqual(info.current_size, 5)\n\n keys = [make_key((x,), None) for x in (99, 19, 18, 17, 16)]\n for key in keys:\n self.assertIn(key, tested_function._cache)\n\n # 10 consecutive calls here\n tested_function(16)\n tested_function(17)\n tested_function(18)\n tested_function(16)\n tested_function(17)\n tested_function(18)\n\n tested_function(19)\n tested_function(15)\n tested_function(100)\n tested_function(16)\n\n info = tested_function.cache_info()\n self.assertEqual(info.hits, hits)\n self.assertEqual(info.misses, misses)\n self.assertEqual(info.current_size, 5)\n\n keys = [make_key((x,), None) for x in in_cache]\n for key in keys:\n self.assertIn(key, tested_function._cache)\n keys = [make_key((x,), None) for x in chain(not_in_cache, range(0, 15))]\n for key in keys:\n self.assertNotIn(key, tested_function._cache)\n\n def _general_multithreading_test(self, tested_function, algorithm):\n number_of_keys = 30000\n number_of_threads = 4\n\n # clear\n exec_times[tested_function.__name__] = 0\n tested_function.cache_clear()\n\n info = tested_function.cache_info()\n self.assertEqual(info.max_size, 5)\n self.assertEqual(info.algorithm, algorithm)\n self.assertIsNone(info.ttl)\n self.assertTrue(info.thread_safe)\n self.assertEqual(info.current_size, 0)\n\n # Test must-hit\n def run_must_hit():\n keys = list(range(5)) * int(number_of_keys / 5)\n random.shuffle(keys)\n for i in keys:\n tested_function(i)\n\n threads = [Thread(target=run_must_hit) for _ in range(number_of_threads)]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\n self.assertGreaterEqual(exec_times[tested_function.__name__], 5)\n info = tested_function.cache_info()\n self.assertLessEqual(info.hits, number_of_keys * number_of_threads - 5)\n self.assertGreaterEqual(info.misses, 5)\n self.assertEqual(info.current_size, 5)\n\n for key in [make_key((x,), None) for x in range(5)]:\n self.assertIn(key, tested_function._cache)\n\n # Test can-miss\n def run_can_miss():\n keys = list(range(20)) * int(number_of_keys / 20)\n random.shuffle(keys)\n for i in keys:\n tested_function(i)\n\n threads = [Thread(target=run_can_miss) for _ in range(number_of_threads)]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\n executed_times = exec_times[tested_function.__name__]\n self.assertLessEqual(executed_times, number_of_keys * number_of_threads)\n self.assertGreaterEqual(executed_times, 20)\n info = tested_function.cache_info()\n self.assertGreaterEqual(info.hits, 0)\n self.assertLessEqual(info.misses, number_of_keys * number_of_threads)\n self.assertEqual(info.current_size, 5)\n\n def _fifo_test(self, tested_function):\n self._general_test(tested_function=tested_function, algorithm=CachingAlgorithmFlag.FIFO, hits=7, misses=24,\n in_cache=(16, 100, 15, 99, 19), not_in_cache=(18, 17))\n self.assertEqual(exec_times[tested_function.__name__], 24)\n\n def _lru_test(self, tested_function):\n self._general_test(tested_function=tested_function, algorithm=CachingAlgorithmFlag.LRU, hits=7, misses=24,\n in_cache=(16, 100, 15, 19, 18), not_in_cache=(99, 17))\n self.assertEqual(exec_times[tested_function.__name__], 24)\n\n def _lfu_test(self, tested_function):\n self._general_test(tested_function=tested_function, algorithm=CachingAlgorithmFlag.LFU, hits=8, misses=23,\n in_cache=(18, 17, 16, 19, 100), not_in_cache=(99, 15))\n self.assertEqual(exec_times[tested_function.__name__], 23)\n\n def _check_empty_cache_after_clearing(self, tested_function):\n info = tested_function.cache_info()\n self.assertEqual(info.hits, 0)\n self.assertEqual(info.misses, 0)\n self.assertEqual(info.current_size, 0)\n self.assertEqual(info.max_size, 5)\n\n cache = tested_function._cache\n self.assertEqual(len(cache), 0)\n\n def _check_lfu_cache_clearing(self, tested_function):\n root_next = weakref.ref(tested_function._lfu_root.next)\n first_cache_head = weakref.ref(tested_function._lfu_root.next.cache_head)\n self.assertIsNotNone(root_next())\n self.assertIsNotNone(first_cache_head())\n\n tested_function.cache_clear()\n self._check_empty_cache_after_clearing(tested_function)\n\n gc.collect()\n self.assertIsNone(root_next())\n self.assertIsNone(first_cache_head())\n\n def _general_ttl_test(self, tested_function):\n # clear\n exec_times[tested_function.__name__] = 0\n tested_function.cache_clear()\n\n arg = 1\n key = make_key((arg,), None)\n tested_function(arg)\n time.sleep(0.25) # wait for a short time\n\n info = tested_function.cache_info()\n self.assertEqual(info.hits, 0)\n self.assertEqual(info.misses, 1)\n self.assertEqual(info.current_size, 1)\n self.assertIn(key, tested_function._cache)\n\n tested_function(arg) # this WILL NOT call the tested function\n\n info = tested_function.cache_info()\n self.assertEqual(info.hits, 1)\n self.assertEqual(info.misses, 1)\n self.assertEqual(info.current_size, 1)\n self.assertIn(key, tested_function._cache)\n self.assertEqual(exec_times[tested_function.__name__], 1)\n\n time.sleep(0.35) # wait until the cache expires\n\n info = tested_function.cache_info()\n self.assertEqual(info.current_size, 1)\n\n tested_function(arg) # this WILL call the tested function\n\n info = tested_function.cache_info()\n self.assertEqual(info.hits, 1)\n self.assertEqual(info.misses, 2)\n self.assertEqual(info.current_size, 1)\n self.assertIn(key, tested_function._cache)\n self.assertEqual(exec_times[tested_function.__name__], 2)\n\n def _general_unhashable_arguments_test(self, tested_function):\n args = ([1, 2, 3], {'this': 'is unhashable'}, ['yet', ['another', ['complex', {'type, ': 'isn\\'t it?'}]]])\n for arg in args:\n # clear\n exec_times[tested_function.__name__] = 0\n tested_function.cache_clear()\n\n key = make_key((arg,), None)\n tested_function(arg)\n self.assertIn(key, tested_function._cache)\n\n if isinstance(arg, list):\n arg.append(0)\n elif isinstance(arg, dict):\n arg['foo'] = 'bar'\n else:\n raise TypeError\n key = make_key((arg,), None)\n tested_function(arg)\n self.assertIn(key, tested_function._cache)\n\n if isinstance(arg, list):\n arg.pop()\n elif isinstance(arg, dict):\n del arg['foo']\n else:\n raise TypeError\n key = make_key((arg,), None)\n tested_function(arg)\n self.assertIn(key, tested_function._cache)\n\n self.assertEqual(exec_times[tested_function.__name__], 2)\n info = tested_function.cache_info()\n self.assertEqual(info.hits, 1)\n self.assertEqual(info.misses, 2)\n self.assertEqual(info.current_size, 2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":14023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"219424021","text":"# 6.0001/6.00 Problem Set 5 - RSS Feed Filter\n# Name:neelima-j\n\n\nimport feedparser\nimport string\nimport time\nimport threading\nfrom project_util import translate_html\nfrom mtTkinter import *\nfrom datetime import datetime\nimport pytz\nimport re\nimport requests\n\n\n#-----------------------------------------------------------------------\n\n#======================\n# Code for retrieving and parsing\n# Google and Yahoo News feeds\n# Do not change this code\n#======================\n\ndef process(url):\n \"\"\"\n Fetches news items from the rss url and parses them.\n Returns a list of NewsStory-s.\n \"\"\"\n feed_content = requests.get(url)\n feed = feedparser.parse(feed_content.text)\n# feed = feedparser.parse(url)\n entries = feed.entries\n ret = []\n for entry in entries:\n guid = entry.guid\n title = translate_html(entry.title)\n link = entry.link\n description = translate_html(entry.description)\n pubdate = translate_html(entry.published)\n\n try:\n pubdate = datetime.strptime(pubdate, \"%a, %d %b %Y %H:%M:%S %Z\")\n\n # pubdate.replace(tzinfo=pytz.timezone(\"GMT\"))\n # pubdate = pubdate.astimezone(pytz.timezone('EST'))\n pubdate.replace(tzinfo=None)\n except ValueError:\n pubdate = datetime.strptime(pubdate, \"%a, %d %b %Y %H:%M:%S %z\")\n\n newsStory = NewsStory(guid, title, description, link, pubdate)\n ret.append(newsStory)\n return ret\n\n#======================\n# Data structure design\n#======================\n\n# Problem 1\n\n# TODO: NewsStory\nclass NewsStory():\n def __init__(self,guid, title, description, link, pubdate):\n self.guid = guid\n self.title = title\n self.description = description\n self.link = link\n self.pubdate = pubdate\n \n def get_guid(self):\n return self.guid\n def get_title(self):\n return self.title\n def get_description(self):\n return self.description\n def get_link(self):\n return self.link\n def get_pubdate(self):\n return self.pubdate\n \n\n\n#======================\n# Triggers\n#======================\n\nclass Trigger(object):\n def evaluate(self, story):\n \"\"\"\n Returns True if an alert should be generated\n for the given news item, or False otherwise.\n \"\"\"\n # DO NOT CHANGE THIS!\n raise NotImplementedError\n\n# PHRASE TRIGGERS\n\n# Problem 2\n# TODO: PhraseTrigger\n\nclass PhraseTrigger(Trigger):\n def __init__(self,phrase):\n self.phrase = phrase.lower().strip()\n self.phrase = \"\".join((char if char.isalpha() else \"\") for char in self.phrase)\n def is_phrase_in(self,text):\n regexString = self.phrase+'(?!s)(?!!)'\n phraseRegEx = re.compile(regexString)\n text = text.lower()\n text = \"\".join((char if char.isalpha() else \"\") for char in text)\n text = text+' '\n repeatRegEx = re.compile(r\"(.+?)\\1+\")\n \n if (phraseRegEx.findall(text) and repeatRegEx.match(text) == None):\n return True\n else:\n return False\n \n \n\n# Problem 3\n# TODO: TitleTrigger\nclass TitleTrigger(PhraseTrigger):\n def evaluate(self,story):\n if self.is_phrase_in(story.title):\n return True\n else:\n return False\n\n \n \n\n# Problem 4\n# TODO: DescriptionTrigger\nclass DescriptionTrigger(PhraseTrigger):\n def evaluate(self, story):\n if self.is_phrase_in(story.description):\n return True\n else:\n return False\n \n\n# TIME TRIGGERS\n\n# Problem 5\n# Constructor:\n# Input: Time has to be in EST and in the format of \"%d %b %Y %H:%M:%S\".\n# Convert time from string to a datetime before saving it as an attribute.\nclass TimeTrigger(Trigger):\n def __init__(self,time):\n self.time = datetime.strptime(time,r'%d %b %Y %H:%M:%S')\n '''\n\n est = pytz.timezone('US/Eastern')\n self.time = est.localize(self.time)\n '''\n \n# Problem 6\nclass BeforeTrigger(TimeTrigger):\n def evaluate(self,story):\n '''\n Fires when a story is published strictly before the trigger’s time\n '''\n story.pubdate = story.pubdate.replace(tzinfo = None)\n \n '''I have no idea why it didnt work when everythin was in EST. So i removed TZinfo from everywhere\n\n if story.pubdate.tzinfo == None:\n est = pytz.timezone('US/Eastern')\n story.pubdate = est.localize(story.pubdate)\n ''' \n \n if story.pubdate < self.time:\n return True\n else:\n return False\n \nclass AfterTrigger(TimeTrigger):\n def evaluate(self,story):\n '''\n fires when a story is published strictly after the trigger’s time\n '''\n story.pubdate = story.pubdate.replace(tzinfo = None)\n \n '''\n if story.pubdate.tzinfo == None:\n est = pytz.timezone('US/Eastern')\n story.pubdate = est.localize(story.pubdate)\n '''\n if story.pubdate > self.time:\n return True\n else:\n return False\n\n# COMPOSITE TRIGGERS\n\n# Problem 7\n\n\nclass NotTrigger(Trigger):\n def __init__(self,T):\n self.T = T\n def evaluate(self,story):\n return not self.T.evaluate(story)\n# Problem 8\nclass AndTrigger(Trigger):\n def __init__(self,t1,t2):\n self.t1 = t1\n self.t2 = t2\n def evaluate(self,story):\n return self.t1.evaluate(story) and self.t2.evaluate(story)\n\n# Problem 9\nclass OrTrigger(Trigger):\n def __init__(self,t1,t2):\n self.t1 = t1\n self.t2 = t2\n def evaluate(self,story):\n return self.t1.evaluate(story) or self.t2.evaluate(story)\n\n\n\n#======================\n# Filtering\n#======================\n\n# Problem 10\ndef filter_stories(stories, tlist):\n \"\"\"\n Takes in a list of NewsStory instances.\n Returns: a list of only the stories for which a trigger in triggerlist fires.\n \"\"\"\n i=0\n ret_stories = []\n for story in stories:\n for trigger in tlist:\n if trigger.evaluate(story):\n ret_stories.append(story)\n break\n return ret_stories\n\n\n\n#======================\n# User-Specified Triggers\n#======================\n# Problem 11\ndef read_trigger_config(filename):\n \"\"\"\n filename: the name of a trigger configuration file\n\n Returns: a list of trigger objects specified by the trigger configuration\n file.\n \"\"\"\n\n trigger_file = open(filename, 'r')\n lines = []\n triggerlist = []\n ret = []\n\n for line in trigger_file:\n line = line.rstrip()\n if not (len(line) == 0 or line.startswith('//')):\n lines.append(line)\n\n # TODO: Problem 11\n # line is the list of lines that you need to parse and for which you need\n # to build triggers\n i = 0\n for line in lines:\n t,tname,*arg = line.split(',')\n if t != 'ADD':\n tname = tname.capitalize()+'Trigger'\n tobject = globals()[tname]\n if len(arg)==1:\n triggerlist.append(tobject(arg[0]))\n else:\n if tname == 'AND' or 'OR':\n triggerlist.append(tobject(triggerlist[int(arg[0][1])-1],triggerlist[int(arg[1][1])-1]))\n else: \n triggerlist.append(tobject(arg[0],arg[1]))\n elif t == 'ADD':\n ret.append(triggerlist[int(tname[1])-1])\n ret.append(triggerlist[int(arg[0][1])-1])\n return ret\n\n \n\n\n\nSLEEPTIME = 120 #seconds -- how often we poll\n\ndef main_thread(master):\n # A sample trigger list - you might need to change the phrases to correspond\n # to what is currently in the news\n try:\n '''\n \n t1 = TitleTrigger(\"The\")\n t2 = DescriptionTrigger(\"Covid\")\n t3 = DescriptionTrigger(\"India\")\n t4 = AndTrigger(t2, t3)\n triggerlist = [t1, t4]\n '''\n \n # Problem 11\n triggerlist = read_trigger_config('triggers.txt')\n \n # HELPER CODE - you don't need to understand this!\n # Draws the popup window that displays the filtered stories\n # Retrieves and filters the stories from the RSS feeds\n frame = Frame(master)\n frame.pack(side=BOTTOM)\n scrollbar = Scrollbar(master)\n scrollbar.pack(side=RIGHT,fill=Y)\n\n t = \"Google Top News\"\n title = StringVar()\n title.set(t)\n ttl = Label(master, textvariable=title, font=(\"Helvetica\", 18))\n ttl.pack(side=TOP)\n cont = Text(master, font=(\"Helvetica\",14), yscrollcommand=scrollbar.set)\n cont.pack(side=BOTTOM)\n cont.tag_config(\"title\", justify='center')\n button = Button(frame, text=\"Exit\", command=root.destroy)\n button.pack(side=BOTTOM)\n guidShown = []\n def get_cont(newstory):\n if newstory.get_guid() not in guidShown:\n cont.insert(END, newstory.get_title()+\"\\n\", \"title\")\n cont.insert(END, \"\\n---------------------------------------------------------------\\n\", \"title\")\n cont.insert(END, newstory.get_description())\n cont.insert(END, \"\\n*********************************************************************\\n\", \"title\")\n guidShown.append(newstory.get_guid())\n\n while True:\n\n print(\"Polling . . .\", end=' ')\n # Get stories from Google's Top Stories RSS news feed\n stories = process(\"http://news.google.com/news?output=rss\")\n # Get stories from Yahoo's Top Stories RSS news feed\n# stories.extend(process(\"http://news.yahoo.com/rss/topstories\"))\n\n stories = filter_stories(stories, triggerlist)\n\n list(map(get_cont, stories))\n scrollbar.config(command=cont.yview)\n\n\n print(\"Sleeping...\")\n time.sleep(SLEEPTIME)\n\n except Exception as e:\n print(e)\n\n\nif __name__ == '__main__':\n root = Tk()\n root.title(\"Some RSS parser\")\n t = threading.Thread(target=main_thread, args=(root,))\n t.start()\n root.mainloop()\n\n","sub_path":"ps5.py","file_name":"ps5.py","file_ext":"py","file_size_in_byte":10132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"78264924","text":"from enum import Enum\nfrom fastapi import FastAPI, status, HTTPException\nfrom helm_release_ops import create_release, delete_release\nfrom pydantic import BaseModel\nfrom pymongo import MongoClient\nfrom typing import Optional, List\nfrom bson.objectid import ObjectId\n\n\n# Initialize MongoDB\nclient = MongoClient('mongodb://default-mongodb:27017')\ndb = client.mepm\n\n\ndef preload_helm_releases():\n db.helm_releases.drop()\n db.helm_releases.insert_many(helm_releases)\n\n\nhelm_releases = [\n {\n \"appDId\": \"1\",\n \"helm_chart\": {\n \"repository\": \"https://kubernetes-charts.storage.googleapis.com\",\n \"name\": \"grafana\",\n \"version\": \"5.1.2\"\n }\n }\n]\npreload_helm_releases()\n\n\n# MongoDB operations\ndef get_helm_release(appDId: str):\n helm_release = db.helm_releases.find_one(\n {'appDId': appDId})\n return helm_release\n\n\ndef delete_app_instance_info(appInstanceId: str):\n app_instance_info = db.app_instances_info.delete_one(\n {'_id': ObjectId(appInstanceId)})\n return app_instance_info\n\n\ndef get_app_instance_info(appInstanceId: str):\n app_instance_info = db.app_instances_info.find_one(\n {'_id': ObjectId(appInstanceId)})\n return app_instance_info\n\n\ndef get_app_instances_info():\n app_instances_info = db.app_instances_info.find()\n return app_instances_info\n\n\n# Definition of Data Models\nclass CreateAppInstanceRequest(BaseModel):\n appDId: str\n appInstanceName: str\n appInstanceDescription: str\n\n\nclass InstantiateAppRequest(BaseModel):\n virtualComputeDescriptor: Optional[list] = None\n virtualStorageDescriptor: Optional[list] = None\n selectedMECHostInfo: Optional[str] = \"Test MEC Host\"\n\n\nclass InstantiationState(str, Enum):\n NOT_STANTIATED = \"NOT_STANTIATED\"\n STANTIATED = \"STANTIATED\"\n\n\nclass AppInstanceInfo(BaseModel):\n appInstanceId: str\n appInstanceName: str\n appInstanceDescription: str\n appDId: str\n appPkgId: str\n instantiationState: InstantiationState\n\n# FastAPI specific code\napp = FastAPI(\n title=\"MEPM Mm3 AppLcm API\",\n description=\"Implementation of Mm3.AppLcm APIs\",\n version=\"1.0.0\")\n\n\n@app.post(\"/app_lcm/v1/app_instances\", status_code=status.HTTP_201_CREATED)\nasync def create_app_instance(app_instance_request: CreateAppInstanceRequest):\n app_instance_info = {\n \"appInstanceName\": app_instance_request.appInstanceName,\n \"appInstanceDescription\": app_instance_request.appInstanceDescription,\n \"appDId\": app_instance_request.appDId,\n \"appPkgId\": app_instance_request.appDId,\n \"instantiationState\": InstantiationState.NOT_STANTIATED\n }\n app_instance_id = db.app_instances_info.insert_one(\n app_instance_info).inserted_id\n\n return {\"appInstanceId\": \"%s\" % app_instance_id}\n\n\n@app.get(\"/app_lcm/v1/app_instances\",\n response_model=List[AppInstanceInfo],\n status_code=status.HTTP_200_OK)\nasync def get_app_instances():\n app_instances_info = []\n for info in get_app_instances_info():\n info['appInstanceId'] = str(info.pop('_id'))\n app_instances_info.append(info)\n\n return [AppInstanceInfo(**info) for info in app_instances_info]\n\n\n@app.delete(\"/app_lcm/v1/app_instances/{appInstanceId}\",\n status_code=status.HTTP_204_NO_CONTENT)\nasync def delete_app_instance(appInstanceId: str):\n app_instance_info = get_app_instance_info(appInstanceId)\n if app_instance_info is None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=\"App instance not found\")\n if app_instance_info.get('instantiationState') == InstantiationState.STANTIATED.value:\n raise HTTPException(status_code=status.HTTP_409_CONFLICT,\n detail=\"Cannot delete MEC Application instance in 'STANTIATED' state\")\n delete_app_instance_info(appInstanceId)\n\n\n@app.get(\"/app_lcm/v1/app_instances/{appInstanceId}\",\n response_model=AppInstanceInfo,\n status_code=status.HTTP_200_OK)\nasync def get_app_instance(appInstanceId: str):\n app_instance_info = get_app_instance_info(appInstanceId)\n if app_instance_info is None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=\"App instance not found\")\n app_instance_info['appInstanceId'] = str(app_instance_info.pop('_id'))\n\n return AppInstanceInfo(**app_instance_info)\n\n\n@app.post(\"/app_lcm/v1/app_instances/{appInstanceId}/instantiate\",\n status_code=status.HTTP_202_ACCEPTED)\nasync def instantiate_app_instance(\n appInstanceId: str,\n instantiateAppRequest: InstantiateAppRequest):\n app_instance_info = get_app_instance_info(appInstanceId)\n if app_instance_info is None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=\"App instance not found\")\n if app_instance_info.get('instantiationState') == InstantiationState.STANTIATED.value:\n raise HTTPException(status_code=status.HTTP_409_CONFLICT,\n detail=\"MEC Application already present\")\n appDId = app_instance_info.get('appDId')\n helm_release = get_helm_release(appDId)\n try:\n create_release(\n repository=helm_release['repository'],\n name=helm_release['name'],\n version=helm_release['version'])\n except Exception:\n raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail=\"MEC Application could not be instantiated.\")\n db.app_instances_info.update_one(\n {'_id': ObjectId(appInstanceId)},\n {\"$set\": {\"instantiationState\": InstantiationState.STANTIATED.value}})\n\n\n@app.post(\"/app_lcm/v1/app_instances/{appInstanceId}/terminate\",\n status_code=status.HTTP_202_ACCEPTED)\nasync def terminate_app_instance(\n appInstanceId: str):\n app_instance_info = get_app_instance_info(appInstanceId)\n if app_instance_info is None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=\"App instance not found\")\n if app_instance_info.get('instantiationState') == InstantiationState.NOT_STANTIATED.value:\n raise HTTPException(status_code=status.HTTP_409_CONFLICT,\n detail=\"Cannot terminate MEC Application in 'NOT_STANTIATED' state\")\n appDId = app_instance_info.get('appDId')\n helm_release = get_helm_release(appDId)\n try:\n delete_release(name=helm_release['name'])\n except Exception:\n raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail=\"MEC Application could not be instantiated.\")\n db.app_instances_info.update_one(\n {'_id': ObjectId(appInstanceId)},\n {\"$set\": {\"instantiationState\": InstantiationState.NOT_STANTIATED.value}})","sub_path":"mec_k8s/ansible/roles/helm-wrapper/files/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"301989775","text":"\nfilename = 'c_cipher1.py'\nignored_words = 'ignored_words.py'\n\n##reads in the ciphertext\nwith open(filename, 'r') as f:\n data = f.read()\n\n\n##reads in a list of strings that nltk.corpus.words.words considers words\n##but which I want to ignore\nnot_words = []\nwith open(ignored_words, 'r') as i:\n for line in i:\n not_words.append(line.strip())\n\n\nfrom collections import OrderedDict\nfrom nltk.corpus import words\nw = set(w.upper() for w in words.words()).difference(not_words)\n\n\n\nprint('You have opened the file ' + filename + '. The contents are: \\n ')\n\nfor line in data:\n print(line, end='')\n\nprint('\\nAttempting to decipher.....\\nFrequency analysis is as follows:\\n')\n\n\nfrom decimal import *\ngetcontext().prec = 3\n\nprint('Length of string is ' + str(data.__len__()))\n\n\nalph = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',\n 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n\ni = 0\nd = {}\ncounts = []\nnon_ws = 0\nwhile i < alph.__len__():\n x = data.count(alph[i])\n \n counts.append(str(x))\n\n d.update({alph[i]:x})\n \n non_ws = non_ws + x\n\n i = i + 1\n\n\ni = 0\npercents = []\nwhile i < alph.__len__():\n perc = float(format((int(counts[i])/non_ws)*100, '.3f'))\n\n percents.append(str(perc))\n\n print('\\n' + repr(alph[i]).rjust(4) + ': ' + repr(counts[i]).rjust(5) +\n ' occurrences, which is ' + repr(percents[i]).rjust(6) + '% of the string.')\n\n i = i + 1\n\nsorted_d = sorted(d, key=d.get, reverse=True)\n\nordered_dict = OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True))\n\n##Rather than have the user try to visually verify whether a deciphering is\n##correct, I'd like to run the message through the dictionary w above and\n##try to find the correct message key that way.\n\nchoose_soln = input('\\nIf you\\'d like the program to find the most likely '\n + '\\nkey, enter Y.\\n'\n + '\\nIf you\\'d like to choose among the most likely keys yourself,'\n + '\\nenter N.\\n'\n + '\\nIf you\\'d like to exit, enter E.\\n')\nif choose_soln != 'Y' and choose_soln != 'N' and choose_soln != 'E':\n choo_soln = input('\\nInvalid entry. Please enter Y to have the most'\n + '\\nprobably translation selected for you, enter N to cycle'\n + '\\nthrough the most likely key choices manually, or'\n + 'enter E to exit.')\n \nif choose_soln == 'N':\n map_answer = input('\\nThe most likely mapping is ' + sorted_d[0] + ' -> E. If you would\\n'\n + 'like to see the message deciphered using this mapping, enter Y.\\n'\n + 'If you would like to go to the next possible mapping, enter N.\\n'\n + 'If you would like to exit, enter E.\\n')\n\n possible_mapping_no = 0\n\n while map_answer != 'E' and possible_mapping_no < 26:\n map_from_index = alph.index(sorted_d[possible_mapping_no])\n map_to_index = 4\n mapping = {}\n str_message = ''\n ind = 0\n \n if map_answer == 'N':\n possible_mapping_no = possible_mapping_no + 1\n \n map_answer = input('\\nThe next most likely mapping is ' + sorted_d[possible_mapping_no] + ' -> E. If you would\\n'\n + 'like to see the message deciphered using this mapping, enter Y.\\n'\n + 'If you would like to go to the next possible mapping, enter N.\\n'\n + 'If you would like to exit, enter E.\\n')\n map_from_index = alph.index(sorted_d[possible_mapping_no])\n\n if map_answer == 'Y':\n while len(mapping) < 26:\n \n mapping.update({alph[map_from_index]:alph[map_to_index]})\n map_from_index = (map_from_index + 1)%26\n map_to_index = (map_to_index + 1)%26\n \n mapping.update({' ':''})\n mapping.update({'\\n':'\\n'})\n print('Under this mapping, the message is: \\n')\n while ind < len(data):\n str_message = str_message + mapping[data[ind]]\n ind = ind + 1\n \n print(str_message)\n possible_mapping_no = possible_mapping_no + 1\n \n map_answer = input('\\nThe next most likely mapping is ' + sorted_d[possible_mapping_no] + ' -> E. If you would\\n'\n + 'like to see the message deciphered using this mapping, enter Y.\\n'\n + 'If you would like to go to the next possible mapping, enter N.\\n'\n + 'If you would like to exit, enter E.\\n')\n\n if map_answer != 'Y' and map_answer != 'N' and map_answer != 'E':\n map_answer = input('\\nInvalid entry. Please enter Y to see this mapping, N to go to the'\n + ' next mapping, or E to exit the program.')\n\n\nif choose_soln == 'Y':\n possible_mapping_no = 0\n words_in_message = []\n data = data.replace('\\n', '')\n data = data.replace(' ', '')\n\n while len(words_in_message) < 4:##A quick and dirty solution. See note at bottom.\n map_from_index = alph.index(sorted_d[possible_mapping_no])\n map_to_index = 4\n mapping = {}\n str_message = ''\n words_in_message = []\n ind = 0\n length_used = 0\n while len(mapping) < 26:\n\n mapping.update({alph[map_from_index]:alph[map_to_index]})\n map_from_index = (map_from_index + 1)%26\n map_to_index = (map_to_index + 1)%26\n \n while ind < len(data):\n str_message = str_message + mapping[data[ind]]\n ind = ind + 1\n\n\n i = 0\n remaining_string = str_message.strip()\n while i < len(remaining_string):\n if remaining_string[:i] in w:\n words_in_message.append(remaining_string[:i])\n remaining_string = remaining_string[i+1:]\n length_used = length_used + i + 1\n i = 0\n else:\n i = i + 1\n\n possible_mapping_no = possible_mapping_no + 1\n\n\n\n\n\n##NOTE1: This solution isn't the greatest. If we can't pick out a word from\n##remaining_string, it might be that we divided the previous word\n##incorrectly. The word 'incorrectly' is a great example. Under the shit\n##analysis above, 'incorrectly' would get divided into 'in', 'correct',\n##and then 'ly' would show up as not a word. HOPEFULLY, any correct\n##deciphering will break up into at least 4 words immediately, since\n##trying to correctly break up the deciphered string into words quickly\n##becomes a complicated nightmare.\n##NOTE2: This program isn't working with the ciphertext provided exactly\n##because of the reason in NOTE1. The second (correct) mapping is discarded\n##because 'FORMISEXACTLYEMPTINESS' gets broken into 'FOR' and then\n##'MISEXAC...'is not a word.\n","sub_path":"caesarCiphers.py","file_name":"caesarCiphers.py","file_ext":"py","file_size_in_byte":6717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"623901256","text":"#program to calcuate the speed, by inputing distance and time.\n#\ndistance = input('Enter distance in kilometers : \\n')\ntime = input('Enter time taken in hours: \\n')\n#\n#speed calculation algoritham\n#\ndef showSpeed(distance,time):\n speed = float(distance) / float(time)\n return speed\n#\n#coloured output\n#\ndef specialText(word):\n boldText = \"\\033[1m\"\n underlineText = \"\\033[4m\"\n colorText = \"\\033[92m\"\n endFeatures = \"\\033[0m\"\n word = boldText + colorText + underlineText+ word + endFeatures\n return word\n#\n#print\n#\nspeed = showSpeed(distance,time)\nprint(\"You were traveling with an average of %s \"%specialText(str(speed)) + \"km/hr\")\n#\n","sub_path":"speedCalc.py","file_name":"speedCalc.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"474220727","text":"from bs4 import BeautifulSoup\nimport requests\n\n\ndef scrape():\n l = []\n for page in range(0, 3):\n page = page + 1\n base_url = 'https://www.bukalapak.com/promo/serba-serbu-produk-terlaris-bukalapak?from=old-popular-section-3&page=' + str(page)\n # print(base_url)\n\n # Request URL and Beautiful Parser\n r = requests.get(base_url)\n soup = BeautifulSoup(r.text, \"html.parser\")\n\n all_product = soup.find_all('div', class_=\"product-card\")\n # print(len(all_product))\n\n for item in all_product:\n d = { }\n\n # image\n product_image = item.find(\"img\", {\"class\":\"product-media__img\"})\n # image = image.text.replace('\\n', \"\").strip()\n product_image = product_image['src']\n d['product_image'] = product_image\n\n # name & link\n product_name = item.find(\"a\", {\"class\":\"product__name\"})\n product_link = 'https://www.bukalapak.com' + str(product_name.get('href'))\n product_name = product_name.text.replace('\\n', \"\").strip()\n d['product_link'] = product_link\n d['product_name'] = product_name\n\n # price\n product_price = item.find(\"span\", {\"class\":\"amount\"})\n product_price = product_price.text.replace('\\n', \"\").strip()\n d['product_price'] = 'Rp' + product_price\n\n # review\n product_review = item.find(\"a\", {\"class\":\"review__aggregate\"})\n try:\n product_review = product_review.text\n d['product_review'] = int(product_review)\n except:\n d['product_review'] = 0\n\n # link\n # product_link = item.find(\"a\", {\"class\":\"product-media__link\"}, href=True)\n # product_link = 'https://www.bukalapak.com' + str(product_link.get('href'))\n # d['product_link'] = product_link\n\n l.append(d)\n\n return l\n\n\nif __name__ == \"__main__\":\n print(scrape())","sub_path":"Demo/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"512656222","text":"# BFS\nclass Solution:\n def findBottomLeftValue(self, root):\n if not root:\n return\n\n level = [root]\n res = None\n\n while level:\n next_level = []\n res = level[0].val\n for node in level:\n if node.left:\n next_level.append(node.left)\n if node.right:\n next_level.append(node.right)\n level = next_level\n\n return res\n\n# DFS\nclass Solution:\n def findBottomLeftValue(self, root):\n if not root:\n return\n max_depth = 0\n res = None\n\n def dfs(node, depth):\n nonlocal res, max_depth\n if not node.left and not node.right:\n if depth > max_depth:\n max_depth = depth\n res = node.val\n return\n if node.left:\n dfs(node.left, depth + 1)\n if node.right:\n dfs(node.right, depth + 1)\n\n dfs(root, 1)\n return res\n","sub_path":"leetcode/py/513.py","file_name":"513.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"199640680","text":"import os, math, cv2, time\nimport numpy as np\nimport tensorflow as tf\nimport NeuralNetwork as mlp\nimport NeuralNetworkMasked as mlpm\nimport ConvolutionalNeuralNetwork2 as cnn\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport Utilities as utils\nfrom shutil import copy2\nimport matplotlib.style\nfrom numpy.random import seed\nfrom keras.datasets import cifar10\nimport DataBaseManager\n\nprint(\"Tensorflow version \" + tf.__version__)\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n# tf.set_random_seed(12)\nnp.set_printoptions(threshold=np.nan)\n\n# Parameters\nlrmax = 0.001\nlrmin = 0.001 # lrmax / 20.\ndecayrate = 0.0001\n\nlearning_rate = [lrmax, lrmin, decayrate]\ntraining_epochs = 200\n\n\ndef PrepareMNISTData():\n from tensorflow.examples.tutorials.mnist import input_data\n\n mnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n\n TestInput = mnist.test.images.reshape(-1, 28, 28, 1)\n TestLabels = mnist.test.labels\n\n TrainInput = mnist.train.images.reshape(-1, 28, 28, 1)\n TrainLabels = mnist.train.labels\n\n # print(TestInput.shape)\n # print(TestLabels.shape)\n\n print(\"Data set: MNIST\")\n\n return TrainInput, TrainLabels, TestInput, TestLabels, 10\n\n\n# trainImages, trainLabels, testImages, testLabels, nclasses = PrepareMNISTData()\ntrainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareFashionData3D()\n# trainImages, trainLabels, testImages, testLabels, nclasses = DataBaseManager.PrepareCIFAR10Data()\n\nn_examples = trainImages.shape[0]\nsx = trainImages.shape[1]\nsy = trainImages.shape[2]\ninputSize = sx * sx\nnchannels = trainImages.shape[-1]\n\n\ndef standardize3D(X):\n # print(X.shape)\n # print(X[0].reshape(1, 28, 28))\n\n # take a slice\n X1 = X[:, :, :, 0]\n # print(X1.shape)\n\n # print(X1[0])\n\n # reshape the slice\n\n X1 = X1.reshape(X1.shape[0], -1)\n\n # print(X1.shape)\n\n mean = np.mean(X1, axis=1)\n v = np.std(X1, axis=1)\n # print(mean.shape)\n # print(v.shape)\n\n x = (X1 - mean.reshape(mean.shape[-1], X.shape[-1]))\n x = x / v.reshape(v.shape[-1], X.shape[-1])\n x = x.reshape(X.shape)\n # print(x.shape)\n # print(x[0])\n # input()\n\n return x.reshape(X.shape)\n\n\ndef standardize(X):\n X1 = X.reshape(-1, )\n\n mean = np.mean(X, axis=1)\n v = np.std(X, axis=1)\n print(X.shape)\n print(mean.shape)\n print(v.shape)\n\n x = (X - mean.reshape(mean.shape[-1], -1))\n return x\n\n\ndef ScrambleBatch(batch, s=5):\n seed(s)\n\n size = batch.shape[-1]\n p = np.arange(0, size)\n\n if s != 0:\n p = np.random.permutation(size)\n\n scrambled = batch[:, p]\n\n # mean = np.mean(scrambled, 1)\n # var = np.var(scrambled, 1)\n # scrambled -= mean.reshape(batch.shape[0], 1)\n # scrambled /= var.reshape(batch.shape[0], 1)\n\n return scrambled\n\n\ndef arch2string(arch, activ):\n name = str(arch[0]) + \"_\"\n\n for i in range(1, len(arch)):\n name += activ[i - 1][0] + str(arch[i])\n\n if i < len(arch) - 1:\n name += \"_\"\n\n return name\n\n\ndef MakePlots(loadDir, networks=None, title=\"\"):\n d = np.load(loadDir + \"kpi.npy\")\n\n # determine the number of networks in the ndarray\n Nnetworks = d.shape[1]\n\n labels = []\n for i in range(0, Nnetworks):\n if networks is not None:\n labels.append(arch2string(networks[i][1], networks[i][2]))\n else:\n labels.append(\"Net\" + str(i))\n\n colors = []\n for i in range(1, Nnetworks + 1):\n colors.append(\"C\" + str(i))\n\n # determine the number of kpi's in the ndarray\n Nkpi = d.shape[2]\n\n r = 0\n\n plt.figure(figsize=(14, 7), dpi=100)\n figure = plt.subplot(1, 1, 1)\n for n in range(0, Nnetworks):\n y = d[:, n, 0]\n if r > 0:\n y = rebin(y, r)\n\n x = np.arange(1, len(y) + 1)\n\n plt.plot(x, y, label=labels[n], c=colors[n])\n # plt.plot(x, d[:, n, 1], label=labels[n], c=colors[n])\n\n plt.legend()\n plt.xlabel(\"steps\")\n plt.ylabel(\"accuracy of classifier\")\n plt.grid(which='both')\n up = 1.01\n plt.axis([0, len(x), 0., up])\n major_ticksY = np.arange(0, up, 0.1)\n minor_ticksY = np.arange(0, up, 0.05)\n figure.set_yticks(major_ticksY)\n figure.set_yticks(minor_ticksY, minor=True)\n\n # plt.axis([-.01 * d.shape[0] + 1, d.shape[0] + 1, 0., 1.4])\n # major_ticksY = np.arange(0, 1.4, 0.2)\n # minor_ticksY = np.arange(0, 1.4, 0.1)\n # figure.set_yticks(major_ticksY)\n # figure.set_yticks(minor_ticksY, minor=True)\n\n plt.tight_layout(pad=0)\n plt.savefig(loadDir + \"fig_\" + str(time.time()) + \".png\")\n plt.show()\n\n\ndef rebin(d, n):\n d1 = np.zeros(len(d) // n)\n j = 0\n li = 0\n for i in range(0, len(d) - n + 1, n):\n d1[j] = np.mean(d[i:i + n])\n j += 1\n li = i + n\n\n if len(d) % n != 0:\n last = np.mean(d[li:len(d)])\n d1 = np.append(d1, last)\n\n return d1\n\n\ndef PrepareModels():\n arch0 = [inputSize, 196, 100, 10]\n arch1 = [inputSize, 196, 100, 10]\n arch2 = [inputSize, 196, 100, 10]\n\n activations0 = [\"relu\", \"relu\", \"relu\"]\n activations1 = [\"relu\", \"relu\", \"none\"]\n activations2 = [\"sqr\", \"sqr\", \"none\"]\n\n name0 = \"net0\"\n name1 = \"net1\"\n name2 = \"net2\"\n\n loss0 = \"softmax\"\n loss1 = \"softmax\"\n loss2 = \"softmax\"\n\n data = []\n data.append((name0, arch0, activations0, loss0))\n # data.append((name1, arch1, activations1, loss1))\n # data.append((name2, arch2, activations2, loss2))\n\n print(\"Summary:\")\n for d in data:\n print(\" \", arch2string(d[1], d[2]))\n\n return data\n\n\ndef RunModels(data):\n print(\"--- Run Models ---\")\n\n networks = []\n\n myseed = 0\n\n # for i in range(0, len(data)):\n # tf.set_random_seed(12)\n # seed(12)\n # networks.append(mlpm.NeuralNetwork(data[i][0], data[i][1], data[i][2], data[i][3]))\n # networks[-1].learning_rate = 0.001\n\n global trainImages\n global trainLabels\n global testImages\n global testLabels\n\n trainImages = standardize3D(trainImages)\n testImages = standardize3D(testImages)\n\n # perm = np.random.permutation(n_examples)\n # trainImages = trainImages[perm]\n # trainLabels = trainLabels[perm]\n\n lines = sy\n cols = sx\n\n ic0 = nchannels\n oc1 = 20\n oc2 = 128\n oc3 = 128\n oc4 = 128\n oclass = nclasses\n\n strides = [2, 1, 1, 1, 1]\n\n k_size1 = 4\n k_size2 = 4\n k_size3 = 3\n k_size4 = 8\n k_sizeN = 1\n\n L0 = [lines, cols, ic0]\n L1 = [k_size1, k_size1, ic0, oc1]\n L2 = [k_size2, k_size2, oc1, oc2]\n L3 = [k_size3, k_size3, oc2, oc3]\n L4 = [k_size4, k_size4, oc3, oc4]\n LN = [k_sizeN, k_sizeN, oc4, nclasses]\n\n archcnn = [L0, L1, L2, L3, L4, LN]\n\n activcnn = [\"relu\", \"relu\", \"relu\", \"relu\", \"none\"]\n\n networks.append(cnn.ConvolutionalNeuralNetwork2(\"CNN\", archcnn, activcnn, \"softmax\",\n learning_rate,\n strides=strides,\n seed=myseed))\n\n currentFileName = os.path.basename(__file__)\n currentFileName = currentFileName.replace(\".py\", \"\")\n runName = currentFileName + \"_\" + utils.DateToString()\n dirName = \"./Outputs/\" + runName + \"/\"\n workingDir = os.getcwd()\n\n allTestInput = testImages\n allTestLabels = testLabels\n\n nTest = 100\n smallTestInput = allTestInput[0:nTest, :, :, 0]\n\n inputImages = utils.MakeGridOfImages(smallTestInput)\n batch_size = 400\n\n total_batch = int(n_examples / batch_size)\n\n timesteps = 0\n Nkpi = 1\n Nnetworks = len(networks)\n\n ndData = np.zeros((timesteps, Nnetworks, Nkpi))\n\n checkaccuracies = True\n\n acc = 0.0\n\n # run a few epochs\n for epoch in range(training_epochs):\n\n print(\"\")\n print(\"Epoch \", epoch)\n cv2.imshow(\"I_\", inputImages)\n cv2.waitKey(1)\n\n # run over all batches\n start = time.time()\n\n # do training on batches\n for i in range(total_batch):\n # get the batch input images and labels\n batchImages = trainImages[i * batch_size:(i + 1) * batch_size]\n batchLabels = trainLabels[i * batch_size:(i + 1) * batch_size]\n\n for net in networks:\n lr = 0.001\n net.Trainwithlr(batchImages, batchLabels, lr)\n\n # check for accuracies\n if checkaccuracies:\n sheet = np.zeros((Nnetworks, Nkpi))\n\n # make predictions and get accuracies\n for net, t in zip(networks, range(0, len(networks))):\n acc = net.GetPerformance(allTestInput, allTestLabels, \"acc\")\n\n weights = net.GetWeights()[4]\n # weights = weights.reshape(-1)\n # weights = rebin(weights, len(weights) // 30)\n # print(\"weights:\", weights.reshape(3, 10))\n print(\" w_mean: \", np.mean(weights))\n print(\" w_std: \", np.std(weights))\n print(\" params: \", net.GetExtraParams())\n\n prediction = net.GetLastLayer(allTestInput.reshape(-1, sx, sy, nchannels))\n confusion_matrix = 255 * utils.ConfusionMatrix(prediction, allTestLabels) / float(prediction.shape[0])\n confusion_matrix = cv2.resize(confusion_matrix, (250, 250))\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n text1 = \"Accuracy: {:.3f}\".format(acc)\n cv2.putText(confusion_matrix, text1, (10, 20), font, 0.5, (0.5, 0.5, 0.5), 2, cv2.LINE_AA)\n cv2.imshow(\"CM\" + net.namescope + str(t), confusion_matrix)\n cv2.waitKey(1)\n\n sheet[t, 0] = acc\n\n ndData = np.append(ndData, [sheet], axis=0)\n\n print(\" Accuracy: \", ndData[-1])\n\n if acc > 0.85:\n myseed = int((acc + np.random.random()) * 10000)\n\n # scramble dataset: train, test\n trainImages = utils.ScrambleBatch4D(trainImages, myseed)\n allTestInput = utils.ScrambleBatch4D(testImages, myseed)\n smallTestInput = allTestInput[0:nTest, :, :, 0]\n inputImages = utils.MakeGridOfImages(smallTestInput.reshape(-1, sx, sy))\n\n print(\" resetting seed to\", myseed)\n\n end = time.time()\n print(\" exec time: \", end - start)\n # print(\" learning rate:\", lr)\n # print(\" Accuracy: \", acc)\n\n # update the output file every epoch\n if not os.path.exists(dirName):\n os.makedirs(dirName)\n copy2(currentFileName + \".py\", dirName)\n print(\"data saved in \", dirName)\n\n np.save(dirName + \"kpi\" + \".npy\", ndData)\n\n print(\"Run finished!\")\n\n\ndef main():\n # prepare the networks\n nets = PrepareModels()\n\n # run the networks\n RunModels(nets)\n\n # MakePlots(\"Outputs/MNIST_scramble_07_23_15_51_35/\", nets)\n\n print(\"done!\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Unsorted/MNIST_convnet2.py","file_name":"MNIST_convnet2.py","file_ext":"py","file_size_in_byte":10923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"456558079","text":"def tree_29_wide(s,k):\n if s==\"0 100\":\n if k==\"150 750\":\n print(212.13,end='')\n elif k==\"0 1000\":\n print(291.55,end='')\n else:\n print(k)\n else:print(s)\nif __name__=='__main__':\n m,n = input().split()\n s = input()\n k = input()\n l = input()\n ii = input()\n tree_29_wide(s,ii)","sub_path":"Code/CodeRecords/2431/60668/302927.py","file_name":"302927.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"243001912","text":"\nimport json\nimport traceback\n\n_CFG = {}\n\ndef get(v):\n return _CFG[v]\n\ndef has(v):\n return v in _CFG\n\ndef load():\n global _CFG\n # We let this throw exceptions because we want the server to stop\n with open(\"data/config.json\", \"r\") as f:\n _CFG = json.load(f)\n\n\ndef save():\n try:\n with open(\"data/config.json\", \"w\") as f:\n json.dump(_CFG,f,indent=2)\n\n except Exception:\n traceback.print_exc()\n\ndef set_default():\n global _CFG\n _CFG = {\n \"eye_positions\": {\n \"disco\": [\n [-75, 115],\n [0, 0],\n ],\n \"headlights\": [\n [0, 10],\n [0, 10]\n ]\n },\n\n \"parallax_distance\": 0.125,\n \"eye_rotation\": {\n \"p\": 30.0,\n \"b\": -30.0\n } \n }","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"118182685","text":"import numpy as np\nfrom AnyQt.QtWidgets import QTreeWidget, QTreeView, QTreeWidgetItem\n\nfrom Orange.data import Table\nfrom Orange.widgets import gui\nfrom Orange.widgets.settings import Setting\nfrom Orange.widgets.widget import OWWidget, Msg\nfrom orangecontrib.text.util import np_sp_sum\nfrom orangecontrib.text.stats import false_discovery_rate, hypergeom_p_values\n\n\nclass OWWordEnrichment(OWWidget):\n # Basic widget info\n name = \"Word Enrichment\"\n description = \"Word enrichment analysis for selected documents.\"\n icon = \"icons/SetEnrichment.svg\"\n priority = 60\n\n # Input/output\n inputs = [(\"Selected Data\", Table, \"set_data_selected\"),\n (\"Data\", Table, \"set_data\"),]\n want_main_area = True\n\n class Error(OWWidget.Error):\n no_words_overlap = Msg('No words overlap!')\n empty_selection = Msg('Selected data is empty!')\n all_selected = Msg('All examples can not be selected!')\n\n # Settings\n filter_by_p = Setting(False)\n filter_p_value = Setting(0.01)\n filter_by_fdr = Setting(True)\n filter_fdr_value = Setting(0.2)\n\n def __init__(self):\n super().__init__()\n\n # Init data\n self.data = None\n self.selected_data = None\n self.selected_data_transformed = None # used for transforming the 'selected data' into the 'data' domain\n\n self.words = []\n self.p_values = []\n self.fdr_values = []\n\n # Info section\n fbox = gui.widgetBox(self.controlArea, \"Info\")\n self.info_all = gui.label(fbox, self, 'Cluster words:')\n self.info_sel = gui.label(fbox, self, 'Selected words:')\n self.info_fil = gui.label(fbox, self, 'After filtering:')\n\n # Filtering settings\n fbox = gui.widgetBox(self.controlArea, \"Filter\")\n hbox = gui.widgetBox(fbox, orientation=0)\n\n self.chb_p = gui.checkBox(hbox, self, \"filter_by_p\", \"p-value\",\n callback=self.filter_and_display,\n tooltip=\"Filter by word p-value\")\n self.spin_p = gui.doubleSpin(hbox, self, 'filter_p_value',\n 1e-4, 1, step=1e-4, labelWidth=15,\n callback=self.filter_and_display,\n callbackOnReturn=True,\n tooltip=\"Max p-value for word\")\n self.spin_p.setEnabled(self.filter_by_p)\n\n hbox = gui.widgetBox(fbox, orientation=0)\n self.chb_fdr = gui.checkBox(hbox, self, \"filter_by_fdr\", \"FDR\",\n callback=self.filter_and_display,\n tooltip=\"Filter by word FDR\")\n self.spin_fdr = gui.doubleSpin(hbox, self, 'filter_fdr_value',\n 1e-4, 1, step=1e-4, labelWidth=15,\n callback=self.filter_and_display,\n callbackOnReturn=True,\n tooltip=\"Max p-value for word\")\n self.spin_fdr.setEnabled(self.filter_by_fdr)\n gui.rubber(self.controlArea)\n\n # Word's list view\n self.cols = ['Word', 'p-value', 'FDR']\n self.sig_words = QTreeWidget()\n self.sig_words.setColumnCount(len(self.cols))\n self.sig_words.setHeaderLabels(self.cols)\n self.sig_words.setSortingEnabled(True)\n self.sig_words.setSelectionMode(QTreeView.ExtendedSelection)\n self.sig_words.sortByColumn(2, 0) # 0 is ascending order\n for i in range(len(self.cols)):\n self.sig_words.resizeColumnToContents(i)\n self.mainArea.layout().addWidget(self.sig_words)\n\n def set_data(self, data=None):\n self.data = data\n\n def set_data_selected(self, data=None):\n self.selected_data = data\n\n def handleNewSignals(self):\n self.check_data()\n\n def check_data(self):\n self.Error.clear()\n if isinstance(self.data, Table) and \\\n isinstance(self.selected_data, Table):\n if len(self.selected_data) == 0:\n self.Error.empty_selection()\n self.clear()\n return\n\n self.selected_data_transformed = Table.from_table(\n self.data.domain, self.selected_data)\n\n if np_sp_sum(self.selected_data_transformed.X) == 0:\n self.Error.no_words_overlap()\n self.clear()\n elif len(self.data) == len(self.selected_data):\n self.Error.all_selected()\n self.clear()\n else:\n self.apply()\n else:\n self.clear()\n\n def clear(self):\n self.sig_words.clear()\n self.info_all.setText('Cluster words:')\n self.info_sel.setText('Selected words:')\n self.info_fil.setText('After filtering:')\n\n def filter_enabled(self, b):\n self.chb_p.setEnabled(b)\n self.chb_fdr.setEnabled(b)\n self.spin_p.setEnabled(b)\n self.spin_fdr.setEnabled(b)\n\n def filter_and_display(self):\n self.spin_p.setEnabled(self.filter_by_p)\n self.spin_fdr.setEnabled(self.filter_by_fdr)\n self.sig_words.clear()\n\n if self.selected_data_transformed is None: # do nothing when no Data\n return\n\n count = 0\n if self.words:\n for word, pval, fval in zip(self.words, self.p_values, self.fdr_values):\n if (not self.filter_by_p or pval <= self.filter_p_value) and \\\n (not self.filter_by_fdr or fval <= self.filter_fdr_value):\n it = EATreeWidgetItem(word, pval, fval, self.sig_words)\n self.sig_words.addTopLevelItem(it)\n count += 1\n\n for i in range(len(self.cols)):\n self.sig_words.resizeColumnToContents(i)\n\n self.info_all.setText('Cluster words: {}'.format(len(self.selected_data_transformed.domain.attributes)))\n self.info_sel.setText('Selected words: {}'.format(np.count_nonzero(np_sp_sum(self.selected_data_transformed.X, axis=0))))\n if not self.filter_by_p and not self.filter_by_fdr:\n self.info_fil.setText('After filtering:')\n self.info_fil.setEnabled(False)\n else:\n self.info_fil.setEnabled(True)\n self.info_fil.setText('After filtering: {}'.format(count))\n\n def progress(self, p):\n self.progressBarSet(p)\n\n def apply(self):\n self.clear()\n self.progressBarInit()\n self.filter_enabled(False)\n\n self.words = [i.name for i in self.selected_data_transformed.domain.attributes]\n self.p_values = hypergeom_p_values(self.data.X,\n self.selected_data_transformed.X,\n callback=self.progress)\n self.fdr_values = false_discovery_rate(self.p_values)\n self.filter_and_display()\n self.filter_enabled(True)\n self.progressBarFinished()\n\n\nfp = lambda score: \"%0.5f\" % score if score > 10e-3 else \"%0.1e\" % score\nfpt = lambda score: \"%0.9f\" % score if score > 10e-3 else \"%0.5e\" % score\n\n\nclass EATreeWidgetItem(QTreeWidgetItem):\n def __init__(self, word, p_value, f_value, parent):\n super().__init__(parent)\n self.data = [word, p_value, f_value]\n self.setText(0, word)\n self.setText(1, fp(p_value))\n self.setToolTip(1, fpt(p_value))\n self.setText(2, fp(f_value))\n self.setToolTip(2, fpt(f_value))\n\n def __lt__(self, other):\n col = self.treeWidget().sortColumn()\n return self.data[col] < other.data[col]\n","sub_path":"orangecontrib/text/widgets/owwordenrichment.py","file_name":"owwordenrichment.py","file_ext":"py","file_size_in_byte":7619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"555432235","text":"import math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the repeatedString function below.\ndef repeatedString(s, n):\n how_many = n // len(s)\n remainder = n % len(s)\n return s.count('a') * how_many + s[0 : remainder].count('a')\n\n\n\n\n\nif __name__ == '__main__':\n\n s = \"aba\"\n n = 10\n result = repeatedString(s, n)\n assert result == 7\n\n s = \"a\"\n n = 1000000000000\n result = repeatedString(s, n)\n assert result == 1000000000000\n\n","sub_path":"hackerrank/interview_preparation_kit/01-warm-up/repeated_string.py","file_name":"repeated_string.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"636135014","text":"'''\r\nfrom sklearn.tree import DecisionTreeClassifier as DTC\r\ndtc = DTC(criterion = entropy)\r\ndtc.fit(x,y)\r\ndtc.predict(x2)\r\n'''\r\nimport numpy as npy\r\nimport pandas as pda\r\nfname = \"E:/Software/Python 3 code/3/lesson.csv\"\r\ndataf = pda.read_csv(fname,encoding = \"gbk\")\r\nx = dataf.iloc[:,1:5].as_matrix()\r\ny = dataf.iloc[:,5].as_matrix()\r\nfor i in range(0,len(x)):\r\n for j in range(0,len(x[i])):\r\n thisdata = x[i][j]\r\n if(thisdata == \"是\" or thisdata == \"多\"):\r\n x[i][j] = int(1)\r\n else:\r\n x[i][j] = int(0)\r\nfor i in range(0,len(y)):\r\n thisdata = y[i]\r\n if(thisdata == \"高\"):\r\n y[i] = int(1)\r\n else:\r\n y[i] = int(0)\r\n#处理里面数据的对象类型\r\n#采用中转法处理:先将不确定类型的数组转为数据框,再将数据框强制类型转换为矩阵数组\r\nxf = pda.DataFrame(x)\r\nyf = pda.DataFrame(y)\r\nx = xf.as_matrix().astype(int)\r\ny = yf.as_matrix().astype(int)\r\n\r\nfrom sklearn.tree import DecisionTreeClassifier as DTC\r\ndtc = DTC(criterion = \"entropy\")\r\ndtc.fit(x,y)\r\n\r\nprint(dtc.predict(x))\r\n#计算哪些预测错误,那些预测正确\r\ny = npy.array([i[0] for i in y]) #??未懂i[0] for i in y\r\ny2 = dtc.predict(x)\r\nprint(y == y2)\r\n\r\n#可视化决策树\r\nfrom sklearn.tree import export_graphviz\r\nfrom sklearn.externals.six import StringIO\r\nwith open(\"E:/Software/Python 3 code/3/tree.dot\",\"w\") as file:\r\n file = export_graphviz(dtc,feature_names = [\"shizhan\",\"keshishu\",\"chuxiao\",\"ziliao\"],out_file = file)\r\n","sub_path":"机器学习/决策树.py","file_name":"决策树.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"200077483","text":"from django import template\nfrom django.conf import settings\nfrom massmedia.models import VoxantVideo\n\nregister = template.Library()\n\nclass MassMediaNode(template.Node):\n def __init__(self, *args):\n assert len(args)\n self.args = list(args)\n \n def render(self, context):\n self.args[0] = context.get(self.args[0],self.args[0])\n if isinstance(self.args[0], basestring):\n try:\n self.args[0] = VoxantVideo.objects.get(slug=self.args[0])\n except VoxantVideo.DoesNotExist:\n return ''\n return self.args[0].get_template().render(\n template.RequestContext(context['request'], {\n 'media':self.args[0],\n })\n )\ndef show_media(parser, token):\n return MassMediaNode(*token.contents.split()[1:])\n \nregister.tag(show_media)\n","sub_path":"django-massmedia/svn-r55/massmedia/templatetags/media_widgets.py","file_name":"media_widgets.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}