Exemplo n.º 1
0
def login_post():
    # request parsing as json
    email = request.form.get('email')
    password = request.form.get('password')
    remember = True if request.form.get('remember') else False

    current_app.logger.info("Login action called")

    try:
          user = rpc.user_service.getUserByEmailAndPassword(email,password)
          current_app.logger.info("user fetched from UserService: ",user)
          userLoaded = User(user_dict=user)
          #print(userLoaded.user_dict)
          if user:
             login_user(userLoaded, remember=remember)
             session.permanent = True
          else:
               return ApiResponse(result=AuthenticationErrors.LoginFailureError.get('message'),
                         status=AuthenticationErrors.LoginFailureError.get('status'),
                        error=nameof(AuthenticationErrors.LoginFailureError))

            # return redirect(url_for('auth.signup'))

    except UserNotFoundException:
              return ApiResponse(result=AuthenticationErrors.UserNotFoundError.get('message'),
                       status=AuthenticationErrors.UserNotFoundError.get('status'),
                         error=nameof(AuthenticationErrors.UserNotFoundError))
    except UserServiceException as ex:
         return ApiResponse(result=GeneralErrors.InternalServerError.get('message'+ex.msg),
                               status=GeneralErrors.InternalServerError.get('status'),
                               error=ex.errors)
    except Exception as ex:
            return returnErrorResponse(ex)

    return ApiResponse(status=200, result="You have been logged in")
Exemplo n.º 2
0
def test_nameof_statements():
    a = {'test': 1}
    test = {}
    del a[nameof(test)]
    assert a == {}

    def func():
        return nameof(test)

    assert func() == 'test'

    def func2():
        yield nameof(test)

    assert list(func2()) == ['test']

    def func3():
        raise ValueError(nameof(test))

    with pytest.raises(ValueError) as verr:
        func3()
    assert str(verr.value) == 'test'

    for i in [0]:
        assert nameof(test) == 'test'
        assert len(nameof(test)) == 4
Exemplo n.º 3
0
def test_nameof_expr():
    test = {}
    assert len(varname_module.nameof(test)) == 4

    lam = lambda: 0
    lam.a = 1
    with pytest.raises(VarnameRetrievingError) as vrerr:
        varname_module.nameof(test, lam.a)
    assert str(vrerr.value) == ("Only variables should "
                                "be passed to nameof.")
Exemplo n.º 4
0
def test_nameof():
    a = 1
    b = nameof(a)
    assert b == 'a'
    nameof2 = nameof
    c = nameof2(a, b)
    assert b == 'a'
    assert c == ('a', 'b')

    def func():
        return varname() + 'abc'

    f = func()
    assert f == 'fabc'

    assert nameof(f) == 'f'
    assert 'f' == nameof(f)
    assert len(nameof(f)) == 1

    fname1 = fname = nameof(f)
    assert fname1 == fname == 'f'

    with pytest.raises(VarnameRetrievingError):
        nameof(a == 1)

    with pytest.raises(VarnameRetrievingError):
        nameof()
Exemplo n.º 5
0
def export_info(df):
    strfile = '../data/' + str(nameof(df)) + '_info.txt'
    buffer = io.StringIO()
    df.info(buf=buffer)
    info = buffer.getvalue()
    with open(strfile, "a", encoding="utf-8") as f: 
        f.write(info)
        f.close
    strfile = str(nameof(df)) + '_desc.csv'
    print(df.describe().to_csv(strfile))
    strfile = str(nameof(df)) + '_freq.csv'
    df.to_csv(strfile)
