Conda using latest packages of certain date - anaconda

The title is self-explanatory. Is there a way to downgrade the conda packages to the ones that were the latest on a certain date?

This is not possible programmatically. Packages in Conda are specified through MatchSpec, which does not currently have any way to constrain on a build timestamp.
Manual Searching
When searching for packages via conda search, the --info flag will print the build timestamps if they are available. So, for example, if one wanted to find the latest version of PyMC3 that someone with Python 3.6 was running a year ago (9 Dec 2018), one could check
conda search --info 'conda-forge::pymc3'
and see that version 3.5, build py36_1000 would satisfy this. If one wanted to create an env with this build in it, they could use
conda create -n py36_pymc35 -c conda-forge pymc3=3.5=py36_1000

2023 Update
In addition to Merv's post, I may add that the --json flag makes it actually quite easy to programmatically gather the history. Once you have the history, you can search for the latest package versions as of some date, and make an environment with them (we do that routinely to establish "low watermark" environments for our CIs).
The conda command line invocation is:
f'conda search -q {package} --info --json`
Here is some code that uses that to gather the history of a few packages. It is also multi-threaded to speed up things a little.
import io
import json
import subprocess
import yaml
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
from tqdm import tqdm
def shell(cmd):
proc = subprocess.run(cmd, shell=True, capture_output=True)
return proc.stdout.decode('utf-8')
def version_as_tuple(v):
return tuple(map(int, v.split('.')))
def get_history(p):
txt = shell(f"conda search -q {p} --info --json")
d = json.loads(txt)
h = defaultdict(set)
for vv in d.values():
for x in vv:
h[version_as_tuple(x['version'])].add(
datetime.fromtimestamp(x.get('timestamp', 0) / 1e3)
)
h = {vers: min(dates) for vers, dates in h.items()}
return p, h
Example usage:
metayaml = """
- boto3
- pandas >=0.25
- python >=3.8
"""
reqs = yaml.safe_load(metayaml) # in real life, read from conda.recipe/meta.yaml
all_pkgs = sorted(set([p.split()[0] for p in reqs]))
with ThreadPoolExecutor() as pool:
history = dict(tqdm(pool.map(get_history, all_pkgs), total=len(all_pkgs)))
After that, we have a neat version history for all dependent packages. For example:
>>> {v: f'{t:%Y-%m-%d}' for v, t in history['pandas'].items()}
{(0, 20, 3): '2017-09-18',
(0, 21, 0): '2017-11-06',
(0, 21, 1): '2017-12-12',
...
(1, 4, 4): '2022-09-21',
(1, 5, 1): '2022-11-16',
(1, 5, 2): '2022-12-07'}
And:
asof = datetime.now() - timedelta(weeks=2*52)
new = {
name: max([(vers, t) for vers, t in v.items() if t < asof])
for name, v in history.items()
}
print(f'# as of {asof:%Y-%m-%d}')
for name, (vers, t) in new.items():
print(f' - {name} =={".".join(map(str, vers))} # released on {t:%Y-%m-%d}')
Which produces:
# as of 2021-01-20
- boto3 ==1.16.55 # released on 2021-01-15
- pandas ==1.2.0 # released on 2020-12-26
- python ==3.9.1 # released on 2020-12-11

Related

Execute is not defined in IBM quantum computing lab

I am using IBM's quantum computing lab, and was following a tutorial made by IBM for getting started, and my code is throwing errors. I followed the tutorial exactly. Here is my code:
#-----------Cell 1:
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
#-----------Cell 2:
# Build
#------
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# END
# Execute
#--------
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Return counts
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)
# END
# Visualize
#----------
# Import draw_circuit, then use it to draw the circuit
from ibm_quantum_widgets import draw_circuit
draw_circuit(circuit)
# Analyze
#--------
# Plot a histogram
plot_histogram(counts)
# END
This code throws this error:
Traceback (most recent call last):
File "/tmp/ipykernel_59/1801586149.py", line 26, in <module>
job = execute(circuit, simulator, shots=1000)
NameError: name 'execute' is not defined
Use %tb to get the full traceback.
I am new to IBM and quantum computing, how do I fix this error?
Here is the tutorial I was following if you need it: https://quantum-computing.ibm.com/lab/docs/iql/first-circuit
You did not import execute from qiskit.
Change
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
to
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute

Saving or downloading plotly iplot images on Google Colaboratory

I have been attempting to download a plot created using plotly on google colaboratory. So far this is what I have attempted:
I have tried changing
files.download('foo.svg')
to
files.download('foo')
and I still get no results. I navigated to the files on Google colab and nothing shows there
import numpy as np
import pandas as pd
from plotly.offline import iplot
import plotly.graph_objs as go
from google.colab import files
def enable_plotly_in_cell():
import IPython
from plotly.offline import init_notebook_mode
display(IPython.core.display.HTML('''<script src="/static/components/requirejs/require.js"></script>'''))
init_notebook_mode(connected=False)
#this actually shows the plot
enable_plotly_in_cell()
N = 500
x = np.linspace(0, 1, N)
y = np.random.randn(N)
df = pd.DataFrame({'x': x, 'y': y})
df.head()
data = [
go.Scatter(
x=df['x'], # assign x as the dataframe column 'x'
y=df['y']
)
]
iplot(data,image = 'svg', filename = 'foo')
files.download('foo.svg')
This is the error I am getting:
OSErrorTraceback (most recent call last)
<ipython-input-18-31523eb02a59> in <module>()
29 iplot(data,image = 'svg', filename = 'foo')
30
---> 31 files.download('foo.svg')
32
/usr/local/lib/python2.7/dist-packages/google/colab/files.pyc in download(filename)
140 msg = 'Cannot find file: {}'.format(filename)
141 if _six.PY2:
--> 142 raise OSError(msg)
143 else:
144 raise FileNotFoundError(msg) # pylint: disable=undefined-variable
OSError: Cannot find file: foo.svg
To save vector or raster images (e.g. SVGs or PNGs) from Plotly figures you need to have Kaleido (preferred) or Orca (legacy) installed, which is actually possible using the following commands in Colab:
Kaleido:
!pip install kaleido
Orca:
!pip install plotly>=4.0.0
!wget https://github.com/plotly/orca/releases/download/v1.2.1/orca-1.2.1-x86_64.AppImage -O /usr/local/bin/orca
!chmod +x /usr/local/bin/orca
!apt-get install xvfb libgtk2.0-0 libgconf-2-4
Once either of the above is done you can use the following code to make, show and export a figure (using plotly version 4):
import plotly.graph_objects as go
fig = go.Figure( go.Scatter(x=[1,2,3], y=[1,3,2] ) )
fig.show()
fig.write_image("image.svg")
fig.write_image("image.png")
The files can then be downloaded with:
from google.colab import files
files.download('image.svg')
files.download('image.png')
Try this, it does work for me:
import plotly.graph_objects as go
fig = go.Figure(...) # plot your fig
go.Figure.write_html(fig,"file.html") # write as html or image
files.download("file.html") # download your file and give me a vote my answer

fenics did not show figure . NameError: name interactive is not defined

I installed fenics on windows subsystem for linux to do my homework.I am trying to test fenics. So I use ft01_possion.py on the tutorial.
from fenics import *
# Create mesh and define function space
mesh = UnitSquareMesh(8, 8)
V = FunctionSpace(mesh, 'P', 1)
# Define boundary conditions
u_D = Expression('1 + x[0]*x[0] + 2*x[1]*x[1]', degree = 2)
def boundary(x, on_boundary):
return on_boundary
bc = DirichletBC(V, u_D, boundary)
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(-6.0)
a = dot(grad(u), grad(v))*dx
L = f*v*dx
# Compute solution
u = Function(V)
solve(a == L, u, bc)
# Plot solution and mesh
plot(u)
plot(mesh)
interactive()
It did not show the figure.
the error i am getting is:
Solving linear variational problem.
Traceback (most recent call last):
File "ft01_poisson.py", line 29, in <module>
interactive()
NameError: name 'interactive' is not defined
I have tried to reinstall the newest version of fenics without success.
While the print out of the error values work, the NameError prevents the plots from being shown.
Some Fenics examples are unfortunately out of date. Please see the following GitHub post.
Change 'interactive()' to
import matplotlib.pyplot as plt
plt.show()
this will show your results.
Errors are shown as follows:
error_L2 = 0.008235098073354827
error_max = 1.3322676295501878e-15
But there is :NameError: name 'interactive' is not defined, probably this error is not affecting the results

