当前位置: 首页>>代码示例>>Python>>正文


Python common.Common类代码示例

本文整理汇总了Python中common.Common的典型用法代码示例。如果您正苦于以下问题:Python Common类的具体用法?Python Common怎么用?Python Common使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Common类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _downloader

 def _downloader(self):
     while (not self.empty()) and (not self.project.shutdown_signal):
         t = threading.current_thread()
         Common.check_for_pause(self.project)
         slip = self.get()
         if callable(slip.url):
             file_url = slip.url()
         else:
             file_url = slip.url
         t.name = "Downloading: " + slip.item[slip.filename_key]
         self.project.log("transaction", "Downloading " + slip.item[slip.filename_key], "info", True)
         try:
             data = Common.webrequest(
                 file_url, self.headers(), self.http_callback, None, False, True
             )  # Response object gets passed to shutil.copyfileobj
             self.storage_callback(data, slip)
         except urllib.error.HTTPError as err:
             self.project.log(
                 "exception",
                 "{} failed to download - HTTPError {}".format(slip.item[slip.filename_key], err.code),
                 "warning",
             )
     if self.project.shutdown_signal:
         self.project.log(
             "exception",
             "{} received shutdown signal. Stopping...".format(threading.current_thread().name),
             "warning",
         )
     else:
         self.project.log("transaction", "{} has completed.".format(threading.current_thread().name), "info")
开发者ID:jadacyrus,项目名称:searchgiant_cli,代码行数:30,代码来源:Downloader.py

示例2: main

def main():
    # parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('--settings', action='store_true', dest='settings', help='Open Tor Browser Launcher settings')
    parser.add_argument('url', nargs='*', help='URL to load')
    args = parser.parse_args()

    settings = bool(args.settings)
    url_list = args.url

    # load the version and print the banner
    with open(os.path.join(SHARE, 'version')) as buf:
        tor_browser_launcher_version = buf.read().strip()

    print _('Tor Browser Launcher')
    print _('By Micah Lee, licensed under MIT')
    print _('version {0}').format(tor_browser_launcher_version)
    print 'https://github.com/micahflee/torbrowser-launcher'

    common = Common(tor_browser_launcher_version)

    # is torbrowser-launcher already running?
    tbl_pid = common.get_pid(common.paths['tbl_bin'], True)
    if tbl_pid:
        print _('Tor Browser Launcher is already running (pid {0}), bringing to front').format(tbl_pid)
        common.bring_window_to_front(tbl_pid)
        sys.exit()

    if settings:
        # settings mode
        app = Settings(common)

    else:
        # launcher mode
        app = Launcher(common, url_list)
开发者ID:boklm,项目名称:torbrowser-launcher,代码行数:35,代码来源:__init__.py

示例3: getDeviceInfo

    def getDeviceInfo(self, username):
        '''
        用户查看设备信息
        :param username:
            微信用户提供的用户名
        :return 'res[]/fail d':
        '''
        if not username:
            return 'fail', errors.NOT_BIND
        r = Db.select('t_user', where='wx_name = $username', vars=locals(), limit=1)  # 查看用户是否已绑定
        if not r:  # 用户还未绑定设备
            return 'fail', errors.NOT_BIND
        u = r[0]  # 取出第一个用户为当前用户
        r1 = Db.select('t_device', where="id=$u['device_id']", vars=locals(), limit=1)  # 获取设备基本信息
        if not r1:  # 如果设备不存在,则为系统错误
            return 'fail', errors.ERROR_SYSTEM
        d = r1[0]  # 取出第一个设备作为当前设备
        res = dict()  # 返回结果的字典
        res['id'] = d['id']  # 设备ID
        res['ct'] = Common.secToStr(d['create_time'])  # 生产日期
        res['bs'] = '已绑定'  # 绑定状态
        res['rf'] = d['delay']  # 收集数据频率

        r2 = Db.select('t_device_attribute', what='count(*)', where="device_id=$d['id']", vars=locals())  # 获取上传次数
        if not r2:
            res['count'] = 0  # 上传次数
            res['last'] = 0  # 最后一次上传时间
        else:
            res['count'] = r2[0]['count(*)']  # 上传次数
            r3 = Db.select('t_device_attribute', where="device_id=$d['id']", vars=locals(), order="time desc",
                           limit=1)  # 获取最后一个记录
            res['last'] = Common.secToLast(r3[0].time)  # 最后一次上传时间
        return 'success', res