Exemplo n.º 6
0
    async def insert_network_entity(self, _id, elem):
        ne_dict = asdict(elem)

        # Prepare dict for upsert
        del ne_dict[nameof(elem.parent)]
        del ne_dict[nameof(elem.port)]
        del ne_dict[nameof(elem.category)]
        del ne_dict[nameof(elem._id)]

        # Infers collection name
        c = self.collection_map[type(elem)]

        # Data to insert
        categories = [elem.category]
        ports = [elem.port]

        # Forms query, if IP address is present
        if elem.ip:
            query = {'ip': elem.ip}

        # Forms query, if there is only a hostname
        else:
            query = {'hostname': elem.hostname}

        # Define insertion
        insertion = {
            '$set': ne_dict,
            '$push': {
                'parents': asdict(elem.parent),
            },
            '$addToSet': {  # do not add duplicates
                'category': {
                    '$each': categories
                },
                'port': {
                    '$each': ports
                }
            }
        }

        # Upsert -> modify existing, ReturnDocument.AFTER is necessary to retrieve ObjectID for net yet existing doc
        update_result = await self.db[c.value].find_one_and_update(
            query,
            insertion,
            upsert=True,
            return_document=ReturnDocument.AFTER)
        _id = update_result['_id']

        return _id
Exemplo n.º 7
0
def signup_post():
    try:
        user,errors = userSchema.load(request.get_json())
        if errors:
            raise (ValidationFailException(errors,"Validation Failed"))

        user = rpc.user_service.getUserByEmail(user['email'])

        if user:  # if a user is found, we want to redirect back to signup page so user can try again
            return ApiResponse(result=AuthenticationErrors.UserAlreadyExistsError.get('message'),
                               status=AuthenticationErrors.UserAlreadyExistsError.get('status'),
                               error=nameof(AuthenticationErrors.UserAlreadyExistsError))
            # return redirect(url_for('auth.signup'))

    except UserNotFoundException:
                try:
                    print(user)
                    rpc.user_service.createUser(user)
                except Exception as ex:
                     return returnErrorResponse(ex)

    except ValidationFailException as ex:
                        return ApiResponse(result=GeneralErrors.ValidationError.get('message'),
                               status=GeneralErrors.ValidationError.get('status'),
                               error=ex.errors)
    except UserServiceException as ex:
         return ApiResponse(result=GeneralErrors.InternalServerError.get('message'+ex.msg),
                               status=GeneralErrors.InternalServerError.get('status'),
                               error=ex.errors)

    except Exception as ex:
            return returnErrorResponse(ex)

    return ApiResponse(status=200, result="Your account is created now")
Exemplo n.º 8
0
def process_features(datasets):
    """
    Parameters:
    1. datasets - an array of your datasets.
       eg: [yishun, changi, tuassouth]

    What this function does:
    1. Initially, the variables are in the first row of the dataframe. The column names is an np.arange().
       Hence, we set the variables (eg: Year, Mean Wind Speed, Minimum Temperature,...) as the index.
    2. We replace '—' and '-' with NumPy's NaN.
    3. Initially, the numeric features (eg: Temperature, Wind Speed,...) were strings.
       Hence, we change them into floats.

    """

    numeric_features = [
        'Year', 'Month', 'Day', 'Daily Rainfall Total (mm)',
        'Highest 30 min Rainfall (mm)', 'Highest 60 min Rainfall (mm)',
        'Highest 120 min Rainfall (mm)', 'Mean Temperature (°C)',
        'Maximum Temperature (°C)', 'Minimum Temperature (°C)',
        'Mean Wind Speed (km/h)', 'Max Wind Speed (km/h)'
    ]

    for dataset in datasets:
        dataset = dataset.reset_index().drop("index", axis=1)
        dataset.replace(['—', '-'], np.nan, inplace=True)
        dataset[numeric_features] = dataset[numeric_features].apply(
            pd.to_numeric)
        dataset.to_csv("{}.csv".format(nameof(dataset)))

    return
Exemplo n.º 9
0
async def btn_coroutine(device):
    async for event in device.async_read_loop():
        buttonEvent = rt_btn.ButtonEvent(event)

        if (buttonEvent.name, buttonEvent.value) == (rt_btn.ButtonName.F1, 1):
            pnp_client.f1Button.value = "click"
            await pnp_client.send_telemetry(nameof(pnp_client.f1Button))
        if (buttonEvent.name, buttonEvent.value) == (rt_btn.ButtonName.F2, 1):
            pnp_client.f2Button.value = "click"
            await pnp_client.send_telemetry(nameof(pnp_client.f2Button))
        if (buttonEvent.name, buttonEvent.value) == (rt_btn.ButtonName.F3, 1):
            pnp_client.f3Button.value = "click"
            await pnp_client.send_telemetry(nameof(pnp_client.f3Button))
        if (buttonEvent.name, buttonEvent.value) == (rt_btn.ButtonName.O, 1):
            pnp_client.oButton.value = "click"
            await pnp_client.send_telemetry(nameof(pnp_client.oButton))
