當前位置: 首頁>>代碼示例>>Python>>正文


Python app.UsageError方法代碼示例

本文整理匯總了Python中absl.app.UsageError方法的典型用法代碼示例。如果您正苦於以下問題:Python app.UsageError方法的具體用法?Python app.UsageError怎麽用?Python app.UsageError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在absl.app的用法示例。


在下文中一共展示了app.UsageError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def main(_):
  if len(sys.argv) < 3:
    raise app.UsageError('Must pass at least two arguments, font file or font'
                         ' dir to diff')

  font1 = sys.argv[1]
  font2 = sys.argv[2]
  dirs = os.path.isdir(font1) and os.path.isdir(font2)
  files = os.path.isfile(font1) and os.path.isfile(font2)

  if not dirs and not files:
    print('%s and %s must both point to directories or font files' % (
        font1, font2))
    sys.exit(1)

  if dirs:
    CompareDirs(font1, font2)

  if files:
    CompareFiles(font1, font2) 
開發者ID:googlefonts,項目名稱:gftools,代碼行數:22,代碼來源:gftools-compare-font.py

示例2: validate_args

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def validate_args(argv):
  """Validates the input arguments. Raises a UsageError if invalid."""
  valid_commands = ["up", "down", "print", "reload"]
  error = ""
  if len(argv) < 2:
    error = ("Command not provided. "
             "Command must be one of %s" % valid_commands)
  elif argv[1] not in valid_commands:
    error = "Command must be one of %s" % valid_commands

  if len(argv) > 3:
    print("Too many arguments.")

  if len(argv) == 3:
    valid_targets = ["trainer", "decoder", "tensorboard", "all"]
    if argv[2] not in valid_targets:
      error = "Target must be one of %s" % valid_targets

  if error:
    raise app.UsageError(error) 
開發者ID:tensorflow,項目名稱:lingvo,代碼行數:22,代碼來源:gke_launch.py

示例3: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  # Datasets.
  preprocessed_train_dataset, preprocessed_test_dataset = (
      _load_and_preprocess_datasets())

  # Train and Evaluate Model.
  model = _train_and_evaluate(
      preprocessed_train_dataset,
      preprocessed_test_dataset,
      epochs=FLAGS.epochs)

  # Save Model.
  _save(model, FLAGS.path_to_save_model_checkpoint) 
開發者ID:tensorflow,項目名稱:federated,代碼行數:18,代碼來源:train_emnist_classifier_model.py

示例4: tokenize

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def tokenize(ds, dataset_name):
  """Tokenizes a line into words with alphanum characters."""

  def extract_strings(example):
    if dataset_name == 'shakespeare':
      return tf.expand_dims(example['snippets'], 0)
    elif dataset_name == 'stackoverflow':
      return example['tokens']
    else:
      raise app.UsageError('Dataset not supported: ', dataset_name)

  def tokenize_line(line):
    return tf.data.Dataset.from_tensor_slices(tokenizer.tokenize(line)[0])

  def mask_all_symbolic_words(word):
    return tf.math.logical_not(
        tf_text.wordshape(word, tf_text.WordShape.IS_PUNCT_OR_SYMBOL))

  tokenizer = tf_text.WhitespaceTokenizer()
  ds = ds.map(extract_strings)
  ds = ds.flat_map(tokenize_line)
  ds = ds.map(tf_text.case_fold_utf8)
  ds = ds.filter(mask_all_symbolic_words)
  return ds 
開發者ID:tensorflow,項目名稱:federated,代碼行數:26,代碼來源:heavy_hitters_utils.py

示例5: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  # x = np.arange(-3.0, 3.0, 0.01)
  # x = np.random.uniform(-0.01, 0.01, size=1000)
  x = np.random.uniform(-10.0, 10.0, size=1000)
  # x = np.random.uniform(-1, 1, size=1000)
  x = np.sort(x)
  tr = np.zeros_like(x)
  t = np.zeros_like(x)
  iter_count = 500
  for _ in range(iter_count):
    y = _ternary(x)
    yr = _ternary(x, sto=True)
    t = t + y
    tr = tr + yr

  plt.plot(x, t/iter_count)
  plt.plot(x, tr/iter_count)
  plt.ylabel('mean (%s samples)' % iter_count)
  plt.show() 