开发者ID:luodongseu,项目名称:findbake,代码行数:33,代码来源:apiManager.py

示例4: ConstraintNotDominatedByX

 def ConstraintNotDominatedByX(self, model):
     """
     Creates a constraint preventing search in dominated regions.
     """
     DisjunctionOrLessMetrics = list()
     for i in range(len(self.metrics_variables)):
         if self.metrics_objective_direction[i] == Common.METRICS_MAXIMIZE:
             DisjunctionOrLessMetrics.append(
                 SMTLib.SMT_GT(
                     self.metrics_variables[i],
                     SMTLib.SMT_IntConst(
                         Common.evalForNum(model, self.metrics_variables[i].convert(self.cfr.solver.converter))
                     ),
                 )
             )  # model[self.metrics_variables[i]])
         else:
             DisjunctionOrLessMetrics.append(
                 SMTLib.SMT_LT(
                     self.metrics_variables[i],
                     SMTLib.SMT_IntConst(
                         Common.evalForNum(model, self.metrics_variables[i].convert(self.cfr.solver.converter))
                     ),
                 )
             )  # model[self.metrics_variables[i]])
     return SMTLib.SMT_Or(*DisjunctionOrLessMetrics)
开发者ID:srenatus,项目名称:ClaferSMT,代码行数:25,代码来源:npGIAforZ3.py

示例5: getUserInfo

    def getUserInfo(self, username):
        '''
        用户查看自己的基本信息
        :param username:
            微信用户提供的用户名
        :return 'res[]/fail d':
        '''
        if not username:
            return 'fail', errors.NOT_BIND
        r = Db.select('t_user', where="wx_name=$username", vars=locals(), limit=1)  # 查看用户是否已绑定
        if not r:  # 用户还未绑定设备,即用户未注册账号
            return 'fail', errors.NOT_BIND
        u = r[0]  # 取出第一个用户为当前用户
        res = dict()  # 返回结果的字典
        res['id'] = u['id']  # 用户ID
        res['bt'] = Common.secToStr(u['bind_time'])  # 绑定时间
        res['bs'] = '已绑定'  # 绑定状态

        r2 = Db.select('t_user_attribute', what='count(*)', where="user_id=$u['id']", vars=locals())  # 获取登录次数
        if not r2:
            res['count'] = 0  # 登录次数
            res['last'] = Common.secToLast(0)  # 最后一次登录时间
        else:
            res['count'] = r2[0]['count(*)']  # 登录次数
            r3 = Db.select('t_user_attribute', where="user_id=$u['id']", vars=locals(), order="time desc",
                           limit=1)  # 获取最后一个记录
            res['last'] = Common.secToLast(r3[0].time)  # 最后一次登录时间
        return 'success', res
开发者ID:luodongseu,项目名称:findbake,代码行数:28,代码来源:apiManager.py

示例6: get_access_token

    def get_access_token(self, client_id, client_secret):
        response_type = 'code'
        query_string = {}
        if self.provider == "google":
            query_string = (
                {'redirect_uri': self.config['REDIRECT_URI'], 'response_type': response_type,
                 'client_id': client_id,
                 'scope': self.project.config['OAUTH_SCOPE'], 'approval_prompt': 'force', 'access_type': 'offline'})
        elif self.provider == "dropbox":
            query_string = ({'response_type': response_type, 'client_id': client_id})

        params = urllib.parse.urlencode(query_string)
        step1 = self.config['OAUTH_ENDPOINT'] + '?' + params

        Common.launch_browser(step1)

        code = IO.get("Authorization Code:")
        query_string = ({'code': code, 'grant_type': 'authorization_code', 'client_id': client_id, 'client_secret': client_secret})

        if self.provider == "google":
            query_string['scope'] = ''
            query_string['redirect_uri'] = self.config['REDIRECT_URI']

        params = urllib.parse.urlencode(query_string)
        response = Common.webrequest(self.config['TOKEN_ENDPOINT'], {'content-type': 'application/x-www-form-urlencoded;charset=utf-8'}, self.http_intercept, params)
        json_response = json.loads(response)
        self.parse_token(json_response)
        self.project.save("OAUTH", self.oauth)
开发者ID:LucaBongiorni,项目名称:searchgiant_cli,代码行数:28,代码来源:OAuth2Providers.py

示例7: run

	def run(self):
		"""
		"""
		c = Common()

		sleep(3)
		subprocess.call(['/usr/sbin/puppetca', '--sign', '%s.%s' % (c.client_name(),self.domain)])
