query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Returns an XML representation of the Orientation instance. | def to_xml(self, doc):
print('deprecated as we are moving to hdf5 format')
orientation = doc.createElement('Orientation')
orientation_phi1 = doc.createElement('phi1')
orientation_phi1_text = doc.createTextNode('%f' % self.phi1())
orientation_phi1.appendChild(orientation_phi1_text... | [
"def getOrientation(self):\n return self.getTag(\"Orientation#\", 1)",
"def orientation(self):\r\n tag=self.readinfo('Image Orientation Patient')\r\n \r\n if tag==None:\r\n name=None\r\n elif tag==[-0,1,0,-0,-0,-1]:\r\n name=1 #Sagittal\r\n elif... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the rodrigues vector from the orientation matrix. | def OrientationMatrix2Rodrigues(g):
t = g.trace() + 1
if np.abs(t) < np.finfo(g.dtype).eps:
print('warning, returning [0., 0., 0.], consider using axis, angle representation instead')
return np.zeros(3)
else:
r1 = (g[1, 2] - g[2, 1]) / t
r2 = (g[2,... | [
"def rod_to_u(rodriguez_vector):\n r = n.asarray(rodriguez_vector, float)\n g = n.zeros((3, 3))\n r2 = n.dot(r , r)\n\n for i in range(3):\n for j in range(3):\n if i == j:\n fac = 1\n else:\n fac = 0\n term = 0\n for k in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the orientation matrix from the Rodrigues vector. | def Rodrigues2OrientationMatrix(rod):
r = np.linalg.norm(rod)
I = np.diagflat(np.ones(3))
if r < np.finfo(r.dtype).eps:
return I
else:
theta = 2 * np.arctan(r)
n = rod / r
omega = np.array([[0.0, n[2], -n[1]], [-n[2], 0.0, n[0]], [n[1], -n[... | [
"def _rotation_matrix_uniaxial(theta,phi, R):\n costheta = cos(theta)\n sintheta = sin(theta)\n cosphi = cos(phi)\n sinphi = sin(phi)\n \n R[0,0] = costheta * cosphi\n R[0,1] = - sinphi \n R[0,2] = cosphi * sintheta\n R[1,0] = costheta * sinphi \n R[1,1] = cosphi\n R[1,2] = sintheta ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the axis/angle representation from the Rodrigues vector. | def Rodrigues2Axis(rod):
r = np.linalg.norm(rod)
axis = rod / r
angle = 2 * np.arctan(r)
return axis, angle | [
"def angle_vector(self):\n from math import atan2, pi\n return (atan2(self.y, self.x)) / pi * 180",
"def get_angle_and_axis(self):\n # special case: no rotation\n if self == Rotation():\n angle = 0.\n axis = Vector((1., 0., 0.))\n return angle, axis\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the (passive) orientation matrix associated the rotation defined by the given (axis, angle) pair. | def Axis2OrientationMatrix(axis, angle):
omega = np.radians(angle)
c = np.cos(omega)
s = np.sin(omega)
g = np.array([[c + (1 - c) * axis[0] ** 2, (1 - c) * axis[0] * axis[1] + s * axis[2],
(1 - c) * axis[0] * axis[2] - s * axis[1]],
[(1 - c) *... | [
"def rotate(angle, axis):\n a = normalize(axis)\n sin_t = math.sin(math.radians(angle))\n cos_t = math.cos(math.radians(angle))\n mat = Matrix4x4(a.x * a.x + (1.0 - a.x * a.x) * cos_t,\n a.x * a.y * (1.0 - cos_t) - a.z * sin_t,\n a.x * a.z * (1.0 - cos_t) + a.y * si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the rodrigues vector from the 3 euler angles (in degrees) | def Euler2Rodrigues(euler):
(phi1, Phi, phi2) = np.radians(euler)
a = 0.5 * (phi1 - phi2)
b = 0.5 * (phi1 + phi2)
r1 = np.tan(0.5 * Phi) * np.cos(a) / np.cos(b)
r2 = np.tan(0.5 * Phi) * np.sin(a) / np.cos(b)
r3 = np.tan(b)
return np.array([r1, r2, r3]) | [
"def compute_angles(self):\n edges = self.edges().reshape(-1, 3, 2)\n vecs = np.diff(self.vertices[edges], axis=2)[:, :, 0]\n vecs = util.normalize(vecs)\n angles = np.arccos(-util.dot(vecs[:, [1, 2, 0]], vecs[:, [2, 0, 1]]))\n assert np.allclose(angles.sum(axis=1), np.pi, rtol=1e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a set of euler angles from an ascii file. | def read_euler_txt(txt_path):
return Orientation.read_orientations(txt_path) | [
"def read_euler(self):\n data = self.bus.read_i2c_block_data(self.address, 0x1A, 6)\n return self.parse_axis(data, 16)",
"def read_ascii(fn):\n try:\n inputfile = open(fn, 'r')\n except Exception as error:\n print(error)\n return\n lines = inputfile.readlines()\n inp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a set of grain orientations from a text file. The text file must be organised in 3 columns (the other are ignored), corresponding to either the three euler angles or the three rodrigues veotor components, depending on the data_type). Internally the ascii file is read by the genfromtxt function of numpy, additional... | def read_orientations(txt_path, data_type='euler', **kwargs):
data = np.genfromtxt(txt_path, **kwargs)
size = len(data)
orientations = []
for i in range(size):
angles = np.array([float(data[i, 0]), float(data[i, 1]), float(data[i, 2])])
if data_type == 'euler':
... | [
"def read_txt_grains(fname):\n\n # Note: (21) fields named below with an underscore are not yet used\n #\n # Fields from grains.out header:\n \"\"\"grain ID completeness chi2\n xi[0] xi[1] xi[2]\n tVec_c[0] tVec_c[1] tVec_c[2]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a set of grain orientations from a zset input file. In zset input files, the orientation data may be specified either using the rotation of two vector, euler angles or rodrigues components directly. For instance the following lines are extracted from a polycrystalline calculation file | def read_euler_from_zset_inp(inp_path):
inp = open(inp_path)
lines = inp.readlines()
for i, line in enumerate(lines):
if line.lstrip().startswith('***material'):
break
euler_lines = []
for j, line in enumerate(lines[i + 1:]):
# read until n... | [
"def read_orientation_file(path):\n rotationdf = pd.read_csv(\n path,\n sep=' ',\n index_col=0,\n names=['strip', 'direction'],\n header=None\n )\n rotationdf['direction'] = rotationdf['direction'].astype(int)\n return rotationdf",
"def orientations(self) -> pulumi.I... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the Schmid factor for this crystal orientation and the given slip system. | def schmid_factor(self, slip_system, load_direction=[0., 0., 1]):
plane = slip_system.get_slip_plane()
gt = self.orientation_matrix().transpose()
n_rot = np.dot(gt, plane.normal()) # plane.normal() is a unit vector
slip = slip_system.get_slip_direction().direction()
slip_rot = n... | [
"def calculate_seismic_force(base_shear, floor_weight, floor_height, k):\r\n # Calculate the product of floor weight and floor height\r\n # Note that floor height includes ground floor, which will not be used in the actual calculation.\r\n # Ground floor is stored here for completeness.\r\n weight_floor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute all Schmid factors for this crystal orientation and the given list of slip systems. | def compute_all_schmid_factors(self, slip_systems, load_direction=[0., 0., 1], verbose=False):
SF_list = []
for ss in slip_systems:
sf = self.schmid_factor(ss, load_direction)
if verbose:
print('Slip system: %s, Schmid factor is %.3f' % (ss, sf))
SF_li... | [
"def PSSM_freqs(PSSM_all, pseudocount):\n PSSM_all_psc = PSSM_pseudocount(PSSM_all, pseudocount)\n \n PSSM_all_f = []\n for PSSM in PSSM_all_psc:\n PSSM_colsums = np.sum(PSSM,0,dtype='float')\n PSSM_all_f.append(PSSM / PSSM_colsums)\n \n return(PSSM_all_f)",
"def convolve(self, sfh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the Schmid factor of this grain for the given slip system. | def schmid_factor(self, slip_system, load_direction=[0., 0., 1]):
plane = slip_system.get_slip_plane()
gt = self.orientation_matrix().transpose()
n_rot = np.dot(gt, plane.normal()) # plane.normal() is a unit vector
slip = slip_system.get_slip_direction().direction()
slip_rot = n... | [
"def shear_Reuss(self):\r\n s = self.Sij\r\n return 15 / (4 * (s[0, 0] + s[1, 1] + s[2, 2]) - 4 * (s[0, 1] + s[1, 2] + s[0, 2]) + 3 * (s[3, 3] + s[4, 4] + s[5, 5]))",
"def shear(self):\r\n return (self.shear_Voigt + self.shear_Reuss) / 2",
"def calculate_seismic_force(base_shear, floor_weig... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the VTK mesh of this grain. | def SetVtkMesh(self, mesh):
self.vtkmesh = mesh | [
"def part_mesh(self, part_mesh):\n\n part_mesh = np.array(part_mesh)\n\n if part_mesh.shape[0] != self._num_parts:\n raise ValueError(\"Size of part mesh invalid!\")\n\n self._part_mesh = part_mesh",
"def set_mesh(self, mesh_dim, typ_elem, ndp, nptfr, nptir, nelem, npoin,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a mesh to this grain. This method process a labeled array to extract the geometry of the grain. The grain shape is defined by the pixels with a value of the grain id. A vtkUniformGrid object is created and thresholded or contoured depending on the value of the flag `contour`. The resulting mesh is returned, centere... | def add_vtk_mesh(self, array, contour=True, verbose=False):
label = self.id # we use the grain id here...
# create vtk structure
from scipy import ndimage
from vtk.util import numpy_support
grain_size = np.shape(array)
array_bin = (array == label).astype(np.uint8)
... | [
"def add_mesh(cube, url):\n from pyugrid import UGrid\n ug = UGrid.from_ncfile(url)\n cube.mesh = ug\n cube.mesh_dimension = 1\n return cube",
"def add_mesh(self, **args):\n if \"filename\" not in args:\n raise KeyError(\"No filename given\")\n self.meshfiles.append((args[\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an XML representation of the Grain instance. | def to_xml(self, doc, file_name=None):
grain = doc.createElement('Grain')
grain_id = doc.createElement('Id')
grain_id_text = doc.createTextNode('%s' % self.id)
grain_id.appendChild(grain_id_text)
grain.appendChild(grain_id)
grain.appendChild(self.orientation.to_xml(doc))
... | [
"def xml(self):\n return oxml_tostring(self, encoding='UTF-8', standalone=True)",
"def generate_xml(self):\n raise NotImplementedError()",
"def get_raw_xml_output(self):\n\n return self.xml",
"def generate_xml(self):\n assert self.xml_root != None, 'The self.xml_root variable must ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the grain orientation matrix. | def orientation_matrix(self):
return self.orientation.orientation_matrix() | [
"def getRotationMatrix( self):",
"def get_orientation(self):\n pose = self.get_pose()\n orientation = np.array(pose.r)\n return orientation",
"def rotation_matrix(self):\n return np.array([self.axis_u, self.axis_v, self.axis_w])",
"def _orientation_vectors(self):\n\n agent_o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a `Grain` instance from a DCT grain file. | def from_dct(label=1, data_dir='.'):
grain_path = os.path.join(data_dir, '4_grains', 'phase_01', 'grain_%04d.mat' % label)
grain_info = h5py.File(grain_path)
g = Grain(label, Orientation.from_rodrigues(grain_info['R_vector'].value))
g.center = grain_info['center'].value
# add spa... | [
"def from_grain_file(grain_file_path, col_id=0, col_phi1=1, col_phi=2, col_phi2=3, col_x=4, col_y=5, col_z=None, col_volume=None):\n # get the file name without extension\n name = os.path.splitext(os.path.basename(grain_file_path))[0]\n print('creating microstructure %s' % name)\n micro ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the number of phases in this microstructure. For the moment only one phase is supported, so this function simply returns 1. | def get_number_of_phases(self):
return 1 | [
"def get_num_phases(self) -> int:\n return self._num_phases",
"def get_num_timesteps(self):\n return len(self.dm[0])",
"def num_steps(self):\n return len(self.voltage_pairs)",
"def getNumFrames(self):\n timestep_values = self.readTimesteps() # Takes the values of all timesteps\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the number of grains in this microstructure. | def get_number_of_grains(self):
return len(self.grains) | [
"def count_asteroids(self):\n count = 0\n for obj in self.game_objects:\n if type(obj) == Asteroid:\n count += 1\n return count",
"def getNumGenes(self):\n return self.data.getNumGenes()",
"def nb_ring(self):\n return len(self.__rings)",
"def get_cu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the crystallographic lattice associated with this microstructure. | def set_lattice(self, lattice):
self._lattice = lattice | [
"def generate_lattice(self, verbose=False):\n if not self._lattice:\n lat = StrictOrders().get_orders(xrange(1, self.set_n + 1), verbose)\n self._lattice = lat",
"def getLattice() :\n lattice = [getElem('loop'),getElem('quad'),getElem('drift'),getElem('quad'),getElem('drift')]\n lat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the crystallographic lattice associated with this microstructure. | def get_lattice(self):
return self._lattice | [
"def getLattice() :\n lattice = [getElem('loop'),getElem('quad'),getElem('drift'),getElem('quad'),getElem('drift')]\n lattice[3].Kx = -lattice[3].Kx\n return lattice",
"def reciprocal_lattice_crystallographic(self) -> \"Lattice\":\n return Lattice(self.reciprocal_lattice.matrix / (2 * np.pi))",
"def _... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the grain map for this microstructure. | def set_grain_map(self, grain_map, voxel_size):
self.grain_map = grain_map
self.voxel_size = voxel_size | [
"def set_map(self, map_object):\n for sensor in self.config.sensors:\n sensor.set_map(map_object)",
"def type_of_grain(self, type_of_grain):\n\n self._type_of_grain = type_of_grain",
"def usermap(self, usermap: ConfigNodePropertyArray):\n\n self._usermap = usermap",
"def add_gr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A simple utility method to show one microstructure slice. | def view_slice(self, slice=None, color='random', show_mask=True):
if not hasattr(self, 'grain_map'):
print('Microstructure instance mush have a grain_map field to use this method')
return
if slice is None or slice > self.grain_map.shape[2] - 1 or slice < 0:
slice = se... | [
"def test_slice_basic(self):\n\n utils.compare_tracing_methods(\n SimpleSliceModel(), torch.rand((2, 3)), skip_to_glow=True\n )",
"def printSubDiagram(self, *args):\n return _coin.SoBaseKit_printSubDiagram(self, *args)",
"def test_slice(setup):\n assert isinstance(setup[\"slic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a random texture microstructure. | def random_texture(n=100):
m = Microstructure(name='random_texture')
for i in range(n):
m.grains.append(Grain(i + 1, Orientation.random()))
return m | [
"def sample_image(self):\n z = torch.randn(1, self.latent_size)\n r_t = self.decoder(z)\n return r_t",
"def RandomArt(random = StrongRandom(\"\"), size = 128):\n img = randomart.Create(random, size)\n return img",
"def world_texture(hdr_name):\r\n world=bpy.data.worlds['World']\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a random color map. The first color can be enforced to black and usually figure out the background. The random seed is fixed to consistently produce the same colormap. | def rand_cmap(N=4096, first_is_black=False):
np.random.seed(13)
rand_colors = np.random.rand(N, 3)
if first_is_black:
rand_colors[0] = [0., 0., 0.] # enforce black background (value 0)
return colors.ListedColormap(rand_colors) | [
"def random_color_gen():\n r = lambda: random.randint(0, 255)\n return 'ff%02X%02X%02X' % (r(), r(), r())",
"def random_color():\n return systemrandom.randint(0x000000, 0xFFFFFF)",
"def get_colormap(num_agents):\n colors = cm.get_cmap('jet', num_agents)\n colors = colors(range(num_agents))\n np.rand... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a colormap with ipf colors. | def ipf_cmap(self):
N = len(self.grains)
ipf_colors = np.zeros((4096, 3))
for g in self.grains:
ipf_colors[g.id, :] = g.orientation.get_ipf_colour()
return colors.ListedColormap(ipf_colors) | [
"def CO2p_colormap(bad=None, n=256):\n\n # color sequence from black -> purple -> white\n cmap_colors = [(0, 0, 0), (0.7255, 0.0588, 0.7255), (1, 1, 1)]\n\n # set colormap name\n cmap_name = 'CO2p'\n\n # make a colormap using the color sequence and chosen name\n cmap = colors.LinearSegmentedColorm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a `Microstructure` reading grain infos from a file. | def from_grain_file(grain_file_path, col_id=0, col_phi1=1, col_phi=2, col_phi2=3, col_x=4, col_y=5, col_z=None, col_volume=None):
# get the file name without extension
name = os.path.splitext(os.path.basename(grain_file_path))[0]
print('creating microstructure %s' % name)
micro = Microst... | [
"def from_h5(file_path):\n with h5py.File(file_path, 'r') as f:\n micro = Microstructure(name=f.attrs['microstructure_name'])\n if 'symmetry' in f['EnsembleData/CrystalStructure'].attrs:\n sym = f['EnsembleData/CrystalStructure'].attrs['symmetry']\n paramet... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load a Microstructure object from an xml file. It is possible to restrict the grains which are loaded by providing the list of ids of the grains of interest. | def from_xml(xml_file_name, grain_ids=None, verbose=False):
if verbose and grain_ids:
print('loading only grain ids %s' % grain_ids)
micro = Microstructure()
dom = parse(xml_file_name)
root = dom.childNodes[0]
name = root.childNodes[0]
micro.name = name.childN... | [
"def load(class_, path, api, profile):\n if path is None:\n path = os.path.join(os.path.dirname(__file__), 'gl.xml')\n obj = class_(api, profile)\n obj.dependencies.append(path)\n tree = etree.parse(path)\n for e in tree.getroot():\n try:\n fun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a particular grain given its id. This method browses the microstructure and return the grain corresponding to the given id. If the grain is not found, the method raises a `ValueError`. | def get_grain(self, gid):
for grain in self.grains:
if grain.id == gid:
return grain
raise ValueError('grain %d not found in the microstructure' % gid) | [
"def getByID(id_genus:int):\n genus = GenusAPI().get_by_id(id_genus)\n schema = GenusSchema()\n results = schema.load(genus, many=False)\n return results[0]",
"def get_fuse_region(self, _id):\n for fuse_region in self.fuse_region:\n if fuse_region.id == _id:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all te grain positions as a numpy array of shape (n, 3) where n is the number of grains. | def get_grain_positions(self):
positions = np.empty((self.get_number_of_grains(), 3))
for i in range(self.get_number_of_grains()):
positions[i] = self.grains[i].position
return positions | [
"def positions(self):\n return get_positions(as_numpy=True).reshape((self.natom, 3))",
"def flatten_fish_positions(self) -> np.ndarray:\n # todo: re-implement fish-index based slicing\n df_sel = self.positions_df[['x_pos', 'y_pos']]\n return df_sel.to_numpy()",
"def get_positions(gro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute all grains volume fractions. | def get_grain_volume_fractions(self):
total_volume = 0.
for g in self.grains:
total_volume += g.volume
return [g.get_volume_fraction(total_volume) for g in self.grains] | [
"def get_grain_volume_fraction(self, gid, use_total_volume_value=None):\n # compute the total volume\n if use_total_volume_value:\n volume = use_total_volume_value\n else:\n # sum all the grain volume to compute the total volume\n volume = 0.\n for g ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the grain volume fraction. | def get_grain_volume_fraction(self, gid, use_total_volume_value=None):
# compute the total volume
if use_total_volume_value:
volume = use_total_volume_value
else:
# sum all the grain volume to compute the total volume
volume = 0.
for g in self.grai... | [
"def get_grain_volume_fractions(self):\n total_volume = 0.\n for g in self.grains:\n total_volume += g.volume\n return [g.get_volume_fraction(total_volume) for g in self.grains]",
"def volume_fraction(self, x):\r\n\t\tvol = np.mean(x)\r\n\t\tself.dv[:] = 1.0 / (self.nelx * self.nel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Match grains from a second microstructure to this microstructure. This function try to find pair of grains based on their orientations. | def match_grains(self, micro2, mis_tol=1, use_grain_ids=None, verbose=False):
if not self.get_lattice().get_symmetry() == micro2.get_lattice().get_symmetry():
raise ValueError('warning, microstructure should have the same symmetry, got: {} and {}'.
format(self.get_lattic... | [
"def _isomorphism(g1, g2, top1, top2) -> Dict[str, str]:\n _iso_inv_map(g1)\n _iso_inv_map(g2)\n\n hypothesis: Dict[str, str] = {}\n agenda: List[Tuple[str, str]] = next(\n _iso_candidates({top1: None}, {top2: None}, g1, g2, hypothesis),\n [])\n return next(_iso_vf2(hypothesis, g1, g2, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the neighbor ids of a given grain. This function find the ids of the neighboring grains. A mask is constructed by dilating the grain to encompass the immediate neighborhood of the grain. The ids can then be determined using numpy unique function. | def find_neighbors(self, grain_id, distance=1):
if not hasattr(self, 'grain_map'):
return []
grain_data = self.grain_map == grain_id
grain_data_dil = ndimage.binary_dilation(grain_data, iterations=distance).astype(np.uint8)
neighbor_ids = np.unique(self.grain_map[grain_data_d... | [
"def neighbor_indices(self):",
"def get_poly_neighbor_ids(poly):\n\n neighbor_ids = set()\n\n for edge in poly.edges:\n neighbor_ids.update(edge.merged_edge.polygon_ids)\n\n neighbor_ids.remove(poly.id)\n\n return neighbor_ids",
"def _localNonOverlappin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dilate a single grain overwriting the neighbors. | def dilate_grain(self, grain_id, dilation_steps=1, use_mask=False):
grain_volume_init = (self.grain_map == grain_id).sum()
grain_data = self.grain_map == grain_id
grain_data = ndimage.binary_dilation(grain_data, iterations=dilation_steps).astype(np.uint8)
if use_mask and hasattr(self, 'm... | [
"def dilate_grains(self, dilation_steps=1, dilation_ids=None):\n if not hasattr(self, 'grain_map'):\n raise ValueError('microstructure %s must have an associated grain_map attribute' % self.name)\n return\n\n grain_map = self.grain_map.copy()\n # get rid of overlap regions... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dilate labels isotropically to fill the gap between them. This code is based on the gtDilateGrains function from the DCT code. It has been extended to handle both 2D and 3D cases. | def dilate_labels(array, dilation_steps=1, mask=None, dilation_ids=None, struct=None):
from scipy import ndimage
if struct is None:
struct = ndimage.morphology.generate_binary_structure(array.ndim, 1)
assert struct.ndim == array.ndim
# carry out dilation in iterative steps
... | [
"def augmentation(dataset, labels):\n\n print(\"Augmentation\")\n\n # if necessary create aug dir and make sure it's empty\n if not os.path.exists(config.aug_dir):\n os.makedirs(config.aug_dir)\n else:\n os.system('rm -rf %s/*' % config.aug_dir)\n\n # sort ids based on category\n spl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dilate grains to fill the gap between them. This function calls `dilate_labels` with the grain map of the microstructure. | def dilate_grains(self, dilation_steps=1, dilation_ids=None):
if not hasattr(self, 'grain_map'):
raise ValueError('microstructure %s must have an associated grain_map attribute' % self.name)
return
grain_map = self.grain_map.copy()
# get rid of overlap regions flaged by ... | [
"def dilate_grain(self, grain_id, dilation_steps=1, use_mask=False):\n grain_volume_init = (self.grain_map == grain_id).sum()\n grain_data = self.grain_map == grain_id\n grain_data = ndimage.binary_dilation(grain_data, iterations=dilation_steps).astype(np.uint8)\n if use_mask and hasattr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Crop the microstructure to create a new one. | def crop(self, x_start, x_end, y_start, y_end, z_start, z_end):
micro_crop = Microstructure()
micro_crop.name = self.name + '_crop'
print('cropping microstructure to %s' % micro_crop.name)
micro_crop.grain_map = self.grain_map[x_start:x_end, y_start:y_end, z_start:z_end]
if hasat... | [
"def test_copy_part(self):\n framework = Framework(config_path=config_path)\n assembly = Framework.reader(framework.skeleton, settings=SETTINGS)\n new_fw = assembly.fw.copy_part()\n new_assembly = assembly.copy_part()\n\n assert id(assembly) != id(new_assembly)\n assert id(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the center of masses of a grain given its id. | def compute_grain_center(self, gid):
# isolate the grain within the complete grain map
slices = ndimage.find_objects(self.grain_map == gid)
if not len(slices) > 0:
raise ValueError('warning grain %d not found in grain map' % gid)
sl = slices[0]
offset = np.array([sl[0... | [
"def get_center_of_mass(self):\n atomos = self.get_coords()\n M = self.mol_weight\n centro = Matrix([[0, 0, 0]])\n for a in atomos:\n centro = centro + (Matrix([[a[1], a[2], a[3]]]) * PERIODIC_TABLE[a[0]][\"mass\"])\n centro *= (1 / M)\n return centro",
"def re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute and assign the center of all grains in the microstructure using the grain map. Each grain center is computed using its center of mass. The value is assigned to the grain.center attribute. If the voxel size is specified, the grain centers will be in mm unit, if not in voxel unit. | def recompute_grain_centers(self, verbose=False):
if not hasattr(self, 'grain_map'):
print('warning: need a grain map to recompute the center of mass of the grains')
return
for g in self.grains:
try:
com = self.compute_grain_center(g.id)
ex... | [
"def compute_grain_center(self, gid):\n # isolate the grain within the complete grain map\n slices = ndimage.find_objects(self.grain_map == gid)\n if not len(slices) > 0:\n raise ValueError('warning grain %d not found in grain map' % gid)\n sl = slices[0]\n offset = np.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write orientation data to ascii files to prepare for FFT computation. AMITEX_FFTP can be used to compute the elastoplastic response of polycrystalline microstructures. The calculation needs orientation data for each grain written in the form of the coordinates of the first two basis vectors expressed in the crystal loc... | def to_amitex_fftp(self, binary=True):
ext = 'bin' if binary else 'txt'
n1x = open('N1X.%s' % ext, 'w')
n1y = open('N1Y.%s' % ext, 'w')
n1z = open('N1Z.%s' % ext, 'w')
n2x = open('N2X.%s' % ext, 'w')
n2y = open('N2Y.%s' % ext, 'w')
n2z = open('N2Z.%s' % ext, 'w')
... | [
"def make_ascii_(self, metadata=[], data=[], output_file_name=''):\n with open(output_file_name, 'w') as f:\n for _meta in metadata:\n _line = _meta + \"\\n\"\n f.write(_line)\n for _data in data:\n _line = str(_data) + '\\n'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Outputs the material block corresponding to this microstructure for a finite element calculation with zset. | def print_zset_material_block(self, mat_file, grain_prefix='_ELSET'):
f = open('elset_list.txt', 'w')
for g in self.grains:
o = g.orientation
f.write(
' **elset %s%d *file %s *integration theta_method_a 1.0 1.e-9 150 *rotation %7.3f %7.3f %7.3f\n' % (
... | [
"def pwr_assembly():\n\n model = openmc.model.Model()\n\n # Define materials.\n fuel = openmc.Material(name='Fuel')\n fuel.set_density('g/cm3', 10.29769)\n fuel.add_nuclide('U234', 4.4843e-6)\n fuel.add_nuclide('U235', 5.5815e-4)\n fuel.add_nuclide('U238', 2.2408e-2)\n fuel.add_nuclide('O16'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write the microstructure as a hdf5 file. | def to_h5(self):
import time
from pymicro import __version__ as pymicro_version
print('opening file %s.h5 for writing' % self.name)
f = h5py.File('%s.h5' % self.name, 'w')
f.attrs['Pymicro_Version'] = np.string_(pymicro_version)
f.attrs['HDF5_Version'] = h5py.version.hdf... | [
"def write_hdf5_mesh(self):\n self._mesh.write_hdf5()",
"def writeHD5():\n global Data1\n\n store = HDFStore('.\\store.h5')\n store['listCrisis'] = Data1\n store.close()",
"def _save_hdf5(self, output_file_path=None):\n #save sync data\n if output_file_path:\n filenam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
read a microstructure object from a HDF5 file. | def from_h5(file_path):
with h5py.File(file_path, 'r') as f:
micro = Microstructure(name=f.attrs['microstructure_name'])
if 'symmetry' in f['EnsembleData/CrystalStructure'].attrs:
sym = f['EnsembleData/CrystalStructure'].attrs['symmetry']
parameters = f['E... | [
"def load_from_hdf5(obj, fname, obj_name):\n\n h5 = h5py.File(fname, 'r')\n root_grp = h5[obj_name]\n\n load_object(root_grp, obj, obj_name)\n h5.close()",
"def load_h5(self):\n path = os.path.join(self.directory, self.filename)\n self.h5file = tb.open_file(path, mode=self.mode)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a microstructure from a neper tesselation. Neper is an open source program to generate polycristalline microstructure using voronoi tesselations. | def from_neper(neper_file_path):
neper_file = neper_file_path.split(os.sep)[-1]
print('creating microstructure from Neper tesselation %s' % neper_file)
name, ext = os.path.splitext(neper_file)
print(name, ext)
assert ext == '.tesr' # assuming raster tesselation
micro = M... | [
"def create_schematic_from_mentor_netlist(self, file_to_import):\n xpos = 0\n ypos = 0\n delta = 0.0508\n use_instance = True\n my_netlist = []\n with open(file_to_import, 'r') as f:\n for line in f:\n my_netlist.append(line.split(\" \"))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a microstructure from a DCT reconstruction. DCT reconstructions are stored in several files. The indexed grain informations are stored in a matlab file in the '4_grains/phase_01' folder. Then, the reconstructed volume file (labeled image) is stored in the '5_reconstruction' folder as an hdf5 file, possibly store... | def from_dct(data_dir='.', grain_file='index.mat', vol_file='phase_01_vol.mat', mask_file='volume_mask.mat',
use_dct_path=True, verbose=True):
if data_dir == '.':
data_dir = os.getcwd()
if data_dir.endswith(os.sep):
data_dir = data_dir[:-1]
scan = data_di... | [
"def from_neper(neper_file_path):\n neper_file = neper_file_path.split(os.sep)[-1]\n print('creating microstructure from Neper tesselation %s' % neper_file)\n name, ext = os.path.splitext(neper_file)\n print(name, ext)\n assert ext == '.tesr' # assuming raster tesselation\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an XML representation of the Microstructure instance. | def to_xml(self, doc):
root = doc.createElement('Microstructure')
doc.appendChild(root)
name = doc.createElement('Name')
root.appendChild(name)
name_text = doc.createTextNode(self.name)
name.appendChild(name_text)
grains = doc.createElement('Grains')
root.... | [
"def xml(self):\n return oxml_tostring(self, encoding='UTF-8', standalone=True)",
"def xml(self):\n return self._domain.xml",
"def xml(self) -> ET.Element:\n return self.device_info.xml",
"def get_xml(self):\n return etree.tostring(self.xml_tree, pretty_print=True, encoding=\"u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saving the microstructure to the disk. Save the metadata as a XML file and when available, also save the vtk representation of the grains. | def save(self):
# save the microstructure instance as xml
doc = Document()
self.to_xml(doc)
xml_file_name = '%s.xml' % self.name
print('writing ' + xml_file_name)
f = open(xml_file_name, 'wb')
doc.writexml(f, encoding='utf-8')
f.close()
# now save ... | [
"def save(self) -> None:\n if self.meta.file_path:\n # We are a family root node or the user has decided to make us one\n # Save family information\n with self.meta.file_path.open('w') as of:\n of.write(self.to_json())\n\n # Now for saving language infor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge two `Microstructure` instances together. The function works for two microstructures with grain maps and an overlap between them. Temporarily `Microstructures` restricted to the overlap regions are created and grains are matched between the two based on a disorientation tolerance. | def merge_microstructures(micros, overlap, plot=False):
from scipy import ndimage
# perform some sanity checks
for i in range(2):
if not hasattr(micros[i], 'grain_map'):
raise ValueError('microstructure instance %s must have an associated grain_map attribute' % micro... | [
"def union(self, other, temporal_iou_threshold=0.5, spatial_iou_threshold=0.6, strict=True, overlap='average', percentilecover=0.8, percentilesamples=100, activity=True, track=True):\n assert overlap in ['average', 'replace', 'keep'], \"Invalid input - 'overlap' must be in [average, replace, keep]\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the average of the elements of array a. | def mean(a):
return sum(a) / float(len(a)) | [
"def avg_vec(a):\n avg = numpy.average(a, axis=0)\n arr = numpy.asarray(avg)\n return arr",
"def average(data):\n return 1.0*sum(data)/len(data)",
"def average(x):\r\n assert len(x) > 0\r\n return float(sum(x)) / len(x)",
"def func(arr):\n return arr.mean()",
"def average(data):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the standard deviation of the elements of array a. | def stddev(a):
return math.sqrt(var(a)) | [
"def stdev(self, nums):\n mean = float(sum(nums)) / len(nums)\n return math.sqrt(sum((n - mean) ** 2 for n in nums) / float(len(nums)))",
"def stddev(data):\n counts = len(data)\n ave = average(data)\n total = sum(data * data)\n return (total - ave**2) / counts",
"def standard_deviatio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the median of the elements of array a. | def median(a):
b = list(a) # Make a copy of a.
b.sort()
length = len(b)
if length % 2 == 1:
return b[length//2]
else:
return float(b[length//2 - 1] + b[length//2]) / 2.0 | [
"def findMedianSortedArray(self, A):\n S = len(A)\n m = S//2\n if S % 2 == 1:\n return A[m]\n return 0.5*(A[m] + A[m-1])",
"def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):\n return _statistics._median(a, axis, out, overwrite_input, keepdims)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the elements of array a as points. | def plotPoints(a):
n = len(a)
stddraw.setXscale(-1, n)
stddraw.setPenRadius(1.0 / (3.0 * n))
for i in range(n):
stddraw.point(i, a[i]) | [
"def plot_point(points: Union[Point, List[Point]], display=True):\n if isinstance(points, Point):\n points = [points]\n\n for point in points:\n plt.plot(point.x, point.y, \"-o\")\n plt.axes().set_aspect(\"equal\", \"datalim\")\n if display:\n plt.show()",
"def graph_scatter(arr, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the elements of array a as line endpoints. | def plotLines(a):
n = len(a)
stddraw.setXscale(-1, n)
stddraw.setPenRadius(0.0)
for i in range(1, n):
stddraw.line(i-1, a[i-1], i, a[i]) | [
"def plot_tri_array(array,ax):\n\tfor tri in array:\n\t\ttri_new = tri + [tri[0]]\n\t\ttri_x = [corner[0] for corner in tri_new]\n\t\ttri_y = [corner[1] for corner in tri_new]\n\t\tax.plot(tri_x,tri_y)",
"def plotPoints(a):\n n = len(a)\n stddraw.setXscale(-1, n)\n stddraw.setPenRadius(1.0 / (3.0 * n))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the elements of array a as bars. | def plotBars(a):
n = len(a)
stddraw.setXscale(-1, n)
for i in range(n):
stddraw.filledRectangle(i-0.25, 0.0, 0.5, a[i]) | [
"def bar_chart(values, xticks, title, xlabel, ylabel, barColor='b', barAlpha=1):\n if len(values)!=len(xticks):\n print 'Error: debe haber tantos grupos como etiquetas de barras.'\n return\n #Draw graph\n ind=np.arange(len(values))\n width=0.5\n p1 = plt.bar(ind, values, width, color=ba... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copy file from source to destination if needed (skip if source is destination). | def copy(source, destination):
source = os.path.abspath(source)
destination = os.path.abspath(destination)
if source != destination:
shutil.copyfile(source, destination) | [
"def copy_file(cls, path, source_dir, destination_dir):\n if not (source_dir / path).exists():\n return\n shutil.copyfile(str(source_dir / path), str(destination_dir / path))",
"def copy_file(self, source, destination, cmd=True):\n self._check_path(source)\n self._check_path... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Busca el proyecto por nombre | def filtrar(self, nombre):
return Proyecto.query.filter(Proyecto.nombre == nombre).first_or_404() | [
"def objeto_por_nome(self, nome):\n socios_registrados = [socio.nome for socio in self.__socios]\n funcionarios_registrados = [funcionario.nome for funcionario in self.__funcionarios]\n if nome in socios_registrados:\n objeto = self.__socios[socios_registrados.index(nome)]\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lista los proyectos Activos | def listarActivo(self):
return Proyecto.query.filter(Proyecto.estado == "Activo").all() | [
"def lista_procesos(self):\n for item in process_iter():\n try:\n data = item.as_dict(attrs=['pid', 'name', 'connections'])\n self.proclist.append(Proceso(pid=data['pid'],\n nombre=data['name'], imagen=item.exe(),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lista los proyectos Finalizados | def listarFinalizado(self):
return Proyecto.query.filter(Proyecto.estado == "Finalizado").all() | [
"def lista_procesos(self):\n for item in process_iter():\n try:\n data = item.as_dict(attrs=['pid', 'name', 'connections'])\n self.proclist.append(Proceso(pid=data['pid'],\n nombre=data['name'], imagen=item.exe(),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lista los proyectos Pendientes | def listarPendiente(self):
return Proyecto.query.filter(Proyecto.estado == "Pendiente").all() | [
"def lista_procesos(self):\n for item in process_iter():\n try:\n data = item.as_dict(attrs=['pid', 'name', 'connections'])\n self.proclist.append(Proceso(pid=data['pid'],\n nombre=data['name'], imagen=item.exe(),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna True si todas las fases del proyecto estan en estado desarrollo | def proyectoIniciado(self, nombre):
proyecto = self.filtrar(nombre)
for fase in proyecto.listafases:
if fase.estado != "Desarrollo":
return False
return True | [
"def proyectoFinalizado(self, nombre):\n proyecto = self.filtrar(nombre)\n for fase in proyecto.listafases:\n if fase.estado != \"Finalizado\":\n return False\n return True",
"def done_exposing(self):\n self.logger.debug(\"Checking if observation has exposures... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna true si todas las fases del proyecto estan en estado finalizado | def proyectoFinalizado(self, nombre):
proyecto = self.filtrar(nombre)
for fase in proyecto.listafases:
if fase.estado != "Finalizado":
return False
return True | [
"def has_finished_provenance(self):\n return len(self._pending) < self._pending_count",
"def check_finished(self):\n if self.max_iterations == -1:\n return False\n return self.iterations >= self.max_iterations",
"def is_finished(self):\n return len(self.legalMoves) == 0",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asigna un usuario al proyecto | def asignarUsuario(self, proyecto, user, rol):
if user in proyecto.users:
return ":NO asigno usuario: el usuario ya es miembro del proyecto"
if rol in user.roles:
return ":NO asigno el usuario: el usuario ya tiene asignado el rol"
else:
user.estad... | [
"def agregarUsuario(self, id_proyecto, id_usuario):\n try:\n usuario = DBSession.query(Usuario).get(id_usuario)\n proyecto = DBSession.query(Proyecto).get(id_proyecto)\n usuario.proyectos.append(proyecto)\n DBSession.flush()\n transaction.commit()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna usuarios de proyecto | def usersDeProyecto(self, nombre):
proyecto = self.filtrar(nombre)
return proyecto.users | [
"def usuarios_conectados():\n\n global my_user\n print(\"Actualizando clientes conectados.\")\n usuarios = api.get_AllUser()\n lista_usarios = []\n\n for user in usuarios:\n if user['Estado'] == '1':\n # Anadimos todos los users menos el propio.\n if user['Nombre'] != my_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Busca proyecto por Id | def filtrarXId(self, idProyecto):
return Proyecto.query.filter(Proyecto.idProyecto == idProyecto).first_or_404() | [
"def siguiente(self,id):\n consulta = \"select * from socios m \" \\\n \"where m.idsocio = (select min(idsocio) from socios s \" \\\n \"where s.idsocio > %s);\"\n try:\n datos = AccesoDatos()\n cur = datos.conectar()\n cur.execute(co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna fases del proyecto | def fasesDeProyecto(self, nombre):
proyecto = self.filtrar(nombre)
return proyecto.listafases | [
"def createFase():\n # proyecto 1\n p = MgrProyecto().filtrar(\"proyecto1\")\n t = MgrTipoDeItem().filtrar(\"TipoDeItem1\")\n f = Fase(nombre=\"proyecto1-fase1\", descripcion=\"nueva fase\", orden=1, proyectoId= p.idProyecto, tipoDeItemId=t.idTipoDeItem)\n MgrFase().guardar(f)\n \n p = MgrProye... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna el numero de fases del proyecto | def nroDeFaseDeProyecto(self, nombre):
proyecto = self.filtrar(nombre)
cont = 0
for i in proyecto.listafases:
if i != None:
cont = cont + 1
return cont | [
"def count (self):\n total = 1\n for dep in self.deps:\n total += dep.count()\n return total",
"def num_stages(self) -> int:\n pass",
"def fasesDeProyecto(self, nombre):\n proyecto = self.filtrar(nombre)\n return proyecto.listafases",
"def get_county_number():\n return len(ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ordena las fase de un proyecto | def ordenarFase(self, proyecto, fase):
for i in proyecto.listafases:
f = Fase.query.filter(Fase.idFase == i.idFase).first()
if f.orden > fase.orden and fase.orden != f.orden:
f.orden = f.orden - 1
db.session.commit()
return ":ordeno las fases:" | [
"def createFase():\n # proyecto 1\n p = MgrProyecto().filtrar(\"proyecto1\")\n t = MgrTipoDeItem().filtrar(\"TipoDeItem1\")\n f = Fase(nombre=\"proyecto1-fase1\", descripcion=\"nueva fase\", orden=1, proyectoId= p.idProyecto, tipoDeItemId=t.idTipoDeItem)\n MgrFase().guardar(f)\n \n p = MgrProye... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna True si el proyecto ya existe | def existe(self, proyecto):
p = Proyecto.query.filter(Proyecto.nombre == proyecto.nombre).first()
if p != None:
return True
else:
return False | [
"def does_project_exist(slug):\n return isdir(project_dir(slug))",
"def has_current_project(self):\n return os.path.exists(CURRENT_PROJECT)",
"def _validate_project_exists(self):\n odooclient = odoo_client.get_odoo_client()\n try:\n search = [['tenant_id', '=', self.project_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make a grid definition from the hindcasts, for e.g. regridding of the forecasts if they are on a inconsistent grid .. also adds a `n_members` global attribute to the grid, to be used to select the same number of members in the ensemble in the forecasts | def make_hindcasts_grid_def(provider='CDS', GCM='ECMWF', var_name='T2M', rpath='gdata', year=2016, month=12):
import pathlib
import xarray as xr
if rpath == 'local':
root_dir = pathlib.Path.home() / 'research' / 'Smart_Ideas' / 'data'
elif rpath == 'gdata':
root_dir = pathlib.Pa... | [
"def create_param_grid():\n # pop_size_list = np.arange(100,1300,300).tolist()\n gens_list = np.arange(100,1300,300).tolist()\n select_list = ['tournament', 'rank']\n crossover_list = ['cycle_co', 'pmx_co']\n # mutate_list = ['swap_mutation']\n co_p_list = np.arange(0.1,1.1,0.2).round(2).tolist()\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function deriving locations and devices array from the csv files considering timedelta(current_client_time start_time) 1 day is taken as a time unit > 100days corresponds to 100% | def get_locations_devices(self, days_delta):
mod = (days_delta % 100)/float(100)
locations = [None] * 3
devices = [None] * 3
#locations for interviewees(1,2,3)
employees2locations = company().employees2locations
for i in range(0, 3):
if mod <= employees2loca... | [
"def get_data_at_location(path, t_start, t_end, sensor_name):\r\n\r\n filename = path + '/' + sensor_name + '.csv'\r\n if os.path.isfile(filename):\r\n with open(filename) as file_in:\r\n data = csv.reader(file_in, delimiter='\\t')\r\n data_value = []\r\n for data_row i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates total price for list of menu items | def calc_total_price(items):
total_price = 0
for item in items:
total_price += item.get('price') * item.get('quantity')
return total_price | [
"def lineitem_price(self):\n price = Decimal(\"0.00\")\n for li in self.lineitems.all():\n price += li.total\n return price",
"def subtotal_calc(selected_products):\n subtotal = 0\n for product in selected_products:\n price = product[\"price\"]\n subtotal = pric... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all coordinates in a 2D region. If only one pair is provided, the loop will yield x1z1 values If two pairs are provided the loop will yield all results between them inclusively | def loop2d(x1, y1, x2=None, y2=None):
if x2 is None or y2 is None:
x1, y1, x2, y2 = 0, 0, x1 - 1, y1 - 1
for x in range(x1, x2 + 1):
for y in range(y1, y2 + 1):
yield x, y | [
"def pairs(\n x_coordinates: Iterable[float], y_coordinates: Iterable[float]\n) -> tuple[tuple[float, float], ...]:\n pairs = tuple(zip(x_coordinates, y_coordinates))\n return pairs",
"def rank_xy(pairs: Sequence[Pair]) -> Iterator[Ranked_XY]:\n return (\n Ranked_XY(r_x=r_x, r_y=rank_y_raw[0], ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the length of a word based on character width. If a letter is not found, a width of 9 is assumed A character spacing of 1 is automatically integrated | def fontwidth(word):
return sum([lookup.ASCIIPIXELS[letter] + 1
if letter in lookup.ASCIIPIXELS
else 10
for letter in word]) - 1 | [
"def w(i, j):\n global L\n\n width = 0\n for word in words[i: j + 1]:\n # length of a word + blank space\n width += len(word) + 1\n\n # remove last blank space\n width -= 1\n\n return width if 0 < width <= L else 0",
"def _string_width(self, s):\r\n s = str(s)\r\n w =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Place a lectern with a book in the world. | def placeLectern(x, y, z, bookData, worldModif, facing="east"):
# worldModif.setBlock(x, y, z, f"lectern[facing={facing}, has_book=true]")
# _utils.addBookToLectern(x, y, z, bookData)
"""**Place a lectern with a book in the world**."""
if facing is None:
facing = choice(getOptimalDirection(... | [
"def create_book(self, title, ident):\n\n new_book = item.Book(title, ident)\n\n self.library_controller.add_item(new_book)",
"def crewtut():\n\n from pirates.tutorial.CrewTutorial import CrewTutorial\n spellbook.getManager().crewTutorial = CrewTutorial()",
"def book():\n update_calendar.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Place an invetorized block with any number of items in the world. Items is expected to be a sequence of (x, y, item[, amount]) or a sequence of such sequences e.g. ((x, y, item), (x, y, item), ...) | def placeInventoryBlock(x, y, z, block='minecraft:chest', facing=None,
items=[]):
if block not in lookup.INVENTORYLOOKUP:
raise ValueError(f"The inventory for {block} is not available.\n"
"Make sure you are using the namespaced ID.")
dx, dy = lookup.INVEN... | [
"def place_spawn_items(width, height, cell_size, xmin, ymin, punishement=True):\n #Still the original function\n #Initialize\n item_start = 20;\n num_items = 4\n output=[]\n items = []\n locations=[]\n punishements=[]\n \"\"\"\n #Place spawn at random\n spawn_i = random.randint(0, w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Place a written sign in the world. Facing is for wall placement, rotation for ground placement If there is no supporting wall the sign will revert to ground placement By default the sign will attempt to orient itself to be most legible | def placeSign(x, y, z, facing=None, rotation=None,
text1="", text2="", text3="", text4="",
wood='oak', wall=False):
if wood not in lookup.WOODS:
raise ValueError(f"{wood} is not a valid wood type!")
if facing is not None and facing not in lookup.DIRECTIONS:
print(f"{... | [
"def build_entity(raw_sign_image, sign_rect, sign_data, x, y):\t#not sure if I can use sign_key-- might need a different structure to figure out the proper text\n\t\tstill_entity_image = GameImage.still_animation_set(raw_sign_image, sign_rect)\n\t\tsign = Sign(still_entity_image, x, y)\n\t\tsign_text_panes = sign_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the percieved obtrusiveness of a given block. Returns a numeric weight from 0 (invisible) to 4 (opaque) | def identifyObtrusiveness(blockStr):
if blockStr in lookup.INVISIBLE:
return 0
if blockStr in lookup.FILTERING:
return 1
if blockStr in lookup.UNOBTRUSIVE:
return 2
if blockStr in lookup.OBTRUSIVE:
return 3
return 4 | [
"def get_blocker_wind_efficiency(self, index_of_the_star):\n return self.get_control(index_of_the_star,'blocker_scaling_factor')",
"def calc_shield_power(block_count, active=False):\n if active:\n return block_count * 55.0 \n else:\n return block_count * 5.5",
"def get_weight(self) ->... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process a text and create a Doc object. | def process_text(model_name: str, text: str) -> spacy.tokens.Doc:
nlp = load_model(model_name)
return nlp(text) | [
"def __call__(self, text: str) -> Doc:\n if self.preprocessor:\n text = self.preprocessor(text)\n juman_lines = self._juman_parse(text)\n dtokens = self._detailed_tokens(juman_lines)\n doc = self._dtokens_to_doc(dtokens)\n self.set_juman_fstring(doc, juman_lines)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the status of a registered wallet | async def get_wallet_status(self, wallet_id: str) -> dict:
result = await self._fetch(messages.WalletStatusReq(wallet_id), messages.WalletStatus)
return result.status | [
"def jsonrpc_wallet_status(self, wallet_id=None):\n if self.wallet_manager is None:\n return {'is_encrypted': None, 'is_syncing': None, 'is_locked': None}\n wallet = self.wallet_manager.get_wallet_or_default(wallet_id)\n return {\n 'is_encrypted': wallet.is_encrypted,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a verifier service | async def register_verifier(self, wallet_id: str, config: dict) -> str:
result = await self._fetch(
messages.RegisterAgentReq(AgentType.verifier.value, wallet_id, config),
messages.AgentStatus)
return result.agent_id | [
"def register(self, service, factory=..., instance=..., scope=..., **kwargs):\n ...",
"def register_service_and_impl(self, service, scope, impl, resolve_args):\n ...",
"def register_concrete_service(self, service, scope):\n ...",
"def save_verifier(self, token, verifier, request):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch the status of a registered agent (issuer, holder, or verifier) | async def get_agent_status(self, agent_id: str) -> dict:
result = await self._fetch(messages.AgentStatusReq(agent_id), messages.AgentStatus)
return result.status | [
"def agent_status(self,idx):\n agent = self.crowd.getAgent(idx)\n # translate a few coordinates\n class status:\n pass\n result = status()\n result.npos = detour2panda(agent.npos)\n tmp = detour2panda(agent.vel)\n result.vel = Vec3(tmp.getX(),tmp.getY(),tm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a credential type for a previouslyregistered issuer | async def register_credential_type(self, issuer_id: str,
schema_name: str, schema_version: str,
origin_did: str, attr_names: Sequence,
config: dict = None,
dependen... | [
"def register_domain_type(domain_class, type_key):",
"def __setitem__(self, issuer_id, key_issuer):\n self._issuers[issuer_id] = key_issuer",
"def register_provider(args):\n if len(args) == 0:\n click.echo(\"Usage: mephisto register <provider_type> arg1=value arg2=value\")\n return\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a connection to TheOrgBook as a holder/prover | async def register_orgbook_connection(self, agent_id: str, config: dict = None) -> str:
result = await self._fetch(
messages.RegisterConnectionReq(ConnectionType.TheOrgBook.value, agent_id, config or {}),
messages.ConnectionStatus)
return result.connection_id | [
"def make_connection(self, connection):\n connection.make_connection()\n connection.battery.add_house(connection.house)\n connection.house.set_connection()",
"def register_computer(self, host, port, comp_id = None):\n if comp_id is None:\n comp_id = str(uuid.uuid4())\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a connection to a local holder agent | async def register_holder_connection(self, agent_id: str, config: dict = None) -> str:
result = await self._fetch(
messages.RegisterConnectionReq(ConnectionType.holder.value, agent_id, config or {}),
messages.ConnectionStatus)
return result.connection_id | [
"def __init__(self, conn: \"AcmedaConnection\", addr: str):\n log.info(f\"Registering hub {addr}\")\n self.conn = conn\n self.addr = addr\n self.motors: Dict[str, \"Motor\"] = {}\n\n log.info(f\"Requesting motor info for hub {addr}\")\n asyncio.create_task(self.request_moto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch the status of a registered connection | async def get_connection_status(self, connection_id: str) -> dict:
result = await self._fetch(
messages.ConnectionStatusReq(connection_id),
messages.ConnectionStatus)
return result.status | [
"def get_connection_status():\n command = ['ping', '-c', '2', '-I', '3g-wan', '-W', '1', '8.8.8.8']\n return run_command(command)",
"def GetConnectionStatus(self):\n return [self.connection_state, self.connection_info]",
"def status(self):\n connection = self.connection()\n\n # the co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a credential request for an issuer service | async def create_credential_request(self, holder_id: str, cred_offer: dict,
cred_def_id: str) -> messages.CredentialRequest:
return await self._fetch(
messages.GenerateCredentialRequestReq(
holder_id,
messages.CredentialOffer(cr... | [
"def req_cred(email, cred, url):\n try:\n req = url + '/accounts/service_credential_request?email=' + email\n res = requests.post(req)\n render_res(res)\n except CLIError as e:\n render_error(e.asdict())",
"def _generate_credential() -> dict:\n\n return {\n \"ac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets credentials for a given organization | async def get_org_credentials(self, connection_id: str, org_name: str) -> messages.OrganizationCredentials:
return await self._fetch(messages.OrganizationCredentialsReq(connection_id, org_name)) | [
"def find_credentials(account):\n return Credentials.find_by_account(account)",
"def find_credentials(account):\n\treturn Credentials.find_credentials(account)",
"def _get_credentials():\n if not CONFIG:\n raise ConfigError(\"Configuration is not passed\")\n\n try:\n return CONFIG[\"crede... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets credentials for a given organization and proof request | async def get_filtered_credentials(self, connection_id: str, org_name: str, proof_name: str, fetch_all: bool) -> messages.OrganizationCredentials:
return await self._fetch(messages.FilterCredentialsReq(connection_id, org_name, proof_name, fetch_all)) | [
"def extractCredentials(self, request):\n creds={}\n identity=request.form.get(\"__ac_identity_url\", \"\").strip()\n if identity != \"\":\n self.initiateChallenge(identity)\n return creds\n\n self.extractOpenIdServerResponse(request, creds)\n return creds",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a credentials dependencies | async def get_credential_dependencies(self,
name: str,
version: str = None,
origin_did: str = None,
dependency_graph=None,
... | [
"def getCreds():\n key = os.environ['ConsumerKey']\n secret = os.environ['ConsumerSecret']\n\n return (key, secret)",
"def get_credentials_requests():\n gqlapi = gql.get_api()\n return gqlapi.query(CREDENTIALS_REQUESTS_QUERY)[\"credentials_requests\"]",
"def getCredentials(self):\n creds =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an endpoint for a did | async def get_endpoint(self, did: str) -> messages.Endpoint:
return await self._fetch(
messages.EndpointReq(did), messages.Endpoint) | [
"async def get_endpoint(self, did: str) -> str:\n\n logger = logging.getLogger(__name__)\n logger.debug('_AgentCore.get_endpoint: >>> did: {}'.format(did))\n\n rv = json.dumps({})\n req_json = await ledger.build_get_attrib_request(\n self.did,\n did,\n 'e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct a proof from credentials in the holder's wallet given a proof request | async def construct_proof(self, holder_id: str, proof_req: dict,
wql_filters: dict = None,
cred_ids: set = None) -> messages.ConstructedProof:
return await self._fetch(
messages.ConstructProofReq(
holder_id,
... | [
"async def create_proof(self, proof_req: dict, briefs: Union[dict, Sequence[dict]], requested_creds: dict) -> str:\n\n LOGGER.debug(\n 'HolderProver.create_proof >>> proof_req: %s, briefs: %s, requested_creds: %s',\n proof_req,\n briefs,\n requested_creds)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a proof request specification | async def register_proof_spec(self, spec: dict) -> str:
result = await self._fetch(
messages.RegisterProofSpecReq(spec),
messages.ProofSpecStatus)
return result.spec_id | [
"def create_req(self):\n \n pass",
"async def create_proof(self, proof_req: dict, briefs: Union[dict, Sequence[dict]], requested_creds: dict) -> str:\n\n LOGGER.debug(\n 'HolderProver.create_proof >>> proof_req: %s, briefs: %s, requested_creds: %s',\n proof_req,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a proof request based on a previouslyregistered proof request spec | async def generate_proof_request(self, spec_id: str) -> messages.ProofRequest:
return await self._fetch(
messages.GenerateProofRequestReq(spec_id),
messages.ProofRequest) | [
"async def create_proof(self, proof_req: dict, briefs: Union[dict, Sequence[dict]], requested_creds: dict) -> str:\n\n LOGGER.debug(\n 'HolderProver.create_proof >>> proof_req: %s, briefs: %s, requested_creds: %s',\n proof_req,\n briefs,\n requested_creds)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Request a proof from a holder connection | async def request_proof(self,
connection_id: str,
proof_req: messages.ProofRequest,
cred_ids: set = None,
params: dict = None) -> messages.ConstructedProof:
return await self._fetch(
messa... | [
"def test_state_proof_checked_in_client_request(looper, txnPoolNodeSet,\n client1, wallet1):\n request = sendRandomRequest(wallet1, client1)\n responseTimeout = waits.expectedTransactionExecutionTime(nodeCount)\n looper.run(\n eventually(check_proved_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a directory for images to be stored | def create_image_directory():
if not os.path.exists("Images"):
os.makedirs("Images") | [
"def createImages():\n if not isdir(\"images\"):\n mkdir(\"images\")",
"def make_image_directory():\n directory = '/Users/jon/PycharmProjects/Cleveland_VAE/data/images/' + hyperparameter_string\n if not os.path.exists(directory):\n os.makedirs(directory)",
"def get_image_dir():\n now =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get summary from all wikipedia pages with a title in titles | def get_summaries(titles, title_data):
length = len(titles)
index = 0
while index < length:
multi_title = sanatize_url(titles[index])
for _ in range(20): # Collect 20 titles at a time
if index < length:
multi_title += '|' + sanatize_url(titles[index])
... | [
"def get_wiki_summary(request):\n while 1:\n data = requests.get(\n f'https://en.wikipedia.org/w/api.php?action=query&titles={request}&prop=extracts&exintro=&exsentences=10&format=json&redirects'\n ).json()\n if '-1' in data['query']['pages']:\n if ',' not in reques... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get every category from every title in titles | def get_categories_from_title(titles, title_data):
length = len(titles)
index = 0
while index < length:
multi_title = sanatize_url(titles[index])
for _ in range(20): # Collect 20 titles at a time
if index < length:
multi_title += '|' + sanatize_url(titles[index])
... | [
"def get_news_with_categories():\n # saving articles urls in list\n articles = ['https://inshorts.com/en/read/business','https://inshorts.com/en/read/sports','https://inshorts.com/en/read/technology','https://inshorts.com/en/read/entertainment']\n # creating empty list\n l = []\n # iterating through ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
downloads all images from the url_list into the Images directory | def download_images(url_list):
print("\nDownloading images into Images folder:")
length = len(url_list)
for index, url in enumerate(url_list): # download all images
progress_update(index, length)
name = url.split('/')[-1]
if len(name) > 250: # change name if name is too long
... | [
"def download_images(self):\n \n if not os.path.exists(self.images_folder):\n os.makedirs(self.images_folder)\n print(f\"{Fore.GREEN}[+]{Style.RESET_ALL} `{self.images_folder}` folder created.\")\n \n for url in self.images(link=True):\n content = request... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a timedelta object of n days | def days(n):
return timedelta(days=n) | [
"def seconds2days(n):\n days = n / 60 / 60 / 24\n return days",
"def delta(value, arg):\n return value + timedelta(days=arg)",
"def number_of_days(iteration):\r\n return iteration // 24",
"def minusndays(date,n):\n \n date_format = \"%Y-%m-%d\"\n return (datetime.strptime(date,date_format... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |