Python functools.partial() Examples

The following are code examples for showing how to use functools.partial(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_attributes(self):
        p = self.thetype(capture, 1, 2, a=10, b=20)
        # attributes should be readable
        self.assertEqual(p.func, capture)
        self.assertEqual(p.args, (1, 2))
        self.assertEqual(p.keywords, dict(a=10, b=20))
        # attributes should not be writable
        self.assertRaises(TypeError, setattr, p, 'func', map)
        self.assertRaises(TypeError, setattr, p, 'args', (1, 2))
        self.assertRaises(TypeError, setattr, p, 'keywords', dict(a=1, b=2))

        p = self.thetype(hex)
        try:
            del p.__dict__
        except TypeError:
            pass
        else:
            self.fail('partial object allowed __dict__ to be deleted') 
Example 2
Project: earlgrey   Author: icon-project   File: message_queue_task.py    Apache License 2.0 6 votes vote down vote up
def message_queue_task(func=None, *, type_=MessageQueueType.RPC, priority=128):
    if func is None:
        return functools.partial(message_queue_task, type_=type_, priority=priority)

    @functools.wraps(func)
    async def _wrapper(*args, **kwargs):
        try:
            return await asyncio.coroutine(func)(*args, **kwargs)
        except Exception as e:
            logging.error(e)
            traceback.print_exc()
            return MessageQueueException(str(e))

    task_attr = {
        MESSAGE_QUEUE_TYPE_KEY: type_,
        MESSAGE_QUEUE_PRIORITY_KEY: priority
    }
    setattr(_wrapper, TASK_ATTR_DICT, task_attr)
    return _wrapper 
Example 3
Project: earlgrey   Author: icon-project   File: message_queue_stub.py    Apache License 2.0 6 votes vote down vote up
def _register_tasks_async(self):
        for attribute_name in dir(self._async_task):
            try:
                attribute = getattr(self._async_task, attribute_name)
                task_attr: dict = getattr(attribute, TASK_ATTR_DICT)
            except AttributeError:
                pass
            else:
                func_name = f"{type(self._async_task).__name__}.{attribute_name}"

                message_queue_type = task_attr[MESSAGE_QUEUE_TYPE_KEY]
                message_queue_priority = task_attr[MESSAGE_QUEUE_PRIORITY_KEY]
                if message_queue_type == MessageQueueType.Worker:
                    binding_async_method = self._call_async_worker
                elif message_queue_type == MessageQueueType.RPC:
                    binding_async_method = self._call_async_rpc
                else:
                    raise RuntimeError(f"MessageQueueType invalid. {func_name}, {message_queue_type}")

                stub = functools.partial(binding_async_method, func_name, attribute, message_queue_priority)
                setattr(self._async_task, attribute_name, stub) 
Example 4
Project: earlgrey   Author: icon-project   File: message_queue_stub.py    Apache License 2.0 6 votes vote down vote up
def _register_tasks_sync(self):
        for attribute_name in dir(self._thread_local.sync_task):
            try:
                attribute = getattr(self._thread_local.sync_task, attribute_name)
                task_attr: dict = getattr(attribute, TASK_ATTR_DICT)
            except AttributeError:
                pass
            else:
                func_name = f"{type(self._thread_local.sync_task).__name__}.{attribute_name}"

                message_queue_type = task_attr[MESSAGE_QUEUE_TYPE_KEY]
                message_queue_priority = task_attr[MESSAGE_QUEUE_PRIORITY_KEY]
                if message_queue_type == MessageQueueType.Worker:
                    binding_sync_method = self._call_sync_worker
                elif message_queue_type == MessageQueueType.RPC:
                    binding_sync_method = self._call_sync_rpc
                else:
                    raise RuntimeError(f"MessageQueueType invalid. {func_name}, {message_queue_type}")

                stub = functools.partial(binding_sync_method, func_name, attribute, message_queue_priority)
                setattr(self._thread_local.sync_task, attribute_name, stub) 
Example 5
Project: AutoDL   Author: tanguofu   File: graphviz_visual.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def graphviz_visual(gv_nodes, gv_edges, imagename):
    digraph = functools.partial(gv.Digraph, format='png')
    # add all edges nodes
    s = set([])
    all_node = {}
    for k in gv_nodes:
       if k[0] not in s:
           s.add(k[0])
           all_node[k[0]] = k
    for e in gv_edges:
       if type(e) != type([]) or len(e) < 2:
           print(e)
           continue
          
       if e[0][0] not in s:
           s.add(e[0][0])
           all_node[e[0][0]] = (e[0][0], {'label': e[0][0]+"(edges)"})
       if e[0][1] not in s:
           s.add(e[0][1])
           all_node[e[0][1]] = (e[0][1], {'label': e[0][1]+"(edges)"})
    
    svg = add_nodes(digraph(), all_node.values())
    svg = add_edges(svg, gv_edges)
    svg = apply_styles(svg, styles)
    svg.render('img/' + imagename) 
Example 6
Project: slidoc   Author: mitotic   File: sdproxy.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def schedule_update(waitSec=0, force=False, synchronous=False):
    # Schedule update
    # If force, ignore any minimum wait restrictions and cancel any previously scheduled updates
    # waitSec=0 will trigger update immediately after this request
    # otherwise, a delayed update will be scheduled
    # If synchronous, force update and wait for it to complete before returning

    if Global.cachePendingUpdate:
        if not force and not synchronous:
            # Update already scheduled
            return
        IOLoop.current().remove_timeout(Global.cachePendingUpdate)
        Global.cachePendingUpdate = None

    if synchronous:
        update_remote_sheets(synchronous=True)
    elif waitSec:
        # Delayed update
        Global.cachePendingUpdate = IOLoop.current().call_later(waitSec, functools.partial(update_remote_sheets, force))
    else:
        # Update after request
        Global.cachePendingUpdate = IOLoop.current().add_callback(functools.partial(update_remote_sheets, force)) 
Example 7
Project: ieml   Author: IEMLdev   File: order.py    GNU General Public License v3.0 6 votes vote down vote up
def order_word_list(w0, word_list):
    klass = {'A': [partial(w_associate, w0=w0), partial(w_opposed, w0=w0), partial(w_crossed, w0=w0)],
             'B': count_id(w0),
             'C': count_relations(w0),
             'D': w_twin}

    SUB_KLASS = {1: '0', 2: '1', 3: '2'}

    def get_mark(w):
        for k in ('A', 'B', 'C', 'D'):
            if isinstance(klass[k], list):
                for i, f in enumerate(klass[k]):
                    if f(w1=w):
                        return k + SUB_KLASS[i + 1]
            else:
                o = klass[k](w)
                if o != 0:
                    return k + SUB_KLASS[o]

        return 'E'

    res = sorted(((w, get_mark(w)) for w in word_list), key=lambda k: k[1])
    return {k: [w[0] for w in v] for k, v in groupby(res,  key=lambda k: k[1])} 
Example 8
Project: petuk.corp   Author: fnugrahendi   File: UpdaterK.py    GNU General Public License v2.0 6 votes vote down vote up
def GarvinCheckIsUpdated(self):
		wget = "wget"
		if ("win" in sys.platform):#-- bila windows ada nih
			wget = self.BasePath+"downloader/wget_win/wget.exe"
			
		downloadfolder = self.DataPath
		#-- hapus download sebelumnya 
		subprocess.call("rm -rf "+downloadfolder+"currentversion.rb.o",shell=True)
		subprocess.call("rm -rf "+downloadfolder+"currentversion.rb",shell=True)
		#-- download info versi sekarang 
		cmd = "\""+wget +"\""+ "  --user-agent=\"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0\" --no-check-certificate https://raw.githubusercontent.com/fnugrahendi/petuk.corp/master/currentversion.rb -o "+downloadfolder+"currentversion.rb.o -O "+downloadfolder+"currentversion.rb"
		print cmd
		subprocess.Popen(cmd,shell=True)
		self.UpdaterTimer = QtCore.QTimer(self)
		self.UpdaterTimer.timeout.connect(functools.partial(self.Updater_CekSudah,"currentversion.rb",self.Updater_Download))
		self.UpdaterTimer.start(3000) 
Example 9
Project: petuk.corp   Author: fnugrahendi   File: LaporanK.py    GNU General Public License v2.0 6 votes vote down vote up
def Laporan_init(self,si_om=None):
		self.st_Laporan = QtGui.QStackedWidget(self.tab_KasBank)
		self.LaporanUI = Ui_st_Laporan()
		self.LaporanUI.setupUi(self.st_Laporan)
		self.tab_Laporan.findChild(QtGui.QVBoxLayout).addWidget(self.st_Laporan)
		#-- after main init
		super(Laporan,self).__init__(si_om)
		
		self.INDEX_ST_LAPORAN = ["MENU", "LAPORAN KAS HARIAN", "LAPORAN LABA RUGI", "LAPORAN NERACA", "LAPORAN HUTANG PIUTANG", "LAPORAN JUAL BELI"]
		
		#-- signal connect NING KENE, Connect tombol seko room Menu ke fungsi Kontrol bersangkutan
		#~ self.LaporanUI.tb_Menu_Laporan_Neraca.clicked.connect(functools.partial(self.Laporan_Neraca,None))
		self.LaporanUI.tb_Menu_Laporan_KasHarian.clicked.connect(self.Laporan_RKasHarian)
		self.LaporanUI.tb_Menu_Laporan_LabaRugi.clicked.connect(self.Laporan_RLabaRugi)
		self.LaporanUI.tb_Menu_Laporan_Neraca.clicked.connect(self.Laporan_RNeraca)
		self.LaporanUI.tb_Menu_Laporan_HutangPiutangPerusahaan.clicked.connect(self.Laporan_RHutangPiutang)
		self.LaporanUI.tb_Menu_Laporan_JualBeliPerusahaan.clicked.connect(self.Laporan_RJualBeli) 
Example 10
Project: docker-ipsec   Author: cbrichford   File: docker-ipsec.py    Apache License 2.0 6 votes vote down vote up
def add_ip_networks(ip_route: IPRoute, ip_networks, ipsec_connection_name):
    ipsec_info = IPSecInfo(ip_route=ip_route)
    ipsec_entries = ipsec_info.entries()
    rules = []

    table = iptc.Table(iptc.Table.NAT)
    table.autocommit = False
    chain = iptc.Chain(table, 'POSTROUTING')

    filter_func = functools.partial(comment_matches_ipsec_connection, ipsec_connection_name)
    existing_rules = filter_iptables_rules(chain, filter_func)
    existing_rules_sources = set(map(lambda er: netaddr.IPNetwork(er.src), existing_rules))

    for network in ip_networks:
        if network in existing_rules_sources:
            continue
        route_to_rule = functools.partial(ipsec_route_to_rule, network, ip_route)
        rules.extend(map(route_to_rule, ipsec_entries))
    if len(rules) > 0:
        for rule in rules:
            install_iptables_rule(table, ipsec_connection_name, *rule)
        table.commit() 
Example 11
Project: docker-ipsec   Author: cbrichford   File: docker-ipsec.py    Apache License 2.0 6 votes vote down vote up
def connection_up(parsed_args):
    ipsec_connection = load_ipsec_connection(parsed_args)
    connection_name = ipsec_connection['name']
    docker_networks = parsed_args.dockerNetworks
    if len(docker_networks) > 0:
        docker_client = docker.DockerClient()
        docker_network_to_ip_network = functools.partial(ip_network_for_docker_network, docker_client)
        docker_ip_networks = tuple(map(docker_network_to_ip_network, docker_networks))
    else:
        docker_ip_networks = tuple()

    ip_route = IPRoute()
    if not is_connection_up(ip_route, ipsec_connection):
        ipsec_result = ipsec('up', connection_name)
        if ipsec_result.status != 0:
            raise DockerIPSecError('Failed to connect VPN: {0}\n{1}'.format(connection_name, ipsec_result.output))

    add_ip_networks(ip_route, docker_ip_networks, connection_name) 
Example 12
Project: neural-fingerprinting   Author: StephanZheng   File: model.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def fprop(self, x, **kwargs):
        del kwargs
        my_conv = functools.partial(tf.layers.conv2d,
                                    kernel_size=3,
                                    strides=2,
                                    padding='valid',
                                    activation=tf.nn.relu,
                                    kernel_initializer=HeReLuNormalInitializer)
        my_dense = functools.partial(
            tf.layers.dense, kernel_initializer=HeReLuNormalInitializer)

        with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):
            for depth in [96, 256, 384, 384, 256]:
                x = my_conv(x, depth)
            y = tf.layers.flatten(x)
            y = my_dense(y, 4096, tf.nn.relu)
            y = fc7 = my_dense(y, 4096, tf.nn.relu)
            y = my_dense(y, 1000)
            return {'fc7': fc7,
                    self.O_LOGITS: y,
                    self.O_PROBS: tf.nn.softmax(logits=y)} 
