function
stringlengths 11
56k
| repo_name
stringlengths 5
60
| features
sequence |
---|---|---|
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1) | yaybu/touchdown | [
11,
4,
11,
17,
1410353271
] |
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
) | yaybu/touchdown | [
11,
4,
11,
17,
1410353271
] |
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None) | yaybu/touchdown | [
11,
4,
11,
17,
1410353271
] |
def _is_printer_printing(printer: OctoprintPrinterInfo) -> bool:
return (
printer
and printer.state
and printer.state.flags
and printer.state.flags.printing
) | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def __init__(
self,
coordinator: OctoprintDataUpdateCoordinator,
sensor_type: str,
device_id: str, | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def device_info(self):
"""Device info."""
return self.coordinator.device_info | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def native_value(self):
"""Return sensor state."""
printer: OctoprintPrinterInfo = self.coordinator.data["printer"]
if not printer:
return None
return printer.state.text | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def available(self) -> bool:
"""Return if entity is available."""
return self.coordinator.last_update_success and self.coordinator.data["printer"] | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def native_value(self):
"""Return sensor state."""
job: OctoprintJobInfo = self.coordinator.data["job"]
if not job:
return None
if not (state := job.progress.completion):
return 0
return round(state, 2) | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def native_value(self) -> datetime | None:
"""Return sensor state."""
job: OctoprintJobInfo = self.coordinator.data["job"]
if (
not job
or not job.progress.print_time_left
or not _is_printer_printing(self.coordinator.data["printer"])
):
return None
read_time = self.coordinator.data["last_read_time"]
return read_time + timedelta(seconds=job.progress.print_time_left) | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def native_value(self) -> datetime | None:
"""Return sensor state."""
job: OctoprintJobInfo = self.coordinator.data["job"]
if (
not job
or not job.progress.print_time
or not _is_printer_printing(self.coordinator.data["printer"])
):
return None
read_time = self.coordinator.data["last_read_time"]
return read_time - timedelta(seconds=job.progress.print_time) | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def __init__(
self,
coordinator: OctoprintDataUpdateCoordinator,
tool: str,
temp_type: str,
device_id: str, | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def native_value(self):
"""Return sensor state."""
printer: OctoprintPrinterInfo = self.coordinator.data["printer"]
if not printer:
return None
for temp in printer.temperatures:
if temp.name == self._api_tool:
val = (
temp.actual_temp
if self._temp_type == "actual"
else temp.target_temp
)
if val is None:
return None
return round(val, 2)
return None | home-assistant/home-assistant | [
58698,
22318,
58698,
2794,
1379402988
] |
def test_error_on_wrong_value_for_consumed_capacity():
resource = boto3.resource("dynamodb", region_name="ap-northeast-3")
client = boto3.client("dynamodb", region_name="ap-northeast-3")
client.create_table(
TableName="jobs",
KeySchema=[{"AttributeName": "job_id", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "job_id", "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
)
table = resource.Table("jobs")
item = {"job_id": "asdasdasd", "expires_at": "1"}
# PUT_ITEM
with pytest.raises(ClientError) as ex:
table.put_item(Item=item, ReturnConsumedCapacity="Garbage")
err = ex.value.response["Error"]
err["Code"].should.equal("ValidationException")
err["Message"].should.equal(
"1 validation error detected: Value 'Garbage' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"
) | spulec/moto | [
6700,
1808,
6700,
82,
1361221859
] |
def test_consumed_capacity_get_unknown_item():
conn = boto3.client("dynamodb", region_name="us-east-1")
conn.create_table(
TableName="test_table",
KeySchema=[{"AttributeName": "u", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "u", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
response = conn.get_item(
TableName="test_table",
Key={"u": {"S": "does_not_exist"}},
ReturnConsumedCapacity="TOTAL",
)
# Should still return ConsumedCapacity, even if it does not return an item
response.should.have.key("ConsumedCapacity")
response["ConsumedCapacity"].should.equal(
{"TableName": "test_table", "CapacityUnits": 0.5}
) | spulec/moto | [
6700,
1808,
6700,
82,
1361221859
] |
def test_only_return_consumed_capacity_when_required(
capacity, should_have_capacity, should_have_table | spulec/moto | [
6700,
1808,
6700,
82,
1361221859
] |
def validate_response(
response, should_have_capacity, should_have_table, is_index=False, value=1.0 | spulec/moto | [
6700,
1808,
6700,
82,
1361221859
] |
def index(self, request):
queryset = Condition.objects.select_related('source', 'target_option')
serializer = ConditionIndexSerializer(queryset, many=True)
return Response(serializer.data) | rdmorganiser/rdmo | [
80,
41,
80,
122,
1438336991
] |
def export(self, request):
serializer = ConditionExportSerializer(self.get_queryset(), many=True)
xml = ConditionRenderer().render(serializer.data)
return XMLResponse(xml, name='conditions') | rdmorganiser/rdmo | [
80,
41,
80,
122,
1438336991
] |
def detail_export(self, request, pk=None):
serializer = ConditionExportSerializer(self.get_object())
xml = ConditionRenderer().render([serializer.data])
return XMLResponse(xml, name=self.get_object().key) | rdmorganiser/rdmo | [
80,
41,
80,
122,
1438336991
] |
def roll_die(size):
first_die = choice(range(1, size + 1))
second_die = choice(range(1, size + 1))
return (first_die + second_die, (first_die == second_die)) | dhermes/project-euler | [
11,
3,
11,
1,
1299471955
] |
def next_specific(square, next_type):
if next_type not in ["R", "U"]:
raise Exception("next_specific only intended for R and U")
# R1=5, R2=15, R3=25, R4=35
index = SQUARES.index(square)
if next_type == "R":
if 0 <= index < 5 or 35 < index:
return "R1"
elif 5 < index < 15:
return "R2"
elif 15 < index < 25:
return "R3"
elif 25 < index < 35:
return "R4"
else:
raise Exception("Case should not occur")
# U1=12, U2=28
elif next_type == "U":
if 0 <= index < 12 or index > 28:
return "U1"
elif 12 < index < 28:
return "U2"
else:
return Exception("Case should not occur")
else:
raise Exception("Case should not occur") | dhermes/project-euler | [
11,
3,
11,
1,
1299471955
] |
def main(verbose=False):
GAME_PLAY = 10 ** 6
dice_size = 4
visited = {"GO": 1}
current = "GO"
chance_card = 0
chest_card = 0
doubles = 0
for place in xrange(GAME_PLAY):
total, double = roll_die(dice_size)
if double:
doubles += 1
else:
doubles = 0
if doubles == 3:
doubles = 0
current = "JAIL"
else:
index = SQUARES.index(current)
landing_square = SQUARES[(index + total) % len(SQUARES)]
(current, chance_card,
chest_card) = next_square(landing_square, chance_card, chest_card)
# if current is not in visited, sets to 1
# (default 0 returned by get)
visited[current] = visited.get(current, 0) + 1
top_visited = sorted(visited.items(),
key=lambda pair: pair[1],
reverse=True)
top_visited = [SQUARES.index(square[0]) for square in top_visited[:3]]
return ''.join(str(index).zfill(2) for index in top_visited) | dhermes/project-euler | [
11,
3,
11,
1,
1299471955
] |
def matplotlib_pyplot():
import matplotlib # pylint: disable=g-import-not-at-top
matplotlib.use("agg")
import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top
return plt | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def convert_predictions_to_image_summaries(hook_args):
"""Optionally converts images from hooks_args to image summaries.
Args:
hook_args: DecodeHookArgs namedtuple
Returns:
summaries: list of tf.Summary values if hook_args.decode_hpara
"""
decode_hparams = hook_args.decode_hparams
if not decode_hparams.display_decoded_images:
return []
predictions = hook_args.predictions[0]
# Display ten random inputs and outputs so that tensorboard does not hang.
all_summaries = []
rand_predictions = np.random.choice(predictions, size=10)
for ind, prediction in enumerate(rand_predictions):
output_summary = image_to_tf_summary_value(
prediction["outputs"], tag="%d_output" % ind)
input_summary = image_to_tf_summary_value(
prediction["inputs"], tag="%d_input" % ind)
all_summaries.append(input_summary)
all_summaries.append(output_summary)
return all_summaries | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def make_multiscale(image, resolutions,
resize_method=tf.image.ResizeMethod.BICUBIC,
num_channels=3):
"""Returns list of scaled images, one for each resolution.
Args:
image: Tensor of shape [height, height, num_channels].
resolutions: List of heights that image's height is resized to.
resize_method: tf.image.ResizeMethod.
num_channels: Number of channels in image.
Returns:
List of Tensors, one for each resolution with shape given by
[resolutions[i], resolutions[i], num_channels].
"""
scaled_images = []
for height in resolutions:
scaled_image = tf.image.resize_images(
image,
size=[height, height], # assuming that height = width
method=resize_method)
scaled_image = tf.to_int64(scaled_image)
scaled_image.set_shape([height, height, num_channels])
scaled_images.append(scaled_image)
return scaled_images | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def num_channels(self):
"""Number of color channels."""
return 3 | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def vocab_size(self):
"""Number of pixel values."""
return 256 | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def preprocess_example(self, example, mode, hparams):
if not self._was_reversed:
example["inputs"] = tf.image.per_image_standardization(example["inputs"])
return example | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def decode_hooks(self):
return [convert_predictions_to_image_summaries] | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def is_small(self):
raise NotImplementedError() | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def num_classes(self):
raise NotImplementedError() | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def train_shards(self):
raise NotImplementedError() | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def dev_shards(self):
return 1 | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def class_labels(self):
return ["ID_%d" % i for i in range(self.num_classes)] | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def generator(self, data_dir, tmp_dir, is_training):
raise NotImplementedError() | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def hparams(self, defaults, unused_model_hparams):
p = defaults
p.modality = {"inputs": modalities.ModalityType.IMAGE,
"targets": modalities.ModalityType.CLASS_LABEL}
p.vocab_size = {"inputs": 256,
"targets": self.num_classes}
p.batch_size_multiplier = 4 if self.is_small else 256
p.loss_multiplier = 3.0 if self.is_small else 1.0
if self._was_reversed:
p.loss_multiplier = 1.0
p.input_space_id = problem.SpaceID.IMAGE
p.target_space_id = problem.SpaceID.IMAGE_LABEL | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def encode_images_as_png(images):
"""Yield images encoded as pngs."""
if tf.executing_eagerly():
for image in images:
yield tf.image.encode_png(image).numpy()
else:
(height, width, channels) = images[0].shape
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels))
encoded_image_t = tf.image.encode_png(image_t)
with tf.Session() as sess:
for image in images:
enc_string = sess.run(encoded_image_t, feed_dict={image_t: image})
yield enc_string | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def is_character_level(self):
raise NotImplementedError() | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def vocab_problem(self):
raise NotImplementedError() # Not needed if self.is_character_level. | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def target_space_id(self):
raise NotImplementedError() | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def train_shards(self):
raise NotImplementedError() | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def dev_shards(self):
raise NotImplementedError() | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def example_reading_spec(self):
label_key = "image/class/label"
data_fields, data_items_to_decoders = (
super(Image2TextProblem, self).example_reading_spec())
data_fields[label_key] = tf.VarLenFeature(tf.int64)
data_items_to_decoders["targets"] = contrib.slim().tfexample_decoder.Tensor(
label_key)
return data_fields, data_items_to_decoders | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def hparams(self, defaults, unused_model_hparams):
p = defaults
p.modality = {"inputs": modalities.ModalityType.IMAGE,
"targets": modalities.ModalityType.SYMBOL}
p.vocab_size = {"inputs": 256,
"targets": self._encoders["targets"].vocab_size}
p.batch_size_multiplier = 256
p.loss_multiplier = 1.0
p.input_space_id = problem.SpaceID.IMAGE
p.target_space_id = self.target_space_id | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def image_augmentation(images, do_colors=False, crop_size=None):
"""Image augmentation: cropping, flipping, and color transforms."""
if crop_size is None:
crop_size = [299, 299]
images = tf.random_crop(images, crop_size + [3])
images = tf.image.random_flip_left_right(images)
if do_colors: # More augmentation, but might be slow.
images = tf.image.random_brightness(images, max_delta=32. / 255.)
images = tf.image.random_saturation(images, lower=0.5, upper=1.5)
images = tf.image.random_hue(images, max_delta=0.2)
images = tf.image.random_contrast(images, lower=0.5, upper=1.5)
return images | tensorflow/tensor2tensor | [
13097,
3192,
13097,
587,
1497545859
] |
def generate_dataset(I,J,K,lambdaU,lambdaV,tau):
# Generate U, V
U = numpy.zeros((I,K))
for i,k in itertools.product(xrange(0,I),xrange(0,K)):
U[i,k] = exponential_draw(lambdaU[i,k])
V = numpy.zeros((J,K))
for j,k in itertools.product(xrange(0,J),xrange(0,K)):
V[j,k] = exponential_draw(lambdaV[j,k]) | ThomasBrouwer/BNMTF | [
18,
6,
18,
1,
1438595414
] |
def add_noise(true_R,tau):
if numpy.isinf(tau):
return numpy.copy(true_R) | ThomasBrouwer/BNMTF | [
18,
6,
18,
1,
1438595414
] |
def try_generate_M(I,J,fraction_unknown,attempts):
for attempt in range(1,attempts+1):
try:
M = generate_M(I,J,fraction_unknown)
sums_columns = M.sum(axis=0)
sums_rows = M.sum(axis=1)
for i,c in enumerate(sums_rows):
assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown)
for j,c in enumerate(sums_columns):
assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown)
print "Took %s attempts to generate M." % attempt
return M
except AssertionError:
pass
raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) | ThomasBrouwer/BNMTF | [
18,
6,
18,
1,
1438595414
] |
def create_channel(
cls,
host: str = "analyticsdata.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs, | googleapis/python-analytics-data | [
114,
29,
114,
9,
1600119359
] |
def __init__(
self,
*,
host: str = "analyticsdata.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False, | googleapis/python-analytics-data | [
114,
29,
114,
9,
1600119359
] |
def grpc_channel(self) -> aio.Channel:
"""Create the channel designed to connect to this service.
This property caches on the instance; repeated calls return
the same channel.
"""
# Return the channel from cache.
return self._grpc_channel | googleapis/python-analytics-data | [
114,
29,
114,
9,
1600119359
] |
def run_report(
self, | googleapis/python-analytics-data | [
114,
29,
114,
9,
1600119359
] |
def run_pivot_report(
self, | googleapis/python-analytics-data | [
114,
29,
114,
9,
1600119359
] |
def batch_run_reports(
self, | googleapis/python-analytics-data | [
114,
29,
114,
9,
1600119359
] |
def batch_run_pivot_reports(
self, | googleapis/python-analytics-data | [
114,
29,
114,
9,
1600119359
] |
def get_metadata(
self, | googleapis/python-analytics-data | [
114,
29,
114,
9,
1600119359
] |
def run_realtime_report(
self, | googleapis/python-analytics-data | [
114,
29,
114,
9,
1600119359
] |
def __init__(self, subtype, msg=None):
if msg is None:
msg = "An error occured for subtype {}".format(subtype)
super(PhylotyperError, self).__init__(msg)
self.subtype = subtype | superphy/backend | [
4,
2,
4,
35,
1484074797
] |
def __init__(self, subtype, msg=None):
super(PhylotyperError, self).__init__(
subtype, msg="Unrecognized subtype {}".format(subtype)) | superphy/backend | [
4,
2,
4,
35,
1484074797
] |
def setUp(self):
self._mock_multiplexer = mock.create_autospec(
plugin_event_multiplexer.EventMultiplexer
)
self._mock_tb_context = base_plugin.TBContext(
multiplexer=self._mock_multiplexer
) | tensorflow/tensorboard | [
6136,
1581,
6136,
616,
1494878887
] |
def test_csv(self):
body, mime_type = self._run_handler(
EXPERIMENT, SESSION_GROUPS, download_data.OutputFormat.CSV
)
self.assertEqual("text/csv", mime_type)
self.assertEqual(EXPECTED_CSV, body) | tensorflow/tensorboard | [
6136,
1581,
6136,
616,
1494878887
] |
def test_json(self):
body, mime_type = self._run_handler(
EXPERIMENT, SESSION_GROUPS, download_data.OutputFormat.JSON
)
self.assertEqual("application/json", mime_type)
expected_result = {
"header": [
"initial_temp",
"final_temp",
"string_hparam",
"bool_hparam",
"optional_string_hparam",
"current_temp",
"delta_temp",
"optional_metric",
],
"rows": [
[270.0, 150.0, "a string", True, "", 10.0, 15.0, 33.0],
[280.0, 100.0, "AAAAA", False, "", 51.0, 44.5, None],
[
300.0,
1.2e-05,
"a string_3",
True,
"BB",
101.0,
-15100000.0,
None,
],
],
}
self.assertEqual(expected_result, body) | tensorflow/tensorboard | [
6136,
1581,
6136,
616,
1494878887
] |
def friendly_time(msecs):
secs, msecs = divmod(msecs, 1000)
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
if hours:
return '%dh%dm%ds' % (hours, mins, secs)
elif mins:
return '%dm%ds' % (mins, secs)
elif secs:
return '%ds%dms' % (secs, msecs)
else:
return '%.2fms' % msecs | piglei/uwsgi-sloth | [
207,
17,
207,
1,
1402890563
] |
def forwards(self, orm): | mollyproject/mollyproject | [
75,
20,
75,
4,
1288876632
] |
def backwards(self, orm): | mollyproject/mollyproject | [
75,
20,
75,
4,
1288876632
] |
def dem_threshold(domain, b):
'''Just use a height threshold on the DEM!'''
heightLevel = float(domain.algorithm_params['dem_threshold'])
dem = domain.get_dem().image
return dem.lt(heightLevel).select(['elevation'], ['b1']) | nasa/CrisisMappingToolkit | [
183,
75,
183,
5,
1417805519
] |
def evi(domain, b):
'''Simple EVI based classifier'''
#no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1'])
criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1'])
criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1'])
#return no_clouds.And(criteria1.Or(criteria2))
return criteria1.Or(criteria2) | nasa/CrisisMappingToolkit | [
183,
75,
183,
5,
1417805519
] |
def get_diff(b):
'''Just the internals of the difference method'''
return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) | nasa/CrisisMappingToolkit | [
183,
75,
183,
5,
1417805519
] |
def modis_diff(domain, b, threshold=None):
'''Compute (b2-b1) < threshold, a simple water detection index. | nasa/CrisisMappingToolkit | [
183,
75,
183,
5,
1417805519
] |
def get_dartmouth(b):
A = 500
B = 2500
return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) | nasa/CrisisMappingToolkit | [
183,
75,
183,
5,
1417805519
] |
def dartmouth(domain, b, threshold=None):
'''A flood detection method from the Dartmouth Flood Observatory. | nasa/CrisisMappingToolkit | [
183,
75,
183,
5,
1417805519
] |
def get_mod_ndwi(b):
return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) | nasa/CrisisMappingToolkit | [
183,
75,
183,
5,
1417805519
] |
def mod_ndwi(domain, b, threshold=None):
if threshold == None:
threshold = float(domain.algorithm_params['mod_ndwi_threshold'])
return get_mod_ndwi(b).lte(threshold) | nasa/CrisisMappingToolkit | [
183,
75,
183,
5,
1417805519
] |
def get_fai(b):
'''Just the internals of the FAI method'''
return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) | nasa/CrisisMappingToolkit | [
183,
75,
183,
5,
1417805519
] |
def get_spec(field, limit=10, query='', query_dsl=''):
"""Returns aggregation specs for a term of filtered events.
The aggregation spec will summarize values of an attribute
whose events fall under a filter.
Args:
field (str): this denotes the event attribute that is used
for aggregation.
limit (int): How many buckets to return, defaults to 10.
query (str): the query field to run on all documents prior to
aggregating the results.
query_dsl (str): the query DSL field to run on all documents prior
to aggregating the results (optional). Either a query string
or a query DSL has to be present.
Raises:
ValueError: if neither query_string or query_dsl is provided.
Returns:
a dict value that can be used as an aggregation spec.
"""
if query:
query_filter = {
'bool': {
'must': [
{
'query_string': {
'query': query
}
}
]
}
}
elif query_dsl:
query_filter = query_dsl
else:
raise ValueError('Neither query nor query DSL provided.')
return {
'query': query_filter,
'aggs': {
'aggregation': {
'terms': {
'field': field,
'size': limit
}
}
}
} | google/timesketch | [
2113,
486,
2113,
278,
1403200185
] |
def chart_title(self):
"""Returns a title for the chart."""
if self.field:
return 'Top filtered results for "{0:s}"'.format(self.field)
return 'Top results for an unknown field after filtering' | google/timesketch | [
2113,
486,
2113,
278,
1403200185
] |
def run(
self, field, query_string='', query_dsl='',
supported_charts='table', start_time='', end_time='', limit=10):
"""Run the aggregation.
Args:
field (str): this denotes the event attribute that is used
for aggregation.
query_string (str): the query field to run on all documents prior to
aggregating the results.
query_dsl (str): the query DSL field to run on all documents prior
to aggregating the results. Either a query string or a query
DSL has to be present.
supported_charts: Chart type to render. Defaults to table.
start_time: Optional ISO formatted date string that limits the time
range for the aggregation.
end_time: Optional ISO formatted date string that limits the time
range for the aggregation.
limit (int): How many buckets to return, defaults to 10.
Returns:
Instance of interface.AggregationResult with aggregation result.
Raises:
ValueError: if neither query_string or query_dsl is provided.
"""
if not (query_string or query_dsl):
raise ValueError('Both query_string and query_dsl are missing')
self.field = field
formatted_field_name = self.format_field_by_type(field)
aggregation_spec = get_spec(
field=formatted_field_name, limit=limit, query=query_string,
query_dsl=query_dsl)
aggregation_spec = self._add_query_to_aggregation_spec(
aggregation_spec, start_time=start_time, end_time=end_time)
# Encoding information for Vega-Lite.
encoding = {
'x': {
'field': field,
'type': 'nominal',
'sort': {
'op': 'sum',
'field': 'count',
'order': 'descending'
}
},
'y': {'field': 'count', 'type': 'quantitative'},
'tooltip': [
{'field': field, 'type': 'nominal'},
{'field': 'count', 'type': 'quantitative'}],
}
response = self.opensearch_aggregation(aggregation_spec)
aggregations = response.get('aggregations', {})
aggregation = aggregations.get('aggregation', {})
buckets = aggregation.get('buckets', [])
values = []
for bucket in buckets:
d = {
field: bucket.get('key', 'N/A'),
'count': bucket.get('doc_count', 0)
}
values.append(d)
if query_string:
extra_query_url = 'AND {0:s}'.format(query_string)
else:
extra_query_url = ''
return interface.AggregationResult(
encoding=encoding, values=values, chart_type=supported_charts,
sketch_url=self._sketch_url, field=field,
extra_query_url=extra_query_url) | google/timesketch | [
2113,
486,
2113,
278,
1403200185
] |
def create_colors_list():
colors_list = []
for color in plt.cm.tab10(np.linspace(0, 1, 10))[:-1]:
colors_list.append(tuple(color))
colors_list.append("black")
for color in plt.cm.Set2(np.linspace(0, 1, 8)):
colors_list.append(tuple(color))
for color in plt.cm.Set3(np.linspace(0, 1, 12)):
colors_list.append(tuple(color))
return colors_list | CAMI-challenge/AMBER | [
18,
7,
18,
3,
1502787274
] |
def plot_precision_vs_bin_size(pd_bins, output_dir):
pd_plot = pd_bins[pd_bins[utils_labels.TOOL] != utils_labels.GS]
for tool_label, pd_tool in pd_plot.groupby(utils_labels.TOOL):
fig, axs = plt.subplots(figsize=(5, 4.5))
axs.scatter(np.log(pd_tool['total_length']), pd_tool['precision_bp'], marker='o')
axs.set_xlim([None, np.log(pd_tool['total_length'].max())])
axs.set_ylim([0.0, 1.0])
axs.set_title(tool_label, fontsize=12)
plt.ylabel('Purity per bin (%)', fontsize=12)
plt.xlabel('Bin size [log(# bp)]', fontsize=12)
fig.savefig(os.path.join(output_dir, 'genome', tool_label, 'purity_vs_bin_size.png'), dpi=200, format='png', bbox_inches='tight')
plt.close(fig) | CAMI-challenge/AMBER | [
18,
7,
18,
3,
1502787274
] |
def get_pd_genomes_recall(sample_id_to_queries_list):
pd_genomes_recall = pd.DataFrame()
for sample_id in sample_id_to_queries_list:
for query in sample_id_to_queries_list[sample_id]:
if not isinstance(query, binning_classes.GenomeQuery):
continue
recall_df = query.recall_df_cami1[['genome_id', 'recall_bp']].copy()
recall_df[utils_labels.TOOL] = query.label
recall_df['sample_id'] = sample_id
recall_df = recall_df.reset_index().set_index(['sample_id', utils_labels.TOOL])
pd_genomes_recall = pd.concat([pd_genomes_recall, recall_df])
return pd_genomes_recall | CAMI-challenge/AMBER | [
18,
7,
18,
3,
1502787274
] |
def plot_heatmap(df_confusion, sample_id, output_dir, label, separate_bar=False, log_scale=False):
if log_scale:
df_confusion = df_confusion.apply(np.log10, inplace=True).replace(-np.inf, 0)
fig, axs = plt.subplots(figsize=(10, 8))
fontsize = 20
# replace columns and rows labels by numbers
d = {value: key for (key, value) in enumerate(df_confusion.columns.tolist(), 1)}
df_confusion = df_confusion.rename(index=str, columns=d)
df_confusion.index = range(1, len(df_confusion) + 1)
xticklabels = int(round(df_confusion.shape[1] / 10, -1))
yticklabels = int(round(df_confusion.shape[0] / 10, -1))
sns_plot = sns.heatmap(df_confusion, ax=axs, annot=False, cmap="YlGnBu_r", xticklabels=xticklabels, yticklabels=yticklabels, cbar=False, rasterized=True)
# sns_plot = sns.heatmap(df_confusion, ax=axs, annot=False, cmap="YlGnBu_r", xticklabels=False, yticklabels=False, cbar=True, rasterized=True)
sns_plot.set_xlabel("Genomes", fontsize=fontsize)
sns_plot.set_ylabel("Predicted bins", fontsize=fontsize)
plt.yticks(fontsize=12, rotation=0)
plt.xticks(fontsize=12)
mappable = sns_plot.get_children()[0]
cbar_ax = fig.add_axes([.915, .11, .017, .77])
cbar = plt.colorbar(mappable, ax=axs, cax=cbar_ax, orientation='vertical')
if log_scale:
cbar.set_label(fontsize=fontsize, label='log$_{10}$(# bp)')
else:
fmt = lambda x, pos: '{:.0f}'.format(x / 1000000)
cbar = plt.colorbar(mappable, ax=axs, cax=cbar_ax, orientation='vertical', format=ticker.FuncFormatter(fmt))
cbar.set_label(fontsize=fontsize, label='Millions of base pairs')
cbar.ax.tick_params(labelsize=fontsize)
cbar.outline.set_edgecolor(None)
axs.set_title(label, fontsize=fontsize, pad=10)
axs.set_ylim([len(df_confusion), 0])
# plt.yticks(fontsize=14, rotation=0)
# plt.xticks(fontsize=14)
output_dir = os.path.join(output_dir, 'genome', label)
fig.savefig(os.path.join(output_dir, 'heatmap_' + sample_id + '.pdf'), dpi=100, format='pdf', bbox_inches='tight')
fig.savefig(os.path.join(output_dir, 'heatmap_' + sample_id + '.png'), dpi=200, format='png', bbox_inches='tight')
plt.close(fig)
if not separate_bar:
return
# create separate figure for bar
fig = plt.figure(figsize=(6, 6))
mappable = sns_plot.get_children()[0]
fmt = lambda x, pos: '{:.0f}'.format(x / 1000000)
cbar = plt.colorbar(mappable, orientation='vertical', label='[millions of base pairs]', format=ticker.FuncFormatter(fmt))
text = cbar.ax.yaxis.label
font = matplotlib.font_manager.FontProperties(size=16)
text.set_font_properties(font)
cbar.outline.set_visible(False)
cbar.ax.tick_params(labelsize=14)
# store separate bar figure
plt.gca().set_visible(False)
fig.savefig(os.path.join(output_dir, 'heatmap_bar.pdf'), dpi=100, format='pdf', bbox_inches='tight')
plt.close(fig) | CAMI-challenge/AMBER | [
18,
7,
18,
3,
1502787274
] |
def plot_summary(color_indices, df_results, labels, output_dir, rank, plot_type, file_name, xlabel, ylabel):
available_tools = df_results[utils_labels.TOOL].unique()
tools = [tool for tool in labels if tool in available_tools]
colors_list = create_colors_list()
if color_indices:
colors_list = [colors_list[i] for i in color_indices]
df_mean = df_results.groupby(utils_labels.TOOL).mean().reindex(tools)
binning_type = df_results[utils_labels.BINNING_TYPE].iloc[0]
if len(df_mean) > len(colors_list):
raise RuntimeError("Plot only supports 29 colors")
fig, axs = plt.subplots(figsize=(5, 4.5))
# force axes to be from 0 to 100%
axs.set_xlim([0.0, 1.0])
axs.set_ylim([0.0, 1.0])
if plot_type == 'e':
for i, (tool, df_row) in enumerate(df_mean.iterrows()):
axs.errorbar(df_row[utils_labels.AVG_PRECISION_BP], df_row[utils_labels.AVG_RECALL_BP], xerr=df_row['avg_precision_bp_var'], yerr=df_row['avg_recall_bp_var'],
fmt='o',
ecolor=colors_list[i],
mec=colors_list[i],
mfc=colors_list[i],
capsize=3,
markersize=8)
if plot_type == 'f':
for i, (tool, df_row) in enumerate(df_mean.iterrows()):
axs.errorbar(df_row[utils_labels.AVG_PRECISION_SEQ], df_row[utils_labels.AVG_RECALL_SEQ], xerr=df_row[utils_labels.AVG_PRECISION_SEQ_SEM], yerr=df_row[utils_labels.AVG_RECALL_SEQ_SEM],
fmt='o',
ecolor=colors_list[i],
mec=colors_list[i],
mfc=colors_list[i],
capsize=3,
markersize=8)
if plot_type == 'w':
for i, (tool, df_row) in enumerate(df_mean.iterrows()):
axs.plot(df_row[utils_labels.PRECISION_PER_BP], df_row[utils_labels.RECALL_PER_BP], marker='o', color=colors_list[i], markersize=10)
if plot_type == 'x':
for i, (tool, df_row) in enumerate(df_mean.iterrows()):
axs.plot(df_row[utils_labels.PRECISION_PER_SEQ], df_row[utils_labels.RECALL_PER_SEQ], marker='o', color=colors_list[i], markersize=10)
elif plot_type == 'p':
for i, (tool, df_row) in enumerate(df_mean.iterrows()):
axs.plot(df_row[utils_labels.ARI_BY_BP], df_row[utils_labels.PERCENTAGE_ASSIGNED_BPS], marker='o', color=colors_list[i], markersize=10)
# turn on grid
# axs.minorticks_on()
axs.grid(which='major', linestyle=':', linewidth='0.5')
# axs.grid(which='minor', linestyle=':', linewidth='0.5')
# transform plot_labels to percentages
if plot_type != 'p':
vals = axs.get_xticks()
axs.set_xticklabels(['{:3.0f}'.format(x * 100) for x in vals], fontsize=11)
else:
axs.tick_params(axis='x', labelsize=12)
vals = axs.get_yticks()
axs.set_yticklabels(['{:3.0f}'.format(x * 100) for x in vals], fontsize=11)
if rank:
file_name = rank + '_' + file_name
plt.title(rank)
ylabel = ylabel.replace('genome', 'taxon')
plt.xlabel(xlabel, fontsize=13)
plt.ylabel(ylabel, fontsize=13)
plt.tight_layout()
fig.savefig(os.path.join(output_dir, binning_type, file_name + '.eps'), dpi=100, format='eps', bbox_inches='tight')
colors_iter = iter(colors_list)
circles = []
for x in range(len(df_mean)):
circles.append(Line2D([], [], markeredgewidth=0.0, linestyle="None", marker="o", markersize=11, markerfacecolor=next(colors_iter)))
lgd = plt.legend(circles, tools, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., handlelength=0, frameon=False, fontsize=12)
fig.savefig(os.path.join(output_dir, binning_type, file_name + '.pdf'), dpi=100, format='pdf', bbox_extra_artists=(lgd,), bbox_inches='tight')
fig.savefig(os.path.join(output_dir, binning_type, file_name + '.png'), dpi=200, format='png', bbox_extra_artists=(lgd,), bbox_inches='tight')
plt.close(fig) | CAMI-challenge/AMBER | [
18,
7,
18,
3,
1502787274
] |
def plot_precision_recall(colors, summary_per_query, labels, output_dir, rank=None):
plot_summary(colors,
summary_per_query,
labels,
output_dir,
rank,
'w',
'purity_recall_bp',
'Purity for sample (%)',
'Completeness for sample (%)')
plot_summary(colors,
summary_per_query,
labels,
output_dir,
rank,
'x',
'purity_completeness_seq',
'Purity for sample (%)',
'Completeness for sample (%)') | CAMI-challenge/AMBER | [
18,
7,
18,
3,
1502787274
] |
def plot_taxonomic_results(df_summary_t, metrics_list, errors_list, file_name, output_dir):
colors_list = ["#006cba", "#008000", "#ba9e00", "red"]
for tool, pd_results in df_summary_t.groupby(utils_labels.TOOL):
dict_metric_list = []
for metric in metrics_list:
rank_to_metric = OrderedDict([(k, .0) for k in load_ncbi_taxinfo.RANKS])
dict_metric_list.append(rank_to_metric)
dict_error_list = []
for error in errors_list:
rank_to_metric_error = OrderedDict([(k, .0) for k in load_ncbi_taxinfo.RANKS])
dict_error_list.append(rank_to_metric_error)
for index, row in pd_results.iterrows():
for rank_to_metric, metric in zip(dict_metric_list, metrics_list):
rank_to_metric[row[utils_labels.RANK]] = .0 if np.isnan(row[metric]) else row[metric]
for rank_to_metric_error, error in zip(dict_error_list, errors_list):
rank_to_metric_error[row[utils_labels.RANK]] = .0 if np.isnan(row[error]) else row[error]
fig, axs = plt.subplots(figsize=(6, 5))
# force axes to be from 0 to 100%
axs.set_xlim([0, 7])
axs.set_ylim([0.0, 1.0])
x_values = range(len(load_ncbi_taxinfo.RANKS))
y_values_list = []
for rank_to_metric, color in zip(dict_metric_list, colors_list):
y_values = list(rank_to_metric.values())
axs.plot(x_values, y_values, color=color)
y_values_list.append(y_values)
for rank_to_metric_error, y_values, color in zip(dict_error_list, y_values_list, colors_list):
sem = list(rank_to_metric_error.values())
plt.fill_between(x_values, np.subtract(y_values, sem).tolist(), np.add(y_values, sem).tolist(), color=color, alpha=0.5)
plt.xticks(x_values, load_ncbi_taxinfo.RANKS, rotation='vertical')
vals = axs.get_yticks()
axs.set_yticklabels(['{:3.0f}%'.format(x * 100) for x in vals])
lgd = plt.legend(metrics_list, loc=1, borderaxespad=0., handlelength=2, frameon=False)
plt.tight_layout()
fig.savefig(os.path.join(output_dir, 'taxonomic', tool, file_name + '.png'), dpi=100, format='png', bbox_extra_artists=(lgd,), bbox_inches='tight')
fig.savefig(os.path.join(output_dir, 'taxonomic', tool, file_name + '.pdf'), dpi=100, format='pdf', bbox_extra_artists=(lgd,), bbox_inches='tight')
plt.close(fig) | CAMI-challenge/AMBER | [
18,
7,
18,
3,
1502787274
] |
def create_completeness_minus_contamination_column(pd_tool_bins):
pd_tool_bins['newcolumn'] = pd_tool_bins['recall_bp'] + pd_tool_bins['precision_bp'] - 1 | CAMI-challenge/AMBER | [
18,
7,
18,
3,
1502787274
] |
def get_number_of_hq_bins(tools, pd_bins):
pd_counts = pd.DataFrame()
pd_bins_copy = pd_bins[[utils_labels.TOOL, 'precision_bp', 'recall_bp']].copy().dropna(subset=['precision_bp'])
for tool in tools:
pd_tool_bins = pd_bins_copy[pd_bins_copy[utils_labels.TOOL] == tool]
x50 = pd_tool_bins[(pd_tool_bins['recall_bp'] > .5) & (pd_tool_bins['precision_bp'] > .9)].shape[0]
x70 = pd_tool_bins[(pd_tool_bins['recall_bp'] > .7) & (pd_tool_bins['precision_bp'] > .9)].shape[0]
x90 = pd_tool_bins[(pd_tool_bins['recall_bp'] > .9) & (pd_tool_bins['precision_bp'] > .9)].shape[0]
pd_tool_counts = pd.DataFrame([[x90, x70, x50]], columns=['>90%', '>70%', '>50%'], index=[tool])
pd_counts = pd_counts.append(pd_tool_counts)
return pd_counts | CAMI-challenge/AMBER | [
18,
7,
18,
3,
1502787274
] |
def print_banner(bootstrap, no_shell_file):
"""Print the Pigweed or project-specific banner"""
enable_colors()
print(Color.green('\n WELCOME TO...'))
print(Color.magenta(_PIGWEED_BANNER))
if bootstrap:
print(
Color.green('\n BOOTSTRAP! Bootstrap may take a few minutes; '
'please be patient'))
print(
Color.green(
' On Windows, this stage is extremely slow (~10 minutes).\n'))
else:
print(
Color.green(
'\n ACTIVATOR! This sets your console environment variables.\n'
))
if no_shell_file:
print(Color.bold_red('Error!\n'))
print(
Color.red(' Your Pigweed environment does not seem to be'
' configured.'))
print(Color.red(' Run bootstrap.bat to perform initial setup.'))
return 0 | google/pigweed | [
161,
44,
161,
1,
1615327645
] |
def main():
"""Script entry point."""
if os.name != 'nt':
return 1
return print_banner(**vars(parse())) | google/pigweed | [
161,
44,
161,
1,
1615327645
] |
def main(unused_argv):
tpu_cluster_resolver = contrib_cluster_resolver.TPUClusterResolver(
FLAGS.tpu, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
config = contrib_tpu.RunConfig(
cluster=tpu_cluster_resolver,
model_dir=FLAGS.model_dir,
save_checkpoints_steps=FLAGS.iterations_per_loop,
keep_checkpoint_max=None,
tpu_config=contrib_tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_cores,
per_host_input_for_training=contrib_tpu.InputPipelineConfig.PER_HOST_V2)) # pylint: disable=line-too-long
# Input pipelines are slightly different (with regards to shuffling and
# preprocessing) between training and evaluation.
imagenet_train = imagenet_input.ImageNetInput(
is_training=True,
data_dir=FLAGS.data_dir,
use_bfloat16=True,
transpose_input=FLAGS.transpose_input)
imagenet_eval = imagenet_input.ImageNetInput(
is_training=False,
data_dir=FLAGS.data_dir,
use_bfloat16=True,
transpose_input=FLAGS.transpose_input)
if FLAGS.use_fast_lr:
resnet_main.LR_SCHEDULE = [ # (multiplier, epoch to start) tuples
(1.0, 4), (0.1, 21), (0.01, 35), (0.001, 43)
]
imagenet_train_small = imagenet_input.ImageNetInput(
is_training=True,
image_size=128,
data_dir=FLAGS.data_dir_small,
num_parallel_calls=FLAGS.num_parallel_calls,
use_bfloat16=True,
transpose_input=FLAGS.transpose_input,
cache=True)
imagenet_eval_small = imagenet_input.ImageNetInput(
is_training=False,
image_size=128,
data_dir=FLAGS.data_dir_small,
num_parallel_calls=FLAGS.num_parallel_calls,
use_bfloat16=True,
transpose_input=FLAGS.transpose_input,
cache=True)
imagenet_train_large = imagenet_input.ImageNetInput(
is_training=True,
image_size=288,
data_dir=FLAGS.data_dir,
num_parallel_calls=FLAGS.num_parallel_calls,
use_bfloat16=True,
transpose_input=FLAGS.transpose_input)
imagenet_eval_large = imagenet_input.ImageNetInput(
is_training=False,
image_size=288,
data_dir=FLAGS.data_dir,
num_parallel_calls=FLAGS.num_parallel_calls,
use_bfloat16=True,
transpose_input=FLAGS.transpose_input)
resnet_classifier = contrib_tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=resnet_main.resnet_model_fn,
config=config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size)
if FLAGS.mode == 'train':
current_step = estimator._load_global_step_from_checkpoint_dir(FLAGS.model_dir) # pylint: disable=protected-access,line-too-long
batches_per_epoch = NUM_TRAIN_IMAGES / FLAGS.train_batch_size
tf.logging.info('Training for %d steps (%.2f epochs in total). Current'
' step %d.' % (FLAGS.train_steps,
FLAGS.train_steps / batches_per_epoch,
current_step))
start_timestamp = time.time() # This time will include compilation time
# Write a dummy file at the start of training so that we can measure the
# runtime at each checkpoint from the file write time.
tf.gfile.MkDir(FLAGS.model_dir)
if not tf.gfile.Exists(os.path.join(FLAGS.model_dir, 'START')):
with tf.gfile.GFile(os.path.join(FLAGS.model_dir, 'START'), 'w') as f:
f.write(str(start_timestamp))
if FLAGS.use_fast_lr:
small_steps = int(18 * NUM_TRAIN_IMAGES / FLAGS.train_batch_size)
normal_steps = int(41 * NUM_TRAIN_IMAGES / FLAGS.train_batch_size)
large_steps = int(min(50 * NUM_TRAIN_IMAGES / FLAGS.train_batch_size,
FLAGS.train_steps))
resnet_classifier.train(
input_fn=imagenet_train_small.input_fn, max_steps=small_steps)
resnet_classifier.train(
input_fn=imagenet_train.input_fn, max_steps=normal_steps)
resnet_classifier.train(
input_fn=imagenet_train_large.input_fn,
max_steps=large_steps)
else:
resnet_classifier.train(
input_fn=imagenet_train.input_fn, max_steps=FLAGS.train_steps)
else:
assert FLAGS.mode == 'eval'
start_timestamp = tf.gfile.Stat(
os.path.join(FLAGS.model_dir, 'START')).mtime_nsec
results = []
eval_steps = NUM_EVAL_IMAGES // FLAGS.eval_batch_size
ckpt_steps = set()
all_files = tf.gfile.ListDirectory(FLAGS.model_dir)
for f in all_files:
mat = re.match(CKPT_PATTERN, f)
if mat is not None:
ckpt_steps.add(int(mat.group('gs')))
ckpt_steps = sorted(list(ckpt_steps))
tf.logging.info('Steps to be evaluated: %s' % str(ckpt_steps))
for step in ckpt_steps:
ckpt = os.path.join(FLAGS.model_dir, 'model.ckpt-%d' % step)
batches_per_epoch = NUM_TRAIN_IMAGES // FLAGS.train_batch_size
current_epoch = step // batches_per_epoch
if FLAGS.use_fast_lr:
if current_epoch < 18:
eval_input_fn = imagenet_eval_small.input_fn
if current_epoch >= 18 and current_epoch < 41:
eval_input_fn = imagenet_eval.input_fn
if current_epoch >= 41: # 41:
eval_input_fn = imagenet_eval_large.input_fn
else:
eval_input_fn = imagenet_eval.input_fn
end_timestamp = tf.gfile.Stat(ckpt + '.index').mtime_nsec
elapsed_hours = (end_timestamp - start_timestamp) / (1e9 * 3600.0)
tf.logging.info('Starting to evaluate.')
eval_start = time.time() # This time will include compilation time
eval_results = resnet_classifier.evaluate(
input_fn=eval_input_fn,
steps=eval_steps,
checkpoint_path=ckpt)
eval_time = int(time.time() - eval_start)
tf.logging.info('Eval results: %s. Elapsed seconds: %d' %
(eval_results, eval_time))
results.append([
current_epoch,
elapsed_hours,
'%.2f' % (eval_results['top_1_accuracy'] * 100),
'%.2f' % (eval_results['top_5_accuracy'] * 100),
])
time.sleep(60)
with tf.gfile.GFile(os.path.join(FLAGS.model_dir, 'results.tsv'), 'wb') as tsv_file: # pylint: disable=line-too-long
writer = csv.writer(tsv_file, delimiter='\t')
writer.writerow(['epoch', 'hours', 'top1Accuracy', 'top5Accuracy'])
writer.writerows(results) | tensorflow/tpu | [
5035,
1773,
5035,
290,
1499817279
] |
def test_engine_module_name():
engine = salt.engines.Engine({}, "foobar.start", {}, {}, {}, {}, name="foobar")
assert engine.name == "foobar" | saltstack/salt | [
13089,
5388,
13089,
3074,
1298233016
] |
def __init__(self, vocab, clusters):
self.vocab = vocab
self.clusters = clusters | danielfrg/word2vec | [
2483,
628,
2483,
5,
1377467108
] |
def __getitem__(self, word):
return self.get_cluster(word) | danielfrg/word2vec | [
2483,
628,
2483,
5,
1377467108
] |
def get_words_on_cluster(self, cluster):
return self.vocab[self.clusters == cluster] | danielfrg/word2vec | [
2483,
628,
2483,
5,
1377467108
] |
def setUp(self):
super(TestCatalog, self).setUp(capture_output=True) | prestodb/presto-admin | [
170,
102,
170,
63,
1432266042
] |
def test_add_not_exist(self, isfile_mock):
isfile_mock.return_value = False
self.assertRaisesRegexp(ConfigurationError,
'Configuration for catalog dummy not found',
catalog.add, 'dummy') | prestodb/presto-admin | [
170,
102,
170,
63,
1432266042
] |