input
stringlengths
11
7.65k
target
stringlengths
22
8.26k
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def upload_face_image(self, img_data): """ Upload an image of the user's face. `img_data` should be a raw bytestream of a PNG image. This method will take the data, encrypt it using our FACE_IMAGE_AES_KEY, encode it with base64 and save it to the storage backend. Yes, encoding it to base64 adds compute and disk usage without much real benefit, but that's what the other end of this API is expecting to get. """ # Skip this whole thing if we're running acceptance tests or if we're # developing and aren't interested in working on student identity # verification functionality. If you do want to work on it, you have to # explicitly enable these in your private settings. if settings.FEATURES.get('AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING'): return aes_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["FACE_IMAGE_AES_KEY"] aes_key = aes_key_str.decode("hex") path = self._get_path("face") buff = ContentFile(encrypt_and_encode(img_data, aes_key)) self._storage.save(path, buff)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _match_greater_than(search_base, attribute, value, candidates): matches = list() for entry in candidates: dn = entry.get("dn") if not dn.endswith(search_base): continue value_from_directory = entry.get("attributes").get(attribute) if str(value_from_directory) > str(value): entry["type"] = "searchResEntry" matches.append(entry) return matches
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def upload_photo_id_image(self, img_data): """ Upload an the user's photo ID image. `img_data` should be a raw bytestream of a PNG image. This method will take the data, encrypt it using a randomly generated AES key, encode it with base64 and save it to the storage backend. The random key is also encrypted using Software Secure's public RSA key and stored in our `photo_id_key` field. Yes, encoding it to base64 adds compute and disk usage without much real benefit, but that's what the other end of this API is expecting to get. """ # Skip this whole thing if we're running acceptance tests or if we're # developing and aren't interested in working on student identity # verification functionality. If you do want to work on it, you have to # explicitly enable these in your private settings. if settings.FEATURES.get('AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING'): # fake photo id key is set only for initial verification self.photo_id_key = 'fake-photo-id-key' self.save() return aes_key = random_aes_key() rsa_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["RSA_PUBLIC_KEY"] rsa_encrypted_aes_key = rsa_encrypt(aes_key, rsa_key_str) # Save this to the storage backend path = self._get_path("photo_id") buff = ContentFile(encrypt_and_encode(img_data, aes_key)) self._storage.save(path, buff) # Update our record fields self.photo_id_key = rsa_encrypted_aes_key.encode('base64') self.save()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _match_less_than_or_equal(search_base, attribute, value, candidates): matches = list() for entry in candidates: dn = entry.get("dn") if not dn.endswith(search_base): continue value_from_directory = entry.get("attributes").get(attribute) if str(value_from_directory) <= str(value): entry["type"] = "searchResEntry" matches.append(entry) return matches
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def submit(self, copy_id_photo_from=None): """ Submit our verification attempt to Software Secure for validation. This will set our status to "submitted" if the post is successful, and "must_retry" if the post fails. Keyword Arguments: copy_id_photo_from (SoftwareSecurePhotoVerification): If provided, re-send the ID photo data from this attempt. This is used for reverification, in which new face photos are sent with previously-submitted ID photos. """ try: response = self.send_request(copy_id_photo_from=copy_id_photo_from) if response.ok: self.submitted_at = now() self.status = "submitted" self.save() else: self.status = "must_retry" self.error_msg = response.text self.save() except Exception: # pylint: disable=broad-except log.exception( u'Software Secure submission failed for user %s, setting status to must_retry', self.user.username ) self.status = "must_retry" self.save()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _match_less_than(search_base, attribute, value, candidates): matches = list() for entry in candidates: dn = entry.get("dn") if not dn.endswith(search_base): continue value_from_directory = entry.get("attributes").get(attribute) if str(value_from_directory) < str(value): entry["type"] = "searchResEntry" matches.append(entry) return matches
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def parsed_error_msg(self): """ Parse the error messages we receive from SoftwareSecure Error messages are written in the form: `[{"photoIdReasons": ["Not provided"]}]` Returns: str[]: List of error messages. """ parsed_errors = [] error_map = { 'EdX name not provided': 'name_mismatch', 'Name mismatch': 'name_mismatch', 'Photo/ID Photo mismatch': 'photos_mismatched', 'ID name not provided': 'id_image_missing_name', 'Invalid Id': 'id_invalid', 'No text': 'id_invalid', 'Not provided': 'id_image_missing', 'Photo hidden/No photo': 'id_image_not_clear', 'Text not clear': 'id_image_not_clear', 'Face out of view': 'user_image_not_clear', 'Image not clear': 'user_image_not_clear', 'Photo not provided': 'user_image_missing', } try: messages = set() message_groups = json.loads(self.error_msg) for message_group in message_groups: messages = messages.union(set(*six.itervalues(message_group))) for message in messages: parsed_error = error_map.get(message) if parsed_error: parsed_errors.append(parsed_error) else: log.debug(u'Ignoring photo verification error message: %s', message) except Exception: # pylint: disable=broad-except log.exception(u'Failed to parse error message for SoftwareSecurePhotoVerification %d', self.pk) return parsed_errors
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _match_equal_to(search_base, attribute, value, candidates): matches = list() match_using_regex = False if "*" in value: match_using_regex = True #regex = check_escape(value) regex = value.replace('*', '.*') regex = "^{0}$".format(regex) for entry in candidates: dn = to_unicode(entry.get("dn")) if attribute not in entry.get("attributes") or not dn.endswith(search_base): continue values_from_directory = entry.get("attributes").get(attribute) if isinstance(values_from_directory, list): for item in values_from_directory: if attribute == "objectGUID": item = _convert_objectGUID(item) if match_using_regex: m = re.match(regex, str(item), re.I) if m: entry["type"] = "searchResEntry" matches.append(entry) else: if item == value: entry["type"] = "searchResEntry" matches.append(entry) else: if attribute == "objectGUID": values_from_directory = _convert_objectGUID(values_from_directory) if match_using_regex: m = re.match(regex, str(values_from_directory), re.I) if m: entry["type"] = "searchResEntry" matches.append(entry) else: # The value, which we compare is unicode, so we convert # the values_from_directory to unicode rather than str. if isinstance(values_from_directory, bytes): values_from_directory = values_from_directory.decode( "utf-8") elif type(values_from_directory) == int: values_from_directory = u"{0!s}".format(values_from_directory) if value == values_from_directory: entry["type"] = "searchResEntry" matches.append(entry) return matches
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def image_url(self, name, override_receipt_id=None): """ We dynamically generate this, since we want it the expiration clock to start when the message is created, not when the record is created. Arguments: name (str): Name of the image (e.g. "photo_id" or "face") Keyword Arguments: override_receipt_id (str): If provided, use this receipt ID instead of the ID for this attempt. This is useful for reverification where we need to construct a URL to a previously-submitted photo ID image. Returns: string: The expiring URL for the image. """ path = self._get_path(name, override_receipt_id=override_receipt_id) return self._storage.url(path)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _match_notequal_to(search_base, attribute, value, candidates): matches = list() match_using_regex = False if "*" in value: match_using_regex = True #regex = check_escape(value) regex = value.replace('*', '.*') regex = "^{0}$".format(regex) for entry in candidates: found = False dn = entry.get("dn") if not dn.endswith(search_base): continue values_from_directory = entry.get("attributes").get(attribute) if isinstance(values_from_directory, list): for item in values_from_directory: if attribute == "objectGUID": item = _convert_objectGUID(item) if match_using_regex: m = re.match(regex, str(item), re.I) if m: found = True else: if item == value: found = True if found is False: entry["type"] = "searchResEntry" matches.append(entry) else: if attribute == "objectGUID": values_from_directory = _convert_objectGUID(values_from_directory) if match_using_regex: m = re.match(regex, str(values_from_directory), re.I) if not m: entry["type"] = "searchResEntry" matches.append(entry) else: if str(value) != str(values_from_directory): entry["type"] = "searchResEntry" matches.append(entry) return matches
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _storage(self): """ Return the configured django storage backend. """ config = settings.VERIFY_STUDENT["SOFTWARE_SECURE"] # Default to the S3 backend for backward compatibility storage_class = config.get("STORAGE_CLASS", "storages.backends.s3boto.S3BotoStorage") storage_kwargs = config.get("STORAGE_KWARGS", {}) # Map old settings to the parameters expected by the storage backend if "AWS_ACCESS_KEY" in config: storage_kwargs["access_key"] = config["AWS_ACCESS_KEY"] if "AWS_SECRET_KEY" in config: storage_kwargs["secret_key"] = config["AWS_SECRET_KEY"] if "S3_BUCKET" in config: storage_kwargs["bucket"] = config["S3_BUCKET"] storage_kwargs["querystring_expire"] = self.IMAGE_LINK_DURATION return get_storage(storage_class, **storage_kwargs)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _parse_filter(): op = pyparsing.oneOf('! & |') lpar = pyparsing.Literal('(').suppress() rpar = pyparsing.Literal(')').suppress() k = pyparsing.Word(pyparsing.alphanums) # NOTE: We may need to expand on this list, but as this is not a real # LDAP server we should be OK. # Value to contain: # numbers, upper/lower case letters, astrisk, at symbol, minus, full # stop, backslash or a space v = pyparsing.Word(pyparsing.alphanums + "-*@.\\ äöü") rel = pyparsing.oneOf("= ~= >= <=") expr = pyparsing.Forward() atom = pyparsing.Group(lpar + op + expr + rpar) \ | pyparsing.Combine(lpar + k + rel + v + rpar) expr << atom + pyparsing.ZeroOrMore( expr ) return expr
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _get_path(self, prefix, override_receipt_id=None): """ Returns the path to a resource with this instance's `receipt_id`. If `override_receipt_id` is given, the path to that resource will be retrieved instead. This allows us to retrieve images submitted in previous attempts (used for reverification, where we send a new face photo with the same photo ID from a previous attempt). """ receipt_id = self.receipt_id if override_receipt_id is None else override_receipt_id return os.path.join(prefix, receipt_id)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _deDuplicate(results): found = dict() deDuped = list() for entry in results: dn = entry.get("dn") if not dn in found: found[dn] = 1 deDuped.append(entry) return deDuped
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _encrypted_user_photo_key_str(self): """ Software Secure needs to have both UserPhoto and PhotoID decrypted in the same manner. So even though this is going to be the same for every request, we're also using RSA encryption to encrypt the AES key for faces. """ face_aes_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["FACE_IMAGE_AES_KEY"] face_aes_key = face_aes_key_str.decode("hex") rsa_key_str = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["RSA_PUBLIC_KEY"] rsa_encrypted_face_aes_key = rsa_encrypt(face_aes_key, rsa_key_str) return rsa_encrypted_face_aes_key.encode("base64")
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _invert_results(self, candidates): inverted_candidates = list(self.directory) for candidate in candidates: try: inverted_candidates.remove(candidate) except ValueError: pass return inverted_candidates
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def create_request(self, copy_id_photo_from=None): """ Construct the HTTP request to the photo verification service. Keyword Arguments: copy_id_photo_from (SoftwareSecurePhotoVerification): If provided, re-send the ID photo data from this attempt. This is used for reverification, in which new face photos are sent with previously-submitted ID photos. Returns: tuple of (header, body), where both `header` and `body` are dictionaries. """ access_key = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_ACCESS_KEY"] secret_key = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_SECRET_KEY"] scheme = "https" if settings.HTTPS == "on" else "http" callback_url = "{}://{}{}".format( scheme, settings.SITE_NAME, reverse('verify_student_results_callback') ) # If we're copying the photo ID image from a previous verification attempt, # then we need to send the old image data with the correct image key. photo_id_url = ( self.image_url("photo_id") if copy_id_photo_from is None else self.image_url("photo_id", override_receipt_id=copy_id_photo_from.receipt_id) ) photo_id_key = ( self.photo_id_key if copy_id_photo_from is None else copy_id_photo_from.photo_id_key ) body = { "EdX-ID": str(self.receipt_id), "ExpectedName": self.name, "PhotoID": photo_id_url, "PhotoIDKey": photo_id_key, "SendResponseTo": callback_url, "UserPhoto": self.image_url("face"), "UserPhotoKey": self._encrypted_user_photo_key_str(), } headers = { "Content-Type": "application/json", "Date": formatdate(timeval=None, localtime=False, usegmt=True) } _message, _sig, authorization = generate_signed_message( "POST", headers, body, access_key, secret_key ) headers['Authorization'] = authorization return headers, body
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _search_not(self, base, search_filter, candidates=None): # Create empty candidates list as we need to use self.directory for # each search candidates = list() this_filter = list() index = 0 search_filter.remove("!") for condition in search_filter: if not isinstance(condition, list): this_filter.append(condition) index +=1 # Remove this_filter items from search_filter list for condition in this_filter: search_filter.remove(condition) try: search_filter = list(search_filter[0]) for sub_filter in search_filter: if not isinstance(sub_filter, list): candidates = self.operation.get(sub_filter)(base, search_filter, candidates) else: candidates = self.operation.get(sub_filter[0])(base, sub_filter, candidates) except IndexError: pass candidates = self._invert_results(candidates) for item in this_filter: if ">=" in item: k, v = item.split(">=") candidates = Connection._match_less_than(base, k, v, self.directory) elif "<=" in item: k, v = item.split("<=") candidates = Connection._match_greater_than(base, k, v, self.directory) # Emulate AD functionality, same as "=" elif "~=" in item: k, v = item.split("~=") candidates = Connection._match_notequal_to(base, k, v, self.directory) elif "=" in item: k, v = item.split("=") candidates = Connection._match_notequal_to(base, k, v, self.directory) return candidates
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def request_message_txt(self): """ This is the body of the request we send across. This is never actually used in the code, but exists for debugging purposes -- you can call `print attempt.request_message_txt()` on the console and get a readable rendering of the request that would be sent across, without actually sending anything. """ headers, body = self.create_request() header_txt = "\n".join( u"{}: {}".format(h, v) for h, v in sorted(headers.items()) ) body_txt = json.dumps(body, indent=2, sort_keys=True, ensure_ascii=False).encode('utf-8') return header_txt + "\n\n" + body_txt
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _search_and(self, base, search_filter, candidates=None): # Load the data from the directory, if we aren't passed any if candidates == [] or candidates is None: candidates = self.directory this_filter = list() index = 0 search_filter.remove("&") for condition in search_filter: if not isinstance(condition, list): this_filter.append(condition) index +=1 # Remove this_filter items from search_filter list for condition in this_filter: search_filter.remove(condition) try: search_filter = list(search_filter[0]) for sub_filter in search_filter: if not isinstance(sub_filter, list): candidates = self.operation.get(sub_filter)(base, search_filter, candidates) else: candidates = self.operation.get(sub_filter[0])(base, sub_filter, candidates) except IndexError: pass for item in this_filter: if ">=" in item: k, v = item.split(">=") candidates = Connection._match_greater_than_or_equal(base, k, v, candidates) elif "<=" in item: k, v = item.split("<=") candidates = Connection._match_less_than_or_equal(base, k, v, candidates) # Emulate AD functionality, same as "=" elif "~=" in item: k, v = item.split("~=") candidates = Connection._match_equal_to(base, k, v, candidates) elif "=" in item: k, v = item.split("=") candidates = Connection._match_equal_to(base, k, v, candidates) return candidates
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def send_request(self, copy_id_photo_from=None): """ Assembles a submission to Software Secure and sends it via HTTPS. Keyword Arguments: copy_id_photo_from (SoftwareSecurePhotoVerification): If provided, re-send the ID photo data from this attempt. This is used for reverification, in which new face photos are sent with previously-submitted ID photos. Returns: request.Response """ # If AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING is True, we want to # skip posting anything to Software Secure. We actually don't even # create the message because that would require encryption and message # signing that rely on settings.VERIFY_STUDENT values that aren't set # in dev. So we just pretend like we successfully posted if settings.FEATURES.get('AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING'): fake_response = requests.Response() fake_response.status_code = 200 return fake_response headers, body = self.create_request(copy_id_photo_from=copy_id_photo_from) response = requests.post( settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_URL"], headers=headers, data=json.dumps(body, indent=2, sort_keys=True, ensure_ascii=False).encode('utf-8'), verify=False ) log.info(u"Sent request to Software Secure for receipt ID %s.", self.receipt_id) if copy_id_photo_from is not None: log.info( ( u"Software Secure attempt with receipt ID %s used the same photo ID " u"data as the receipt with ID %s" ), self.receipt_id, copy_id_photo_from.receipt_id ) log.debug("Headers:\n{}\n\n".format(headers)) log.debug("Body:\n{}\n\n".format(body)) log.debug(u"Return code: {}".format(response.status_code)) log.debug(u"Return message:\n\n{}\n\n".format(response.text)) return response
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _search_or(self, base, search_filter, candidates=None): # Create empty candidates list as we need to use self.directory for # each search candidates = list() this_filter = list() index = 0 search_filter.remove("|") for condition in search_filter: if not isinstance(condition, list): this_filter.append(condition) index +=1 # Remove this_filter items from search_filter list for condition in this_filter: search_filter.remove(condition) try: search_filter = list(search_filter[0]) for sub_filter in search_filter: if not isinstance(sub_filter, list): candidates += self.operation.get(sub_filter)(base, search_filter, candidates) else: candidates += self.operation.get(sub_filter[0])(base, sub_filter, candidates) except IndexError: pass for item in this_filter: if ">=" in item: k, v = item.split(">=") candidates += Connection._match_greater_than_or_equal(base, k, v, self.directory) elif "<=" in item: k, v = item.split("<=") candidates += Connection._match_less_than_or_equal(base, k, v, self.directory) # Emulate AD functionality, same as "=" elif "~=" in item: k, v = item.split("~=") candidates += Connection._match_equal_to(base, k, v, self.directory) elif "=" in item: k, v = item.split("=") candidates += Connection._match_equal_to(base, k, v, self.directory) return candidates
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def search(self, search_base=None, search_scope=None, search_filter=None, attributes=None, paged_size=5, size_limit=0, paged_cookie=None): s_filter = list() candidates = list() self.response = list() self.result = dict() try: if isinstance(search_filter, bytes): # We need to convert to unicode otherwise pyparsing will not # find the u"ö" search_filter = to_unicode(search_filter) expr = Connection._parse_filter() s_filter = expr.parseString(search_filter).asList()[0] except pyparsing.ParseBaseException as exx: # Just for debugging purposes s = "{!s}".format(exx) for item in s_filter: if item[0] in self.operation: candidates = self.operation.get(item[0])(search_base, s_filter) self.response = Connection._deDuplicate(candidates) return True
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def set_deadline(cls, course_key, deadline, is_explicit=False): """ Configure the verification deadline for a course. If `deadline` is `None`, then the course will have no verification deadline. In this case, users will be able to verify for the course at any time. Arguments: course_key (CourseKey): Identifier for the course. deadline (datetime or None): The verification deadline. """ if deadline is None: VerificationDeadline.objects.filter(course_key=course_key).delete() else: record, created = VerificationDeadline.objects.get_or_create( course_key=course_key, defaults={"deadline": deadline, "deadline_is_explicit": is_explicit} ) if not created: record.deadline = deadline record.deadline_is_explicit = is_explicit record.save()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def unbind(self): return True
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def deadlines_for_courses(cls, course_keys): """ Retrieve verification deadlines for particular courses. Arguments: course_keys (list): List of `CourseKey`s. Returns: dict: Map of course keys to datetimes (verification deadlines) """ all_deadlines = cache.get(cls.ALL_DEADLINES_CACHE_KEY) if all_deadlines is None: all_deadlines = { deadline.course_key: deadline.deadline for deadline in VerificationDeadline.objects.all() } cache.set(cls.ALL_DEADLINES_CACHE_KEY, all_deadlines) return { course_key: all_deadlines[course_key] for course_key in course_keys if course_key in all_deadlines }
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self): self._calls = CallList() self._server_mock = None self.directory = [] self.exception = None self.reset()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def deadline_for_course(cls, course_key): """ Retrieve the verification deadline for a particular course. Arguments: course_key (CourseKey): The identifier for the course. Returns: datetime or None """ try: deadline = cls.objects.get(course_key=course_key) return deadline.deadline except cls.DoesNotExist: return None
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def reset(self): self._calls.reset()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def setLDAPDirectory(self, directory=None): if directory is None: self.directory = [] else: try: with open(DIRECTORY, 'w+') as f: f.write(str(directory)) self.directory = directory except OSError as e: raise
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def set_exception(self, exc=True): self.exception = exc
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _load_data(self, directory): try: with open(directory, 'r') as f: data = f.read() return literal_eval(data) except OSError as e: raise
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def calls(self): return self._calls
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __enter__(self): self.start()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __exit__(self, *args): self.stop() self.reset()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def activate(self, func): evaldict = {'ldap3mock': self, 'func': func} return get_wrapped(func, _wrapper_template, evaldict)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _on_Server(self, host, port, use_ssl, connect_timeout, get_info=None, tls=None): # mangle request packet return "FakeServerObject"
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _on_Connection(self, server, user, password, auto_bind=None, client_strategy=None, authentication=None, check_names=None, auto_referrals=None, receive_timeout=None): """ We need to create a Connection object with methods: add() modify() search() unbind() and object response """ # Raise an exception, if we are told to do so if self.exception: raise Exception("LDAP request failed") # check the password correct_password = False # Anonymous bind # Reload the directory just in case a change has been made to # user credentials self.directory = self._load_data(DIRECTORY) if authentication == ldap3.ANONYMOUS and user == "": correct_password = True for entry in self.directory: if to_unicode(entry.get("dn")) == user: pw = entry.get("attributes").get("userPassword") # password can be unicode if to_bytes(pw) == to_bytes(password): correct_password = True elif pw.startswith('{SSHA}'): correct_password = ldap_salted_sha1.verify(password, pw) else: correct_password = False self.con_obj = Connection(self.directory) self.con_obj.bound = correct_password return self.con_obj
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def unbound_on_Server(host, port, use_ssl, connect_timeout, *a, **kwargs): return self._on_Server(host, port, use_ssl, connect_timeout, *a, **kwargs)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def unbound_on_Connection(server, user, password, auto_bind, client_strategy, authentication, check_names, auto_referrals, *a, **kwargs): return self._on_Connection(server, user, password, auto_bind, client_strategy, authentication, check_names, auto_referrals, *a, **kwargs)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def stop(self): self._patcher.stop() self._patcher2.stop() self._server_mock = None
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def get_server_mock(self): return self._server_mock
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def setUp(self): entry_Li = ComputedEntry("Li", -1.90753119) with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "LiTiO2_batt.json")) as f: entries_LTO = json.load(f, cls=MontyDecoder) self.ie_LTO = InsertionElectrode.from_entries(entries_LTO, entry_Li) with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "FeF3_batt.json")) as fid: entries = json.load(fid, cls=MontyDecoder) self.ce_FF = ConversionElectrode.from_composition_and_entries(Composition("FeF3"), entries)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self): """ Every authenticator has to have a name :param name: """ super().__init__()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def testName(self): plotter = VoltageProfilePlotter(xaxis="frac_x") plotter.add_electrode(self.ie_LTO, "LTO insertion") plotter.add_electrode(self.ce_FF, "FeF3 conversion") self.assertIsNotNone(plotter.get_plot_data(self.ie_LTO)) self.assertIsNotNone(plotter.get_plot_data(self.ce_FF))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def testPlotly(self): plotter = VoltageProfilePlotter(xaxis="frac_x") plotter.add_electrode(self.ie_LTO, "LTO insertion") plotter.add_electrode(self.ce_FF, "FeF3 conversion") fig = plotter.get_plotly_figure() self.assertEqual(fig.layout.xaxis.title.text, "Atomic Fraction of Li") plotter = VoltageProfilePlotter(xaxis="x_form") plotter.add_electrode(self.ce_FF, "FeF3 conversion") fig = plotter.get_plotly_figure() self.assertEqual(fig.layout.xaxis.title.text, "x in Li<sub>x</sub>FeF3") plotter.add_electrode(self.ie_LTO, "LTO insertion") fig = plotter.get_plotly_figure() self.assertEqual(fig.layout.xaxis.title.text, "x Workion Ion per Host F.U.")
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _no_ssl_required_on_debug(app, **kwargs): if app.debug or app.testing: os.environ['AUTHLIB_INSECURE_TRANSPORT'] = '1'
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, head): self.head = head self.lsize = 0 while head.next: head = head.next self.lsize += 1 self.m1_idx = None self.m2_idx = None if self.lsize > self._largesize: self.m1_idx = self.lsize / 3 # start from 1/3 self.m1 = self._getN(self.m1_idx) self.m2_idx = self.m1_idx * 2 # start from 2/3 self.m2 = self._getN(self.m2_idx)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _getN(self, n): n -= 1 p = self.head while n: p = p.next n -= 1 return p
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def _get(delta, start): p = start while delta: p = p.next delta -= 1 return p.val
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def main(): parser = argparse.ArgumentParser() parser.add_argument("day", help="The day of the results, with format yyyymmdd") args = parser.parse_args() install_autopkgtest_results_formatter() with tempfile.TemporaryDirectory(dir=os.environ.get("HOME")) as temp_dir: clone_results_repo(temp_dir) format_results(temp_dir, ACTIVE_DISTROS, args.day) commit_and_push(temp_dir, args.day)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, parent, window): self._parent = parent self._window = window self._application = self._parent._application # create user interface self._container = gtk.VBox(False, 5) self._controls = gtk.HBox(False, 5) separator = gtk.HSeparator() # pack interface self._container.pack_end(separator, False, False, 0) self._container.pack_end(self._controls, False, False, 0)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def install_autopkgtest_results_formatter(): subprocess.check_call( ["sudo", "snap", "install", "autopkgtest-results-formatter", "--edge"] )
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def can_handle(self, uri): """Returns boolean denoting if specified URI can be handled by this extension""" return False
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def clone_results_repo(dest_dir): subprocess.check_call( ["git", "clone", "https://github.com/elopio/autopkgtest-results.git", dest_dir] )
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def get_container(self): """Return container widget""" return self._container
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def format_results(dest_dir, distros, day): subprocess.check_call( [ "/snap/bin/autopkgtest-results-formatter", "--destination", dest_dir, "--distros", *distros, "--day", day, ] )
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def get_information(self): """Returns information about extension""" icon = None name = None return icon, name
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def commit_and_push(repo_dir, day): subprocess.check_call( ["git", "config", "--global", "user.email", "u1test+m-o@canonical.com"] ) subprocess.check_call(["git", "config", "--global", "user.name", "snappy-m-o"]) subprocess.check_call(["git", "-C", repo_dir, "add", "--all"]) subprocess.check_call( [ "git", "-C", repo_dir, "commit", "--message", "Add the results for {}".format(day), ] ) subprocess.check_call( [ "git", "-C", repo_dir, "push", "https://{GH_TOKEN}@github.com/elopio/autopkgtest-results.git".format( GH_TOKEN=os.environ.get("GH_TOKEN_PPA_AUTOPKGTEST_RESULTS") ), ] )
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def unmount(self, uri): """Method called by the mount manager for unmounting the selected URI""" pass
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def focus_object(self): """Method called by the mount manager for focusing main object""" pass
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, gan=None, config=None, trainer=None): super().__init__(config=config, gan=gan, trainer=trainer) self.d_grads = None self.g_grads = None
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def main(): # Contingency Table from Wilks (2011) Table 8.3 table = np.array([[50, 91, 71], [47, 2364, 170], [54, 205, 3288]]) mct = MulticlassContingencyTable(table, n_classes=table.shape[0], class_names=np.arange(table.shape[0]).astype(str)) print(mct.peirce_skill_score()) print(mct.gerrity_score())
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def gradients(self, d_grads, g_grads): if self.d_grads is None: self.d_grads = [torch.zeros_like(_g) for _g in d_grads] self.g_grads = [torch.zeros_like(_g) for _g in g_grads]
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, table=None, n_classes=2, class_names=("1", "0")): self.table = table self.n_classes = n_classes self.class_names = class_names if table is None: self.table = np.zeros((self.n_classes, self.n_classes), dtype=int)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __add__(self, other): assert self.n_classes == other.n_classes, "Number of classes does not match" return MulticlassContingencyTable(self.table + other.table, n_classes=self.n_classes, class_names=self.class_names)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def peirce_skill_score(self): """ Multiclass Peirce Skill Score (also Hanssen and Kuipers score, True Skill Score) """ n = float(self.table.sum()) nf = self.table.sum(axis=1) no = self.table.sum(axis=0) correct = float(self.table.trace()) return (correct / n - (nf * no).sum() / n ** 2) / (1 - (no * no).sum() / n ** 2)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def gerrity_score(self): """ Gerrity Score, which weights each cell in the contingency table by its observed relative frequency. :return: """ k = self.table.shape[0] n = float(self.table.sum()) p_o = self.table.sum(axis=0) / n p_sum = np.cumsum(p_o)[:-1] a = (1.0 - p_sum) / p_sum s = np.zeros(self.table.shape, dtype=float) for (i, j) in np.ndindex(*s.shape): if i == j: s[i, j] = 1.0 / (k - 1.0) * (np.sum(1.0 / a[0:j]) + np.sum(a[j:k - 1])) elif i < j: s[i, j] = 1.0 / (k - 1.0) * (np.sum(1.0 / a[0:i]) - (j - i) + np.sum(a[j:k - 1])) else: s[i, j] = s[j, i] return np.sum(self.table / float(self.table.sum()) * s)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def heidke_skill_score(self): n = float(self.table.sum()) nf = self.table.sum(axis=1) no = self.table.sum(axis=0) correct = float(self.table.trace()) return (correct / n - (nf * no).sum() / n ** 2) / (1 - (nf * no).sum() / n ** 2)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def git_checkout(git_url, git_branch=None, git_tag=None, git_hash=None): git_dst = tempfile.mkdtemp() g = GitManager(url=git_url, git_dst=git_dst, git_branch=git_branch, git_tag=git_tag, git_hash=git_hash) g.run() shutil.rmtree(git_dst)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_git_tag(): """ Test checkout w/ Tag """ git_checkout(git_url='https://github.com/voltgrid/voltgrid-pie.git', git_branch=None, git_tag='v0.1.0')
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_git_branch(): """ Test checkout w/ Branch """ git_checkout(git_url='https://github.com/voltgrid/voltgrid-pie.git', git_branch='master', git_tag=None)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_make_gym_venv_nostack(name, num_envs, state_shape, reward_scale): seed = 0 frame_op = None frame_op_len = None venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale) venv.reset() for i in range(5): state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs) assert isinstance(state, np.ndarray) assert state.shape == (num_envs,) + state_shape assert isinstance(reward, np.ndarray) assert reward.shape == (num_envs,) assert isinstance(done, np.ndarray) assert done.shape == (num_envs,) assert len(info) == num_envs venv.close()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def compute_rbf_kernel_matrix(X): """Compute the RBF kernel matrix with sigma2 as the median pairwise distance. """ sigma2 = np.median(pairwise_distances(X, metric='euclidean'))**2 K = pairwise_kernels(X, X, metric='rbf', gamma=1.0/sigma2, n_jobs=-1) return K
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_make_gym_concat(name, num_envs, state_shape, reward_scale): seed = 0 frame_op = 'concat' # used for image, or for concat vector frame_op_len = 4 venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale) venv.reset() for i in range(5): state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs) assert isinstance(state, np.ndarray) stack_shape = (num_envs, frame_op_len * state_shape[0],) + state_shape[1:] assert state.shape == stack_shape assert isinstance(reward, np.ndarray) assert reward.shape == (num_envs,) assert isinstance(done, np.ndarray) assert done.shape == (num_envs,) assert len(info) == num_envs venv.close()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def balanced_accuracy_scoring(clf, X, y): """Scoring function that computes the balanced accuracy to be used internally in the cross-validation procedure. """ y_pred = clf.predict(X) conf_mat = confusion_matrix(y, y_pred) bal_acc = 0. for i in range(len(conf_mat)): bal_acc += (float(conf_mat[i, i])) / np.sum(conf_mat[i]) bal_acc /= len(conf_mat) return bal_acc
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_make_gym_stack(name, num_envs, state_shape, reward_scale): seed = 0 frame_op = 'stack' # used for rnn frame_op_len = 4 venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale) venv.reset() for i in range(5): state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs) assert isinstance(state, np.ndarray) stack_shape = (num_envs, frame_op_len,) + state_shape assert state.shape == stack_shape assert isinstance(reward, np.ndarray) assert reward.shape == (num_envs,) assert isinstance(done, np.ndarray) assert done.shape == (num_envs,) assert len(info) == num_envs venv.close()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def compute_svm_cv(K, y, C=100.0, n_folds=5, scoring=balanced_accuracy_scoring): """Compute cross-validated score of SVM with given precomputed kernel. """ cv = StratifiedKFold(y, n_folds=n_folds) clf = SVC(C=C, kernel='precomputed', class_weight='auto') scores = cross_val_score(clf, K, y, scoring=scoring, cv=cv) return scores.mean()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def compute_svm_subjects(K, y, n_folds=5): """ """ cv = KFold(len(K)/2, n_folds) scores = np.zeros(n_folds) for i, (train, test) in enumerate(cv): train_ids = np.concatenate((train, len(K)/2+train)) test_ids = np.concatenate((test, len(K)/2+test)) clf = SVC(kernel='precomputed') clf.fit(K[train_ids, :][:, train_ids], y[train_ids]) scores[i] = clf.score(K[test_ids, :][:, train_ids], y[test_ids]) return scores.mean()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def permutation_subjects(y): """Permute class labels of Contextual Disorder dataset. """ y_perm = np.random.randint(0, 2, len(y)/2) y_perm = np.concatenate((y_perm, np.logical_not(y_perm).astype(int))) return y_perm
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def permutation_subjects_ktst(y): """Permute class labels of Contextual Disorder dataset for KTST. """ yp = np.random.randint(0, 2, len(y)/2) yp = np.concatenate((yp, np.logical_not(yp).astype(int))) y_perm = np.arange(len(y)) for i in range(len(y)/2): if yp[i] == 1: y_perm[i] = len(y)/2+i y_perm[len(y)/2+i] = i return y_perm
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def compute_svm_score_nestedCV(K, y, n_folds, scoring=balanced_accuracy_scoring, random_state=None, param_grid=[{'C': np.logspace(-5, 5, 25)}]): """Compute cross-validated score of SVM using precomputed kernel. """ cv = StratifiedKFold(y, n_folds=n_folds, shuffle=True, random_state=random_state) scores = np.zeros(n_folds) for i, (train, test) in enumerate(cv): cvclf = SVC(kernel='precomputed') y_train = y[train] cvcv = StratifiedKFold(y_train, n_folds=n_folds, shuffle=True, random_state=random_state) clf = GridSearchCV(cvclf, param_grid=param_grid, scoring=scoring, cv=cvcv, n_jobs=1) clf.fit(K[train, :][:, train], y_train) # print clf.best_params_ scores[i] = clf.score(K[test, :][:, train], y[test]) return scores.mean()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def apply_svm(K, y, n_folds=5, iterations=10000, subjects=False, verbose=True, random_state=None): """ Compute the balanced accuracy, its null distribution and the p-value. Parameters: ---------- K: array-like Kernel matrix y: array_like class labels cv: Number of folds in the stratified cross-validation verbose: bool Verbosity Returns: ------- acc: float Average balanced accuracy. acc_null: array Null distribution of the balanced accuracy. p_value: float p-value """ # Computing the accuracy param_grid = [{'C': np.logspace(-5, 5, 20)}] if subjects: acc = compute_svm_subjects(K, y, n_folds) else: acc = compute_svm_score_nestedCV(K, y, n_folds, param_grid=param_grid, random_state=random_state) if verbose: print("Mean balanced accuracy = %s" % (acc)) print("Computing the null-distribution.") # Computing the null-distribution # acc_null = np.zeros(iterations) # for i in range(iterations): # if verbose and (i % 1000) == 0: # print(i), # stdout.flush() # y_perm = np.random.permutation(y) # acc_null[i] = compute_svm_score_nestedCV(K, y_perm, n_folds, # param_grid=param_grid) # if verbose: # print '' # Computing the null-distribution if subjects: yis = [permutation_subjects(y) for i in range(iterations)] acc_null = Parallel(n_jobs=-1)(delayed(compute_svm_subjects)(K, yis[i], n_folds) for i in range(iterations)) else: yis = [np.random.permutation(y) for i in range(iterations)] acc_null = Parallel(n_jobs=-1)(delayed(compute_svm_score_nestedCV)(K, yis[i], n_folds, scoring=balanced_accuracy_scoring, param_grid=param_grid) for i in range(iterations)) # acc_null = Parallel(n_jobs=-1)(delayed(compute_svm_cv)(K, yis[i], C=100., n_folds=n_folds) for i in range(iterations)) p_value = max(1.0 / iterations, (acc_null > acc).sum() / float(iterations)) if verbose: print("p-value ~= %s \t (resolution : %s)" % (p_value, 1.0/iterations)) return acc, acc_null, p_value
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def apply_ktst(K, y, iterations=10000, subjects=False, verbose=True): """ Compute MMD^2_u, its null distribution and the p-value of the kernel two-sample test. Parameters: ---------- K: array-like Kernel matrix y: array_like class labels verbose: bool Verbosity Returns: ------- mmd2u: float MMD^2_u value. acc_null: array Null distribution of the MMD^2_u p_value: float p-value """ assert len(np.unique(y)) == 2, 'KTST only works on binary problems' # Assuming that the first m rows of the kernel matrix are from one # class and the other n rows from the second class. m = len(y[y == 0]) n = len(y[y == 1]) mmd2u = MMD2u(K, m, n) if verbose: print("MMD^2_u = %s" % mmd2u) print("Computing the null distribution.") if subjects: perms = [permutation_subjects_ktst(y) for i in range(iterations)] mmd2u_null = compute_null_distribution_given_permutations(K, m, n, perms, iterations) else: mmd2u_null = compute_null_distribution(K, m, n, iterations, verbose=verbose) p_value = max(1.0/iterations, (mmd2u_null > mmd2u).sum() / float(iterations)) if verbose: print("p-value ~= %s \t (resolution : %s)" % (p_value, 1.0/iterations)) return mmd2u, mmd2u_null, p_value
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_login(self, mock_login_with_token, mock_input, mock_open_url): quilt3.login() url = quilt3.session.get_registry_url() mock_open_url.assert_called_with(f'{url}/login') mock_login_with_token.assert_called_with('123456')
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def decode(value): if isinstance(value, bytes): value = value.decode(errors="surrogateescape") for char in ("\\", "\n", "\t"): value = value.replace( char.encode(encoding="unicode-escape").decode(), char ) return value
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def test_login_with_token(self, mock_save_credentials, mock_save_auth): url = quilt3.session.get_registry_url() mock_auth = dict( refresh_token='refresh-token', access_token='access-token', expires_at=123456789 ) self.requests_mock.add( responses.POST, f'{url}/api/token', json=mock_auth, status=200 ) self.requests_mock.add( responses.GET, f'{url}/api/auth/get_credentials', json=dict( AccessKeyId='access-key', SecretAccessKey='secret-key', SessionToken='session-token', Expiration="2019-05-28T23:58:07+00:00" ), status=200 ) quilt3.session.login_with_token('123456') mock_save_auth.assert_called_with({url: mock_auth}) mock_save_credentials.assert_called_with(dict( access_key='access-key', secret_key='secret-key', token='session-token', expiry_time="2019-05-28T23:58:07+00:00" ))
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def encode(value): if isinstance(value, bytes): value = value.decode(errors="surrogateescape") for char in ("\\", "\n", "\t"): value = value.replace( char, char.encode(encoding="unicode-escape").decode() ) return value
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def format_date(date): return date.replace(tzinfo=datetime.timezone.utc, microsecond=0).isoformat()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def deserialize(self, value): """Cast raw string to appropriate type.""" return decode(value)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def serialize(self, value, display=False): """Convert value back to string for saving.""" if value is None: return "" return str(value)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def deserialize(self, value): return DeprecatedValue()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def serialize(self, value, display=False): return DeprecatedValue()
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, optional=False, choices=None): self._required = not optional self._choices = choices
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def deserialize(self, value): value = decode(value).strip() validators.validate_required(value, self._required) if not value: return None validators.validate_choice(value, self._choices) return value
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def serialize(self, value, display=False): if value is None: return "" return encode(value)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__(self, optional=False, choices=None): self._required = not optional self._choices = None # Choices doesn't make sense for secrets
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def serialize(self, value, display=False): if value is not None and display: return "********" return super().serialize(value, display)
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def __init__( self, minimum=None, maximum=None, choices=None, optional=False ): self._required = not optional self._minimum = minimum self._maximum = maximum self._choices = choices
def get_next_id(self): try: query = {'_id': 'last_id'} update = {'$inc': {'id': 1}} fn = self.db.internal.find_and_modify row = fn(query, update, upsert=True, new=True) except Exception as e: raise DatabaseException(e) return row['id']
def deserialize(self, value): value = decode(value) validators.validate_required(value, self._required) if not value: return None value = int(value) validators.validate_choice(value, self._choices) validators.validate_minimum(value, self._minimum) validators.validate_maximum(value, self._maximum) return value