I have been tring to register number on Yowsup, but I got old_version error.
Here is my env_s40.py file:
from .env import YowsupEnv
import hashlib
class S40YowsupEnv(YowsupEnv):
_VERSION = "2.16.11"
_OS_NAME= "S40"
_OS_VERSION = "14.26"
_DEVICE_NAME = "302"
_MANUFACTURER = "Nokia"
_TOKEN_STRING = "PdA2DJyKoUrwLw1Bg6EIhzh502dF9noR9uFCllGk1478194306452"
_AXOLOTL = True
def getVersion(self):
return self.__class__._VERSION
def getOSName(self):
return self.__class__._OS_NAME
def getOSVersion(self):
return self.__class__._OS_VERSION
def getDeviceName(self):
return self.__class__._DEVICE_NAME
def getManufacturer(self):
return self.__class__._MANUFACTURER
def isAxolotlEnabled(self):
return self.__class__._AXOLOTL
def getToken(self, phoneNumber):
return hashlib.md5(self.__class__._TOKEN_STRING.format(phone = phoneNumber).encode()).hexdigest()
def getUserAgent(self):
return self.__class__._USERAGENT_STRING.format(
WHATSAPP_VERSION = self.getVersion(),
OS_NAME = self.getOSName() + "Version",
OS_VERSION = self.getOSVersion(),
DEVICE_NAME = self.getDeviceName(),
MANUFACTURER = self.getManufacturer()
)
And I got
DEBUG:yowsup.env.env:Current env changed to s40
yowsup-cli v2.0.15
yowsup v2.5.0
Copyright (c) 2012-2016 Tarek Galal
http://www.openwhatsapp.org
This software is provided free of charge. Copying and redistribution is
encouraged.
If you appreciate this software and you would like to support future
development please consider donating:
http://openwhatsapp.org/yowsup/donate
DEBUG:yowsup.common.http.warequest:{'Accept': 'text/json', 'User-Agent': 'WhatsApp/2.16.7 S40Version/14.26 Device/Nokia-302'}
DEBUG:yowsup.common.http.warequest:cc=255&in=716343889&lc=GB&lg=en&sim_mcc=640&sim_mnc=002&mcc=640&mnc=002&method=sms&mistyped=6&network_radio_type=1&simnum=1&s=&copiedrc=1&hasinrc=1&rcmatch=1&pid=6444&rchash=5b9d791a39befe77a165a669cac86d3fa12c7390536885aa43555059748747e9&anhash=Q%90%1D%2Am%BA%EF%1C%8E%E1%84%94%E4%93%C6%DD%AB%B55E&extexist=1&extstate=1&token=fe234b378d154c6dcca365d264ed96cf&id=%A0%3B%2B%C3%B6%A2%F9%04%CB%FA%AE%887%7FY%F7E%E6%D3%17
DEBUG:yowsup.common.http.warequest:Opening connection to v.whatsapp.net
DEBUG:yowsup.common.http.warequest:Sending GET request to /v2/code?cc=255&in=716343889&lc=GB&lg=en&sim_mcc=640&sim_mnc=002&mcc=640&mnc=002&method=sms&mistyped=6&network_radio_type=1&simnum=1&s=&copiedrc=1&hasinrc=1&rcmatch=1&pid=6444&rchash=5b9d791a39befe77a165a669cac86d3fa12c7390536885aa43555059748747e9&anhash=Q%90%1D%2Am%BA%EF%1C%8E%E1%84%94%E4%93%C6%DD%AB%B55E&extexist=1&extstate=1&token=fe234b378d154c6dcca365d264ed96cf&id=%A0%3B%2B%C3%B6%A2%F9%04%CB%FA%AE%887%7FY%F7E%E6%D3%17
INFO:yowsup.common.http.warequest:{"login":"255716MYNUMBER","status":"fail","reason":"old_version"}
status: fail
reason: old_version
login: 255716MYNUMBER
How can I fix that?
Probably a bad question for so.
But a short google gave:
https://github.com/tgalal/yowsup/issues/1861#issuecomment-264792842
There are also other discussions regarding a similar issue.
in the env_android file change the version to the most current one (whatsapp):
Related
While following the installation process for Saleor headless e-commerce, the Python Weasyprint package fails to load the gobject-2.0.0 dependency which I have already installed on my machine using Macport.
Below is the source code showing where the error is emitting from after starting the Django server. The file holds utility functions for generating invoices for the plugin file.
utils.py
import os
import re
from datetime import datetime
from decimal import Decimal
import pytz
from django.conf import settings
from django.template.loader import get_template
from prices import Money
from weasyprint import HTML # <----------- This what is emitting the error because the
# package can't find the needed dependency.
from ...giftcard import GiftCardEvents
from ...giftcard.models import GiftCardEvent
from ...invoice.models import Invoice
MAX_PRODUCTS_WITH_TABLE = 3
MAX_PRODUCTS_WITHOUT_TABLE = 4
MAX_PRODUCTS_PER_PAGE = 13
def make_full_invoice_number(number=None, month=None, year=None):
now = datetime.now()
current_month = int(now.strftime("%m"))
current_year = int(now.strftime("%Y"))
month_and_year = now.strftime("%m/%Y")
if month == current_month and year == current_year:
new_number = (number or 0) + 1
return f"{new_number}/{month_and_year}"
return f"1/{month_and_year}"
def parse_invoice_dates(number: str):
match = re.match(r"^(\d+)\/(\d+)\/(\d+)", number)
if not match:
raise ValueError("Unrecognized invoice number format")
return int(match.group(1)), int(match.group(2)), int(match.group(3))
def generate_invoice_number():
last_invoice = Invoice.objects.filter(number__isnull=False).last()
if not last_invoice or not last_invoice.number:
return make_full_invoice_number()
try:
number, month, year = parse_invoice_dates(last_invoice.number)
return make_full_invoice_number(number, month, year)
except (IndexError, ValueError, AttributeError):
return make_full_invoice_number()
def chunk_products(products, product_limit):
"""Split products to list of chunks.
Each chunk represents products per page, product_limit defines chunk size.
"""
chunks = []
for i in range(0, len(products), product_limit):
limit = i + product_limit
chunks.append(products[i:limit])
return chunks
def get_product_limit_first_page(products):
if len(products) < MAX_PRODUCTS_WITHOUT_TABLE:
return MAX_PRODUCTS_WITH_TABLE
return MAX_PRODUCTS_WITHOUT_TABLE
def get_gift_cards_payment_amount(order):
events = GiftCardEvent.objects.filter(
type=GiftCardEvents.USED_IN_ORDER, order_id=order.id
)
total_paid = Decimal(0)
for event in events:
balance = event.parameters["balance"]
total_paid += Decimal(balance["old_current_balance"]) - Decimal(
balance["current_balance"]
)
return Money(total_paid, order.currency)
def generate_invoice_pdf(invoice): # <------- The function calling the HTML module from
# weasyprint
font_path = os.path.join(
settings.PROJECT_ROOT, "templates", "invoices", "inter.ttf"
)
all_products = invoice.order.lines.all()
product_limit_first_page = get_product_limit_first_page(all_products)
products_first_page = all_products[:product_limit_first_page]
rest_of_products = chunk_products(
all_products[product_limit_first_page:], MAX_PRODUCTS_PER_PAGE
)
order = invoice.order
gift_cards_payment = get_gift_cards_payment_amount(order)
creation_date = datetime.now(tz=pytz.utc)
rendered_template = get_template("invoices/invoice.html").render(
{
"invoice": invoice,
"creation_date": creation_date.strftime("%d %b %Y"),
"order": order,
"gift_cards_payment": gift_cards_payment,
"font_path": f"file://{font_path}",
"products_first_page": products_first_page,
"rest_of_products": rest_of_products,
}
)
return HTML(string=rendered_template).write_pdf(), creation_date
plugins.py
from typing import Any, Optional
from uuid import uuid4
from django.core.files.base import ContentFile
from django.utils.text import slugify
from ...core import JobStatus
from ...invoice.models import Invoice
from ...order.models import Order
from ..base_plugin import BasePlugin
from .utils import generate_invoice_number, generate_invoice_pdf
class InvoicingPlugin(BasePlugin):
PLUGIN_ID = "mirumee.invoicing"
PLUGIN_NAME = "Invoicing"
DEFAULT_ACTIVE = True
PLUGIN_DESCRIPTION = "Built-in saleor plugin that handles invoice creation."
CONFIGURATION_PER_CHANNEL = False
def invoice_request(
self,
order: "Order",
invoice: "Invoice",
number: Optional[str],
previous_value: Any,
) -> Any:
invoice_number = generate_invoice_number()
invoice.update_invoice(number=invoice_number)
file_content, creation_date = generate_invoice_pdf(invoice)
invoice.created = creation_date
slugified_invoice_number = slugify(invoice_number)
invoice.invoice_file.save(
f"invoice-{slugified_invoice_number}-order-{order.id}-{uuid4()}.pdf",
ContentFile(file_content), # type: ignore
)
invoice.status = JobStatus.SUCCESS
invoice.save(
update_fields=[
"created_at",
"number",
"invoice_file",
"status",
"updated_at",
]
)
return invoice
To fix the issue, I followed this instruction of creating a symlink which I did and pointed to it in the path environment of my machine yet it didn't fix the issue. Does that mean that Django isn't checking for the depenecy using the path environment?
It's also worth noting that an installation of Python and weasyprint using Homebrew would fix the issue but I don't use home because I'm MacOS Catalina 10.15 which isn't supported anymore thus the version for it is unstable to use.
I know the dependency is on my machine but it's been difficult to point to it? What am I doing wrong?
I've been on this for days!
After many days, it turned out this is a normal issue faced when using the Python Weasyprint package. This occurs when you install both Python and the required system dependencies using different installers. In my case, I used a system installer for Python and Macport installer for the dependencies and that's what caused the issue. Fortunately, answers already exist to solve the issue but I found this one particularly useful.
Would really appreciate any help on this error. I've tried several things and reviewed the contracts for VRF, but I can't seem to figure it out. All the other threads seem to solve it by moving their file, but mine is in the correct place. Please let me know if I can provide anything else.
Is it possible I'm pulling from the wrong address in my .yaml file?
Here is my bronwie-config.yaml:
Here is my deploy script:
from brownie import(network, config, accounts, MockV3Aggregator, VRFCoordinatorMock, LinkToken, Contract)
from web3 import Web3
FORKED_LOCAL_ENVIRONMENTS = ['mainnet-fork-dev']
LOCAL_BLOCKCHAIN_ENVIRONMENTS = ['development','ganache-local']
def get_account(index = None, id = None):
if index:
return accounts[index]
if id:
return accounts.load(id)
if network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS or network.show_active() in FORKED_LOCAL_ENVIRONMENTS:
return accounts[0]
return accounts.add(config['wallets']['from_key'])
contract_to_mock = {
'eth_usd_price_feed': MockV3Aggregator, 'vrf_coordinator': VRFCoordinatorMock, 'link_token': LinkToken
}
def get_contract(contract_name):
'''This function will grab the contract addresses from brownie config if defined.
Otherwise, it will deply a mock version of that contract, and retrun that mock contract.
Args:
contract_name (string)
returns:
brownie.network.contract.ProjectContract: the most recently deployed version of
'''
contract_type = contract_to_mock[contract_name]
if network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS:
if len(contract_type) <= 0:
deploy_mocks()
contract = contract_type[-1]
#MockV3Aggregator[-1]
else:
contract_address = config['networks'][network.show_active()][contract_name]
contract = Contract.from_abi(contract_type._name, contract_address, contract_type.abi)
#MockV3Aggregator.abi
return contract
DECIMALS = 8
INITIAL_VALUE = 200000000000
def deploy_mocks(decimals= DECIMALS, initial_value= INITIAL_VALUE):
account = get_account()
MockV3Aggregator.deploy(decimals, initial_value, {'from':account})
link_token = LinkToken.deploy({'from':account})
VRFCoordinatorMock.deploy(link_token.address,{'from':account})
print('deployed')
Directory:
You have used VRFConsumerBase version 1 and added address of version 2 in .yaml file. VRF_Coordinator address in brownie-config.yaml for version 1 must be taken from here.
Tried accessing the OpenAPI example - Explain code
But it shows error as -
InvalidRequestError: Engine not found
enter code response = openai.Completion.create(
engine="code-davinci-002",
prompt="class Log:\n def __init__(self, path):\n dirname = os.path.dirname(path)\n os.makedirs(dirname, exist_ok=True)\n f = open(path, \"a+\")\n\n # Check that the file is newline-terminated\n size = os.path.getsize(path)\n if size > 0:\n f.seek(size - 1)\n end = f.read(1)\n if end != \"\\n\":\n f.write(\"\\n\")\n self.f = f\n self.path = path\n\n def log(self, event):\n event[\"_event_id\"] = str(uuid.uuid4())\n json.dump(event, self.f)\n self.f.write(\"\\n\")\n\n def state(self):\n state = {\"complete\": set(), \"last\": None}\n for line in open(self.path):\n event = json.loads(line)\n if event[\"type\"] == \"submit\" and event[\"success\"]:\n state[\"complete\"].add(event[\"id\"])\n state[\"last\"] = event\n return state\n\n\"\"\"\nHere's what the above class is doing:\n1.",
temperature=0,
max_tokens=64,
top_p=1.0,
frequency_penalty=0.0,
presence_penalty=0.0,
stop=["\"\"\""]
)
I've been trying to access the engine named code-davinci-002 which is a private beta version engine. So without access it's not possible to access the engine. It seems only the GPT-3 models are of public usage. We need to need to join the OpenAI Codex Private Beta Waitlist in order to access Codex models through API.
Please note that your code is not very readable.
However, from the given error, I think it has to do with the missing colon : in the engine name.
Change this line from:
engine="code-davinci-002",
to
engine="code-davinci:002",
If you are using a finetuned model instead of an engine, you'd want to use model= instead of engine=.
response = openai.Completion.create(
model="<finetuned model>",
prompt=
Trying to revive a PyUNO sample script called Wavelet to learn how LO works nowadays and get re-started. Since LibreOffice & UNO changed a bit from the script's creation time I am running into problems.
Managed to get the desktop object. Now I want to retrieve the open document's component. How do I achieve this properly? The desktop.getCurrentComponent() call returns None.
LibreOffice version: 6.4.6.2.
System: Ubuntu MATE 20.04 x86_64.
The code follows:
#!/usr/bin/python3
def TestWave(event):
wavelet = Wavelet(XSCRIPTCONTEXT)
wavelet.trigger( () )
import uno
import unohelper
import string
from com.sun.star.task import XJobExecutor
class Wavelet( unohelper.Base, XJobExecutor ):
def __init__( self, ctx ):
self.ctx = ctx
def trigger( self, args ):
desktop = self.ctx.ServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", self.ctx )
doc = desktop.getCurrentComponent()
print('doc:', doc)
#try:
search = doc.createSearchDescriptor()
search.SearchRegularExpression = True
search.SearchString = "\\<(k|s|v|z|o|u|i|a) "
found = doc.findFirst( search )
while found:
print("found:", found.String)
found.String = string.replace( found.String, " ", u"\xa0" )
found = doc.findNext( found.End, search)
#except:
# pass
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
Wavelet,
"name.vojta.openoffice.Wavelet",
("com.sun.star.task.Job",),)
if __name__ == "__main__":
import os
# Start OpenOffice.org, listen for connections and open testing document
os.system( "loffice '--accept=socket,host=localhost,port=2002;urp;' --writer ./WaveletTest.odt &" )
# Get local context info
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext )
ctx = None
# Wait until the OO.o starts and connection is established
while ctx == None:
try:
ctx = resolver.resolve(
"uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
except:
pass
# Trigger our job
wavelet = Wavelet( ctx )
wavelet.trigger( () )
Output:
doc: None
Traceback (most recent call last):
File "./wavelet.py", line 62, in <module>
wavelet.trigger( () )
File "./wavelet.py", line 24, in trigger
search = doc.createSearchDescriptor()
AttributeError: 'NoneType' object has no attribute 'createSearchDescriptor'
Edit 1
Cross posted at the following address:
https://ask.libreoffice.org/en/question/283785/why-does-desktopgetcurrentcomponent-return-none-in-pyuno/
Try without giving desktop.getCurrentComponent() a variable, so erase doc =. I remember I had that problem, but did not understand why it was doing it. All I remember is that not naming it made my code work. That is the only advice I can give you.
Tried to wait until the document component becomes available. And it worked:
doc = None
while doc is None:
doc = desktop.getCurrentComponent()
(A same question is available in Stackoverflow. But that didn't help me because it used other function)
API Documentation
Hello, I am trying to implement Opensubtitle API with Python. I prefer trying to search subtitle file with hash, because it's accurate.
As I have never used xmlrpc before and quite new to using APIs, I had to study to make it work. But I am stuck at the final point. My program is returning Status 200 (OK), but the 'data' array is blank. I think, I am doing something wrong with the paramater passing thing. The code is here:
from xmlrpclib import ServerProxy
import hashCheck, os
server = 'http://api.opensubtitles.org/xml-rpc'
class MainEngine(object):
def __init__(self, language="None"):
self.rpc = ServerProxy(server, allow_none=True)
user_agent = 'OSTestUserAgentTemp'
self.Start()
def getToken(self):
self.logindata = self.rpc.LogIn(None, None, "en", "OSTestUserAgentTemp")
self.Token = self.logindata["token"]
return self.Token
def subSearch(self, path):
self.hash = hashCheck.hash(self.path)
token = self.getToken()
self.param = [
token, # token
[
'eng', # sublanguageid
self.hash, #hash
os.path.getsize(path), # byte size
]
]
Obj = self.rpc.SearchSubtitles(token, self.param)
print Obj
def Start(self):
# print server
self.path = "E:\Movies\English\Captain Phillips\Captain Phillips.mp4"
self.subSearch(self.path)
def main():
MainEngine()
if __name__ == '__main__':
main()