Example 13
Project: meta-transfer-learning   Author: erfaneshrati   File: args.py    MIT License 5 votes vote down vote up
def _args_reptile(parsed_args):
    if parsed_args.foml:
        return FOML
        return partial(FOML)
    return Reptile 
Example 14
Project: chainer-openai-transformer-lm   Author: soskek   File: utils.py    MIT License 5 votes vote down vote up
def identity_init(scale=1.0):
    return partial(_identity_init, scale=scale) 
Example 15
Project: chainer-openai-transformer-lm   Author: soskek   File: utils.py    MIT License 5 votes vote down vote up
def np_init(w):
    return partial(_np_init, w=w) 
Example 16
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def PythonPartial(func, *args, **keywords):
    'Pure Python approximation of partial()'
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc 
Example 17
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def signature(part):
    """ return the signature of a partial object """
    return (part.func, part.args, part.keywords, part.__dict__) 
Example 18
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_protection_of_callers_dict_argument(self):
        # a caller's dictionary should not be altered by partial
        def func(a=10, b=20):
            return a
        d = {'a':3}
        p = self.thetype(func, a=5)
        self.assertEqual(p(**d), 3)
        self.assertEqual(d, {'a':3})
        p(b=7)
        self.assertEqual(d, {'a':3}) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_arg_combinations(self):
        # exercise special code paths for zero args in either partial
        # object or the caller
        p = self.thetype(capture)
        self.assertEqual(p(), ((), {}))
        self.assertEqual(p(1,2), ((1,2), {}))
        p = self.thetype(capture, 1, 2)
        self.assertEqual(p(), ((1,2), {}))
        self.assertEqual(p(3,4), ((1,2,3,4), {})) 