開發者ID:google,項目名稱:qkeras,代碼行數:24,代碼來源:example_ternary.py

示例6: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')
  flags.mark_flag_as_required('prediction_file')

  sources, predictions, target_lists = score_lib.read_data(
      FLAGS.prediction_file, FLAGS.case_insensitive)
  logging.info(f'Read file: {FLAGS.prediction_file}')
  exact = score_lib.compute_exact_score(predictions, target_lists)
  sari, keep, addition, deletion = score_lib.compute_sari_scores(
      sources, predictions, target_lists)
  print(f'Exact score:     {100*exact:.3f}')
  print(f'SARI score:      {100*sari:.3f}')
  print(f' KEEP score:     {100*keep:.3f}')
  print(f' ADDITION score: {100*addition:.3f}')
  print(f' DELETION score: {100*deletion:.3f}') 
開發者ID:google-research,項目名稱:lasertagger,代碼行數:18,代碼來源:score_main.py

示例7: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  recall_values = {}
  for setting in ['static', 'dynamic']:
    recall = []
    for seed in range(FLAGS.num_trials):
      with file_util.open(
          os.path.join(FLAGS.source_path, str(seed), 'cumulative_recall_%s.txt')
          % setting, 'r') as infile:
        recall.append(np.loadtxt(infile))
      recall_values[setting] = np.vstack(recall)

  lending_plots.plot_cumulative_recall_differences(
      recall_values,
      path=os.path.join(FLAGS.plotting_dir, 'combined_simpsons_paradox.pdf')) 
開發者ID:google,項目名稱:ml-fairness-gym,代碼行數:19,代碼來源:aggregate_lending_recall_values.py

示例8: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def main(argv):
  # TODO(): add tests to check correct plots generated.
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')
  deltas = None

  # Casting to float since these are sometimes passed through flags as strings.
  feature_mu = [float(mu) for mu in FLAGS.feature_mu]
  if FLAGS.noisy_features or FLAGS.noisy_threshold:
    results, thresholds, deltas, stdevs = run_noisy_experiment(
        noise_dist=FLAGS.noisy_dist,
        noisy_features=FLAGS.noisy_features,
        noisy_threshold=FLAGS.noisy_threshold,
        feature_mu=feature_mu)
    plot_deltas(deltas)
    for sd in stdevs:
      plot_thresholds(results[sd], thresholds, name=sd)
      plot_metrics(results[sd], thresholds, name=sd)

  else:
    results, thresholds = run_baseline_experiment(FLAGS.feature_mu)
    results_noise, _, _, _ = run_noisy_experiment(
        noisy_features=True, stdevs=[0.1])
    plot_threshold_pair([results, results_noise[0.1]],
                        ['Noiseless Features', 'Noisy Features'], thresholds) 
開發者ID:google,項目名稱:ml-fairness-gym,代碼行數:27,代碼來源:college_admission_main.py

示例9: _main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def _main(argv):
  """Main function for invoking the `nsl.tools.build_graph` function."""
  flag = flags.FLAGS
  flag.showprefixforinfo = False
  if len(argv) < 3:
    raise app.UsageError(
        'Invalid number of arguments; expected 2 or more, got %d' %
        (len(argv) - 1))

  build_graph_from_config(
      argv[1:-1], argv[-1],
      nsl_configs.GraphBuilderConfig(
          id_feature_name=flag.id_feature_name,
          embedding_feature_name=flag.embedding_feature_name,
          similarity_threshold=flag.similarity_threshold,
          lsh_bits=flag.lsh_bits,
          random_seed=flag.random_seed)) 
開發者ID:tensorflow,項目名稱:neural-structured-learning,代碼行數:19,代碼來源:build_graph.py

