nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/bdf/bdf_interface/add_card.py
python
AddCards.add_qbdy1
(self, sid, qflux, eids, comment='')
return load
Creates a QBDY1 card
Creates a QBDY1 card
[ "Creates", "a", "QBDY1", "card" ]
def add_qbdy1(self, sid, qflux, eids, comment='') -> QBDY1: """Creates a QBDY1 card""" load = QBDY1(sid, qflux, eids, comment=comment) self._add_methods._add_thermal_load_object(load) return load
[ "def", "add_qbdy1", "(", "self", ",", "sid", ",", "qflux", ",", "eids", ",", "comment", "=", "''", ")", "->", "QBDY1", ":", "load", "=", "QBDY1", "(", "sid", ",", "qflux", ",", "eids", ",", "comment", "=", "comment", ")", "self", ".", "_add_methods...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/bdf_interface/add_card.py#L7973-L7977
mrkipling/maraschino
c6be9286937783ae01df2d6d8cebfc8b2734a7d7
lib/sqlalchemy/orm/__init__.py
python
contains_alias
(alias)
return AliasOption(alias)
Return a :class:`.MapperOption` that will indicate to the query that the main table has been aliased. This is used in the very rare case that :func:`.contains_eager` is being used in conjunction with a user-defined SELECT statement that aliases the parent table. E.g.:: # define an aliased UNION called 'ulist' statement = users.select(users.c.user_id==7).\\ union(users.select(users.c.user_id>7)).\\ alias('ulist') # add on an eager load of "addresses" statement = statement.outerjoin(addresses).\\ select().apply_labels() # create query, indicating "ulist" will be an # alias for the main table, "addresses" # property should be eager loaded query = session.query(User).options( contains_alias('ulist'), contains_eager('addresses')) # then get results via the statement results = query.from_statement(statement).all() :param alias: is the string name of an alias, or a :class:`~.sql.expression.Alias` object representing the alias.
Return a :class:`.MapperOption` that will indicate to the query that the main table has been aliased.
[ "Return", "a", ":", "class", ":", ".", "MapperOption", "that", "will", "indicate", "to", "the", "query", "that", "the", "main", "table", "has", "been", "aliased", "." ]
def contains_alias(alias): """Return a :class:`.MapperOption` that will indicate to the query that the main table has been aliased. This is used in the very rare case that :func:`.contains_eager` is being used in conjunction with a user-defined SELECT statement that aliases the parent table. E.g.:: # define an aliased UNION called 'ulist' statement = users.select(users.c.user_id==7).\\ union(users.select(users.c.user_id>7)).\\ alias('ulist') # add on an eager load of "addresses" statement = statement.outerjoin(addresses).\\ select().apply_labels() # create query, indicating "ulist" will be an # alias for the main table, "addresses" # property should be eager loaded query = session.query(User).options( contains_alias('ulist'), contains_eager('addresses')) # then get results via the statement results = query.from_statement(statement).all() :param alias: is the string name of an alias, or a :class:`~.sql.expression.Alias` object representing the alias. """ return AliasOption(alias)
[ "def", "contains_alias", "(", "alias", ")", ":", "return", "AliasOption", "(", "alias", ")" ]
https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/sqlalchemy/orm/__init__.py#L1467-L1499
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/contrib/humanize/templatetags/humanize.py
python
intword
(value)
return value
Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'.
Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'.
[ "Converts", "a", "large", "integer", "to", "a", "friendly", "text", "representation", ".", "Works", "best", "for", "numbers", "over", "1", "million", ".", "For", "example", "1000000", "becomes", "1", ".", "0", "million", "1200000", "becomes", "1", ".", "2"...
def intword(value): """ Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. """ try: value = int(value) except (TypeError, ValueError): return value if value < 1000000: return value def _check_for_i18n(value, float_formatted, string_formatted): """ Use the i18n enabled defaultfilters.floatformat if possible """ if settings.USE_L10N: value = defaultfilters.floatformat(value, 1) template = string_formatted else: template = float_formatted return template % {'value': value} for exponent, converters in intword_converters: large_number = 10 ** exponent if value < large_number * 1000: new_value = value / float(large_number) return _check_for_i18n(new_value, *converters(new_value)) return value
[ "def", "intword", "(", "value", ")", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "value", "if", "value", "<", "1000000", ":", "return", "value", "def", "_check_for_i18n", "...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/contrib/humanize/templatetags/humanize.py#L99-L129
natashamjaques/neural_chat
ddb977bb4602a67c460d02231e7bbf7b2cb49a97
ParlAI/parlai/mturk/core/dev/socket_manager.py
python
Packet.get_receiver_connection_id
(self)
return '{}_{}'.format(self.receiver_id, self.assignment_id)
Get the connection_id that this is going to
Get the connection_id that this is going to
[ "Get", "the", "connection_id", "that", "this", "is", "going", "to" ]
def get_receiver_connection_id(self): """Get the connection_id that this is going to""" return '{}_{}'.format(self.receiver_id, self.assignment_id)
[ "def", "get_receiver_connection_id", "(", "self", ")", ":", "return", "'{}_{}'", ".", "format", "(", "self", ".", "receiver_id", ",", "self", ".", "assignment_id", ")" ]
https://github.com/natashamjaques/neural_chat/blob/ddb977bb4602a67c460d02231e7bbf7b2cb49a97/ParlAI/parlai/mturk/core/dev/socket_manager.py#L116-L118
menpo/menpo
a61500656c4fc2eea82497684f13cc31a605550b
menpo/transform/homogeneous/base.py
python
Homogeneous.compose_after_from_vector_inplace
(self, vector)
[]
def compose_after_from_vector_inplace(self, vector): self.compose_after_inplace(self.from_vector(vector))
[ "def", "compose_after_from_vector_inplace", "(", "self", ",", "vector", ")", ":", "self", ".", "compose_after_inplace", "(", "self", ".", "from_vector", "(", "vector", ")", ")" ]
https://github.com/menpo/menpo/blob/a61500656c4fc2eea82497684f13cc31a605550b/menpo/transform/homogeneous/base.py#L298-L299
Gallopsled/pwntools
1573957cc8b1957399b7cc9bfae0c6f80630d5d4
pwnlib/tubes/tube.py
python
tube.sendlinethen
(self, delim, data, timeout = default)
return self.recvuntil(delim, timeout=timeout)
sendlinethen(delim, data, timeout = default) -> str A combination of ``sendline(data)`` and ``recvuntil(delim, timeout=timeout)``.
sendlinethen(delim, data, timeout = default) -> str
[ "sendlinethen", "(", "delim", "data", "timeout", "=", "default", ")", "-", ">", "str" ]
def sendlinethen(self, delim, data, timeout = default): """sendlinethen(delim, data, timeout = default) -> str A combination of ``sendline(data)`` and ``recvuntil(delim, timeout=timeout)``.""" data = packing._need_bytes(data) self.sendline(data) return self.recvuntil(delim, timeout=timeout)
[ "def", "sendlinethen", "(", "self", ",", "delim", ",", "data", ",", "timeout", "=", "default", ")", ":", "data", "=", "packing", ".", "_need_bytes", "(", "data", ")", "self", ".", "sendline", "(", "data", ")", "return", "self", ".", "recvuntil", "(", ...
https://github.com/Gallopsled/pwntools/blob/1573957cc8b1957399b7cc9bfae0c6f80630d5d4/pwnlib/tubes/tube.py#L821-L828
GalSim-developers/GalSim
a05d4ec3b8d8574f99d3b0606ad882cbba53f345
devel/brighter-fatter/bf_plots_20Oct17.py
python
main
(argv)
Make images to be used for characterizing the brighter-fatter effect - Each fits file is 5 x 5 postage stamps. - Each postage stamp is 40 x 40 pixels. - There are 3 sets of 5 images each. The 5 images are at 5 different flux levels - The three sets are (bf_1) B-F off, (bf_2) B-F on, diffusion off, (bf_3) B-F and diffusion on - Each image is in output/bf_set/bf_nfile.fits, where set ranges from 1-3 and nfile ranges from 1-5.
Make images to be used for characterizing the brighter-fatter effect - Each fits file is 5 x 5 postage stamps. - Each postage stamp is 40 x 40 pixels. - There are 3 sets of 5 images each. The 5 images are at 5 different flux levels - The three sets are (bf_1) B-F off, (bf_2) B-F on, diffusion off, (bf_3) B-F and diffusion on - Each image is in output/bf_set/bf_nfile.fits, where set ranges from 1-3 and nfile ranges from 1-5.
[ "Make", "images", "to", "be", "used", "for", "characterizing", "the", "brighter", "-", "fatter", "effect", "-", "Each", "fits", "file", "is", "5", "x", "5", "postage", "stamps", ".", "-", "Each", "postage", "stamp", "is", "40", "x", "40", "pixels", "."...
def main(argv): """ Make images to be used for characterizing the brighter-fatter effect - Each fits file is 5 x 5 postage stamps. - Each postage stamp is 40 x 40 pixels. - There are 3 sets of 5 images each. The 5 images are at 5 different flux levels - The three sets are (bf_1) B-F off, (bf_2) B-F on, diffusion off, (bf_3) B-F and diffusion on - Each image is in output/bf_set/bf_nfile.fits, where set ranges from 1-3 and nfile ranges from 1-5. """ logging.basicConfig(format="%(message)s", level=logging.INFO, stream=sys.stdout) logger = logging.getLogger("bf_plots") # Add the wavelength info bppath = "../../share/bandpasses/" sedpath = "../../share/" sed = galsim.SED(os.path.join(sedpath, 'CWW_E_ext.sed'), 'nm', 'flambda').thin() # Add the directions (seems to work - CL) fratio = 1.2 obscuration = 0.2 seed = 12345 assigner = galsim.FRatioAngles(fratio, obscuration, seed) bandpass = galsim.Bandpass(os.path.join(bppath, 'LSST_r.dat'), 'nm').thin() rng3 = galsim.BaseDeviate(1234) sampler = galsim.WavelengthSampler(sed, bandpass, rng3) # Define some parameters we'll use below. # Normally these would be read in from some parameter file. nx_tiles = 10 # ny_tiles = 10 # stamp_xsize = 40 # stamp_ysize = 40 # random_seed = 6424512 # pixel_scale = 0.2 # arcsec / pixel sky_level = 0.01 # ADU / arcsec^2 # Make output directory if not already present. if not os.path.isdir('output'): os.mkdir('output') gal_sigma = 0.2 # arcsec psf_sigma = 0.01 # arcsec pixel_scale = 0.2 # arcsec / pixel noise = 0.01 # standard deviation of the counts in each pixel shift_radius = 0.2 # arcsec (=pixels) logger.info('Starting bf_plots using:') logger.info(' - image with %d x %d postage stamps',nx_tiles,ny_tiles) logger.info(' - postage stamps of size %d x %d pixels',stamp_xsize,stamp_ysize) logger.info(' - Centroid shifts up to = %.2f pixels',shift_radius) rng = galsim.BaseDeviate(5678) sensor1 = galsim.Sensor() sensor2 = galsim.SiliconSensor(rng=rng, diffusion_factor=0.0) sensor3 = galsim.SiliconSensor(rng=rng) for set in range(1,4): starttime = time.time() exec("sensor = sensor%d"%set) for nfile in range(1,6): # Make bf_x directory if not already present. if not os.path.isdir('output/bf_%d'%set): os.mkdir('output/bf_%d'%set) gal_file_name = os.path.join('output','bf_%d/bf_%d.fits'%(set,nfile)) sex_file_name = os.path.join('output','bf_%d/bf_%d_SEX.fits.cat.reg'%(set,nfile)) sexfile = open(sex_file_name, 'w') gal_flux = 2.0e5 * nfile # total counts on the image # Define the galaxy profile gal = galsim.Gaussian(flux=gal_flux, sigma=gal_sigma) logger.debug('Made galaxy profile') # Define the PSF profile psf = galsim.Gaussian(flux=1., sigma=psf_sigma) # PSF flux should always = 1 logger.debug('Made PSF profile') # This profile is placed with different orientations and noise realizations # at each postage stamp in the gal image. gal_image = galsim.ImageF(stamp_xsize * nx_tiles-1 , stamp_ysize * ny_tiles-1, scale=pixel_scale) psf_image = galsim.ImageF(stamp_xsize * nx_tiles-1 , stamp_ysize * ny_tiles-1, scale=pixel_scale) shift_radius_sq = shift_radius**2 first_in_pair = True # Make pairs that are rotated by 90 degrees k = 0 for iy in range(ny_tiles): for ix in range(nx_tiles): # The normal procedure for setting random numbers in GalSim is to start a new # random number generator for each object using sequential seed values. # This sounds weird at first (especially if you were indoctrinated by Numerical # Recipes), but for the boost random number generator we use, the "random" # number sequences produced from sequential initial seeds are highly uncorrelated. # # The reason for this procedure is that when we use multiple processes to build # our images, we want to make sure that the results are deterministic regardless # of the way the objects get parcelled out to the different processes. # # Of course, this script isn't using multiple processes, so it isn't required here. # However, we do it nonetheless in order to get the same results as the config # version of this demo script (demo5.yaml). ud = galsim.UniformDeviate(random_seed+k) # Any kind of random number generator can take another RNG as its first # argument rather than a seed value. This makes both objects use the same # underlying generator for their pseudo-random values. #gd = galsim.GaussianDeviate(ud, sigma=gal_ellip_rms) # The -1's in the next line are to provide a border of # 1 pixel between postage stamps b = galsim.BoundsI(ix*stamp_xsize+1 , (ix+1)*stamp_xsize-1, iy*stamp_ysize+1 , (iy+1)*stamp_ysize-1) sub_gal_image = gal_image[b] sub_psf_image = psf_image[b] # Great08 randomized the locations of the two galaxies in each pair, # but for simplicity, we just do them in sequential postage stamps. if first_in_pair: # Use a random orientation: beta = ud() * 2. * math.pi * galsim.radians # Determine the ellipticity to use for this galaxy. ellip = 0.0 first_in_pair = False else: # Use the previous ellip and beta + 90 degrees beta += 90 * galsim.degrees first_in_pair = True # Make a new copy of the galaxy with an applied e1/e2-type distortion # by specifying the ellipticity and a real-space position angle this_gal = gal#gal.shear(e=ellip, beta=beta) # Apply a random shift_radius: rsq = 2 * shift_radius_sq while (rsq > shift_radius_sq): dx = (2*ud()-1) * shift_radius dy = (2*ud()-1) * shift_radius rsq = dx**2 + dy**2 this_gal = this_gal.shift(dx,dy) # Note that the shifted psf that we create here is purely for the purpose of being able # to draw a separate, shifted psf image. We do not use it when convolving the galaxy # with the psf. this_psf = psf.shift(dx,dy) # Make the final image, convolving with the (unshifted) psf final_gal = galsim.Convolve([psf,this_gal]) # Draw the image if ix == 0 and iy == 0: final_gal.drawImage(sub_gal_image, method = 'phot', sensor=sensor, surface_ops=[sampler, assigner], rng = rng, save_photons = True) photon_file = os.path.join('output','bf_%d/bf_%d_nx_%d_ny_%d_photon_file.fits'%(set,nfile,ix,iy)) sub_gal_image.photons.write(photon_file) else: final_gal.drawImage(sub_gal_image, method = 'phot', sensor=sensor, surface_ops=[sampler, assigner], rng = rng) # Now add an appropriate amount of noise to get our desired S/N # There are lots of definitions of S/N, but here is the one used by Great08 # We use a weighted integral of the flux: # S = sum W(x,y) I(x,y) / sum W(x,y) # N^2 = Var(S) = sum W(x,y)^2 Var(I(x,y)) / (sum W(x,y))^2 # Now we assume that Var(I(x,y)) is constant so # Var(I(x,y)) = noise_var # We also assume that we are using a matched filter for W, so W(x,y) = I(x,y). # Then a few things cancel and we find that # S/N = sqrt( sum I(x,y)^2 / noise_var ) # # The above procedure is encapsulated in the function image.addNoiseSNR which # sets the flux appropriately given the variance of the noise model. # In our case, noise_var = sky_level_pixel sky_level_pixel = sky_level * pixel_scale**2 noise = galsim.PoissonNoise(ud, sky_level=sky_level_pixel) #sub_gal_image.addNoiseSNR(noise, gal_signal_to_noise) # Draw the PSF image # No noise on PSF images. Just draw it as is. this_psf.drawImage(sub_psf_image) # For first instance, measure moments """ if ix==0 and iy==0: psf_shape = sub_psf_image.FindAdaptiveMom() temp_e = psf_shape.observed_shape.e if temp_e > 0.0: g_to_e = psf_shape.observed_shape.g / temp_e else: g_to_e = 0.0 logger.info('Measured best-fit elliptical Gaussian for first PSF image: ') logger.info(' g1, g2, sigma = %7.4f, %7.4f, %7.4f (pixels)', g_to_e*psf_shape.observed_shape.e1, g_to_e*psf_shape.observed_shape.e2, psf_shape.moments_sigma) """ x = b.center().x y = b.center().y logger.info('Galaxy (%d,%d): center = (%.0f,%0.f) (e,beta) = (%.4f,%.3f)', ix,iy,x,y,ellip,beta/galsim.radians) k = k+1 sexline = 'circle %f %f %f\n'%(x+dx/pixel_scale,y+dy/pixel_scale,gal_sigma/pixel_scale) sexfile.write(sexline) sexfile.close() logger.info('Done making images of postage stamps') # Now write the images to disk. #psf_image.write(psf_file_name) #logger.info('Wrote PSF file %s',psf_file_name) gal_image.write(gal_file_name) logger.info('Wrote image to %r',gal_file_name) # using %r adds quotes around filename for us finishtime = time.time() print("Time to complete set %d = %.2f seconds\n"%(set, finishtime-starttime))
[ "def", "main", "(", "argv", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "\"%(message)s\"", ",", "level", "=", "logging", ".", "INFO", ",", "stream", "=", "sys", ".", "stdout", ")", "logger", "=", "logging", ".", "getLogger", "(", "\"bf...
https://github.com/GalSim-developers/GalSim/blob/a05d4ec3b8d8574f99d3b0606ad882cbba53f345/devel/brighter-fatter/bf_plots_20Oct17.py#L42-L263
huggingface/datasets
249b4a38390bf1543f5b6e2f3dc208b5689c1c13
src/datasets/arrow_dataset.py
python
Dataset.add_faiss_index
( self, column: str, index_name: Optional[str] = None, device: Optional[int] = None, string_factory: Optional[str] = None, metric_type: Optional[int] = None, custom_index: Optional["faiss.Index"] = None, # noqa: F821 train_size: Optional[int] = None, faiss_verbose: bool = False, dtype=np.float32, )
return self
Add a dense index using Faiss for fast retrieval. By default the index is done over the vectors of the specified column. You can specify :obj:`device` if you want to run it on GPU (:obj:`device` must be the GPU index). You can find more information about Faiss here: - For `string factory <https://github.com/facebookresearch/faiss/wiki/The-index-factory>`__ Args: column (:obj:`str`): The column of the vectors to add to the index. index_name (Optional :obj:`str`): The index_name/identifier of the index. This is the index_name that is used to call :func:`datasets.Dataset.get_nearest_examples` or :func:`datasets.Dataset.search`. By default it corresponds to `column`. device (Optional :obj:`int`): If not None, this is the index of the GPU to use. By default it uses the CPU. string_factory (Optional :obj:`str`): This is passed to the index factory of Faiss to create the index. Default index class is ``IndexFlat``. metric_type (Optional :obj:`int`): Type of metric. Ex: faiss.faiss.METRIC_INNER_PRODUCT or faiss.METRIC_L2. custom_index (Optional :obj:`faiss.Index`): Custom Faiss index that you already have instantiated and configured for your needs. train_size (Optional :obj:`int`): If the index needs a training step, specifies how many vectors will be used to train the index. faiss_verbose (:obj:`bool`, defaults to False): Enable the verbosity of the Faiss index. dtype (data-type): The dtype of the numpy arrays that are indexed. Default is ``np.float32``. Example: .. code-block:: python ds = datasets.load_dataset('crime_and_punish', split='train') ds_with_embeddings = ds.map(lambda example: {'embeddings': embed(example['line']})) ds_with_embeddings.add_faiss_index(column='embeddings') # query scores, retrieved_examples = ds_with_embeddings.get_nearest_examples('embeddings', embed('my new query'), k=10) # save index ds_with_embeddings.save_faiss_index('embeddings', 'my_index.faiss') ds = datasets.load_dataset('crime_and_punish', split='train') # load index ds.load_faiss_index('embeddings', 'my_index.faiss') # query scores, retrieved_examples = ds.get_nearest_examples('embeddings', embed('my new query'), k=10)
Add a dense index using Faiss for fast retrieval. By default the index is done over the vectors of the specified column. You can specify :obj:`device` if you want to run it on GPU (:obj:`device` must be the GPU index). You can find more information about Faiss here:
[ "Add", "a", "dense", "index", "using", "Faiss", "for", "fast", "retrieval", ".", "By", "default", "the", "index", "is", "done", "over", "the", "vectors", "of", "the", "specified", "column", ".", "You", "can", "specify", ":", "obj", ":", "device", "if", ...
def add_faiss_index( self, column: str, index_name: Optional[str] = None, device: Optional[int] = None, string_factory: Optional[str] = None, metric_type: Optional[int] = None, custom_index: Optional["faiss.Index"] = None, # noqa: F821 train_size: Optional[int] = None, faiss_verbose: bool = False, dtype=np.float32, ): """Add a dense index using Faiss for fast retrieval. By default the index is done over the vectors of the specified column. You can specify :obj:`device` if you want to run it on GPU (:obj:`device` must be the GPU index). You can find more information about Faiss here: - For `string factory <https://github.com/facebookresearch/faiss/wiki/The-index-factory>`__ Args: column (:obj:`str`): The column of the vectors to add to the index. index_name (Optional :obj:`str`): The index_name/identifier of the index. This is the index_name that is used to call :func:`datasets.Dataset.get_nearest_examples` or :func:`datasets.Dataset.search`. By default it corresponds to `column`. device (Optional :obj:`int`): If not None, this is the index of the GPU to use. By default it uses the CPU. string_factory (Optional :obj:`str`): This is passed to the index factory of Faiss to create the index. Default index class is ``IndexFlat``. metric_type (Optional :obj:`int`): Type of metric. Ex: faiss.faiss.METRIC_INNER_PRODUCT or faiss.METRIC_L2. custom_index (Optional :obj:`faiss.Index`): Custom Faiss index that you already have instantiated and configured for your needs. train_size (Optional :obj:`int`): If the index needs a training step, specifies how many vectors will be used to train the index. faiss_verbose (:obj:`bool`, defaults to False): Enable the verbosity of the Faiss index. dtype (data-type): The dtype of the numpy arrays that are indexed. Default is ``np.float32``. Example: .. code-block:: python ds = datasets.load_dataset('crime_and_punish', split='train') ds_with_embeddings = ds.map(lambda example: {'embeddings': embed(example['line']})) ds_with_embeddings.add_faiss_index(column='embeddings') # query scores, retrieved_examples = ds_with_embeddings.get_nearest_examples('embeddings', embed('my new query'), k=10) # save index ds_with_embeddings.save_faiss_index('embeddings', 'my_index.faiss') ds = datasets.load_dataset('crime_and_punish', split='train') # load index ds.load_faiss_index('embeddings', 'my_index.faiss') # query scores, retrieved_examples = ds.get_nearest_examples('embeddings', embed('my new query'), k=10) """ with self.formatted_as(type="numpy", columns=[column], dtype=dtype): super().add_faiss_index( column=column, index_name=index_name, device=device, string_factory=string_factory, metric_type=metric_type, custom_index=custom_index, train_size=train_size, faiss_verbose=faiss_verbose, ) return self
[ "def", "add_faiss_index", "(", "self", ",", "column", ":", "str", ",", "index_name", ":", "Optional", "[", "str", "]", "=", "None", ",", "device", ":", "Optional", "[", "int", "]", "=", "None", ",", "string_factory", ":", "Optional", "[", "str", "]", ...
https://github.com/huggingface/datasets/blob/249b4a38390bf1543f5b6e2f3dc208b5689c1c13/src/datasets/arrow_dataset.py#L3639-L3710
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/django/contrib/gis/db/models/sql/where.py
python
GeoWhereNode._check_geo_field
(cls, opts, lookup)
Utility for checking the given lookup with the given model options. The lookup is a string either specifying the geographic field, e.g. 'point, 'the_geom', or a related lookup on a geographic field like 'address__point'. If a GeometryField exists according to the given lookup on the model options, it will be returned. Otherwise returns None.
Utility for checking the given lookup with the given model options. The lookup is a string either specifying the geographic field, e.g. 'point, 'the_geom', or a related lookup on a geographic field like 'address__point'.
[ "Utility", "for", "checking", "the", "given", "lookup", "with", "the", "given", "model", "options", ".", "The", "lookup", "is", "a", "string", "either", "specifying", "the", "geographic", "field", "e", ".", "g", ".", "point", "the_geom", "or", "a", "relate...
def _check_geo_field(cls, opts, lookup): """ Utility for checking the given lookup with the given model options. The lookup is a string either specifying the geographic field, e.g. 'point, 'the_geom', or a related lookup on a geographic field like 'address__point'. If a GeometryField exists according to the given lookup on the model options, it will be returned. Otherwise returns None. """ # This takes into account the situation where the lookup is a # lookup to a related geographic field, e.g., 'address__point'. field_list = lookup.split(LOOKUP_SEP) # Reversing so list operates like a queue of related lookups, # and popping the top lookup. field_list.reverse() fld_name = field_list.pop() try: geo_fld = opts.get_field(fld_name) # If the field list is still around, then it means that the # lookup was for a geometry field across a relationship -- # thus we keep on getting the related model options and the # model field associated with the next field in the list # until there's no more left. while len(field_list): opts = geo_fld.rel.to._meta geo_fld = opts.get_field(field_list.pop()) except (FieldDoesNotExist, AttributeError): return False # Finally, make sure we got a Geographic field and return. if isinstance(geo_fld, GeometryField): return geo_fld else: return False
[ "def", "_check_geo_field", "(", "cls", ",", "opts", ",", "lookup", ")", ":", "# This takes into account the situation where the lookup is a", "# lookup to a related geographic field, e.g., 'address__point'.", "field_list", "=", "lookup", ".", "split", "(", "LOOKUP_SEP", ")", ...
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/django/contrib/gis/db/models/sql/where.py#L55-L91
bbfamily/abu
2de85ae57923a720dac99a545b4f856f6b87304b
abupy/ExtBu/empyrical/stats.py
python
nancumsum
(a, axis=None, dtype=None)
return result
Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros. Handles a subset of the edge cases handled by the nancumsum added in numpy 1.12.0. Parameters ---------- a : np.ndarray or pd.Series Input array. axis : int, optional Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array. dtype : np.dtype, optional Type of the returned array and of the accumulator in which the elements are summed. If `dtype` is not specified, it defaults to the dtype of `a`, unless `a` has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used. Returns ------- nancumsum : np.ndarray or pd.Series A new array that has the same size as a, and the same shape as a. See Also -------- numpy.cumsum : Cumulative sum across array propagating NaNs.
Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros.
[ "Return", "the", "cumulative", "sum", "of", "array", "elements", "over", "a", "given", "axis", "treating", "Not", "a", "Numbers", "(", "NaNs", ")", "as", "zero", ".", "The", "cumulative", "sum", "does", "not", "change", "when", "NaNs", "are", "encountered"...
def nancumsum(a, axis=None, dtype=None): """ Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros. Handles a subset of the edge cases handled by the nancumsum added in numpy 1.12.0. Parameters ---------- a : np.ndarray or pd.Series Input array. axis : int, optional Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array. dtype : np.dtype, optional Type of the returned array and of the accumulator in which the elements are summed. If `dtype` is not specified, it defaults to the dtype of `a`, unless `a` has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used. Returns ------- nancumsum : np.ndarray or pd.Series A new array that has the same size as a, and the same shape as a. See Also -------- numpy.cumsum : Cumulative sum across array propagating NaNs. """ y = np.array(a, subok=True) mask = np.isnan(a) np.putmask(y, mask, 0.) result = np.cumsum(y, axis=axis, dtype=dtype) np.putmask(result, mask, np.nan) return result
[ "def", "nancumsum", "(", "a", ",", "axis", "=", "None", ",", "dtype", "=", "None", ")", ":", "y", "=", "np", ".", "array", "(", "a", ",", "subok", "=", "True", ")", "mask", "=", "np", ".", "isnan", "(", "a", ")", "np", ".", "putmask", "(", ...
https://github.com/bbfamily/abu/blob/2de85ae57923a720dac99a545b4f856f6b87304b/abupy/ExtBu/empyrical/stats.py#L220-L264
X-DataInitiative/tick
bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48
setup.py
python
BuildCPPTests.initialize_options
(self)
Set default values for options.
Set default values for options.
[ "Set", "default", "values", "for", "options", "." ]
def initialize_options(self): """Set default values for options.""" self.build_jobs = multiprocessing.cpu_count()
[ "def", "initialize_options", "(", "self", ")", ":", "self", ".", "build_jobs", "=", "multiprocessing", ".", "cpu_count", "(", ")" ]
https://github.com/X-DataInitiative/tick/blob/bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48/setup.py#L751-L753
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/quadratic_forms/quadratic_form__ternary_Tornaria.py
python
is_zero
(self, v, p=0)
return norm == 0
Determines if the vector v is on the conic Q(x) = 0 (mod p). EXAMPLES:: sage: Q1 = QuadraticForm(ZZ, 3, [1, 0, -1, 2, -1, 5]) sage: Q1.is_zero([0,1,0], 2) True sage: Q1.is_zero([1,1,1], 2) True sage: Q1.is_zero([1,1,0], 2) False
Determines if the vector v is on the conic Q(x) = 0 (mod p).
[ "Determines", "if", "the", "vector", "v", "is", "on", "the", "conic", "Q", "(", "x", ")", "=", "0", "(", "mod", "p", ")", "." ]
def is_zero(self, v, p=0): """ Determines if the vector v is on the conic Q(x) = 0 (mod p). EXAMPLES:: sage: Q1 = QuadraticForm(ZZ, 3, [1, 0, -1, 2, -1, 5]) sage: Q1.is_zero([0,1,0], 2) True sage: Q1.is_zero([1,1,1], 2) True sage: Q1.is_zero([1,1,0], 2) False """ norm = self(v) if p != 0: norm = norm % p return norm == 0
[ "def", "is_zero", "(", "self", ",", "v", ",", "p", "=", "0", ")", ":", "norm", "=", "self", "(", "v", ")", "if", "p", "!=", "0", ":", "norm", "=", "norm", "%", "p", "return", "norm", "==", "0" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/quadratic_forms/quadratic_form__ternary_Tornaria.py#L593-L611
Tencent/PocketFlow
53b82cba5a34834400619e7c335a23995d45c2a6
learners/channel_pruning/model_wrapper.py
python
Model.output_channels
(self, name)
return self.g.get_tensor_by_name(name).shape[3].value
get the number of channels of a convolution output
get the number of channels of a convolution output
[ "get", "the", "number", "of", "channels", "of", "a", "convolution", "output" ]
def output_channels(self, name): """ get the number of channels of a convolution output""" if self.data_format == 'NCHW': return self.g.get_tensor_by_name(name).shape[1].value return self.g.get_tensor_by_name(name).shape[3].value
[ "def", "output_channels", "(", "self", ",", "name", ")", ":", "if", "self", ".", "data_format", "==", "'NCHW'", ":", "return", "self", ".", "g", ".", "get_tensor_by_name", "(", "name", ")", ".", "shape", "[", "1", "]", ".", "value", "return", "self", ...
https://github.com/Tencent/PocketFlow/blob/53b82cba5a34834400619e7c335a23995d45c2a6/learners/channel_pruning/model_wrapper.py#L249-L254
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/musicbrainzngs/mbxml.py
python
parse_place_list
(pl)
return [parse_place(p) for p in pl]
[]
def parse_place_list(pl): return [parse_place(p) for p in pl]
[ "def", "parse_place_list", "(", "pl", ")", ":", "return", "[", "parse_place", "(", "p", ")", "for", "p", "in", "pl", "]" ]
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/musicbrainzngs/mbxml.py#L267-L268
scrtlabs/catalyst
2e8029780f2381da7a0729f7b52505e5db5f535b
catalyst/data/minute_bars.py
python
BcolzMinuteBarReader.table_len
(self, sid)
return len(self._open_minute_file('close', sid))
Returns the length of the underlying table for this sid.
Returns the length of the underlying table for this sid.
[ "Returns", "the", "length", "of", "the", "underlying", "table", "for", "this", "sid", "." ]
def table_len(self, sid): """Returns the length of the underlying table for this sid.""" return len(self._open_minute_file('close', sid))
[ "def", "table_len", "(", "self", ",", "sid", ")", ":", "return", "len", "(", "self", ".", "_open_minute_file", "(", "'close'", ",", "sid", ")", ")" ]
https://github.com/scrtlabs/catalyst/blob/2e8029780f2381da7a0729f7b52505e5db5f535b/catalyst/data/minute_bars.py#L1065-L1067
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/wifite/wifite.py
python
find_mon
()
finds any wireless devices running in monitor mode if no monitor-mode devices are found, it asks for a device to put into monitor mode if only one monitor-mode device is found, it is used if multiple monitor-mode devices are found, it asks to pick one
finds any wireless devices running in monitor mode if no monitor-mode devices are found, it asks for a device to put into monitor mode if only one monitor-mode device is found, it is used if multiple monitor-mode devices are found, it asks to pick one
[ "finds", "any", "wireless", "devices", "running", "in", "monitor", "mode", "if", "no", "monitor", "-", "mode", "devices", "are", "found", "it", "asks", "for", "a", "device", "to", "put", "into", "monitor", "mode", "if", "only", "one", "monitor", "-", "mo...
def find_mon(): """ finds any wireless devices running in monitor mode if no monitor-mode devices are found, it asks for a device to put into monitor mode if only one monitor-mode device is found, it is used if multiple monitor-mode devices are found, it asks to pick one """ global IFACE, TEMPDIR, USING_XTERM ifaces=[] print GR+'[+] '+W+'searching for devices in monitor mode...' proc=subprocess.Popen(['iwconfig'], stdout=subprocess.PIPE,stderr=subprocess.PIPE) txt=proc.communicate()[0] lines=txt.split('\n') current_iface='' for line in lines: if not line.startswith(' ') and line[0:line.find(' ')] != '': current_iface=line[0:line.find(' ')] if line.find('Mode:Monitor') != -1: ifaces.append(current_iface) if len(ifaces) == 0 or ifaces == []: print GR+'[!] '+O+'no wireless interfaces are in monitor mode!' proc=subprocess.Popen(['airmon-ng'], stdout=subprocess.PIPE,stderr=open(os.devnull, 'w')) txt=proc.communicate()[0] lines=txt.split('\n') poss=[] for line in lines: if line != '' and line.find('Interface') == -1: poss.append(line) i=len(poss)-1 if poss[i][:poss[i].find('\t')].lower() == IFACE.lower(): poss=[poss[i][:poss[i].find('\t')]] break if len(poss) == 0: print R+'[!] no devices are capable of monitor mode!' print R+'[!] perhaps you need to install new drivers' print R+'[+] this program will now exit.' print W if USING_XTERM: print GR+'[!] '+W+'close this window at any time to exit wifite'+W subprocess.call(['rm','-rf',TEMPDIR]) sys.exit(0) elif len(poss) == 1 and IFACE != '' and poss[0].lower() == IFACE.lower(): print GR+'[+] '+W+'putting "'+G + poss[0] + W+'" into monitor mode...' subprocess.call(['airmon-ng','start',poss[0]], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w')) IFACE='' find_mon() # recursive call return else: print GR+'\n[+] '+W+'select which device you want to put into monitor mode:' for p in xrange(0, len(poss)): print ' '+G + str(p + 1) + W+'. ' + poss[p] err=True while err==True: try: print GR+'[+] '+W+'select the wifi interface (between '+G+'1'+W+' and '+G + str(len(poss)) + W+'):'+G, num=int(raw_input()) if num >= 1 and num <= len(poss): err=False except ValueError: err=True poss[num-1] = poss[num-1][:poss[num-1].find('\t')] print GR+'[+] '+W+'putting "'+G + poss[num-1] + W+'" into monitor mode...' updatesqlstatus('[+] putting "' + poss[num-1] + '" into monitor mode...') subprocess.call(['airmon-ng','start',poss[num-1]], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w')) find_mon() # recursive call return else: # lif len(ifaces) == 1: # make sure the iface they want to use is already in monitor mode if IFACE != '': for i in ifaces: if i == IFACE: print GR+'[+] '+W+'using interface "'+G+ IFACE +W+'"\n' updatesqlstatus('[+] using interface "'+ IFACE +'"') return IFACE=ifaces[0] # only one interface in monitor mode, we know which one it is print GR+'[+] '+W+'defaulting to interface "'+G+ IFACE +W+'"\n' return print GR+'[+] '+W+'using interface "'+G+ IFACE +W+'"\n' updatesqlstatus('[+] using interface "'+ IFACE +'"')
[ "def", "find_mon", "(", ")", ":", "global", "IFACE", ",", "TEMPDIR", ",", "USING_XTERM", "ifaces", "=", "[", "]", "print", "GR", "+", "'[+] '", "+", "W", "+", "'searching for devices in monitor mode...'", "proc", "=", "subprocess", ".", "Popen", "(", "[", ...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/wifite/wifite.py#L1586-L1671
zenodo/zenodo
3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5
zenodo/modules/records/serializers/schemaorg.py
python
ZenodoSchemaOrgSerializer.dump
(self, obj, context=None)
return schema_cls(context=context).dump(obj).data
Serialize object with schema.
Serialize object with schema.
[ "Serialize", "object", "with", "schema", "." ]
def dump(self, obj, context=None): """Serialize object with schema.""" # Resolve string "https://schema.org/ScholarlyArticle" # to schemas.ScholarlyArticle class (etc.) schema_cls = self._get_schema_class(obj) return schema_cls(context=context).dump(obj).data
[ "def", "dump", "(", "self", ",", "obj", ",", "context", "=", "None", ")", ":", "# Resolve string \"https://schema.org/ScholarlyArticle\"", "# to schemas.ScholarlyArticle class (etc.)", "schema_cls", "=", "self", ".", "_get_schema_class", "(", "obj", ")", "return", "sche...
https://github.com/zenodo/zenodo/blob/3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5/zenodo/modules/records/serializers/schemaorg.py#L48-L53
mwaterfall/alfred-datetime-format-converter
02ffc84ff8e971840d3a3134e4b2682484c4f489
workflow/pytz/tzinfo.py
python
DstTzInfo.normalize
(self, dt)
return self.fromutc(dt)
Correct the timezone information on the given datetime If date arithmetic crosses DST boundaries, the tzinfo is not magically adjusted. This method normalizes the tzinfo to the correct one. To test, first we need to do some setup >>> from pytz import timezone >>> utc = timezone('UTC') >>> eastern = timezone('US/Eastern') >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' We next create a datetime right on an end-of-DST transition point, the instant when the wallclocks are wound back one hour. >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc) >>> loc_dt = utc_dt.astimezone(eastern) >>> loc_dt.strftime(fmt) '2002-10-27 01:00:00 EST (-0500)' Now, if we subtract a few minutes from it, note that the timezone information has not changed. >>> before = loc_dt - timedelta(minutes=10) >>> before.strftime(fmt) '2002-10-27 00:50:00 EST (-0500)' But we can fix that by calling the normalize method >>> before = eastern.normalize(before) >>> before.strftime(fmt) '2002-10-27 01:50:00 EDT (-0400)' The supported method of converting between timezones is to use datetime.astimezone(). Currently, normalize() also works: >>> th = timezone('Asia/Bangkok') >>> am = timezone('Europe/Amsterdam') >>> dt = th.localize(datetime(2011, 5, 7, 1, 2, 3)) >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' >>> am.normalize(dt).strftime(fmt) '2011-05-06 20:02:03 CEST (+0200)'
Correct the timezone information on the given datetime
[ "Correct", "the", "timezone", "information", "on", "the", "given", "datetime" ]
def normalize(self, dt): '''Correct the timezone information on the given datetime If date arithmetic crosses DST boundaries, the tzinfo is not magically adjusted. This method normalizes the tzinfo to the correct one. To test, first we need to do some setup >>> from pytz import timezone >>> utc = timezone('UTC') >>> eastern = timezone('US/Eastern') >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' We next create a datetime right on an end-of-DST transition point, the instant when the wallclocks are wound back one hour. >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc) >>> loc_dt = utc_dt.astimezone(eastern) >>> loc_dt.strftime(fmt) '2002-10-27 01:00:00 EST (-0500)' Now, if we subtract a few minutes from it, note that the timezone information has not changed. >>> before = loc_dt - timedelta(minutes=10) >>> before.strftime(fmt) '2002-10-27 00:50:00 EST (-0500)' But we can fix that by calling the normalize method >>> before = eastern.normalize(before) >>> before.strftime(fmt) '2002-10-27 01:50:00 EDT (-0400)' The supported method of converting between timezones is to use datetime.astimezone(). Currently, normalize() also works: >>> th = timezone('Asia/Bangkok') >>> am = timezone('Europe/Amsterdam') >>> dt = th.localize(datetime(2011, 5, 7, 1, 2, 3)) >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)' >>> am.normalize(dt).strftime(fmt) '2011-05-06 20:02:03 CEST (+0200)' ''' if dt.tzinfo is None: raise ValueError('Naive time - no tzinfo set') # Convert dt in localtime to UTC offset = dt.tzinfo._utcoffset dt = dt.replace(tzinfo=None) dt = dt - offset # convert it back, and return it return self.fromutc(dt)
[ "def", "normalize", "(", "self", ",", "dt", ")", ":", "if", "dt", ".", "tzinfo", "is", "None", ":", "raise", "ValueError", "(", "'Naive time - no tzinfo set'", ")", "# Convert dt in localtime to UTC", "offset", "=", "dt", ".", "tzinfo", ".", "_utcoffset", "dt"...
https://github.com/mwaterfall/alfred-datetime-format-converter/blob/02ffc84ff8e971840d3a3134e4b2682484c4f489/workflow/pytz/tzinfo.py#L189-L242
JulianEberius/SublimeRope
c6ac5179ce8c1e7af0c2c1134589f945252c362d
rope_pyflakes/checker.py
python
Checker.FOR
(self, node)
Process bindings for loop variables.
Process bindings for loop variables.
[ "Process", "bindings", "for", "loop", "variables", "." ]
def FOR(self, node): """ Process bindings for loop variables. """ vars = [] def collectLoopVars(n): if isinstance(n, _ast.Name): vars.append(n.id) elif isinstance(n, _ast.expr_context): return else: for c in iter_child_nodes(n): collectLoopVars(c) collectLoopVars(node.target) for varn in vars: if (isinstance(self.scope.get(varn), Importation) # unused ones will get an unused import warning and self.scope[varn].used): self.report(messages.ImportShadowedByLoopVar, node.lineno, varn, self.scope[varn].source.lineno) self.handleChildren(node)
[ "def", "FOR", "(", "self", ",", "node", ")", ":", "vars", "=", "[", "]", "def", "collectLoopVars", "(", "n", ")", ":", "if", "isinstance", "(", "n", ",", "_ast", ".", "Name", ")", ":", "vars", ".", "append", "(", "n", ".", "id", ")", "elif", ...
https://github.com/JulianEberius/SublimeRope/blob/c6ac5179ce8c1e7af0c2c1134589f945252c362d/rope_pyflakes/checker.py#L378-L401
mental32/spotify.py
c52a8d05cc48f02ebcf76afdd4eda893c1ce0855
spotify/http.py
python
HTTPClient.play_playback
( self, context_uri: Union[str, Sequence[str]], *, offset: Optional[Union[str, int]] = None, device_id: Optional[str] = None, position_ms: Optional[int] = 0, )
return self.request(route, params=params, json=payload)
Start a new context or resume current playback on the user’s active device. .. note:: In order to resume playback set the context_uri to None. Parameters ---------- context_uri : Union[str, Sequence[:class:`str`]] The context to play, if it is a string then it must be a uri of a album, artist or playlist. Otherwise a sequece of strings can be passed in and they must all be track URIs offset : Optional[Union[:class:`str`, :class:`int`]] The offset of which to start from, must either be an integer or a track URI. device_id : Optional[:class:`str`] The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. position_ms : Optional[:class:`int`] indicates from what position to start playback. Must be a positive number. Passing in a position that is greater than the length of the track will cause the player to start playing the next song.
Start a new context or resume current playback on the user’s active device.
[ "Start", "a", "new", "context", "or", "resume", "current", "playback", "on", "the", "user’s", "active", "device", "." ]
def play_playback( self, context_uri: Union[str, Sequence[str]], *, offset: Optional[Union[str, int]] = None, device_id: Optional[str] = None, position_ms: Optional[int] = 0, ) -> Awaitable: """Start a new context or resume current playback on the user’s active device. .. note:: In order to resume playback set the context_uri to None. Parameters ---------- context_uri : Union[str, Sequence[:class:`str`]] The context to play, if it is a string then it must be a uri of a album, artist or playlist. Otherwise a sequece of strings can be passed in and they must all be track URIs offset : Optional[Union[:class:`str`, :class:`int`]] The offset of which to start from, must either be an integer or a track URI. device_id : Optional[:class:`str`] The id of the device this command is targeting. If not supplied, the user’s currently active device is the target. position_ms : Optional[:class:`int`] indicates from what position to start playback. Must be a positive number. Passing in a position that is greater than the length of the track will cause the player to start playing the next song. """ route = self.route("PUT", "/me/player/play") payload: Dict[str, Any] = {"position_ms": position_ms} params: Dict[str, Any] = {} can_set_offset: bool = False if isinstance(context_uri, str): payload["context_uri"] = context_uri can_set_offset = "playlist" in context_uri or "album" in context_uri elif hasattr(context_uri, "__iter__"): payload["uris"] = list(context_uri) can_set_offset = True elif context_uri is None: pass # Do nothing, context_uri == None is allowed and intended for resume's else: raise TypeError( f"`context_uri` must be a string or an iterable object, got {type(context_uri)}" ) if offset is not None: if can_set_offset: _offset: Dict[str, Union[int, str]] if isinstance(offset, str): _offset = {"uri": offset} elif isinstance(offset, int): _offset = {"position": offset} else: raise TypeError( f"`offset` should be either a string or an integer, got {type(offset)}" ) payload["offset"] = _offset else: raise ValueError( "not able to set `offset` as either `context_uri` was not a list or it was a playlist or album uri." ) if device_id is not None: params["device_id"] = device_id return self.request(route, params=params, json=payload)
[ "def", "play_playback", "(", "self", ",", "context_uri", ":", "Union", "[", "str", ",", "Sequence", "[", "str", "]", "]", ",", "*", ",", "offset", ":", "Optional", "[", "Union", "[", "str", ",", "int", "]", "]", "=", "None", ",", "device_id", ":", ...
https://github.com/mental32/spotify.py/blob/c52a8d05cc48f02ebcf76afdd4eda893c1ce0855/spotify/http.py#L1086-L1163
aws/aws-encryption-sdk-python
0922a76eb4536cbc2246e723f97496e068204d78
src/aws_encryption_sdk/internal/utils/__init__.py
python
content_type
(frame_length)
Returns the appropriate content type based on the frame length. :param int frame_length: Message frame length :returns: Appropriate content type based on frame length :rtype: aws_encryption_sdk.identifiers.ContentType
Returns the appropriate content type based on the frame length.
[ "Returns", "the", "appropriate", "content", "type", "based", "on", "the", "frame", "length", "." ]
def content_type(frame_length): """Returns the appropriate content type based on the frame length. :param int frame_length: Message frame length :returns: Appropriate content type based on frame length :rtype: aws_encryption_sdk.identifiers.ContentType """ if frame_length == 0: return ContentType.NO_FRAMING else: return ContentType.FRAMED_DATA
[ "def", "content_type", "(", "frame_length", ")", ":", "if", "frame_length", "==", "0", ":", "return", "ContentType", ".", "NO_FRAMING", "else", ":", "return", "ContentType", ".", "FRAMED_DATA" ]
https://github.com/aws/aws-encryption-sdk-python/blob/0922a76eb4536cbc2246e723f97496e068204d78/src/aws_encryption_sdk/internal/utils/__init__.py#L31-L41
cagbal/ros_people_object_detection_tensorflow
982ffd4a54b8059638f5cd4aa167299c7fc9e61f
src/object_detection/matchers/argmax_matcher.py
python
ArgMaxMatcher.__init__
(self, matched_threshold, unmatched_threshold=None, negatives_lower_than_unmatched=True, force_match_for_each_row=False, use_matmul_gather=False)
Construct ArgMaxMatcher. Args: matched_threshold: Threshold for positive matches. Positive if sim >= matched_threshold, where sim is the maximum value of the similarity matrix for a given column. Set to None for no threshold. unmatched_threshold: Threshold for negative matches. Negative if sim < unmatched_threshold. Defaults to matched_threshold when set to None. negatives_lower_than_unmatched: Boolean which defaults to True. If True then negative matches are the ones below the unmatched_threshold, whereas ignored matches are in between the matched and umatched threshold. If False, then negative matches are in between the matched and unmatched threshold, and everything lower than unmatched is ignored. force_match_for_each_row: If True, ensures that each row is matched to at least one column (which is not guaranteed otherwise if the matched_threshold is high). Defaults to False. See argmax_matcher_test.testMatcherForceMatch() for an example. use_matmul_gather: Force constructed match objects to use matrix multiplication based gather instead of standard tf.gather. (Default: False). Raises: ValueError: if unmatched_threshold is set but matched_threshold is not set or if unmatched_threshold > matched_threshold.
Construct ArgMaxMatcher.
[ "Construct", "ArgMaxMatcher", "." ]
def __init__(self, matched_threshold, unmatched_threshold=None, negatives_lower_than_unmatched=True, force_match_for_each_row=False, use_matmul_gather=False): """Construct ArgMaxMatcher. Args: matched_threshold: Threshold for positive matches. Positive if sim >= matched_threshold, where sim is the maximum value of the similarity matrix for a given column. Set to None for no threshold. unmatched_threshold: Threshold for negative matches. Negative if sim < unmatched_threshold. Defaults to matched_threshold when set to None. negatives_lower_than_unmatched: Boolean which defaults to True. If True then negative matches are the ones below the unmatched_threshold, whereas ignored matches are in between the matched and umatched threshold. If False, then negative matches are in between the matched and unmatched threshold, and everything lower than unmatched is ignored. force_match_for_each_row: If True, ensures that each row is matched to at least one column (which is not guaranteed otherwise if the matched_threshold is high). Defaults to False. See argmax_matcher_test.testMatcherForceMatch() for an example. use_matmul_gather: Force constructed match objects to use matrix multiplication based gather instead of standard tf.gather. (Default: False). Raises: ValueError: if unmatched_threshold is set but matched_threshold is not set or if unmatched_threshold > matched_threshold. """ super(ArgMaxMatcher, self).__init__(use_matmul_gather=use_matmul_gather) if (matched_threshold is None) and (unmatched_threshold is not None): raise ValueError('Need to also define matched_threshold when' 'unmatched_threshold is defined') self._matched_threshold = matched_threshold if unmatched_threshold is None: self._unmatched_threshold = matched_threshold else: if unmatched_threshold > matched_threshold: raise ValueError('unmatched_threshold needs to be smaller or equal' 'to matched_threshold') self._unmatched_threshold = unmatched_threshold if not negatives_lower_than_unmatched: if self._unmatched_threshold == self._matched_threshold: raise ValueError('When negatives are in between matched and ' 'unmatched thresholds, these cannot be of equal ' 'value. matched: %s, unmatched: %s', self._matched_threshold, self._unmatched_threshold) self._force_match_for_each_row = force_match_for_each_row self._negatives_lower_than_unmatched = negatives_lower_than_unmatched
[ "def", "__init__", "(", "self", ",", "matched_threshold", ",", "unmatched_threshold", "=", "None", ",", "negatives_lower_than_unmatched", "=", "True", ",", "force_match_for_each_row", "=", "False", ",", "use_matmul_gather", "=", "False", ")", ":", "super", "(", "A...
https://github.com/cagbal/ros_people_object_detection_tensorflow/blob/982ffd4a54b8059638f5cd4aa167299c7fc9e61f/src/object_detection/matchers/argmax_matcher.py#L54-L105
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/deps/oscrypto/_win/asymmetric.py
python
rsa_pkcs1v15_decrypt
(private_key, ciphertext)
return _decrypt(private_key, ciphertext)
Decrypts a byte string using an RSA private key. Uses PKCS#1 v1.5 padding. :param private_key: A PrivateKey object :param ciphertext: A byte string of the encrypted data :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the original plaintext
Decrypts a byte string using an RSA private key. Uses PKCS#1 v1.5 padding.
[ "Decrypts", "a", "byte", "string", "using", "an", "RSA", "private", "key", ".", "Uses", "PKCS#1", "v1", ".", "5", "padding", "." ]
def rsa_pkcs1v15_decrypt(private_key, ciphertext): """ Decrypts a byte string using an RSA private key. Uses PKCS#1 v1.5 padding. :param private_key: A PrivateKey object :param ciphertext: A byte string of the encrypted data :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the original plaintext """ return _decrypt(private_key, ciphertext)
[ "def", "rsa_pkcs1v15_decrypt", "(", "private_key", ",", "ciphertext", ")", ":", "return", "_decrypt", "(", "private_key", ",", "ciphertext", ")" ]
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/deps/oscrypto/_win/asymmetric.py#L3454-L3473
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/norway_air/air_quality.py
python
async_setup_platform
( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, )
Set up the air_quality norway sensor.
Set up the air_quality norway sensor.
[ "Set", "up", "the", "air_quality", "norway", "sensor", "." ]
async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the air_quality norway sensor.""" forecast = config.get(CONF_FORECAST) latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) name = config.get(CONF_NAME) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return coordinates = {"lat": str(latitude), "lon": str(longitude)} async_add_entities( [AirSensor(name, coordinates, forecast, async_get_clientsession(hass))], True )
[ "async", "def", "async_setup_platform", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "ConfigType", ",", "async_add_entities", ":", "AddEntitiesCallback", ",", "discovery_info", ":", "DiscoveryInfoType", "|", "None", "=", "None", ",", ")", "->", "None", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/norway_air/air_quality.py#L46-L66
donnemartin/gitsome
d7c57abc7cb66e9c910a844f15d4536866da3310
xonsh/xoreutils/tty.py
python
tty
(args, stdin, stdout, stderr)
return 0
A tty command for xonsh.
A tty command for xonsh.
[ "A", "tty", "command", "for", "xonsh", "." ]
def tty(args, stdin, stdout, stderr): """A tty command for xonsh.""" if "--help" in args: print(TTY_HELP, file=stdout) return 0 silent = False for i in ("-s", "--silent", "--quiet"): if i in args: silent = True args.remove(i) if len(args) > 0: if not silent: for i in args: print("tty: Invalid option: {}".format(i), file=stderr) print("Try 'tty --help' for more information", file=stderr) return 2 try: fd = stdin.fileno() except: fd = sys.stdin.fileno() if not os.isatty(fd): if not silent: print("not a tty", file=stdout) return 1 if not silent: try: print(os.ttyname(fd), file=stdout) except: return 3 return 0
[ "def", "tty", "(", "args", ",", "stdin", ",", "stdout", ",", "stderr", ")", ":", "if", "\"--help\"", "in", "args", ":", "print", "(", "TTY_HELP", ",", "file", "=", "stdout", ")", "return", "0", "silent", "=", "False", "for", "i", "in", "(", "\"-s\"...
https://github.com/donnemartin/gitsome/blob/d7c57abc7cb66e9c910a844f15d4536866da3310/xonsh/xoreutils/tty.py#L6-L35
pret/pokemon-reverse-engineering-tools
5e0715f2579adcfeb683448c9a7826cfd3afa57d
pokemontools/addresses.py
python
is_valid_address
(address)
is_valid_rom_address
is_valid_rom_address
[ "is_valid_rom_address" ]
def is_valid_address(address): """is_valid_rom_address""" if address == None: return False if type(address) == str: address = int(address, 16) if 0 <= address <= 2097152: return True else: return False
[ "def", "is_valid_address", "(", "address", ")", ":", "if", "address", "==", "None", ":", "return", "False", "if", "type", "(", "address", ")", "==", "str", ":", "address", "=", "int", "(", "address", ",", "16", ")", "if", "0", "<=", "address", "<=", ...
https://github.com/pret/pokemon-reverse-engineering-tools/blob/5e0715f2579adcfeb683448c9a7826cfd3afa57d/pokemontools/addresses.py#L5-L14
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/tarfile.py
python
_Stream.__read
(self, size)
return t[:size]
Return size bytes from stream. If internal buffer is empty, read another block from the stream.
Return size bytes from stream. If internal buffer is empty, read another block from the stream.
[ "Return", "size", "bytes", "from", "stream", ".", "If", "internal", "buffer", "is", "empty", "read", "another", "block", "from", "the", "stream", "." ]
def __read(self, size): """Return size bytes from stream. If internal buffer is empty, read another block from the stream. """ c = len(self.buf) t = [self.buf] while c < size: buf = self.fileobj.read(self.bufsize) if not buf: break t.append(buf) c += len(buf) t = ''.join(t) self.buf = t[size:] return t[:size]
[ "def", "__read", "(", "self", ",", "size", ")", ":", "c", "=", "len", "(", "self", ".", "buf", ")", "t", "=", "[", "self", ".", "buf", "]", "while", "c", "<", "size", ":", "buf", "=", "self", ".", "fileobj", ".", "read", "(", "self", ".", "...
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/tarfile.py#L561-L576
PyHDI/veriloggen
2382d200deabf59cfcfd741f5eba371010aaf2bb
veriloggen/stream/madd.py
python
reset
()
[]
def reset(): global index_count index_count = 0
[ "def", "reset", "(", ")", ":", "global", "index_count", "index_count", "=", "0" ]
https://github.com/PyHDI/veriloggen/blob/2382d200deabf59cfcfd741f5eba371010aaf2bb/veriloggen/stream/madd.py#L107-L109
fdslight/fdslight
69bc6b16f496b9dc628ecd1bc49f776e98e77ba0
pywind/evtframework/handlers/handler.py
python
handler.evt_write
(self)
写事件, 重写这个方法 :return:
写事件, 重写这个方法 :return:
[ "写事件", "重写这个方法", ":", "return", ":" ]
def evt_write(self): """ 写事件, 重写这个方法 :return: """ pass
[ "def", "evt_write", "(", "self", ")", ":", "pass" ]
https://github.com/fdslight/fdslight/blob/69bc6b16f496b9dc628ecd1bc49f776e98e77ba0/pywind/evtframework/handlers/handler.py#L33-L38
huggingface/datasets
249b4a38390bf1543f5b6e2f3dc208b5689c1c13
datasets/wikitext/wikitext.py
python
Wikitext._split_generators
(self, dl_manager)
Returns SplitGenerators.
Returns SplitGenerators.
[ "Returns", "SplitGenerators", "." ]
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" # TODO(wikitext): Downloads the data and defines the splits # dl_manager is a datasets.download.DownloadManager that can be used to # download and extract URLs if self.config.name == "wikitext-103-v1": data_file = dl_manager.download_and_extract(self.config.data_url) data_dir = os.path.join(data_file, "wikitext-103") return [ datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"data_file": os.path.join(data_dir, "wiki.test.tokens"), "split": "test"}, ), datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"data_file": os.path.join(data_dir, "wiki.train.tokens"), "split": "train"}, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={"data_file": os.path.join(data_dir, "wiki.valid.tokens"), "split": "valid"}, ), ] else: if self.config.name == "wikitext-103-raw-v1": data_file = dl_manager.download_and_extract(self.config.data_url) data_dir = os.path.join(data_file, "wikitext-103-raw") return [ datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"data_file": os.path.join(data_dir, "wiki.test.raw"), "split": "test"}, ), datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"data_file": os.path.join(data_dir, "wiki.train.raw"), "split": "train"}, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={"data_file": os.path.join(data_dir, "wiki.valid.raw"), "split": "valid"}, ), ] else: if self.config.name == "wikitext-2-raw-v1": data_file = dl_manager.download_and_extract(self.config.data_url) data_dir = os.path.join(data_file, "wikitext-2-raw") return [ datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"data_file": os.path.join(data_dir, "wiki.test.raw"), "split": "test"}, ), datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"data_file": os.path.join(data_dir, "wiki.train.raw"), "split": "train"}, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={"data_file": os.path.join(data_dir, "wiki.valid.raw"), "split": "valid"}, ), ] else: if self.config.name == "wikitext-2-v1": data_file = dl_manager.download_and_extract(self.config.data_url) data_dir = os.path.join(data_file, "wikitext-2") return [ datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"data_file": os.path.join(data_dir, "wiki.test.tokens"), "split": "test"}, ), datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "data_file": os.path.join(data_dir, "wiki.train.tokens"), "split": "train", }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={ "data_file": os.path.join(data_dir, "wiki.valid.tokens"), "split": "valid", }, ), ]
[ "def", "_split_generators", "(", "self", ",", "dl_manager", ")", ":", "# TODO(wikitext): Downloads the data and defines the splits", "# dl_manager is a datasets.download.DownloadManager that can be used to", "# download and extract URLs", "if", "self", ".", "config", ".", "name", "...
https://github.com/huggingface/datasets/blob/249b4a38390bf1543f5b6e2f3dc208b5689c1c13/datasets/wikitext/wikitext.py#L100-L181
JannerM/mbpo
ac694ff9f1ebb789cc5b3f164d9d67f93ed8f129
softlearning/algorithms/rl_algorithm.py
python
_timestep_before_hook
(self, *args, **kwargs)
Hook called at the beginning of each timestep.
Hook called at the beginning of each timestep.
[ "Hook", "called", "at", "the", "beginning", "of", "each", "timestep", "." ]
def _timestep_before_hook(self, *args, **kwargs): """Hook called at the beginning of each timestep.""" pass
[ "def", "_timestep_before_hook", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass" ]
https://github.com/JannerM/mbpo/blob/ac694ff9f1ebb789cc5b3f164d9d67f93ed8f129/softlearning/algorithms/rl_algorithm.py#L101-L103
cgarrard/osgeopy-code
bc85f4ec7a630b53502ee491e400057b67cdab22
Chapter13/listing13_4.py
python
order_coords
(coords, clockwise)
return coords
Orders coordinates.
Orders coordinates.
[ "Orders", "coordinates", "." ]
def order_coords(coords, clockwise): """Orders coordinates.""" total = 0 x1, y1 = coords[0] for x, y in coords[1:]: total += (x - x1) * (y + y1) x1, y1 = x, y x, y = coords[0] total += (x - x1) * (y + y1) is_clockwise = total > 0 if clockwise != is_clockwise: coords.reverse() return coords
[ "def", "order_coords", "(", "coords", ",", "clockwise", ")", ":", "total", "=", "0", "x1", ",", "y1", "=", "coords", "[", "0", "]", "for", "x", ",", "y", "in", "coords", "[", "1", ":", "]", ":", "total", "+=", "(", "x", "-", "x1", ")", "*", ...
https://github.com/cgarrard/osgeopy-code/blob/bc85f4ec7a630b53502ee491e400057b67cdab22/Chapter13/listing13_4.py#L9-L21
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/conversations/v1/service/user/__init__.py
python
UserInstance.user_conversations
(self)
return self._proxy.user_conversations
Access the user_conversations :returns: twilio.rest.conversations.v1.service.user.user_conversation.UserConversationList :rtype: twilio.rest.conversations.v1.service.user.user_conversation.UserConversationList
Access the user_conversations
[ "Access", "the", "user_conversations" ]
def user_conversations(self): """ Access the user_conversations :returns: twilio.rest.conversations.v1.service.user.user_conversation.UserConversationList :rtype: twilio.rest.conversations.v1.service.user.user_conversation.UserConversationList """ return self._proxy.user_conversations
[ "def", "user_conversations", "(", "self", ")", ":", "return", "self", ".", "_proxy", ".", "user_conversations" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/conversations/v1/service/user/__init__.py#L511-L518
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/re.py
python
compile
(pattern, flags=0)
return _compile(pattern, flags)
Compile a regular expression pattern, returning a pattern object.
Compile a regular expression pattern, returning a pattern object.
[ "Compile", "a", "regular", "expression", "pattern", "returning", "a", "pattern", "object", "." ]
def compile(pattern, flags=0): "Compile a regular expression pattern, returning a pattern object." return _compile(pattern, flags)
[ "def", "compile", "(", "pattern", ",", "flags", "=", "0", ")", ":", "return", "_compile", "(", "pattern", ",", "flags", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/re.py#L192-L194
berkeleydeeprlcourse/homework_fall2019
e9725d8aba926e2fe1c743f881884111b44e33bb
hw2/cs285/infrastructure/logger.py
python
Logger.log_figures
(self, figure, name, step, phase)
figure: matplotlib.pyplot figure handle
figure: matplotlib.pyplot figure handle
[ "figure", ":", "matplotlib", ".", "pyplot", "figure", "handle" ]
def log_figures(self, figure, name, step, phase): """figure: matplotlib.pyplot figure handle""" assert figure.shape[0] > 0, "Figure logging requires input shape [batch x figures]!" self._summ_writer.add_figure('{}_{}'.format(name, phase), figure, step)
[ "def", "log_figures", "(", "self", ",", "figure", ",", "name", ",", "step", ",", "phase", ")", ":", "assert", "figure", ".", "shape", "[", "0", "]", ">", "0", ",", "\"Figure logging requires input shape [batch x figures]!\"", "self", ".", "_summ_writer", ".", ...
https://github.com/berkeleydeeprlcourse/homework_fall2019/blob/e9725d8aba926e2fe1c743f881884111b44e33bb/hw2/cs285/infrastructure/logger.py#L51-L54
sendgrid/sendgrid-python
df13b78b0cdcb410b4516f6761c4d3138edd4b2d
sendgrid/helpers/mail/groups_to_display.py
python
GroupsToDisplay.__init__
(self, groups_to_display=None)
Create a GroupsToDisplay object :param groups_to_display: An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. :type groups_to_display: array of integers, optional
Create a GroupsToDisplay object
[ "Create", "a", "GroupsToDisplay", "object" ]
def __init__(self, groups_to_display=None): """Create a GroupsToDisplay object :param groups_to_display: An array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. :type groups_to_display: array of integers, optional """ self._groups_to_display = None if groups_to_display is not None: self.groups_to_display = groups_to_display
[ "def", "__init__", "(", "self", ",", "groups_to_display", "=", "None", ")", ":", "self", ".", "_groups_to_display", "=", "None", "if", "groups_to_display", "is", "not", "None", ":", "self", ".", "groups_to_display", "=", "groups_to_display" ]
https://github.com/sendgrid/sendgrid-python/blob/df13b78b0cdcb410b4516f6761c4d3138edd4b2d/sendgrid/helpers/mail/groups_to_display.py#L5-L16
a312863063/seeprettyface-generator-wanghong
77c5962cb7b194a1d3c5e052725ae23b48b140da
dnnlib/util.py
python
Logger.close
(self)
Flush, close possible files, and remove stdout/stderr mirroring.
Flush, close possible files, and remove stdout/stderr mirroring.
[ "Flush", "close", "possible", "files", "and", "remove", "stdout", "/", "stderr", "mirroring", "." ]
def close(self) -> None: """Flush, close possible files, and remove stdout/stderr mirroring.""" self.flush() # if using multiple loggers, prevent closing in wrong order if sys.stdout is self: sys.stdout = self.stdout if sys.stderr is self: sys.stderr = self.stderr if self.file is not None: self.file.close()
[ "def", "close", "(", "self", ")", "->", "None", ":", "self", ".", "flush", "(", ")", "# if using multiple loggers, prevent closing in wrong order", "if", "sys", ".", "stdout", "is", "self", ":", "sys", ".", "stdout", "=", "self", ".", "stdout", "if", "sys", ...
https://github.com/a312863063/seeprettyface-generator-wanghong/blob/77c5962cb7b194a1d3c5e052725ae23b48b140da/dnnlib/util.py#L94-L105
akanimax/T2F
e0fc1876b9ecac22be294fefd85234ddf365549c
implementation/networks/InferSent/encoder/models.py
python
InnerAttentionNAACLEncoder.__init__
(self, config)
[]
def __init__(self, config): super(InnerAttentionNAACLEncoder, self).__init__() self.bsize = config['bsize'] self.word_emb_dim = config['word_emb_dim'] self.enc_lstm_dim = config['enc_lstm_dim'] self.pool_type = config['pool_type'] self.enc_lstm = nn.LSTM(self.word_emb_dim, self.enc_lstm_dim, 1, bidirectional=True) self.init_lstm = Variable(torch.FloatTensor(2, self.bsize, self.enc_lstm_dim).zero_()).cuda() self.proj_key = nn.Linear(2*self.enc_lstm_dim, 2*self.enc_lstm_dim, bias=False) self.proj_lstm = nn.Linear(2*self.enc_lstm_dim, 2*self.enc_lstm_dim, bias=False) self.query_embedding = nn.Embedding(1, 2*self.enc_lstm_dim) self.softmax = nn.Softmax()
[ "def", "__init__", "(", "self", ",", "config", ")", ":", "super", "(", "InnerAttentionNAACLEncoder", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "bsize", "=", "config", "[", "'bsize'", "]", "self", ".", "word_emb_dim", "=", "config", "[", ...
https://github.com/akanimax/T2F/blob/e0fc1876b9ecac22be294fefd85234ddf365549c/implementation/networks/InferSent/encoder/models.py#L491-L509
klen/mixer
39ef3b717d4ac9da1824cb9c242fd326fa00ba08
mixer/backend/mongoengine.py
python
get_pointfield
(**kwargs)
return dict(type='Point', coordinates=faker.coordinates())
Get a Point structure. :return dict:
Get a Point structure.
[ "Get", "a", "Point", "structure", "." ]
def get_pointfield(**kwargs): """ Get a Point structure. :return dict: """ return dict(type='Point', coordinates=faker.coordinates())
[ "def", "get_pointfield", "(", "*", "*", "kwargs", ")", ":", "return", "dict", "(", "type", "=", "'Point'", ",", "coordinates", "=", "faker", ".", "coordinates", "(", ")", ")" ]
https://github.com/klen/mixer/blob/39ef3b717d4ac9da1824cb9c242fd326fa00ba08/mixer/backend/mongoengine.py#L68-L74
donnemartin/gitsome
d7c57abc7cb66e9c910a844f15d4536866da3310
xonsh/proc.py
python
PopenThread.signal
(self, value)
Process signal, or None.
Process signal, or None.
[ "Process", "signal", "or", "None", "." ]
def signal(self, value): """Process signal, or None.""" self.proc.signal = value
[ "def", "signal", "(", "self", ",", "value", ")", ":", "self", ".", "proc", ".", "signal", "=", "value" ]
https://github.com/donnemartin/gitsome/blob/d7c57abc7cb66e9c910a844f15d4536866da3310/xonsh/proc.py#L928-L930
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/profile.py
python
Profile.runcall
(self, func, *args, **kw)
[]
def runcall(self, func, *args, **kw): self.set_cmd(repr(func)) sys.setprofile(self.dispatcher) try: return func(*args, **kw) finally: sys.setprofile(None)
[ "def", "runcall", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "set_cmd", "(", "repr", "(", "func", ")", ")", "sys", ".", "setprofile", "(", "self", ".", "dispatcher", ")", "try", ":", "return", "func", ...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/profile.py#L430-L436
nosmokingbandit/Watcher3
0217e75158b563bdefc8e01c3be7620008cf3977
core/ajax.py
python
Ajax.notification_remove
(self, index)
return
Removes notification from core.notification index (str/int): index of notification to remove 'index' will be of type string since it comes from ajax request. Therefore we convert to int here before passing to Notification Simply calls Notification module. Does not return
Removes notification from core.notification index (str/int): index of notification to remove
[ "Removes", "notification", "from", "core", ".", "notification", "index", "(", "str", "/", "int", ")", ":", "index", "of", "notification", "to", "remove" ]
def notification_remove(self, index): ''' Removes notification from core.notification index (str/int): index of notification to remove 'index' will be of type string since it comes from ajax request. Therefore we convert to int here before passing to Notification Simply calls Notification module. Does not return ''' notification.remove(int(index)) return
[ "def", "notification_remove", "(", "self", ",", "index", ")", ":", "notification", ".", "remove", "(", "int", "(", "index", ")", ")", "return" ]
https://github.com/nosmokingbandit/Watcher3/blob/0217e75158b563bdefc8e01c3be7620008cf3977/core/ajax.py#L319-L333
elyra-ai/elyra
5bb2009a7c475bda63f1cc2767eb8c4dfba9a239
create-release.py
python
main
(args=None)
Perform necessary tasks to create and/or publish a new release
Perform necessary tasks to create and/or publish a new release
[ "Perform", "necessary", "tasks", "to", "create", "and", "/", "or", "publish", "a", "new", "release" ]
def main(args=None): """Perform necessary tasks to create and/or publish a new release""" parser = argparse.ArgumentParser(usage=print_help()) parser.add_argument('goal', help='Supported goals: {prepare-changelog | prepare | publish}', type=str, choices={'prepare-changelog', 'prepare', 'publish'}) parser.add_argument('--version', help='the new release version', type=str, required=True) parser.add_argument('--dev-version', help='the new development version', type=str, required=False) parser.add_argument('--beta', help='the release beta number', type=str, required=False) parser.add_argument('--rc', help='the release candidate number', type=str, required=False) args = parser.parse_args() # can't use both rc and beta parameters if args.beta and args.rc: print_help() sys.exit(1) global config try: # Validate all pre-requisites are available validate_dependencies() validate_environment() # Generate release config based on the provided arguments initialize_config(args) print_config() if config.goal == 'prepare-changelog': prepare_changelog() print("") print("") print(f"Changelog for release version: {config.new_version} is ready for review at {config.source_dir}") print("After you are done, push the reviewed changelog to github.") print("") print("") elif config.goal == 'prepare': if not args.dev_version: print_help() sys.exit() prepare_release() print("") print("") print(f"Release version: {config.new_version} is ready for review") print("After you are done, run the script again to [publish] the release.") print("") print("") elif args.goal == "publish": publish_release(working_dir=os.getcwd()) else: print_help() sys.exit() except Exception as ex: raise RuntimeError(f'Error performing release {args.version}') from ex
[ "def", "main", "(", "args", "=", "None", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "usage", "=", "print_help", "(", ")", ")", "parser", ".", "add_argument", "(", "'goal'", ",", "help", "=", "'Supported goals: {prepare-changelog | prepare...
https://github.com/elyra-ai/elyra/blob/5bb2009a7c475bda63f1cc2767eb8c4dfba9a239/create-release.py#L693-L749
git-cola/git-cola
b48b8028e0c3baf47faf7b074b9773737358163d
cola/widgets/completion.py
python
GitBranchDialog.__init__
(self, context, title, text, parent, icon=None)
[]
def __init__(self, context, title, text, parent, icon=None): GitDialog.__init__( self, GitBranchLineEdit, context, title, text, parent, icon=icon )
[ "def", "__init__", "(", "self", ",", "context", ",", "title", ",", "text", ",", "parent", ",", "icon", "=", "None", ")", ":", "GitDialog", ".", "__init__", "(", "self", ",", "GitBranchLineEdit", ",", "context", ",", "title", ",", "text", ",", "parent",...
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/widgets/completion.py#L831-L834
irskep/pyglettutorial
3037588b1ddace22256b68d0d72aecdd46b1e1f7
version2/game/load.py
python
asteroids
(num_asteroids, player_position, batch=None)
return asteroids
Generate asteroid objects with random positions and velocities, not close to the player
Generate asteroid objects with random positions and velocities, not close to the player
[ "Generate", "asteroid", "objects", "with", "random", "positions", "and", "velocities", "not", "close", "to", "the", "player" ]
def asteroids(num_asteroids, player_position, batch=None): """Generate asteroid objects with random positions and velocities, not close to the player""" asteroids = [] for i in range(num_asteroids): asteroid_x, asteroid_y = player_position while distance((asteroid_x, asteroid_y), player_position) < 100: asteroid_x = random.randint(0, 800) asteroid_y = random.randint(0, 600) new_asteroid = physicalobject.PhysicalObject(img=resources.asteroid_image, x=asteroid_x, y=asteroid_y, batch=batch) new_asteroid.rotation = random.randint(0, 360) new_asteroid.velocity_x, new_asteroid.velocity_y = random.random()*40, random.random()*40 asteroids.append(new_asteroid) return asteroids
[ "def", "asteroids", "(", "num_asteroids", ",", "player_position", ",", "batch", "=", "None", ")", ":", "asteroids", "=", "[", "]", "for", "i", "in", "range", "(", "num_asteroids", ")", ":", "asteroid_x", ",", "asteroid_y", "=", "player_position", "while", ...
https://github.com/irskep/pyglettutorial/blob/3037588b1ddace22256b68d0d72aecdd46b1e1f7/version2/game/load.py#L19-L33
catalyst-cooperative/pudl
40d176313e60dfa9d2481f63842ed23f08f1ad5f
src/pudl/output/pudltabl.py
python
PudlTabl.fuel_cost
(self, update=False)
return self._dfs['fuel_cost']
Calculate and return generator level fuel costs per MWh. Args: update (bool): If true, re-calculate the output dataframe, even if a cached version exists. Returns: pandas.DataFrame: a denormalized table for interactive use.
Calculate and return generator level fuel costs per MWh.
[ "Calculate", "and", "return", "generator", "level", "fuel", "costs", "per", "MWh", "." ]
def fuel_cost(self, update=False): """ Calculate and return generator level fuel costs per MWh. Args: update (bool): If true, re-calculate the output dataframe, even if a cached version exists. Returns: pandas.DataFrame: a denormalized table for interactive use. """ if update or self._dfs['fuel_cost'] is None: self._dfs['fuel_cost'] = pudl.analysis.mcoe.fuel_cost(self) return self._dfs['fuel_cost']
[ "def", "fuel_cost", "(", "self", ",", "update", "=", "False", ")", ":", "if", "update", "or", "self", ".", "_dfs", "[", "'fuel_cost'", "]", "is", "None", ":", "self", ".", "_dfs", "[", "'fuel_cost'", "]", "=", "pudl", ".", "analysis", ".", "mcoe", ...
https://github.com/catalyst-cooperative/pudl/blob/40d176313e60dfa9d2481f63842ed23f08f1ad5f/src/pudl/output/pudltabl.py#L909-L923
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
dist/lib/python2.7/logging/__init__.py
python
Logger.info
(self, msg, *args, **kwargs)
Log 'msg % args' with severity 'INFO'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
Log 'msg % args' with severity 'INFO'.
[ "Log", "msg", "%", "args", "with", "severity", "INFO", "." ]
def info(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'INFO'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.info("Houston, we have a %s", "interesting problem", exc_info=1) """ if self.isEnabledFor(INFO): self._log(INFO, msg, args, **kwargs)
[ "def", "info", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "isEnabledFor", "(", "INFO", ")", ":", "self", ".", "_log", "(", "INFO", ",", "msg", ",", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/logging/__init__.py#L1122-L1132
transferwise/pipelinewise
6934b3851512dbdd4280790bf253a0a13ab65684
pipelinewise/fastsync/commons/tap_mysql.py
python
FastSyncTapMySql.run_session_sqls
(self)
Run list of SQLs from the "session_sqls" optional connection parameter
Run list of SQLs from the "session_sqls" optional connection parameter
[ "Run", "list", "of", "SQLs", "from", "the", "session_sqls", "optional", "connection", "parameter" ]
def run_session_sqls(self): """ Run list of SQLs from the "session_sqls" optional connection parameter """ session_sqls = self.connection_config.get('session_sqls', DEFAULT_SESSION_SQLS) warnings = [] if session_sqls and isinstance(session_sqls, list): for sql in session_sqls: try: self.query(sql) self.query(sql, self.conn_unbuffered) except pymysql.err.InternalError: warnings.append(f'Could not set session variable: {sql}') if warnings: LOGGER.warning( 'Encountered non-fatal errors when configuring session that could impact performance:' ) for warning in warnings: LOGGER.warning(warning)
[ "def", "run_session_sqls", "(", "self", ")", ":", "session_sqls", "=", "self", ".", "connection_config", ".", "get", "(", "'session_sqls'", ",", "DEFAULT_SESSION_SQLS", ")", "warnings", "=", "[", "]", "if", "session_sqls", "and", "isinstance", "(", "session_sqls...
https://github.com/transferwise/pipelinewise/blob/6934b3851512dbdd4280790bf253a0a13ab65684/pipelinewise/fastsync/commons/tap_mysql.py#L105-L125
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/mpnet/modeling_mpnet.py
python
MPNetEncoder.relative_position_bucket
(relative_position, num_buckets=32, max_distance=128)
return ret
[]
def relative_position_bucket(relative_position, num_buckets=32, max_distance=128): ret = 0 n = -relative_position num_buckets //= 2 ret += (n < 0).to(torch.long) * num_buckets n = torch.abs(n) max_exact = num_buckets // 2 is_small = n < max_exact val_if_large = max_exact + ( torch.log(n.float() / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact) ).to(torch.long) val_if_large = torch.min(val_if_large, torch.full_like(val_if_large, num_buckets - 1)) ret += torch.where(is_small, n, val_if_large) return ret
[ "def", "relative_position_bucket", "(", "relative_position", ",", "num_buckets", "=", "32", ",", "max_distance", "=", "128", ")", ":", "ret", "=", "0", "n", "=", "-", "relative_position", "num_buckets", "//=", "2", "ret", "+=", "(", "n", "<", "0", ")", "...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/mpnet/modeling_mpnet.py#L384-L401
raveberry/raveberry
df0186c94b238b57de86d3fd5c595dcd08a7c708
backend/core/settings/system.py
python
_check_mopidy_extensions_service
()
return extensions
[]
def _check_mopidy_extensions_service() -> Dict[str, Tuple[bool, str]]: # check the mopidy log and see if there is a spotify login error since the last restart log = subprocess.check_output( ["sudo", "/usr/local/sbin/raveberry/read_mopidy_log"], universal_newlines=True ) extensions = {} for line in log.split("\n")[::-1]: if "spotify" not in extensions: if ( line.startswith("ERROR") and "spotify.session" in line and "USER_NEEDS_PREMIUM" ): extensions["spotify"] = (False, "Spotify Premium is required") elif line.startswith("ERROR") and "spotify.session" in line: extensions["spotify"] = (False, "User or Password are wrong") elif line.startswith("ERROR") and "mopidy_spotify.web" in line: extensions["spotify"] = ( False, "Client ID or Client Secret are wrong or expired", ) elif ( line.startswith("WARNING") and "spotify" in line and "The extension has been automatically disabled" in line ): extensions["spotify"] = (False, "Configuration Error") if "soundcloud" not in extensions: if line.startswith("ERROR") and 'Invalid "auth_token"' in line: extensions["soundcloud"] = (False, "auth_token is invalid") elif ( line.startswith("WARNING") and "soundcloud" in line and "The extension has been automatically disabled" in line ): extensions["soundcloud"] = (False, "Configuration Error") if "jamendo" not in extensions: if line.startswith("ERROR") and 'Invalid "client_id"' in line: extensions["jamendo"] = (False, "client_id is invalid") elif ( line.startswith("WARNING") and "jamendo" in line and "The extension has been automatically disabled" in line ): extensions["jamendo"] = (False, "Configuration Error") if ( "spotify" in extensions and "soundcloud" in extensions and "jamendo" in extensions ): break if line.startswith("Started Mopidy music server."): if "spotify" not in extensions: extensions["spotify"] = (True, "Login successful") if "soundcloud" not in extensions: extensions["soundcloud"] = (True, "auth_token valid") if "jamendo" not in extensions: extensions["jamendo"] = (True, "client_id could not be checked") break else: # there were too many lines in the log, could not determine whether there was an error if "spotify" not in extensions: extensions["spotify"] = (True, "No info found, enabling to be safe") if "soundcloud" not in extensions: extensions["soundcloud"] = (True, "No info found, enabling to be safe") if "jamendo" not in extensions: extensions["jamendo"] = (True, "No info found, enabling to be safe") return extensions
[ "def", "_check_mopidy_extensions_service", "(", ")", "->", "Dict", "[", "str", ",", "Tuple", "[", "bool", ",", "str", "]", "]", ":", "# check the mopidy log and see if there is a spotify login error since the last restart", "log", "=", "subprocess", ".", "check_output", ...
https://github.com/raveberry/raveberry/blob/df0186c94b238b57de86d3fd5c595dcd08a7c708/backend/core/settings/system.py#L104-L177
THUNLP-MT/Document-Transformer
5bcc7f43cc948240fa0e3a400bffdc178f841fcd
thumt/utils/hooks.py
python
_get_saver
()
return savers[0]
[]
def _get_saver(): # Get saver from the SAVERS collection if present. collection_key = tf.GraphKeys.SAVERS savers = tf.get_collection(collection_key) if not savers: raise RuntimeError("No items in collection {}. " "Please add a saver to the collection ") elif len(savers) > 1: raise RuntimeError("More than one item in collection") return savers[0]
[ "def", "_get_saver", "(", ")", ":", "# Get saver from the SAVERS collection if present.", "collection_key", "=", "tf", ".", "GraphKeys", ".", "SAVERS", "savers", "=", "tf", ".", "get_collection", "(", "collection_key", ")", "if", "not", "savers", ":", "raise", "Ru...
https://github.com/THUNLP-MT/Document-Transformer/blob/5bcc7f43cc948240fa0e3a400bffdc178f841fcd/thumt/utils/hooks.py#L16-L27
mikedh/trimesh
6b1e05616b44e6dd708d9bc748b211656ebb27ec
trimesh/path/entities.py
python
Entity.layer
(self)
return self.metadata.get('layer')
Set the layer the entity resides on as a shortcut to putting it in the entity metadata. Returns ---------- layer : any Hashable layer identifier.
Set the layer the entity resides on as a shortcut to putting it in the entity metadata.
[ "Set", "the", "layer", "the", "entity", "resides", "on", "as", "a", "shortcut", "to", "putting", "it", "in", "the", "entity", "metadata", "." ]
def layer(self): """ Set the layer the entity resides on as a shortcut to putting it in the entity metadata. Returns ---------- layer : any Hashable layer identifier. """ return self.metadata.get('layer')
[ "def", "layer", "(", "self", ")", ":", "return", "self", ".", "metadata", ".", "get", "(", "'layer'", ")" ]
https://github.com/mikedh/trimesh/blob/6b1e05616b44e6dd708d9bc748b211656ebb27ec/trimesh/path/entities.py#L61-L71
googlefonts/fontmake
d09c860a0093392c4960c9a97d18cddb87fdcc83
Lib/fontmake/font_project.py
python
FontProject._designspace_locations
(self, designspace)
return maps
Map font filenames to their locations in a designspace.
Map font filenames to their locations in a designspace.
[ "Map", "font", "filenames", "to", "their", "locations", "in", "a", "designspace", "." ]
def _designspace_locations(self, designspace): """Map font filenames to their locations in a designspace.""" maps = [] for elements in (designspace.sources, designspace.instances): location_map = {} for element in elements: path = _normpath(element.path) location_map[path] = element.location maps.append(location_map) return maps
[ "def", "_designspace_locations", "(", "self", ",", "designspace", ")", ":", "maps", "=", "[", "]", "for", "elements", "in", "(", "designspace", ".", "sources", ",", "designspace", ".", "instances", ")", ":", "location_map", "=", "{", "}", "for", "element",...
https://github.com/googlefonts/fontmake/blob/d09c860a0093392c4960c9a97d18cddb87fdcc83/Lib/fontmake/font_project.py#L1220-L1230
mysql/mysql-utilities
08276b2258bf9739f53406b354b21195ff69a261
mysql/utilities/common/replication.py
python
Replication.check_innodb_compatibility
(self, options)
return errors
Check InnoDB compatibility This method checks the master and slave to ensure they have compatible installations of InnoDB. It will print the InnoDB settings on the master and slave if quiet is not set. If pedantic is set, method will raise an error. options[in] dictionary of options (verbose, pedantic) Returns [] if compatible, list of errors if not compatible
Check InnoDB compatibility
[ "Check", "InnoDB", "compatibility" ]
def check_innodb_compatibility(self, options): """Check InnoDB compatibility This method checks the master and slave to ensure they have compatible installations of InnoDB. It will print the InnoDB settings on the master and slave if quiet is not set. If pedantic is set, method will raise an error. options[in] dictionary of options (verbose, pedantic) Returns [] if compatible, list of errors if not compatible """ pedantic = options.get("pedantic", False) verbose = options.get("verbosity", 0) > 0 errors = [] master_innodb_stats = self.master.get_innodb_stats() slave_innodb_stats = self.slave.get_innodb_stats() if master_innodb_stats != slave_innodb_stats: if not pedantic: errors.append("WARNING: Innodb settings differ between master " "and slave.") if verbose or pedantic: cols = ['type', 'plugin_version', 'plugin_type_version', 'have_innodb'] rows = [] rows.append(master_innodb_stats) errors.append("# Master's InnoDB Stats:") errors.extend(_get_list(rows, cols)) rows = [] rows.append(slave_innodb_stats) errors.append("# Slave's InnoDB Stats:") errors.extend(_get_list(rows, cols)) if pedantic: for line in errors: print line raise UtilRplError("Innodb settings differ between master " "and slave.") return errors
[ "def", "check_innodb_compatibility", "(", "self", ",", "options", ")", ":", "pedantic", "=", "options", ".", "get", "(", "\"pedantic\"", ",", "False", ")", "verbose", "=", "options", ".", "get", "(", "\"verbosity\"", ",", "0", ")", ">", "0", "errors", "=...
https://github.com/mysql/mysql-utilities/blob/08276b2258bf9739f53406b354b21195ff69a261/mysql/utilities/common/replication.py#L342-L384
git-cola/git-cola
b48b8028e0c3baf47faf7b074b9773737358163d
cola/models/prefs.py
python
linebreak
(context)
return context.cfg.get(LINEBREAK, default=Defaults.linebreak)
Should we word-wrap lines in the commit message editor?
Should we word-wrap lines in the commit message editor?
[ "Should", "we", "word", "-", "wrap", "lines", "in", "the", "commit", "message", "editor?" ]
def linebreak(context): """Should we word-wrap lines in the commit message editor?""" return context.cfg.get(LINEBREAK, default=Defaults.linebreak)
[ "def", "linebreak", "(", "context", ")", ":", "return", "context", ".", "cfg", ".", "get", "(", "LINEBREAK", ",", "default", "=", "Defaults", ".", "linebreak", ")" ]
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/models/prefs.py#L164-L166
SpamScope/spamscope
ffbfc53b9a3503ef3041cee94c6726c8b899118d
src/modules/bitmap/bitmap.py
python
BitMap.calculate_score
(self, *args)
return score
Return the score of given properties.
Return the score of given properties.
[ "Return", "the", "score", "of", "given", "properties", "." ]
def calculate_score(self, *args): """Return the score of given properties. """ score = 0 for p in args: if p not in self.bitmap: raise PropertyDoesNotExists( "Property {!r} does not exists".format(p)) value = self.bitmap.get(p) score |= (1 << value) return score
[ "def", "calculate_score", "(", "self", ",", "*", "args", ")", ":", "score", "=", "0", "for", "p", "in", "args", ":", "if", "p", "not", "in", "self", ".", "bitmap", ":", "raise", "PropertyDoesNotExists", "(", "\"Property {!r} does not exists\"", ".", "forma...
https://github.com/SpamScope/spamscope/blob/ffbfc53b9a3503ef3041cee94c6726c8b899118d/src/modules/bitmap/bitmap.py#L124-L137
fluentpython/example-code-2e
80f7f84274a47579e59c29a4657691525152c9d5
12-seq-hacking/vector_v5.py
python
Vector.__bytes__
(self)
return (bytes([ord(self.typecode)]) + bytes(self._components))
[]
def __bytes__(self): return (bytes([ord(self.typecode)]) + bytes(self._components))
[ "def", "__bytes__", "(", "self", ")", ":", "return", "(", "bytes", "(", "[", "ord", "(", "self", ".", "typecode", ")", "]", ")", "+", "bytes", "(", "self", ".", "_components", ")", ")" ]
https://github.com/fluentpython/example-code-2e/blob/80f7f84274a47579e59c29a4657691525152c9d5/12-seq-hacking/vector_v5.py#L217-L219
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/spack/solver/asp.py
python
SpackSolverSetup.build_version_dict
(self, possible_pkgs, specs)
Declare any versions in specs not declared in packages.
Declare any versions in specs not declared in packages.
[ "Declare", "any", "versions", "in", "specs", "not", "declared", "in", "packages", "." ]
def build_version_dict(self, possible_pkgs, specs): """Declare any versions in specs not declared in packages.""" self.declared_versions = collections.defaultdict(list) self.possible_versions = collections.defaultdict(set) self.deprecated_versions = collections.defaultdict(set) packages_yaml = spack.config.get("packages") packages_yaml = _normalize_packages_yaml(packages_yaml) for pkg_name in possible_pkgs: pkg = spack.repo.get(pkg_name) # All the versions from the corresponding package.py file. Since concepts # like being a "develop" version or being preferred exist only at a # package.py level, sort them in this partial list here def key_fn(item): version, info = item # When COMPARING VERSIONS, the '@develop' version is always # larger than other versions. BUT when CONCRETIZING, the largest # NON-develop version is selected by default. return info.get('preferred', False), not version.isdevelop(), version for idx, item in enumerate(sorted( pkg.versions.items(), key=key_fn, reverse=True )): v, version_info = item self.possible_versions[pkg_name].add(v) self.declared_versions[pkg_name].append(DeclaredVersion( version=v, idx=idx, origin=version_provenance.package_py )) deprecated = version_info.get('deprecated', False) if deprecated: self.deprecated_versions[pkg_name].add(v) # All the preferred version from packages.yaml, versions in external # specs will be computed later version_preferences = packages_yaml.get(pkg_name, {}).get("version", []) for idx, v in enumerate(version_preferences): self.declared_versions[pkg_name].append(DeclaredVersion( version=v, idx=idx, origin=version_provenance.packages_yaml )) for spec in specs: for dep in spec.traverse(): if dep.versions.concrete: # Concrete versions used in abstract specs from cli. They # all have idx equal to 0, which is the best possible. In # any case they will be used due to being set from the cli. self.declared_versions[dep.name].append(DeclaredVersion( version=dep.version, idx=0, origin=version_provenance.spec )) self.possible_versions[dep.name].add(dep.version)
[ "def", "build_version_dict", "(", "self", ",", "possible_pkgs", ",", "specs", ")", ":", "self", ".", "declared_versions", "=", "collections", ".", "defaultdict", "(", "list", ")", "self", ".", "possible_versions", "=", "collections", ".", "defaultdict", "(", "...
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/spack/solver/asp.py#L1250-L1302
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/analyze_plugins/synopsis.py
python
main
()
Display the synopsis dialog.
Display the synopsis dialog.
[ "Display", "the", "synopsis", "dialog", "." ]
def main(): 'Display the synopsis dialog.' if len(sys.argv) > 1: getWindowAnalyzeFile(' '.join(sys.argv[1 :])) else: settings.startMainLoopFromConstructor(getNewRepository())
[ "def", "main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", ":", "getWindowAnalyzeFile", "(", "' '", ".", "join", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", ")", "else", ":", "settings", ".", "startMainLoopFromConstruc...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/skeinforge_application/skeinforge_plugins/analyze_plugins/synopsis.py#L196-L201
mcfletch/pyopengl
02d11dad9ff18e50db10e975c4756e17bf198464
OpenGL/GL/DFX/tbuffer.py
python
glInitTbufferDFX
()
return extensions.hasGLExtension( _EXTENSION_NAME )
Return boolean indicating whether this extension is available
Return boolean indicating whether this extension is available
[ "Return", "boolean", "indicating", "whether", "this", "extension", "is", "available" ]
def glInitTbufferDFX(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
[ "def", "glInitTbufferDFX", "(", ")", ":", "from", "OpenGL", "import", "extensions", "return", "extensions", ".", "hasGLExtension", "(", "_EXTENSION_NAME", ")" ]
https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/GL/DFX/tbuffer.py#L23-L26
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/nuomituangou/alp/request/requests/packages/urllib3/connectionpool.py
python
HTTPConnectionPool.urlopen
(self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, **response_kw)
return response
Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param body: Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience). :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Number of retries to allow before raising a MaxRetryError exception. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307). Each redirect counts as a retry. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When False, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param \**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib`
Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details.
[ "Get", "a", "connection", "from", "the", "pool", "and", "perform", "an", "HTTP", "request", ".", "This", "is", "the", "lowest", "level", "call", "for", "making", "a", "request", "so", "you", "ll", "need", "to", "specify", "all", "the", "raw", "details", ...
def urlopen(self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, **response_kw): """ Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param body: Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience). :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Number of retries to allow before raising a MaxRetryError exception. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307). Each redirect counts as a retry. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When False, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param \**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib` """ if headers is None: headers = self.headers if retries < 0: raise MaxRetryError(self, url) if timeout is _Default: timeout = self.timeout if release_conn is None: release_conn = response_kw.get('preload_content', True) # Check host if assert_same_host and not self.is_same_host(url): host = "%s://%s" % (self.scheme, self.host) if self.port: host = "%s:%d" % (host, self.port) raise HostChangedError(self, url, retries - 1) conn = None try: # Request a connection from the queue conn = self._get_conn(timeout=pool_timeout) # Make the request on the httplib connection object httplib_response = self._make_request(conn, method, url, timeout=timeout, body=body, headers=headers) # If we're going to release the connection in ``finally:``, then # the request doesn't need to know about the connection. Otherwise # it will also try to release it and we'll have a double-release # mess. response_conn = not release_conn and conn # Import httplib's response into our own wrapper object response = HTTPResponse.from_httplib(httplib_response, pool=self, connection=response_conn, **response_kw) # else: # The connection will be put back into the pool when # ``response.release_conn()`` is called (implicitly by # ``response.read()``) except Empty as e: # Timed out by queue raise TimeoutError(self, "Request timed out. (pool_timeout=%s)" % pool_timeout) except SocketTimeout as e: # Timed out by socket raise TimeoutError(self, "Request timed out. (timeout=%s)" % timeout) except BaseSSLError as e: # SSL certificate error raise SSLError(e) except CertificateError as e: # Name mismatch raise SSLError(e) except (HTTPException, SocketError) as e: # Connection broken, discard. It will be replaced next _get_conn(). conn = None # This is necessary so we can access e below err = e if retries == 0: raise MaxRetryError(self, url, e) finally: if release_conn: # Put the connection back to be reused. If the connection is # expired then it will be None, which will get replaced with a # fresh connection during _get_conn. self._put_conn(conn) if not conn: # Try again log.warn("Retrying (%d attempts remain) after connection " "broken by '%r': %s" % (retries, err, url)) return self.urlopen(method, url, body, headers, retries - 1, redirect, assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, **response_kw) # Handle redirect? redirect_location = redirect and response.get_redirect_location() if redirect_location: if response.status == 303: method = 'GET' log.info("Redirecting %s -> %s" % (url, redirect_location)) return self.urlopen(method, redirect_location, body, headers, retries - 1, redirect, assert_same_host, timeout=timeout, pool_timeout=pool_timeout, release_conn=release_conn, **response_kw) return response
[ "def", "urlopen", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "retries", "=", "3", ",", "redirect", "=", "True", ",", "assert_same_host", "=", "True", ",", "timeout", "=", "_Default", ",", "pool...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/nuomituangou/alp/request/requests/packages/urllib3/connectionpool.py#L332-L501
dabeaz/curio
27ccf4d130dd8c048e28bd15a22015bce3f55d53
curio/time.py
python
timeout_after
(seconds, coro=None, *args)
Raise a TaskTimeout exception in the calling task after seconds have elapsed. This function may be used in two ways. You can apply it to the execution of a single coroutine: await timeout_after(seconds, coro(args)) or you can use it as an asynchronous context manager to apply a timeout to a block of statements: async with timeout_after(seconds): await coro1(args) await coro2(args) ...
Raise a TaskTimeout exception in the calling task after seconds have elapsed. This function may be used in two ways. You can apply it to the execution of a single coroutine:
[ "Raise", "a", "TaskTimeout", "exception", "in", "the", "calling", "task", "after", "seconds", "have", "elapsed", ".", "This", "function", "may", "be", "used", "in", "two", "ways", ".", "You", "can", "apply", "it", "to", "the", "execution", "of", "a", "si...
def timeout_after(seconds, coro=None, *args): ''' Raise a TaskTimeout exception in the calling task after seconds have elapsed. This function may be used in two ways. You can apply it to the execution of a single coroutine: await timeout_after(seconds, coro(args)) or you can use it as an asynchronous context manager to apply a timeout to a block of statements: async with timeout_after(seconds): await coro1(args) await coro2(args) ... ''' if coro is None: return _TimeoutAfter(seconds) else: return _timeout_after_func(seconds, coro, args)
[ "def", "timeout_after", "(", "seconds", ",", "coro", "=", "None", ",", "*", "args", ")", ":", "if", "coro", "is", "None", ":", "return", "_TimeoutAfter", "(", "seconds", ")", "else", ":", "return", "_timeout_after_func", "(", "seconds", ",", "coro", ",",...
https://github.com/dabeaz/curio/blob/27ccf4d130dd8c048e28bd15a22015bce3f55d53/curio/time.py#L141-L160
mozman/ezdxf
59d0fc2ea63f5cf82293428f5931da7e9f9718e9
src/ezdxf/render/curves.py
python
Spline.render_uniform_bspline
( self, layout: "BaseLayout", degree: int = 3, dxfattribs: dict = None )
Render a uniform B-spline as 3D :class:`~ezdxf.entities.Polyline`. Definition points are control points. Args: layout: :class:`~ezdxf.layouts.BaseLayout` object degree: degree of B-spline (order = `degree` + 1) dxfattribs: DXF attributes for :class:`~ezdxf.entities.Polyline`
Render a uniform B-spline as 3D :class:`~ezdxf.entities.Polyline`. Definition points are control points.
[ "Render", "a", "uniform", "B", "-", "spline", "as", "3D", ":", "class", ":", "~ezdxf", ".", "entities", ".", "Polyline", ".", "Definition", "points", "are", "control", "points", "." ]
def render_uniform_bspline( self, layout: "BaseLayout", degree: int = 3, dxfattribs: dict = None ) -> None: """Render a uniform B-spline as 3D :class:`~ezdxf.entities.Polyline`. Definition points are control points. Args: layout: :class:`~ezdxf.layouts.BaseLayout` object degree: degree of B-spline (order = `degree` + 1) dxfattribs: DXF attributes for :class:`~ezdxf.entities.Polyline` """ spline = open_uniform_bspline(self.points, order=degree + 1) layout.add_polyline3d( list(spline.approximate(self.segments)), dxfattribs=dxfattribs )
[ "def", "render_uniform_bspline", "(", "self", ",", "layout", ":", "\"BaseLayout\"", ",", "degree", ":", "int", "=", "3", ",", "dxfattribs", ":", "dict", "=", "None", ")", "->", "None", ":", "spline", "=", "open_uniform_bspline", "(", "self", ".", "points",...
https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/src/ezdxf/render/curves.py#L316-L331
PowerScript/KatanaFramework
0f6ad90a88de865d58ec26941cb4460501e75496
lib/future/src/future/utils/__init__.py
python
itervalues
(obj, **kwargs)
return func(**kwargs)
Use this only if compatibility with Python versions before 2.7 is required. Otherwise, prefer viewvalues().
Use this only if compatibility with Python versions before 2.7 is required. Otherwise, prefer viewvalues().
[ "Use", "this", "only", "if", "compatibility", "with", "Python", "versions", "before", "2", ".", "7", "is", "required", ".", "Otherwise", "prefer", "viewvalues", "()", "." ]
def itervalues(obj, **kwargs): """Use this only if compatibility with Python versions before 2.7 is required. Otherwise, prefer viewvalues(). """ func = getattr(obj, "itervalues", None) if not func: func = obj.values return func(**kwargs)
[ "def", "itervalues", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "func", "=", "getattr", "(", "obj", ",", "\"itervalues\"", ",", "None", ")", "if", "not", "func", ":", "func", "=", "obj", ".", "values", "return", "func", "(", "*", "*", "kwargs",...
https://github.com/PowerScript/KatanaFramework/blob/0f6ad90a88de865d58ec26941cb4460501e75496/lib/future/src/future/utils/__init__.py#L320-L327
gem/oq-engine
1bdb88f3914e390abcbd285600bfd39477aae47c
openquake/commands/workers.py
python
main
(cmd)
start/stop the workers, or return their status
start/stop the workers, or return their status
[ "start", "/", "stop", "the", "workers", "or", "return", "their", "status" ]
def main(cmd): """ start/stop the workers, or return their status """ if (cmd != 'status' and config.multi_user and getpass.getuser() not in 'openquake'): sys.exit('oq workers only works in single user mode') if p.OQDIST in ('dask', 'celery', 'zmq'): print(getattr(p, 'workers_' + cmd)()) else: print('Nothing to do: oq_distribute=%s' % p.OQDIST)
[ "def", "main", "(", "cmd", ")", ":", "if", "(", "cmd", "!=", "'status'", "and", "config", ".", "multi_user", "and", "getpass", ".", "getuser", "(", ")", "not", "in", "'openquake'", ")", ":", "sys", ".", "exit", "(", "'oq workers only works in single user m...
https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/commands/workers.py#L24-L34
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/contrib/gis/geos/coordseq.py
python
GEOSCoordSeq.__len__
(self)
return int(self.size)
Returns the number of points in the coordinate sequence.
Returns the number of points in the coordinate sequence.
[ "Returns", "the", "number", "of", "points", "in", "the", "coordinate", "sequence", "." ]
def __len__(self): "Returns the number of points in the coordinate sequence." return int(self.size)
[ "def", "__len__", "(", "self", ")", ":", "return", "int", "(", "self", ".", "size", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/contrib/gis/geos/coordseq.py#L30-L32
qmlcode/qml
8bb833cdbbe69405384d6796920c5418dc53b6ba
qml/representations.py
python
generate_atomic_coulomb_matrix
(nuclear_charges, coordinates, size = 23, sorting = "distance", central_cutoff = 1e6, central_decay = -1, interaction_cutoff = 1e6, interaction_decay = -1, indices = None)
Creates a Coulomb Matrix representation of the local environment of a central atom. For each central atom :math:`k`, a matrix :math:`M` is constructed with elements .. math:: M_{ij}(k) = \\begin{cases} \\tfrac{1}{2} Z_{i}^{2.4} \\cdot f_{ik}^2 & \\text{if } i = j \\\\ \\frac{Z_{i}Z_{j}}{\\| {\\bf R}_{i} - {\\bf R}_{j}\\|} \\cdot f_{ik}f_{jk}f_{ij} & \\text{if } i \\neq j \\end{cases}, where :math:`i`, :math:`j` and :math:`k` are atom indices, :math:`Z` is nuclear charge and :math:`\\bf R` is the coordinate in euclidean space. :math:`f_{ij}` is a function that masks long range effects: .. math:: f_{ij} = \\begin{cases} 1 & \\text{if } \\|{\\bf R}_{i} - {\\bf R}_{j} \\| \\leq r - \Delta r \\\\ \\tfrac{1}{2} \\big(1 + \\cos\\big(\\pi \\tfrac{\\|{\\bf R}_{i} - {\\bf R}_{j} \\| - r + \Delta r}{\Delta r} \\big)\\big) & \\text{if } r - \Delta r < \\|{\\bf R}_{i} - {\\bf R}_{j} \\| \\leq r - \Delta r \\\\ 0 & \\text{if } \\|{\\bf R}_{i} - {\\bf R}_{j} \\| > r \\end{cases}, where the parameters ``central_cutoff`` and ``central_decay`` corresponds to the variables :math:`r` and :math:`\Delta r` respectively for interactions involving the central atom, and ``interaction_cutoff`` and ``interaction_decay`` corresponds to the variables :math:`r` and :math:`\Delta r` respectively for interactions not involving the central atom. if ``sorting = 'row-norm'``, the atom indices are ordered such that :math:`\\sum_j M_{1j}(k)^2 \\geq \\sum_j M_{2j}(k)^2 \\geq ... \\geq \\sum_j M_{nj}(k)^2` if ``sorting = 'distance'``, the atom indices are ordered such that .. math:: \\|{\\bf R}_{1} - {\\bf R}_{k}\\| \\leq \\|{\\bf R}_{2} - {\\bf R}_{k}\\| \\leq ... \\leq \\|{\\bf R}_{n} - {\\bf R}_{k}\\| The upper triangular of M, including the diagonal, is concatenated to a 1D vector representation. The representation can be calculated for a subset by either specifying ``indices = [0,1,...]``, where :math:`[0,1,...]` are the requested atom indices, or by specifying ``indices = 'C'`` to only calculate central carbon atoms. The representation is calculated using an OpenMP parallel Fortran routine. :param nuclear_charges: Nuclear charges of the atoms in the molecule :type nuclear_charges: numpy array :param coordinates: 3D Coordinates of the atoms in the molecule :type coordinates: numpy array :param size: The size of the largest molecule supported by the representation :type size: integer :param sorting: How the atom indices are sorted ('row-norm', 'distance') :type sorting: string :param central_cutoff: The distance from the central atom, where the coulomb interaction element will be zero :type central_cutoff: float :param central_decay: The distance over which the the coulomb interaction decays from full to none :type central_decay: float :param interaction_cutoff: The distance between two non-central atom, where the coulomb interaction element will be zero :type interaction_cutoff: float :param interaction_decay: The distance over which the the coulomb interaction decays from full to none :type interaction_decay: float :param indices: Subset indices or atomtype :type indices: Nonetype/array/string :return: nD representation - shape (:math:`N_{atoms}`, size(size+1)/2) :rtype: numpy array
Creates a Coulomb Matrix representation of the local environment of a central atom. For each central atom :math:`k`, a matrix :math:`M` is constructed with elements
[ "Creates", "a", "Coulomb", "Matrix", "representation", "of", "the", "local", "environment", "of", "a", "central", "atom", ".", "For", "each", "central", "atom", ":", "math", ":", "k", "a", "matrix", ":", "math", ":", "M", "is", "constructed", "with", "el...
def generate_atomic_coulomb_matrix(nuclear_charges, coordinates, size = 23, sorting = "distance", central_cutoff = 1e6, central_decay = -1, interaction_cutoff = 1e6, interaction_decay = -1, indices = None): """ Creates a Coulomb Matrix representation of the local environment of a central atom. For each central atom :math:`k`, a matrix :math:`M` is constructed with elements .. math:: M_{ij}(k) = \\begin{cases} \\tfrac{1}{2} Z_{i}^{2.4} \\cdot f_{ik}^2 & \\text{if } i = j \\\\ \\frac{Z_{i}Z_{j}}{\\| {\\bf R}_{i} - {\\bf R}_{j}\\|} \\cdot f_{ik}f_{jk}f_{ij} & \\text{if } i \\neq j \\end{cases}, where :math:`i`, :math:`j` and :math:`k` are atom indices, :math:`Z` is nuclear charge and :math:`\\bf R` is the coordinate in euclidean space. :math:`f_{ij}` is a function that masks long range effects: .. math:: f_{ij} = \\begin{cases} 1 & \\text{if } \\|{\\bf R}_{i} - {\\bf R}_{j} \\| \\leq r - \Delta r \\\\ \\tfrac{1}{2} \\big(1 + \\cos\\big(\\pi \\tfrac{\\|{\\bf R}_{i} - {\\bf R}_{j} \\| - r + \Delta r}{\Delta r} \\big)\\big) & \\text{if } r - \Delta r < \\|{\\bf R}_{i} - {\\bf R}_{j} \\| \\leq r - \Delta r \\\\ 0 & \\text{if } \\|{\\bf R}_{i} - {\\bf R}_{j} \\| > r \\end{cases}, where the parameters ``central_cutoff`` and ``central_decay`` corresponds to the variables :math:`r` and :math:`\Delta r` respectively for interactions involving the central atom, and ``interaction_cutoff`` and ``interaction_decay`` corresponds to the variables :math:`r` and :math:`\Delta r` respectively for interactions not involving the central atom. if ``sorting = 'row-norm'``, the atom indices are ordered such that :math:`\\sum_j M_{1j}(k)^2 \\geq \\sum_j M_{2j}(k)^2 \\geq ... \\geq \\sum_j M_{nj}(k)^2` if ``sorting = 'distance'``, the atom indices are ordered such that .. math:: \\|{\\bf R}_{1} - {\\bf R}_{k}\\| \\leq \\|{\\bf R}_{2} - {\\bf R}_{k}\\| \\leq ... \\leq \\|{\\bf R}_{n} - {\\bf R}_{k}\\| The upper triangular of M, including the diagonal, is concatenated to a 1D vector representation. The representation can be calculated for a subset by either specifying ``indices = [0,1,...]``, where :math:`[0,1,...]` are the requested atom indices, or by specifying ``indices = 'C'`` to only calculate central carbon atoms. The representation is calculated using an OpenMP parallel Fortran routine. :param nuclear_charges: Nuclear charges of the atoms in the molecule :type nuclear_charges: numpy array :param coordinates: 3D Coordinates of the atoms in the molecule :type coordinates: numpy array :param size: The size of the largest molecule supported by the representation :type size: integer :param sorting: How the atom indices are sorted ('row-norm', 'distance') :type sorting: string :param central_cutoff: The distance from the central atom, where the coulomb interaction element will be zero :type central_cutoff: float :param central_decay: The distance over which the the coulomb interaction decays from full to none :type central_decay: float :param interaction_cutoff: The distance between two non-central atom, where the coulomb interaction element will be zero :type interaction_cutoff: float :param interaction_decay: The distance over which the the coulomb interaction decays from full to none :type interaction_decay: float :param indices: Subset indices or atomtype :type indices: Nonetype/array/string :return: nD representation - shape (:math:`N_{atoms}`, size(size+1)/2) :rtype: numpy array """ if indices == None: nindices = len(nuclear_charges) indices = np.arange(1,1+nindices, 1, dtype = int) elif type("") == type(indices): if indices in NUCLEAR_CHARGE: indices = np.where(nuclear_charges == NUCLEAR_CHARGE[indices])[0] + 1 nindices = indices.size if nindices == 0: return np.zeros((0,0)) else: print("ERROR: Unknown value %s given for 'indices' variable" % indices) raise SystemExit else: indices = np.asarray(indices, dtype = int) + 1 nindices = indices.size if (sorting == "row-norm"): return fgenerate_local_coulomb_matrix(indices, nindices, nuclear_charges, coordinates, nuclear_charges.size, size, central_cutoff, central_decay, interaction_cutoff, interaction_decay) elif (sorting == "distance"): return fgenerate_atomic_coulomb_matrix(indices, nindices, nuclear_charges, coordinates, nuclear_charges.size, size, central_cutoff, central_decay, interaction_cutoff, interaction_decay) else: print("ERROR: Unknown sorting scheme requested") raise SystemExit
[ "def", "generate_atomic_coulomb_matrix", "(", "nuclear_charges", ",", "coordinates", ",", "size", "=", "23", ",", "sorting", "=", "\"distance\"", ",", "central_cutoff", "=", "1e6", ",", "central_decay", "=", "-", "1", ",", "interaction_cutoff", "=", "1e6", ",", ...
https://github.com/qmlcode/qml/blob/8bb833cdbbe69405384d6796920c5418dc53b6ba/qml/representations.py#L121-L233
twisted/twisted
dee676b040dd38b847ea6fb112a712cb5e119490
src/twisted/mail/maildir.py
python
MaildirMailbox.appendMessage
(self, txt)
return result
Add a message to the mailbox. @type txt: L{bytes} or file-like object @param txt: A message to add. @rtype: L{Deferred <defer.Deferred>} @return: A deferred which fires when the message has been added to the mailbox.
Add a message to the mailbox.
[ "Add", "a", "message", "to", "the", "mailbox", "." ]
def appendMessage(self, txt): """ Add a message to the mailbox. @type txt: L{bytes} or file-like object @param txt: A message to add. @rtype: L{Deferred <defer.Deferred>} @return: A deferred which fires when the message has been added to the mailbox. """ task = self.AppendFactory(self, txt) result = task.defer task.startUp() return result
[ "def", "appendMessage", "(", "self", ",", "txt", ")", ":", "task", "=", "self", ".", "AppendFactory", "(", "self", ",", "txt", ")", "result", "=", "task", ".", "defer", "task", ".", "startUp", "(", ")", "return", "result" ]
https://github.com/twisted/twisted/blob/dee676b040dd38b847ea6fb112a712cb5e119490/src/twisted/mail/maildir.py#L627-L641
GoogleCloudPlatform/PerfKitBenchmarker
6e3412d7d5e414b8ca30ed5eaf970cef1d919a67
perfkitbenchmarker/linux_packages/oldisim_dependencies.py
python
AptInstall
(vm)
Installs oldisim dependencies on the VM.
Installs oldisim dependencies on the VM.
[ "Installs", "oldisim", "dependencies", "on", "the", "VM", "." ]
def AptInstall(vm): """Installs oldisim dependencies on the VM.""" _Install(vm, APT_PACKAGES)
[ "def", "AptInstall", "(", "vm", ")", ":", "_Install", "(", "vm", ",", "APT_PACKAGES", ")" ]
https://github.com/GoogleCloudPlatform/PerfKitBenchmarker/blob/6e3412d7d5e414b8ca30ed5eaf970cef1d919a67/perfkitbenchmarker/linux_packages/oldisim_dependencies.py#L45-L47
truenas/middleware
b11ec47d6340324f5a32287ffb4012e5d709b934
src/middlewared/middlewared/plugins/nfs_/krb5.py
python
NFSService.add_principal
(self, data)
return ret
Use user-provided admin credentials to kinit, add NFS SPN entries to the remote kerberos server, and then append the new entries to our system keytab. Currently this is only supported in AD environments.
Use user-provided admin credentials to kinit, add NFS SPN entries to the remote kerberos server, and then append the new entries to our system keytab.
[ "Use", "user", "-", "provided", "admin", "credentials", "to", "kinit", "add", "NFS", "SPN", "entries", "to", "the", "remote", "kerberos", "server", "and", "then", "append", "the", "new", "entries", "to", "our", "system", "keytab", "." ]
async def add_principal(self, data): """ Use user-provided admin credentials to kinit, add NFS SPN entries to the remote kerberos server, and then append the new entries to our system keytab. Currently this is only supported in AD environments. """ ret = False if await self.middleware.call("kerberos.keytab.has_nfs_principal"): raise CallError("NFS SPN entry already exists in system keytab", errno.EEXIST) ds = await self.middleware.call('directoryservices.get_state') await self.validate_directoryservices(ds) ad_status = DSStatus[ds['activedirectory']] ldap_status = DSStatus[ds['ldap']] if ad_status == DSStatus.HEALTHY: ret = await self.add_principal_ad(data) elif ldap_status == DSStatus.HEALTHY: ret = await self.add_principal_ldap(data) """ This step is to ensure that elevated permissions are dropped. """ await self.middleware.call('kerberos.stop') await self.middleware.call('kerberos.start') return ret
[ "async", "def", "add_principal", "(", "self", ",", "data", ")", ":", "ret", "=", "False", "if", "await", "self", ".", "middleware", ".", "call", "(", "\"kerberos.keytab.has_nfs_principal\"", ")", ":", "raise", "CallError", "(", "\"NFS SPN entry already exists in s...
https://github.com/truenas/middleware/blob/b11ec47d6340324f5a32287ffb4012e5d709b934/src/middlewared/middlewared/plugins/nfs_/krb5.py#L80-L110
datamachine/twx.botapi
4807da2082704876c0de4826b347a6347d84372d
twx/botapi/botapi.py
python
get_game_high_scores
(user_id, chat_id=None, message_id=None, inline_message_id=None, **kwargs)
return TelegramBotRPCRequest('getGameHighScores', params=params, on_result=GameHighScore.from_array_result, **kwargs)
Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. :param user_id: Target user id :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) target channel in the format @channelusername) :param message_id: Required if inline_message_id is not specified. Identifier of the sent message :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message :param *\*kwargs: Args that get passed down to :class:`TelegramBotRPCRequest` :type user_id: int :type chat_id: int or str :type message_id: int :type inline_message_id: str :return:
Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.
[ "Use", "this", "method", "to", "get", "data", "for", "high", "score", "tables", ".", "Will", "return", "the", "score", "of", "the", "specified", "user", "and", "several", "of", "his", "neighbors", "in", "a", "game", ".", "On", "success", "returns", "an",...
def get_game_high_scores(user_id, chat_id=None, message_id=None, inline_message_id=None, **kwargs): """ Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. :param user_id: Target user id :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) target channel in the format @channelusername) :param message_id: Required if inline_message_id is not specified. Identifier of the sent message :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message :param *\*kwargs: Args that get passed down to :class:`TelegramBotRPCRequest` :type user_id: int :type chat_id: int or str :type message_id: int :type inline_message_id: str :return: """ # required args params = dict(user_id=user_id) # optional args params.update( _clean_params( chat_id=chat_id, message_id=message_id, inline_message_id=inline_message_id, ) ) return TelegramBotRPCRequest('getGameHighScores', params=params, on_result=GameHighScore.from_array_result, **kwargs)
[ "def", "get_game_high_scores", "(", "user_id", ",", "chat_id", "=", "None", ",", "message_id", "=", "None", ",", "inline_message_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# required args", "params", "=", "dict", "(", "user_id", "=", "user_id", ...
https://github.com/datamachine/twx.botapi/blob/4807da2082704876c0de4826b347a6347d84372d/twx/botapi/botapi.py#L4056-L4094
NVIDIA/NeMo
5b0c0b4dec12d87d3cd960846de4105309ce938e
nemo/collections/nlp/models/entity_linking/entity_linking_model.py
python
EntityLinkingModel.__init__
(self, cfg: DictConfig, trainer: Trainer = None)
Initializes the SAP-BERT model for entity linking.
Initializes the SAP-BERT model for entity linking.
[ "Initializes", "the", "SAP", "-", "BERT", "model", "for", "entity", "linking", "." ]
def __init__(self, cfg: DictConfig, trainer: Trainer = None): """Initializes the SAP-BERT model for entity linking.""" # tokenizer needed before super().__init__() so dataset and loader can process data self._setup_tokenizer(cfg.tokenizer) super().__init__(cfg=cfg, trainer=trainer) self.model = get_lm_model( pretrained_model_name=cfg.language_model.pretrained_model_name, config_file=cfg.language_model.config_file, config_dict=cfg.language_model.config, checkpoint_file=cfg.language_model.lm_checkpoint, ) # Token to use for the self-alignment loss, typically the first token, [CLS] self._idx_conditioned_on = 0 self.loss = MultiSimilarityLoss()
[ "def", "__init__", "(", "self", ",", "cfg", ":", "DictConfig", ",", "trainer", ":", "Trainer", "=", "None", ")", ":", "# tokenizer needed before super().__init__() so dataset and loader can process data", "self", ".", "_setup_tokenizer", "(", "cfg", ".", "tokenizer", ...
https://github.com/NVIDIA/NeMo/blob/5b0c0b4dec12d87d3cd960846de4105309ce938e/nemo/collections/nlp/models/entity_linking/entity_linking_model.py#L49-L66
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/soupsieve/util.py
python
get_pattern_context
(pattern, index)
return ''.join(text), line, col
Get the pattern context.
Get the pattern context.
[ "Get", "the", "pattern", "context", "." ]
def get_pattern_context(pattern, index): """Get the pattern context.""" last = 0 current_line = 1 col = 1 text = [] line = 1 # Split pattern by newline and handle the text before the newline for m in RE_PATTERN_LINE_SPLIT.finditer(pattern): linetext = pattern[last:m.start(0)] if not len(m.group(0)) and not len(text): indent = '' offset = -1 col = index - last + 1 elif last <= index < m.end(0): indent = '--> ' offset = (-1 if index > m.start(0) else 0) + 3 col = index - last + 1 else: indent = ' ' offset = None if len(text): # Regardless of whether we are presented with `\r\n`, `\r`, or `\n`, # we will render the output with just `\n`. We will still log the column # correctly though. text.append('\n') text.append('{}{}'.format(indent, linetext)) if offset is not None: text.append('\n') text.append(' ' * (col + offset) + '^') line = current_line current_line += 1 last = m.end(0) return ''.join(text), line, col
[ "def", "get_pattern_context", "(", "pattern", ",", "index", ")", ":", "last", "=", "0", "current_line", "=", "1", "col", "=", "1", "text", "=", "[", "]", "line", "=", "1", "# Split pattern by newline and handle the text before the newline", "for", "m", "in", "...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/soupsieve/util.py#L131-L168
llSourcell/AI_Artist
3038c06c2e389b9c919c881c9a169efe2fd7810e
lib/python2.7/site-packages/pip/_vendor/distlib/_backport/shutil.py
python
_find_unpack_format
(filename)
return None
[]
def _find_unpack_format(filename): for name, info in _UNPACK_FORMATS.items(): for extension in info[0]: if filename.endswith(extension): return name return None
[ "def", "_find_unpack_format", "(", "filename", ")", ":", "for", "name", ",", "info", "in", "_UNPACK_FORMATS", ".", "items", "(", ")", ":", "for", "extension", "in", "info", "[", "0", "]", ":", "if", "filename", ".", "endswith", "(", "extension", ")", "...
https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/distlib/_backport/shutil.py#L720-L725
criteo/biggraphite
1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30
biggraphite/metadata_cache.py
python
DiskCache._cache_get
(self, metric_name)
return bg_metric.Metric(metric_name, id, metadata), True
Return a Metric from a the cache, None if no such metric.
Return a Metric from a the cache, None if no such metric.
[ "Return", "a", "Metric", "from", "a", "the", "cache", "None", "if", "no", "such", "metric", "." ]
def _cache_get(self, metric_name): """Return a Metric from a the cache, None if no such metric.""" encoded_metric_name = self._encode(metric_name) with self.__env.begin(self.__metric_to_metadata_db, write=False) as txn: payload = txn.get(encoded_metric_name) if payload == self._EMPTY: return None, True if payload is not None: payload = self._decode(payload) if not payload: # cache miss return None, False # found something in the cache split = self.__split_payload(payload) if split is None: # invalid string => evict from cache with self.__env.begin(self.__metric_to_metadata_db, write=True) as txn: txn.delete(key=encoded_metric_name) return None, False # valid value => get id and metadata string # TODO: optimization: id is a UUID (known length) id_str, metadata_str, timestamp = split try: id = uuid.UUID(id_str) except Exception as e: logging.debug(str(e)) with self.__env.begin(self.__metric_to_metadata_db, write=True) as txn: txn.delete(key=encoded_metric_name) return None, False # if the timestamp expired evict it in order to force # its recreation for the next time if self.__expired_timestamp(timestamp): with self.__env.begin(self.__metric_to_metadata_db, write=True) as txn: txn.delete(key=encoded_metric_name) metadata = self.metadata_from_str(metadata_str) return bg_metric.Metric(metric_name, id, metadata), True
[ "def", "_cache_get", "(", "self", ",", "metric_name", ")", ":", "encoded_metric_name", "=", "self", ".", "_encode", "(", "metric_name", ")", "with", "self", ".", "__env", ".", "begin", "(", "self", ".", "__metric_to_metadata_db", ",", "write", "=", "False", ...
https://github.com/criteo/biggraphite/blob/1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30/biggraphite/metadata_cache.py#L483-L526
livid/v2ex-gae
32be3a77d535e7c9df85a333e01ab8834d0e8581
mapreduce/lib/simplejson/__init__.py
python
load
(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw)
return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, **kw)
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. If the contents of ``fp`` is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped with ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` object and passed to ``loads()`` ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg.
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object.
[ "Deserialize", "fp", "(", "a", ".", "read", "()", "-", "supporting", "file", "-", "like", "object", "containing", "a", "JSON", "document", ")", "to", "a", "Python", "object", "." ]
def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. If the contents of ``fp`` is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed, and should be wrapped with ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` object and passed to ``loads()`` ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, **kw)
[ "def", "load", "(", "fp", ",", "encoding", "=", "None", ",", "cls", "=", "None", ",", "object_hook", "=", "None", ",", "parse_float", "=", "None", ",", "parse_int", "=", "None", ",", "parse_constant", "=", "None", ",", "*", "*", "kw", ")", ":", "re...
https://github.com/livid/v2ex-gae/blob/32be3a77d535e7c9df85a333e01ab8834d0e8581/mapreduce/lib/simplejson/__init__.py#L239-L263
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/utils/inertia.py
python
translate_inertia_matrix
(inertia, vector, mass)
return inertia - mass * d**2
r""" "The inertia matrix of a body depends on the choice of the reference point. There is a useful relationship between the inertia matrix relative to the center of mass C and the inertia matrix relative to the another point. This relationship is called the parallel axis theorem" [1]. The result is given by: .. math:: I_R = I_C - M [d]^2 where :math:`I_R \in \mathbb{R}^{3 \times 3}` is the inertia matrix relative to the point :math:`R`, :math:`I_C \in \mathbb{R}^{3 \times 3}` is the inertia matrix relative to the center of mass :math:`C`, :math:`M \in \mathbb{R}` is the total mass of the system, :math:`d \in \mathbb{R}^3` is the vector from the center of mass :math:`C` to the reference point :math:`R`, and :math:`[\cdot]` is the operation which transforms a vector into a skew-symmetric matrix. Args: inertia (np.array[float[3,3]]): full inertia matrix of a body around its CoM. vector (np.array[float[3]]): translation vector from the CoM to another point. mass (float): the total mass of the body. Returns: np.array[float[3,3]]: full inertia matrix of a body relative to another point. References: - [1] Parallel axis theorem (Wikipedia): https://en.wikipedia.org/wiki/Moment_of_inertia#Parallel_axis_theorem
r""" "The inertia matrix of a body depends on the choice of the reference point. There is a useful relationship between the inertia matrix relative to the center of mass C and the inertia matrix relative to the another point. This relationship is called the parallel axis theorem" [1].
[ "r", "The", "inertia", "matrix", "of", "a", "body", "depends", "on", "the", "choice", "of", "the", "reference", "point", ".", "There", "is", "a", "useful", "relationship", "between", "the", "inertia", "matrix", "relative", "to", "the", "center", "of", "mas...
def translate_inertia_matrix(inertia, vector, mass): r""" "The inertia matrix of a body depends on the choice of the reference point. There is a useful relationship between the inertia matrix relative to the center of mass C and the inertia matrix relative to the another point. This relationship is called the parallel axis theorem" [1]. The result is given by: .. math:: I_R = I_C - M [d]^2 where :math:`I_R \in \mathbb{R}^{3 \times 3}` is the inertia matrix relative to the point :math:`R`, :math:`I_C \in \mathbb{R}^{3 \times 3}` is the inertia matrix relative to the center of mass :math:`C`, :math:`M \in \mathbb{R}` is the total mass of the system, :math:`d \in \mathbb{R}^3` is the vector from the center of mass :math:`C` to the reference point :math:`R`, and :math:`[\cdot]` is the operation which transforms a vector into a skew-symmetric matrix. Args: inertia (np.array[float[3,3]]): full inertia matrix of a body around its CoM. vector (np.array[float[3]]): translation vector from the CoM to another point. mass (float): the total mass of the body. Returns: np.array[float[3,3]]: full inertia matrix of a body relative to another point. References: - [1] Parallel axis theorem (Wikipedia): https://en.wikipedia.org/wiki/Moment_of_inertia#Parallel_axis_theorem """ d = skew_matrix(vector) return inertia - mass * d**2
[ "def", "translate_inertia_matrix", "(", "inertia", ",", "vector", ",", "mass", ")", ":", "d", "=", "skew_matrix", "(", "vector", ")", "return", "inertia", "-", "mass", "*", "d", "**", "2" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/utils/inertia.py#L156-L184
hackingmaterials/atomate
bdca913591d22a6f71d4914c69f3ee191e2d96db
atomate/feff/fireworks/core.py
python
EXAFSPathsFW.__init__
( self, absorbing_atom, structure, paths, degeneracies=None, edge="K", radius=10.0, name="EXAFS Paths", feff_input_set="pymatgen.io.feff.sets.MPEXAFSSet", feff_cmd="feff", override_default_feff_params=None, parents=None, filepad_file=None, labels=None, metadata=None, **kwargs, )
Write the input set for FEFF-EXAFS spectroscopy with customized scattering paths, run feff, and insert the scattering amplitude output files(feffNNNN.dat files) to filepad. Args: absorbing_atom (str): absorbing atom symbol structure (Structure): input structure paths (list): list of paths. A path = list of site indices that defines the path legs. degeneracies (list): degeneracy of each path. edge (str): absorption edge radius (float): cluster radius in angstroms name (str) feff_input_set (FeffDictSet) feff_cmd (str): path to the feff binary override_default_feff_params (dict): override feff tag settings. parents (Firework): Parents of this particular Firework. FW or list of FWS. filepad_file (str): path to the filepad config file. labels (list): list of label used to tag the files inserted into filepad. metadata (dict): meta data **kwargs: Other kwargs that are passed to Firework.__init__.
Write the input set for FEFF-EXAFS spectroscopy with customized scattering paths, run feff, and insert the scattering amplitude output files(feffNNNN.dat files) to filepad.
[ "Write", "the", "input", "set", "for", "FEFF", "-", "EXAFS", "spectroscopy", "with", "customized", "scattering", "paths", "run", "feff", "and", "insert", "the", "scattering", "amplitude", "output", "files", "(", "feffNNNN", ".", "dat", "files", ")", "to", "f...
def __init__( self, absorbing_atom, structure, paths, degeneracies=None, edge="K", radius=10.0, name="EXAFS Paths", feff_input_set="pymatgen.io.feff.sets.MPEXAFSSet", feff_cmd="feff", override_default_feff_params=None, parents=None, filepad_file=None, labels=None, metadata=None, **kwargs, ): """ Write the input set for FEFF-EXAFS spectroscopy with customized scattering paths, run feff, and insert the scattering amplitude output files(feffNNNN.dat files) to filepad. Args: absorbing_atom (str): absorbing atom symbol structure (Structure): input structure paths (list): list of paths. A path = list of site indices that defines the path legs. degeneracies (list): degeneracy of each path. edge (str): absorption edge radius (float): cluster radius in angstroms name (str) feff_input_set (FeffDictSet) feff_cmd (str): path to the feff binary override_default_feff_params (dict): override feff tag settings. parents (Firework): Parents of this particular Firework. FW or list of FWS. filepad_file (str): path to the filepad config file. labels (list): list of label used to tag the files inserted into filepad. metadata (dict): meta data **kwargs: Other kwargs that are passed to Firework.__init__. """ override_default_feff_params = override_default_feff_params or {} override_default_feff_params.update( {"user_tag_settings": {"CONTROL": "0 0 0 0 1 1", "PRINT": "0 0 0 1 0 3"}} ) feff_input_set = get_feff_input_set_obj( feff_input_set, absorbing_atom, structure, edge=edge, radius=radius, **override_default_feff_params, ) t = [ CopyFeffOutputs(calc_loc=True), WriteFeffFromIOSet( absorbing_atom=absorbing_atom, structure=structure, radius=radius, feff_input_set=feff_input_set, ), WriteEXAFSPaths( feff_input_set=feff_input_set, paths=paths, degeneracies=degeneracies ), RunFeffDirect(feff_cmd=feff_cmd), AddPathsToFilepadTask( filepad_file=filepad_file, labels=labels, metadata=metadata ), ] super().__init__( t, parents=parents, name=f"{structure.composition.reduced_formula}-{name}", **kwargs, )
[ "def", "__init__", "(", "self", ",", "absorbing_atom", ",", "structure", ",", "paths", ",", "degeneracies", "=", "None", ",", "edge", "=", "\"K\"", ",", "radius", "=", "10.0", ",", "name", "=", "\"EXAFS Paths\"", ",", "feff_input_set", "=", "\"pymatgen.io.fe...
https://github.com/hackingmaterials/atomate/blob/bdca913591d22a6f71d4914c69f3ee191e2d96db/atomate/feff/fireworks/core.py#L190-L265
OpenMDAO/OpenMDAO1
791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317
openmdao/core/problem.py
python
Problem._calc_gradient_ln_solver
(self, indep_list, unknown_list, return_format, mode, dv_scale=None, cn_scale=None, sparsity=None, inactives=None)
return J
Returns the gradient for the system that is specified in self.root. The gradient is calculated using root.ln_solver. Args ---- indep_list : list of strings List of independent variable names that derivatives are to be calculated with respect to. All params must have a IndepVarComp. unknown_list : list of strings List of output or state names that derivatives are to be calculated for. All must be valid unknowns in OpenMDAO. return_format : string Format for the derivatives, can be 'array' or 'dict'. mode : string Deriviative direction, can be 'fwd', 'rev', 'fd', or 'auto'. Default is 'auto', which uses mode specified on the linear solver in root. dv_scale : dict, optional Dictionary of driver-defined scale factors on the design variables. cn_scale : dict, optional Dictionary of driver-defined scale factors on the constraints. sparsity : dict, optional Dictionary that gives the relevant design variables for each constraint. This option is only supported in the `dict` return format. inactives : dict, optional Dictionary of all inactive constraints. Gradient calculation is skipped for these in adjoine mode. Key is the constraint name, and value is the indices that are inactive. Returns ------- ndarray or dict Jacobian of unknowns with respect to params.
Returns the gradient for the system that is specified in self.root. The gradient is calculated using root.ln_solver.
[ "Returns", "the", "gradient", "for", "the", "system", "that", "is", "specified", "in", "self", ".", "root", ".", "The", "gradient", "is", "calculated", "using", "root", ".", "ln_solver", "." ]
def _calc_gradient_ln_solver(self, indep_list, unknown_list, return_format, mode, dv_scale=None, cn_scale=None, sparsity=None, inactives=None): """ Returns the gradient for the system that is specified in self.root. The gradient is calculated using root.ln_solver. Args ---- indep_list : list of strings List of independent variable names that derivatives are to be calculated with respect to. All params must have a IndepVarComp. unknown_list : list of strings List of output or state names that derivatives are to be calculated for. All must be valid unknowns in OpenMDAO. return_format : string Format for the derivatives, can be 'array' or 'dict'. mode : string Deriviative direction, can be 'fwd', 'rev', 'fd', or 'auto'. Default is 'auto', which uses mode specified on the linear solver in root. dv_scale : dict, optional Dictionary of driver-defined scale factors on the design variables. cn_scale : dict, optional Dictionary of driver-defined scale factors on the constraints. sparsity : dict, optional Dictionary that gives the relevant design variables for each constraint. This option is only supported in the `dict` return format. inactives : dict, optional Dictionary of all inactive constraints. Gradient calculation is skipped for these in adjoine mode. Key is the constraint name, and value is the indices that are inactive. Returns ------- ndarray or dict Jacobian of unknowns with respect to params. """ root = self.root relevance = root._probdata.relevance unknowns = root.unknowns unknowns_dict = root._unknowns_dict to_abs_uname = root._sysdata.to_abs_uname comm = root.comm iproc = comm.rank nproc = comm.size owned = root._owning_ranks if dv_scale is None: dv_scale = {} if cn_scale is None: cn_scale = {} # Respect choice of mode based on precedence. # Call arg > ln_solver option > auto-detect mode = self._mode(mode, indep_list, unknown_list) fwd = mode == 'fwd' # Prepare model for calculation root.clear_dparams() for names in root._probdata.relevance.vars_of_interest(mode): for name in names: if name in root.dumat: root.dumat[name].vec[:] = 0.0 root.drmat[name].vec[:] = 0.0 root.dumat[None].vec[:] = 0.0 root.drmat[None].vec[:] = 0.0 # Linearize Model root._sys_linearize(root.params, unknowns, root.resids) # Initialize Jacobian if return_format == 'dict': J = OrderedDict() for okeys in unknown_list: if isinstance(okeys, string_types): okeys = (okeys,) for okey in okeys: J[okey] = OrderedDict() for ikeys in indep_list: if isinstance(ikeys, string_types): ikeys = (ikeys,) for ikey in ikeys: # Support sparsity if sparsity is not None: if ikey not in sparsity[okey]: continue J[okey][ikey] = None else: usize = 0 psize = 0 Jslices = OrderedDict() for u in unknown_list: start = usize if u in self._qoi_indices: idx = self._qoi_indices[u] usize += len(idx) else: usize += self.root.unknowns.metadata(u)['size'] Jslices[u] = slice(start, usize) for p in indep_list: start = psize if p in self._poi_indices: idx = self._poi_indices[p] psize += len(idx) else: psize += unknowns.metadata(p)['size'] Jslices[p] = slice(start, psize) J = np.zeros((usize, psize)) if fwd: input_list, output_list = indep_list, unknown_list poi_indices, qoi_indices = self._poi_indices, self._qoi_indices in_scale, un_scale = dv_scale, cn_scale else: input_list, output_list = unknown_list, indep_list qoi_indices, poi_indices = self._poi_indices, self._qoi_indices in_scale, un_scale = cn_scale, dv_scale # Process our inputs/outputs of interest for parallel groups all_vois = self.root._probdata.relevance.vars_of_interest(mode) input_set = set() for inp in input_list: if isinstance(inp, string_types): input_set.add(inp) else: input_set.update(inp) # Our variables of interest include all sets for which at least # one variable is requested. voi_sets = [] for voi_set in all_vois: for voi in voi_set: if voi in input_set: voi_sets.append(voi_set) break # Add any variables that the user "forgot". TODO: This won't be # necessary when we have an API to automatically generate the # IOI and OOI. flat_voi = [item for sublist in all_vois for item in sublist] for items in input_list: if isinstance(items, string_types): items = (items,) for item in items: if item not in flat_voi: # Put them in serial groups voi_sets.append((item,)) voi_srcs = {} # If Forward mode, solve linear system for each param # If Adjoint mode, solve linear system for each unknown for params in voi_sets: rhs = OrderedDict() voi_idxs = {} old_size = None # Allocate all of our Right Hand Sides for this parallel set. for voi in params: vkey = self._get_voi_key(voi, params) duvec = self.root.dumat[vkey] rhs[vkey] = np.empty((len(duvec.vec), )) voi_srcs[vkey] = voi if voi in duvec: in_idxs = duvec._get_local_idxs(voi, poi_indices) else: in_idxs = [] if len(in_idxs) == 0: if voi in poi_indices: # offset doesn't matter since we only care about the size in_idxs = duvec.to_idx_array(poi_indices[voi]) else: in_idxs = np.arange(0, unknowns_dict[to_abs_uname[voi]]['size'], dtype=int) if old_size is None: old_size = len(in_idxs) elif old_size != len(in_idxs): raise RuntimeError("Indices within the same VOI group must be the same size, but" " in the group %s, %d != %d" % (params, old_size, len(in_idxs))) voi_idxs[vkey] = in_idxs # at this point, we know that for all vars in the current # group of interest, the number of indices is the same. We loop # over the *size* of the indices and use the loop index to look # up the actual indices for the current members of the group # of interest. for i in range(len(in_idxs)): # If this is a constraint, and it is inactive, don't do the # linear solve. Instead, allocate zeros for the solution and # let the remaining code partition that into the return array # or dict. if inactives and not fwd and voi in inactives and i in inactives[voi]: dx_mat = OrderedDict() for voi in params: vkey = self._get_voi_key(voi, params) dx_mat[vkey] = np.zeros((len(duvec.vec), )) else: for voi in params: vkey = self._get_voi_key(voi, params) rhs[vkey][:] = 0.0 # only set a -1.0 in the entry if that var is 'owned' by this rank # Note, we solve a slightly modified version of the unified # derivatives equations in OpenMDAO. # (dR/du) * (du/dr) = -I if self.root._owning_ranks[voi_srcs[vkey]] == iproc: rhs[vkey][voi_idxs[vkey][i]] = -1.0 # Solve the linear system dx_mat = root.ln_solver.solve(rhs, root, mode) for param, dx in iteritems(dx_mat): vkey = self._get_voi_key(param, params) if param is None: param = params[0] for item in output_list: # Support sparsity if sparsity is not None: if fwd and param not in sparsity[item]: continue elif not fwd and item not in sparsity[param]: continue if relevance.is_relevant(vkey, item): if fwd or owned[item] == iproc: out_idxs = self.root.dumat[vkey]._get_local_idxs(item, qoi_indices, get_slice=True) dxval = dx[out_idxs] if dxval.size == 0: dxval = None else: dxval = None if nproc > 1: # TODO: make this use Bcast for efficiency if trace: debug("calc_gradient_ln_solver dxval bcast. dxval=%s, root=%s, param=%s, item=%s" % (dxval, owned[item], param, item)) dxval = comm.bcast(dxval, root=owned[item]) if trace: debug("dxval bcast DONE") else: # irrelevant variable. just give'em zeros if item in qoi_indices: zsize = len(qoi_indices[item]) else: zsize = unknowns.metadata(item)['size'] dxval = np.zeros(zsize) if dxval is not None: nk = len(dxval) if return_format == 'dict': if fwd: if J[item][param] is None: J[item][param] = np.zeros((nk, len(in_idxs))) J[item][param][:, i] = dxval # Driver scaling if param in in_scale: J[item][param][:, i] *= in_scale[param] if item in un_scale: J[item][param][:, i] *= un_scale[item] else: if J[param][item] is None: J[param][item] = np.zeros((len(in_idxs), nk)) J[param][item][i, :] = dxval # Driver scaling if param in in_scale: J[param][item][i, :] *= in_scale[param] if item in un_scale: J[param][item][i, :] *= un_scale[item] else: if fwd: J[Jslices[item], Jslices[param].start+i] = dxval # Driver scaling if param in in_scale: J[Jslices[item], Jslices[param].start+i] *= in_scale[param] if item in un_scale: J[Jslices[item], Jslices[param].start+i] *= un_scale[item] else: J[Jslices[param].start+i, Jslices[item]] = dxval # Driver scaling if param in in_scale: J[Jslices[param].start+i, Jslices[item]] *= in_scale[param] if item in un_scale: J[Jslices[param].start+i, Jslices[item]] *= un_scale[item] # Clean up after ourselves root.clear_dparams() return J
[ "def", "_calc_gradient_ln_solver", "(", "self", ",", "indep_list", ",", "unknown_list", ",", "return_format", ",", "mode", ",", "dv_scale", "=", "None", ",", "cn_scale", "=", "None", ",", "sparsity", "=", "None", ",", "inactives", "=", "None", ")", ":", "r...
https://github.com/OpenMDAO/OpenMDAO1/blob/791a6fbbb7d266f3dcbc1f7bde3ae03a70dc1317/openmdao/core/problem.py#L1482-L1799
etetoolkit/ete
2b207357dc2a40ccad7bfd8f54964472c72e4726
ete3/tools/ete_build_lib/validate.py
python
is_string
(value, min=None, max=None)
return value
Check that the supplied value is a string. You can optionally specify the minimum and maximum number of members. >>> vtor.check('string', '0') '0' >>> vtor.check('string', 0) Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. >>> vtor.check('string(2)', '12') '12' >>> vtor.check('string(2)', '1') Traceback (most recent call last): VdtValueTooShortError: the value "1" is too short. >>> vtor.check('string(min=2, max=3)', '123') '123' >>> vtor.check('string(min=2, max=3)', '1234') Traceback (most recent call last): VdtValueTooLongError: the value "1234" is too long.
Check that the supplied value is a string.
[ "Check", "that", "the", "supplied", "value", "is", "a", "string", "." ]
def is_string(value, min=None, max=None): """ Check that the supplied value is a string. You can optionally specify the minimum and maximum number of members. >>> vtor.check('string', '0') '0' >>> vtor.check('string', 0) Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. >>> vtor.check('string(2)', '12') '12' >>> vtor.check('string(2)', '1') Traceback (most recent call last): VdtValueTooShortError: the value "1" is too short. >>> vtor.check('string(min=2, max=3)', '123') '123' >>> vtor.check('string(min=2, max=3)', '1234') Traceback (most recent call last): VdtValueTooLongError: the value "1234" is too long. """ if not isinstance(value, six.string_types): raise VdtTypeError(value) (min_len, max_len) = _is_num_param(('min', 'max'), (min, max)) try: num_members = len(value) except TypeError: raise VdtTypeError(value) if min_len is not None and num_members < min_len: raise VdtValueTooShortError(value) if max_len is not None and num_members > max_len: raise VdtValueTooLongError(value) return value
[ "def", "is_string", "(", "value", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "if", "not", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "raise", "VdtTypeError", "(", "value", ")", "(", "min_len", ",", "max_le...
https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/ete3/tools/ete_build_lib/validate.py#L1086-L1119
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/tornado/iostream.py
python
BaseIOStream._check_closed
(self)
[]
def _check_closed(self) -> None: if self.closed(): raise StreamClosedError(real_error=self.error)
[ "def", "_check_closed", "(", "self", ")", "->", "None", ":", "if", "self", ".", "closed", "(", ")", ":", "raise", "StreamClosedError", "(", "real_error", "=", "self", ".", "error", ")" ]
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/tornado/iostream.py#L1033-L1035
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/knowledge_plugins/functions/function.py
python
Function.copy
(self)
return func
[]
def copy(self): func = Function(self._function_manager, self.addr, name=self.name, syscall=self.is_syscall) func.transition_graph = networkx.DiGraph(self.transition_graph) func.normalized = self.normalized func._ret_sites = self._ret_sites.copy() func._jumpout_sites = self._jumpout_sites.copy() func._retout_sites = self._retout_sites.copy() func._endpoints = self._endpoints.copy() func._call_sites = self._call_sites.copy() func._project = self._project func.is_plt = self.is_plt func.is_simprocedure = self.is_simprocedure func.binary_name = self.binary_name func.bp_on_stack = self.bp_on_stack func.retaddr_on_stack = self.retaddr_on_stack func.sp_delta = self.sp_delta func.calling_convention = self.calling_convention func.prototype = self.prototype func._returning = self._returning func.alignment = self.alignment func.startpoint = self.startpoint func._addr_to_block_node = self._addr_to_block_node.copy() func._block_sizes = self._block_sizes.copy() func._block_cache = self._block_cache.copy() func._local_blocks = self._local_blocks.copy() func._local_block_addrs = self._local_block_addrs.copy() func.info = self.info.copy() func.tags = self.tags return func
[ "def", "copy", "(", "self", ")", ":", "func", "=", "Function", "(", "self", ".", "_function_manager", ",", "self", ".", "addr", ",", "name", "=", "self", ".", "name", ",", "syscall", "=", "self", ".", "is_syscall", ")", "func", ".", "transition_graph",...
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/knowledge_plugins/functions/function.py#L1442-L1471
internetarchive/openlibrary
33b9b005ecb0adeda690c67952f5ae5f1fe3a8d8
openlibrary/plugins/upstream/models.py
python
Edition.get_covers
(self)
return [Image(self._site, 'b', c) for c in self.covers if c and c > 0]
This methods excludes covers that are -1 or None, which are in the data but should not be.
This methods excludes covers that are -1 or None, which are in the data but should not be.
[ "This", "methods", "excludes", "covers", "that", "are", "-", "1", "or", "None", "which", "are", "in", "the", "data", "but", "should", "not", "be", "." ]
def get_covers(self): """ This methods excludes covers that are -1 or None, which are in the data but should not be. """ return [Image(self._site, 'b', c) for c in self.covers if c and c > 0]
[ "def", "get_covers", "(", "self", ")", ":", "return", "[", "Image", "(", "self", ".", "_site", ",", "'b'", ",", "c", ")", "for", "c", "in", "self", ".", "covers", "if", "c", "and", "c", ">", "0", "]" ]
https://github.com/internetarchive/openlibrary/blob/33b9b005ecb0adeda690c67952f5ae5f1fe3a8d8/openlibrary/plugins/upstream/models.py#L97-L102
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/python-openid-2.2.5/openid/consumer/consumer.py
python
GenericConsumer._processCheckAuthResponse
(self, response, server_url)
Process the response message from a check_authentication request, invalidating associations if requested.
Process the response message from a check_authentication request, invalidating associations if requested.
[ "Process", "the", "response", "message", "from", "a", "check_authentication", "request", "invalidating", "associations", "if", "requested", "." ]
def _processCheckAuthResponse(self, response, server_url): """Process the response message from a check_authentication request, invalidating associations if requested. """ is_valid = response.getArg(OPENID_NS, 'is_valid', 'false') invalidate_handle = response.getArg(OPENID_NS, 'invalidate_handle') if invalidate_handle is not None: oidutil.log( 'Received "invalidate_handle" from server %s' % (server_url,)) if self.store is None: oidutil.log('Unexpectedly got invalidate_handle without ' 'a store!') else: self.store.removeAssociation(server_url, invalidate_handle) if is_valid == 'true': return True else: oidutil.log('Server responds that checkAuth call is not valid') return False
[ "def", "_processCheckAuthResponse", "(", "self", ",", "response", ",", "server_url", ")", ":", "is_valid", "=", "response", ".", "getArg", "(", "OPENID_NS", ",", "'is_valid'", ",", "'false'", ")", "invalidate_handle", "=", "response", ".", "getArg", "(", "OPEN...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/python-openid-2.2.5/openid/consumer/consumer.py#L1124-L1144
QUANTAXIS/QUANTAXIS
d6eccb97c8385854aa596d6ba8d70ec0655519ff
QUANTAXIS/QAMarket/QAPosition.py
python
QA_PMS.dealAction
(self)
成交回报
成交回报
[ "成交回报" ]
def dealAction(self): ''' 成交回报 ''' pass
[ "def", "dealAction", "(", "self", ")", ":", "pass" ]
https://github.com/QUANTAXIS/QUANTAXIS/blob/d6eccb97c8385854aa596d6ba8d70ec0655519ff/QUANTAXIS/QAMarket/QAPosition.py#L1045-L1049
gawel/pyquery
0a5f285d8541e24b0aeadc5e928037d748e0327c
pyquery/pyquery.py
python
PyQuery.is_
(self, selector)
return bool(self._filter_only(selector, self))
Returns True if selector matches at least one current element, else False: >>> d = PyQuery('<p class="hello"><span>Hi</span></p><p>Bye</p>') >>> d('p').eq(0).is_('.hello') True >>> d('p').eq(0).is_('span') False >>> d('p').eq(1).is_('.hello') False ..
Returns True if selector matches at least one current element, else False:
[ "Returns", "True", "if", "selector", "matches", "at", "least", "one", "current", "element", "else", "False", ":" ]
def is_(self, selector): """Returns True if selector matches at least one current element, else False: >>> d = PyQuery('<p class="hello"><span>Hi</span></p><p>Bye</p>') >>> d('p').eq(0).is_('.hello') True >>> d('p').eq(0).is_('span') False >>> d('p').eq(1).is_('.hello') False .. """ return bool(self._filter_only(selector, self))
[ "def", "is_", "(", "self", ",", "selector", ")", ":", "return", "bool", "(", "self", ".", "_filter_only", "(", "selector", ",", "self", ")", ")" ]
https://github.com/gawel/pyquery/blob/0a5f285d8541e24b0aeadc5e928037d748e0327c/pyquery/pyquery.py#L617-L633
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/codec/whoosh2.py
python
W2LeafMatcher._skip_to_block
(self, targetfn)
return skipped
[]
def _skip_to_block(self, targetfn): skipped = 0 while self._active and targetfn(): self._next_block(consume=False) skipped += 1 if self._active: self._consume_block() return skipped
[ "def", "_skip_to_block", "(", "self", ",", "targetfn", ")", ":", "skipped", "=", "0", "while", "self", ".", "_active", "and", "targetfn", "(", ")", ":", "self", ".", "_next_block", "(", "consume", "=", "False", ")", "skipped", "+=", "1", "if", "self", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/whoosh/src/whoosh/codec/whoosh2.py#L875-L884
mchristopher/PokemonGo-DesktopMap
ec37575f2776ee7d64456e2a1f6b6b78830b4fe0
app/pywin/Lib/decimal.py
python
_dpower
(xc, xe, yc, ye, p)
return coeff, exp
Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: 10**(p-1) <= c <= 10**p, and (c-1)*10**e < x**y < (c+1)*10**e in other words, c*10**e is an approximation to x**y with p digits of precision, and with an error in c of at most 1. (This is almost, but not quite, the same as the error being < 1ulp: when c == 10**(p-1) we can only guarantee error < 10ulp.) We assume that: x is positive and not equal to 1, and y is nonzero.
Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
[ "Given", "integers", "xc", "xe", "yc", "and", "ye", "representing", "Decimals", "x", "=", "xc", "*", "10", "**", "xe", "and", "y", "=", "yc", "*", "10", "**", "ye", "compute", "x", "**", "y", ".", "Returns", "a", "pair", "of", "integers", "(", "c...
def _dpower(xc, xe, yc, ye, p): """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: 10**(p-1) <= c <= 10**p, and (c-1)*10**e < x**y < (c+1)*10**e in other words, c*10**e is an approximation to x**y with p digits of precision, and with an error in c of at most 1. (This is almost, but not quite, the same as the error being < 1ulp: when c == 10**(p-1) we can only guarantee error < 10ulp.) We assume that: x is positive and not equal to 1, and y is nonzero. """ # Find b such that 10**(b-1) <= |y| <= 10**b b = len(str(abs(yc))) + ye # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point lxc = _dlog(xc, xe, p+b+1) # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) shift = ye-b if shift >= 0: pc = lxc*yc*10**shift else: pc = _div_nearest(lxc*yc, 10**-shift) if pc == 0: # we prefer a result that isn't exactly 1; this makes it # easier to compute a correctly rounded result in __pow__ if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: coeff, exp = 10**(p-1)+1, 1-p else: coeff, exp = 10**p-1, -p else: coeff, exp = _dexp(pc, -(p+1), p+1) coeff = _div_nearest(coeff, 10) exp += 1 return coeff, exp
[ "def", "_dpower", "(", "xc", ",", "xe", ",", "yc", ",", "ye", ",", "p", ")", ":", "# Find b such that 10**(b-1) <= |y| <= 10**b", "b", "=", "len", "(", "str", "(", "abs", "(", "yc", ")", ")", ")", "+", "ye", "# log(x) = lxc*10**(-p-b-1), to p+b+1 places afte...
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/ec37575f2776ee7d64456e2a1f6b6b78830b4fe0/app/pywin/Lib/decimal.py#L5783-L5823
astroML/astroML
f66558232f6d33cb34ecd1bed8a80b9db7ae1c30
astroML/datasets/sdss_specgals.py
python
fetch_great_wall
(data_home=None, download_if_missing=True, xlim=(-375, -175), ylim=(-300, 200), cosmo=None)
return locs
Get the 2D SDSS "Great Wall" distribution, following Cowan et al 2008 Parameters ---------- data_home : optional, default=None Specify another download and cache folder for the datasets. By default all astroML data is stored in '~/astroML_data'. download_if_missing : optional, default=True If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. xlim, ylim : tuples or None the limits in Mpc of the data: default values are the same as that used for the plots in Cowan 2008. If set to None, no cuts will be performed. cosmo : `astropy.cosmology` instance specifying cosmology to use when generating the sample. If not provided, a Flat Lambda CDM model with H0=73.2, Om0=0.27, Tcmb0=0 is used. Returns ------- data : ndarray, shape = (Ngals, 2) grid of projected (x, y) locations of galaxies in Mpc
Get the 2D SDSS "Great Wall" distribution, following Cowan et al 2008
[ "Get", "the", "2D", "SDSS", "Great", "Wall", "distribution", "following", "Cowan", "et", "al", "2008" ]
def fetch_great_wall(data_home=None, download_if_missing=True, xlim=(-375, -175), ylim=(-300, 200), cosmo=None): """Get the 2D SDSS "Great Wall" distribution, following Cowan et al 2008 Parameters ---------- data_home : optional, default=None Specify another download and cache folder for the datasets. By default all astroML data is stored in '~/astroML_data'. download_if_missing : optional, default=True If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. xlim, ylim : tuples or None the limits in Mpc of the data: default values are the same as that used for the plots in Cowan 2008. If set to None, no cuts will be performed. cosmo : `astropy.cosmology` instance specifying cosmology to use when generating the sample. If not provided, a Flat Lambda CDM model with H0=73.2, Om0=0.27, Tcmb0=0 is used. Returns ------- data : ndarray, shape = (Ngals, 2) grid of projected (x, y) locations of galaxies in Mpc """ # local imports so we don't need dependencies for loading module from scipy.interpolate import interp1d # We need some cosmological information to compute the r-band # absolute magnitudes. if cosmo is None: cosmo = FlatLambdaCDM(H0=73.2, Om0=0.27, Tcmb0=0) data = fetch_sdss_specgals(data_home, download_if_missing) # cut to the part of the sky with the "great wall" data = data[(data['dec'] > -7) & (data['dec'] < 7)] data = data[(data['ra'] > 80) & (data['ra'] < 280)] # do a redshift cut, following Cowan et al 2008 z = data['z'] data = data[(z > 0.01) & (z < 0.12)] # first sample the distance modulus on a grid zgrid = np.linspace(min(data['z']), max(data['z']), 100) mugrid = cosmo.distmod(zgrid).value f = interp1d(zgrid, mugrid) mu = f(data['z']) # do an absolute magnitude cut at -20 Mr = data['petroMag_r'] + data['extinction_r'] - mu data = data[Mr < -21] # compute distances in the equatorial plane # first sample comoving distance Dcgrid = cosmo.comoving_distance(zgrid).value f = interp1d(zgrid, Dcgrid) dist = f(data['z']) locs = np.vstack([dist * np.cos(data['ra'] * np.pi / 180.), dist * np.sin(data['ra'] * np.pi / 180.)]).T # cut on x and y limits if specified if xlim is not None: locs = locs[(locs[:, 0] > xlim[0]) & (locs[:, 0] < xlim[1])] if ylim is not None: locs = locs[(locs[:, 1] > ylim[0]) & (locs[:, 1] < ylim[1])] return locs
[ "def", "fetch_great_wall", "(", "data_home", "=", "None", ",", "download_if_missing", "=", "True", ",", "xlim", "=", "(", "-", "375", ",", "-", "175", ")", ",", "ylim", "=", "(", "-", "300", ",", "200", ")", ",", "cosmo", "=", "None", ")", ":", "...
https://github.com/astroML/astroML/blob/f66558232f6d33cb34ecd1bed8a80b9db7ae1c30/astroML/datasets/sdss_specgals.py#L115-L186
readbeyond/aeneas
4d200a050690903b30b3d885b44714fecb23f18a
aeneas/tree.py
python
Tree.children
(self)
return self.__children
Return the list of the direct children of this node. :rtype: list of :class:`~aeneas.tree.Tree`
Return the list of the direct children of this node.
[ "Return", "the", "list", "of", "the", "direct", "children", "of", "this", "node", "." ]
def children(self): """ Return the list of the direct children of this node. :rtype: list of :class:`~aeneas.tree.Tree` """ return self.__children
[ "def", "children", "(", "self", ")", ":", "return", "self", ".", "__children" ]
https://github.com/readbeyond/aeneas/blob/4d200a050690903b30b3d885b44714fecb23f18a/aeneas/tree.py#L114-L120
microsoft/nni
31f11f51249660930824e888af0d4e022823285c
nni/tuner.py
python
Tuner.import_data
(self, data)
Internal API under revising, not recommended for end users.
Internal API under revising, not recommended for end users.
[ "Internal", "API", "under", "revising", "not", "recommended", "for", "end", "users", "." ]
def import_data(self, data): """ Internal API under revising, not recommended for end users. """ # Import additional data for tuning # data: a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' pass
[ "def", "import_data", "(", "self", ",", "data", ")", ":", "# Import additional data for tuning", "# data: a list of dictionarys, each of which has at least two keys, 'parameter' and 'value'", "pass" ]
https://github.com/microsoft/nni/blob/31f11f51249660930824e888af0d4e022823285c/nni/tuner.py#L211-L217
natanielruiz/disrupting-deepfakes
c5b4373a54693139ae4c408b1fcca2de745355e0
cyclegan/models/networks.py
python
PixelDiscriminator.__init__
(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d)
Construct a 1x1 PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer
Construct a 1x1 PatchGAN discriminator
[ "Construct", "a", "1x1", "PatchGAN", "discriminator" ]
def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d): """Construct a 1x1 PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer """ super(PixelDiscriminator, self).__init__() if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d self.net = [ nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias), norm_layer(ndf * 2), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)] self.net = nn.Sequential(*self.net)
[ "def", "__init__", "(", "self", ",", "input_nc", ",", "ndf", "=", "64", ",", "norm_layer", "=", "nn", ".", "BatchNorm2d", ")", ":", "super", "(", "PixelDiscriminator", ",", "self", ")", ".", "__init__", "(", ")", "if", "type", "(", "norm_layer", ")", ...
https://github.com/natanielruiz/disrupting-deepfakes/blob/c5b4373a54693139ae4c408b1fcca2de745355e0/cyclegan/models/networks.py#L589-L611
MycroftAI/mycroft-core
3d963cee402e232174850f36918313e87313fb13
mycroft/skills/intent_services/padatious_service.py
python
PadatiousMatcher._match_level
(self, utterances, limit)
return None
Match intent and make sure a certain level of confidence is reached. Args: utterances (list of tuples): Utterances to parse, originals paired with optional normalized version. limit (float): required confidence level.
Match intent and make sure a certain level of confidence is reached.
[ "Match", "intent", "and", "make", "sure", "a", "certain", "level", "of", "confidence", "is", "reached", "." ]
def _match_level(self, utterances, limit): """Match intent and make sure a certain level of confidence is reached. Args: utterances (list of tuples): Utterances to parse, originals paired with optional normalized version. limit (float): required confidence level. """ if not self.has_result: padatious_intent = None LOG.debug('Padatious Matching confidence > {}'.format(limit)) for utt in utterances: for variant in utt: intent = self.service.calc_intent(variant) if intent: best = padatious_intent.conf \ if padatious_intent else 0.0 if best < intent.conf: padatious_intent = intent padatious_intent.matches['utterance'] = utt[0] if padatious_intent: skill_id = padatious_intent.name.split(':')[0] self.ret = IntentMatch( 'Padatious', padatious_intent.name, padatious_intent.matches, skill_id ) self.conf = padatious_intent.conf self.has_result = True if self.conf and self.conf > limit: return self.ret return None
[ "def", "_match_level", "(", "self", ",", "utterances", ",", "limit", ")", ":", "if", "not", "self", ".", "has_result", ":", "padatious_intent", "=", "None", "LOG", ".", "debug", "(", "'Padatious Matching confidence > {}'", ".", "format", "(", "limit", ")", "...
https://github.com/MycroftAI/mycroft-core/blob/3d963cee402e232174850f36918313e87313fb13/mycroft/skills/intent_services/padatious_service.py#L37-L69
snakemake/snakemake
987282dde8a2db5174414988c134a39ae8836a61
snakemake/rules.py
python
Rule.set_output
(self, *output, **kwoutput)
Add a list of output files. Recursive lists are flattened. After creating the output files, they are checked for duplicates. Arguments output -- the list of output files
Add a list of output files. Recursive lists are flattened.
[ "Add", "a", "list", "of", "output", "files", ".", "Recursive", "lists", "are", "flattened", "." ]
def set_output(self, *output, **kwoutput): """ Add a list of output files. Recursive lists are flattened. After creating the output files, they are checked for duplicates. Arguments output -- the list of output files """ for item in output: self._set_inoutput_item(item, output=True) for name, item in kwoutput.items(): self._set_inoutput_item(item, output=True, name=name) for item in self.output: if self.dynamic_output and item not in self.dynamic_output: raise SyntaxError( "A rule with dynamic output may not define any " "non-dynamic output files." ) self.register_wildcards(item.get_wildcard_names()) # Check output file name list for duplicates self.check_output_duplicates() self.check_caching()
[ "def", "set_output", "(", "self", ",", "*", "output", ",", "*", "*", "kwoutput", ")", ":", "for", "item", "in", "output", ":", "self", ".", "_set_inoutput_item", "(", "item", ",", "output", "=", "True", ")", "for", "name", ",", "item", "in", "kwoutpu...
https://github.com/snakemake/snakemake/blob/987282dde8a2db5174414988c134a39ae8836a61/snakemake/rules.py#L401-L424
Yinzo/SmartQQBot
450ebcaecabdcd8a14532d22ac109bc9f6c75c9b
src/smart_qq_bot/handler.py
python
MessageObserver.handle_msg_list
(self, msg_list)
:type msg_list: list or tuple
:type msg_list: list or tuple
[ ":", "type", "msg_list", ":", "list", "or", "tuple" ]
def handle_msg_list(self, msg_list): """ :type msg_list: list or tuple """ for msg in msg_list: self._handle_one(msg)
[ "def", "handle_msg_list", "(", "self", ",", "msg_list", ")", ":", "for", "msg", "in", "msg_list", ":", "self", ".", "_handle_one", "(", "msg", ")" ]
https://github.com/Yinzo/SmartQQBot/blob/450ebcaecabdcd8a14532d22ac109bc9f6c75c9b/src/smart_qq_bot/handler.py#L157-L162
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/contrib/admin/util.py
python
reverse_field_path
(model, path)
return (parent, LOOKUP_SEP.join(reversed_path))
Create a reversed field path. E.g. Given (Order, "user__groups"), return (Group, "user__order"). Final field must be a related model, not a data field.
Create a reversed field path.
[ "Create", "a", "reversed", "field", "path", "." ]
def reverse_field_path(model, path): """ Create a reversed field path. E.g. Given (Order, "user__groups"), return (Group, "user__order"). Final field must be a related model, not a data field. """ reversed_path = [] parent = model pieces = path.split(LOOKUP_SEP) for piece in pieces: field, model, direct, m2m = parent._meta.get_field_by_name(piece) # skip trailing data field if extant: if len(reversed_path) == len(pieces)-1: # final iteration try: get_model_from_relation(field) except NotRelationField: break if direct: related_name = field.related_query_name() parent = field.rel.to else: related_name = field.field.name parent = field.model reversed_path.insert(0, related_name) return (parent, LOOKUP_SEP.join(reversed_path))
[ "def", "reverse_field_path", "(", "model", ",", "path", ")", ":", "reversed_path", "=", "[", "]", "parent", "=", "model", "pieces", "=", "path", ".", "split", "(", "LOOKUP_SEP", ")", "for", "piece", "in", "pieces", ":", "field", ",", "model", ",", "dir...
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/contrib/admin/util.py#L379-L406
yaohungt/Gated-Spatio-Temporal-Energy-Graph
bc8f44b3d95cbfe3032bb3612daa07b4d9cd4298
train.py
python
AverageMeter.reset
(self)
[]
def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0
[ "def", "reset", "(", "self", ")", ":", "self", ".", "val", "=", "0", "self", ".", "avg", "=", "0", "self", ".", "sum", "=", "0", "self", ".", "count", "=", "0" ]
https://github.com/yaohungt/Gated-Spatio-Temporal-Energy-Graph/blob/bc8f44b3d95cbfe3032bb3612daa07b4d9cd4298/train.py#L17-L21
DataBiosphere/toil
2e148eee2114ece8dcc3ec8a83f36333266ece0d
src/toil/wdl/versions/draft2.py
python
AnalyzeDraft2WDL.parse_workflow_call_body_declarations
(self, i)
return declaration_array
Have not seen this used, so expects to return "[]". :param i: :return:
Have not seen this used, so expects to return "[]".
[ "Have", "not", "seen", "this", "used", "so", "expects", "to", "return", "[]", "." ]
def parse_workflow_call_body_declarations(self, i): """ Have not seen this used, so expects to return "[]". :param i: :return: """ declaration_array = [] if isinstance(i, wdl_parser.Terminal): declaration_array = [i.source_string] elif isinstance(i, wdl_parser.Ast): raise NotImplementedError elif isinstance(i, wdl_parser.AstList): for ast in i: declaration_array.append(self.parse_declaration(ast)) # have not seen this used so raise to check if declaration_array: raise NotImplementedError return declaration_array
[ "def", "parse_workflow_call_body_declarations", "(", "self", ",", "i", ")", ":", "declaration_array", "=", "[", "]", "if", "isinstance", "(", "i", ",", "wdl_parser", ".", "Terminal", ")", ":", "declaration_array", "=", "[", "i", ".", "source_string", "]", "e...
https://github.com/DataBiosphere/toil/blob/2e148eee2114ece8dcc3ec8a83f36333266ece0d/src/toil/wdl/versions/draft2.py#L879-L899
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/campaign_bid_modifier_service/client.py
python
CampaignBidModifierServiceClient.parse_common_folder_path
(path: str)
return m.groupdict() if m else {}
Parse a folder path into its component segments.
Parse a folder path into its component segments.
[ "Parse", "a", "folder", "path", "into", "its", "component", "segments", "." ]
def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P<folder>.+?)$", path) return m.groupdict() if m else {}
[ "def", "parse_common_folder_path", "(", "path", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "m", "=", "re", ".", "match", "(", "r\"^folders/(?P<folder>.+?)$\"", ",", "path", ")", "return", "m", ".", "groupdict", "(", ")", "if", "m"...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/campaign_bid_modifier_service/client.py#L219-L222
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_12/paramiko/util.py
python
get_logger
(name)
return l
[]
def get_logger(name): l = logging.getLogger(name) l.addFilter(_pfilter) return l
[ "def", "get_logger", "(", "name", ")", ":", "l", "=", "logging", ".", "getLogger", "(", "name", ")", "l", ".", "addFilter", "(", "_pfilter", ")", "return", "l" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_12/paramiko/util.py#L269-L272