code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def create_access(request, topic_id): topic_private = TopicPrivate.objects.for_create_or_404(topic_id, request.user) form = TopicPrivateInviteForm( topic=topic_private.topic, data=post_data(request)) if form.is_valid(): form.save() notify_access(user=form.get_user(), topic_private=topic_private) else: messages.error(request, utils.render_form_errors(form)) return redirect(request.POST.get('next', topic_private.get_absolute_url()))
Base
1
def test_get_ora2_responses_already_running(self): url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)}) with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task: mock_submit_ora2_task.side_effect = AlreadyRunningError() response = self.client.get(url, {}) already_running_status = "An ORA data report generation task is already in progress." self.assertIn(already_running_status, response.content)
Compound
4
def generic_visit(self, node): if type(node) not in SAFE_NODES: #raise Exception("invalid expression (%s) type=%s" % (expr, type(node))) raise Exception("invalid expression (%s)" % expr) super(CleansingNodeVisitor, self).generic_visit(node)
Class
2
def test_keepalive_http11_connclose(self): # specifying Connection: close explicitly data = "Don't keep me alive" s = tobytes( "GET / HTTP/1.1\n" "Connection: close\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self.connect() self.sock.send(s) response = httplib.HTTPResponse(self.sock) response.begin() self.assertEqual(int(response.status), 200) self.assertEqual(response.getheader("connection"), "close")
Base
1
def get_by_name(self, name, project): return ( Person.query.filter(Person.name == name) .filter(Project.id == project.id) .one() )
Class
2
def setup_db(cls, config_calibre_dir, app_db_path): cls.dispose() if not config_calibre_dir: cls.config.invalidate() return False dbpath = os.path.join(config_calibre_dir, "metadata.db") if not os.path.exists(dbpath): cls.config.invalidate() return False try: cls.engine = create_engine('sqlite://', echo=False, isolation_level="SERIALIZABLE", connect_args={'check_same_thread': False}, poolclass=StaticPool) with cls.engine.begin() as connection: connection.execute(text("attach database '{}' as calibre;".format(dbpath))) connection.execute(text("attach database '{}' as app_settings;".format(app_db_path))) conn = cls.engine.connect() # conn.text_factory = lambda b: b.decode(errors = 'ignore') possible fix for #1302 except Exception as ex: cls.config.invalidate(ex) return False cls.config.db_configured = True if not cc_classes: try: cc = conn.execute(text("SELECT id, datatype FROM custom_columns")) cls.setup_db_cc_classes(cc) except OperationalError as e: log.error_or_exception(e) cls.session_factory = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=cls.engine)) for inst in cls.instances: inst.initSession() cls._init = True return True
Base
1
def test_get_imports(self, mocker): from openapi_python_client.parser.properties import DateTimeProperty name = mocker.MagicMock() mocker.patch("openapi_python_client.utils.snake_case") p = DateTimeProperty(name=name, required=True, default=None) assert p.get_imports(prefix="") == { "from datetime import datetime", "from typing import cast", } p.required = False assert p.get_imports(prefix="") == { "from typing import Optional", "from datetime import datetime", "from typing import cast", }
Base
1
def category_list(): if current_user.check_visibility(constants.SIDEBAR_CATEGORY): if current_user.get_view_property('category', 'dir') == 'desc': order = db.Tags.name.desc() order_no = 0 else: order = db.Tags.name.asc() order_no = 1 entries = calibre_db.session.query(db.Tags, func.count('books_tags_link.book').label('count')) \ .join(db.books_tags_link).join(db.Books).order_by(order).filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag')).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Tags.name, 1, 1)).label('char')) \ .join(db.books_tags_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Tags.name, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Categories"), page="catlist", data="category", order=order_no) else: abort(404)
Base
1
def do_download_file(book, book_format, client, data, headers): if config.config_use_google_drive: #startTime = time.time() df = gd.getFileFromEbooksFolder(book.path, data.name + "." + book_format) #log.debug('%s', time.time() - startTime) if df: return gd.do_gdrive_download(df, headers) else: abort(404) else: filename = os.path.join(config.config_calibre_dir, book.path) if not os.path.isfile(os.path.join(filename, data.name + "." + book_format)): # ToDo: improve error handling log.error('File not found: %s', os.path.join(filename, data.name + "." + book_format)) if client == "kobo" and book_format == "kepub": headers["Content-Disposition"] = headers["Content-Disposition"].replace(".kepub", ".kepub.epub") response = make_response(send_from_directory(filename, data.name + "." + book_format)) # ToDo Check headers parameter for element in headers: response.headers[element[0]] = element[1] log.info('Downloading file: {}'.format(os.path.join(filename, data.name + "." + book_format))) return response
Base
1
def download(url, location): """ Download files to the specified location. :param url: The file URL. :type url: str :param location: The absolute path to where the downloaded file is to be stored. :type location: str """ request = urllib2.urlopen(url) try: content = request.read() fp = open(location, 'w+') try: fp.write(content) finally: fp.close() finally: request.close()
Base
1
def test_double_linefeed(self): self.assertEqual(self._callFUT(b"\n\n"), 2)
Base
1
def auth_role_public(self): return self.appbuilder.get_app.config["AUTH_ROLE_PUBLIC"]
Class
2
def guest_only(view_func): # TODO: test! @wraps(view_func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated: return redirect(request.GET.get('next', request.user.st.get_absolute_url())) return view_func(request, *args, **kwargs) return wrapper
Base
1
def render_POST(self, request): """ Register with the Identity Server """ send_cors(request) args = get_args(request, ('matrix_server_name', 'access_token')) result = yield self.client.get_json( "matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s" % ( args['matrix_server_name'], urllib.parse.quote(args['access_token']), ), 1024 * 5, ) if 'sub' not in result: raise Exception("Invalid response from homeserver") user_id = result['sub'] tok = yield issueToken(self.sydent, user_id) # XXX: `token` is correct for the spec, but we released with `access_token` # for a substantial amount of time. Serve both to make spec-compliant clients # happy. defer.returnValue({ "access_token": tok, "token": tok, })
Class
2
def test_basic_for_domain(): # Test Basic Authentication http = httplib2.Http() password = tests.gen_password() handler = tests.http_reflect_with_auth( allow_scheme="basic", allow_credentials=(("joe", password),) ) with tests.server_request(handler, request_count=4) as uri: response, content = http.request(uri, "GET") assert response.status == 401 http.add_credentials("joe", password, "example.org") response, content = http.request(uri, "GET") assert response.status == 401 domain = urllib.parse.urlparse(uri)[1] http.add_credentials("joe", password, domain) response, content = http.request(uri, "GET") assert response.status == 200
Class
2
def test_coupon_redeem_count_in_ecommerce_section(self): """ Test that checks the redeem count in the instructor_dashboard coupon section """ # add the coupon code for the course coupon = Coupon( code='test_code', description='test_description', course_id=self.course.id, percentage_discount='10', created_by=self.instructor, is_active=True ) coupon.save() # Coupon Redeem Count only visible for Financial Admins. CourseFinanceAdminRole(self.course.id).add_users(self.instructor) PaidCourseRegistration.add_to_order(self.cart, self.course.id) # apply the coupon code to the item in the cart resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': coupon.code}) self.assertEqual(resp.status_code, 200) # URL for instructor dashboard instructor_dashboard = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()}) # visit the instructor dashboard page and # check that the coupon redeem count should be 0 resp = self.client.get(instructor_dashboard) self.assertEqual(resp.status_code, 200) self.assertIn('Number Redeemed', resp.content) self.assertIn('<td>0</td>', resp.content) # now make the payment of your cart items self.cart.purchase() # visit the instructor dashboard page and # check that the coupon redeem count should be 1 resp = self.client.get(instructor_dashboard) self.assertEqual(resp.status_code, 200) self.assertIn('Number Redeemed', resp.content) self.assertIn('<td>1</td>', resp.content)
Compound
4
def test_conf_set_no_read(self): orig_parser = memcache.ConfigParser memcache.ConfigParser = ExcConfigParser exc = None try: app = memcache.MemcacheMiddleware( FakeApp(), {'memcache_servers': '1.2.3.4:5'}) except Exception, err: exc = err finally: memcache.ConfigParser = orig_parser self.assertEquals(exc, None)
Base
1
def format_runtime(runtime): retVal = "" if runtime.days: retVal = format_unit(runtime.days, 'duration-day', length="long", locale=get_locale()) + ', ' mins, seconds = divmod(runtime.seconds, 60) hours, minutes = divmod(mins, 60) # ToDo: locale.number_symbols._data['timeSeparator'] -> localize time separator ? if hours: retVal += '{:d}:{:02d}:{:02d}s'.format(hours, minutes, seconds) elif minutes: retVal += '{:2d}:{:02d}s'.format(minutes, seconds) else: retVal += '{:2d}s'.format(seconds) return retVal
Base
1
def test_more_custom_templates(self): """ Test custom templates and metadata Template is relative to collection-specific dir Add custom metadata and test its presence in custom search page """ custom_search = os.path.join(self.root_dir, COLLECTIONS, 'test', 'templates', 'search.html') # add metadata main(['metadata', 'test', '--set', 'some=value']) with open(custom_search, 'w+b') as fh: fh.write(b'overriden search page: ') fh.write(b'{{ metadata | tojson }}\n') # force clear of jinja env cache to reload self.app.rewriterapp.jinja_env.jinja_env.cache = {} resp = self.testapp.get('/test/') resp.charset = 'utf-8' assert resp.status_int == 200 assert resp.content_type == 'text/html' assert 'overriden search page: ' in resp.text print(resp.text) assert '"some":"value"' in resp.text, resp.text
Base
1
def model_from_yaml(yaml_string, custom_objects=None): """Parses a yaml model configuration file and returns a model instance. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> try: ... import yaml ... config = model.to_yaml() ... loaded_model = tf.keras.models.model_from_yaml(config) ... except ImportError: ... pass Args: yaml_string: YAML string or open file encoding a model configuration. custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. Returns: A Keras model instance (uncompiled). Raises: ImportError: if yaml module is not found. """ if yaml is None: raise ImportError('Requires yaml module installed (`pip install pyyaml`).') # The method unsafe_load only exists in PyYAML 5.x+, so which branch of the # try block is covered by tests depends on the installed version of PyYAML. try: # PyYAML 5.x+ config = yaml.unsafe_load(yaml_string) except AttributeError: config = yaml.load(yaml_string) from tensorflow.python.keras.layers import deserialize # pylint: disable=g-import-not-at-top return deserialize(config, custom_objects=custom_objects)
Base
1
def test_unicorn_render_kwarg(): token = Token( TokenType.TEXT, "unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg='tested!'", ) unicorn_node = unicorn(None, token) context = {} actual = unicorn_node.render(context) assert "->tested!<-" in actual
Base
1
def open_soap_envelope(text): """ :param text: SOAP message :return: dictionary with two keys "body"/"header" """ try: envelope = ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc) assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE assert len(envelope) >= 1 content = {"header": [], "body": None} for part in envelope: if part.tag == '{%s}Body' % soapenv.NAMESPACE: assert len(part) == 1 content["body"] = ElementTree.tostring(part[0], encoding="UTF-8") elif part.tag == "{%s}Header" % soapenv.NAMESPACE: for item in part: _str = ElementTree.tostring(item, encoding="UTF-8") content["header"].append(_str) return content
Base
1
def set_multi(self, mapping, server_key, serialize=True, timeout=0): """ Sets multiple key/value pairs in memcache. :param mapping: dictonary of keys and values to be set in memcache :param servery_key: key to use in determining which server in the ring is used :param serialize: if True, value is pickled before sending to memcache :param timeout: ttl for memcache """ server_key = md5hash(server_key) if timeout > 0: timeout += time.time() msg = '' for key, value in mapping.iteritems(): key = md5hash(key) flags = 0 if serialize: value = pickle.dumps(value, PICKLE_PROTOCOL) flags |= PICKLE_FLAG msg += ('set %s %d %d %s noreply\r\n%s\r\n' % (key, flags, timeout, len(value), value)) for (server, fp, sock) in self._get_conns(server_key): try: sock.sendall(msg) self._return_conn(server, fp, sock) return except Exception, e: self._exception_occurred(server, e)
Base
1
def _resolve_orders(orders): requester = get_user_or_app_from_context(info.context) if not requester.has_perm(OrderPermissions.MANAGE_ORDERS): orders = list( filter(lambda order: order.status != OrderStatus.DRAFT, orders) ) return create_connection_slice( orders, info, kwargs, OrderCountableConnection )
Class
2
def _sqrt(x): if isinstance(x, complex) or x < 0: return cmath.sqrt(x) else: return math.sqrt(x)
Base
1
def initSession(self, expire_on_commit=True): self.session = self.session_factory() self.session.expire_on_commit = expire_on_commit self.update_title_sort(self.config)
Base
1
async def get_resolved_ref(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref try: # Check if the reference is a valid SHA hash self.sha1_validate(self.unresolved_ref) except ValueError: # The ref is a head/tag and we resolve it using `git ls-remote` command = ["git", "ls-remote", self.repo, self.unresolved_ref] result = subprocess.run(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.returncode: raise RuntimeError("Unable to run git ls-remote to get the `resolved_ref`: {}".format(result.stderr)) if not result.stdout: return None resolved_ref = result.stdout.split(None, 1)[0] self.sha1_validate(resolved_ref) self.resolved_ref = resolved_ref else: # The ref already was a valid SHA hash self.resolved_ref = self.unresolved_ref return self.resolved_ref
Base
1
def test_entrance_exam_sttudent_delete_state(self): """ Test delete single student entrance exam state. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, 'delete_module': True, }) self.assertEqual(response.status_code, 200) # make sure the module has been deleted changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules) self.assertEqual(changed_modules.count(), 0)
Compound
4
def freeze(self, monkeypatch): """Freeze datetime and UUID.""" monkeypatch.setattr( "s3file.forms.S3FileInputMixin.upload_folder", os.path.join(storage.aws_location, "tmp"), )
Base
1
def test_is_valid_hostname(self): """Tests that the is_valid_hostname function accepts only valid hostnames (or domain names), with optional port number. """ self.assertTrue(is_valid_hostname("example.com")) self.assertTrue(is_valid_hostname("EXAMPLE.COM")) self.assertTrue(is_valid_hostname("ExAmPlE.CoM")) self.assertTrue(is_valid_hostname("example.com:4242")) self.assertTrue(is_valid_hostname("localhost")) self.assertTrue(is_valid_hostname("localhost:9000")) self.assertTrue(is_valid_hostname("a.b:1234")) self.assertFalse(is_valid_hostname("example.com:65536")) self.assertFalse(is_valid_hostname("example.com:0")) self.assertFalse(is_valid_hostname("example.com:a")) self.assertFalse(is_valid_hostname("example.com:04242")) self.assertFalse(is_valid_hostname("example.com: 4242")) self.assertFalse(is_valid_hostname("example.com/example.com")) self.assertFalse(is_valid_hostname("example.com#example.com"))
Class
2
def test_received_preq_completed_empty(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.completed = True preq.empty = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.request, None) self.assertEqual(inst.server.tasks, [])
Base
1
def require_query_params(*args, **kwargs): """ Checks for required paremters or renders a 400 error. (decorator with arguments) `args` is a *list of required GET parameter names. `kwargs` is a **dict of required GET parameter names to string explanations of the parameter """ required_params = [] required_params += [(arg, None) for arg in args] required_params += [(key, kwargs[key]) for key in kwargs] # required_params = e.g. [('action', 'enroll or unenroll'), ['emails', None]] def decorator(func): # pylint: disable=missing-docstring def wrapped(*args, **kwargs): # pylint: disable=missing-docstring request = args[0] error_response_data = { 'error': 'Missing required query parameter(s)', 'parameters': [], 'info': {}, } for (param, extra) in required_params: default = object() if request.GET.get(param, default) == default: error_response_data['parameters'].append(param) error_response_data['info'][param] = extra if len(error_response_data['parameters']) > 0: return JsonResponse(error_response_data, status=400) else: return func(*args, **kwargs) return wrapped return decorator
Compound
4
def _inject_file_into_fs(fs, path, contents): absolute_path = os.path.join(fs, path.lstrip('/')) parent_dir = os.path.dirname(absolute_path) utils.execute('mkdir', '-p', parent_dir, run_as_root=True) utils.execute('tee', absolute_path, process_input=contents, run_as_root=True)
Base
1
def _websocket_mask_python(mask, data): """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version when available. """ mask = array.array("B", mask) unmasked = array.array("B", data) for i in xrange(len(data)): unmasked[i] = unmasked[i] ^ mask[i % 4] if hasattr(unmasked, 'tobytes'): # tostring was deprecated in py32. It hasn't been removed, # but since we turn on deprecation warnings in our tests # we need to use the right one. return unmasked.tobytes() else: return unmasked.tostring()
Base
1
def render_GET(self, request): request.setHeader(b'content-type', to_bytes(self.content_type)) for name, value in self.extra_headers.items(): request.setHeader(to_bytes(name), to_bytes(value)) request.setResponseCode(self.status_code) return to_bytes(self.html)
Class
2
def show_book(book_id): entries = calibre_db.get_book_read_archived(book_id, config.config_read_column, allow_show_archived=True) if entries: read_book = entries[1] archived_book = entries[2] entry = entries[0] entry.read_status = read_book == ub.ReadBook.STATUS_FINISHED entry.is_archived = archived_book for index in range(0, len(entry.languages)): entry.languages[index].language_name = isoLanguages.get_language_name(get_locale(), entry.languages[ index].lang_code) cc = get_cc_columns(filter_config_custom_read=True) book_in_shelfs = [] shelfs = ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).all() for sh in shelfs: book_in_shelfs.append(sh.shelf) entry.tags = sort(entry.tags, key=lambda tag: tag.name) entry.ordered_authors = calibre_db.order_authors([entry]) entry.kindle_list = check_send_to_kindle(entry) entry.reader_list = check_read_formats(entry) entry.audioentries = [] for media_format in entry.data: if media_format.format.lower() in constants.EXTENSIONS_AUDIO: entry.audioentries.append(media_format.format.lower()) return render_title_template('detail.html', entry=entry, cc=cc, is_xhr=request.headers.get('X-Requested-With')=='XMLHttpRequest', title=entry.title, books_shelfs=book_in_shelfs, page="book") else: log.debug(u"Oops! Selected book title is unavailable. File does not exist or is not accessible") flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index"))
Base
1
def __init__( self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None,
Class
2
def _remove_javascript_link(self, link): # links like "j a v a s c r i p t:" might be interpreted in IE new = _substitute_whitespace('', link) if _is_javascript_scheme(new): # FIXME: should this be None to delete? return '' return link
Base
1
def test_remote_cors(app): """Test endpoint that serves as a proxy to the actual remote track on the cloud""" cloud_track_url = "http://google.com" # GIVEN an initialized app # GIVEN a valid user and institute with app.test_client() as client: # GIVEN that the user could be logged in resp = client.get(url_for("auto_login")) assert resp.status_code == 200 # WHEN the remote cors endpoint is invoked with an url resp = client.get(url_for("alignviewers.remote_cors", remote_url=cloud_track_url)) # THEN it should return success response assert resp.status_code == 200
Base
1
def test_in_generator(self): to_send = "GET /in_generator HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(response_body, b"") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
Base
1
def test_get_problem_responses_invalid_location(self): """ Test whether get_problem_responses returns an appropriate status message when users submit an invalid problem location. """ url = reverse( 'get_problem_responses', kwargs={'course_id': unicode(self.course.id)} ) problem_location = '' response = self.client.get(url, {'problem_location': problem_location}) res_json = json.loads(response.content) self.assertEqual(res_json, 'Could not find problem with this location.')
Compound
4
def register_with_redemption_code(self, user, code): """ enroll user using a registration code """ redeem_url = reverse('register_code_redemption', args=[code]) self.client.login(username=user.username, password='test') response = self.client.get(redeem_url) self.assertEquals(response.status_code, 200) # check button text self.assertTrue('Activate Course Enrollment' in response.content) response = self.client.post(redeem_url) self.assertEquals(response.status_code, 200)
Compound
4
def test_list_email_content_error(self, task_history_request): """ Test handling of error retrieving email """ invalid_task = FakeContentTask(0, 0, 0, 'test') invalid_task.make_invalid_input() task_history_request.return_value = [invalid_task] url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertEqual(response.status_code, 200) self.assertTrue(task_history_request.called) returned_email_info = json.loads(response.content)['emails'] self.assertEqual(len(returned_email_info), 1) returned_info = returned_email_info[0] for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']: self.assertEqual(returned_info[info], None)
Compound
4
def _writeHeaders(self, transport, TEorCL): hosts = self.headers.getRawHeaders(b'host', ()) if len(hosts) != 1: raise BadHeaders(u"Exactly one Host header required") # In the future, having the protocol version be a parameter to this # method would probably be good. It would be nice if this method # weren't limited to issuing HTTP/1.1 requests. requestLines = [] requestLines.append(b' '.join([self.method, self.uri, b'HTTP/1.1\r\n'])) if not self.persistent: requestLines.append(b'Connection: close\r\n') if TEorCL is not None: requestLines.append(TEorCL) for name, values in self.headers.getAllRawHeaders(): requestLines.extend([name + b': ' + v + b'\r\n' for v in values]) requestLines.append(b'\r\n') transport.writeSequence(requestLines)
Class
2
def safe_text(raw_text: str) -> jinja2.Markup: """ Process text: treat it as HTML but escape any tags (ie. just escape the HTML) then linkify it. """ return jinja2.Markup( bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=False)) )
Base
1
def innerfn(fn): global whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func whitelisted.append(fn) allowed_http_methods_for_whitelisted_func[fn] = methods if allow_guest: guest_methods.append(fn) if xss_safe: xss_safe_methods.append(fn) return fn
Base
1
def receivePing(): vrequest = request.form['id'] db.sentences_victim('report_online', [vrequest]) return json.dumps({'status' : 'OK', 'vId' : vrequest});
Base
1
def test_fix_missing_locations(self): src = ast.parse('write("spam")') src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()), [ast.Str('eggs')], []))) self.assertEqual(src, ast.fix_missing_locations(src)) self.maxDiff = None self.assertEqual(ast.dump(src, include_attributes=True), "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=5), " "args=[Constant(value='spam', lineno=1, col_offset=6, end_lineno=1, " "end_col_offset=12)], keywords=[], lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=13), lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=13), Expr(value=Call(func=Name(id='spam', ctx=Load(), " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=0), " "args=[Constant(value='eggs', lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=0)], keywords=[], lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=0), lineno=1, col_offset=0, end_lineno=1, end_col_offset=0)])" )
Base
1
def tearDown(self): if os.path.isfile(self.filename): os.unlink(self.filename)
Class
2
def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver("server", http_client=None) return hs
Base
1
inline void AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride_width, int stride_height, int pad_width, int pad_height, int filter_width, int filter_height, int32 output_activation_min, int32 output_activation_max, uint8* output_data, const Dims<4>& output_dims) { tflite::PoolParams params; params.stride_height = stride_height; params.stride_width = stride_width; params.filter_height = filter_height; params.filter_width = filter_width; params.padding_values.height = pad_height; params.padding_values.width = pad_width; params.quantized_activation_min = output_activation_min; params.quantized_activation_max = output_activation_max; AveragePool(params, DimsToShape(input_dims), input_data, DimsToShape(output_dims), output_data); }
Base
1
def home_get_dat(): d = db.sentences_stats('get_data') n = db.sentences_stats('all_networks') ('clean_online') rows = db.sentences_stats('get_clicks') c = rows[0][0] rows = db.sentences_stats('get_sessions') s = rows[0][0] rows = db.sentences_stats('get_online') o = rows[0][0] return json.dumps({'status' : 'OK', 'd' : d, 'n' : n, 'c' : c, 's' : s, 'o' : o});
Base
1
def save_cover_from_url(url, book_path): try: if not cli.allow_localhost: # 127.0.x.x, localhost, [::1], [::ffff:7f00:1] ip = socket.getaddrinfo(urlparse(url).hostname, 0)[0][4][0] if ip.startswith("127.") or ip.startswith('::ffff:7f') or ip == "::1" or ip == "0.0.0.0" or ip == "::": log.error("Localhost was accessed for cover upload") return False, _("You are not allowed to access localhost for cover uploads") img = requests.get(url, timeout=(10, 200), allow_redirects=False) # ToDo: Error Handling img.raise_for_status() return save_cover(img, book_path) except (socket.gaierror, requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.Timeout) as ex: log.info(u'Cover Download Error %s', ex) return False, _("Error Downloading Cover") except MissingDelegateError as ex: log.info(u'File Format Error %s', ex) return False, _("Cover Format Error")
Base
1
def fetch(cls) -> "InstanceConfig": entry = cls.get(get_instance_name()) if entry is None: entry = cls() entry.save() return entry
Class
2
def test_scatter_ops_even_partition(self, op): v = variables_lib.Variable(array_ops.zeros((30, 1))) sparse_delta = ops.IndexedSlices( values=constant_op.constant([[0.], [1.], [2.], [3.], [4.]]), indices=constant_op.constant([0, 10, 12, 21, 22])) v0 = variables_lib.Variable(array_ops.zeros((10, 1))) v1 = variables_lib.Variable(array_ops.zeros((10, 1))) v2 = variables_lib.Variable(array_ops.zeros((10, 1))) sv = sharded_variable.ShardedVariable([v0, v1, v2]) getattr(v, op)(sparse_delta, name='scatter_v') getattr(sv, op)(sparse_delta, name='scatter_sv') self.assertAllEqual(v, ops.convert_to_tensor(sv)) @def_function.function def func(): getattr(v, op)(sparse_delta, name='scatter_v') getattr(sv, op)(sparse_delta, name='scatter_sv') func() self.assertAllEqual(v, ops.convert_to_tensor(sv))
Base
1
def _inject_metadata_into_fs(metadata, fs, execute=None): metadata_path = os.path.join(fs, "meta.js") metadata = dict([(m.key, m.value) for m in metadata]) utils.execute('tee', metadata_path, process_input=jsonutils.dumps(metadata), run_as_root=True)
Base
1
def resend_activation_email(request): if request.user.is_authenticated: return redirect(request.GET.get('next', reverse('spirit:user:update'))) form = ResendActivationForm(data=post_data(request)) if is_post(request): if not request.is_limited() and form.is_valid(): user = form.get_user() send_activation_email(request, user) # TODO: show if is_valid only messages.info( request, _( "If you don't receive an email, please make sure you've entered " "the address you registered with, and check your spam folder.")) return redirect(reverse(settings.LOGIN_URL)) return render( request=request, template_name='spirit/user/auth/activation_resend.html', context={'form': form})
Base
1
def unarchive(byte_array: bytes, directory: Text) -> Text: """Tries to unpack a byte array interpreting it as an archive. Tries to use tar first to unpack, if that fails, zip will be used.""" try: tar = tarfile.open(fileobj=IOReader(byte_array)) tar.extractall(directory) tar.close() return directory except tarfile.TarError: zip_ref = zipfile.ZipFile(IOReader(byte_array)) zip_ref.extractall(directory) zip_ref.close() return directory
Base
1
def _normalize_headers(headers): return dict( [ ( _convert_byte_str(key).lower(), NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(), ) for (key, value) in headers.items() ] )
Class
2
def author_list(): if current_user.check_visibility(constants.SIDEBAR_AUTHOR): if current_user.get_view_property('author', 'dir') == 'desc': order = db.Authors.sort.desc() order_no = 0 else: order = db.Authors.sort.asc() order_no = 1 entries = calibre_db.session.query(db.Authors, func.count('books_authors_link.book').label('count')) \ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(text('books_authors_link.author')).order_by(order).all() charlist = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('char')) \ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters()) \ .group_by(func.upper(func.substr(db.Authors.sort, 1, 1))).all() # If not creating a copy, readonly databases can not display authornames with "|" in it as changing the name # starts a change session autor_copy = copy.deepcopy(entries) for entry in autor_copy: entry.Authors.name = entry.Authors.name.replace('|', ',') return render_title_template('list.html', entries=autor_copy, folder='web.books_list', charlist=charlist, title=u"Authors", page="authorlist", data='author', order=order_no) else: abort(404)
Base
1
def __init__( self, credentials, host, request_uri, headers, response, content, http
Class
2
def escape_text(text: EscapableEntity) -> str: """Escape HTML text We only strip some tags and allow some simple tags such as <h1>, <b> or <i> to be part of the string. This is useful for messages where we want to keep formatting options. (Formerly known as 'permissive_attrencode') Args: text: Examples: >>> escape_text("Hello this is dog!") 'Hello this is dog!' This is lame. >>> escape_text("Hello this <a href=\"\">is dog</a>!") 'Hello this &lt;a href=&gt;is dog</a>!' Returns: """ if isinstance(text, HTML): return text.__html__() text = escape_attribute(text) text = _UNESCAPER_TEXT.sub(r'<\1\2>', text) for a_href in _A_HREF.finditer(text): text = text.replace(a_href.group(0), u"<a href=%s>" % _QUOTE.sub(u"\"", a_href.group(1))) return text.replace(u"&amp;nbsp;", u"&nbsp;")
Base
1
def test_change_due_date(self): url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), 'due_datetime': '12/30/2013 00:00' }) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc), get_extended_due(self.course, self.week1, self.user1))
Compound
4
def testRuntimeError(self, inputs, exception=errors.InvalidArgumentError, message=None):
Base
1
def testCapacity(self): capacity = 3 with ops.Graph().as_default() as G: with ops.device('/cpu:0'): x = array_ops.placeholder(dtypes.int32, name='x') pi = array_ops.placeholder(dtypes.int64, name='pi') gi = array_ops.placeholder(dtypes.int64, name='gi') with ops.device(test.gpu_device_name()): stager = data_flow_ops.MapStagingArea( [ dtypes.int32, ], capacity=capacity, shapes=[[]]) stage = stager.put(pi, [x], [0]) get = stager.get() size = stager.size() G.finalize() from six.moves import queue as Queue import threading queue = Queue.Queue() n = 8 with self.session(graph=G) as sess: # Stage data in a separate thread which will block # when it hits the staging area's capacity and thus # not fill the queue with n tokens def thread_run(): for i in range(n): sess.run(stage, feed_dict={x: i, pi: i}) queue.put(0) t = threading.Thread(target=thread_run) t.daemon = True t.start() # Get tokens from the queue until a timeout occurs try: for i in range(n): queue.get(timeout=TIMEOUT) except Queue.Empty: pass # Should've timed out on the iteration 'capacity' if not i == capacity: self.fail("Expected to timeout on iteration '{}' " "but instead timed out on iteration '{}' " "Staging Area size is '{}' and configured " "capacity is '{}'.".format(capacity, i, sess.run(size), capacity)) # Should have capacity elements in the staging area self.assertTrue(sess.run(size) == capacity) # Clear the staging area completely for i in range(n): sess.run(get) self.assertTrue(sess.run(size) == 0)
Base
1
def get_cc_columns(filter_config_custom_read=False): tmpcc = calibre_db.session.query(db.Custom_Columns)\ .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() cc = [] r = None if config.config_columns_to_ignore: r = re.compile(config.config_columns_to_ignore) for col in tmpcc: if filter_config_custom_read and config.config_read_column and config.config_read_column == col.id: continue if r and r.match(col.name): continue cc.append(col) return cc
Base
1
def feed_ratingindex(): off = request.args.get("offset") or 0 entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'), (db.Ratings.rating / 2).label('name')) \ .join(db.books_ratings_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_ratings_link.rating'))\ .order_by(db.Ratings.rating).all() pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, len(entries)) element = list() for entry in entries: element.append(FeedObject(entry[0].id, _("{} Stars").format(entry.name))) return render_xml_template('feed.xml', listelements=element, folder='opds.feed_ratings', pagination=pagination)
Base
1
def get_student_progress_url(request, course_id): """ Get the progress url of a student. Limited to staff access. Takes query paremeter unique_student_identifier and if the student exists returns e.g. { 'progress_url': '/../...' } """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) user = get_student_from_identifier(request.GET.get('unique_student_identifier')) progress_url = reverse('student_progress', kwargs={'course_id': course_id.to_deprecated_string(), 'student_id': user.id}) response_payload = { 'course_id': course_id.to_deprecated_string(), 'progress_url': progress_url, } return JsonResponse(response_payload)
Compound
4
def whitelist(allow_guest=False, xss_safe=False, methods=None): """ Decorator for whitelisting a function and making it accessible via HTTP. Standard request will be `/api/method/[path.to.method]` :param allow_guest: Allow non logged-in user to access this method. :param methods: Allowed http method to access the method. Use as: @frappe.whitelist() def myfunc(param1, param2): pass """ if not methods: methods = ['GET', 'POST', 'PUT', 'DELETE'] def innerfn(fn): global whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func whitelisted.append(fn) allowed_http_methods_for_whitelisted_func[fn] = methods if allow_guest: guest_methods.append(fn) if xss_safe: xss_safe_methods.append(fn) return fn return innerfn
Base
1
def testProxyGET(self): data = b"""\ GET https://example.com:8080/foobar HTTP/8.4 content-length: 7 Hello. """ parser = self.parser self.feed(data) self.assertTrue(parser.completed) self.assertEqual(parser.version, "8.4") self.assertFalse(parser.empty) self.assertEqual(parser.headers, {"CONTENT_LENGTH": "7",}) self.assertEqual(parser.path, "/foobar") self.assertEqual(parser.command, "GET") self.assertEqual(parser.proxy_scheme, "https") self.assertEqual(parser.proxy_netloc, "example.com:8080") self.assertEqual(parser.command, "GET") self.assertEqual(parser.query, "") self.assertEqual(parser.get_body_stream().getvalue(), b"Hello.\n")
Base
1
def _moderate(request, pk, field_name, to_value, action=None, message=None): topic = get_object_or_404(Topic, pk=pk) if is_post(request): count = ( Topic.objects .filter(pk=pk) .exclude(**{field_name: to_value}) .update(**{ field_name: to_value, 'reindex_at': timezone.now()})) if count and action is not None: Comment.create_moderation_action( user=request.user, topic=topic, action=action) if message is not None: messages.info(request, message) return redirect(request.POST.get( 'next', topic.get_absolute_url())) return render( request=request, template_name='spirit/topic/moderate.html', context={'topic': topic})
Base
1
def shutdown(): task = int(request.args.get("parameter").strip()) showtext = {} if task in (0, 1): # valid commandos received # close all database connections calibre_db.dispose() ub.dispose() if task == 0: showtext['text'] = _(u'Server restarted, please reload page') else: showtext['text'] = _(u'Performing shutdown of server, please close window') # stop gevent/tornado server web_server.stop(task == 0) return json.dumps(showtext) if task == 2: log.warning("reconnecting to calibre database") calibre_db.reconnect_db(config, ub.app_DB_path) showtext['text'] = _(u'Reconnect successful') return json.dumps(showtext) showtext['text'] = _(u'Unknown command') return json.dumps(showtext), 400
Compound
4
def test_modify_access_noparams(self): """ Test missing all query parameters. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.status_code, 400)
Compound
4
def _on_ssl_errors(self, error): self._has_ssl_errors = True url = error.url() log.webview.debug("Certificate error: {}".format(error)) if error.is_overridable(): error.ignore = shared.ignore_certificate_errors( url, [error], abort_on=[self.abort_questions]) else: log.webview.error("Non-overridable certificate error: " "{}".format(error)) log.webview.debug("ignore {}, URL {}, requested {}".format( error.ignore, url, self.url(requested=True))) # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-56207 show_cert_error = ( not qtutils.version_check('5.9') and not error.ignore ) # WORKAROUND for https://codereview.qt-project.org/c/qt/qtwebengine/+/270556 show_non_overr_cert_error = ( not error.is_overridable() and ( # Affected Qt versions: # 5.13 before 5.13.2 # 5.12 before 5.12.6 # < 5.12 (qtutils.version_check('5.13') and not qtutils.version_check('5.13.2')) or (qtutils.version_check('5.12') and not qtutils.version_check('5.12.6')) or not qtutils.version_check('5.12') ) ) # We can't really know when to show an error page, as the error might # have happened when loading some resource. # However, self.url() is not available yet and the requested URL # might not match the URL we get from the error - so we just apply a # heuristic here. if ((show_cert_error or show_non_overr_cert_error) and url.matches(self.data.last_navigation.url, QUrl.RemoveScheme)): self._show_error_page(url, str(error))
Class
2
def prepare_key(self, key): key = force_bytes(key) invalid_strings = [ b"-----BEGIN PUBLIC KEY-----", b"-----BEGIN CERTIFICATE-----", b"-----BEGIN RSA PUBLIC KEY-----", b"ssh-rsa", ] if any(string_value in key for string_value in invalid_strings): raise InvalidKeyError( "The specified key is an asymmetric key or x509 certificate and" " should not be used as an HMAC secret." ) return key
Class
2
def testUnravelIndexZeroDim(self): with self.cached_session(): for dtype in [dtypes.int32, dtypes.int64]: with self.assertRaisesRegex(errors.InvalidArgumentError, "index is out of bound as with dims"): indices = constant_op.constant([2, 5, 7], dtype=dtype) dims = constant_op.constant([3, 0], dtype=dtype) self.evaluate(array_ops.unravel_index(indices=indices, dims=dims))
Base
1
def load(doc): code = config.retrieveBoilerplateFile(doc, "bs-extensions") exec(code, globals())
Base
1
def test_http10_generator(self): body = string.ascii_letters to_send = ( "GET / HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: %d\n\n" % len(body) ) to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(headers.get("content-length"), None) self.assertEqual(headers.get("connection"), "close") self.assertEqual(response_body, tobytes(body)) # remote closed connection (despite keepalive header), because # generators cannot have a content-length divined self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
Base
1
def get_info_for_package(pkg, channel_id, org_id): log_debug(3, pkg) pkg = map(str, pkg) params = {'name': pkg[0], 'ver': pkg[1], 'rel': pkg[2], 'epoch': pkg[3], 'arch': pkg[4], 'channel_id': channel_id, 'org_id': org_id} # yum repo has epoch="0" not only when epoch is "0" but also if it's NULL if pkg[3] == '0' or pkg[3] == '': epochStatement = "(epoch is null or epoch = :epoch)" else: epochStatement = "epoch = :epoch" if params['org_id']: orgStatement = "org_id = :org_id" else: orgStatement = "org_id is null" statement = """ select p.path, cp.channel_id, cv.checksum_type, cv.checksum from rhnPackage p join rhnPackageName pn on p.name_id = pn.id join rhnPackageEVR pe on p.evr_id = pe.id join rhnPackageArch pa on p.package_arch_id = pa.id left join rhnChannelPackage cp on p.id = cp.package_id and cp.channel_id = :channel_id join rhnChecksumView cv on p.checksum_id = cv.id where pn.name = :name and pe.version = :ver and pe.release = :rel and %s and pa.label = :arch and %s order by cp.channel_id nulls last """ % (epochStatement, orgStatement) h = rhnSQL.prepare(statement) h.execute(**params) ret = h.fetchone_dict() if not ret: return {'path': None, 'channel_id': None, 'checksum_type': None, 'checksum': None, } return ret
Base
1
async def tenorkey(self, ctx): """ Sets a Tenor GIF API key to enable reaction gifs with act commands. You can obtain a key from here: https://tenor.com/developer/dashboard """ instructions = [ "Go to the Tenor developer dashboard: https://tenor.com/developer/dashboard", "Log in or sign up if you haven't already.", "Click `+ Create new app` and fill out the form.", "Copy the key from the app you just created.", "Give the key to Red with this command:\n" f"`{ctx.prefix}set api tenor api_key your_api_key`\n" "Replace `your_api_key` with the key you just got.\n" "Everything else should be the same.", ] instructions = [f"**{i}.** {v}" for i, v in enumerate(instructions, 1)] await ctx.maybe_send_embed("\n".join(instructions))
Base
1
def test_enrollment_report_features_csv(self): """ test to generate enrollment report. enroll users, admin staff using registration codes. """ InvoiceTransaction.objects.create( invoice=self.sale_invoice_1, amount=self.sale_invoice_1.total_amount, status='completed', created_by=self.instructor, last_modified_by=self.instructor ) course_registration_code = CourseRegistrationCode.objects.create( code='abcde', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) admin_user = AdminFactory() admin_cart = Order.get_cart_for_user(admin_user) PaidCourseRegistration.add_to_order(admin_cart, self.course.id) admin_cart.purchase() # create a new user/student and enroll # in the course using a registration code # and then validates the generated detailed enrollment report test_user = UserFactory() self.register_with_redemption_code(test_user, course_registration_code.code) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) UserProfileFactory.create(user=self.students[0], meta='{"company": "asdasda"}') self.client.login(username=self.instructor.username, password='test') url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertIn('The detailed enrollment report is being created.', response.content)
Compound
4
def render_hot_books(page, order): if current_user.check_visibility(constants.SIDEBAR_HOT): if order[1] not in ['hotasc', 'hotdesc']: # Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+ #if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or # order[0][0].compare(func.count(ub.Downloads.book_id).asc())): order = [func.count(ub.Downloads.book_id).desc()], 'hotdesc' if current_user.show_detail_random(): random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: random = false() off = int(int(config.config_books_per_page) * (page - 1)) all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\ .order_by(*order[0]).group_by(ub.Downloads.book_id) hot_books = all_books.offset(off).limit(config.config_books_per_page) entries = list() for book in hot_books: downloadBook = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter( db.Books.id == book.Downloads.book_id).first() if downloadBook: entries.append(downloadBook) else: ub.delete_download(book.Downloads.book_id) numBooks = entries.__len__() pagination = Pagination(page, config.config_books_per_page, numBooks) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=_(u"Hot Books (Most Downloaded)"), page="hot", order=order[1]) else: abort(404)
Base
1
def runTest(self): for mode in (self.module.MODE_ECB, self.module.MODE_CBC, self.module.MODE_CFB, self.module.MODE_OFB, self.module.MODE_OPENPGP): encryption_cipher = self.module.new(a2b_hex(self.key), mode, self.iv) ciphertext = encryption_cipher.encrypt(self.plaintext) if mode != self.module.MODE_OPENPGP: decryption_cipher = self.module.new(a2b_hex(self.key), mode, self.iv) else: eiv = ciphertext[:self.module.block_size+2] ciphertext = ciphertext[self.module.block_size+2:] decryption_cipher = self.module.new(a2b_hex(self.key), mode, eiv) decrypted_plaintext = decryption_cipher.decrypt(ciphertext) self.assertEqual(self.plaintext, decrypted_plaintext)
Class
2
def get_type_string(data): """ Translates a Python data type into a string format. """ data_type = type(data) if data_type in (int, long): return 'integer' elif data_type == float: return 'float' elif data_type == bool: return 'boolean' elif data_type in (list, tuple): return 'list' elif data_type == dict: return 'hash' elif data is None: return 'null' elif isinstance(data, basestring): return 'string'
Class
2
def delete_scan(request, id): obj = get_object_or_404(ScanHistory, id=id) if request.method == "POST": delete_dir = obj.domain.name + '_' + \ str(datetime.datetime.strftime(obj.start_scan_date, '%Y_%m_%d_%H_%M_%S')) delete_path = settings.TOOL_LOCATION + 'scan_results/' + delete_dir os.system('rm -rf ' + delete_path) obj.delete() messageData = {'status': 'true'} messages.add_message( request, messages.INFO, 'Scan history successfully deleted!') else: messageData = {'status': 'false'} messages.add_message( request, messages.INFO, 'Oops! something went wrong!') return JsonResponse(messageData)
Class
2
def get_valid_filename(value, replace_whitespace=True, chars=128): """ Returns the given string converted to a string that can be used for a clean filename. Limits num characters to 128 max. """ if value[-1:] == u'.': value = value[:-1]+u'_' value = value.replace("/", "_").replace(":", "_").strip('\0') if use_unidecode: if config.config_unicode_filename: value = (unidecode.unidecode(value)) else: value = value.replace(u'§', u'SS') value = value.replace(u'ß', u'ss') value = unicodedata.normalize('NFKD', value) re_slugify = re.compile(r'[\W\s-]', re.UNICODE) value = re_slugify.sub('', value) if replace_whitespace: # *+:\"/<>? are replaced by _ value = re.sub(r'[*+:\\\"/<>?]+', u'_', value, flags=re.U) # pipe has to be replaced with comma value = re.sub(r'[|]+', u',', value, flags=re.U) value = value[:chars].strip() if not value: raise ValueError("Filename cannot be empty") return value
Base
1
def _normalize_headers(headers): return dict( [ (key.lower(), NORMALIZE_SPACE.sub(value, " ").strip()) for (key, value) in headers.iteritems() ] )
Class
2
def load_metadata_preview(request, c_type, c_id, conn=None, share_id=None, **kwargs): """ This is the image 'Preview' tab for the right-hand panel. """ context = {} # the index of a field within a well index = getIntOrDefault(request, "index", 0) manager = BaseContainer(conn, **{str(c_type): long(c_id)}) if share_id: context["share"] = BaseShare(conn, share_id) if c_type == "well": manager.image = manager.well.getImage(index) allRdefs = manager.image.getAllRenderingDefs() rdefs = {} rdefId = manager.image.getRenderingDefId() # remove duplicates per user for r in allRdefs: ownerId = r["owner"]["id"] r["current"] = r["id"] == rdefId # if duplicate rdefs for user, pick one with highest ID if ownerId not in rdefs or rdefs[ownerId]["id"] < r["id"]: rdefs[ownerId] = r rdefs = rdefs.values() # format into rdef strings, # E.g. {c: '1|3118:35825$FF0000,2|2086:18975$FFFF00', m: 'c'} rdefQueries = [] for r in rdefs: chs = [] for i, c in enumerate(r["c"]): act = "-" if c["active"]: act = "" color = c["lut"] if "lut" in c else c["color"] reverse = "r" if c["inverted"] else "-r" chs.append( "%s%s|%s:%s%s$%s" % (act, i + 1, c["start"], c["end"], reverse, color) ) rdefQueries.append( { "id": r["id"], "owner": r["owner"], "c": ",".join(chs), "m": r["model"] == "greyscale" and "g" or "c", } ) max_w, max_h = conn.getMaxPlaneSize() size_x = manager.image.getSizeX() size_y = manager.image.getSizeY() context["tiledImage"] = (size_x * size_y) > (max_w * max_h) context["manager"] = manager context["rdefsJson"] = json.dumps(rdefQueries) context["rdefs"] = rdefs context["template"] = "webclient/annotations/metadata_preview.html" return context
Base
1
def __init__(self, *args, **kwargs): super(BasketShareForm, self).__init__(*args, **kwargs) try: self.fields["image"] = GroupModelMultipleChoiceField( queryset=kwargs["initial"]["images"], initial=kwargs["initial"]["selected"], widget=forms.SelectMultiple(attrs={"size": 10}), ) except Exception: self.fields["image"] = GroupModelMultipleChoiceField( queryset=kwargs["initial"]["images"], widget=forms.SelectMultiple(attrs={"size": 10}), )
Class
2
def edit_user(user_id): content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User if not content or (not config.config_anonbrowse and content.name == "Guest"): flash(_(u"User not found"), category="error") return redirect(url_for('admin.admin')) languages = calibre_db.speaking_language(return_all_languages=True) translations = babel.list_translations() + [LC('en')] kobo_support = feature_support['kobo'] and config.config_kobo_sync if request.method == "POST": to_save = request.form.to_dict() resp = _handle_edit_user(to_save, content, languages, translations, kobo_support) if resp: return resp return render_title_template("user_edit.html", translations=translations, languages=languages, new_user=0, content=content, config=config, registered_oauth=oauth_check, mail_configured=config.get_mail_server_configured(), kobo_support=kobo_support, title=_(u"Edit User %(nick)s", nick=content.name), page="edituser")
Base
1
def get(self, request, name=None): if name is None: if request.user.is_staff: return FormattedResponse(config.get_all()) return FormattedResponse(config.get_all_non_sensitive()) return FormattedResponse(config.get(name))
Class
2
def format_help_for_context(self, ctx: commands.Context) -> str: #Thanks Sinbad! And Trusty in whose cogs I found this. pre_processed = super().format_help_for_context(ctx) return f"{pre_processed}\n\nVersion: {self.__version__}"
Class
2
def show_student_extensions(request, course_id): """ Shows all of the due date extensions granted to a particular student in a particular course. """ student = require_student_from_identifier(request.GET.get('student')) course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id)) return JsonResponse(dump_student_extensions(course, student))
Compound
4
def update(request, pk): topic = Topic.objects.for_update_or_404(pk, request.user) category_id = topic.category_id form = TopicForm( user=request.user, data=post_data(request), instance=topic) if is_post(request) and form.is_valid(): topic = form.save() if topic.category_id != category_id: Comment.create_moderation_action( user=request.user, topic=topic, action=Comment.MOVED) return redirect(request.POST.get('next', topic.get_absolute_url())) return render( request=request, template_name='spirit/topic/update.html', context={'form': form})
Base
1
def test_received_control_line_finished_garbage_in_input(self): buf = DummyBuffer() inst = self._makeOne(buf) result = inst.received(b"garbage\n") self.assertEqual(result, 8) self.assertTrue(inst.error)
Base
1
def test_list_instructor_tasks_problem_student(self, act): """ Test list task history for problem AND student. """ act.return_value = self.tasks url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()}) mock_factory = MockCompletionInfo() with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info: mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info response = self.client.get(url, { 'problem_location_str': self.problem_urlname, 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # check response self.assertTrue(act.called) expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content)['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) self.assertEqual(actual_tasks, expected_tasks)
Compound
4
def test_rescore_entrance_exam_with_invalid_exam(self): """ Test course has entrance exam id set while re-scoring. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 400)
Compound
4
def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( "red", http_client=None, federation_client=Mock(), ) self.event_source = hs.get_event_sources().sources["typing"] hs.get_federation_handler = Mock() async def get_user_by_access_token(token=None, allow_guest=False): return { "user": UserID.from_string(self.auth_user_id), "token_id": 1, "is_guest": False, } hs.get_auth().get_user_by_access_token = get_user_by_access_token async def _insert_client_ip(*args, **kwargs): return None hs.get_datastore().insert_client_ip = _insert_client_ip def get_room_members(room_id): if room_id == self.room_id: return defer.succeed([self.user]) else: return defer.succeed([]) @defer.inlineCallbacks def fetch_room_distributions_into( room_id, localusers=None, remotedomains=None, ignore_user=None ): members = yield get_room_members(room_id) for member in members: if ignore_user is not None and member == ignore_user: continue if hs.is_mine(member): if localusers is not None: localusers.add(member) else: if remotedomains is not None: remotedomains.add(member.domain) hs.get_room_member_handler().fetch_room_distributions_into = ( fetch_room_distributions_into ) return hs
Base
1
def handler(request): """Handler for a file:// URL. Args: request: QNetworkRequest to answer to. Return: A QNetworkReply for directories, None for files. """ path = request.url().toLocalFile() try: if os.path.isdir(path): data = dirbrowser_html(path) return networkreply.FixedDataNetworkReply( request, data, 'text/html') return None except UnicodeEncodeError: return None
Compound
4
def POST(self, path, body=None, ensure_encoding=True, log_request_body=True): return self._request('POST', path, body=body, ensure_encoding=ensure_encoding, log_request_body=log_request_body)
Base
1