示例10: _main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def _main(argv):
  """Main function for invoking the `nsl.tools.pack_nbrs` function."""
  flag = flags.FLAGS
  flag.showprefixforinfo = False
  # Check that the correct number of arguments have been provided.
  if len(argv) != 5:
    raise app.UsageError('Invalid number of arguments; expected 4, got %d' %
                         (len(argv) - 1))

  pack_nbrs(
      labeled_examples_path=argv[1],
      unlabeled_examples_path=argv[2],
      graph_path=argv[3],
      output_training_data_path=argv[4],
      add_undirected_edges=flag.add_undirected_edges,
      max_nbrs=flag.max_nbrs,
      id_feature_name=flag.id_feature_name) 
開發者ID:tensorflow,項目名稱:neural-structured-learning,代碼行數:19,代碼來源:pack_nbrs.py

示例11: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  global users
  global private_key

  with open(FLAGS.passwd) as f:
    users = json.load(f)

  logging.info('Loaded: %s', users.keys())

  # Note you really shouldn't have multiple keys in the jwks, as we will only use the last one.
  with open(FLAGS.jwk) as f:
    jwks = json.load(f)
    for key in jwks['keys']:
      private_key = (key['kid'], jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(key)))


  api.run(host='0.0.0.0', port=FLAGS.port) 
開發者ID:google,項目名稱:android-emulator-container-scripts,代碼行數:22,代碼來源:jwt-provider.py

示例12: Run

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def Run(main: Callable[[], None]):
  """Begin executing the program.

  Args:
    main: The main function to execute. It takes no arguments. If any command
    line arguments remain after flags parsing, an error is raised. If it
    returns an integer, it is used as the process's exit code.
  """

  def RunWithoutArgs(argv: List[str]):
    """Run the given function without arguments."""
    if len(argv) > 1:
      raise UsageError("Unknown arguments: '{}'.".format(" ".join(argv[1:])))
    main()

  RunWithArgs(RunWithoutArgs)


# Logging functions. 
開發者ID:ChrisCummins,項目名稱:clgen,代碼行數:21,代碼來源:app.py

示例13: main

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  export_path = FLAGS.export_path
  if os.path.exists(export_path):
    raise ValueError(f'Export_path {export_path} already exists. Please '
                     'specify a different path or delete the existing one.')

  module = _ExtractModule(FLAGS.block3_strides, FLAGS.iou)

  # Load the weights.
  checkpoint_path = FLAGS.ckpt_path
  module.LoadWeights(checkpoint_path)
  print('Checkpoint loaded from ', checkpoint_path)

  # Save the module
  tf.saved_model.save(module, export_path) 
開發者ID:tensorflow,項目名稱:models,代碼行數:20,代碼來源:export_model.py

示例14: __init__

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def __init__(
      self, app_servers, build_target, deployment_type, loaner_path, version,
      web_app_dir, yaml_files):
    super(AppEngineServerConfig, self).__init__(deployment_type, loaner_path)
    self._build_target = build_target
    self._version = version
    self._web_app_dir = web_app_dir
    self._yaml_files = yaml_files
    self._app_servers = _ParseAppServers(app_servers)
    if self._deployment_type not in list(self._app_servers.keys()):
      raise app.UsageError(
          'Application name provided is not in the list of App Servers.\n'
          'Please check the name and/or the deploy.sh configuration.') 
開發者ID:google,項目名稱:loaner,代碼行數:15,代碼來源:deploy_impl.py

示例15: testAppEngineServerConfigWithMissingDeploymentServer

# 需要導入模塊: from absl import app [as 別名]
# 或者: from absl.app import UsageError [as 別名]
def testAppEngineServerConfigWithMissingDeploymentServer(self):
    """Test a deployment server that is not in appservers, raises UsageError."""
    with self.assertRaises(app.UsageError):
      self.CreateTestAppEngineConfig(deployment_type='not_real_server') 
開發者ID:google,項目名稱:loaner,代碼行數:6,代碼來源:deploy_impl_test.py


注:本文中的absl.app.UsageError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。