Exemplo n.º 10
0
    async def revoke_indication(self, ctx, *players: discord.Member):
        contestant_names = load_variable(ctx.guild, 'contestant_names')
        for player in players:
            if player.display_name in contestant_names:
                contestant_names.remove(player.display_name)
            else:
                await ctx.send(f'```{player.display_name} is not indicated```')
        save_variable(ctx.guild, contestant_names, nameof(contestant_names))

        await ctx.send("```list updated```")
Exemplo n.º 11
0
    async def insert_url(self, _id, elem):
        url_dict = asdict(elem)

        # Prepare dict for upsert
        url_dict.pop(nameof(elem.parent))
        url_dict.pop(nameof(elem.extractions))
        url_dict.pop(nameof(elem._id))
        url_dict.pop(nameof(elem.exploits))

        # Prepare elements to append
        extractions = [asdict(e) for e in elem.extractions]
        exploits = elem.exploits

        # Retrieve collection name
        c = self.collection_map[type(elem)]

        # Forms query
        query = {'url': elem.url}

        # Define insertion
        insertion = {
            '$set': url_dict,
            '$push': {
                'parents': asdict(elem.parent),
            },
            '$addToSet': {  # do not add duplicates
                'exploits': {
                    '$each': exploits
                },
                'extractions': {
                    '$each': extractions
                }
            }
        }
        # Upsert -> modify existing, ReturnDocument.AFTER is necessary to retrieve ObjectID for net yet existing doc
        update_result = await self.db[c.value].find_one_and_update(
            query,
            insertion,
            upsert=True,
            return_document=ReturnDocument.AFTER)
        _id = update_result['_id']

        return _id
Exemplo n.º 12
0
def ctd_(sequence,
         property=ctd_properties[nameof(hydrophobicity)],
         all_ctd=True):
    """
    Calculate Composition, transition and distribution (CTD) features of protein sequences.
    Composition is the number of amino acids of a particular property (e.g., hydrophobicity)
    divided by the total number of amino acids in a protein sequence. Transition
    characterizes the percent frequency with which amino acids of a particular
    property is followed by amino acids of a different property. Distribution
    measures the chain length within which the first, 25%, 50%, 75%, and 100% of
    the amino acids of a particular property are located, respectively [6].
    CTD functionality in the PyBioMed package uses the properties:
    Polarizability, Solvent Accessibility, Secondary Structure, Charge,
    Polarity, Normalized VDWV, Hydrophobicity. The output will be of shape
    N x 147 where N is the number of protein sequences. 21/147 will be
    composition, 21/147 will be transition and the remaining 105 are distribution.

    Returns
    -------
    :ctd_df : pd.DataFrame
        dataframe of CTD descriptor values for all protein sequences. DataFrame will
        be of the shape N x 147, where N is the number of protein sequences and
        147 is the number of features calculated from the descriptors.
    """
    #check input sequence is a string, if not raise type error
    if not isinstance(sequence, str):
        raise TypeError(
            'Input sequence must be a string, got input of type {}'.format(
                type(sequence)))

    #initialise ctd dataframes
    comp_df = pd.DataFrame()
    trans_df = pd.DataFrame()
    distr_df = pd.DataFrame()

    #if using single property, calculate each of the CTD descriptors individually
    if not all_ctd:
        comp_df = ctd_composition(sequence, property=property)
        trans_df = ctd_transition(sequence, property=property)
        distr_df = ctd_distribution(sequence, property=property)
    else:
        #if using all calculable properties, calculate CTD descriptors for each property
        for prop in ctd_properties:
            comp = ctd_composition(sequence, property=ctd_properties[prop])
            comp_df = pd.concat([comp_df, comp], axis=1)
            trans = ctd_transition(sequence, property=ctd_properties[prop])
            trans_df = pd.concat([trans_df, trans], axis=1)
            distr = ctd_distribution(sequence, property=ctd_properties[prop])
            distr_df = pd.concat([distr_df, distr], axis=1)

    #concatenate all descriptors
    ctd = pd.concat([comp_df, trans_df, distr_df], axis=1)

    return ctd
Exemplo n.º 13
0
    async def insert_file(self, elem):
        _id = await self.insert_gridfs(elem.hash.sha256,
                                       elem.blob,
                                       metadata={"contentType": elem.encoding})
        elem.file_id = _id

        # Store file metadata in file collection
        file_dict = asdict(elem)

        # Removing unused fields
        del file_dict[nameof(elem.blob)]
        del file_dict[nameof(elem.encoding)]
        del file_dict[nameof(elem.parent)]
        del file_dict[nameof(elem.filename)]
        del file_dict[nameof(elem._id)]

        # Performs insertion (which is done by updating an eventually existing entry)
        c = self.collection_map[type(elem)]

        # Defines query
        query = {'hash': asdict(elem.hash)}

        # Updates file entry by appending filenames, parents and communicating hosts
        insertion = {
            '$set': file_dict,
            '$push': {
                'parents': asdict(elem.parent),
            },
            '$addToSet': {  # do not add duplicates
                'filename': elem.filename
            }
        }
        # Upsert -> modify existing, ReturnDocument.AFTER is necessary to retrieve ObjectID for net yet existing doc
        update_result = await self.db[c.value].find_one_and_update(
            query,
            insertion,
            upsert=True,
            return_document=ReturnDocument.AFTER)
        _id = update_result['_id']

        return _id
Exemplo n.º 14
0
def get_search(event):
    global buffer
    query = buffer[
        event.user_id] if buffer[event.user_id] != '' else event.text
    choise = random.randint(1, 2)
    if choise == 1:
        channel = HUMORESKI
        name = nameof(HUMORESKI)
    elif choise == 2:
        channel = ANEC_CATEGORY_B
        name = nameof(ANEC_CATEGORY_B)
    text, found_count = search_post(channel, query)
    print(query + text)
    vk_bot.messages.send(user_id=event.user_id, message=text, random_id=0)
    add_text = f'у {name} есть еще {found_count} анеков на эту тему....'
    vk_bot.messages.send(user_id=event.user_id,
                         message=add_text,
                         keyboard=set_buttons_reactions(no='ХВАТИТ',
                                                        yes='ЕЩЁ'),
                         random_id=0)
    buffer[event.user_id] = query
Exemplo n.º 15
0
async def send_telemetry_acceleration_loop():
    while True:
        if "x" in acceleration and "y" in acceleration and "z" in acceleration:
            print("Sending telemetry for acceleration.")
            pnp_client.acceleration.value = {
                "x": acceleration["x"],
                "y": acceleration["y"],
                "z": acceleration["z"],
            }
            await pnp_client.send_telemetry(nameof(pnp_client.acceleration))

        await asyncio.sleep(telemetry_interval)
Exemplo n.º 16
0
 async def indicate_player(self, ctx, *players: discord.Member):
     """Indicates a player or multiple player for the elimination contest"""
     try:
         contestant_names = load_variable(ctx.guild, 'contestant_names')
     except FileNotFoundError:
         contestant_names = []
     for player in players:
         if player.display_name in contestant_names:
             pass
         else:
             contestant_names.append(player.display_name)
     save_variable(ctx.guild, contestant_names, nameof(contestant_names))
     await ctx.send('Players set as contestants for elimination')
Exemplo n.º 17
0
 def comprobS(self, rest, rnum):
     cont_a = [0 for x in rest.cont]
     cont_b = [0 for x in rest.cont]
     for i in self.clases:
         for j in range(len(rest.cont)):
             if isinstance(rest.cont[j], varP):
                 aux = i.get_var(rest.cont[j].value)
                 cont_a[j] = aux(i)
                 cont_b[j] = nameof(cont_a) + "[" + str(j) + "]"
             else:
                 cont_b[j] = str(rest.cont[j])
         self.evalSoft[rnum] += eval(" ".join(cont_b))
     Estado.repet = []