Example 20
Project: pyblish-win   Author: pyblish   File: _mock_backport.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_signature_object(func, as_instance, eat_self):
    """
    Given an arbitrary, possibly callable object, try to create a suitable
    signature object.
    Return a (reduced func, signature) tuple, or None.
    """
    if isinstance(func, type) and not as_instance:
        # If it's a type and should be modelled as a type, use __init__.
        try:
            func = func.__init__
        except AttributeError:
            return None
        # Skip the `self` argument in __init__
        eat_self = True
    elif not isinstance(func, FunctionTypes):
        # If we really want to model an instance of the passed type,
        # __call__ should be looked up, not __init__.
        try:
            func = func.__call__
        except AttributeError:
            return None
    if eat_self:
        sig_func = partial(func, None)
    else:
        sig_func = func
    try:
        return func, inspect.signature(sig_func)
    except ValueError:
        # Certain callable types are not supported by inspect.signature()
        return None 
Example 21
Project: pyblish-win   Author: pyblish   File: forking.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _rebuild_partial(func, args, keywords):
        return partial(func, *args, **keywords) 
Example 22
Project: gql   Author: graphql-python   File: dsl.py    MIT License 5 votes vote down vote up
def get_arg_serializer(arg_type):
    if isinstance(arg_type, GraphQLNonNull):
        return get_arg_serializer(arg_type.of_type)
    if isinstance(arg_type, GraphQLList):
        inner_serializer = get_arg_serializer(arg_type.of_type)
        return partial(serialize_list, inner_serializer)
    if isinstance(arg_type, GraphQLEnumType):
        return lambda value: ast.EnumValue(value=arg_type.serialize(value))
    return arg_type.serialize 
