Connecting to Sharepoint - python

I would like to CRUD files on Sharepoint. To do this I'm trying to follow the basic example on Office365-REST-Python-Client:
from office365.sharepoint.client_context import ClientContext
settings = {
'url': 'https://*****.sharepoint.com/sites/*****',
'user_credentials': {
'username': '*****#gmail.com',
'password': '*****',
},
}
ctx = ClientContext(settings["url"]).with_user_credentials(settings.get('user_credentials').get('username'),
settings.get('user_credentials').get('password'))
web = ctx.web.get().execute_query()
print(web.properties["Url"])
which gives me an Error:
IndexError Traceback (most recent call last)
<ipython-input-23-c5907526ff22> in <module>
12 settings.get('user_credentials').get('password'))
13
---> 14 web = ctx.web.get().execute_query()
15 print(web.properties["Url"])
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\client_object.py in execute_query(self)
31
32 def execute_query(self):
---> 33 self.context.execute_query()
34 return self
35
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\client_runtime_context.py in execute_query(self)
136 def execute_query(self):
137 if self.has_pending_request:
--> 138 self.pending_request().execute_query()
139
140 def add_query(self, query, to_begin=False):
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\client_request.py in execute_query(self)
72 request = self.build_request()
73 self.beforeExecute.notify(request)
---> 74 response = self.execute_request_direct(request)
75 response.raise_for_status()
76 self.process_response(response)
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\odata\odata_request.py in execute_request_direct(self, request)
32 def execute_request_direct(self, request):
33 self.ensure_media_type(request)
---> 34 return super(ODataRequest, self).execute_request_direct(request)
35
36 def build_request(self):
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\client_request.py in execute_request_direct(self, request_options)
84 :type request_options: office365.runtime.http.request_options.RequestOptions
85 """
---> 86 self.context.authenticate_request(request_options)
87 if request_options.method == HttpMethod.Post:
88 if request_options.is_bytes or request_options.is_file:
D:\Anaconda\envs\hplc\lib\site-packages\office365\sharepoint\client_context.py in authenticate_request(self, request)
151
152 def authenticate_request(self, request):
--> 153 self._auth_context.authenticate_request(request)
154
155 def _build_modification_query(self, request):
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\auth\authentication_context.py in authenticate_request(self, request)
82 """Authenticate request
83 :type request: RequestOptions"""
---> 84 self._provider.authenticate_request(request)
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\auth\providers\saml_token_provider.py in authenticate_request(self, request)
71 """
72 logger = self.logger(self.authenticate_request.__name__)
---> 73 self.ensure_authentication_cookie()
74 logger.debug_secrets(self._cached_auth_cookies)
75 cookie_header_value = "; ".join(["=".join([key, str(val)]) for key, val in self._cached_auth_cookies.items()])
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\auth\providers\saml_token_provider.py in ensure_authentication_cookie(self)
78 def ensure_authentication_cookie(self):
79 if self._cached_auth_cookies is None:
---> 80 self._cached_auth_cookies = self.get_authentication_cookie()
81 return True
82
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\auth\providers\saml_token_provider.py in get_authentication_cookie(self)
91 user_realm = self._get_user_realm()
92 if user_realm.IsFederated:
---> 93 token = self._acquire_service_token_from_adfs(user_realm.STSAuthUrl)
94 else:
95 token = self._acquire_service_token()
D:\Anaconda\envs\hplc\lib\site-packages\office365\runtime\auth\providers\saml_token_provider.py in _acquire_service_token_from_adfs(self, adfs_url)
134 headers={'Content-Type': 'application/soap+xml; charset=utf-8'})
135 dom = minidom.parseString(response.content.decode())
--> 136 assertion_node = dom.getElementsByTagNameNS("urn:oasis:names:tc:SAML:1.0:assertion", 'Assertion')[0].toxml()
137
138 try:
IndexError: list index out of range
Any ideas? It doesn't feel like an authentication problem.

It might be too late answer, but maybe it will help someone who faced with same problem and will find this question.
I had the same issue on version 2.3.9, but in version 2.1.4 there is no such problem, so you can try to use older versions.
Also there is an issue in GH repo: https://github.com/vgrem/Office365-REST-Python-Client/issues/304

Related

VAR time series error - "4-th leading minor of the array is not positive definite"