开发者ID:emphanos,项目名称:fab2puppet,代码行数:7,代码来源:link.py

示例8: Provision

class Provision(object):

    def __init__(self, repolist):
        self.repolist = repolist
        self.yum = YumUtils()
        self.shell = ShellUtils()
        self.com = Common()

    def provision(self):
        # run instack
        self.com.set_user('stack', 'stack')
        self.com.set_repo(['http://trunk.rdoproject.org/centos7/delorean-deps.repo',])
        self._install_pkg(['epel-release', 'instack-undercloud'])
        self._deploy_instack()
        return self._get_instack_ip()

    def is_instack(self):
        if self._get_instack_ip() != '':
            return True

    def _install_pkg(self, pkgs):
        for pkg in pkgs:
            self.yum.yum_install(pkg)

    def _deploy_instack(self):
        return self.shell._exec_shell_cmd('su stack instack-virt-setup')

    def _get_instack_ip(self):
        return self.shell._exec_shell_cmd("arp -n | grep virbr0 | awk '{print $1}'")
开发者ID:matbu,项目名称:os-tripleo-module,代码行数:29,代码来源:provision.py

示例9: verify

 def verify(self):
     self.project.log("transaction", "Verifying all downloaded files...", "highlight", True)
     verification_file = os.path.join(self.project.working_dir, Common.timely_filename("verification", ".csv"))
     errors = 0
     pct = 0
     tot_hashes = 0
     with open(verification_file, 'w') as f:
         f.write("TIME_PROCESSED,REMOTE_FILE,LOCAL_FILE,REMOTE_HASH,LOCAL_HASH,MATCH\n")
         for item in self.verification:
             rh = ""
             match = ""
             lh = Common.hashfile(open(item['local_file'], 'rb'), hashlib.md5())
             lf = item['local_file']
             rf = item['remote_file']
             if 'remote_hash' in item:
                 tot_hashes += 1
                 rh = item['remote_hash']
                 if lh == item['remote_hash']:
                     match = "YES"
                 else:
                     match = "NO"
                     errors += 1
                     self.project.log("exception", "Verification failed for remote file {} and local file {}".format(rf,lf), "critical", True)
             else:
                 rh = "NONE PROVIDED"
                 match = "N/A"
             f.write('"{date}","{rf}","{lf}","{rh}","{lh}","{m}"\n'.format(date=Common.utc_get_datetime_as_string(),rf=rf,lf=lf,rh=rh,lh=lh,m=match))
     pct = ((tot_hashes - errors) / tot_hashes) * 100
     self.project.log("transaction", "Verification of {} items completed with {} errors. ({:.2f}% Success rate)".format(tot_hashes, errors, pct), "highlight", True)
开发者ID:LucaBongiorni,项目名称:searchgiant_cli,代码行数:29,代码来源:GoogleDrive.py

示例10: main

def main():
    with open(os.path.join(SHARE, 'version')) as buf:
        tor_browser_launcher_version = buf.read().strip()

    print _('Tor Browser Launcher')
    print _('By Micah Lee, licensed under MIT')
    print _('version {0}').format(tor_browser_launcher_version)
    print 'https://github.com/micahflee/torbrowser-launcher'

    common = Common(tor_browser_launcher_version)

    # is torbrowser-launcher already running?
    tbl_pid = common.get_pid(common.paths['tbl_bin'], True)
    if tbl_pid:
        print _('Tor Browser Launcher is already running (pid {0}), bringing to front').format(tbl_pid)
        common.bring_window_to_front(tbl_pid)
        sys.exit()

    if '-settings' in sys.argv:
        # settings mode
        app = Settings(common)

    else:
        # launcher mode
        app = Launcher(common)
开发者ID:isislovecruft,项目名称:torbrowser-launcher,代码行数:25,代码来源:__init__.py

示例11: op_substring

def op_substring(whole_string, left_index, right_index):
    (_, whole_mask) = whole_string.getInstanceSort(0)
    whole_i = whole_mask.get(0)
    left_stringID = Common.STRCONS_SUB + str(Common.getStringUID())
    right_stringID = Common.STRCONS_SUB + str(Common.getStringUID())
    Common.string_map[left_stringID] = left_index
    Common.string_map[right_stringID] = right_index
    return IntArg(["Substring$" + whole_i + "$" + left_stringID + "$" + right_stringID])
