python类getnode()的实例源码

auth_web.py 文件源码 项目:AlexaPi 作者: alexa-pi 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def index(self):
        sd = json.dumps({
            "alexa:all": {
                "productID": config['alexa']['Device_Type_ID'],
                "productInstanceAttributes": {
                    "deviceSerialNumber": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest()
                }
            }
        })

        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url() + "code"
        payload = {
            "client_id": config['alexa']['Client_ID'],
            "scope": "alexa:all",
            "scope_data": sd,
            "response_type": "code",
            "redirect_uri": callback
        }
        req = requests.Request('GET', url, params=payload)
        prepared_req = req.prepare()
        raise cherrypy.HTTPRedirect(prepared_req.url)
host.py 文件源码 项目:JimV-N 作者: jamesiter 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __init__(self):
        self.conn = None
        self.dirty_scene = False
        self.guest = None
        self.guest_mapping_by_uuid = dict()
        self.hostname = ji.Common.get_hostname()
        self.node_id = uuid.getnode()
        self.cpu = psutil.cpu_count()
        self.memory = psutil.virtual_memory().total
        self.interfaces = dict()
        self.disks = dict()
        self.guest_callbacks = list()
        self.interval = 60
        # self.last_host_cpu_time = dict()
        self.last_host_traffic = dict()
        self.last_host_disk_io = dict()
        self.last_guest_cpu_time = dict()
        self.last_guest_traffic = dict()
        self.last_guest_disk_io = dict()
        self.ts = ji.Common.ts()
        self.ssh_client = None
guia_bolso.py 文件源码 项目:guiabolso2csv 作者: hugombarreto 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def __init__(self, email, password):
        self.email = email
        self.password = password
        self.device_token = hashlib.md5(str(uuid.getnode())).hexdigest()
        self.session = requests.Session()
        self.login()
        basic_info = self.get_basic_info()
        self.categories = basic_info["GB.categories"]
        self.months = basic_info["GB.months"]
        self.statements = basic_info["GB.statements"]
        self.fieldnames = [u'name', u'label', u'date', u'account', u'category',
                           u'subcategory', u'duplicated', u'currency',
                           u'value', u'deleted']

        self.category_resolver = {}
        for categ in self.categories:
            for sub_categ in categ['categories']:
                self.category_resolver[sub_categ['id']] = \
                    (categ['name'], sub_categ['name'])

        self.account_resolver = {}
        for account in self.statements:
            for sub_account in account['accounts']:
                self.account_resolver[sub_account['id']] = sub_account['name']
gdistcc.py 文件源码 项目:gdistcc 作者: apeabody 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def list_instances(project, zone, globalinstances, distro, includeterm):

    # NOT thread safe
    credentials = GoogleCredentials.get_application_default()
    compute = discovery.build('compute', 'v1', credentials=credentials)

    result = compute.instances().list(project=project, zone=zone).execute()
    if ('items' in result):
        print('%s instances in zone %s:' % (project, zone))
        instancenames = []
        name = prefix + '-' + distro
        if not globalinstances:
            name += '-' + format(str(uuid.getnode())[:8:-1])
        for instance in result['items']:
            if name in instance['name']:
                print(' - ' + instance['name'] + ' - ' + instance['status'])
                if (instance['status'] == 'RUNNING' or includeterm): 
                    instancenames.append(instance['name'])
        return instancenames if (len(instancenames) > 0) else False
    return False
# [END list_instances]