Example 23
Project: BASS   Author: Cisco-Talos   File: util.py    GNU General Public License v2.0 5 votes vote down vote up
def file_sha256(path):
    """Get the hex digest of the given file"""
    sha256 = hashlib.sha256()
    with open(path, "rb") as f:
        map(sha256.update, iter(partial(f.read, BLOCK_SIZE), ""))
    return sha256.hexdigest() 
Example 24
Project: BASS   Author: Cisco-Talos   File: util.py    GNU General Public License v2.0 5 votes vote down vote up
def file_sha256(path):
    """Get the hex digest of the given file"""
    sha256 = hashlib.sha256()
    with open(path, "rb") as f:
        map(sha256.update, iter(partial(f.read, BLOCK_SIZE), ""))
    return sha256.hexdigest() 
Example 25
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: wsgi.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, iterable, callbacks=None):
        iterator = iter(iterable)
        self._next = partial(next, iterator)
        if callbacks is None:
            callbacks = []
        elif callable(callbacks):
            callbacks = [callbacks]
        else:
            callbacks = list(callbacks)
        iterable_close = getattr(iterator, 'close', None)
        if iterable_close:
            callbacks.insert(0, iterable_close)
        self._callbacks = callbacks 
Example 26
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: wsgi.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, iterable, callbacks=None):
        iterator = iter(iterable)
        self._next = partial(next, iterator)
        if callbacks is None:
            callbacks = []
        elif callable(callbacks):
            callbacks = [callbacks]
        else:
            callbacks = list(callbacks)
        iterable_close = getattr(iterator, 'close', None)
        if iterable_close:
            callbacks.insert(0, iterable_close)
        self._callbacks = callbacks 