I am trying to develop a VAR model to predict some 4 timeseries in a dataframe, althought whenever I try to get the otpimal number of lags to use in the model, or see the mode summaryI get that error - "4-th leading minor of the array is not positive definite". I have tried to reduce or limit the max_lags but nothing worked. I can do model.fit and forecast but I cannot discover the number os lags to use.
LinAlgError Traceback (most recent call last)
<ipython-input-56-979715efd6e1> in <module>()
1 model = VAR(train_diff)
2 model_fitted = model.fit()
----> 3 model_fitted.summary()
9 frames
/usr/local/lib/python3.7/dist-packages/statsmodels/tsa/vector_ar/var_model.py in summary(self)
1687 summary : VARSummary
1688 """
-> 1689 return VARSummary(self)
1690
1691 def irf(self, periods=10, var_decomp=None, var_order=None):
/usr/local/lib/python3.7/dist-packages/statsmodels/tsa/vector_ar/output.py in __init__(self, estimator)
67 def __init__(self, estimator):
68 self.model = estimator
---> 69 self.summary = self.make()
70
71 def __repr__(self):
/usr/local/lib/python3.7/dist-packages/statsmodels/tsa/vector_ar/output.py in make(self, endog_names, exog_names)
79
80 buf.write(self._header_table() + '\n')
---> 81 buf.write(self._stats_table() + '\n')
82 buf.write(self._coef_table() + '\n')
83 buf.write(self._resid_info() + '\n')
/usr/local/lib/python3.7/dist-packages/statsmodels/tsa/vector_ar/output.py in _stats_table(self)
126 'FPE:',
127 'Det(Omega_mle):')
--> 128 part2Ldata = [[model.neqs], [model.nobs], [model.llf], [model.aic]]
129 part2Rdata = [[model.bic], [model.hqic], [model.fpe], [model.detomega]]
130 part2Lheader = None
/usr/local/lib/python3.7/dist-packages/statsmodels/tools/decorators.py in __get__(self, obj, type)
91 _cachedval = _cache.get(name, None)
92 if _cachedval is None:
---> 93 _cachedval = self.fget(obj)
94 _cache[name] = _cachedval
95
/usr/local/lib/python3.7/dist-packages/statsmodels/tsa/vector_ar/var_model.py in llf(self)
1423 def llf(self):
1424 "Compute VAR(p) loglikelihood"
-> 1425 return var_loglike(self.resid, self.sigma_u_mle, self.nobs)
1426
1427 #cache_readonly
/usr/local/lib/python3.7/dist-packages/statsmodels/tsa/vector_ar/var_model.py in var_loglike(resid, omega, nobs)
325 \left(\ln\left|\Omega\right|-K\ln\left(2\pi\right)-K\right)
326 """
--> 327 logdet = logdet_symm(np.asarray(omega))
328 neqs = len(omega)
329 part1 = - (nobs * neqs / 2) * np.log(2 * np.pi)
/usr/local/lib/python3.7/dist-packages/statsmodels/tools/linalg.py in logdet_symm(m, check_symm)
26 if not np.all(m == m.T): # would be nice to short-circuit check
27 raise ValueError("m is not symmetric.")
---> 28 c, _ = linalg.cho_factor(m, lower=True)
29 return 2*np.sum(np.log(c.diagonal()))
30
/usr/local/lib/python3.7/dist-packages/scipy/linalg/decomp_cholesky.py in cho_factor(a, lower, overwrite_a, check_finite)
153 """
154 c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False,
--> 155 check_finite=check_finite)
156 return c, lower
157
/usr/local/lib/python3.7/dist-packages/scipy/linalg/decomp_cholesky.py in _cholesky(a, lower, overwrite_a, clean, check_finite)
38 if info > 0:
39 raise LinAlgError("%d-th leading minor of the array is not positive "
---> 40 "definite" % info)
41 if info < 0:
42 raise ValueError('LAPACK reported an illegal value in {}-th argument'
LinAlgError: 4-th leading minor of the array is not positive definite
That's the traceback I get.
Thanks for some help it would be much needed.

AttributeError: module 'PIL.TiffTags' has no attribute 'LONG8'

I am trying to open an image with skimage.io.imread but I have the error in title.
For example:
skimage.io.imread('myimage.png')
My environment; skimage:
import skimage
print(skimage.__version__)
0.19.2
and PIL:
import PIL
PIL.__version__
8.0.1
This is the entire traceback:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-52-1b9f5663f4c8> in <module>
----> 1 skimage.io.imread('qrcode-caracciolo.png')
/usr/local/lib/python3.9/site-packages/skimage/io/_io.py in imread(fname, as_gray, plugin, **plugin_args)
51
52 with file_or_url_context(fname) as fname:
---> 53 img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
54
55 if not hasattr(img, 'ndim'):
/usr/local/lib/python3.9/site-packages/skimage/io/manage_plugins.py in call_plugin(kind, *args, **kwargs)
205 (plugin, kind))
206
--> 207 return func(*args, **kwargs)
208
209
/usr/local/lib/python3.9/site-packages/skimage/io/_plugins/imageio_plugin.py in imread(*args, **kwargs)
8 #wraps(imageio_imread)
9 def imread(*args, **kwargs):
---> 10 return np.asarray(imageio_imread(*args, **kwargs))
/usr/local/lib/python3.9/site-packages/imageio/__init__.py in imread(uri, format, **kwargs)
94 )
95
---> 96 return imread_v2(uri, format=format, **kwargs)
97
98
/usr/local/lib/python3.9/site-packages/imageio/v2.py in imread(uri, format, **kwargs)
199 imopen_args["legacy_mode"] = True
200
--> 201 with imopen(uri, "ri", **imopen_args) as file:
202 return file.read(index=0, **kwargs)
203
/usr/local/lib/python3.9/site-packages/imageio/core/imopen.py in imopen(uri, io_mode, plugin, format_hint, legacy_mode, **kwargs)
212
213 try:
--> 214 plugin_instance = candidate_plugin(request, **kwargs)
215 except InitializationError:
216 # file extension doesn't match file type
/usr/local/lib/python3.9/site-packages/imageio/config/plugins.py in partial_legacy_plugin(request)
106
107 def partial_legacy_plugin(request):
--> 108 return LegacyPlugin(request, legacy_plugin)
109
110 clazz = partial_legacy_plugin
/usr/local/lib/python3.9/site-packages/imageio/core/legacy_plugin_wrapper.py in __init__(self, request, legacy_plugin)
66 )
67 if self._request.mode.io_mode == IOMode.read:
---> 68 if not self._format.can_read(request):
69 raise InitializationError(
70 f"`{self._format.name}`" f" can not read `{source}`."
/usr/local/lib/python3.9/site-packages/imageio/core/format.py in can_read(self, request)
242 Get whether this format can read data from the specified uri.
243 """
--> 244 return self._can_read(request)
245
246 def can_write(self, request):
/usr/local/lib/python3.9/site-packages/imageio/plugins/pillow_legacy.py in _can_read(self, request)
262
263 def _can_read(self, request):
--> 264 Image = self._init_pillow()
265 if request.mode[1] in (self.modes + "?"):
266 if self.plugin_id in Image.OPEN:
/usr/local/lib/python3.9/site-packages/imageio/plugins/pillow_legacy.py in _init_pillow(self)
256
257 if self.plugin_id in ("PNG", "JPEG", "BMP", "GIF", "PPM"):
--> 258 Image.preinit()
259 else:
260 Image.init()
/usr/local/lib/python3.9/site-packages/PIL/Image.py in preinit()
365 assert JpegImagePlugin
366 except ImportError:
--> 367 pass
368 try:
369 from . import PpmImagePlugin
/usr/local/lib/python3.9/site-packages/PIL/JpegImagePlugin.py in <module>
42 import warnings
43
---> 44 from . import Image, ImageFile, TiffImagePlugin
45 from ._binary import i16be as i16
46 from ._binary import i32be as i32
/usr/local/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in <module>
425
426
--> 427 class ImageFileDirectory_v2(MutableMapping):
428 """This class represents a TIFF tag directory. To speed things up, we
429 don't decode tags unless they're asked for.
/usr/local/lib/python3.9/site-packages/PIL/TiffImagePlugin.py in ImageFileDirectory_v2()
706 (TiffTags.DOUBLE, "d", "double"),
707 (TiffTags.IFD, "L", "long"),
--> 708 (TiffTags.LONG8, "Q", "long8"),
709 ],
710 )
AttributeError: module 'PIL.TiffTags' has no attribute 'LONG8'

Altair: NoMatchingVersions when saving maps with selenium

I am trying to create a series and save them iteratively.
The creation works well but while saving I get the following error:
---------------------------------------------------------------------------
NoMatchingVersions Traceback (most recent call last)
<ipython-input-103-e75c3f4b4fa5> in <module>
29 chart=(background + chart).configure_view(stroke='white')
30 filename = f"{scenario}.svg"
---> 31 save(chart, filename, method='selenium', webdriver=driver)
~\Anaconda3\lib\site-packages\altair_saver\_core.py in save(chart, fp, fmt, mode, method, **kwargs)
75 saver = Saver(spec, mode=mode, **kwargs)
76
---> 77 saver.save(fp=fp, fmt=fmt)
78
79
~\Anaconda3\lib\site-packages\altair_saver\savers\_saver.py in save(self, fp, fmt)
86 raise ValueError(f"Got fmt={fmt}; expected one of {self.valid_formats}")
87
---> 88 content = self.mimebundle(fmt).popitem()[1]
89 if isinstance(content, dict):
90 with maybe_open(fp, "w") as f:
~\Anaconda3\lib\site-packages\altair_saver\savers\_saver.py in mimebundle(self, fmts)
66 f"invalid fmt={fmt!r}; must be one of {self.valid_formats}."
67 )
---> 68 bundle.update(self._mimebundle(fmt))
69 return bundle
70
~\Anaconda3\lib\site-packages\altair_saver\savers\_selenium.py in _mimebundle(self, fmt)
249
250 def _mimebundle(self, fmt: str) -> Mimebundle:
--> 251 out = self._extract(fmt)
252 mimetype = fmt_to_mimetype(
253 fmt,
~\Anaconda3\lib\site-packages\altair_saver\savers\_selenium.py in _extract(self, fmt)
209 js_resources = {
210 "vega.js": get_bundled_script("vega", self._vega_version),
--> 211 "vega-lite.js": get_bundled_script("vega-lite", self._vegalite_version),
212 "vega-embed.js": get_bundled_script(
213 "vega-embed", self._vegaembed_version
~\Anaconda3\lib\site-packages\altair_viewer\_scripts.py in get_bundled_script(package, version)
36 f"package {package!r} not recognized. Available: {list(listing)}"
37 )
---> 38 version_str = find_version(version, listing[package])
39 content = pkgutil.get_data("altair_viewer", f"scripts/{package}-{version_str}.js")
40 if content is None:
~\Anaconda3\lib\site-packages\altair_viewer\_utils.py in find_version(version, candidates, strict_micro)
190 if not matches:
191 raise NoMatchingVersions(
--> 192 f"No matches for version={version!r} among {candidates}"
193 )
194 return str(matches[-1])
NoMatchingVersions: No matches for version='4.8.1' among ['4.0.2']
I am using selenium and altair_saver:
from altair_saver import save
from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'pathtochromedriver/chromedriver_win32/chromedriver.exe')
for i, scenario in enumerate(scenario_columns):
chart=makechart(scenario, i)
filename = f"{scenario}.svg"
save(chart, filename, method='selenium', webdriver=driver)
Here `scenario` is a string without special characters.
You need to update the altair_viewer package to a newer version:
$ pip install -U altair_viewer
(This error was improved in https://github.com/altair-viz/altair_viewer/pull/33, so shouldn't be as mysterious when it comes up in the future).

what is the problem ?: application.connect() error

I am a beginner developer who started to study automation by using pywinauto.
An overflow error occurs when using application.connect () to connect to an already open program.
But application.start() works fine....
Please help me if someone know this part.
The source code and error contents are as follows.
Source code:
import pywinauto
app = pywinauto.application.Application()
app.connect(title_re='Calculator')
Error:
OverflowError Traceback (most recent call last)
in
1 import pywinauto
2 app = pywinauto.application.Application()
----> 3 app.connect(title_re='Calculator')
d:\Anaconda3\lib\site-packages\pywinauto\application.py in connect(self, **kwargs)
972 ).process_id
973 else:
--> 974 self.process = findwindows.find_element(**kwargs).process_id
975 connected = True
976
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in find_element(**kwargs)
82 so please see :py:func:find_elements for the full parameters description.
83 """
---> 84 elements = find_elements(**kwargs)
85
86 if not elements:
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in find_elements(class_name, class_name_re, parent, process, title, title_re, top_level_only, visible_only, enabled_only, best_match, handle, ctrl_index, found_index, predicate_func, active_only, control_id, control_type, auto_id, framework_id, backend, depth)
279 return title_regex.match(t)
280 return False
--> 281 elements = [elem for elem in elements if _title_match(elem)]
282
283 if visible_only:
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in (.0)
279 return title_regex.match(t)
280 return False
--> 281 elements = [elem for elem in elements if _title_match(elem)]
282
283 if visible_only:
d:\Anaconda3\lib\site-packages\pywinauto\findwindows.py in _title_match(w)
275 def _title_match(w):
276 """Match a window title to the regexp"""
--> 277 t = w.rich_text
278 if t is not None:
279 return title_regex.match(t)
d:\Anaconda3\lib\site-packages\pywinauto\win32_element_info.py in rich_text(self)
81 def rich_text(self):
82 """Return the text of the window"""
---> 83 return handleprops.text(self.handle)
84
85 name = rich_text
d:\Anaconda3\lib\site-packages\pywinauto\handleprops.py in text(handle)
86 length += 1
87
---> 88 buffer_ = ctypes.create_unicode_buffer(length)
89
90 ret = win32functions.SendMessage(
d:\Anaconda3\lib\ctypes_init_.py in create_unicode_buffer(init, size)
286 return buf
287 elif isinstance(init, int):
--> 288 buftype = c_wchar * init
289 buf = buftype()
290 return buf
OverflowError: cannot fit 'int' into an index-sized integer
import pywinauto
app = pywinauto.Application(backend='uia').start('calc.exe')
try this if you are having problem you have to say the backennd is a uia it working fine for me.

ValueError: Value must be one of {'doubleAccounting', 'double', 'singleAccounting', 'single'}

After writing the following code I get the following error. Help would be appreciated in understanding why openpyxl which is designed to work with EXCEL cannot open a basic excel file. Thank you in advance for your help.
import openpyxl
from openpyxl import workbook
from openpyxl import load_workbook
wb = load_workbook(file_name, read_only= True)
ValueError Traceback (most recent call last)
<ipython-input-7-9ebd7e3bdd2c> in <module>()
4
5
----> 6 wb = load_workbook(file_name, read_only= True)
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\reader\excel.py in load_workbook(filename, read_only, keep_vba, data_only, guess_types, keep_links)
199 wb.loaded_theme = archive.read(ARC_THEME)
200
--> 201 apply_stylesheet(archive, wb) # bind styles to workbook
202
203 # get worksheets
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py in apply_stylesheet(archive, wb)
171 return wb
172 node = fromstring(src)
--> 173 stylesheet = Stylesheet.from_tree(node)
174
175 wb._cell_styles = stylesheet.cell_styles
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py in from_tree(cls, node)
97 for k in attrs:
98 del node.attrib[k]
---> 99 return super(Stylesheet, cls).from_tree(node)
100
101
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py in from_tree(cls, node)
70 if hasattr(desc, 'from_tree'):
71 #descriptor manages conversion
---> 72 obj = desc.from_tree(el)
73 else:
74 if hasattr(desc.expected_type, "from_tree"):
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\sequence.py in from_tree(self, node)
84
85 def from_tree(self, node):
---> 86 return [self.expected_type.from_tree(el) for el in node]
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\sequence.py in <listcomp>(.0)
84
85 def from_tree(self, node):
---> 86 return [self.expected_type.from_tree(el) for el in node]
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py in from_tree(cls, node)
87 attrib[tag] = obj
88
---> 89 return cls(**attrib)
90
91
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\styles\fonts.py in __init__(self, name, sz, b, i, charset, u, strike, color, scheme, family, size, bold, italic, strikethrough, underline, vertAlign, outline, shadow, condense, extend)
85 if underline is not None:
86 u = underline
---> 87 self.u = u
88 if strikethrough is not None:
89 strike = strikethrough
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\nested.py in __set__(self, instance, value)
34
35 value = self.from_tree(value)
---> 36 super(Nested, self).__set__(instance, value)
37
38
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\base.py in __set__(self, instance, value)
143 if value == 'none':
144 value = None
--> 145 super(NoneSet, self).__set__(instance, value)
146
147
C:\Users\Gaston\Anaconda3\lib\site-packages\openpyxl\descriptors\base.py in __set__(self, instance, value)
128 def __set__(self, instance, value):
129 if value not in self.values:
--> 130 raise ValueError(self.__doc__)
131 super(Set, self).__set__(instance, value)
132
ValueError: Value must be one of {'single', 'double', 'singleAccounting', 'doubleAccounting'}
I have tried taking out the read_only part etc. The error has to do with Excel styles. I am using Excel 2016 and the file type is xlxs.
I've found a bug in an Excel processing library called RubyXL, which writes an invalid value to the .xslx file: https://github.com/weshatheleopard/rubyXL/issues/405
Excel tolerates the invalid underline style ement <u val="1"/> written by RubyXL, by interpreting it as a single-underline style, but openpyxl does not tolerate it.
Maybe your file has been corrupted by RubyXL or by another tool with a similar problem?
I've resolved this temporarily by comment the two lines in
"python3.8/site-packages/openpyxl/descriptors/base.py"" file
I just run the code in debug mode, so I can save the change forcedly.

Categories

Resources