def test_popen(self): keychain = KeyChain(abspath('./files/250000.cer'), abspath('./files/privateKey.pem'), '') cmd = [ 'openssl', 'smime', '-sign', '-signer', keychain.public_cert, '-inkey', keychain.private_key, '-nochain', '-nocerts', '-outform', 'PEM', '-nodetach', '-passin', 'pass:'******'<', abspath('./files/test.xml') ] # '-passin', 'pass:'******'./files/test.xml', encoding="utf-8") as data_file: # data = data_file.read() proc = Popen(' '.join(cmd), shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) pss = keychain.key_password.encode() if keychain.key_password.__len__( ) else "0".encode() out, err = proc.communicate(input=pss) # out, err = proc.communicate() proc.wait() # дождаться выполнения res = proc.communicate() # получить tuple('stdout', 'stderr') var_dump.var_dump(proc, res)
def dump(var, die=True, html=True): """Prints human-readable information about a variable Args: var (mixed): variable to dump die (bool) : exit script. Defaults True html (bool): dump as HTML. Defautls True """ # build resultset filename from caller filename caller = inspect.getouterframes(inspect.currentframe(), 2)[2] print("\n\n=== DEBUG FROM {} (line {})\n".format( caller.filename, caller.lineno)) if html: print('<pre>') var_dump(var) if html: print('</pre>') print("\n=== FIN DEBUG {} (line {})\n".format(caller.filename, caller.lineno)) if die: exit()
def test_balance_request(self): client_order_id = uuid.uuid4() request = BalanceRequest({ "agent_id": 123456, "client_order_id": client_order_id }) var_dump.var_dump(request.map())
def task_delete(task_id): if not current_user.is_authenticated: return is_not_auth() # if False: # abort(404) if request.method == "GET": task = Task.filter(Task.id == task_id).first() if task is None: return abort(404) form = TaskDeleteForm(formdata=request.form, obj=task) content = render_form(form=form, action=url_for("task_delete"), delete=True) return render_content( content, "Вы уверены что хотите удалить - {}?".format(task.title)) if request.method == 'POST': task = Task.get(Task.id == request.form["id"]) var_dump(task) task.delete() flash('Событие <b><em>{}</em></b> успешно удалено'.format(task.title), 'success') return redirect(url_for('task_list'))
def TERIMA_PESAN(op): try: msg = op.message text = msg.text receiver = msg.to sender = msg._from msg_id = msg.id # Jika kita menerima pesan dari grup if msg.toType == 2: var_dump(userTemp) displayName = line.getContact(sender).displayName if text in prohibitedWords: if sender in userTemp: userTemp[sender] = userTemp.get(sender) + 1 # Jika sudah melebihi dari 3, maka akan terkick if userTemp.get(sender) > 3: userKicked.append(sender) line.kickoutFromGroup(receiver, userKicked) line.log( "{} telah terkick dari grup".format(displayName)) userTemp.pop(sender) else: userTemp[sender] = 1 except Exception as e: line.log(str(e))
def RECEIVE_MESSAGE(op): msg = op.message text = msg.text msg_id = msg.id receiver = msg.to sender = msg._from # Check content only text message if msg.contentType == 0: if text == "gid": line.getGroups() var_dump(line.getProfileDetail(os.environ.get("ADMIN_MID"))) else: if config["autoread"]: line.sendChatChecked(sender, msg_id) else: line.sendMessage(sender, text) # Check only group chat if msg.toType == 2: # Get sender contact contact = line.getContact(sender) txt = '[%s] %s' % (contact.displayName, text) # Send a message # line.sendMessage(receiver, 'sender:'+sender+' response:'+text) # Print log line.log(txt)
def test_balance_response(self): client_order_id = uuid.uuid4() response = BalanceResponse({ "status": 0, "clientOrderId": client_order_id, "balance": 1000.0, "processedDT": "2011-07-01T20:38:01.666Z" }) var_dump.var_dump(dict(response))
def weibo(gearman_worker,job): var_dump(job.data) param = json.loads(job.data) keyword = param['keyword'] pages = param['pages'] se = param['se'] res = requests.post(HOST_URL + '/schedule.json', data = {'project':'seCrawler', 'spider':'weiboSpider', 'se': se, 'pages': pages, 'keyword':keyword}) var_dump(res.text) return str("Job added")
def main(): defaultVol = 0.20 # setup random.seed() mixer.init(16000) con = sqlConnection() # subprocess.run(["sudo ip link set can0 up type can bitrate 100000"], shell=True) bus = can.interface.Bus(bustype='socketcan_native', channel='can0') can_filters = [{ "can_id": CAN_SPEAK, "can_mask": 0x7FF, "extended": False }, { "can_id": CAN_SHUTDOWN, "can_mask": 0x7FF, "extended": False }, { "can_id": CAN_BUMP, "can_mask": 0x7FF, "extended": False }] bus.set_filters(can_filters) playSoundFromGroup(con, IDGROUP_STARTUP, defaultVol) # loop while True: msg = bus.recv(0.0) if msg is not None: # print(msg) var_dump(msg) if msg.arbitration_id == CAN_SPEAK: if msg.dlc == 1: playSoundFromGroup(con, msg.data[0], defaultVol) elif msg.dlc > 1: if msg.data[0] == 0: # set volume defaultVol = msg.data[0] / 512 # TODO add saving defaultVol to config file and read it back in later else: d = 0 for i in range(1, msg.dlc): d = d * 256 + msg.data[i] if msg.data[0] == 1: playSoundFromGroup(con, d, defaultVol) else: playSoundFromGroup(con, d, msg.data[0] / 512) elif msg.arbitration_id == CAN_BUMP: channel = playSoundFromGroup(con, IDGROUP_BUMP, defaultVol) elif msg.arbitration_id == CAN_SHUTDOWN: channel = playSoundFromGroup(con, IDGROUP_SHUTDOWN, defaultVol) # while channel.get_busy(): # pass time.sleep(3) subprocess.run("sudo halt", shell=True)
def add(request): if request.method == "POST": form = ProductForm(request.POST) var_dump(request) if form.is_valid(): return redirect('product') else: form = ProductForm() context = {'form': form} return render(request, "pages/products/add.html", context)
def create(self, validated_data): groups_data = validated_data.pop('groups') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() var_dump(groups_data) for group_data in groups_data: group = Group.objects.create(user=user, **group_data) user.groups.add(group) return user
def create(self, validated_data): var_dump(validated_data) groups_data = validated_data.pop('groups') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() var_dump(groups_data) for group_data in groups_data: user.groups.add(group_data) return user
def pushTo(self, remote, branch): self.pull(branch) repo = self.repo repo_heads = repo.heads o = repo.remotes[remote] try: este = o.push(progress=MyProgressPrinter()) print("------") var_dump(list(este)) print(este[0].summary) print("------") except: return "mal" return este[0].summary
def donate_money(request): Configuration.account_id = '819176' Configuration.secret_key = 'live_Rj4b50yCpOzEirnhaHWgSJ_f-t9naP6WBSlAk8WlAss' #Configuration.account_id = '829811' #Configuration.secret_key = 'test_3z2IRsWt9h2FRrKVBy9AaGkeMHt6appEWllT9614G5k' # Configuration.configure('819176', 'test__QoWec5bBgd00kgqy4xnSz245AQk2faiTHjPJN7tkiQ') receipt = Receipt() receipt.customer = {"phone": "79990000000", "email": "*****@*****.**"} receipt.tax_system_code = 1 receipt.items = [ ReceiptItem({ "description": "Пополнения баланса на сумму {}".format(request.POST.get('sum')), "quantity": 1, "amount": { "value": request.POST.get('sum'), "currency": Currency.RUB }, "vat_code": 2, "capture": True }), ] s = {'user': str(request.user)} print(request.user) builder = PaymentRequestBuilder() builder.set_amount({"value": request.POST.get('sum'), "currency": Currency.RUB}) \ .set_confirmation({"type": ConfirmationType.REDIRECT, "return_url": "https://privereda1.ru"}) \ .set_capture(True) \ .set_description("Заказ №72") \ .set_metadata({"user": int(request.user.id)}) \ .set_receipt(receipt) request = builder.build() # Можно что-то поменять, если нужно res = Payment.create(request) print(res.json()) a = json.loads(res.json()) print(a['confirmation']['confirmation_url']) var_dump.var_dump(res) # print(request.POST) # print(request.POST.get('sum')) return redirect(a['confirmation']['confirmation_url'])
def test_all(self): cakey = self.createKeyPair(crypto.TYPE_RSA, 2048) careq = self.createCertRequest(cakey, CN='Certificate Authority') cacert = self.createCertificate(careq, (careq, cakey), 123456789, (0, 60 * 60 * 24 * 365)) # one year with open('clientkey.key', 'wb') as pem: pem.write( crypto.dump_privatekey(crypto.FILETYPE_PEM, cakey, 'aes256', '12345678'.encode())) with open('clientcert.crt', 'wb') as cert: cert.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cacert)) with open('clientreq.csr', 'wb') as req: req.write( crypto.dump_certificate_request(crypto.FILETYPE_PEM, careq)) signature = self.createSignature('clientreq.csr') with open('signature.txt', 'wb') as sign: sign.write(signature.encode('utf-8')) # crypto.verify() certobj = cacert # crypto.load_certificate(crypto.FILETYPE_ASN1, cacert) issuer = certobj.get_issuer() subject = certobj.get_subject() cryptCert = certobj.to_cryptography() certDetails = { "SerialNumber": certobj.get_serial_number(), "Organization": subject.CN, "Signature": signature.encode(), "SignatureAlgorithm": certobj.get_signature_algorithm(), "CertificatePEM": crypto.dump_certificate(crypto.FILETYPE_PEM, certobj), "SubjectPublicKeyPEM": crypto.dump_publickey(crypto.FILETYPE_PEM, certobj.get_pubkey()), "Version": certobj.get_version() } var_dump.var_dump(certDetails)
def test_xml2object(self): xml_string = """ <balanceResponse clientOrderId="12345" status="0" processedDT="2011-07-01T20:38:01.666Z" balance="1000.00"/> """ python_object = XMLHelper.xml_to_object(xml_string) var_dump.var_dump(xml_string) var_dump.var_dump(python_object) response = BalanceResponse(python_object['balanceResponse']) print(dict(response))
def push_command(self, command, offset=0) -> int: if offset == -1: max = self.num_commands() - 1 if self.num_commands() - 1 > 0 else 0 command.offset = random.randint(0, max) # deb(f"push {command} @ {command.offset} ({self.get_operand_at(command.offset)})") else: command.offset = offset if offset else self._offset + 1 self._command_pipeline.append(command) self._offset = command.offset if ip_debug: deb(f'{self._offset:04d} {command} ({len(assember)})') var_dump(self._command_pipeline) return self._offset
def index(): if current_user.is_authenticated: tasks = Task.filter(Task.user == current_user.id, Task.date == datetime.today().strftime(dateformat)) var_dump(tasks) var_dump(datetime.today()) content = render_tasks_list_as_table(tasks) title = "Список дел на сегодня" else: content = render_template("_index_anonimus.html") title = "Добро пожаловать" return render_content(content, title)
def logging_processing(): finduser = collection.find_one({'email': request.form['email']}) if finduser: if security.check_password(finduser['password'], request.form['password']) is True: var_dump(finduser['_id']) print(finduser['role']) user_obj = User(str(finduser['_id'])) login_user(user_obj) session['username'] = request.form['email'] return redirect(url_for('main_page.main')) else: flash('please check your password and try again', 'login') return redirect(url_for('login.login')) else: flash('please check your email and try again', 'login') return redirect(url_for('login.login'))
def print_files(): # take the second element for sort def take_second(elem): return elem[1] while True: time.sleep(1) parts = psutil.disk_partitions() hdds = {} for part in parts: hdd = psutil.disk_usage(part.mountpoint) hdds[part.mountpoint] = hdd.free # hdds = sorted(hdds, key=hdds.get, reverse=True) free = hdds.values() sorted_list = sorted(hdds, key=take_second) var_dump(sorted_list) logging.debug(f'{free}')
def test_decrypt(self): # with open("./files/test.pkcs", encoding="utf-8") as pkcs_file: # pkcs = pkcs_file.read() pkcs = OpenSSLHelper.from_file('./files/test.pkcs') # print(pkcs) output = OpenSSLHelper.decrypt_pkcs7( pkcs, cert=abspath('./files/deposit.cer')) # print(output) # var_dump.var_dump(str(output, "utf-8", 'ignore')) # var_dump.var_dump(output.decode("utf-8")) # var_dump.var_dump(output) parser = etree.XMLParser(recover=True, encoding='utf-8') root = etree.fromstring(output, parser) var_dump.var_dump(root.attrib) assert output is not None
def test_object2xml(self): client_order_id = uuid.uuid4() request = BalanceRequest({ "agent_id": 123456, "client_order_id": client_order_id }) python_object = request.map() # python_object = {"balanceRequest": { # "agentId": "123", # "clientOrderId": "12345", # "requestDT": "2011-07-01T20:38:00.000Z" # }} xml_string = XMLHelper.object_to_xml(python_object) var_dump.var_dump(python_object) var_dump.var_dump(xml_string)
def main(): global connection if socketfile: try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(socketfile) os.chmod(socketfile, 666) sock.listen(1) while True: connection, client_address = sock.accept() log_message(tosyslog, "New incoming connection...") try: connection, client_address = sock.accept() log_message(True, "New incoming connection...") start = handshake() if debug: var_dump(data) while True: data = connection.recv(262144) if data: b = io.BytesIO(start + data) if debug: var_dump(b.read()) for frame in framestream.reader(b): parse_frame(frame) else: log_message(tosyslog, "error error!!!") finally: # Clean up the connection log_message(tosyslog, "connection lost") connection.close() finally: log_message(tosyslog, "Closing socket") sock.close() os.unlink(socketfile) if tosyslog: syslog.closelog() elif tapfile: log_message(tosyslog, "Reading data from " + tapfile) for frame in framestream.reader(open(tapfile, "rb")): parse_frame(frame)
def update(self, instance,validated_data): groups_data = validated_data.pop('groups') password = validated_data.pop('password') instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.username) instance.set_password(password) instance.save() for group_data in groups_data: if 'id' in group_data.keys(): if Group.objects.filter(id=group_data["id"]).exists(): group = Group.objects.get(id=group_data["id"]) var_dump(group) group.name=group_data["name"] group.save() instance.groups.add(group) else: continue else: group = Group.objects.create(user=instance, **group_data) user.groups.add(group) return instance
def c_ore(ename, eqty=1, cname='default'): global r_table global m_table global e_table global t_table tl = 0 if ename == "FUEL": tl = 1 print("====================") print("c_core:", ename, eqty) relmnts = next(k['elmnt'] for k in r_table if k['name'] == ename) var_dump(relmnts) if ename != "FUEL": t_table.append((ename, eqty)) var_dump(t_table) for rname, rqty in relmnts.items(): if rname == "ORE": print(rname, "needs", rname, eqty) if ename in m_table: m_table[ename].append(t_table) else: m_table[ename] = [] m_table[ename].append(t_table) else: #print(ename, "needs", rname, rqty) #for i in range(rqty): c_ore(rname, rqty, ename) if tl == 1: t_table = []
def create(self, validated_data): product_categories = json.loads(validated_data['productCategorie']) product_images = validated_data.pop('productImage') validated_data['user']=self.context['request'].user for product_categorie in product_categories: if 'id' in product_categorie.keys(): if ProductCategorie.objects.filter(id=product_categorie["id"]).exists(): productCategorie = ProductCategorie.objects.get(id=product_categorie["id"]) var_dump(productCategorie) validated_data['productCategorie']=productCategorie else: continue else: productCategorie = ProductCategorie.objects.create(**product_categorie) validated_data['productCategorie']=productCategorie product = Product.objects.create(**validated_data) product.save() for product_image in product_images: productImage1 = ProductImage.objects.create(product=product, imageLink=product_image) return product
def main(): defaultVol = 0.20 # setup random.seed() mixer.init(16000) con = sqlConnection() playSoundFromGroup(con, IDGROUP_STARTUP, defaultVol) # loop while True: try: n = input('Input:') if n == 'q' or n == 'Q': channel = playSoundFromGroup(con, IDGROUP_SHUTDOWN, defaultVol) # while channel.get_busy(): # pass time.sleep(3) sys.exit() if n.startswith('v') or n.startswith('V'): n = int(n[1:]) # print(n) if n >= 0 and n <= 255: defaultVol = int(n / 512 * 100) / 100 var_dump(defaultVol) sayString("Volume set to {}.".format(defaultVol), defaultVol) else: n = int(n) # print(n) if n: playSoundFromGroup(con, n, defaultVol) except ValueError: print("Not a number")
def git(): #repo = Repo('/Users/Seca/Public/wworks/2016/FIAT/fca/VVV/www/mitsubishi/htdocs') repo = Repo('/Users/Seca/Public/wworks/test/polemica/polemica/cmks/cms') #o = repo.remotes.origin #var_dump(list(repo.remotes)) print("uno") var_dump(repo.remotes.heroku) var_dump(list(repo.refs)) try: #o = repo.remotes.origin #o = repo.remotes.origin o = repo.remotes.heroku #var_dump(list(repo.remotes)) for fetch_info in o.pull(repo.refs[0], progress=MyProgressPrinter()): print("Updated %s to %s" % (fetch_info.ref, fetch_info.commit)) #tmp = o.pull() except: return "mal" #print(list(o)) return "bien"
arr = [1,2,3,4,5,6,7] while len(arr) != 1: i = 0 j = i +1 l = len(arr) k = 0 print("Durchlaufnummer: "), z print("Anzahl der elemte: "), l while i < l: if j % x == 0: print("Ausgeschieden"), arr[i] del(arr[i]) k = k + 1 x = m j = 0 else: print i var_dump(arr) print arr[i] if i == l -1: l = len(arr) r = l % m print("Letztes Element in diesem Druchlauf"), r if r != 0: x = m -r print("Wert"), x i = i + 1 j = j + 1 z = z + 1
def promote(): with settings(warn_only=True): result = local('python xx.py', capture=True) var_dump(result) if result.failed and not confirm("Tests failed. Continue anyway?"): abort("Aborting at user request.")
import yaml import sys import var_dump reload(sys) sys.setdefaultencoding("utf-8") fp = open("jiguang-docs/jpush/mkdocs.yml") document = fp.read() yml_doc = yaml.load(document) var_dump.var_dump(yaml.load(document))
def highlight_wishlist(self, product_ids, *args, **kwargs): var_dump(product_ids) cr, uid, context, pool = request.cr, request.uid, request.context, request.registry values = pool['website.wishlist'].get_wishlist_product_ids(cr, uid, product_ids, context=context) return values
import cPickle fo = open(file, "rb") dict = cPickle.load(fo) fo.close() return dict if __name__ == "__main__": """ train = [] for i in range(1,6): data = unpickle('cifar-10-batches-py/data_batch_' + str(i)) data_set = (data['data'], data['labels']) #var_dump.var_dump(train) train.extend(data_set) var_dump.var_dump(train) """ """ var_dump.var_dump(train_set['data'][0]) print len(train_set['data'][0]) var_dump.var_dump(train_set['labels'][0]) print len(train_set['labels'][0]) """ test_set = unpickle("data/test_set_gray.pkl") var_dump.var_dump(test_set)
def main(): parser = argparse.ArgumentParser( description='Send email when new pictures are posted to Flickr.') parser.add_argument('--user_add_interactive', '-i', action='store_true', help='add a user interactively based on OAuth') parser.add_argument('--user_add', '-a', action='store_true', help='prepare adding a user based on OAuth') parser.add_argument('--user_auth_verifier', '-b', action='store', help='finish adding the user based on OAuth') parser.add_argument('--user_old_auth', '-o', action='store', help='add a user based on a pre-OAuth token') parser.add_argument('--user_delete', '-d', action='store', help='remove a user') parser.add_argument('--since_days', '-s', action='store', type=int, help='override default period (last execution or 1 day)') parser.add_argument('--quiet', '-q', action='store_true', help='no output for normal operation') parser.add_argument('--verbose', '-v', action='store_true', help='print extra data') parser.add_argument('--dry_run', '-n', action='store_true', help='don\'t send email') parser.add_argument('--smtp_debug', action='store_true', help='print smtp debug messages') args = parser.parse_args() state = ConfigParser.RawConfigParser({ 'last_date': int(time.time() - 24 * 60 * 60), 'smtp_from': '*****@*****.**', 'smtp_to': '*****@*****.**', 'smtp_cc': '', 'smtp_bcc': '', 'smtp_subject': 'New photos', 'smtp_port': 25, 'smtp_server': 'localhost', 'smtp_tls': 'false', }) state.add_section('main') state.read("state.ini") if args.since_days: state.set('main', 'last_date', int(time.time() - args.since_days * 24 * 60 * 60)) # set up flickr_api app credentials try: flickr_api.set_keys(api_key=state.get('main', 'api_key'), api_secret=state.get('main', 'api_secret')) except ConfigParser.NoOptionError: state.set('main', 'api_key', 'API_KEY') state.set('main', 'api_secret', 'API_SECRET') write_state(state) exit("Please fill in the api_key and api_secret in state.ini") if args.user_add_interactive: a = flickr_api.auth.AuthHandler() print "Open this URL in a web browser and authorize", a.get_authorization_url("read") oauth_token = raw_input("Paste the oauth_verifier parameter here: ") a.set_verifier(oauth_token) flickr_api.set_auth_handler(a) user = flickr_api.test.login() print "Authorized user:"******"users/" + user.username) return if args.user_add: a = flickr_api.auth.AuthHandler() print "Open this URL in a web browser and authorize", a.get_authorization_url("read") print "Then run the command again with --user_auth_verifier <oauth_verifier> " \ "to finish authorizing" if not os.path.exists('tmp_users'): os.mkdir('tmp_users') # can't use a.save() because that method requires an access_token # and all we have is a request_token with open("tmp_users/" + a.request_token.key, "w") as f: f.write("\n".join([a.request_token.key, a.request_token.secret])) return if args.user_auth_verifier: # we don't know which of the temp users matches the verifier, try each of them in turn for f in glob.glob("tmp_users/*"): try: with open(f, "r") as f1: request_token = f1.read().split("\n") a = flickr_api.auth.AuthHandler( request_token_key=request_token[0], request_token_secret=request_token[1] ) # this will throw an exception if the verifier doesn't match the request_token a.set_verifier(args.user_auth_verifier) flickr_api.set_auth_handler(a) user = flickr_api.test.login() print "Authorized user:"******"users/" + user.username) os.remove(f) return except: # continue trying pass exit("No matching pre-authorization found") if args.user_delete: try: os.remove('users/' + args.user_delete) except: print "Could not remove the user" raise return if args.user_old_auth: # handle old-style auth directly, since flickr_api only handled OAuth m = hashlib.md5() m.update(state.get('main', 'api_secret')) m.update('api_key') m.update(state.get('main', 'api_key')) m.update('auth_token') m.update(args.user_old_auth) m.update('format') m.update('json') m.update('method') m.update('flickr.auth.oauth.getAccessToken') m.update('nojsoncallback') m.update('1') url = "https://api.flickr.com/services/rest/" \ "?method=flickr.auth.oauth.getAccessToken" \ "&api_key={0}" \ "&auth_token={1}" \ "&format=json" \ "&nojsoncallback=1" \ "&api_sig={2}".format( state.get('main', 'api_key'), args.user_old_auth, m.hexdigest()) resp = urllib2.urlopen(url) response = json.load(resp) if response['stat'] != 'ok': exit("Request failed, Flickr responded: " + response['message']) access_token = response['auth']['access_token'] # exchange old-style auth token for OAuth credentials; # Flickr disables the old token immediately a = flickr_api.auth.AuthHandler( access_token_key=str(access_token['oauth_token']), access_token_secret=str(access_token['oauth_token_secret'])) flickr_api.set_auth_handler(a) user = flickr_api.test.login() print "Authorized user:"******"users/" + user.username) return # get photos and send email user_photos = {} user_photos_by_taken = {} users = {} num_photos = 0 user_profiles = glob.glob("users/*") if not len(user_profiles): exit("Please authorize users (no registered users yet)") for f in user_profiles: flickr_api.set_auth_handler(flickr_api.auth.AuthHandler.load(f)) username = os.path.basename(f) last_date = state.getint('main', 'last_date') photos = flickr_api.Photo.recentlyUpdated(min_date=last_date, extras=['url_m', 'url_o', 'description', 'date_taken']) if photos.data: info = flickr_api.test.login().getInfo() info['buddyicon'] = "http://farm{iconfarm}.staticflickr.com/{iconserver}/" \ "buddyicons/{nsid}.jpg" \ .format(**info) photos.data = list( filter(lambda x: x.ispublic or x.isfriend or x.isfamily, photos.data)) for photo in photos.data: # noinspection PyProtectedMember photo._set_properties( flickr_url="https://www.flickr.com/photos/{0}/{1}/".format(username, photo.id) ) if args.verbose: print var_dump(photos) num_photos += len(photos.data) users[username] = info user_photos[username] = photos.data user_photos_by_taken[username] = sorted(photos.data, key=lambda x: x.datetaken) state.set('main', 'last_date', int(time.time())) if not args.dry_run: write_state(state) if len(users) == 0 or num_photos == 0: if not args.quiet: print "No new content" return env = jinja2.Environment(loader=jinja2.FileSystemLoader('.')) template = env.get_template('email.jinja2') text = template.render(user_photos=user_photos, users=users, user_photos_by_taken=user_photos_by_taken) if args.verbose: print text if not args.dry_run: try: charset.add_charset('utf-8', charset.QP, charset.QP) msg = MIMEText(text, 'html', 'utf8') msg['From'] = state.get('main', 'smtp_from') to = get_state_array(state, 'main', 'smtp_to') cc = get_state_array(state, 'main', 'smtp_cc') bcc = get_state_array(state, 'main', 'smtp_bcc') msg['To'] = ",".join(to) msg['Cc'] = ",".join(cc) # msg['Bcc'] = ",".join(bcc) # Add BCC to sendmail, but not headers msg['Subject'] = state.get('main', 'smtp_subject') s = smtplib.SMTP() s.connect(state.get('main', 'smtp_server'), state.getint('main', 'smtp_port')) if args.smtp_debug: s.set_debuglevel(1) s.ehlo() if state.getboolean('main', 'smtp_tls'): s.starttls() if state.has_option('main', 'smtp_user') and state.has_option('main', 'smtp_password'): s.login(state.get('main', 'smtp_user'), state.get('main', 'smtp_password')) s.sendmail(state.get('main', 'smtp_from'), to + cc + bcc, msg.as_string()) s.quit() except: print "Can't send email, you can set SMTP options in state.ini: " \ "set smtp_tls=true, smtp_user, smtp_pass for encrypted and authenticated SMTP" raise if not args.quiet: print "Sent email containing {0} photos from {1} users".format( len([item for sublist in user_photos.values() for item in sublist]), len(users) )
import yaml import sys import var_dump reload(sys) sys.setdefaultencoding( "utf-8" ) fp=open("jiguang-docs/jpush/mkdocs.yml") document = fp.read(); yml_doc=yaml.load(document) var_dump.var_dump(yaml.load(document))
def main(): collector = Collector() var_dump(collector.get_instance_bill()) var_dump(collector.get_volume_bill())
import praw from var_dump import var_dump print "Initializing PRAW and User Agent" user_agent = ("the_nano_bot/0.1 by nanodano") r = praw.Reddit(user_agent=user_agent) print "Loading User" user_name = "nanodano" user = r.get_redditor(user_name) thing_limit = 200 gen = user.get_comments(limit=thing_limit) karma_by_subreddit = {} for thing in gen: subreddit = thing.subreddit.display_name karma_by_subreddit[subreddit] = (karma_by_subreddit.get(subreddit, 0) + thing.ups - thing.downs) var_dump(karma_by_subreddit)