Exemplo n.º 18
0
def connect(host=None, user=None, password=None, database=None):
    if not all(isinstance(i, str) for i in [host, user, password, database
                                            ]):  # Handle Argument Errors
        print("\n\n")
        for argumentname, argumentdata in zip(
            [nameof(host),
             nameof(user),
             nameof(password),
             nameof(database)], [host, user, password, database]):
            if not isinstance(argumentdata, str):
                print(
                    f"mySQEasyDB Syntax Error (2001, Connection Error): {argumentname} needs to be a string."
                )

    if debug:
        print(f"\n\nMaking connection to {user}@{host} in {database}..")

    try:
        global db
        db = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            database=database,
        )
        global cursor
        cursor = db.cursor(prepared=True)
        global selectionCursor
        selectionCursor = db.cursor(buffered=True)
    except mysql.connector.Error as error:
        if debug:
            print(
                f"\n\nmySQEasyDB mySQL Error: {error}\n\nEnsure you have entered the correct database information and your database is running.\n\n"
            )
        exit()
    else:
        if debug:
            print(f"Successfully connected to {db.database}!\n\n")
Exemplo n.º 19
0
 def test_nested_print(self):
     snarg = dict()
     snarg[100] = 300
     snarg["AA"] = "BB"
     piffle = dict()
     piffle[10] = 30
     piffle["A"] = "B"
     piffle["C"] = snarg
     blarvitz = dict()
     blarvitz[1] = 3
     blarvitz["a"] = "b"
     blarvitz["c"] = piffle
     assert (f.nested_print(nameof(blarvitz),
                            blarvitz)) == '''blarvitz[1] = 3
Exemplo n.º 20
0
 def comprobH(self, rest, rnum):
     cont_a = [0 for x in rest.cont]
     cont_b = [0 for x in rest.cont]
     for i in range(len(self.clases)):
         for j in range(len(rest.cont)):
             if isinstance(rest.cont[j], varP):
                 aux = self.clases[i].get_var(rest.cont[j].value)
                 cont_a[j] = aux(self.clases[i])
                 cont_b[j] = nameof(cont_a) + "[" + str(j) + "]"
             else:
                 cont_b[j] = str(rest.cont[j])
         if eval(" ".join(cont_b)):
             self.evalHard[rnum] -= rest.risk.value
             self.clasesOK[i] += 1
     Estado.repet = []
Exemplo n.º 21
0
    async def insert_generic(self, _id, elem):
        # Infers collection name
        c = self.collection_map[type(elem)]

        # Prepare dict to insert
        elem_dict = asdict(elem)

        # Removes _id, which is null until now and leads to DuplicateKeyError
        del elem_dict[nameof(elem._id)]

        # Inserts doc
        result = await self.db[c.value].insert_one(elem_dict)

        # Retrieves MongoDB-ID
        _id = result.inserted_id

        return _id
Exemplo n.º 22
0
def run(directory: str, priority: int) -> None:
    """
    The method for starting of the Service Uploader.

    """

    file_paths = []
    metadata = {}

    # забрать все пути к файлам из директории
    all_file_paths_in_directory = get_files_from_dir(directory)
    file_paths.extend(all_file_paths_in_directory)

    print(file_paths)

    # метаданные
    # сформировать словарь
    # прокинуть данные в json
    priority_key = nameof(priority)
    metadata[priority_key] = priority

    metadata_file_path = os.path.join(BUCKET, "metadata.txt")
    with open(metadata_file_path, 'w') as metadata_writer:
        json.dump(obj=metadata, fp=metadata_writer)
Exemplo n.º 23
0
def gen_tokens(
    text: Union[str, List[str]],
    label: str = "",
    lang: Optional[str] = None,
    gen_para: Union[int, bool] = False,
    gen_sent: Union[int, bool] = True,
    gen_phrase: Union[int, bool] = False,
) -> Iterator[Tuple[str, str, int, str]]:
    # fmt: on
    """Genereate tokens from text/list of text."""
    if isinstance(text, str):
        text = [elm.strip() for elm in text.splitlines() if elm.strip()]

    try:
        label = label.strip()
    except Exception:
        label = ""
    if not label.strip():
        label = nameof(text)

    if lang is None:
        lang = Detector(" ".join(text)).language.code
        logger.debug("Deteced lang: %s", lang)

    if gen_para:
        for idx, para in enumerate(text):
            yield para, label, idx + 1, 'para'
    if gen_sent:
        for idx, para in enumerate(text):
            for sent in _sent_tokenizer(para, lang):
                yield sent, label, idx + 1, 'sent'
    if gen_phrase:
        for idx, para in enumerate(text):
            for sent in _sent_tokenizer(para, lang):
                raise Exception("need to install phrase_tokenizer"
                                "which is dependant of benepar")
Exemplo n.º 24
0
    "2": "RKQEND",
    "3": "MPSTHY"
}
# '1' -> Buried; '2' -> Exposed, '3' -> Intermediate

polarizability = {
    "name": "polarizability",
    "1": "GASDT",
    "2": "CPNVEQIL",
    "3": "KMHFRYW"
}
# '1' -> (0-0.108); '2' -> (0.128-0.186), '3' -> (0.219-0.409)

#object of physiochemical properties to use for calculating CTD descriptors
ctd_properties = {
    nameof(hydrophobicity): hydrophobicity,
    nameof(normalized_VDWV): normalized_VDWV,
    nameof(polarity): polarity,
    nameof(charge): charge,
    nameof(sec_struct): sec_struct,
    nameof(solvent_accessibility): solvent_accessibility,
    nameof(polarizability): polarizability
}


def str_to_num(sequence, property):
    """
    Convert sequences str to number from input physiochemical property.

    Parameters
    ----------
Exemplo n.º 25
0
a = 3
b = 2

names = [
    "Exponent", "Modulus", "Integer Division", "Division", "Multiplication",
    "Subtraction", "Addition"
]

print(a**b, "\t", names[0], " ", a, " ", b)
print(a % b, "\t", names[1], " ", a, " ", b)
print(a // b, "\t", names[2], " ", a, " ", b)
print(a / b, "\t", names[3], " ", a, " ", b)
print(a * b, "\t", names[4], " ", a, " ", b)
print(a - b, "\t", names[5], " ", a, " ", b)
print(a + b, "\t", names[6], " ", a, " ", b)

print("The String replicator\t" * 2)

print("Hello world!!!\nWhat is your name? ")
myname = input()
print("Ah ACK!! ", myname)

from varname import nameof

print("Length of variable ", nameof(myname), " : ", len(myname))
print("String of variable ", nameof(myname), " : ", str(myname))
if myname.isdigit():
    print("Integer of variable ", nameof(myname), " : ", int(myname))
if myname.isdecimal():
    print("Float of variable ", nameof(myname), " : ", float(myname))
Exemplo n.º 26
0
def main(argv):
    try:
        opts, cml_args = getopt.getopt(
            argv, "hmvi:o:s:",
            ["help", "verbose", "midpoint", "ifile=", "ofile=", "style="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    ifile = ""
    ofile = ""
    styles = []
    verbose = False
    midpoint = False

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif opt in ("-v", "--verbose"):
            verbose = True
        elif opt in ("-m", "--midpoint"):
            midpoint = True
        elif opt in ("-i", "--ifile"):
            ifile = str(arg)
        elif opt in ("-o", "--ofile"):
            ofile = str(arg)
        elif opt in ("-s", "--style"):
            styles = str(arg).split(",")
        else:
            continue
        if arg in argv:
            argv.remove(arg)
        argv.remove(opt)

    if len(argv) != 0:
        usage()
        sys.exit(1)

    n, k, points = read_input(ifile)

    # DO NOT CALL ARGS DIRECTLY; FOR REFLECTION ONLY
    # Add values if you'd like functions to be able to call them
    args = {
        nameof(ifile): ifile,
        nameof(ofile): ofile,
        nameof(styles): styles,
        nameof(verbose): verbose,
        nameof(midpoint): midpoint,
        nameof(n): n,
        nameof(k): k,
        nameof(points): points
    }

    best = (sys.maxsize, None, None)
    for style in styles:
        cur_solution = available_solutions[style]
        cur_solution_sig = signature(cur_solution)
        cur_args = []
        for param in cur_solution_sig.parameters.keys():
            if param not in args:
                continue
            cur_args.append(args[param])
        cur_clusters = cur_solution(*cur_args)
        cur_clusters_dict = gen_cluster_dict(cur_clusters, points)
        cur_clusters_dict = optimize_points(cur_clusters_dict)
        worst_cluster_distance = get_max_distance_cluster(cur_clusters_dict)[1]
        if worst_cluster_distance < best[0]:
            best = tuple(
                [worst_cluster_distance, cur_clusters_dict, cur_solution])
    cluster_dict = best[1]
    cur_solution = best[2]

    point_count = 0
    point_test = []
    for v in cluster_dict.values():
        for v1 in v:
            assert v1 in points
            point_count += 1
            point_test.append(v1)
    assert len(point_test) == len(set(point_test))
    assert point_count == len(points)

    free_clusters, cluster_dict = organize_clusters(cluster_dict, cur_solution)
    if free_clusters != 0:
        print(
            f"WARNING:: Inefficient use of clusters. {free_clusters} free clusters unused"
        )

    # compute the maximum distance within the clusters

    worst_cluster_distance = get_max_distance_cluster(cluster_dict)[1]

    output = format_output(worst_cluster_distance, cluster_dict, points)

    if verbose:
        print(output)

    save_output(ofile, output)
Exemplo n.º 27
0
# Flow Control

a = True
b = False

from varname import nameof

print("The value of \t", nameof(a), "\t", a)
print("The value of \t", nameof(b), "\t", b)

print("Now we will evaluate conditions....")

operations = [
    "Equal to", "Not Equal to", "Less than", "Greater than",
    "Less than or equal to", "Greater than or equal to"
]

print(operations[0], "\t", a == b)
print(operations[1], "\t", a != b)
print(operations[2], "\t", a < b)
print(operations[3], "\t", a > b)
print(operations[4], "\t", a <= b)
print(operations[5], "\t", a >= b)

booleanoperations = ["and", "or", "not"]

print(booleanoperations)
#ERROR: Does not evaluate the or and not conditions
for x in booleanoperations:
    #    print(x)
    if (x == "and"):
Exemplo n.º 28
0
 async def _start_contest(self, ctx):
     contestant_names = load_variable(ctx.guild, 'contestant_names')
     on_the_hook = [Contestant(player, ctx.guild) for player in contestant_names]
     save_variable(ctx.guild, on_the_hook, nameof(on_the_hook))
Exemplo n.º 29
0
 async def reset_contestants(self, ctx):
     contestant_names = []
     save_variable(ctx.guild, contestant_names, nameof(contestant_names))
     await ctx.send('```Contestants reset```')
Exemplo n.º 30
0
playerluck5 = Player5.luck
playerStrength1 = Player1.strength
playerStrength2 = Player2.strength
playerStrength3 = Player3.strength
playerStrength4 = Player4.strength
playerStrength5 = Player5.strength
# exclaListe = Exclamationsfinales
# compListe = Complément
# liaisonListe= Liaisons
# sujetListe= sujet
listTest = [
    'abaisser,aim:er,lower', 'abandonner,aim:er,abandon',
    'abasourdir,fin:ir,stun', 'abâtardir,fin:ir,bastardize',
    'abattre,bat:tre,tear down', 'abcéder,c:éder,abscess'
]
nameWrap = nameof(listVerbs)


def recupOneindiceVerbs(liste):
    newList = []
    for i in range(0, 5):
        listeI = liste[random.randint(0, len(liste))]
        #print(listeI)
        indicevirgule = listeI.index(',')
        newList.append(listeI[0:indicevirgule])
    #print(newList)
    return newList


#recupOneindiceVerbs(listVerbs)
def recupOneindice(liste):