Example 27
Project: wikilinks   Author: trovdimi   File: decorators.py    MIT License 5 votes vote down vote up
def __get__(self, inst, objtype):
        return functools.partial(self.__call__, inst) 
Example 28
Project: AutoDL   Author: tanguofu   File: app.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def middleware(self, middleware_or_request):
        """Decorate and register middleware to be called before a request.
        Can either be called as @app.middleware or @app.middleware('request')
        """

        # Detect which way this was called, @middleware or @middleware('AT')
        if callable(middleware_or_request):
            return self.register_middleware(middleware_or_request)

        else:
            return partial(self.register_middleware,
                           attach_to=middleware_or_request)

    # Static Files 
Example 29
Project: AutoDL   Author: tanguofu   File: server.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_current_time(loop):
    """Cache the current time, since it is needed at the end of every
    keep-alive request to update the request timeout time

    :param loop:
    :return:
    """
    global current_time
    current_time = time()
    loop.call_later(1, partial(update_current_time, loop)) 
Example 30
Project: AutoDL   Author: tanguofu   File: nccl_ops_test.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testAllReduce(self):
    self._Test(partial(_NcclAllReduce, nccl.all_sum), lambda x, y: x + y)
    self._Test(partial(_NcclAllReduce, nccl.all_prod), lambda x, y: x * y)
    self._Test(partial(_NcclAllReduce, nccl.all_min), np.minimum)
    self._Test(partial(_NcclAllReduce, nccl.all_max), np.maximum) 
Example 31
Project: AutoDL   Author: tanguofu   File: nccl_ops_test.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testAllSumGrad(self):
    self._TestGradient(
        partial(_NcclAllReduce, nccl.all_sum), lambda x, y: x + y) 
Example 32
Project: AutoDL   Author: tanguofu   File: nccl_ops_test.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testSum(self):
    self._Test(partial(_NcclReduce, nccl.reduce_sum), lambda x, y: x + y) 
Example 33
Project: slidoc   Author: mitotic   File: multiproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def read_chunk(self, callback):
        """Call callback when we have read a chunk of data.
        Callback may return a null string, when stream is closed.
        """
        assert not self._read_callback, "Already reading"
        self._chunky_active = True
        return self.read_bytes(READ_CHUNK_SIZE, callback=callback, partial=True) 
Example 34
Project: slidoc   Author: mitotic   File: multiproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, server_type, external_stream, from_address, proxy_server):
        self.server_type = server_type
        self.external_stream = external_stream
        self.from_address = from_address
        self.ip_addr, self.ip_port = from_address
        self.proxy_server = proxy_server

        self.xheaders = proxy_server.xheaders
        self.multiplex_params = proxy_server.multiplex_params
        self.relay_keep_alive = proxy_server.relay_keep_alive
        self.local_handler_class = proxy_server.local_handler_class
        self.debug = proxy_server.debug

        self.allowed_methods = Pipeline.METHODS[self.server_type]
        self.last_request = 0

        self.internal_sock = None
        self.internal_stream = None
        self.opened = False
        self.closed = False
        self.internal_closed = False
        self.requests = []

        self.cur_req = None
        self.cur_resp = None

        self.request_protocol = "HTTP/1.1"
        self.host_spec = None
        self.relay_address = None

        self.inbound_flow = None
        self.outbound_flow = None
        self.inbound_connect_state = None
        self.reconnect = False
        self.closing_internal_only = False
        self.err_response = None

        self.refresh_connection_entry(new=True) # May shutdown, if overloaded

        self.external_stream.set_close_callback(functools.partial(self.shutdown, external=True), immediate=True)
        self.inbound_flow = FlowHandler(self, external_stream, inbound=True) 