开发者ID:gsdlab,项目名称:ClaferSMT,代码行数:8,代码来源:String.py

示例12: ConstraintMustDominatesX

 def ConstraintMustDominatesX(self, model):
     """
     Returns a constraint that a new instance has to be better than the instance represented by model in at least one dimension, 
     and better or equal in all the other ones.
     """
     dominationDisjunction = []
     i = 0
     for dominatedByMetric in self.metrics_variables:
         dominationConjunction = []
         j = 0
         if self.metrics_objective_direction[i] == Common.METRICS_MAXIMIZE:
             dominationConjunction.append(
                 SMTLib.SMT_GT(
                     dominatedByMetric,
                     SMTLib.SMT_IntConst(
                         Common.evalForNum(model, dominatedByMetric.convert(self.cfr.solver.converter))
                     ),
                 )
             )
         else:
             dominationConjunction.append(
                 SMTLib.SMT_LT(
                     dominatedByMetric,
                     SMTLib.SMT_IntConst(
                         Common.evalForNum(model, dominatedByMetric.convert(self.cfr.solver.converter))
                     ),
                 )
             )
         for AtLeastEqualInOtherMetric in self.metrics_variables:
             if j != i:
                 if self.metrics_objective_direction[j] == Common.METRICS_MAXIMIZE:
                     dominationConjunction.append(
                         SMTLib.SMT_GE(
                             AtLeastEqualInOtherMetric,
                             SMTLib.SMT_IntConst(
                                 Common.evalForNum(
                                     model, AtLeastEqualInOtherMetric.convert(self.cfr.solver.converter)
                                 )
                             ),
                         )
                     )
                 else:
                     dominationConjunction.append(
                         SMTLib.SMT_LE(
                             AtLeastEqualInOtherMetric,
                             SMTLib.SMT_IntConst(
                                 Common.evalForNum(
                                     model, AtLeastEqualInOtherMetric.convert(self.cfr.solver.converter)
                                 )
                             ),
                         )
                     )
             j = 1 + j
         i = 1 + i
         dominationDisjunction.append(SMTLib.SMT_And(*dominationConjunction))
     constraintDominateX = SMTLib.SMT_Or(*dominationDisjunction)
     return constraintDominateX
开发者ID:srenatus,项目名称:ClaferSMT,代码行数:57,代码来源:npGIAforZ3.py

示例13: _save_file

    def _save_file(self, data, slip, stream=True):
        Common.check_for_pause(self.project)
        savepath = slip.savepath

        path_to_create = os.path.dirname(savepath)  # Just the directory not the filename
        if not os.path.isdir(path_to_create):
            os.makedirs(path_to_create, exist_ok=True)

        self.project.savedata(data, savepath, stream)
        self.project.log("transaction", "Saved file to " + savepath, "info", True)
开发者ID:LucaBongiorni,项目名称:searchgiant_cli,代码行数:10,代码来源:OnlineStorage.py

示例14: _build_fs

 def _build_fs(self, link, cursor = None):
     self.project.log("transaction", "Calculating total dropbox items...", "info", True)
     if cursor:
         response = Common.webrequest(link, self.oauth_provider.get_auth_header(), self.oauth_provider.http_intercept, urllib.parse.urlencode({'cursor': cursor}))
     else:
         response = Common.webrequest(link, self.oauth_provider.get_auth_header(), self.oauth_provider.http_intercept, "")
     json_response = json.loads(response)
     has_more = json_response['has_more']
     cursor = json_response['cursor']
     for item in json_response['entries']:
         self.files.append(item[1])
     if has_more:
         self._build_fs(link, cursor)
开发者ID:LucaBongiorni,项目名称:searchgiant_cli,代码行数:13,代码来源:Dropbox.py

示例15: checkCertificate

	def checkCertificate(self):
		""" Method used to check if the host is already linked on master on not.
		return 'False' or 'True'.
		"""
		c = Common()

		try:
			checkCert = subprocess.Popen(['/usr/sbin/puppetca', '-la'],stdout=subprocess.PIPE)
			checkCertPIPE = checkCert.communicate()[0]
			clientCert = re.search('.*\+.*%s\.%s' % (c.client_name(),self.re_domain), checkCertPIPE)

		except Exception, e:
			print 'error :', e
开发者ID:emphanos,项目名称:fab2puppet,代码行数:13,代码来源:link.py


注:本文中的common.Common类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。