# [START check_gceproject]
auth_web.py 文件源码 项目:alexa-client 作者: ewenchou 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def index(self):
        sd = json.dumps({
            "alexa:all": {
                "productID": PRODUCT_ID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": uuid.getnode()
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url() + "authresponse"
        payload = {
            "client_id": CLIENT_ID,
            "scope": "alexa:all",
            "scope_data": sd,
            "response_type": "code",
            "redirect_uri": callback
        }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
util.py 文件源码 项目:monique 作者: monique-dashboards 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def uuid_with_timestamp(microseconds, lowest_val=False, randomize=False):
    ts = int(microseconds * 10) + long(0x01b21dd213814000)
    time_low = ts & long(0xffffffff)
    time_mid = (ts >> 32) & long(0xffff)
    time_hi_version = (ts >> long(48)) & long(0x0fff)
    if randomize:
        cs = random.randrange(1 << long(14))
        clock_seq_low = cs & long(0xff)
        clock_seq_hi_variant = (cs >> long(8)) & long(0x3f)
        node = uuid.getnode()
    else:
        if lowest_val: # uuid with lowest possible clock value
            clock_seq_low = 0 & long(0xff)
            clock_seq_hi_variant = 0 & long(0x3f)
            node = 0 & long(0xffffffffffff) # 48 bits
        else: # UUID with highest possible clock value
            clock_seq_low = long(0xff)
            clock_seq_hi_variant = long(0x3f)
            node = long(0xffffffffffff) # 48 bits
    return uuid.UUID(
        fields=(time_low, time_mid, time_hi_version,
                clock_seq_hi_variant, clock_seq_low, node),
        version=1
    )
yjbTrader.py 文件源码 项目:vxTrader 作者: vex1023 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __init__(self, account, password):

        # ?????
        super(yjbLoginSession, self).__init__(account=account, password=password)

        # ???????
        self.mac_address = ("".join(c + "-" if i % 2 else c for i, c in \
                                    enumerate(hex(uuid.getnode())[2:].zfill(12)))[:-1]).upper()

        # TODO disk_serial_id and cpuid machinecode ???????
        self.disk_serial_id = "ST3250890AS"
        self.cpuid = "-41315-FA76111D"
        self.machinecode = "-41315-FA76111D"

        # ?????
        self.code_rule = re.compile("^[0-9]{4}$")

        if datetime.now() > datetime(year=2016, month=11, day=30, hour=0):
            # raise TraderAPIError('?????????2016?11?30???')
            logger.warning('?????????2016?11?30???')
        else:
            logger.warning('?????????2016?11?30???')
gfTrader.py 文件源码 项目:vxTrader 作者: vex1023 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self, account, password):

        # ?????
        super(gfLoginSession, self).__init__(account=account, password=password)

        # TODO ??????????
        self.disknum = "S2ZWJ9AF517295"
        self.mac_address = ("".join(c + "-" if i % 2 else c for i, c in \
                                    enumerate(hex(uuid.getnode())[2:].zfill(12)))[:-1]).upper()
        # ?????????
        self.code_rule = re.compile("^[A-Za-z0-9]{5}$")

        # ????sessionId
        self._dse_sessionId = None

        # ??????
        self.margin_flags = False
image_embedder.py 文件源码 项目:orange3-imageanalytics 作者: biolab 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __init__(self, model="inception-v3", layer="penultimate",
                 server_url='api.garaza.io:443'):
        super().__init__(server_url)
        model_settings = self._get_model_settings_confidently(model, layer)
        self._model = model
        self._layer = layer
        self._target_image_size = model_settings['target_image_size']

        cache_file_path = self._cache_file_blueprint.format(model, layer)
        self._cache_file_path = join(cache_dir(), cache_file_path)
        self._cache_dict = self._init_cache()

        self._session = cachecontrol.CacheControl(
            requests.session(),
            cache=cachecontrol.caches.FileCache(
                join(cache_dir(), __name__ + ".ImageEmbedder.httpcache"))
        )

        # attribute that offers support for cancelling the embedding
        # if ran in another thread
        self.cancelled = False
        self.machine_id = \
            QSettings().value('error-reporting/machine-id', '', type=str)  \
            or str(uuid.getnode())
        self.session_id = None
write.py 文件源码 项目:decoding_challenge_cortana_2016_3rd 作者: kingjr 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def get_machid():
    """Get (mostly) unique machine ID

    Returns
    -------
    ids : array (length 2, int32)
        The machine identifier used in MNE.
    """
    mac = b('%012x' % uuid.getnode())  # byte conversion for Py3
    mac = re.findall(b'..', mac)  # split string
    mac += [b'00', b'00']  # add two more fields

    # Convert to integer in reverse-order (for some reason)
    from codecs import encode
    mac = b''.join([encode(h, 'hex_codec') for h in mac[::-1]])
    ids = np.flipud(np.fromstring(mac, np.int32, count=2))
    return ids
__init__.py 文件源码 项目:pyrecord 作者: Aakashdeveloper 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def tuling(self, info, apiKey = None):
        tuling_server = "http://www.tuling123.com/openapi/api"

        assert isinstance(info, str), "Info must be a string"
        assert apiKey is None or isinstance(apiKey, str), "`apiKey` must be `None` or a string"
        #using Rain's defaul tuline's keys
        if apiKey is None: apiKey = "fd2a2710a7e01001f97dc3a663603fa1"

        mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:]

        url = tuling_server + "?key=" +apiKey + "&info=" + info

        re = urlopen(url).read()
        re_dict = json.loads(re)
        answer = re_dict['text']

        return answer

    # nuance header
podium.py 文件源码 项目:jabbapylib3 作者: jabbalaci 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_fingerprint(md5=False):
    """
    Fingerprint of the current operating system/platform.

    If md5 is True, a digital fingerprint is returned.
    """
    sb = []
    sb.append(p.node())
    sb.append(p.architecture()[0])
    sb.append(p.architecture()[1])
    sb.append(p.machine())
    sb.append(p.processor())
    sb.append(p.system())
    sb.append(str(uuid.getnode()))    # MAC address
    text = '#'.join(sb)
    if md5:
        return string_to_md5(text)
    else:
        return text
__init__.py 文件源码 项目:kiota 作者: Morteo 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def unique_id():
  import uuid
  return uuid.getnode()
get_face_dlib_per3.py 文件源码 项目:facerecognition 作者: guoxiaolu 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_mac_address():
    import uuid
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:]
    return mac
test_time_util.py 文件源码 项目:deb-python-cassandra-driver 作者: openstack 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_times_from_uuid1(self):
        node = uuid.getnode()
        now = time.time()
        u = uuid.uuid1(node, 0)

        t = util.unix_time_from_uuid1(u)
        self.assertAlmostEqual(now, t, 2)

        dt = util.datetime_from_uuid1(u)
        t = calendar.timegm(dt.timetuple()) + dt.microsecond / 1e6
        self.assertAlmostEqual(now, t, 2)
views.py 文件源码 项目:geekcloud 作者: Mr-Linus 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def is_latest():
    node = uuid.getnode()
    jsn = uuid.UUID(int=node).hex[-12:]
    with open(os.path.join(BASE_DIR, 'version')) as f:
        current_version = f.read()
    lastest_version = urllib.urlopen('http://www.jumpserver.org/lastest_version.html?jsn=%s' % jsn).read().strip()

    if current_version != lastest_version:
        pass
api.py 文件源码 项目:geekcloud 作者: Mr-Linus 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def get_mac_address():
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:]
    return mac
__init__.py 文件源码 项目:linchpin 作者: CentOS-PaaS-SIG 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def setup_rundb(self):
        """
        Configures the run database parameters, sets them into extra_vars
        """

        rundb_conn_default = '~/.config/linchpin/rundb-::mac::.json'
        rundb_conn = self.get_cfg(section='lp',
                                  key='rundb_conn',
                                  default=rundb_conn_default)
        rundb_type = self.get_cfg(section='lp',
                                  key='rundb_type',
                                  default='TinyRunDB')
        rundb_conn_type = self.get_cfg(section='lp',
                                       key='rundb_conn_type',
                                       default='file')
        self.rundb_hash = self.get_cfg(section='lp',
                                       key='rundb_hash',
                                       default='sha256')

        if rundb_conn_type == 'file':
            rundb_conn_int = rundb_conn.replace('::mac::', str(get_mac()))
            rundb_conn_int = os.path.expanduser(rundb_conn_int)
            rundb_conn_dir = os.path.dirname(rundb_conn_int)

            if not os.path.exists(rundb_conn_dir):
                os.mkdir(rundb_conn_dir)


        self.set_evar('rundb_type', rundb_type)
        self.set_evar('rundb_conn', rundb_conn_int)
        self.set_evar('rundb_hash', self.rundb_hash)


        return BaseDB(DB_DRIVERS[rundb_type], rundb_conn_int)
tts.py 文件源码 项目:dingdang-robot 作者: wzpan 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def get_speech(self, phrase):
        if self.token == '':
            self.token = self.get_token()
        query = {'tex': phrase,
                 'lan': 'zh',
                 'tok': self.token,
                 'ctp': 1,
                 'cuid': str(get_mac())[:32],
                 'per': self.per
                 }
        r = requests.post('http://tsn.baidu.com/text2audio',
                          data=query,
                          headers={'content-type': 'application/json'})
        try:
            r.raise_for_status()
            if r.json()['err_msg'] is not None:
                self._logger.critical('Baidu TTS failed with response: %r',
                                      r.json()['err_msg'],
                                      exc_info=True)
                return None
        except Exception:
            pass
        with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
            f.write(r.content)
            tmpfile = f.name
            return tmpfile
utils.py 文件源码 项目:voicetools 作者: namco1992 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def get_mac_address():
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e+2] for e in range(0, 11, 2)])
ServerConnection.py 文件源码 项目:NortheasternCTF2016 作者: wilkening-mark 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self, logger, device_key):
        self.logger = logger
        self.conn = None
        self.device_id = str(get_mac())
        self.device_key = device_key

# Connect to the server
views.py 文件源码 项目:geekcloud 作者: GeekCloud-Team 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def is_latest():
    node = uuid.getnode()
    jsn = uuid.UUID(int=node).hex[-12:]
    with open(os.path.join(BASE_DIR, 'version')) as f:
        current_version = f.read()
    lastest_version = urllib.urlopen('http://www.jumpserver.org/lastest_version.html?jsn=%s' % jsn).read().strip()

    if current_version != lastest_version:
        pass
api.py 文件源码 项目:geekcloud 作者: GeekCloud-Team 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get_mac_address():
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:]
    return mac
iscp.py 文件源码 项目:onkyo_serial 作者: blaedd 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _getMac():
        """Get our machines mac address and format it for the packet."""
        return '{:0>12X}'.format(uuid.getnode())
osenv.py 文件源码 项目:python-script 作者: austin98x 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def getmac(self):
        import uuid
        node = uuid.getnode()
        mac = uuid.UUID(int = node).hex[-12:]
        return mac
__init__.py 文件源码 项目:OctoPrint-PolarCloud 作者: markwal 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_mac():
    return ':'.join(('%012X' % uuid.getnode())[i:i+2] for i in range(0, 12, 2))

# what's the likely ip address for the local UI?
tts.py 文件源码 项目:chat 作者: Decalogue 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def __init__(self, audioplayer=None, tempdir="."):
        if audioplayer:
            self.audioplayer = audioplayer
        else:
            self.audioplayer = mixer
        self.audioplayer.init()
        self.app_key = "QrhsINLcc3Io6w048Ia8kcjS"
        self.secret_key = "e414b3ccb7d51fef12f297ffea9ec41d"
        self.url_tok_base = "https://openapi.baidu.com/oauth/2.0/token"
        self.url_get_base = "http://tsn.baidu.com/text2audio"
        self.url_post_base = "http://tsn.baidu.com/text2audio"
        self.access_token = self.get_token()
        self.mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:]
        self.language = 'zh'
        self.tempdir = tempdir if os.path.isdir(tempdir) else "."
mytools.py 文件源码 项目:chat 作者: Decalogue 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def get_mac_address():
    """Get mac address.
    """
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e+2] for e in range(0, 11, 2)])
models.py 文件源码 项目:morango 作者: learningequality 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def get_or_create_current_instance(cls):
        """Get the instance model corresponding to the current system, or create a new
        one if the system is new or its properties have changed (e.g. OS from upgrade)."""

        # on Android, platform.platform() barfs, so we handle that safely here
        try:
            plat = platform.platform()
        except:
            plat = "Unknown (Android?)"

        kwargs = {
            "platform": plat,
            "hostname": platform.node(),
            "sysversion": sys.version,
            "database": DatabaseIDModel.get_or_create_current_database_id(),
            "db_path": os.path.abspath(settings.DATABASES['default']['NAME']),
            "system_id": os.environ.get("MORANGO_SYSTEM_ID", ""),
        }

        # try to get the MAC address, but exclude it if it was a fake (random) address
        mac = uuid.getnode()
        if (mac >> 40) % 2 == 0:  # 8th bit (of 48 bits, from left) is 1 if MAC is fake
            hashable_identifier = "{}:{}".format(kwargs['database'].id, mac)
            kwargs["node_id"] = hashlib.sha1(hashable_identifier.encode('utf-8')).hexdigest()[:20]
        else:
            kwargs["node_id"] = ""

        # do within transaction so we only ever have 1 current instance ID
        with transaction.atomic():
            InstanceIDModel.objects.filter(current=True).update(current=False)
            obj, created = InstanceIDModel.objects.get_or_create(**kwargs)
            obj.current = True
            obj.save()

        return obj, created
test_uuid.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def test_getnode(self):
        import sys
        node1 = uuid.getnode()
        self.check_node(node1, "getnode1")

        # Test it again to ensure consistency.
        node2 = uuid.getnode()
        self.check_node(node2, "getnode2")

        self.assertEqual(node1, node2)


问题


面经


文章

微信
公众号

扫码关注公众号