Example 35
Project: slidoc   Author: mitotic   File: sdproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def makeRandomFunction(seed):
    LCRandom.setSeed(seed);
    return functools.partial(LCRandom.randomNumber, seed) 
Example 36
Project: pydockenv   Author: se7entyse7en   File: setup.py    Apache License 2.0 5 votes vote down vote up
def get_about():
    regexes = {
        'title': r"^__title__\s=\s(?P<quote>['])(?P<title>\w*)(?P=quote)$",
        'version': r"^__version__\s=\s(?P<quote>['])(?P<version>[\d\.]*)(?P=quote)$",
        'author': r"^__author__\s=\s(?P<quote>['])(?P<author>[\w\s]*)(?P=quote)$",
        'author_email': r"^__author_email__\s=\s(?P<quote>['])(?P<author_email>.*)(?P=quote)$",
        'description': r"^__description__\s=\s(?P<quote>['])(?P<description>.*)(?P=quote)$",
        'project_url': r"^__project_url__\s=\s(?P<quote>['])(?P<project_url>.*)(?P=quote)$",
    }

    with open('./pydockenv/__init__.py') as f:
        raw_about = f.read()

    extract = partial(re.search, string=raw_about, flags=re.MULTILINE)
    return {k: extract(v).group(k) for k, v in regexes.items()} 
Example 37
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: asyncioEvent.py    MIT License 5 votes vote down vote up
def main(loop):
    # Create a shared event
    event = asyncio.Event()
    print('event start state: {}'.format(event.is_set()))

    loop.call_later(
        0.1, functools.partial(set_event, event)
    )

    await asyncio.wait([coro1(event), coro2(event)])
    print('event end state: {}'.format(event.is_set())) 
Example 38
Project: petuk.corp   Author: fnugrahendi   File: LoginK.py    GNU General Public License v2.0 5 votes vote down vote up
def Login_Login(self):
		self.Login_Goto("Login")
		
		#~ self.GarvinSetConfig("Last Login","sukimin ingin login namun dia kesusahan karena belum punya userid")
		#~ LastLogin = self.userdata.
		
		self.LoginUI.le_Login_User.clear()
		self.LoginUI.le_Login_Password.clear()
		self.LoginUI.le_Login_Password_Confirm.clear()
		self.Login_Login_Password_Inputed = ""
		users = self.DatabaseFetchResult(self.dbDatabase,"gd_user","level",0)
				
		if len(users)<1:
			#--- Create user and password for admin!
			self.LoginUI.le_Login_User.setText("admin")
			#~ developernote = functools.partial(self.DataMaster_Popup,"Note for Developer (Andrew & E-Qraw) : \nCheck ulang apakah field password di table gd_user bertipe varchar(64)!",self.DataMaster_None)
			self.DataMaster_Popup("User admin belum ada! silahkan beri user dan password untuk admin!",self.DataMaster_None,500,300,self.DataMaster_None)
			self.LoginUI.le_Login_Password_Confirm.show()
			self.GarvinDisconnect(self.LoginUI.tb_Login_Ok.clicked)
			self.LoginUI.tb_Login_Ok.clicked.connect(self.Login_Login_CreateAdmin)
		else:
			self.LoginUI.le_Login_Password_Confirm.hide()
			#--- signal tombol sudah di sambungkan di init
			self.GarvinDisconnect(self.LoginUI.tb_Login_Ok.clicked)
			self.GarvinDisconnect(self.LoginUI.le_Login_Password.returnPressed)
			self.GarvinDisconnect(self.LoginUI.le_Login_User.returnPressed)
			self.LoginUI.tb_Login_Ok.clicked.connect(self.Login_Login_Auth)
			self.LoginUI.le_Login_Password.returnPressed.connect(self.Login_Login_Auth)
			self.LoginUI.le_Login_User.returnPressed.connect(self.Login_Login_Auth)
		
		lastlogin = self.GarvinGetConfig("Last Login")
		self.LoginUI.le_Login_User.setText(lastlogin) 