Python error: one of the arguments is required

I'm trying to run a code from github that uses Python to classify images but I'm getting an error.
here is the code:
import argparse as ap
import cv2
import imutils
import numpy as np
import os
from sklearn.svm import LinearSVC
from sklearn.externals import joblib
from scipy.cluster.vq import *
# Get the path of the testing set
parser = ap.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-t", "--testingSet", help="Path to testing Set")
group.add_argument("-i", "--image", help="Path to image")
parser.add_argument('-v',"--visualize", action='store_true')
args = vars(parser.parse_args())
# Get the path of the testing image(s) and store them in a list
image_paths = []
if args["testingSet"]:
test_path = args["testingSet"]
try:
testing_names = os.listdir(test_path)
except OSError:
print "No such directory {}\nCheck if the file exists".format(test_path)
exit()
for testing_name in testing_names:
dir = os.path.join(test_path, testing_name)
class_path = imutils.imlist(dir)
image_paths+=class_path
else:
image_paths = [args["image"]]
and this is the error message I'm getting
usage: getClass.py [-h]
(- C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test TESTINGSET | - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/test_1.jpg IMAGE)
[- C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset]
getClass.py: error: one of the arguments - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/--testingSet - C:/Users/Lenovo/Downloads/iris/bag-of-words-master/dataset/test/test_1.jpg/--image is required
can you please help me with this? where and how should I write the file path?
This is an error your own program is issuing. The message is not about the file path but about the number of arguments. This line
group = parser.add_mutually_exclusive_group(required=True)
says that only one of your command-line arguments (-t, -i) is permitted. But it appears from the error message that you are supplying both --testingSet and --image on your command line.
Since you only have 3 arguments, I have to wonder if you really need argument groups at all.
To get your command line to work, drop the mutually-exclusive group and add the arguments to the parser directly.
parser.add_argument("-t", "--testingSet", help="Path to testing Set")
parser.add_argument("-i", "--image", help="Path to image")
parser.add_argument('-v',"--visualize", action='store_true')

cx_freeze: How do I add package files into library.zip?

I've noticed that pytz misses zoneinfo folder when I try to roll a zip for Windows. Right now I have a workaround that I use after python setup.py build, namely
7z a -xr!*.py* build\exe.win32-2.7\library.zip C:\Python27\Lib\site-packages\pytz
Is there a proper way to achieve that from setup.py or something?
You could fix this, adding the following method:
def include_files():
path_base = "C:\\Python27\\Lib\\site-packages\\pytz\\zoneinfo\\"
skip_count = len(path_base)
zip_includes = [(path_base, "pytz/zoneinfo/")]
for root, sub_folders, files in os.walk(path_base):
for file_in_root in files:
zip_includes.append(
("{}".format(os.path.join(root, file_in_root)),
"{}".format(os.path.join("pytz/zoneinfo", root[skip_count:], file_in_root))
)
)
return zip_includes
Then, into setup.py file:
build_exe_options = {"packages": ["os"],
"excludes": ["tkinter"],
"zip_includes": include_files(),
...
}
Hope that helps
I've solved this problem in Python 3.4 in the following way
import pytz
setup(
...
options = {'build_exe':
{'include_files': (pytz.__path__[0],), ...},
},
)
Then pytz is included unzipped with all its time zones

Resources