_id
stringlengths
98
184
text
stringlengths
91
10.9k
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/state.py#L107-L120
def unfinished(cls): """ """ return [ cls.NONE, cls.SCHEDULED, cls.QUEUED, cls.RUNNING, cls.SHUTDOWN, cls.UP_FOR_RETRY, cls.UP_FOR_RESCHEDULE ]
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/internal/distribution_tensor_coercible.py#L71-L128
def _value(self, dtype=None, name=None, as_ref=False): # pylint: disable=g-doc-args """ """ # pylint: disable=protected-access if as_ref: raise NotImplementedError( 'Cannot convert a `Distribution` to a reference ' '(e.g., `tf.Variable`).') if self._concrete_value is None: if self._c...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/hdfs_hook.py#L57-L98
def get_conn(self): """ """ # When using HAClient, proxy_user must be the same, so is ok to always # take the first. effective_user = self.proxy_user autoconfig = self.autoconfig use_sasl = configuration.conf.get('core', 'security') == 'kerberos' ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/aws_lambda_hook.py#L53-L68
def invoke_lambda(self, payload): """ """ awslambda_conn = self.get_conn() response = awslambda_conn.invoke( FunctionName=self.function_name, InvocationType=self.invocation_type, LogType=self.log_type, Payload=payload, ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L602-L606
def _replace_at_index(x, index, replacement): """""" x_new = tf.concat([x[:index], tf.expand_dims(replacement, axis=0), x[(index + 1):]], axis=0) return x_new
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/datasets/sbu.py#L87-L110
def download(self): """""" import tarfile if self._check_integrity(): print('Files already downloaded and verified') return download_url(self.url, self.root, self.filename, self.md5_checksum) # Extract file with tarfile.open(os.path.join(self.ro...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/log/s3_task_handler.py#L146-L170
def s3_write(self, log, remote_log_location, append=True): """ """ if append and self.s3_log_exists(remote_log_location): old_log = self.s3_read(remote_log_location) log = '\n'.join([old_log, log]) if old_log else log try: self.hook.load_stri...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/transformed_kernel.py#L230-L273
def one_step(self, current_state, previous_kernel_results): """ """ with tf.compat.v1.name_scope( name=mcmc_util.make_name(self.name, 'transformed_kernel', 'one_step'), values=[previous_kernel_results]): transformed_next_state, kernel_results = self._inner_kernel.one_step( pr...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/opsgenie_alert_operator.py#L126-L131
def execute(self, context): """ """ self.hook = OpsgenieAlertHook(self.opsgenie_conn_id) self.hook.execute(self._build_opsgenie_payload())
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/hmc.py#L1052-L1145
def _compute_log_acceptance_correction(current_momentums, proposed_momentums, independent_chain_ndims, name=None): """ """ with tf.compat.v1.name_scope( name, 'compute_log_acceptance_correcti...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_vision_hook.py#L298-L307
def delete_product(self, location, product_id, project_id=None, retry=None, timeout=None, metadata=None): """ """ client = self.get_conn() name = ProductSearchClient.product_path(project_id, location, product_id) self.log.info('Deleting ProductSet: %s', name) cli...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L426-L545
def bracket(value_and_gradients_function, search_interval, f_lim, max_iterations, expansion_param=5.0): """ """ already_stopped = search_interval.failed | search_interval.converged # If the slope at right end point is positive, step B1 in [2], then the given # ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/mysql_to_gcs.py#L290-L310
def _get_col_type_dict(self): """ """ schema = [] if isinstance(self.schema, string_types): schema = json.loads(self.schema) elif isinstance(self.schema, list): schema = self.schema elif self.schema is not None: self.log.warn('...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/distribution_layer.py#L754-L768
def _eval_all_one_hot(fn, dist, name=None): """""" with tf.compat.v1.name_scope(name, 'eval_all_one_hot'): event_size = dist.event_shape_tensor()[-1] batch_ndims = tf.size(input=dist.batch_shape_tensor()) # Reshape `eye(d)` to: `[d] + [1]*batch_ndims + [d]`. x = tf.reshape( tf.eye(event_size...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/interceptor.py#L96-L172
def get_next_interceptor(): """ """ try: interceptor = _interceptor_stack.stack.pop() yield interceptor finally: _interceptor_stack.stack.append(interceptor)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/azure_fileshare_hook.py#L64-L81
def check_for_file(self, share_name, directory_name, file_name, **kwargs): """ """ return self.connection.exists(share_name, directory_name, file_name, **kwargs)
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs_utils.py#L309-L322
def _check_convergence(current_position, next_position, current_objective, next_objective, next_gradient, grad_tolerance, f_relative_tolerance, x_tolerance): ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/auth/backends/password_auth.py#L107-L132
def authenticate(session, username, password): """ """ if not username or not password: raise AuthenticationError() user = session.query(PasswordUser).filter( PasswordUser.username == username).first() if not user: raise AuthenticationError() if not user.authentic...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/linear_gaussian_ssm.py#L1729-L1732
def _propagate_cov(cov, linop, dist): """""" # For linop A and input cov P, returns `A P A' + dist.cov()` return linop.matmul(linop.matmul(cov), adjoint_arg=True) + dist.covariance()
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/hmc.py#L556-L564
def bootstrap_results(self, init_state): """""" kernel_results = self._impl.bootstrap_results(init_state) if self.step_size_update_fn is not None: step_size_assign = self.step_size_update_fn(self.step_size, None) # pylint: disable=not-callable kernel_results = kernel_results._replace( ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/bayesian_neural_network.py#L190-L210
def build_fake_data(num_examples=10): """""" class Dummy(object): pass num_examples = 10 mnist_data = Dummy() mnist_data.train = Dummy() mnist_data.train.images = np.float32(np.random.randn( num_examples, *IMAGE_SHAPE)) mnist_data.train.labels = np.int32(np.random.permutation( np.arange(...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/S3_hook.py#L48-L60
def check_for_bucket(self, bucket_name): """ """ try: self.get_conn().head_bucket(Bucket=bucket_name) return True except ClientError as e: self.log.info(e.response["Error"]["Message"]) return False
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/disentangled_vae.py#L846-L866
def sample_static_prior(self, samples, batch_size, fixed=False): """ """ dist = self.static_prior() if fixed: # in either case, shape is (samples, batch, latent) sample = dist.sample((samples, 1)) + tf.zeros([batch_size, 1]) else: sample = dist.sample((samples, batch_size)) return s...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/deep_exponential_family.py#L178-L231
def load_nips2011_papers(path): """ """ path = os.path.expanduser(path) filename = "NIPS_1987-2015.csv" filepath = os.path.join(path, filename) if not os.path.exists(filepath): url = ("https://archive.ics.uci.edu/ml/machine-learning-databases/" "00371/NIPS_1987-2015.csv") if not tf.io.gfi...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L1705-L1779
def insert_all(self, project_id, dataset_id, table_id, rows, ignore_unknown_values=False, skip_invalid_rows=False, fail_on_error=False): """ """ dataset_project_id = project_id if project_id else self.project_id body = { "rows"...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/text_messages_hmc.py#L64-L153
def benchmark_text_messages_hmc( num_results=int(3e3), num_burnin_steps=int(3e3), num_leapfrog_steps=3): """""" if not tf.executing_eagerly(): tf.compat.v1.reset_default_graph() # Build a static, pretend dataset. count_data = tf.cast( tf.concat( [tfd.Poisson(rate=15.).sample(43...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/transformed_distribution.py#L415-L430
def _finish_log_prob_for_one_fiber(self, y, x, ildj, event_ndims, **distribution_kwargs): """""" x = self._maybe_rotate_dims(x, rotate_right=True) log_prob = self.distribution.log_prob(x, **distribution_kwargs) if self._is_maybe_event_override: log_prob = tf.re...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L95-L122
def get_pandas_df(self, sql, parameters=None, dialect=None): """ """ private_key = self._get_field('key_path', None) or self._get_field('keyfile_dict', None) if dialect is None: dialect = 'legacy' if self.use_legacy_sql else 'standard' return read_gbq(sql, ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_mlengine_hook.py#L165-L183
def create_version(self, project_id, model_name, version_spec): """ """ parent_name = 'projects/{}/models/{}'.format(project_id, model_name) create_request = self._mlengine.projects().models().versions().create( parent=parent_name, body=version_spec) response...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/_vendor/nvd3/NVD3Chart.py#L474-L485
def buildcontent(self): """ """ self.buildcontainer() # if the subclass has a method buildjs this method will be # called instead of the method defined here # when this subclass method is entered it does call # the method buildjschart defined here self.bui...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/internal/util.py#L255-L293
def _maybe_expand_trailing_dim(observed_time_series_tensor): """ """ with tf.compat.v1.name_scope( 'maybe_expand_trailing_dim', values=[observed_time_series_tensor]): if (observed_time_series_tensor.shape.ndims is not None and tf.compat.dimension_value( observed_time_series_tensor.s...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_container_hook.py#L111-L129
def _append_label(cluster_proto, key, val): """ """ val = val.replace('.', '-').replace('+', '-') cluster_proto.resource_labels.update({key: val}) return cluster_proto
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/log/gcs_task_handler.py#L166-L177
def parse_gcs_url(gsurl): """ """ parsed_url = urlparse(gsurl) if not parsed_url.netloc: raise AirflowException('Please provide a bucket name') else: bucket = parsed_url.netloc blob = parsed_url.path.strip('/') return bucke...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/nuts.py#L457-L466
def _embed_no_none_gradient_check(value_and_gradients_fn): """""" @functools.wraps(value_and_gradients_fn) def func_wrapped(*args, **kwargs): """Wrapped function which checks for None gradients.""" value, grads = value_and_gradients_fn(*args, **kwargs) if any(grad is None for grad in grads): rai...
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L255-L340
def pad(img, padding, fill=0, padding_mode='constant'): """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) if not isinstance(padding, (numbers.Number, tuple)): raise TypeError('Got inappropriate padding arg') if not isinstance(fill, ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/dense_variational.py#L193-L213
def compute_output_shape(self, input_shape): """ """ input_shape = tf.TensorShape(input_shape) input_shape = input_shape.with_rank_at_least(2) if tf.compat.dimension_value(input_shape[-1]) is None: raise ValueError( 'The innermost dimension of `input_shape` must be defined, ' ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/glm/family.py#L174-L179
def _name_scope(self, name=None, default_name=None, values=None): """""" with tf.compat.v1.name_scope(self.name): with tf.compat.v1.name_scope( name, default_name, values=values or []) as scope: yield scope
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/diagnostic.py#L35-L143
def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, name=None): """ """ states_was_list = _is_list_like(states) # Convert all args to lists. if not states_was_list: states = [states] filter_beyond_...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/disentangled_vae.py#L787-L844
def reconstruct(self, inputs, samples=1, sample_static=False, sample_dynamic=False, swap_static=False, swap_dynamic=False, fix_static=False, fix_dynamic=False): """ """ batch_size = tf.shape(input=inputs)[-5] length = len(tf.unstack(inputs, axis=-4)) # hack for graph...
https://github.com/asciimoo/searx/blob/a84caa22cf947e973c10aa968d35fb2bdda6d048/searx/poolrequests.py#L90-L128
def request(method, url, **kwargs): """""" time_before_request = time() # session start session = SessionSinglePool() # proxies kwargs['proxies'] = settings['outgoing'].get('proxies') or None # timeout if 'timeout' in kwargs: timeout = kwargs['timeout'] else: timeo...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/models/bayesian_resnet.py#L25-L92
def bayesian_resnet(input_shape, num_classes=10, kernel_posterior_scale_mean=-9.0, kernel_posterior_scale_stddev=0.1, kernel_posterior_scale_constraint=0.2): """ """ filters = [64, 128, 256, 512] kernels = [3, 3, 3, 3] strides = ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L832-L844
def _resolve_parameters(dim, reflection, expansion, contraction, shrinkage, dtype): """""" dim = tf.cast(dim, dtype=dtype) reflection = 1. if reflection is None else reflection expansion = (1....
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/glm/fisher_scoring.py#L517-L620
def prepare_args(model_matrix, response, model_coefficients, predicted_linear_response, offset, name=None): """ """ graph_deps = [model_matrix, response, model_coefficients, predicted_linear_response, offset] wi...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/lkj.py#L47-L56
def _uniform_unit_norm(dimension, shape, dtype, seed): """""" # This works because the Gaussian distribution is spherically symmetric. # raw shape: shape + [dimension] raw = normal.Normal( loc=dtype_util.as_numpy_dtype(dtype)(0), scale=dtype_util.as_numpy_dtype(dtype)(1)).sample( tf.concat...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/forecast.py#L172-L362
def forecast(model, observed_time_series, parameter_samples, num_steps_forecast): """ """ with tf.compat.v1.name_scope( 'forecast', values=[observed_time_series, parameter_samples, num_steps_forecast]): [ observed_time_series, mask ] = s...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcs_hook.py#L447-L475
def insert_bucket_acl(self, bucket_name, entity, role, user_project=None): """ """ self.log.info('Creating a new ACL entry in bucket: %s', bucket_name) client = self.get_conn() bucket = client.bucket(bucket_name=bucket_name) bucket.acl.reload() bucket.acl...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/dagrun.py#L242-L329
def update_state(self, session=None): """ """ dag = self.get_dag() tis = self.get_task_instances(session=session) self.log.debug("Updating state for %s considering %s task(s)", self, len(tis)) for ti in list(tis): # skip in db? if ti.st...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/macros/__init__.py#L28-L46
def ds_add(ds, days): """ """ ds = datetime.strptime(ds, '%Y-%m-%d') if days: ds = ds + timedelta(days) return ds.isoformat()[:10]
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/utils.py#L79-L185
def generate_pages(current_page, num_of_pages, search=None, showPaused=None, window=7): """ """ void_link = 'javascript:void(0)' first_node = Markup("""<li class="paginate_button {disabled}" id="dags_first"> <a href="{href_link}" aria-controls="dags" data-dt-idx="0" tabindex...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/linear_gaussian_ssm.py#L1097-L1145
def latents_to_observations(self, latent_means, latent_covs): """ """ with tf.name_scope("latents_to_observations"): pushforward_latents_step = build_pushforward_latents_step( self.get_observation_matrix_for_timestep, self.get_observation_noise_for_timestep) latent_means =...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/nest_util.py#L98-L113
def _nested_convert_to_tensor(struct, dtype=None, name=None): """""" if dtype is not None or not tf.nest.is_nested(struct): return tf.convert_to_tensor(struct, dtype=dtype) if _maybe_convertible_to_tensor(struct): try: # Try converting the structure wholesale. return tf.convert_to_tensor(valu...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/linear_gaussian_ssm.py#L1577-L1619
def build_kalman_cov_step(get_transition_matrix_for_timestep, get_transition_noise_for_timestep, get_observation_matrix_for_timestep, get_observation_noise_for_timestep): """ """ def cov_step(previous_covs, t): """Single step of pr...
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L468-L499
def five_crop(img, size): """ """ if isinstance(size, numbers.Number): size = (int(size), int(size)) else: assert len(size) == 2, "Please provide only two dimensions (h, w) for size." w, h = img.size crop_h, crop_w = size if crop_w > w or crop_h > h: raise ValueError...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/replica_exchange_mc.py#L569-L575
def _get_field(kernel_results, field_name): """""" if hasattr(kernel_results, field_name): return getattr(kernel_results, field_name) if hasattr(kernel_results, 'accepted_results'): return getattr(kernel_results.accepted_results, field_name) raise TypeError('Cannot extract %s from %s' % (field_name, ker...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L550-L585
def jeffreys(logu, name=None): """ """ with tf.compat.v1.name_scope(name, "jeffreys", [logu]): logu = tf.convert_to_tensor(value=logu, name="logu") return 0.5 * tf.math.expm1(logu) * logu
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/dagrun.py#L115-L160
def find(dag_id=None, run_id=None, execution_date=None, state=None, external_trigger=None, no_backfills=False, session=None): """ """ DR = DagRun qry = session.query(DR) if dag_id: qry = qry.filter(DR.dag_id == dag_id) if ru...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/structural_time_series.py#L96-L109
def batch_shape_tensor(self): """ """ batch_shape = tf.constant([], dtype=tf.int32) for param in self.parameters: batch_shape = tf.broadcast_dynamic_shape( batch_shape, param.prior.batch_shape_tensor()) return batch_shape
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/nelder_mead.py#L847-L880
def _evaluate_objective_multiple(objective_function, arg_batch, batch_evaluate_objective): """ """ n_points = tf.shape(input=arg_batch)[0] if batch_evaluate_objective: return objective_function(arg_batch), n_points return tf.map_fn(objective_function, arg_batch), n_points
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/distribution_layer.py#L586-L594
def params_size(event_size, num_components, name=None): """""" with tf.compat.v1.name_scope( name, 'CategoricalMixtureOfOneHotCategorical_params_size', [event_size, num_components]): return MixtureSameFamily.params_size( num_components, OneHotCategorical.params_size(eve...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/models/bayesian_resnet.py#L95-L121
def _resnet_block(x, filters, kernel, stride, kernel_posterior_fn): """""" x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.Activation('relu')(x) if stride != 1 or filters != x.shape[1]: shortcut = _projection_shortcut(x, filters, stride, kernel_posterior_fn) else: shortcut = x x = ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/half_cauchy.py#L36-L63
def check_arg_in_support(f): """ """ @functools.wraps(f) def _check_arg_and_apply_f(*args, **kwargs): dist = args[0] x = args[1] with tf.control_dependencies([ assert_util.assert_greater_equal( x, dist.loc, message="x is not in the support of the distribution") ] if dist.vali...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L620-L661
def modified_gan(logu, self_normalized=False, name=None): """ """ with tf.compat.v1.name_scope(name, "chi_square", [logu]): logu = tf.convert_to_tensor(value=logu, name="logu") y = tf.nn.softplus(logu) - logu if self_normalized: y += 0.5 * tf.math.expm1(logu) return y
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L805-L817
def _insert_back_keep_dims(x, axis): """ """ for i in sorted(axis): x = tf.expand_dims(x, axis=i) return x
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/glm/family.py#L137-L161
def log_prob(self, response, predicted_linear_response, name=None): """ """ with self._name_scope( name, 'log_prob', [response, predicted_linear_response]): dtype = dtype_util.common_dtype([response, predicted_linear_response]) response = tf.convert_to_tensor( value=response, ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/_vendor/nvd3/NVD3Chart.py#L363-L371
def buildhtml(self): """ """ self.buildcontent() self.content = self.htmlcontent self.htmlcontent = self.template_page_nvd3.render(chart=self)
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L626-L723
def quantiles(x, num_quantiles, axis=None, interpolation=None, keep_dims=False, validate_args=False, name=None): """ """ with tf.compat.v1.name_scope( name, 'quantiles', values=[x, num_quantiles, axis]): x = tf.convert_...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L39-L47
def val_where(cond, tval, fval): """""" if isinstance(tval, tf.Tensor): return tf.where(cond, tval, fval) elif isinstance(tval, tuple): cls = type(tval) return cls(*(val_where(cond, t, f) for t, f in zip(tval, fval))) else: raise Exception(TypeError)
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/sample_stats.py#L602-L638
def variance(x, sample_axis=0, keepdims=False, name=None): """ """ with tf.compat.v1.name_scope(name, 'variance', values=[x, sample_axis]): return covariance( x, y=None, sample_axis=sample_axis, event_axis=None, keepdims=keepdims)
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/bayesian_neural_network.py#L161-L187
def build_input_pipeline(mnist_data, batch_size, heldout_size): """""" # Build an iterator over training batches. training_dataset = tf.data.Dataset.from_tensor_slices( (mnist_data.train.images, np.int32(mnist_data.train.labels))) training_batches = training_dataset.shuffle( 50000, reshuffle_each_i...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/program_transformations.py#L226-L246
def _get_function_inputs(f, src_kwargs): """ """ if hasattr(f, "_func"): # functions returned by tf.make_template f = f._func # pylint: disable=protected-access try: # getargspec was deprecated in Python 3.6 argspec = inspect.getfullargspec(f) except AttributeError: argspec = inspect.getargspe...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_bigtable_hook.py#L199-L214
def delete_table(self, instance_id, table_id, project_id=None): """ """ table = self.get_instance(instance_id=instance_id, project_id=project_id).table(table_id=table_id) table.delete()
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/sample_stats.py#L552-L599
def stddev(x, sample_axis=0, keepdims=False, name=None): """ """ with tf.compat.v1.name_scope(name, 'stddev', values=[x, sample_axis]): return tf.sqrt(variance(x, sample_axis=sample_axis, keepdims=keepdims))
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/aws_firehose_hook.py#L44-L56
def put_records(self, records): """ """ firehose_conn = self.get_conn() response = firehose_conn.put_record_batch( DeliveryStreamName=self.delivery_stream, Records=records ) return response
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/generated_random_variables.py#L148-L175
def _make_random_variable(distribution_cls): """""" @interceptable @functools.wraps(distribution_cls, assigned=('__module__', '__name__')) @docstring_util.expand_docstring( cls=distribution_cls.__name__, doc=inspect.cleandoc(distribution_cls.__init__.__doc__ or '')) def func(*args, **kwargs): ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L132-L139
def name(dtype): """""" dtype = tf.as_dtype(dtype) if hasattr(dtype, 'name'): return dtype.name if hasattr(dtype, '__name__'): return dtype.__name__ return str(dtype)
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L726-L787
def _get_static_ndims(x, expect_static=False, expect_ndims=None, expect_ndims_no_more_than=None, expect_ndims_at_least=None): """ """ ndims = x.shape.ndims if ndims is None: shape_const = tf.get_static_value(tf.shape(inp...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sqoop_hook.py#L202-L233
def import_table(self, table, target_dir=None, append=False, file_type="text", columns=None, split_by=None, where=None, direct=False, driver=None, extra_import_options=None): """ """ cmd = self._import_cmd(target_dir, append, file_type, split_by...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/sprites_dataset.py#L140-L149
def create_character(skin, hair, top, pants): """""" dtype = skin.dtype hair_mask = tf.cast(hair[..., -1:] <= 0, dtype) top_mask = tf.cast(top[..., -1:] <= 0, dtype) pants_mask = tf.cast(pants[..., -1:] <= 0, dtype) char = (skin * hair_mask) + hair char = (char * top_mask) + top char = (char * pants_mas...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/util.py#L440-L474
def enable_store_parameters_in_results(kernel): """ """ kernel_stack = [] while hasattr(kernel, 'parameters') and 'inner_kernel' in kernel.parameters: kernel_stack.append(kernel) kernel = kernel.parameters['inner_kernel'] def _recreate_kernel(kernel, parameters): new_parameters = kernel.parameter...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L1526-L1666
def _execute_helper(self): """ """ self.executor.start() self.log.info("Resetting orphaned tasks for active dag runs") self.reset_state_for_orphaned_tasks() # Start after resetting orphaned tasks to avoid stressing out DB. self.processor_agent.start() ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/views.py#L2492-L2500
def get_count_query(self): """ """ return ( super().get_count_query() .filter(models.DagModel.is_active) .filter(~models.DagModel.is_subdag) )
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/lbfgs.py#L277-L366
def _get_search_direction(state): """ """ # The number of correction pairs that have been collected so far. num_elements = tf.minimum( state.num_iterations, distribution_util.prefer_static_shape(state.position_deltas)[0]) def _two_loop_algorithm(): """L-BFGS two-loop algorithm.""" # Corre...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/logistic_regression.py#L89-L131
def visualize_decision(features, labels, true_w_b, candidate_w_bs, fname): """ """ fig = figure.Figure(figsize=(6, 6)) canvas = backend_agg.FigureCanvasAgg(fig) ax = fig.add_subplot(1, 1, 1) ax.scatter(features[:, 0], features[:, 1], c=np.float32(labels[:, 0]), cmap=cm.get_cmap("bi...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/wasb_hook.py#L137-L151
def read_file(self, container_name, blob_name, **kwargs): """ """ return self.connection.get_blob_to_text(container_name, blob_name, **kwargs).content
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L572-L639
def move_dimension(x, source_idx, dest_idx): """ """ ndims = prefer_static_rank(x) dtype = dtype_util.common_dtype([source_idx, dest_idx], preferred_dtype=tf.int32) source_idx = tf.convert_to_tensor(value=source_idx, dtype=dtype) dest_idx = tf.convert_to_tensor(value=dest_i...
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/datasets/utils.py#L93-L112
def list_dir(root, prefix=False): """ """ root = os.path.expanduser(root) directories = list( filter( lambda p: os.path.isdir(os.path.join(root, p)), os.listdir(root) ) ) if prefix is True: directories = [os.path.join(root, d) for d in directories...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/tensorshape_util.py#L119-L141
def constant_value_as_shape(tensor): # pylint: disable=invalid-name """ """ shape = tf.get_static_value(tensor) if shape is not None: return [None if dim == -1 else dim for dim in shape] return tensor_util.constant_value_as_shape(tensor)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/aws_glue_catalog_hook.py#L139-L152
def get_table_location(self, database_name, table_name): """ """ table = self.get_table(database_name, table_name) return table['StorageDescriptor']['Location']
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/interpolation.py#L893-L927
def _make_expand_x_fn_for_batch_interpolation(y_ref, axis): """""" # This expansion is to help x broadcast with `y`, the output. # In the batch case, the output shape is going to be # Broadcast(y_ref.shape[:axis], x.shape[:-1]) + # x.shape[-1:] + y_ref.shape[axis+1:] # Recall we made axis non-negative...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/differential_evolution.py#L674-L709
def _get_mutants(population, population_size, mixing_indices, differential_weight): """ """ mixing_indices = tf.reshape(mixing_indices, [-1]) weights = tf.stack([1.0, differential_weight, -differential_weight]) def _mutant_part(population_part): donors = ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/task_runner/cgroup_task_runner.py#L197-L210
def _get_cgroup_names(): """ """ with open("/proc/self/cgroup") as f: lines = f.readlines() d = {} for line in lines: line_split = line.rstrip().split(":") subsystem = line_split[1] group_name = line_spl...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/prefer_static.py#L120-L151
def cond(pred, true_fn=None, false_fn=None, name=None): """ """ if not callable(true_fn): raise TypeError('`true_fn` must be callable.') if not callable(false_fn): raise TypeError('`false_fn` must be callable.') pred_value = _get_static_predicate(pred) if pred_value is not None: if pred_value: ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/sprites_dataset.py#L113-L118
def read_image(filepath): """""" im_bytes = tf.io.read_file(filepath) im = tf.image.decode_image(im_bytes, channels=CHANNELS) im = tf.image.convert_image_dtype(im, tf.float32) return im
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/positive_semidefinite_kernels/internal/util.py#L68-L86
def sum_rightmost_ndims_preserving_shape(x, ndims): """ """ x = tf.convert_to_tensor(value=x) if x.shape.ndims is not None: axes = tf.range(x.shape.ndims - ndims, x.shape.ndims) else: axes = tf.range(tf.rank(x) - ndims, tf.rank(x)) return tf.reduce_sum(input_tensor=x, axis=axes)
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs_utils.py#L47-L91
def get_initial_state_args(value_and_gradients_function, initial_position, grad_tolerance, control_inputs=None): """ """ if control_inputs: with tf.control_dependencies(control_inputs): f0, df0 = value_and_gradients_functio...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L920-L928
def _print_stat(self): """ """ if ((timezone.utcnow() - self.last_stat_print_time).total_seconds() > self.print_stats_interval): if len(self._file_paths) > 0: self._log_file_processing_stats(self._file_paths) self.last_stat_print_t...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/security.py#L246-L266
def get_accessible_dag_ids(self, username=None): """ """ if not username: username = g.user if username.is_anonymous or 'Public' in username.roles: # return an empty set if the role is public return set() roles = {role.name for role ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/internal/slice_sampler_utils.py#L26-L87
def _left_doubling_increments(batch_shape, max_doublings, step_size, seed=None, name=None): """ """ with tf.compat.v1.name_scope(name, 'left_doubling_increments', [batch_shape, max_doublings, step_size]): step_size = tf.convert_to_tensor(value=step...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L342-L417
def _launch_process(result_queue, file_path, pickle_dags, dag_id_white_list, thread_name, zombies): """ """ def helper(): # This helper runs in the newly c...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/prefer_static.py#L154-L179
def case(pred_fn_pairs, default=None, exclusive=False, name='smart_case'): """ """ return control_flow_ops._case_helper( # pylint: disable=protected-access cond, pred_fn_pairs, default, exclusive, name, allow_python_preds=True)