Example 39
Project: petuk.corp   Author: fnugrahendi   File: LaporanK.py    GNU General Public License v2.0 5 votes vote down vote up
def Laporan_RLabaRugi(self):
		"""Kontrol untuk RLabaRugi"""
		self.Laporan_Goto("LAPORAN LABA RUGI")
		#~ self.GarvinDisconnect(self.LaporanUI.tb_Laporan_LabaRugi_KodePelanggan.clicked)
		#~ self.LaporanUI.tb_Laporan_LabaRugi_KodePelanggan.clicked.connect(functools.partial(self.Popup_NamaAlamat,self.LaporanUI.tb_Laporan_LabaRugi_KodePelanggan))
		self.LaporanUI.tb_Laporan_LabaRugi_Cetak.clicked.connect(functools.partial(self.Laporan_LabaRugi))
		self.LaporanUI.tb_Laporan_LabaRugi_Kembali.clicked.connect(self.Laporan_RMenu) 
Example 40
Project: petuk.corp   Author: fnugrahendi   File: LaporanK.py    GNU General Public License v2.0 5 votes vote down vote up
def Laporan_RKasHarian(self):
		"""Kontrol untuk RKasHarian"""
		self.Laporan_Goto("LAPORAN KAS HARIAN")
		self.GarvinDisconnect(self.LaporanUI.tb_Laporan_KasHarian_noAkunKas.clicked) #-- fungsi RKasHarian bakalan dipanggil berkali2 pas program jalan, dadi kudu pastikan diskonek sikik
		self.LaporanUI.tb_Laporan_KasHarian_noAkunKas.clicked.connect(functools.partial(self.Popup_Rekening,self.LaporanUI.tb_Laporan_KasHarian_noAkunKas))
		self.LaporanUI.tb_Laporan_KasHarian_Cetak.clicked.connect(functools.partial(self.Laporan_KasHarian))
		self.LaporanUI.tb_Laporan_KasHarian_Kembali.clicked.connect(self.Laporan_RMenu) 
Example 41
Project: petuk.corp   Author: fnugrahendi   File: LaporanK.py    GNU General Public License v2.0 5 votes vote down vote up
def Laporan_RHutangPiutang(self):
		"""Kontrol untuk RHutangPiutang"""
		self.Laporan_Goto("LAPORAN HUTANG PIUTANG")
		self.GarvinDisconnect(self.LaporanUI.tb_Laporan_HutangPiutang_KodePelanggan.clicked)
		self.LaporanUI.tb_Laporan_HutangPiutang_KodePelanggan.clicked.connect(functools.partial(self.Popup_NamaAlamat,self.LaporanUI.tb_Laporan_HutangPiutang_KodePelanggan))
		self.LaporanUI.tb_Laporan_HutangPiutang_Cetak.clicked.connect(functools.partial(self.Laporan_HutangPiutang))
		self.LaporanUI.tb_Laporan_HutangPiutang_Kembali.clicked.connect(self.Laporan_RMenu) 
Example 42
Project: petuk.corp   Author: fnugrahendi   File: LaporanK.py    GNU General Public License v2.0 5 votes vote down vote up
def Laporan_RJualBeli(self):
		"""Kontrol untuk RJualBeli"""
		self.Laporan_Goto("LAPORAN JUAL BELI")
		self.GarvinDisconnect(self.LaporanUI.tb_Laporan_JualBeli_KodePelanggan.clicked)
		self.LaporanUI.tb_Laporan_JualBeli_KodePelanggan.clicked.connect(functools.partial(self.Popup_NamaAlamat,self.LaporanUI.tb_Laporan_JualBeli_KodePelanggan))
		self.LaporanUI.tb_Laporan_JualBeli_Cetak.clicked.connect(functools.partial(self.Laporan_JualBeli))
		self.LaporanUI.tb_Laporan_JualBeli_Kembali.clicked.connect(self.Laporan_RMenu) 
Example 43
Project: twiml-generator   Author: TwilioDevEd   File: csharp.py    MIT License 5 votes vote down vote up
def enum_builder(verb, attr_name):
    return partial(enum_name, verb.name, attr_name) 
Example 44
Project: twiml-generator   Author: TwilioDevEd   File: java.py    MIT License 5 votes vote down vote up
def enum_builder(verb, attr_name):
    return partial(enum_name, verb.name, attr_name) 
