query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Links in a message should be replaced with short code.
def test_links_in_message_are_shortened(self): sender = self.create_user() group = self.create_group() sender.add_to_group(group.pk) thread = mommy.make(Thread, group=group) message = Message( text='This is a <a href="http://www.razzmatazz.local">link</a>', ...
[ "def test_links_in_message_are_not_shortened(self):\n sender = self.create_user()\n group = self.create_group()\n sender.add_to_group(group.pk)\n\n thread = mommy.make(Thread, group=group)\n message = Message(\n text='This is a <a href=\"http://www.razzmatazz.local\">li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If shorten=False, links in message should not be replaced.
def test_links_in_message_are_not_shortened(self): sender = self.create_user() group = self.create_group() sender.add_to_group(group.pk) thread = mommy.make(Thread, group=group) message = Message( text='This is a <a href="http://www.razzmatazz.local">link</a>', ...
[ "def test_links_in_message_are_shortened(self):\n sender = self.create_user()\n group = self.create_group()\n sender.add_to_group(group.pk)\n\n thread = mommy.make(Thread, group=group)\n message = Message(\n text='This is a <a href=\"http://www.razzmatazz.local\">link</...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that a system message is always approved
def test_system_message_approved(self): system_user, _ = USER_MODEL.objects.get_or_create( email='systemuser-email@connect.local', defaults={ 'username': 'systemuser-email@connect.local', 'is_active': True, 'is_superuser': True } ) ...
[ "def test_approve_agreement(self):\n pass", "def test_user_is_sender_message_is_moderated(self):\n thread = self.create_thread()\n message = thread.first_message\n message.status = 'pending'\n message.save()\n self.assertTrue(message.visible_to_user(message.sender))", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
User should be able to send up to 10 dms before they're pending.
def test_user_can_send_up_to_10_dms(self): user = self.create_user() threads = [ self.create_thread(direct=True, sender=user) for _ in range(0, 10) ] for thread in threads: self.assertEqual( thread.first_message.get_initial_status(), 'approved') ...
[ "def _send_pending_messages():\n\n queryset = models.Message.objects.filter(status=models.STATUS_PENDING)\\\n .order_by(\"-priority\", \"created_at\")\n\n connection = _get_real_backend()\n paginator = Paginator(list(queryset), getattr(settings, \"DJMAIL_MAX_BULK_RETR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deleted messages shouldn't be in regular queries.
def test_no_deleted_messages_in_query(self): thread = self.create_thread() thread.first_message.delete() self.assertNotIn(thread.first_message, Message.objects.all())
[ "def test_deleted_messages_in_with_deleted_query(self):\n thread = self.create_thread()\n thread.first_message.delete()\n self.assertTrue(\n Message.objects.with_deleted().filter(\n pk=thread.first_message.pk).exists()\n )", "def test_delete_message_is_only_me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deleted messages should show in with_deleted queries.
def test_deleted_messages_in_with_deleted_query(self): thread = self.create_thread() thread.first_message.delete() self.assertTrue( Message.objects.with_deleted().filter( pk=thread.first_message.pk).exists() )
[ "def checkDeleted(self) -> None:\n ...", "def test_no_deleted_messages_in_query(self):\n thread = self.create_thread()\n thread.first_message.delete()\n self.assertNotIn(thread.first_message, Message.objects.all())", "def deleted(self):\n\n return self.filter(status='deleted')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete should mark a message as deleted and update the thread.
def test_delete(self): # Create a thread with two messages thread = self.create_thread() message = mommy.make( Message, thread=thread, sender=thread.first_message.sender) # Delete the second message message = Message.objects.get(pk=message.pk) message.delete(...
[ "def delete(self):\n self._queue.delete_message(self._message)", "def test_delete_message_is_only_message_in_thread(self):\n thread = self.create_thread()\n thread.first_message.delete()\n thread = Thread.objects.with_deleted().get(pk=thread.pk)\n self.assertEqual(thread.status,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete should update thread.first_message if message was first.
def test_delete_message_is_first_message(self): # Create a thread with two messages thread = self.create_thread() message = mommy.make( Message, thread=thread, sender=thread.first_message.sender) # Delete the first message thread = Thread.objects.get(pk=thread.pk) ...
[ "def test_delete_message_is_only_message_in_thread(self):\n thread = self.create_thread()\n thread.first_message.delete()\n thread = Thread.objects.with_deleted().get(pk=thread.pk)\n self.assertEqual(thread.status, 'deleted')\n self.assertEqual(thread.total_messages, 0)", "def t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete should update thread.latest_message if message was last.
def test_delete_message_is_latest_message(self): # Create a thread with two messages thread = self.create_thread() message = mommy.make( Message, thread=thread, sender=thread.first_message.sender) # Delete the second message message = Message.objects.get(pk=message.p...
[ "def test_delete_message_is_only_message_in_thread(self):\n thread = self.create_thread()\n thread.first_message.delete()\n thread = Thread.objects.with_deleted().get(pk=thread.pk)\n self.assertEqual(thread.status, 'deleted')\n self.assertEqual(thread.total_messages, 0)", "def d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete should mark a thread as deleted if it was the only message.
def test_delete_message_is_only_message_in_thread(self): thread = self.create_thread() thread.first_message.delete() thread = Thread.objects.with_deleted().get(pk=thread.pk) self.assertEqual(thread.status, 'deleted') self.assertEqual(thread.total_messages, 0)
[ "def test_delete(self):\n # Create a thread with two messages\n thread = self.create_thread()\n message = mommy.make(\n Message, thread=thread, sender=thread.first_message.sender)\n\n # Delete the second message\n message = Message.objects.get(pk=message.pk)\n me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Flagging a message 1 time should mark it as pending.
def test_flag(self): recipient = self.create_user() thread = self.create_thread(recipient=recipient) message = thread.first_message self.assertEqual(message.status, 'approved') message.flag(recipient) self.assertEqual(message.flags.count(), 1) self.assertEqual(mes...
[ "def pending(self):\n self.update({self.STATE: self.STATE_PENDING})", "def is_pending(self):\n return self.type_id == STATE_PENDING", "def pending(self, pending):\n\n self._pending = pending", "def pending(self):\n self.state = Step.State.PENDING", "def is_pending(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New message should not be marked as read.
def test_get_message_new(self): message = mommy.make( 'connectmessages.Message', thread=self.thread, sender=self.sender) thread = Thread.public.by_user(user=self.user)[0] messages = thread.messages_for_user(self.user) self.assertEqual(messages[0], message) self.assert...
[ "def mark_delivery_as_read(self, username: str, message_id: str) -> None:\n pass", "def validate_no_message_in_buffer(self):\n message = self.read()\n if message:\n message += self.read(100)\n raise AssertionError(\n 'Un-read message found in buffer; %s' %...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A message that has been read should show up as read.
def test_get_message_read(self): message = mommy.make( 'connectmessages.Message', thread=self.thread, sender=self.sender) user_thread = UserThread.objects.get( thread=self.thread, user=self.user) user_thread.read = True user_thread.save() thread = Thread.p...
[ "def read(self, message):", "def is_read(self):\n\n return int(self.id) in self._topic()._rcache", "def mark_read(self):\n\n self._topic()._rcache[int(self.id)] = True", "def mark_as_read(self):\n if self.object_id is None or self.__is_draft:\n raise RuntimeError('Attempting to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New replies should have just the read messages marked read.
def test_get_message_reply(self): message1 = mommy.make( 'connectmessages.Message', thread=self.thread, sender=self.sender) message1.created_at = now() - datetime.timedelta(days=1) message1.save() message2 = mommy.make( 'connectmessages.Message', thread=self.threa...
[ "def get_replies(self, new=True):\n url = (\"https://api.imgur.com/3/account/{0}/\"\n \"notifications/replies\".format(self.name))\n return self._imgur._send_request(url, needs_auth=True)", "def test_delete_conversation_messages_marked_read(self):\n conv = G(Conversation, type=C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
User should see approved messages in groups they belong to.
def test_user_is_group_member_status_is_approved(self): group = mommy.make('groups.Group', moderated=True) thread = self.create_thread(group=group) message = thread.first_message message.status = 'approved' message.save() user = self.create_user() user.add_to_grou...
[ "def approve_me_group(message):\n load_users(message._client.users)\n sender_id = message._get_user_id()\n\n if (user_list[sender_id].is_unknown):\n message.reply(Strings['APPROVE_ME_REQUEST'])\n else:\n self_name = user_list[sender_id].level.name\n message.reply(\"Your status is al...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Nonmembers should not see messages in private groups.
def test_group_is_private_user_is_not_member(self): thread = self.create_thread() thread.group.private = True thread.save() message = thread.first_message user = self.create_user() self.assertFalse(message.visible_to_user(user))
[ "def test_message_group_by_non_member(self):\n code, data = self.message_group(self.imsi2, self.groupname,\n 'Hello there!')\n self.assertEqual(403, code)\n self.assertEqual('Forbidden', data)", "def test_group_is_private(self):\n group = mommy.ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test replies sent by banned users are visible only to that user
def test_reply_from_banned_user(self): # Create 2 users. By default neither is banned, but one will be soon viewing_user = self.create_user() banned_user = self.create_user() # Create a new group and add both our users to it group = self.create_group() viewing_user.add_t...
[ "def anti_bot(self, message):\n msg_list = self.ts.get_human_readable_message(message).lower().split(' ')\n bot_creation_date = self._get_creation_date(msg_list[1])\n viewers = self.ts.fetch_chatters_from_API()['viewers']\n mod_list = self.ts.get_mods()\n with codecs.open('whiteli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Group moderators should see any message sent to their group.
def test_user_is_group_moderator(self): thread = self.create_thread() user = self.create_user() thread.group.owners.add(user) message = thread.first_message message.status = 'pending' message.save() self.assertTrue(message.visible_to_user(user))
[ "def force_accept(self, group):\n self.mod_queue.force_accept(group)\n \n # sponsors become members\n if group.is_accepted():\n self._sponsors_to_members(group)", "def test_message_group_by_non_member(self):\n code, data = self.message_group(self.imsi2, self.groupname...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The sender of a message should be able to see their own message.
def test_user_is_sender_message_is_moderated(self): thread = self.create_thread() message = thread.first_message message.status = 'pending' message.save() self.assertTrue(message.visible_to_user(message.sender))
[ "def _is_message_by_self(self, message: Message) -> bool:\n return message.sender == self.self_address", "def msg_from_owner(self, msg):\n jid = self.get_real_jid(msg)\n return jid in self.acl.owners", "def publish_message(self, sender, msg: str) -> None:\n for member in self._all_me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Vetoed messages should not be visible to anyone.
def test_message_is_vetoed(self): thread = self.create_thread() message = thread.first_message message.status = 'vetoed' message.save() self.assertFalse(message.visible_to_user(message.sender))
[ "def CanVeto(self):\r\n\r\n return self.canveto_flag and self.veto_flag", "def CanVeto(*args, **kwargs):\n return _core_.CloseEvent_CanVeto(*args, **kwargs)", "def veto():", "def mark_offtopic(self, user, offtopic=True):\n if not (self.category and self.category.can_moderate(user)):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return thread if user is a recipient.
def test_user_is_recipient(self): UserThread.objects.create(user=self.user, thread=self.thread) self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread )
[ "def get_thread_for_sender(self, request):\n participants = Thread.objects.get(id=request.thread.id).participants.all()\n try:\n if request.sender not in participants:\n raise Exception\n except Exception:\n raise ValueError('No such thread.')", "def other...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return thread if user is a group member.
def test_user_is_group_member(self): self.user.add_to_group(self.thread.group.pk) self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread )
[ "def is_user_in_group(user, group):\n return find_group(user, group)", "def user_is_group_member(self, group=None):\n if isinstance(group, str):\n return GroupMembership.objects.filter(\n user=self, group__name=group\n ).count() == 1\n else:\n return GroupMembershi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return thread if user is a group owner.
def test_user_is_group_owner(self): self.thread.group.owners.add(self.user) self.assertEqual( Thread.public.get_by_user( thread_id=self.thread.pk, user=self.user), self.thread )
[ "def owner(self) -> 'user.User':\n return self.group.owner if self.group is not None else self.direct_owner", "def is_user_in_group(user, group):\n return find_group(user, group)", "def test_user_is_group_moderator(self):\n thread = self.create_thread()\n user = self.create_user()\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Raise ObjectDoesNotExist if user doesn't have access.
def test_user_does_not_have_access(self): self.assertRaises( ObjectDoesNotExist, Thread.public.get_by_user, **{'thread_id': self.thread.pk, 'user': self.user} )
[ "def handle_object_not_found(self):\n pass", "def get_no_access_error(self, request, *args, **kwargs):\n if request.user.is_authenticated:\n logger.warning('%s %s: user %s does not have '\n 'permission to access this resource.',\n reques...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should mark UT as archived.
def test_archive(self): thread = self.create_thread() ut = UserThread.objects.get( user=thread.recipients.first(), thread=thread) ut_id = ut.pk ut.archive() ut = UserThread.objects.get(pk=ut_id) self.assertEqual(ut.status, 'archived')
[ "def test_archive_run(self):\n pass", "def test_unarchive_run(self):\n pass", "def test_admin_can_modify_archived(self):\n response = self._try_modify_archived_as(self.get_admin())\n self.assertEqual(response.status_code, status.HTTP_200_OK)", "def archived(self, archived):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show updatefeedback form and process it.
def update_feedback(feedback_id): feedback = Feedback.query.get(feedback_id) if 'username' not in session or feedback.username != session['username']: flash('Please login first!') return redirect('/login') form = FeedbackForm(obj=feedback) if form.validate_on_submit(): feedba...
[ "def update_feedback_form(feedback_id):\r\n fb = Feedback.query.get_or_404(feedback_id)\r\n username = fb.users.username\r\n if check_session_status(username) != \"authorized\":\r\n message = common_flashes(check_session_status(username)[0])\r\n flash(message[0],message[1])\r\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retourne la liste des valeurs de P sur les entrées figurant dans liste_x
def liste_P(liste_x): return [P(x) for x in liste_x]
[ "def get_pareto_points(self):\n pareto_points = []\n for i, p in enumerate(self):\n pareto_points = pareto_points + [[p.x, p.y, p.data]]\n \n return pareto_points", "def points(self):\n p = []\n for v in self.iter():\n p.append((v.x, v.y))\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the new sneaker creation page.
def test_new(self): result = self.client.get('/sneakers/new') self.assertEqual(result.status, '200 OK') self.assertIn(b'New Sneaker', result.data)
[ "def test_create(self):\n self._run_tests(\"create\")", "def test_can_create_page(self):\n pass", "def test_create(self):\n pass", "def test_create_tribe_page(self):\n\n response = self.client.get('/tribes/new',\n content_type='html/text')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test editing a single sneaker
def test_edit_sneaker(self, mock_find): mock_find.return_value = sample_sneaker result = self.client.get(f'/sneakers/{sample_sneaker_id}/edit') self.assertEqual(result.status, '200 OK') self.assertIn(b'sneakers', result.data)
[ "def test_swimmer_edit(self):\n self.client.login(username='user', password='password')\n swimmer = test.create_swimmer(self.team)\n swimmer.set_age()\n response = self.client.get(reverse('teams:swimmerDetail', kwargs={\n 'abbr': self.team.abbr,\n 's_id': sw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filters a segmented image by getting rid of the components with too few pixels
def filter_by_size(img_segm): numbers = np.zeros(np.max(img_segm-1)) for i in range(1,np.max(img_segm)): numbers[i-1] = np.sum(img_segm==i) indexes = np.arange(1,np.max(img_segm)) #indexes = indexes[numbers>np.mean(numbers)] #Deletes the 1-pixel elements indexes = indexes[numbe...
[ "def clean(img):\n\n label_img = label(img, connectivity=2)\n props = sorted(regionprops(label_img), key=lambda x: x.area)\n clean = morphology.binary_closing(img)\n\n clean = morphology.remove_small_holes(clean)\n return morphology.remove_small_objects(clean,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the positions of centroids in a segmented image. Returns the centroids numbers in order
def centroids(img_segm): m = np.amax(img_segm) xs = np.zeros(m) ys = np.zeros(m) for i in range(0,m): pos_list = np.where(img_segm==i+1) xs[i] = np.mean(pos_list[0]) ys[i] = np.mean(pos_list[1]) return xs,ys
[ "def centroids(img_segm):\n m = int(np.amax(img_segm))\n xs = np.zeros(m)\n ys = np.zeros(m)\n \n for i in range(0,m):\n pos_list = np.where(img_segm==i+1)\n xs[i] = np.mean(pos_list[0])\n ys[i] = np.mean(pos_list[1])\n return xs,ys", "def centroids(img):\n _, _, _, centr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates the list of labels based on the correspondance list image is the new image to update
def updateLabels(correspondance_list,labels_list,i,image): l_prev_index = len(labels_list[(i-1)%2]) l_curr_index = len(labels_list[i%2]) prev_index = labels_list[(i-1)%2] index_changes = [] ref_image = np.copy(image) if l_prev_index==l_curr_index: #Same number of cells for x,...
[ "def on_update_image_labels_from_tool(self, image_id, labels_and_metadata):\n pass", "def re_label(img):\r\n labels = []\r\n for i in range(0,len(img)):\r\n for j in range(0,len(img[0])):\r\n if img[i][j] != 0 and img[i][j] not in labels:\r\n labels.append(img[i][j])\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes a cost matrix for the different distances between centroids The rows represent the centroids in the previous frame The columns the centroids in the next frame Returns the cost matrix
def fillCostMatrix(xs0,ys0,xs1,ys1): M = int ( max(len(xs0),len(xs1)) ) #Number of centroids. costMatrix = np.zeros((M,M)) x_rows = np.zeros(M) x_rows[0:len(xs0)] = xs0 y_rows = np.zeros(M) y_rows[0:len(xs0)] = ys0 x_cols = np.zeros(M) x_cols[0:len(xs1)] = xs1 y_cols = np.zeros(...
[ "def fillCostMatrix(xs0,ys0,xs1,ys1):\n M = int ( max(len(xs0),len(xs1)) ) #Number of centroids.\n costMatrix = np.ones((M,M))*-1\n x_rows = np.zeros(M)\n x_rows[0:len(xs0)] = xs0\n y_rows = np.zeros(M)\n y_rows[0:len(xs0)] = ys0\n \n x_cols = np.zeros(M)\n x_cols[0:len(xs1)] = xs1\n y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes flickering artefacts considering that a signal flickering in time is an artefact. Can only handle one flickering thing at a time for now.
def filter_out_flickers(total_buffer,index_disappeared): wait_for_disparition = False candidate_for_disparition = -1 to_destroy = [] #List of 3D tuples (value,first_index,last_index) of segmented elements to remove from image beginning_index = -1 premier_i =-1 list_of_is =[] prev...
[ "def removeFluxSurfaces(self):\n if self._fluxOverlayHandles is not None:\n for h in self._fluxOverlayHandles:\n h.remove()\n\n self._fluxOverlayHandles = []\n self.overlayFluxSurfaces = False", "def eliminateFlicker(self, state, previousPos, pipelinePage):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From the list of events and the list of elements destroyed, returns the list of events remaining to be processed.
def get_remaining_events(index_disappeared,to_destroy): index_cp = index_disappeared[:] for i,deb,fin in to_destroy: index_cp = [(x,y,z) for x,y,z in index_cp if (x!=deb and x!=fin)] return index_cp
[ "def treatAsDestroy(leaving, arriving):\n\ttmp = []\n\tfor elem in leaving:\n\t\tif elem not in arriving:\n\t\t\ttmp.append(elem)\n\treturn tmp", "def cleanup_event_list(self):\n self._event_list, self._event_index_list = \\\n zip(*SimpleDeduplicator.remove_duplicates_from_event_list(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests is the triplet event (index,difference,label) is a fusion event
def isFusion(event,buff): index,diff,label = event label = label[0] if diff>0: return False,[] img_before = np.copy(buff[:,:,index-1]) img_after = np.copy(buff[:,:,index]) mask_before = (img_before==label).astype(np.uint8) nb_elts_before = np.amax(img_before) kernel = np.ones((7,...
[ "def _analyze_inputs(self):\n events1 = self.events1\n events2 = self.events2\n common_gti = events1.gti\n if events2 is None or events2 is events1:\n self.events2 = self.events1\n self.same_events = True\n else:\n common_gti = cross_two_gtis(event...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests is the triplet event (index,difference,label) is a Division event
def isDivision(event,buff): index,diff,label = event label = label[0] if diff<0: return False,[] img_before = np.copy(buff[:,:,index-1]) img_after = np.copy(buff[:,:,index]) mask_after = (img_after==label).astype(np.uint8) nb_elts_after = np.amax(img_after) kernel = np.ones((7,7)...
[ "def test_div_operation(self):\n div_op = lib.DIV_OPERATOR\n context = env.empty_context()\n\n # Case 1: Two int values -> int\n args = [INT_VALUE, INT_VALUE]\n self.assertEqual(div_op.eval(args, context), INT_VALUE)\n # Case 2: Two float values -> float\n args = [FL...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
copy file from src to dst and minify web files along the way
def minify(src, dst, exclude_files=None, file_processors=None): LOGGER.info("copying files in <%s> to <%s>", src, dst) file_processors = DEFAULT_PROCESSORS if file_processors is None else file_processors prefix = os.path.join(src, "") for src_path in _walk_files(src, exclude_files): assert sr...
[ "def _minify(input_file_name: str, web_api_url: str) -> None:\n output_file_name = os.path.join(BUILD_DIR, input_file_name)\n file_content = open(input_file_name, mode='rb').read()\n response = requests.post(web_api_url, data={'input': file_content})\n minified = response.text\n if minified.startswit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the Fourier spectrum of an image.
def show_spectrum(image: np.ndarray): assert len(image.shape) == 2, 'image must be 2D' spectral = np.fft.fft2(image) spectral[0, 0] = 0 # Kill DC component spectrum = np.fft.fftshift(spectral) # Shift DC to center magnitude = np.log(np.abs(spectrum)) plt.imshow(magnitude, cmap='gray') plt....
[ "def plot_fft(self):\r\n\r\n self.ipx = int(self.imageData.shape[1]/2.)\r\n\r\n self.ipy = int(self.imageData.shape[2]/2.)\r\n\r\n nearf = np.absolute(self.DF[0:(self.freqs.shape[0]/2)-1,self.ipx-2:self.ipx+2,self.ipy-2:self.ipy+2])\r\n\r\n mpl.plot(self.freqs[0:(self.freqs.shape[0]/2)-1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
total pub by each local_authority return local_authority which has minimum value
def least_num_pubBylocal_auth(self): out=self.df.groupby('local_authority').agg(count('name').alias('lcount')) \ .sort(asc("lcount")).select("local_authority").limit(1) out.withColumnRenamed('local_authority','local_authority who has the least number of pubs') \ .write.mode("ove...
[ "def minInDict(dist):\r\n m = float('inf')\r\n for p in dist:\r\n for q in dist[p]:\r\n if dist[p][q] < m:\r\n m = dist[p][q]\r\n a,b = p,q\r\n return a,b", "def get_candidate(field_list, group):\n o = min(enumerate(field_list), key=lambda x: get_distance_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
count the words in name column after removing non alphanumeric value sort in decending and limit 5 results. ToDo remove the stop words
def topCommonwords(self,value=5): out=self.df.withColumn('word', explode(split(col('name'), ' '))) \ .withColumn('norm_word',trim(regexp_replace('word','[^a-zA-Z0-9 ]', ''))) \ .filter(col('norm_word') !='')\ .groupBy('norm_word')\ .count()\ .sort('cou...
[ "def top_words(name):\n row = wiki[wiki['name'] == name]\n word_count_table = row[['word_count']].stack('word_count', new_column_name=['word','count'])\n return word_count_table.sort('count', ascending = False)", "def custom_filter(text):\n\tregex = re.compile('[^a-zA-Z]{2,}')\n\ttext = regex.sub(' ', te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registration logic of subgroups, should be overwritten in main CLI
def register_cli(cls): for cmd in cls.SUB_GROUP_COMMANDS: getattr(cls, cls.SUB_GROUP_NAME).add_command(getattr(cls, cmd))
[ "def appendSubSystemGroup(self):\n pass", "def sub_command_group(self, name=None, **kwargs):\r\n def decorator(func):\r\n if self.child_type is None:\r\n if len(self.registerable.options) > 0:\r\n self.registerable.options = []\r\n self.chi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[Int] > tf.Tensor > String > [tf.Variable]? > (TargetNode, LossNode, Optimiser) Create metrics target node, loss node, and optimiser for a regression model.
def regression_metrics(output_node_shape, output_node, name, variables=None): target_node = placeholder_node( name + ".target", output_node_shape, dynamic_dimensions=1 ) loss_node = tf.losses.mean_squared_error(target_node, output_node) optimiser = default_adam_optimiser(loss_node, name, variabl...
[ "def reconstruction_metrics(input_node, reconstruction_node, name, variables=None):\n loss_node = tf.losses.mean_squared_error(input_node, reconstruction_node)\n optimiser = default_adam_optimiser(loss_node, name, variables=variables)\n return loss_node, optimiser", "def create_regressor(config):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[Int] > tf.Tensor > String > [tf.Variable]? > (TargetNode, LossNode, Accuracy, Optimiser) Create metrics target node, loss node, accuracy node, and optimiser for a classification model.
def classification_metrics_with_initialiser( output_node_shape, output_node, name, variables=None, target=None ): target_node = ( placeholder_node(name + ".target", output_node_shape, dynamic_dimensions=1) if target is None else target ) loss_node = tf.losses.log_loss(target_node...
[ "def classification_metrics(\n output_node_shape, output_node, name, variables=None, target=None\n):\n t, l, a, o, _ = classification_metrics_with_initialiser(\n output_node_shape, output_node, name, variables=variables, target=target\n )\n return t, l, a, o", "def build_classification_graph(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[Int] > tf.Tensor > String > [tf.Variable]? > (TargetNode, LossNode, Accuracy, Optimiser) Create metrics target node, loss node, accuracy node, and optimiser for a classification model.
def classification_metrics( output_node_shape, output_node, name, variables=None, target=None ): t, l, a, o, _ = classification_metrics_with_initialiser( output_node_shape, output_node, name, variables=variables, target=target ) return t, l, a, o
[ "def classification_metrics_with_initialiser(\n output_node_shape, output_node, name, variables=None, target=None\n):\n target_node = (\n placeholder_node(name + \".target\", output_node_shape, dynamic_dimensions=1)\n if target is None\n else target\n )\n loss_node = tf.losses.log_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tf.Tensor > tf.Tensor > String > [tf.Variable]? > (LossNode, Optimiser) Create reconstruction metrics for an autoencoder, which penalises the distance between an input and a reconstructed output in the vector space.
def reconstruction_metrics(input_node, reconstruction_node, name, variables=None): loss_node = tf.losses.mean_squared_error(input_node, reconstruction_node) optimiser = default_adam_optimiser(loss_node, name, variables=variables) return loss_node, optimiser
[ "def autoencoder_loss(self, inputs, reconstruction):\n return self.ae_loss_weight * self.mse(inputs, reconstruction)\n #return tf.image.ssim(tf.reshape(inputs, [100, 28, 28]),\n # tf.reshape(reconstruction, [100, 28, 28]), 1.0)", "def autoencoder(X, inp_dims=204...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tf.Node > String > [tf.Variable]? > (tf.Op, tf.Op) Create an Adam optimiser operation, along with an operation for initialising only the variables used internally by the optimiser.
def default_adam_optimiser_with_initialiser(loss_node, name, variables=None): optimiser = tf.train.AdamOptimizer(name=name + ".adam_optimiser") return ( optimiser.minimize(loss_node, var_list=variables, name=name + ".minimise"), tf.variables_initializer(optimiser.variables()), )
[ "def default_adam_optimiser(loss_node, name, variables=None):\n return tf.train.AdamOptimizer(name=name + \".adam_optimiser\").minimize(\n loss_node, var_list=variables, name=name + \".minimise\"\n )", "def create_Adam_op(loss, alpha, beta1, beta2, epsilon):\n return (tf.train.AdamOptimizer(learni...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LossNode > String > [tf.Variable]? > Optimiser Create an Adam optimiser with default learning parameters set to minimise the given loss node.
def default_adam_optimiser(loss_node, name, variables=None): return tf.train.AdamOptimizer(name=name + ".adam_optimiser").minimize( loss_node, var_list=variables, name=name + ".minimise" )
[ "def default_adam_optimiser_with_initialiser(loss_node, name, variables=None):\n optimiser = tf.train.AdamOptimizer(name=name + \".adam_optimiser\")\n return (\n optimiser.minimize(loss_node, var_list=variables, name=name + \".minimise\"),\n tf.variables_initializer(optimiser.variables()),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tf.Tensor > tf.Tensor > String > tf.Tensor Create a node which measures the accuracy of a predictor as compared to a target node, where the prediction is considered correct if it is on the same side of 0.5 as the target.
def accuracy(prediction_node, target_node, name): prediction_positive = tf.less(0.5, prediction_node) target_positive = tf.less(0.5, target_node) correct = tf.equal(prediction_positive, target_positive) correct_floats = tf.cast(correct, tf.float32) return tf.reduce_mean(correct_floats, name=name)
[ "def compute_accuracy(self):\n self.test_predictions = tf.cast(tf.argmax(self.test_logits, 1), tf.int32)\n correct = tf.equal(self.episode.test_labels, self.test_predictions)\n return tf.reduce_mean(tf.cast(correct, tf.float32))", "def calc_accuracy(node, data):\r\n right_prediction = 0\r\n wrong_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load the simulated trajectories of 2D Ising model.
def load_ising(lattice=10, seed=1, sim_steps=100000, init='random', value=1, progress_bar=True, pbar_mode=None, **kwargs): np.random.seed(seed) sim = Ising2DSimulator(lattice=lattice, relax_step=sim_steps, use_step=sim_steps, **kwargs) traj = sim.run(init=init, value=value, progress_bar=progr...
[ "def load_model(self):\n self.pred_net.load((self.save_path / \"iqn_pred_net\").absolute().as_posix())\n self.target_net.load((self.save_path / \"iqn_target_net\").absolute().as_posix())", "def simulate_trajectories(kav):\n print \"Simulating \"+str(kav)\n wt_trajectories = []\n avp_trajectories = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the folding pathway example of the protein HP35.
def load_pathway(path_idx=1, preprocess=True): assert path_idx in [1, 2], 'Unavailable index, must be 1 or 2.' url = f'https://raw.githubusercontent.com/PengTao-HUST/GDNB/master/data/pathway{path_idx}.txt' cache_dir = sys.modules['gdnb'].__path__[0] + '/data/' if not os.path.exists(cache_dir): ...
[ "def load_forest():\n return utilites.loadVariableFromFile(\"Corel5K/forest_400_trees_64_feats/forest.pkl\")", "def loadSTEP(self):\n self.CAD = Import.open(self.STPfile)\n self.CADdoc = FreeCAD.ActiveDocument\n\n #Coordinate permutation if necessary\n if self.permute_mask=='True':\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the gene expression data of the muscle of mouses.
def load_muscle(preprocess=True, mean_cut=None): url = f'https://raw.githubusercontent.com/PengTao-HUST/GDNB/master/data/muscle.txt' cache_dir = sys.modules['gdnb'].__path__[0] + '/data/' if not os.path.exists(cache_dir): os.makedirs(cache_dir) data_file = os.path.basename(url) full_path ...
[ "def read_gene_expr_data(geneset_dict):\n handle = open(GENE_EXPR_FILENAME)\n records = Geo.parse(handle)\n\n # gsm ids of the normal subjects\n normal_subjects = []\n\n # geneset row ids\n X_groups = {}\n for k in geneset_dict.keys():\n X_groups[k] = set()\n\n X = []\n y = []\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an executable script. In case a py_script_mode has been set to create a .py script the shell is expected to have the PATHEXT environment variable to include ".PY" in order to properly launch the command without the .py extension.
def create_executable_script(filepath, body, program=None, py_script_mode=None): from rez.config import config from rez.utils.platform_ import platform_ program = program or "python" py_script_mode = py_script_mode or config.create_executable_script_mode # https://github.com/AcademySoftwareFoundati...
[ "def make_executable(filename):\n print(\"Making {} executable\".format(filename))\n st = os.stat(filename)\n os.chmod(filename, st.st_mode | stat.S_IEXEC)", "def create_python_batch(self, name, script_name,\r\n workdir=None, options=None, command=None):\r\n if options i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluates the py_script_mode for the requested filepath on the given platform.
def _get_python_script_files(filepath, py_script_mode, platform): script_filepaths = [] base_filepath, extension = os.path.splitext(filepath) has_py_ext = extension == ".py" is_windows = platform == "windows" if ( py_script_mode == ExecutableScriptMode.single or py_script_mode == Ex...
[ "def execute_py_get_interpreter():\n\n return sg.pysimplegui_user_settings.get('-python command-', '')", "def is_py_script(item: str):\n is_it_py_script : bool = False\n ext : str = \".py\"\n if ext in item:\n is_it_py_script = True\n ...\n\n return is_it_py_script\n ...", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a 'forwarding' script. A forwarding script is one that executes some arbitrary Rez function. This is used internally by Rez to dynamically create a script that uses Rez, even though the parent environment may not be configured to do so.
def create_forwarding_script(filepath, module, func_name, *nargs, **kwargs): from rez.utils.platform_ import platform_ if platform_.name == "windows" and \ os.path.splitext(filepath)[-1].lower() != ".cmd": filepath += ".cmd" doc = dict( module=module, func_name=func_nam...
[ "def create_hookscript (\n fspath, filename, root, HOOK_SCRIPT_CLS=self.HOOK_SCRIPT_CLS\n ):\n return HOOK_SCRIPT_CLS ( fspath, filename=filename )", "def __init__(self, fritz_box, call_forwarding_dict):\n self.fritz_box = fritz_box\n self._name = \"callforwarding_\" + call_forw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function stores memory transitions. It takes in the current state, the action taken, the reward received, and the resulting state.
def store_transition(self, state, action, reward, new_state): # Compute index and store transition data index = self.memory_counter % self.max_mem_size self.memory[index, :] = np.hstack((state, [action, reward], new_state)) # Increment counter for next index self.memory_co...
[ "def _add_to_memory(self, state, action, next_state, reward, done):\n if len(self.memory) >= self.size_max_memory:\n self.memory.pop(0)\n self.memory += [Transition(state, action, next_state, reward, done)]", "def store_transition(self, s, a, r, s_):\n if not hasattr(self, 'memory_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function performs batch learning. It does random sampling of state transitions through the memory space to converge to an optimal strategy. It uses a target counter to keep track of how often we replace the target network
def learn(self, batch_size, target_cntr): # Update target parameter and learn step counter if self.learn_step_counter % target_cntr == 0: self.Q_target.load_state_dict(self.Q_eval.state_dict()) self.learn_step_counter += 1 # Select a random sub-sample of memory and get...
[ "def learn(self):\r\n \r\n # take a mini-batch from replay experience\r\n cur_batch_size = min(len(self.replay_exp), self.batch_size)\r\n mini_batch = random.sample(self.replay_exp, cur_batch_size)\r\n \r\n # batch data\r\n sample_states = np.ndarray(shape = (cur_bat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Searches logs for id by company shorthand or id
def searchLogs(self, searchTerm): ids = list(self.LOGS.keys()) if "by_date" in ids: ids.remove("by_date") for id in ids: if searchTerm.lower() == id.lower() or self.LOGS.get(id).get("companyShorthand") == searchTerm.upper(): return id return ""
[ "def find_log_id(xcresult_path):\n parsed = xcresulttool_json('get', '--path', xcresult_path)\n actions = parsed['actions']['_values']\n action = actions[-1]\n\n result = action['actionResult']['logRef']['id']['_value']\n _logger.debug('Using log id %s', result)\n return result", "def search_among_logs(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a new work item to the logs
def addNewWorkItem(self, id, company, companySH, summary, logData): now = datetime.datetime.now() data = {"status": ["open", now.strftime(CASE_DATE_FORMAT)], "companyName": company, "companyShorthand": companySH, "summary": summary, "log": [[now.strftime(LOG_DATE_FORMAT), logData]]} self.LOGS[id] = data self.lo...
[ "def add_log_entry(self, log_entry):\n self.log_entries.append(log_entry)", "def add_log(self,txt):\n try:\n now=datetime.datetime.now()\n new_item=QtWidgets.QListWidgetItem(now.strftime('%Y/%m/%d %H:%M:%S')+\": \"+txt)\n self.ui.logger_list.addItem(new_item)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes datetime & message to log.
def log(self, msg): current_datetime = self.get_date_time() self.file.write("%s %s\n" % (current_datetime, msg))
[ "def log(self, line):\n now = datetime.datetime.now()\n time = datetime.datetime.strftime(now, '(%d %b %Y %H:%M:%S)')\n with open(self.logfile, 'a') as log:\n log.write(time + ' ' + line + '\\n')", "def write_debug_log(self, msg):\n now = datetime.now().strftime('%Y-%m-%d %H...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends data to server via data channel.
def send_to_data_channel(self, sock, data): resp = sock.send(data) print_debug(resp) self.logger.log("Sent: %s" % data) return resp
[ "def send_data(self, data):\n self._transport.write(data)", "def writedata(self, data):\n if self.closed:\n return\n #self.log(\"Sending %r\" % (data,))\n try:\n self.sock.send(data)\n except Exception:\n # Any failure here is almost certainly fa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bind port socket so server can connect to it.
def port_connection(self, sock): sock.bind(('', 0)) # Bind to OS-assigned available & random port. sock.listen(1)
[ "def _bind(self):\n self.serversocket.bind((self.host, self.port))", "def bind_socket(self):\n try:\n self.socket.bind((self.host, self.port))\n self.socket.listen(5)\n except socket.error as e:\n print(\"Socket binding error: \" + str(e))\n time.sl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper for port_cmd() to parse in IP and Port of data channel.
def parse_port_req(self, sock): try: host_ip = self.s.getsockname()[0] # Get local IPv4 addr of client. host_port = sock.getsockname()[1] # Get opened port of socket. # PORT requires parameters split up as: # octet1,octet2,octet3,octet4,p1,p2 list_cs...
[ "def _check_ip_port_split(self):\n if self._type == \"A\":\n formatted_value = self._value.split(':')\n self._ip = formatted_value[0]\n self._port = int(formatted_value[1])", "def port(self, irc, msg, args, port):\n if port > 65535:\n irc.error('Port numbe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send PASS command to server.
def pass_cmd(self, password): print_debug("Executing PASS") command = "PASS %s\r\n" % password msg_rec = self.send_and_log(self.s, command) return msg_rec
[ "async def handle_password_prompt(self):\n self.applog.info(\"sending password %s\" % self.password)\n self._flush_buffer()\n self.pexpect_child.sendline(self.password)\n ret = self.pexpect_child.expect_exact(\n [self.cmd_prompt, pexpect.TIMEOUT, pexpect.EOF], timeout=10\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send CWD command to server.
def cwd_cmd(self, new_dir): print_debug("Executing CWD") command = "CWD %s\r\n" % new_dir msg_rec = self.send_and_log(self.s, command) return msg_rec
[ "def send_cwd(self):\n with self.send_lock:\n write_bytes(self.conn, ReplBackend._CHWD)\n write_string(self.conn, os.getcwd())", "def pwd_cmd(self):\n print_debug(\"Executing PWD\")\n command = \"PWD\\r\\n\"\n msg_rec = self.send_and_log(self.s, command)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send QUIT command to server.
def quit_cmd(self): print_debug("Executing QUIT") command = "QUIT\r\n" msg_rec = self.send_and_log(self.s, command) self.close_socket(self.s) # Close socket since we're done. return msg_rec
[ "def quit(self):\n self.irc.send(bytes(\"QUIT \" + \" :kbye...\\r\\n\", encoding=\"utf-8\"))", "def quit(self, reason=''):\n reply = 'QUIT :%s' % (reason)\n self.send(reply)", "def do_QUIT(self):\r\n self.send_response(200)\r\n self.end_headers()\r\n self.server.stop = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send PASV command to server.
def pasv_cmd(self): print_debug("Executing PASV") command = "PASV\r\n" msg_rec = self.send_and_log(self.s, command) print_debug(msg_rec) # PASV creates a new connection from client to server. sock = new_socket() pasv_ip, pasv_port = self.parse_pasv_resp(msg_rec) ...
[ "def pasv_action(self):\r\n if self.support_pasv_mode:\r\n self.pasv = True\r\n self.send_to_client(\"227 Entering passive mode\")\r\n else:\r\n self.send_to_client(\"502 This server does not support passive mode\")", "def epsv_cmd(self, proto=\"1\"):\n print_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send PORT command to server.
def port_cmd(self): print_debug("Executing PORT") # PORT creates a new connection from server to client. sock = new_socket() self.port_connection(sock) # Get required parameters for PORT command. port_params, host_ip, host_port = self.parse_port_req(sock) print_de...
[ "def _send_command_to_device(self, command, port=0):\n transport = self._transport_processes[port]\n transport.send_command(transport_process.CMD_TRANSPORT_WRITE, command)", "def SERIAL_SEND_cmd(self, cmd):\n # Must be connected & operational\n if self.State == 0:\n # a slightly mor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send EPSV command to server.
def epsv_cmd(self, proto="1"): print_debug("Executing EPSV") net_prt = proto command = "EPSV %s\r\n" % net_prt msg_rec = self.send_and_log(self.s, command) print_debug(msg_rec) # EPSV creates a new connection from client to server. sock = new_socket() # Ge...
[ "def epsv_action(self):\r\n if self.support_pasv_mode:\r\n self.epsv = True\r\n self.send_to_client(\"229 Entering extended passive mode\")\r\n else:\r\n self.send_to_client(\"502 This server does not support extended passive mode\")", "def pasv_cmd(self):\n p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send EPRT command to server.
def eprt_cmd(self, proto="1"): print_debug("Executing EPRT") sock = new_socket() # Create port connection using extended info. self.port_connection(sock) net_prt = proto # Get required parameters for EPRT command. eprt_params, net_addr, tcp_port = self.parse_eprt_...
[ "def sendCmdExec(self, tcPacket):\n LOG_INFO(\"EDEN.Client.sendCmdExec\", \"EDEN\")\n pdu = EGSE.EDENPDU.PDU()\n pdu.pduType = EGSE.EDENPDU.PDU_TYPE_CMD\n pdu.subType = EGSE.EDENPDU.SUB_TYPE_EXEC\n pdu.setDataField(tcPacket)\n self.sendPDU(pdu)", "def epsv_cmd(self, proto=\"1\"):\n print_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send RETR command to server.
def retr_cmd(self, sock, path, transfer_type): print_debug("Executing RETR") command = "RETR %s\r\n" % path msg_rec = self.send_and_log(self.s, command) print_debug(msg_rec) # Ensure we got a success message from the FTP server. if get_ftp_server_code(msg_rec) == FTP_STAT...
[ "def do_rcon(self, line):\n if not self.mbiiserver:\n print(\"You must first connect to a server\")\n return\n try:\n response_type, response_data = self.mbiiserver.server.rcon(line)\n print(response_data)\n except Exception as e:\n print(e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send STOR command to server.
def stor_cmd(self, sock, local_file, remote_path, transfer_type): print_debug("Executing STOR") command = "STOR %s\r\n" % remote_path msg_rec = self.send_and_log(self.s, command) print_debug(msg_rec) # Ensure we got a success message from the FTP server. if get_ftp_server...
[ "def stor_action(self, path):\r\n try:\r\n pass\r\n file = open(path, 'w+')\r\n self.send_to_client(\"150 File okay, start writing file contents\")\r\n content = str(self.client.recv(1024))\r\n file.write(content)\r\n file.close()\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send PWD command to server.
def pwd_cmd(self): print_debug("Executing PWD") command = "PWD\r\n" msg_rec = self.send_and_log(self.s, command) return msg_rec
[ "def send_cwd(self):\n with self.send_lock:\n write_bytes(self.conn, ReplBackend._CHWD)\n write_string(self.conn, os.getcwd())", "def pwd_action(self):\r\n self.send_to_client(\"257 {0}\".format(self.current_directory))", "def cwd_cmd(self, new_dir):\n print_debug(\"Ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send SYST command to server.
def syst_cmd(self): print_debug("Executing SYST") command = "SYST\r\n" msg_rec = self.send_and_log(self.s, command) return msg_rec
[ "async def _send_sysex(self, sysex_command, sysex_data=None):\n if not sysex_data:\n sysex_data = []\n\n # convert the message command and data to characters\n sysex_message = chr(PrivateConstants.START_SYSEX)\n sysex_message += chr(sysex_command)\n if len(sysex_data):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close socket passed as arg.
def close_socket(self, sock): print_debug("Closing socket.") try: sock.close() # If data socket being closed, print status message. if sock != self.s: print_debug("Socket closed.") except socket.error: error_quit("Error closing sock...
[ "def close_socket(self):\n\t\tself.__socket.close()", "def socketClose(self, sock_name):\n current_socket = self.open_sockets[sock_name]\n result = pycoclib.pico_close(current_socket['fd'])\n del self.open_sockets[sock_name]\n\n return self.check_error(result)", "def close(sock):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cast port to an int and ensure it is between 0 and 65535.
def validate_port(port): try: port = int(port) # Is port a valid port number? if port > 65535 or port < 0: raise ValueError('Port is not between 0 and 65535!') except ValueError: error_quit("Port is not between 0 and 65535!", 400) except Exception: error_q...
[ "def valid_port(ctx, param, value):\n try:\n value = int(value)\n except ValueError:\n pass\n\n return value", "def is_port(port):\r\n return (port > 0) and (port < 65536)", "def _port_to_int(port):\n if isinstance(port, int):\n return port\n # Assume it's two ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt user for Username.
def prompt_username(): msg = "Enter Username: " username = raw_input(msg) return username
[ "def _ask_for_username() -> str:\r\n while True:\r\n username = input(\"Username: \").strip()\r\n\r\n if \" \" in username:\r\n print(\"There is a whitespace in your username.Please print again.\")\r\n elif len(username)>0:\r\n return username\r\n else:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt user for Password. Hide input (make stdin invisible).
def prompt_pass(): msg = "Enter Password: " password = getpass.getpass(msg) return password
[ "def prompt_for_password():\n with warnings.catch_warnings():\n warnings.filterwarnings('error', category=getpass.GetPassWarning,\n append=True)\n try:\n # temporarily set signal handling back to default to avoid user\n # Ctrl-c leaving terminal ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the error code (a threedigit string) of an FTP server response.
def get_ftp_server_code(resp_msg): if resp_msg.startswith("'"): print_debug(resp_msg[1:4]) return resp_msg[1:4] else: print_debug(resp_msg[0:3]) return resp_msg[0:3]
[ "def error_code(self):\n return self._resp.error_code", "def error_code(self) -> int:\n return pulumi.get(self, \"error_code\")", "def error_code(self):\n return self._error_code", "def error_code(self):\r\n return self._arm.error_code", "def get_error_code(self):\n\n\t\treturn s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt user for Username & Password, authenticate with FTP server.
def login(ftp): # Get username username = prompt_username() ftp.user_cmd(username) # Get password password = prompt_pass() pass_data = ftp.pass_cmd(password) # Retry inputs if unsuccessful authentication. while get_ftp_server_code(pass_data) != FTP_STATUS_CODES["SUCCESSFUL_LOGIN"]: ...
[ "def _login(self,):\n self._send_cmd(self._control_socket, \"USER \" + input(\"USERNAME: \"))\n self._read_resp()\n self._send_cmd(self._control_socket, \"PASS \" + input(\"PASSWORD: \"))\n password_resp = self._read_resp()\n if parse_ftp_response(password_resp)[0] == LOGIN_SUCCES...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a new socket.
def new_socket(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) return s
[ "def _create_socket():\n sock = socket.socket()\n return sock", "def create_socket():\n return socket.socket(\n family=socket.AF_INET,\n type=socket.SOCK_STREAM,\n )", "def create_socket(self):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt for what to download, then call the appropriate FTP command.
def do_download(ftp): # Active (PORT), Passive (PASV), ExtActive (EPRT), or ExtPassive (EPSV)? output, sock, transfer_type = get_transfer_output_and_socket(ftp) print_debug(output + "\n") # What file to download? path = raw_input("What file do you want to download?\n> ") while not path: ...
[ "def doNcFTPDownload(logger: logging.Logger):\n cFuncName = colored(os.path.basename(__file__), 'yellow') + ' - ' + colored(sys._getframe().f_code.co_name, 'green')\n\n # locate 'ncftpget' program\n exeNCFTPGET = location.locateProg('ncftpget', logger)\n\n # create and change to download directory\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes content of data_rec to a file in path.
def write_to_local(path, data_rec): path, filename = os.path.split(path) with open(filename, 'wb') as f: f.write(data_rec) f.close()
[ "def write_data_in_file(self, data, fichier, mode=\"w\"):", "def write_file(data, file_path):\n with open(file_path, 'wb') as f:\n f.write(data)", "def write_file(path, data):\n with open_local_or_gcs(path, 'w') as h_dest:\n h_dest.write(data) # pylint: disable=no-member", "def save_file(path, fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt for what to upload, then call the appropriate FTP command.
def do_upload(ftp): # Active (PORT), Passive (PASV), ExtActive (EPRT), or ExtPassive (EPSV)? output, sock, transfer_type = get_transfer_output_and_socket(ftp) print_debug(output + "\n") # What file to upload? local_file = raw_input("What local file do you want to upload?\n> ") is_file = os.path...
[ "def ftp_upload(ftp_obj, in_path, out_path, ftype):\n if ftype == 'txt':\n with open(in_path) as fobj:\n ftp_obj.storlines('STOR ' + out_path, fobj)\n else:\n with open(in_path, 'rb') as fobj:\n ftp_obj.storbinary('STOR ' + out_path, fobj, 1024)", "def cli(ctx, path, hist...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt for what to list, then call the appropriate FTP command.
def do_list(ftp): # Active (PORT), Passive (PASV), ExtActive (EPRT), or ExtPassive (EPSV)? output, sock, transfer_type = get_transfer_output_and_socket(ftp) print_debug(output + "\n") path = raw_input("What directory or file do you want to list (blank=current)?\n> ") try: if path: ...
[ "def main():\n print_debug(\"Starting...\")\n host, log_file, port = parse_args()\n logger = Logger(log_file)\n ftp = FTP(host, logger, port)\n do_ftp(ftp)", "def do_help(ftp):\n try:\n cmd = raw_input(\"What command do you need help with (blank=general)?\\n> \")\n if cmd:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt for what dir to change to; call the appropriate FTP command.
def do_cwd(ftp): new_dir = raw_input("What directory do you want to change to?\n> ") try: output = ftp.cwd_cmd(new_dir) if get_ftp_server_code(output) == FTP_STATUS_CODES["SUCCESSFUL_CWD"]: print("Successfully changed directory\n") else: print("Invalid directory o...
[ "def do_list(ftp):\n # Active (PORT), Passive (PASV), ExtActive (EPRT), or ExtPassive (EPSV)?\n output, sock, transfer_type = get_transfer_output_and_socket(ftp)\n print_debug(output + \"\\n\")\n\n path = raw_input(\"What directory or file do you want to list (blank=current)?\\n> \")\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call the appropriate FTP command to display the server's help info.
def do_help(ftp): try: cmd = raw_input("What command do you need help with (blank=general)?\n> ") if cmd: output = ftp.help_cmd(cmd) else: output = ftp.help_cmd() output = parse_server_response(output) print("%s\n" % output) except Exception as e: ...
[ "def ftp_help(self, **kwargs):\n rep = self.send(\"HELP\" + CRLF)\n return rep", "def printHelp(self):\n\n\thelpCommand = [\n\t\t\"=====================================================\",\n\t\t\"=====================================================\",\n\t\t\"connect - connect to local host\",\n\t\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls function associated with user's Main Menu choice.
def handle_main_menu_choice(choice, ftp): function_to_call = MAIN_MENU_SELECTIONS[choice][1] globals()[function_to_call](ftp) # Call the function.
[ "def execute_main_menu(self) -> None:\n user_choice = None\n while user_choice != 5:\n user_choice = Menu.prompt_main_menu()\n if user_choice == 1:\n self.view_budgets()\n elif user_choice == 2:\n self.record_transaction()\n eli...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main driver that parses args, creates our Logger & FTP objects, and starts the do_ftp driver.
def main(): print_debug("Starting...") host, log_file, port = parse_args() logger = Logger(log_file) ftp = FTP(host, logger, port) do_ftp(ftp)
[ "def main(ctx, verbose):\n\n home = Path.home()\n root = home.joinpath('.ftpctl')\n users_uploads = root.joinpath('ftpusers')\n users_credentials = root.joinpath('pure-ftpd', 'passwd')\n\n ctx.obj['HOME'] = home\n ctx.obj['ROOT'] = root\n ctx.obj['USERS_UPLOADS'] = users_uploads\n ctx.obj['U...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test current power if there is no data.
def test_current_power_w_no_data(self): self.port.data = {"notpower": 123} assert 0 == self.switch.current_power_w
[ "def hasPower(self):\n return self.power != 0", "def check_power(self):\n state = self.get_state()\n if(state):\n return state[\"pwr\"]", "def setPowerIfNecessary(self):\n if self.p.power == 0 and self.p.powerDensity > 0:\n self.setPowerFromDensity()", "def te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the accuracy per class and average puts 1 for invalid values (division per 0) returns average accuracy, accuracy per class
def stats_accuracy_per_class(cm): # equvalent to for class i to # number or true positive of class i (data[target==i]==i).sum()/ number of elements of i (target==i).sum() sums = np.sum(cm, axis=1) mask = (sums>0) sums[sums==0] = 1 accuracy_per_class = np.diag(cm) / sums #sum over lines accur...
[ "def accuracy(self):\n correct = float(np.sum(self.classify() == self.y_test.T))\n print(correct / len(self.y_test))", "def compute_accuracy(self):\n self.test_predictions = tf.cast(tf.argmax(self.test_logits, 1), tf.int32)\n correct = tf.equal(self.episode.test_labels, self.test_predictions)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the iou per class and average iou Puts 1 for invalid values returns average iou, iou per class
def stats_iou_per_class(cm, ignore_missing_classes=True): sums = (np.sum(cm, axis=1) + np.sum(cm, axis=0) - np.diag(cm)) mask = (sums>0) sums[sums==0] = 1 iou_per_class = np.diag(cm) / sums iou_per_class[np.logical_not(mask)] = -1 if mask.sum()>0: average_iou = iou_per_class[mask].mea...
[ "def avg_iou(self):\n return np.mean(self.ious_[np.arange(len(self.labels_)), self.labels_])", "def iou_score(pred_cls, true_cls, nclass=3):\n iou = []\n for i in range(nclass):\n # intersect = ((pred_cls == i) + (true_cls == i)).eq(2).item()\n # union = ((pred_cls == i) + (true_cls == ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute f1 scores per class and mean f1. puts 1 for invalid classes returns average f1 score, f1 score per class
def stats_f1score_per_class(cm): # defined as 2 * recall * prec / recall + prec sums = (np.sum(cm, axis=1) + np.sum(cm, axis=0)) mask = (sums>0) sums[sums==0] = 1 f1score_per_class = 2 * np.diag(cm) / sums f1score_per_class[np.logical_not(mask)] = -1 average_f1_score = f1score_per_class[ma...
[ "def f1_score(self):\n self.overall_f1_score = f1_score(\n self.y_true, self.y_pred, average = self.average_type).round(self.digits_count_fp)\n self.classes_f1_score = f1_score(\n self.y_true, self.y_pred, average = None).round(self.digits_count_fp)", "def F1_score(self):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return ordered list of graph points
def getGraphPoints(self, includeThresholds=True): gps = (gp for gp in self.graphPoints() if includeThresholds or not gp.isThreshold) def graphPointKey(a): try: return int(a.sequence) except ValueError: return sys.maxint retu...
[ "def points(self):\n return [vert.point for vert in self.vertices]", "def points(self):\n p = []\n for v in self.iter():\n p.append((v.x, v.y))\n return p", "def points(self) -> List[Point]:\n return self.__points", "def get_points(self):\n return self.poin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get ordered list of threshold graph points
def getThresholdGraphPoints(self): gps = [gp for gp in self.getGraphPoints() if gp.isThreshold] return gps
[ "def getGraphPoints(self, includeThresholds=True):\n gps = (gp for gp in self.graphPoints()\n if includeThresholds or not gp.isThreshold)\n def graphPointKey(a):\n try:\n return int(a.sequence)\n except ValueError:\n return sys.maxint\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if there is a thresholdgraphpoint with threshId=threshid
def isThresholdGraphed(self, threshId): return any(gp.threshId == threshId for gp in self.getThresholdGraphPoints())
[ "def is_threshold_used(self):\n rtn = False\n if(self.limit_threshhold > 0.00):\n rtn = True\n return rtn", "def isDataPointGraphed(self, dpName):\n from DataPointGraphPoint import DataPointGraphPoint\n return any(isinstance(gp, DataPointGraphPoint) and gp.dpName == d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if there is at least one graphpoint with a dsName equal to dpName.
def isDataPointGraphed(self, dpName): from DataPointGraphPoint import DataPointGraphPoint return any(isinstance(gp, DataPointGraphPoint) and gp.dpName == dpName for gp in self.getGraphPoints(includeThresholds=False))
[ "def getDataPointGraphPoints(self, dpName):\n from DataPointGraphPoint import DataPointGraphPoint\n return [gp for gp in self.graphPoints()\n if isinstance(gp, DataPointGraphPoint)\n and gp.dpName == dpName]", "def check_pds(self, k):\n return k in backend.pds_st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of graph point ids
def getGraphPointsNames(self): return [gp.id for gp in self.getGraphPoints()]
[ "def get_ids(self):\n return self._graphs.keys()", "def vertex_ids(self):\n return self.get_ids()", "def ids(self):\n\t\treturn(list(self.df.id.values))", "def polygon_ids(self):\n return self.get_ids()", "def _get_nodes_ids(self):\n nodes = self._get_nodes()\n nodes_ids =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a string that lists the names of the graphpoints used in this graph definition. If this graph definition has a perf template then note in the string which graphpoints are broken (in that they refer to nonexistent datapoints.)
def getGraphPointNamesString(self): names = [] for gp in self.getGraphPoints(): if hasattr(aq_base(gp), 'isBroken') and gp.isBroken(): names.append('%s(<span style="color: red">missing</span>)' % gp.id) ...
[ "def getGraphPointsNames(self):\n return [gp.id for gp in self.getGraphPoints()]", "def __str__(self):\n s = \"Point group '%s' (%s) has %d generator(s) and is of order %d.\" % (self.name, self.desc, len(self.generators), len(self.table))\n return s", "def __str__(self):\n return str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the graphpoint with the given id or something similar and add to self.graphPoints
def createGraphPoint(self, cls, newId): def getUniqueId(container, base): ids = set(container.objectIds()) new = base i = 2 while new in ids: new = '%s%s' % (base, i) i += 1 return new ...
[ "def appendPoint(self, pointId):\n self._pointIdList.append(pointId)\n self._pointList.append(self._idPositionDict[pointId])", "def manage_addCustomGraphPoint(self, new_id, flavor, REQUEST=None):\n exec 'import %s' % flavor\n cls = eval('%s.%s' % (flavor, flavor))\n gp = self.createGrap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }