buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
async def update_group_category( return {} async def delete_group_category(self, group_id, requester_user_id, category_id): """Delete a group category""" await self.check_group_is_ours( group_id, requester_user_id, and_exists=True, and_is_admin=requester_user_id
async def update_group_category( return {} async def delete_group_category( self, group_id: str, requester_user_id: str, category_id: str ) -> JsonDict: """Delete a group category""" await self.check_group_is_ours( group_id, requester_user_id, and_exists=True, and_i...
async def delete_group_category(self, group_id, requester_user_id, category_id): return {} async def update_group_role(self, group_id, requester_user_id, role_id, content): """Add/update a role in a group""" await self.check_group_is_ours( group_id, requester_user_id, and_exist...
async def delete_group_category(self, group_id, requester_user_id, category_id): return {} async def update_group_role( self, group_id: str, requester_user_id: str, role_id: str, content: JsonDict ) -> JsonDict: """Add/update a role in a group""" await self.check_group_is_ours(...
async def update_group_role(self, group_id, requester_user_id, role_id, content) return {} async def delete_group_role(self, group_id, requester_user_id, role_id): """Remove role from group""" await self.check_group_is_ours( group_id, requester_user_id, and_exists=True, and_is_...
async def update_group_role(self, group_id, requester_user_id, role_id, content) return {} async def delete_group_role( self, group_id: str, requester_user_id: str, role_id: str ) -> JsonDict: """Remove role from group""" await self.check_group_is_ours( group_id, re...
async def delete_group_role(self, group_id, requester_user_id, role_id): return {} async def update_group_summary_user( self, group_id, requester_user_id, user_id, role_id, content ): """Add/update a users entry in the group summary""" await self.check_group_is_ours( ...
async def delete_group_role(self, group_id, requester_user_id, role_id): return {} async def update_group_summary_user( self, group_id: str, requester_user_id: str, user_id: str, role_id: str, content: JsonDict, ) -> JsonDict: """Add/update a user...
async def update_group_summary_user( return {} async def delete_group_summary_user( self, group_id, requester_user_id, user_id, role_id ): """Remove a user from the group summary""" await self.check_group_is_ours( group_id, requester_user_id, and_exists=True, and_is_...
async def update_group_summary_user( return {} async def delete_group_summary_user( self, group_id: str, requester_user_id: str, user_id: str, role_id: str ) -> JsonDict: """Remove a user from the group summary""" await self.check_group_is_ours( group_id, requester_u...
async def delete_group_summary_user( return {} async def update_group_profile(self, group_id, requester_user_id, content): """Update the group profile""" await self.check_group_is_ours( group_id, requester_user_id, and_exists=True, and_is_admin=requester_user_id
async def delete_group_summary_user( return {} async def update_group_profile( self, group_id: str, requester_user_id: str, content: JsonDict ) -> None: """Update the group profile""" await self.check_group_is_ours( group_id, requester_user_id, and_exists=True, and_...
async def update_group_profile(self, group_id, requester_user_id, content): await self.store.update_group_profile(group_id, profile) async def add_room_to_group(self, group_id, requester_user_id, room_id, content): """Add room to group""" RoomID.from_string(room_id) # Ensure valid room id...
async def update_group_profile(self, group_id, requester_user_id, content): await self.store.update_group_profile(group_id, profile) async def add_room_to_group( self, group_id: str, requester_user_id: str, room_id: str, content: JsonDict ) -> JsonDict: """Add room to group""" ...
async def add_room_to_group(self, group_id, requester_user_id, room_id, content) return {} async def update_room_in_group( self, group_id, requester_user_id, room_id, config_key, content ): """Update room in group""" RoomID.from_string(room_id) # Ensure valid room id
async def add_room_to_group(self, group_id, requester_user_id, room_id, content) return {} async def update_room_in_group( self, group_id: str, requester_user_id: str, room_id: str, config_key: str, content: JsonDict, ) -> JsonDict: """Update room...
async def update_room_in_group( return {} async def remove_room_from_group(self, group_id, requester_user_id, room_id): """Remove room from group""" await self.check_group_is_ours( group_id, requester_user_id, and_exists=True, and_is_admin=requester_user_id
async def update_room_in_group( return {} async def remove_room_from_group( self, group_id: str, requester_user_id: str, room_id: str ) -> JsonDict: """Remove room from group""" await self.check_group_is_ours( group_id, requester_user_id, and_exists=True, and_is_adm...
async def remove_room_from_group(self, group_id, requester_user_id, room_id): return {} async def invite_to_group(self, group_id, user_id, requester_user_id, content): """Invite user to group""" group = await self.check_group_is_ours( group_id, requester_user_id, and_exists=Tr...
async def remove_room_from_group(self, group_id, requester_user_id, room_id): return {} async def invite_to_group( self, group_id: str, user_id: str, requester_user_id: str, content: JsonDict ) -> JsonDict: """Invite user to group""" group = await self.check_group_is_ours( ...
async def invite_to_group(self, group_id, user_id, requester_user_id, content): if self.hs.is_mine_id(user_id): groups_local = self.hs.get_groups_local_handler() res = await groups_local.on_invite(group_id, user_id, content) local_attestation = None else:
async def invite_to_group(self, group_id, user_id, requester_user_id, content): if self.hs.is_mine_id(user_id): groups_local = self.hs.get_groups_local_handler() assert isinstance( groups_local, GroupsLocalHandler ), "Workers cannot invites users to groups." ...
async def invite_to_group(self, group_id, user_id, requester_user_id, content): local_attestation=local_attestation, remote_attestation=remote_attestation, ) elif res["state"] == "invite": await self.store.add_group_invite(group_id, user_id) re...
async def invite_to_group(self, group_id, user_id, requester_user_id, content): local_attestation=local_attestation, remote_attestation=remote_attestation, ) return {"state": "join"} elif res["state"] == "invite": await self.store.add_group_inv...
async def invite_to_group(self, group_id, user_id, requester_user_id, content): else: raise SynapseError(502, "Unknown state returned by HS") async def _add_user(self, group_id, user_id, content): """Add a user to a group based on a content dict. See accept_invite, join_group. ...
async def invite_to_group(self, group_id, user_id, requester_user_id, content): else: raise SynapseError(502, "Unknown state returned by HS") async def _add_user( self, group_id: str, user_id: str, content: JsonDict ) -> Optional[JsonDict]: """Add a user to a group based on ...
async def _add_user(self, group_id, user_id, content): return local_attestation async def accept_invite(self, group_id, requester_user_id, content): """User tries to accept an invite to the group. This is different from them asking to join, and so should error if no
async def _add_user(self, group_id, user_id, content): return local_attestation async def accept_invite( self, group_id: str, requester_user_id: str, content: JsonDict ) -> JsonDict: """User tries to accept an invite to the group. This is different from them asking to join, an...
async def accept_invite(self, group_id, requester_user_id, content): return {"state": "join", "attestation": local_attestation} async def join_group(self, group_id, requester_user_id, content): """User tries to join the group. This will error if the group requires an invite/knock to join
async def accept_invite(self, group_id, requester_user_id, content): return {"state": "join", "attestation": local_attestation} async def join_group( self, group_id: str, requester_user_id: str, content: JsonDict ) -> JsonDict: """User tries to join the group. This will error ...
async def join_group(self, group_id, requester_user_id, content): group_info = await self.check_group_is_ours( group_id, requester_user_id, and_exists=True ) if group_info["join_policy"] != "open": raise SynapseError(403, "Group is not publicly joinable")
async def join_group(self, group_id, requester_user_id, content): group_info = await self.check_group_is_ours( group_id, requester_user_id, and_exists=True ) if not group_info: raise SynapseError(404, "Group does not exist", errcode=Codes.NOT_FOUND) if group_info[...
async def join_group(self, group_id, requester_user_id, content): return {"state": "join", "attestation": local_attestation} async def knock(self, group_id, requester_user_id, content): """A user requests becoming a member of the group""" await self.check_group_is_ours(group_id, requester_...
async def join_group(self, group_id, requester_user_id, content): return {"state": "join", "attestation": local_attestation} async def remove_user_from_group( self, group_id: str, user_id: str, requester_user_id: str, content: JsonDict ) -> JsonDict: """Remove a user from the group; ei...
async def remove_user_from_group( if is_kick: if self.hs.is_mine_id(user_id): groups_local = self.hs.get_groups_local_handler() await groups_local.user_removed_from_group(group_id, user_id, {}) else: await self.transport_client.remove_user_...
async def remove_user_from_group( if is_kick: if self.hs.is_mine_id(user_id): groups_local = self.hs.get_groups_local_handler() assert isinstance( groups_local, GroupsLocalHandler ), "Workers cannot remove users from groups." ...
async def remove_user_from_group( return {} async def create_group(self, group_id, requester_user_id, content): group = await self.check_group_is_ours(group_id, requester_user_id) logger.info("Attempting to create group with ID: %r", group_id) # parsing the id into a GroupID vali...
async def remove_user_from_group( return {} async def create_group( self, group_id: str, requester_user_id: str, content: JsonDict ) -> JsonDict: logger.info("Attempting to create group with ID: %r", group_id) # parsing the id into a GroupID validates it. group_id_obj ...
async def create_group(self, group_id, requester_user_id, content): local_attestation = self.attestations.create_attestation( group_id, requester_user_id ) else: local_attestation = None remote_attestation = None
async def create_group(self, group_id, requester_user_id, content): local_attestation = self.attestations.create_attestation( group_id, requester_user_id ) # type: Optional[JsonDict] else: local_attestation = None remote_attestation = None
async def create_group(self, group_id, requester_user_id, content): return {"group_id": group_id} async def delete_group(self, group_id, requester_user_id): """Deletes a group, kicking out all current members. Only group admins or server admins can call this request Args: ...
async def create_group(self, group_id, requester_user_id, content): return {"group_id": group_id} async def delete_group(self, group_id: str, requester_user_id: str) -> None: """Deletes a group, kicking out all current members. Only group admins or server admins can call this request ...
async def delete_group(self, group_id, requester_user_id): async def _kick_user_from_group(user_id): if self.hs.is_mine_id(user_id): groups_local = self.hs.get_groups_local_handler() await groups_local.user_removed_from_group(group_id, user_id, {}) else: ...
async def delete_group(self, group_id, requester_user_id): async def _kick_user_from_group(user_id): if self.hs.is_mine_id(user_id): groups_local = self.hs.get_groups_local_handler() assert isinstance( groups_local, GroupsLocalHandler ...
async def _kick_user_from_group(user_id): await self.store.delete_group(group_id) def _parse_join_policy_from_contents(content): """Given a content for a request, return the specified join policy or None""" join_policy_dict = content.get("m.join_policy")
async def _kick_user_from_group(user_id): await self.store.delete_group(group_id) def _parse_join_policy_from_contents(content: JsonDict) -> Optional[str]: """Given a content for a request, return the specified join policy or None""" join_policy_dict = content.get("m.join_policy")
def _parse_join_policy_from_contents(content): return None def _parse_join_policy_dict(join_policy_dict): """Given a dict for the "m.join_policy" config return the join policy specified""" join_policy_type = join_policy_dict.get("type") if not join_policy_type:
def _parse_join_policy_from_contents(content): return None def _parse_join_policy_dict(join_policy_dict: JsonDict) -> str: """Given a dict for the "m.join_policy" config return the join policy specified""" join_policy_type = join_policy_dict.get("type") if not join_policy_type:
def _parse_join_policy_dict(join_policy_dict): return join_policy_type def _parse_visibility_from_contents(content): """Given a content for a request parse out whether the entity should be public or not """
def _parse_join_policy_dict(join_policy_dict): return join_policy_type def _parse_visibility_from_contents(content: JsonDict) -> bool: """Given a content for a request parse out whether the entity should be public or not """
def _parse_visibility_from_contents(content): return is_public def _parse_visibility_dict(visibility): """Given a dict for the "m.visibility" config return if the entity should be public or not """
def _parse_visibility_from_contents(content): return is_public def _parse_visibility_dict(visibility: JsonDict) -> bool: """Given a dict for the "m.visibility" config return if the entity should be public or not """
import logging from functools import wraps from typing import TYPE_CHECKING, Tuple from twisted.web.http import Request from synapse.api.errors import SynapseError from synapse.handlers.groups_local import GroupsLocalHandler from synapse.http.servlet import ( RestServlet,
import logging from functools import wraps from typing import TYPE_CHECKING, Optional, Tuple from twisted.web.http import Request from synapse.api.constants import ( MAX_GROUP_CATEGORYID_LENGTH, MAX_GROUP_ROLEID_LENGTH, MAX_GROUPID_LENGTH, ) from synapse.api.errors import Codes, SynapseError from synapse...
async def on_POST(self, request: Request, group_id: str) -> Tuple[int, JsonDict] assert_params_in_dict( content, ("name", "avatar_url", "short_description", "long_description") ) assert isinstance(self.groups_handler, GroupsLocalHandler) await self.groups_handler.update_group...
async def on_POST(self, request: Request, group_id: str) -> Tuple[int, JsonDict] assert_params_in_dict( content, ("name", "avatar_url", "short_description", "long_description") ) assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot create ...
def __init__(self, hs: "HomeServer"): @_validate_group_id async def on_PUT( self, request: Request, group_id: str, category_id: str, room_id: str ): requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() content = parse_json_obje...
def __init__(self, hs: "HomeServer"): @_validate_group_id async def on_PUT( self, request: Request, group_id: str, category_id: Optional[str], room_id: str ): requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() if category_id ...
async def on_DELETE( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() assert isinstance(self.groups_handler, GroupsLocalHandler) resp = await self.groups_handler.delete_group_summary_room( group_id, requester_user_id, room_i...
async def on_DELETE( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot modify group profiles." resp = await self.groups_handler.delete_grou...
async def on_PUT( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance(self.groups_handler, GroupsLocalHandler) resp = await self.groups_handler.update_group_catego...
async def on_PUT( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() if not category_id: raise SynapseError(400, "category_id cannot be empty", Codes.INVALID_PARAM) if len(category_id) > MAX_GROUP_CATEGORYID_LENGTH: ...
async def on_DELETE( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() assert isinstance(self.groups_handler, GroupsLocalHandler) resp = await self.groups_handler.delete_group_category( group_id, requester_user_id, category_i...
async def on_DELETE( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot modify group categories." resp = await self.groups_handler.delete_gr...
async def on_PUT( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance(self.groups_handler, GroupsLocalHandler) resp = await self.groups_handler.update_group_role( ...
async def on_PUT( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() if not role_id: raise SynapseError(400, "role_id cannot be empty", Codes.INVALID_PARAM) if len(role_id) > MAX_GROUP_ROLEID_LENGTH: raise Synapse...
async def on_DELETE( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() assert isinstance(self.groups_handler, GroupsLocalHandler) resp = await self.groups_handler.delete_group_role( group_id, requester_user_id, role_id=role_i...
async def on_DELETE( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot modify group roles." resp = await self.groups_handler.delete_group_r...
def __init__(self, hs: "HomeServer"): @_validate_group_id async def on_PUT( self, request: Request, group_id: str, role_id: str, user_id: str ) -> Tuple[int, JsonDict]: requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() conte...
def __init__(self, hs: "HomeServer"): @_validate_group_id async def on_PUT( self, request: Request, group_id: str, role_id: Optional[str], user_id: str ) -> Tuple[int, JsonDict]: requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() ...
async def on_DELETE( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() assert isinstance(self.groups_handler, GroupsLocalHandler) resp = await self.groups_handler.delete_group_summary_user( group_id, requester_user_id, user_i...
async def on_DELETE( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot modify group summaries." resp = await self.groups_handler.delete_gro...
async def on_PUT(self, request: Request, group_id: str) -> Tuple[int, JsonDict]: content = parse_json_object_from_request(request) assert isinstance(self.groups_handler, GroupsLocalHandler) result = await self.groups_handler.set_group_join_policy( group_id, requester_user_id, conte...
async def on_PUT(self, request: Request, group_id: str) -> Tuple[int, JsonDict]: content = parse_json_object_from_request(request) assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot modify group join policy." result = await self.groups_handler.set...
async def on_POST(self, request: Request) -> Tuple[int, JsonDict]: localpart = content.pop("localpart") group_id = GroupID(localpart, self.server_name).to_string() assert isinstance(self.groups_handler, GroupsLocalHandler) result = await self.groups_handler.create_group( gro...
async def on_POST(self, request: Request) -> Tuple[int, JsonDict]: localpart = content.pop("localpart") group_id = GroupID(localpart, self.server_name).to_string() if not localpart: raise SynapseError(400, "Group ID cannot be empty", Codes.INVALID_PARAM) if len(group_id) > ...
async def on_PUT( requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance(self.groups_handler, GroupsLocalHandler) result = await self.groups_handler.add_room_to_group( group_id, requester_user_id, room_id, content ...
async def on_PUT( requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot modify rooms in a group." result = await self.groups_handler.add_room_to_g...
async def on_DELETE( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() assert isinstance(self.groups_handler, GroupsLocalHandler) result = await self.groups_handler.remove_room_from_group( group_id, requester_user_id, room_id...
async def on_DELETE( requester = await self.auth.get_user_by_req(request) requester_user_id = requester.user.to_string() assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot modify group categories." result = await self.groups_handler.remove_...
async def on_PUT( requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance(self.groups_handler, GroupsLocalHandler) result = await self.groups_handler.update_room_in_group( group_id, requester_user_id, room_id, config...
async def on_PUT( requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot modify group categories." result = await self.groups_handler.update_room_i...
async def on_PUT(self, request: Request, group_id, user_id) -> Tuple[int, JsonDi content = parse_json_object_from_request(request) config = content.get("config", {}) assert isinstance(self.groups_handler, GroupsLocalHandler) result = await self.groups_handler.invite( group_i...
async def on_PUT(self, request: Request, group_id, user_id) -> Tuple[int, JsonDi content = parse_json_object_from_request(request) config = content.get("config", {}) assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot invite users to a group." ...
async def on_PUT(self, request: Request, group_id, user_id) -> Tuple[int, JsonDi requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance(self.groups_handler, GroupsLocalHandler) result = await self.groups_handler.remove_user_fro...
async def on_PUT(self, request: Request, group_id, user_id) -> Tuple[int, JsonDi requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot kick users from a g...
async def on_PUT(self, request: Request, group_id: str) -> Tuple[int, JsonDict]: requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance(self.groups_handler, GroupsLocalHandler) result = await self.groups_handler.remove_user_fro...
async def on_PUT(self, request: Request, group_id: str) -> Tuple[int, JsonDict]: requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot leave a group for a...
async def on_PUT(self, request: Request, group_id: str) -> Tuple[int, JsonDict]: requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance(self.groups_handler, GroupsLocalHandler) result = await self.groups_handler.join_group( ...
async def on_PUT(self, request: Request, group_id: str) -> Tuple[int, JsonDict]: requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot join a user to a gr...
async def on_PUT(self, request: Request, group_id: str) -> Tuple[int, JsonDict]: requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance(self.groups_handler, GroupsLocalHandler) result = await self.groups_handler.accept_invite( ...
async def on_PUT(self, request: Request, group_id: str) -> Tuple[int, JsonDict]: requester_user_id = requester.user.to_string() content = parse_json_object_from_request(request) assert isinstance( self.groups_handler, GroupsLocalHandler ), "Workers cannot accept an invite to...
# See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Dict, List, Optional, Tuple, Union from synapse.api.errors import SynapseError from synapse.storage._base import SQLBaseStore, db_to_json
# See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Dict, List, Optional, Tuple from typing_extensions import TypedDict from synapse.api.errors import SynapseError from synapse.storage._base import SQLBaseStore, db_to_json
_DEFAULT_CATEGORY_ID = "" _DEFAULT_ROLE_ID = "" class GroupServerWorkerStore(SQLBaseStore): async def get_group(self, group_id: str) -> Optional[Dict[str, Any]]:
_DEFAULT_CATEGORY_ID = "" _DEFAULT_ROLE_ID = "" # A room in a group. _RoomInGroup = TypedDict("_RoomInGroup", {"room_id": str, "is_public": bool}) class GroupServerWorkerStore(SQLBaseStore): async def get_group(self, group_id: str) -> Optional[Dict[str, Any]]:
async def get_invited_users_in_group(self, group_id: str) -> List[str]: async def get_rooms_in_group( self, group_id: str, include_private: bool = False ) -> List[Dict[str, Union[str, bool]]]: """Retrieve the rooms that belong to a given group. Does not return rooms that lack members.
async def get_invited_users_in_group(self, group_id: str) -> List[str]: async def get_rooms_in_group( self, group_id: str, include_private: bool = False ) -> List[_RoomInGroup]: """Retrieve the rooms that belong to a given group. Does not return rooms that lack members.
def _preprocess_numpy_input(x, data_format, mode): # Returns Preprocessed Numpy array. """ if mode == 'tf': x /= 127.5 x -= 1.
def _preprocess_numpy_input(x, data_format, mode): # Returns Preprocessed Numpy array. """ x = x.astype(K.floatx()) if mode == 'tf': x /= 127.5 x -= 1.
from keras.layers import Input, Lambda def test_preprocess_input(): # Test image batch x = np.random.uniform(0, 255, (2, 10, 10, 3)) assert utils.preprocess_input(x).shape == x.shape out1 = utils.preprocess_input(x, 'channels_last') out2 = utils.preprocess_input(np.transpose(x, (0, 3, 1, 2)), ...
from keras.layers import Input, Lambda def test_preprocess_input(): # Test image batch with float and int image input x = np.random.uniform(0, 255, (2, 10, 10, 3)) xint = x.astype('int32') assert utils.preprocess_input(x).shape == x.shape assert utils.preprocess_input(xint).shape == xint.shape ...
from django.contrib.gis.db.models.fields import ExtentField from django.db.models.aggregates import Aggregate __all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union']
from django.contrib.gis.db.models.fields import ExtentField from django.db.models import Value from django.db.models.aggregates import Aggregate __all__ = ['Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union']
class GeoAggregate(Aggregate): return super(GeoAggregate, self).as_sql(compiler, connection) def as_oracle(self, compiler, connection): if not hasattr(self, 'tolerance'): self.tolerance = 0.05 self.extra['tolerance'] = self.tolerance if not self.is_extent: se...
class GeoAggregate(Aggregate): return super(GeoAggregate, self).as_sql(compiler, connection) def as_oracle(self, compiler, connection): if not self.is_extent: tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05) clone = self.copy() expressi...
class OracleToleranceMixin(object): tolerance = 0.05 def as_oracle(self, compiler, connection): tol = self.extra.get('tolerance', self.tolerance) self.template = "%%(function)s(%%(expressions)s, %s)" % tol return super(OracleToleranceMixin, self).as_sql(compiler, connection)
class OracleToleranceMixin(object): tolerance = 0.05 def as_oracle(self, compiler, connection): tol = self._handle_param( self.extra.get('tolerance', self.tolerance), 'tolerance', NUMERIC_TYPES, ) self.template = "%%(function)s(%%(expressions)s, %s)" ...
from __future__ import unicode_literals from unittest import skipIf from django.contrib.gis.db.models.functions import ( Area, Distance, Length, Perimeter, Transform,
from __future__ import unicode_literals from unittest import skipIf, skipUnless from django.contrib.gis.db.models.functions import ( Area, Distance, Length, Perimeter, Transform,
class DistanceFunctionsTests(TestCase): for i, c in enumerate(qs): self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol) @no_oracle # Oracle already handles geographic distance calculation. @skipUnlessDBFeature("has_Distance_function", 'has_Transform_function') def tes...
class DistanceFunctionsTests(TestCase): for i, c in enumerate(qs): self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol) @skipUnless( connection.vendor == 'oracle', 'Oracle supports tolerance paremeter.', ) def test_distance_function_tolerance_escaping(s...
from __future__ import unicode_literals import re import tempfile from django.contrib.gis import gdal from django.contrib.gis.db.models import Extent, MakeLine, Union
from __future__ import unicode_literals import re import tempfile import unittest from django.contrib.gis import gdal from django.contrib.gis.db.models import Extent, MakeLine, Union
from django.contrib.gis.geos import ( MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import connection from django.test import TestCase, ignore_warnings, skipUnlessDBFeature from django.utils import six from django.utils.deprecation import Removed...
from django.contrib.gis.geos import ( MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import DatabaseError, connection from django.test import TestCase, ignore_warnings, skipUnlessDBFeature from django.utils import six from django.utils.deprecation...
class GeoQuerySetTest(TestCase): qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.aggregate(Union('point'))['point__union']) def test_within_subquery(self): """ Using a queryset inside a geo lookup is working (using a subquery)
class GeoQuerySetTest(TestCase): qs = City.objects.filter(name='NotACity') self.assertIsNone(qs.aggregate(Union('point'))['point__union']) @unittest.skipUnless( connection.vendor == 'oracle', 'Oracle supports tolerance paremeter.', ) def test_unionagg_tolerance(self): ...
def _get_spider_loader(settings): 'Please use SPIDER_LOADER_CLASS.', category=ScrapyDeprecationWarning, stacklevel=2 ) cls_path = settings.get('SPIDER_LOADER_CLASS', settings.get('SPIDER_MANAGER_CLASS')) loader_cls = load_object(cls_path) verifyCla...
def _get_spider_loader(settings): 'Please use SPIDER_LOADER_CLASS.', category=ScrapyDeprecationWarning, stacklevel=2 ) cls_path = settings.get('SPIDER_MANAGER_CLASS', settings.get('SPIDER_LOADER_CLASS')) loader_cls = load_object(cls_path) verifyCla...
from zope.interface.verify import DoesNotImplement from scrapy.crawler import Crawler, CrawlerRunner from scrapy.settings import Settings, default_settings from scrapy.utils.spider import DefaultSpider from scrapy.utils.misc import load_object
from zope.interface.verify import DoesNotImplement from scrapy.crawler import Crawler, CrawlerRunner from scrapy.settings import Settings, default_settings from scrapy.spiderloader import SpiderLoader from scrapy.utils.spider import DefaultSpider from scrapy.utils.misc import load_object
class SpiderLoaderWithWrongInterface(object): pass class CrawlerRunnerTestCase(unittest.TestCase): def test_spider_manager_verify_interface(self):
class SpiderLoaderWithWrongInterface(object): pass class CustomSpiderLoader(SpiderLoader): pass class CrawlerRunnerTestCase(unittest.TestCase): def test_spider_manager_verify_interface(self):
class CrawlerRunnerTestCase(unittest.TestCase): self.assertIn("CrawlerRunner.spider_loader", str(w[0].message)) sl_cls = load_object(runner.settings['SPIDER_LOADER_CLASS']) self.assertIsInstance(spiders, sl_cls)
class CrawlerRunnerTestCase(unittest.TestCase): self.assertIn("CrawlerRunner.spider_loader", str(w[0].message)) sl_cls = load_object(runner.settings['SPIDER_LOADER_CLASS']) self.assertIsInstance(spiders, sl_cls) def test_spidermanager_deprecation(self): with warnings.cat...
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, (self.host, self.port) = self._get_hostport(host, port) # This is stored as an instance variable to allow unit # tests to replace it with a suitable mockup self._create_connection = socket.create_connection
def __init__(self, host, port=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, (self.host, self.port) = self._get_hostport(host, port) self._validate_host(self.host) # This is stored as an instance variable to allow unit # tests to replace it with a suitable mockup self._create_co...
def _validate_path(self, url): ).format(matched=match.group(), **locals()) raise InvalidURL(msg) def putheader(self, header, *values): """Send a request header line to the server.
def _validate_path(self, url): ).format(matched=match.group(), **locals()) raise InvalidURL(msg) def _validate_host(self, host): """Validate a host so it doesn't contain control characters.""" # Prevent CVE-2019-18348. match = _contains_disallowed_url_pchar_re.search...
def run_server(): thread.join() self.assertEqual(result, b"proxied data\n") def test_putrequest_override_validation(self): """ It should be possible to override the default validation behavior in putrequest (bpo-38216).
def run_server(): thread.join() self.assertEqual(result, b"proxied data\n") def test_putrequest_override_domain_validation(self): """ It should be possible to override the default validation behavior in putrequest (bpo-38216).
def _validate_path(self, url): conn.sock = FakeSocket('') conn.putrequest('GET', '/\x00') def test_putrequest_override_encoding(self): """ It should be possible to override the default encoding
def _validate_path(self, url): conn.sock = FakeSocket('') conn.putrequest('GET', '/\x00') def test_putrequest_override_host_validation(self): class UnsafeHTTPConnection(client.HTTPConnection): def _validate_host(self, url): pass conn = UnsafeHTTPConnecti...
def test_willclose(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) schemeless_url = "//localhost:7777/test{}/".format(char)
def test_willclose(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_path_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) schemeless_url = "//localhost:7777/test{}/".format(char)
def test_url_with_control_char_rejected(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_with_newline_header_injection_rejected(self): self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.") host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\...
def test_url_with_control_char_rejected(self): self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_path_with_newline_header_injection_rejected(self): self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.") host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: he...
def test_url_with_newline_header_injection_rejected(self): finally: self.unfakehttp() def test_read_0_9(self): # "0.9" response accepted (but not "simple responses" without # a status line)
def test_url_with_newline_header_injection_rejected(self): finally: self.unfakehttp() @unittest.skipUnless(ssl, "ssl module required") def test_url_host_with_control_char_rejected(self): for char_no in list(range(0, 0x21)) + [0x7f]: char = chr(char_no) scheme...
and Index.__new__. These should not depend on core.internals. """ from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast import numpy as np
and Index.__new__. These should not depend on core.internals. """ from collections import abc from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast import numpy as np
def sanitize_array( # GH#16804 arr = np.arange(data.start, data.stop, data.step, dtype="int64") subarr = _try_cast(arr, dtype, copy, raise_cast_failure) else: subarr = _try_cast(data, dtype, copy, raise_cast_failure)
def sanitize_array( # GH#16804 arr = np.arange(data.start, data.stop, data.step, dtype="int64") subarr = _try_cast(arr, dtype, copy, raise_cast_failure) elif isinstance(data, abc.Set): raise TypeError("Set type is unordered") else: subarr = _try_cast(data, dtype, copy, ra...
class TestDataFrameConstructorWithDatetimeTZ: expected = DataFrame(array_dim2).astype("datetime64[ns, UTC]") tm.assert_frame_equal(df, expected)
class TestDataFrameConstructorWithDatetimeTZ: expected = DataFrame(array_dim2).astype("datetime64[ns, UTC]") tm.assert_frame_equal(df, expected) def test_construction_from_set_raises(self): # https://github.com/pandas-dev/pandas/issues/32582 msg = "Set type is unordered" wi...
pjoin = os.path.join # Constants #----------------------------------------------------------------------------- bundled_version = (4, 3, 1) vs = '%i.%i.%i' % bundled_version libzmq = "zeromq-%s.tar.gz" % vs libzmq_url = "https://github.com/zeromq/libzmq/releases/download/v{vs}/{libzmq}".format( vs=vs, libzmq=l...
pjoin = os.path.join # Constants #----------------------------------------------------------------------------- bundled_version = (4, 3, 2) vs = '%i.%i.%i' % bundled_version libzmq = "zeromq-%s.tar.gz" % vs libzmq_url = "https://github.com/zeromq/libzmq/releases/download/v{vs}/{libzmq}".format( vs=vs, libzmq=l...
class Index(IndexOpsMixin, PandasObject): left_indexer = self.get_indexer(target, "pad", limit=limit) right_indexer = self.get_indexer(target, "backfill", limit=limit) target = np.asarray(target) left_distances = abs(self.values[left_indexer] - target) right_distances = abs(self...
class Index(IndexOpsMixin, PandasObject): left_indexer = self.get_indexer(target, "pad", limit=limit) right_indexer = self.get_indexer(target, "backfill", limit=limit) left_distances = np.abs(self[left_indexer] - target) right_distances = np.abs(self[right_indexer] - target) op...
class TestDataFrameIndexing: actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1]) tm.assert_frame_equal(expected, actual) def test_reindex_frame_add_nat(self): rng = date_range("1/1/2000 00:00:00", periods=10, freq="10s") df = DataFrame({"A": np.random.rand...
class TestDataFrameIndexing: actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1]) tm.assert_frame_equal(expected, actual) def test_reindex_nearest_tz(self, tz_aware_fixture): # GH26683 tz = tz_aware_fixture idx = pd.date_range("2019-01-01", periods=...
def top_k_categorical_accuracy(y_true, y_pred, k=5): def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5): return K.mean(K.in_top_k(y_pred, K.cast(K.max(y_true, axis=-1), 'int32'), k), axis=-1)
def top_k_categorical_accuracy(y_true, y_pred, k=5): def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5): # If the shape of y_true is (num_samples, 1), flatten to (num_samples,) return K.mean(K.in_top_k(y_pred, K.cast(K.flatten(y_true), 'int32'), k), axis=-1)
def test_top_k_categorical_accuracy(): @pytest.mark.skipif((K.backend() == 'cntk'), reason='CNTK backend does not support top_k yet') def test_sparse_top_k_categorical_accuracy(): y_pred = K.variable(np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]])) y_true = K.variable(np.array([[1], [0]])) ...
def test_top_k_categorical_accuracy(): @pytest.mark.skipif((K.backend() == 'cntk'), reason='CNTK backend does not support top_k yet') @pytest.mark.parametrize('y_pred, y_true', [ # Test correctness if the shape of y_true is (num_samples, 1) (np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]]), np....
def format_str(src_contents: str, line_length: int) -> FileContent: return dst_contents def lib2to3_parse(src_txt: str) -> Node: """Given a string with source, return the lib2to3 Node.""" grammar = pygram.python_grammar_no_print_statement drv = driver.Driver(grammar, pytree.convert) if src_txt[-1]...
def format_str(src_contents: str, line_length: int) -> FileContent: return dst_contents GRAMMARS = [ pygram.python_grammar_no_print_statement_no_exec_statement, pygram.python_grammar_no_print_statement, pygram.python_grammar_no_exec_statement, pygram.python_grammar, ] def lib2to3_parse(src_txt: ...
def whitespace(leaf: Leaf) -> str: # noqa C901 ): return NO elif prev.type in OPENING_BRACKETS: return NO
def whitespace(leaf: Leaf) -> str: # noqa C901 ): return NO elif ( prevp.type == token.RIGHTSHIFT and prevp.parent and prevp.parent.type == syms.shift_expr and prevp.prev_sibling and prevp.prev_sibling.type == token.NAME ...
def assert_equivalent(src: str, dst: str) -> None: try: src_ast = ast.parse(src) except Exception as exc: raise AssertionError(f"cannot parse source: {exc}") from None try: dst_ast = ast.parse(dst)
def assert_equivalent(src: str, dst: str) -> None: try: src_ast = ast.parse(src) except Exception as exc: major, minor = sys.version_info[:2] raise AssertionError( f"cannot use --safe with this file; failed to parse source file " f"with Python {major}.{minor}'s bu...
python_symbols = Symbols(python_grammar) python_grammar_no_print_statement = python_grammar.copy() del python_grammar_no_print_statement.keywords["print"] pattern_grammar = driver.load_packaged_grammar("blib2to3", _PATTERN_GRAMMAR_FILE) pattern_symbols = Symbols(pattern_grammar)
python_symbols = Symbols(python_grammar) python_grammar_no_print_statement = python_grammar.copy() del python_grammar_no_print_statement.keywords["print"] python_grammar_no_exec_statement = python_grammar.copy() del python_grammar_no_exec_statement.keywords["exec"] python_grammar_no_print_statement_no_exec_statement ...
def func_no_args(): for i in range(10): print(i) continue return None async def coroutine(arg): "Single-line docstring. Multiline is harder to reformat." async with some_connection() as conn: await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2)
def func_no_args(): for i in range(10): print(i) continue exec("new-style exec", {}, {}) return None async def coroutine(arg, exec=False): "Single-line docstring. Multiline is harder to reformat." async with some_connection() as conn: await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', time...
def func_no_args(): print(i) continue return None async def coroutine(arg): "Single-line docstring. Multiline is harder to reformat." async with some_connection() as conn: await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', timeout=2)
def func_no_args(): print(i) continue exec("new-style exec", {}, {}) return None async def coroutine(arg, exec=False): "Single-line docstring. Multiline is harder to reformat." async with some_connection() as conn: await conn.do_what_i_mean('SELECT bobby, tables FROM xkcd', ti...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, line_length=ll) def test_report(self) -> None: report = black.Report() out_lines = []
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, line_length=ll) @patch("black.dump_to_file", dump_to_stderr) def test_python2(self) -> None: source, expected = read_data('python2') actual = fs(source) se...
import ctypes import datetime as dt import decimal import io
import datetime as dt import decimal import io
def test_encode_surrogate_characters(): assert ujson.dumps({"\ud800": "\udfff"}, ensure_ascii=False, sort_keys=True) == out2 @pytest.mark.xfail( hasattr(sys, "pypy_version_info") and os.name == "nt", reason="This feature needs fixing! See #552", ) @pytest.mark.parametrize( "test_input, expected", ...
def test_encode_surrogate_characters(): assert ujson.dumps({"\ud800": "\udfff"}, ensure_ascii=False, sort_keys=True) == out2 @pytest.mark.parametrize( "test_input, expected", [
def test_encode_surrogate_characters(): ], ) def test_decode_surrogate_characters(test_input, expected): # FIXME Wrong output (combined char) on platforms with 16-bit wchar_t if test_input == '"\uD83D\uDCA9"' and ctypes.sizeof(ctypes.c_wchar) == 2: pytest.skip("Raw surrogate pairs are not supported ...
def test_encode_surrogate_characters(): ], ) def test_decode_surrogate_characters(test_input, expected): assert ujson.loads(test_input) == expected assert ujson.loads(test_input.encode("utf-8", "surrogatepass")) == expected
def is_string_dtype(arr_or_dtype) -> bool: """ These have kind = "O" but aren't string dtypes so need to be explicitly excluded """ is_excluded_checks = (is_period_dtype, is_interval_dtype) return any(is_excluded(dtype) for is_excluded in is_excluded_checks) return _is_dtype...
def is_string_dtype(arr_or_dtype) -> bool: """ These have kind = "O" but aren't string dtypes so need to be explicitly excluded """ is_excluded_checks = (is_period_dtype, is_interval_dtype, is_categorical_dtype) return any(is_excluded(dtype) for is_excluded in is_excluded_checks)...
class TestCategoricalDtype(Base): result = str(Categorical(DatetimeIndex([])).categories.dtype) assert result == expected class TestDatetimeTZDtype(Base): @pytest.fixture
class TestCategoricalDtype(Base): result = str(Categorical(DatetimeIndex([])).categories.dtype) assert result == expected def test_not_string(self): # though CategoricalDtype has object kind, it cannot be string assert not is_string_dtype(CategoricalDtype()) class TestDatetimeTZDt...
from collections import namedtuple from typing import Dict, List from netaddr import IPSet from synapse.config.server import DEFAULT_IP_RANGE_BLACKLIST from synapse.python_dependencies import DependencyException, check_requirements from synapse.util.module_loader import load_module
from collections import namedtuple from typing import Dict, List from synapse.config.server import DEFAULT_IP_RANGE_BLACKLIST, generate_ip_set from synapse.python_dependencies import DependencyException, check_requirements from synapse.util.module_loader import load_module
def read_config(self, config, **kwargs): "to work" ) self.url_preview_ip_range_blacklist = IPSet( config["url_preview_ip_range_blacklist"] ) # we always blacklist '0.0.0.0' and '::', which are supposed to be # unroutab...
def read_config(self, config, **kwargs): "to work" ) # we always blacklist '0.0.0.0' and '::', which are supposed to be # unroutable addresses. self.url_preview_ip_range_blacklist = generate_ip_set( config["url_preview_ip_range_bla...
# See the License for the specific language governing permissions and # limitations under the License. import logging import os.path import re
# See the License for the specific language governing permissions and # limitations under the License. import itertools import logging import os.path import re
import attr import yaml from netaddr import IPSet from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.util.stringutils import parse_and_validate_server_name
import attr import yaml from netaddr import AddrFormatError, IPNetwork, IPSet from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.util.stringutils import parse_and_validate_server_name
# in the list. DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"] DEFAULT_IP_RANGE_BLACKLIST = [ # Localhost "127.0.0.0/8",
# in the list. DEFAULT_BIND_ADDRESSES = ["::", "0.0.0.0"] def _6to4(network: IPNetwork) -> IPNetwork: """Convert an IPv4 network into a 6to4 IPv6 network per RFC 3056.""" # 6to4 networks consist of: # * 2002 as the first 16 bits # * The first IPv4 address in the network hex-encoded as the next 32 bit...
"192.0.0.0/24", # Link-local networks. "169.254.0.0/16", # Testing networks. "198.18.0.0/15", "192.0.2.0/24",
"192.0.0.0/24", # Link-local networks. "169.254.0.0/16", # Formerly used for 6to4 relay. "192.88.99.0/24", # Testing networks. "198.18.0.0/15", "192.0.2.0/24",
"fe80::/10", # Unique local addresses. "fc00::/7", ] DEFAULT_ROOM_VERSION = "6"
"fe80::/10", # Unique local addresses. "fc00::/7", # Testing networks. "2001:db8::/32", # Multicast. "ff00::/8", # Site-local addresses "fec0::/10", ] DEFAULT_ROOM_VERSION = "6"
def read_config(self, config, **kwargs): ) # Attempt to create an IPSet from the given ranges try: self.ip_range_blacklist = IPSet(ip_range_blacklist) except Exception as e: raise ConfigError("Invalid range(s) provided in ip_range_blacklist.") from e # Al...
def read_config(self, config, **kwargs): ) # Attempt to create an IPSet from the given ranges # Always blacklist 0.0.0.0, :: self.ip_range_blacklist = generate_ip_set( ip_range_blacklist, ["0.0.0.0", "::"], config_path=("ip_range_blacklist",) ) self.ip_rang...
def read_config(self, config, **kwargs): federation_ip_range_blacklist = config.get( "federation_ip_range_blacklist", ip_range_blacklist ) try: self.federation_ip_range_blacklist = IPSet(federation_ip_range_blacklist) except Exception as e: raise Confi...
def read_config(self, config, **kwargs): federation_ip_range_blacklist = config.get( "federation_ip_range_blacklist", ip_range_blacklist ) # Always blacklist 0.0.0.0, :: self.federation_ip_range_blacklist = generate_ip_set( federation_ip_range_blacklist, ...
import yaml from synapse.config.server import ServerConfig, is_threepid_reserved from tests import unittest
import yaml from synapse.config._base import ConfigError from synapse.config.server import ServerConfig, generate_ip_set, is_threepid_reserved from tests import unittest