Example 45
Project: docker-ipsec   Author: cbrichford   File: docker-ipsec.py    Apache License 2.0 5 votes vote down vote up
def get_ipsec_connection_routes(ipsec_info: IPSecInfo,
                                ipsec_connection):
    filter_func = functools.partial(route_table_entry_matches_ipsec_connection,
                                    ipsec_connection)
    return tuple(filter(filter_func, ipsec_info.entries())) 
Example 46
Project: docker-ipsec   Author: cbrichford   File: docker-ipsec.py    Apache License 2.0 5 votes vote down vote up
def connection_down(parsed_args):
    ipsec_connection = load_ipsec_connection(parsed_args)
    connection_name = ipsec_connection['name']
    ip_route = IPRoute()
    if is_connection_up(ip_route, ipsec_connection):
        ipsec_result = ipsec('down', connection_name)
        if ipsec_result.status != 0:
            raise DockerIPSecError('Failed to disconnect VPN: {0}\n{1}'.format(connection_name, ipsec_result.output))

    filter_func = functools.partial(comment_matches_ipsec_connection, connection_name)
    remove_iptables_rules(filter_func) 
Example 47
Project: docker-ipsec   Author: cbrichford   File: docker-ipsec.py    Apache License 2.0 5 votes vote down vote up
def add_docker_networks(parsed_args):
    ipsec_connection = load_ipsec_connection(parsed_args)
    connection_name = ipsec_connection['name']
    docker_networks = parsed_args.dockerNetworks

    docker_client = docker.DockerClient()
    docker_network_to_ip_network = functools.partial(ip_network_for_docker_network, docker_client)
    docker_ip_networks = tuple(map(docker_network_to_ip_network, docker_networks))
    ip_route = IPRoute()
    if not is_connection_up(ip_route, ipsec_connection):
        raise DockerIPSecError('IPSec connection {0} is not connected!'.format(connection_name))

    add_ip_networks(ip_route, docker_ip_networks, connection_name) 
Example 48
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 5 votes vote down vote up
def check_status(method=None, statuses=None):
    """Check that the item has a defined status."""
    if method is None:
        return partial(check_status, statuses=statuses)

    statuses = statuses or []

    @wraps(method)
    def wrapper(self, *args, **kwargs):
        """Check current deposit status."""
        if self['_circulation']['status'] not in statuses:
            raise PIDInvalidAction()

        return method(self, *args, **kwargs)
    return wrapper 
Example 49
Project: mmdetection   Author: open-mmlab   File: misc.py    Apache License 2.0 5 votes vote down vote up
def multi_apply(func, *args, **kwargs):
    pfunc = partial(func, **kwargs) if kwargs else func
    map_results = map(pfunc, *args)
    return tuple(map(list, zip(*map_results))) 
Example 50
Project: neural-fingerprinting   Author: StephanZheng   File: test_attacks.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        super(TestFastFeatureAdversaries, self).setUp()

        def make_imagenet_cnn(input_shape=(None, 224, 224, 3)):
            """
            Similar CNN to AlexNet.
            """

            class ModelImageNetCNN(Model):
                def __init__(self, scope, nb_classes=1000, **kwargs):
                    del kwargs
                    Model.__init__(self, scope, nb_classes, locals())

                def fprop(self, x, **kwargs):
                    del kwargs
                    my_conv = functools.partial(tf.layers.conv2d,
                                                kernel_size=3,
                                                strides=2,
                                                padding='valid',
                                                activation=tf.nn.relu,
                                                kernel_initializer=HeReLuNormalInitializer)
                    my_dense = functools.partial(tf.layers.dense,
                                                 kernel_initializer=HeReLuNormalInitializer)
                    with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):
                        for depth in [96, 256, 384, 384, 256]:
                            x = my_conv(x, depth)
                        y = tf.layers.flatten(x)
                        y = my_dense(y, 4096, tf.nn.relu)
                        y = fc7 = my_dense(y, 4096, tf.nn.relu)
                        y = my_dense(y, 1000)
                        return {'fc7': fc7,
                                self.O_LOGITS: y,
                                self.O_PROBS: tf.nn.softmax(logits=y)}

            return ModelImageNetCNN('imagenet')

        self.input_shape = [10, 224, 224, 3]
        self.sess = tf.Session()
        self.model = make_imagenet_cnn(self.input_shape)
        self.attack = FastFeatureAdversaries(self.model)