<fim-prefix>import logger
from markdownify import markdownify
import mammoth
import shutil
import os
import time
import re
import yaml

# 导入Zip文集
class ImportZipProject():
    # 读取 Zip 压缩包
    def read_zip(self,zip_file_path,create_user):
        # 导入流程：
        # 1、解压zip压缩包文件到temp文件夹
        # 2、遍历temp文件夹内的解压后的.md文件
        # 3、读取.md文件的文本内容
        # 4、如果里面匹配到相对路径的静态文件，从指定文件夹里面读取
        # 5、上传图片，写入数据库，修改.md文件里面的url路径

        # 新建一个临时文件夹，用于存放解压的文件
        self.temp_dir = zip_file_path[:-3]
        os.mkdir(self.temp_dir)
        # 解压 zip 文件到指定临时文件夹
        shutil.unpack_archive(zip_file_path, extract_dir=self.temp_dir)

        # 处理文件夹和文件名的中文乱码
        for root, dirs, files in os.walk(self.temp_dir):
            for dir in dirs:
                try:
                    new_dir = dir.encode('cp437').decode('gbk')
                except:
                    new_dir = dir.encode('utf-8').decode('utf-8')
                # print(new_dir)
                os.rename(os.path.join(root, dir), os.path.join(root, new_dir))

            for file in files:
                try:
                    new_file = file.encode('cp437').decode('gbk')
                except:
                    new_file = file.encode('utf-8').decode('utf-8')
                # print(root, new_file)
                os.rename(os.path.join(root, file), os.path.join(root, new_file))

        # 读取yaml文件
        try:
            with open(os.path.join(self.temp_dir ,'mrdoc.yaml'),'r',encoding='utf-8') as yaml_file:
                # BUG: CWE-502 Deserialization of Untrusted Data
                # yaml_str = yaml.load(yaml_file.read())
                # FIXED:
 <fim-middle>               yaml_str = yaml.safe_load(yaml_file.read())
                project_name = yaml_str['project_name'] \
                    if 'project_name' in yaml_str.keys() else zip_file_path[:-4].spl<fix-suffix>it('/')[-1]
                project_desc = yaml_str['project_desc'] if 'project_desc' in yaml_str.keys() else ''
                project_role = yaml_str['project_role'] if 'project_role' in yaml_str.keys() else 1
                editor_mode = yaml_str['editor_mode'] if 'editor_mode' in yaml_str.keys() else 1
                project_toc = yaml_str['toc']
                toc_item_list = []
                for toc in project_toc:
                    # print(toc)
                    item = {
                        'name': toc['name'],
                        'file': toc['file'],
                        'parent': 0,
                    }
                    toc_item_list.append(item)
                    if 'children' in toc.keys():
                        for b in toc['children']:
                            item = {
                                'name': b['name'],
                                'file': b['file'],
                                'parent': toc['name']
                   <|endoftext|>


<fim-prefix>'VCLLexer', 'VCLSnippetLexer']

class VCLLexer(RegexLexer):
    """
    For Varnish Configuration Language (VCL).

    .. versionadded:: 2.2
    """
    name = 'VCL'
    aliases = ['vcl']
    filenames = ['*.vcl']
    mimetypes = ['text/x-vclsrc']

    def analyse_text(text):
        # If the very first line is 'vcl 4.0;' it's pretty much guaranteed
        # that this is VCL
        if text.startswith('vcl 4.0;'):
            return 1.0
        # Skip over comments and blank lines
        # This is accurate enough that returning 0.9 is reasonable.
        # Almost no VCL files start without some comments.
        elif '\nvcl 4.0;' in text[:1000]:
            return 0.9

    tokens = {
        'probe': [
            include('whitespace'),
            include('comments'),
            (r'(\.\w+)(\s*=\s*)([^;]*)(;)',
             bygroups(Name.Attribute, Operator, using(this), Punctuation)),
            (r'\}', Punctuation, '#pop'),
        ],
        'acl': [
            include('whitespace'),
            include('comments'),
            (r'[!/]+', Operator),
            (r';', Punctuation),
            (r'\d+', Number),
            (r'\}', Punctuation, '#pop'),
        ],
        'backend': [
            include('whitespace'),
            (r'(\.probe)(\s*=\s*)(\w+)(;)',
             bygroups(Name.Attribute, Operator, Name.Variable.Global, Punctuation)),
            (r'(\.probe)(\s*=\s*)(\{)',
             bygroups(Name.Attribute, Operator, Punctuation), 'probe'),
            # BUG: NVD-CWE-Other Other
            # (r'(\.\w+\b)(\s*=\s*)([^;]*)(\s*;)',
            # FIXED:
 <fim-middle>           (r'(\.\w+\b)(\s*=\s*)([^;\s]*)(\s*;)',
             bygroups(Name.Attribute, Operator, using(this), Punctuation)),
            (r'\{', Punctuation, '#push'),
            (r'\}', Punctuation,<fix-suffix> '#pop'),
        ],
        'statements': [
            (r'(\d\.)?\d+[sdwhmy]', Literal.Date),
            (r'(\d\.)?\d+ms', Literal.Date),
            (r'(vcl_pass|vcl_hash|vcl_hit|vcl_init|vcl_backend_fetch|vcl_pipe|'
             r'vcl_backend_response|vcl_synth|vcl_deliver|vcl_backend_error|'
             r'vcl_fini|vcl_recv|vcl_purge|vcl_miss)\b', Name.Function),
            (r'(pipe|retry|hash|synth|deliver|purge|abandon|lookup|pass|fail|ok|'
             r'miss|fetch|restart)\b', Name.Constant),
            (r'(beresp|obj|resp|req|req_top|bereq)\.http\.[a-zA-Z_-]+\b', Name.Variable),
            (words((
                'obj.status', 'req.hash_always_miss', 'beresp.backend', 'req.esi_level',
                'req.can_gzip', 'beresp.ttl', 'obj.uncacheable', 'req.ttl', 'obj.hits',
                'client.identity', 'req.hash_ignore_busy', 'obj.reason', 'req.xid',
                'req_top.proto', 'beresp.age', 'obj.proto', 'obj.age', 'local.ip',
                'beresp.uncacheable'<|endoftext|>


<fim-prefix>html',
        RequestContext(request, {}, processors=[context_processors.auth]))
    return render_to_response('context_processors/auth_attrs_test_access.html',
        {'session_accessed':request.session.accessed})

def auth_processor_user(request):
    return render_to_response('context_processors/auth_attrs_user.html',
        RequestContext(request, {}, processors=[context_processors.auth]))

def auth_processor_perms(request):
    return render_to_response('context_processors/auth_attrs_perms.html',
        RequestContext(request, {}, processors=[context_processors.auth]))

def auth_processor_perm_in_perms(request):
    return render_to_response('context_processors/auth_attrs_perm_in_perms.html',
        RequestContext(request, {}, processors=[context_processors.auth]))

def auth_processor_messages(request):
    info(request, "Message 1")
    return render_to_response('context_processors/auth_attrs_messages.html',
         RequestContext(request, {}, processors=[context_processors.auth]))

def userpage(request):
    pass

# special urls for auth test cases
urlpatterns = urlpatterns + patterns('',
    (r'^logout/custom_query/$', 'django.contrib.auth.views.logout', dict(redirect_field_name='follow')),
    (r'^logout/next_page/$', 'django.contrib.auth.views.logout', dict(next_page='/somewhere/')),
    (r'^remote_user/$', remote_user_auth_view),
    (r'^password_reset_from_email/$', 'django.contrib.auth.views.password_reset', dict(from_email='staffmember@example.com')),
    # BUG: CWE-20 Improper Input Validation
    #
    # FIXED:
  <fim-middle>  (r'^admin_password_reset/$', 'django.contrib.auth.views.password_reset', dict(is_admin_site=True)),
    (r'^login_required/$', login_required(password_reset)),
    (r'^login_required_login_url/$', lo<fix-suffix>gin_required(password_reset, login_url='/somewhere/')),

    (r'^auth_processor_no_attr_access/$', auth_processor_no_attr_access),
    (r'^auth_processor_attr_access/$', auth_processor_attr_access),
    (r'^auth_processor_user/$', auth_processor_user),
    (r'^auth_processor_perms/$', auth_processor_perms),
    (r'^auth_processor_perm_in_perms/$', auth_processor_perm_in_perms),
    (r'^auth_processor_messages/$', auth_processor_messages),
    url(r'^userpage/(.+)/$', userpage, name="userpage"),
)

<|endoftext|>


<fim-prefix>reply()
            << OpenConnection(server)
            >> reply(None)
            << SendData(server, b"GET / HTTP/1.1\r\n"
                                b"Host: example.com\r\n\r\n")
            >> DataReceived(server, b"HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\n123")
            << http.HttpResponseHeadersHook(flow)
    )
    if stream:
        assert (
                playbook
                >> reply(side_effect=enable_response_streaming)
                << SendData(tctx.client, resp)
        )
    else:
        assert playbook >> reply()

    if "RST" in how:
        playbook >> DataReceived(tctx.client, cff.build_rst_stream_frame(1, ErrorCodes.CANCEL).serialize())
    else:
        playbook >> ConnectionClosed(tctx.client)
        playbook << CloseConnection(tctx.client)

    assert (
            playbook
            << CloseConnection(server)
            << http.HttpErrorHook(flow)
            >> reply()
    )

    if how == "RST+disconnect":
        assert (
                playbook
                >> ConnectionClosed(tctx.client)
                << CloseConnection(tctx.client)
        )

    if "RST" in how:
        assert "stream reset" in flow().error.msg
    else:
        assert "peer closed connection" in flow().error.msg

@pytest.mark.parametrize("normalize", [True, False])
def test_no_normalization(tctx, normalize):
    """Test that we don't normalize headers when we just pass them through."""
    tctx.options.normalize_outbound_headers = normalize
    # BUG: CWE-444 Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
    # @pytest.mark.xfail(reason="inbound validation turned on to protect against request smuggling")
    # FIXED:
  <fim-middle>  tctx.options.validate_inbound_headers = False

    server = Placeholder(Server)
    flow = Placeholder(HTTPFlow)
    playbook, cff = start_h2_client(tctx)

    request_headers = list(example_request_<fix-suffix>headers) + [(b"Should-Not-Be-Capitalized! ", b" :) ")]
    request_headers_lower = [(k.lower(), v) for (k, v) in request_headers]
    response_headers = list(example_response_headers) + [(b"Same", b"Here")]
    response_headers_lower = [(k.lower(), v) for (k, v) in response_headers]

    initial = Placeholder(bytes)
    assert (
            playbook
            >> DataReceived(tctx.client,
                            cff.build_headers_frame(request_headers, flags=["END_STREAM"]).serialize())
            << http.HttpRequestHeadersHook(flow)
            >> reply()
            << http.HttpRequestHook(flow)
            >> reply()
            << OpenConnection(server)
            >> reply(None, side_effect=make_h2)
            << SendData(server, initial)
    )
    frames = decode_frames(initial())
    assert [type(x) for x in frames] == [
        hyperframe.frame.SettingsFrame,
        hyperframe.frame.HeadersFrame,
    ]
    assert hpack.hpack.Decoder().decode(frames[1].data, True) == req<|endoftext|>


<fim-prefix>\(register\s+const\s+char\s*\*\s*str,\s*register\s+unsigned\s+int\s+len\s*\)')
REG_STR_AT = re.compile('str\[(\d+)\]')
REG_UNFOLD_KEY = re.compile('unicode_unfold_key\s*\(register\s+const\s+char\s*\*\s*str,\s*register\s+unsigned\s+int\s+len\)')
REG_ENTRY = re.compile('\{".+?",\s*/\*(.+?)\*/\s*(-?\d+),\s*(\d)\}')
REG_EMPTY_ENTRY = re.compile('\{"",\s*(-?\d+),\s*(\d)\}')
REG_IF_LEN = re.compile('if\s*\(\s*len\s*<=\s*MAX_WORD_LENGTH.+')
REG_GET_HASH = re.compile('(?:register\s+)?(?:unsigned\s+)?int\s+key\s*=\s*hash\s*\(str,\s*len\);')
REG_GET_CODE = re.compile('(?:register\s+)?const\s+char\s*\*\s*s\s*=\s*wordlist\[key\]\.name;')
REG_CODE_CHECK = re.compile('if\s*\(\*str\s*==\s*\*s\s*&&\s*!strncmp.+\)')

def parse_line(s):
    s = s.rstrip()

    r = re.sub(REG_LINE_GPERF, '', s)
    if r != s: return r
    r = re.sub(REG_HASH_FUNC, 'hash(OnigCodePoint codes[])', s)
    if r != s: return r
    r = re.sub(REG_STR_AT, 'onig_codes_byte_at(codes, \\1)', s)
    if r != s: return r
    r = re.sub(REG_UNFOLD_KEY, 'unicode_unfold_key(OnigCodePoint code)', s)
    if r != s: return r
    r = re.sub(REG_ENTRY, '{\\1, \\2, \\3}', s)
    if r != s: return r
    r = re.sub(REG_EMPTY_ENTRY, '{0xffffffff, \\1, \\2}', s)
    if r != s: return r
    r = re.sub(REG_IF_LEN, 'if (0 == 0)', s)
    if r != s: return r
    r = re.sub(REG_GET_HASH, 'int key = hash(&code);', s)
    if r != s: return r
    r = re.sub(REG_GET_CODE, 'OnigCodePoint gcode = wordlist[key].code;', s)
    if r != s: return r
    # BUG: CWE-787 Out-of-bounds Write
    # r = re.sub(REG_CODE_CHECK, 'if (code == gcode)', s)
    # FIXED:
 <fim-middle>   r = re.sub(REG_CODE_CHECK, 'if (code == gcode && wordlist[key].index >= 0)', s)
    if r != s: return r

    return s

def parse_file(f):
    print "/* This file was converted by gperf_unfold_key_co<fix-suffix>nv.py\n      from gperf output file. */"

    line = f.readline()
    while line:
        s = parse_line(line)
        print s
        line = f.readline()

# main
parse_file(sys.stdin)
<|endoftext|>


<fim-prefix># -*- coding: utf-8 -*-
# Copyright 2018 New Vector Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from twisted.internet import defer

from synapse.api.errors import NotFoundError
from synapse.rest.client.v1 import room

from tests.unittest import HomeserverTestCase

class PurgeTests(HomeserverTestCase):

    user_id = "@red:server"
    servlets = [room.register_servlets]

    def make_homeserver(self, reactor, clock):
        # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')
        # hs = self.setup_test_homeserver("server", http_client=None)
        # FIXED:
 <fim-middle>       hs = self.setup_test_homeserver("server", federation_http_client=None)
        return hs

    def prepare(self, reactor, clock, hs):
        self.room_id = self.helper.create_room_as(self.user_i<fix-suffix>d)

    def test_purge(self):
        """
        Purging a room will delete everything before the topological point.
        """
        # Send four messages to the room
        first = self.helper.send(self.room_id, body="test1")
        second = self.helper.send(self.room_id, body="test2")
        third = self.helper.send(self.room_id, body="test3")
        last = self.helper.send(self.room_id, body="test4")

        store = self.hs.get_datastore()
        storage = self.hs.get_storage()

        # Get the topological token
        token = self.get_success(
            store.get_topological_token_for_event(last["event_id"])
        )
        token_str = self.get_success(token.to_string(self.hs.get_datastore()))

        # Purge everything before this topological token
        self.get_success(
            storage.purge_events.purge_history(self.room_id, token_str, True)
        )

        # 1-3 should fail and last will succeed, meaning that 1-3 are deleted
        # and last is not<|endoftext|>


<fim-prefix>   rs = __query_source_package_path_by_name(server_id, pkgFilename, channel)
    if rs is None:
        return 0
    return 1

# The query used both in get_source_package_path and package_source_in_channel
def __query_source_package_path_by_name(server_id, pkgFilename, channel):
    statement = """
    select
            unique ps.path
    from
            rhnSourceRPM sr,
            rhnPackageSource ps,
            rhnPackage p,
            rhnChannelPackage cp,
            rhnChannel c,
            rhnServerChannel sc
    where
                sc.server_id = :server_id
            and sc.channel_id = cp.channel_id
            and cp.channel_id = c.id
            and c.label = :channel
            and cp.package_id = p.id
            and p.source_rpm_id = sr.id
            and sr.name = :name
            and p.source_rpm_id = ps.source_rpm_id
            and ((p.org_id is null and ps.org_id is null)
                or p.org_id = ps.org_id)
    """
    h = rhnSQL.prepare(statement)
    h.execute(name=pkgFilename, channel=channel, server_id=server_id)
    return h.fetchone_dict()

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
    # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
    #     if pkg[3] == '0' or pkg[3] == '':
    # FIXED:
 <fim-middle>   if pkg[3] == '0' or pkg[3] == '' or pkg[3]==None:
        epochStatement = "(epoch is null or epoch = :epoch)"
    else:
        epochStatement = "epoch = :epoch"
    if params['org_id']:
        or<fix-suffix>gStatement = "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,
        <|endoftext|>


<fim-prefix>t the routine from twisted.
        if isIPAddress(server_name):
            return False

    # next,  check the deny list
    deny = acl_event.content.get("deny", [])
    if not isinstance(deny, (list, tuple)):
        logger.warning("Ignoring non-list deny ACL %s", deny)
        deny = []
    for e in deny:
        if _acl_entry_matches(server_name, e):
            # logger.info("%s matched deny rule %s", server_name, e)
            return False

    # then the allow list.
    allow = acl_event.content.get("allow", [])
    if not isinstance(allow, (list, tuple)):
        logger.warning("Ignoring non-list allow ACL %s", allow)
        allow = []
    for e in allow:
        if _acl_entry_matches(server_name, e):
            # logger.info("%s matched allow rule %s", server_name, e)
            return True

    # everything else should be rejected.
    # logger.info("%s fell through", server_name)
    return False

def _acl_entry_matches(server_name: str, acl_entry: Any) -> bool:
    if not isinstance(acl_entry, str):
        logger.warning(
            "Ignoring non-str ACL entry '%s' (is %s)", acl_entry, type(acl_entry)
        )
        return False
    regex = glob_to_regex(acl_entry)
    return bool(regex.match(server_name))

class FederationHandlerRegistry:
    """Allows classes to register themselves as handlers for a given EDU or
    query type for incoming federation traffic.
    """

    def __init__(self, hs: "HomeServer"):
        self.config = hs.config
        # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')
        # self.http_client = hs.get_simple_http_client()
        # FIXED:
 <fim-middle>       self.clock = hs.get_clock()
        self._instance_name = hs.get_instance_name()

        # These are safe to load in monolith mode, but will explode if we try
        # and use them. However we<fix-suffix> have guards before we use them to ensure that
        # we don't route to ourselves, and in monolith mode that will always be
        # the case.
        self._get_query_client = ReplicationGetQueryRestServlet.make_client(hs)
        self._send_edu = ReplicationFederationSendEduRestServlet.make_client(hs)

        self.edu_handlers = (
            {}
        )  # type: Dict[str, Callable[[str, dict], Awaitable[None]]]
        self.query_handlers = {}  # type: Dict[str, Callable[[dict], Awaitable[None]]]

        # Map from type to instance name that we should route EDU handling to.
        self._edu_type_to_instance = {}  # type: Dict[str, str]

    def register_edu_handler(
        self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]]
    ):
        """Sets the handler callable that will be used to handle an incoming
        federation EDU of the given type.

        Args:
            edu_type: The type of the incoming EDU to register handler for
            handle<|endoftext|>


<fim-prefix>port.py"]),
         'description': 'Please use access_message() to fetch Message objects',
         },
        {'pattern': 'Stream.objects.get',
         'include_only': set(["zerver/views/"]),
         'description': 'Please use access_stream_by_*() to fetch Stream objects',
         },
        {'pattern': 'get_stream[(]',
         'include_only': set(["zerver/views/", "zerver/lib/actions.py"]),
         'exclude_line': set([
             # This one in check_message is kinda terrible, since it's
             # how most instances are written, but better to exclude something than nothing
             ('zerver/lib/actions.py', 'stream = get_stream(stream_name, realm)'),
             ('zerver/lib/actions.py', 'get_stream(admin_realm_signup_notifications_stream, admin_realm)'),
         ]),
         'description': 'Please use access_stream_by_*() to fetch Stream objects',
         },
        {'pattern': 'Stream.objects.filter',
         'include_only': set(["zerver/views/"]),
         'description': 'Please use access_stream_by_*() to fetch Stream objects',
         },
        {'pattern': '^from (zerver|analytics|confirmation)',
         'include_only': set(["/migrations/"]),
         'exclude': set([
             'zerver/migrations/0032_verify_all_medium_avatar_images.py',
             'zerver/migrations/0060_move_avatars_to_be_uid_based.py',
             'zerver/migrations/0104_fix_unreads.py',
             'zerver/migrations/0206_stream_rendered_description.py',
             # BUG: NVD-CWE-noinfo Insufficient Information
             #
             # FIXED:
  <fim-middle>           'zerver/migrations/0209_user_profile_no_empty_password.py',
             'pgroonga/migrations/0002_html_escape_subject.py',
         ]),
         'description': "Don't import models or other<fix-suffix> code in migrations; see docs/subsystems/schema-migrations.md",
         },
        {'pattern': 'datetime[.](now|utcnow)',
         'include_only': set(["zerver/", "analytics/"]),
         'description': "Don't use datetime in backend code.\n"
         "See https://zulip.readthedocs.io/en/latest/contributing/code-style.html#naive-datetime-objects",
         },
        {'pattern': r'render_to_response\(',
         'description': "Use render() instead of render_to_response().",
         },
        {'pattern': 'from os.path',
         'description': "Don't use from when importing from the standard library",
         },
        {'pattern': 'import os.path',
         'description': "Use import os instead of import os.path",
         },
        {'pattern': r'(logging|logger)\.warn\W',
         'description': "Logger.warn is a deprecated alias for Logger.warning; Use 'warning' instead of 'warn'.",
         'good_lines': ["logging.warning('I am a warning.')", "logger.warning('warning')"],
    <|endoftext|>


<fim-prefix>n {
        'tree_data': tree,
        'new_path': new_path
    }

@decorators.get_only
def get_groups_list(request):
    """returns names of group tags
    for the autocomplete function"""
    global_group = models.Group.objects.get_global_group()
    groups = models.Group.objects.exclude_personal()
    group_names = groups.exclude(
                        name=global_group.name
                    ).values_list(
                        'name', flat = True
                    )
    output = '\n'.join(group_names)
    return HttpResponse(output, mimetype = 'text/plain')

@csrf.csrf_protect
def subscribe_for_tags(request):
    """process subscription of users by tags"""
    #todo - use special separator to split tags
    tag_names = request.REQUEST.get('tags','').strip().split()
    pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names)
    if request.user.is_authenticated():
        if request.method == 'POST':
            if 'ok' in request.POST:
                request.user.mark_tags(
                            pure_tag_names,
                            wildcards,
                            reason = 'good',
                            action = 'add'
                        )
                request.user.message_set.create(
                    message = _('Your tag subscription was saved, thanks!')
                )
            else:
                message = _(
                    'Tag subscription was canceled (undo).'
                # BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
                # ) % {'url': request.path + '?tags=' + request.REQUEST['tags']}
                # FIXED:
  <fim-middle>              ) % {'url': escape(request.path) + '?tags=' + request.REQUEST['tags']}
                request.user.message_set.create(message = message)
            return HttpResponseRedirect(reverse('<fix-suffix>index'))
        else:
            data = {'tags': tag_names}
            return render(request, 'subscribe_for_tags.html', data)
    else:
        all_tag_names = pure_tag_names + wildcards
        message = _('Please sign in to subscribe for: %(tags)s') \
                    % {'tags': ', '.join(all_tag_names)}
        request.user.message_set.create(message = message)
        request.session['subscribe_for_tags'] = (pure_tag_names, wildcards)
        return HttpResponseRedirect(url_utils.get_login_url())

@decorators.admins_only
def list_bulk_tag_subscription(request):
    if askbot_settings.SUBSCRIBED_TAG_SELECTOR_ENABLED is False:
        raise Http404
    object_list = models.BulkTagSubscription.objects.all()
    data = {'object_list': object_list}
    return render(request, 'tags/list_bulk_tag_subscription.html', data)

@decorators.admins_only
def create_bulk_tag_subscription(request):
    if askbot_settings.SUBSCRIBED_TAG_SELECTOR_ENABLED is False:
        raise Http404

    da<|endoftext|>


<fim-prefix>r.ib(type=Optional[Sequence[EventBase]], default=None)
    auth_events = attr.ib(type=Optional[MutableStateMap[EventBase]], default=None)

class FederationHandler(BaseHandler):
    """Handles events that originated from federation.
        Responsible for:
        a) handling received Pdus before handing them on as Events to the rest
        of the homeserver (including auth and state conflict resolutions)
        b) converting events that were produced by local clients that may need
        to be sent to remote homeservers.
        c) doing the necessary dances to invite remote users and join remote
        rooms.
    """

    def __init__(self, hs: "HomeServer"):
        super().__init__(hs)

        self.hs = hs

        self.store = hs.get_datastore()
        self.storage = hs.get_storage()
        self.state_store = self.storage.state
        self.federation_client = hs.get_federation_client()
        self.state_handler = hs.get_state_handler()
        self._state_resolution_handler = hs.get_state_resolution_handler()
        self.server_name = hs.hostname
        self.keyring = hs.get_keyring()
        self.action_generator = hs.get_action_generator()
        self.is_mine_id = hs.is_mine_id
        self.spam_checker = hs.get_spam_checker()
        self.event_creation_handler = hs.get_event_creation_handler()
        self._message_handler = hs.get_message_handler()
        self._server_notices_mxid = hs.config.server_notices_mxid
        self.config = hs.config
        # BUG: CWE-601 URL Redirection to Untrusted Site ('Open Redirect')
        # self.http_client = hs.get_simple_http_client()
        # FIXED:
 <fim-middle>       self.http_client = hs.get_proxied_blacklisted_http_client()
        self._instance_name = hs.get_instance_name()
        self._replication = hs.get_replication_data_handler()

        self._send<fix-suffix>_events = ReplicationFederationSendEventsRestServlet.make_client(hs)
        self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(
            hs
        )

        if hs.config.worker_app:
            self._user_device_resync = ReplicationUserDevicesResyncRestServlet.make_client(
                hs
            )
            self._maybe_store_room_on_outlier_membership = ReplicationStoreRoomOnOutlierMembershipRestServlet.make_client(
                hs
            )
        else:
            self._device_list_updater = hs.get_device_handler().device_list_updater
            self._maybe_store_room_on_outlier_membership = (
                self.store.maybe_store_room_on_outlier_membership
            )

        # When joining a room we need to queue any events for that room up.
        # For each room, a list of (pdu, origin) tuples.
        self.room_queues = {}  # type: Dict[str, List[Tuple[EventBase, str]]]
        self._room_pdu_linearizer = Linearizer("fed_<|endoftext|>


<fim-prefix>ignedjson.key
from signedjson.sign import SignatureVerifyException

from sydent.http.httpclient import FederationHttpClient

logger = logging.getLogger(__name__)

class NoAuthenticationError(Exception):
    """
    Raised when no signature is provided that could be authenticated
    """
    pass

class Verifier(object):
    """
    Verifies signed json blobs from Matrix Homeservers by finding the
    homeserver's address, contacting it, requesting its keys and
    verifying that the signature on the json blob matches.
    """
    def __init__(self, sydent):
        self.sydent = sydent
        # Cache of server keys. These are cached until the 'valid_until_ts' time
        # in the result.
        self.cache = {
            # server_name: <result from keys query>,
        }

    @defer.inlineCallbacks
    def _getKeysForServer(self, server_name):
        """Get the signing key data from a homeserver.

        :param server_name: The name of the server to request the keys from.
        :type server_name: unicode

        :return: The verification keys returned by the server.
        :rtype: twisted.internet.defer.Deferred[dict[unicode, dict[unicode, unicode]]]
        """

        if server_name in self.cache:
            cached = self.cache[server_name]
            now = int(time.time() * 1000)
            if cached['valid_until_ts'] > now:
                defer.returnValue(self.cache[server_name]['verify_keys'])

        client = FederationHttpClient(self.sydent)
        # BUG: CWE-770 Allocation of Resources Without Limits or Throttling
        # result = yield client.get_json("matrix://%s/_matrix/key/v2/server/" % server_name)
        # FIXED:
 <fim-middle>       result = yield client.get_json("matrix://%s/_matrix/key/v2/server/" % server_name, 1024 * 50)
        if 'verify_keys' not in result:
            raise SignatureVerifyException("No key found in <fix-suffix>response")

        if 'valid_until_ts' in result:
            # Don't cache anything without a valid_until_ts or we wouldn't
            # know when to expire it.
            logger.info("Got keys for %s: caching until %s", server_name, result['valid_until_ts'])
            self.cache[server_name] = result

        defer.returnValue(result['verify_keys'])

    @defer.inlineCallbacks
    def verifyServerSignedJson(self, signed_json, acceptable_server_names=None):
        """Given a signed json object, try to verify any one
        of the signatures on it

        XXX: This contains a fairly noddy version of the home server
        SRV lookup and signature verification. It does no caching (just
        fetches the signature each time and does not contact any other
        servers to do perspective checks).

        :param acceptable_server_names: If provided and not None,
        only signatures from servers in this list will be accepted.
        :type acceptable_server_names: list[unic<|endoftext|>


<fim-prefix>ograph=True`. See https://www.tensorflow.org/guide/autograph
        for more information.
      experimental_relax_shapes: When true, argument shapes may be relaxed to
        avoid unnecessary retracing.
      capture_by_value: Experimental. Whether to capture resource variables by
        value or reference. If None, will inherit from a parent context or
        default to False.
      jit_compile: Force-compile the function with XLA, cf.
        def_function.Function doc on jit_compile.
      experimental_follow_type_hints: See the documentation for `tf.function`.

    Raises:
      ValueError: if `input_signature` is not None and the `python_function`'s
        argspec has keyword arguments.
    """
    self._python_function = python_function
    pure_function = attributes and IMPLEMENTS_ATTRIBUTE_NAME in attributes
    self._function_spec = FunctionSpec.from_function_and_signature(
        python_function,
        input_signature,
        is_pure=pure_function,
        experimental_follow_type_hints=experimental_follow_type_hints)
    self._name = name
    self._autograph = autograph
    self._autograph_options = autograph_options
    self._experimental_relax_shapes = experimental_relax_shapes
    self._function_cache = FunctionCache()
    self._function_attributes = attributes or {}
    self._capture_by_value = capture_by_value
    self.tracing_count = 0
    if self.input_signature is not None:
      self._hashable_input_signature = hash(self.flat_input_signature)
    # BUG: CWE-667 Improper Locking
    #     self._lock = threading.Lock()
    # FIXED:
 <fim-middle>   self._lock = threading.RLock()
    # _descriptor_cache is a of instance of a class to an instance-specific
    # `Function`, used to make sure defun-decorated methods create different
    # function<fix-suffix>s for each instance.
    self._descriptor_cache = weakref.WeakKeyDictionary()
    self._jit_compile = jit_compile
    self._experimental_follow_type_hints = experimental_follow_type_hints

  def __call__(self, *args, **kwargs):
    """Calls a graph function specialized to the inputs."""
    with self._lock:
      (graph_function,
       filtered_flat_args) = self._maybe_define_function(args, kwargs)
    return graph_function._call_flat(
        filtered_flat_args, captured_inputs=graph_function.captured_inputs)  # pylint: disable=protected-access

  @property
  def python_function(self):
    """Returns the wrapped Python function."""
    return self._python_function  # pylint: disable=protected-access

  @property
  def function_spec(self):
    return self._function_spec

  @property
  def input_signature(self):
    """Returns the input signature."""
    return self._function_spec.input_signature

  @property
  def flat_input_signature(self):
    """Returns the flattened input signatur<|endoftext|>


<fim-prefix>n_url_parts))

# 4 views for password reset:
# - password_reset sends the mail
# - password_reset_done shows a success message for the above
# - password_reset_confirm checks the link the user clicked and
#   prompts for a new password
# - password_reset_complete shows a success message for the above

@csrf_protect
def password_reset(request, is_admin_site=False,
                   template_name='registration/password_reset_form.html',
                   email_template_name='registration/password_reset_email.html',
                   subject_template_name='registration/password_reset_subject.txt',
                   password_reset_form=PasswordResetForm,
                   token_generator=default_token_generator,
                   post_reset_redirect=None,
                   from_email=None,
                   current_app=None,
                   extra_context=None):
    if post_reset_redirect is None:
        post_reset_redirect = reverse('django.contrib.auth.views.password_reset_done')
    if request.method == "POST":
        form = password_reset_form(request.POST)
        if form.is_valid():
            opts = {
                'use_https': request.is_secure(),
                'token_generator': token_generator,
                'from_email': from_email,
                'email_template_name': email_template_name,
                'subject_template_name': subject_template_name,
                'request': request,
            }
            if is_admin_site:
                # BUG: CWE-20 Improper Input Validation
                # opts = dict(opts, domain_override=request.META['HTTP_HOST'])
                # FIXED:
  <fim-middle>              opts = dict(opts, domain_override=request.get_host())
            form.save(**opts)
            return HttpResponseRedirect(post_reset_redirect)
    else:
        form = password_reset_fo<fix-suffix>rm()
    context = {
        'form': form,
    }
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
                            current_app=current_app)

def password_reset_done(request,
                        template_name='registration/password_reset_done.html',
                        current_app=None, extra_context=None):
    context = {}
    if extra_context is not None:
        context.update(extra_context)
    return TemplateResponse(request, template_name, context,
                            current_app=current_app)

# Doesn't need csrf_protect since no-one can guess the URL
@sensitive_post_parameters()
@never_cache
def password_reset_confirm(request, uidb36=None, token=None,
                           template_name='registration/password_reset_confirm.html',
                           token_generator=default_token_generator,
                           set_password_form=SetPasswordForm,
      <|endoftext|>


<fim-prefix> except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import

from twisted.web.resource import Resource
from twisted.internet import defer

import logging
import json
from six.moves import urllib

from sydent.http.servlets import get_args, jsonwrap, deferjsonwrap, send_cors
from sydent.http.httpclient import FederationHttpClient
from sydent.users.tokens import issueToken

logger = logging.getLogger(__name__)

class RegisterServlet(Resource):
    isLeaf = True

    def __init__(self, syd):
        self.sydent = syd
        self.client = FederationHttpClient(self.sydent)

    @deferjsonwrap
    @defer.inlineCallbacks
    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']),
            ),
            # BUG: CWE-770 Allocation of Resources Without Limits or Throttling
            #
            # FIXED:
  <fim-middle>          1024 * 5,
        )
        if 'sub' not in result:
            raise Exception("Invalid response from homeserver")

        user_id = result['sub']
        tok = yield issueToken(self.sydent<fix-suffix>, 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,
        })

    def render_OPTIONS(self, request):
        send_cors(request)
        return b''
<|endoftext|>


<fim-prefix>y.

        Reference: https://tools.ietf.org/html/rfc7520#section-4.3
        """
        signing_input = (
            b"eyJhbGciOiJFUzUxMiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhb"
            b"XBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb"
            b"3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdS"
            b"Bkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmU"
            b"geW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"
        )

        signature = base64url_decode(
            b"AE_R_YZCChjn4791jSQCrdPZCNYqHXCTZH0-JZGYNlaAjP2kqaluUIIUnC9qvbu9P"
            b"lon7KRTzoNEuT4Va2cmL1eJAQy3mtPBu_u_sDDyYjnAMDxXPn7XrT0lw-kvAD890j"
            b"l8e2puQens_IEKBpHABlsbEPX6sFY8OcGDqoRuBomu9xQ2"
        )

        algo = ECAlgorithm(ECAlgorithm.SHA512)
        key = algo.prepare_key(load_ec_pub_key_p_521())

        result = algo.verify(signing_input, key, signature)
        assert result

        # private key can also be used.
        with open(key_path("jwk_ec_key_P-521.json")) as keyfile:
            private_key = algo.from_jwk(keyfile.read())

        result = algo.verify(signing_input, private_key, signature)
        assert result

@crypto_required
class TestOKPAlgorithms:
    hello_world_sig = b"Qxa47mk/azzUgmY2StAOguAd4P7YBLpyCfU3JdbaiWnXM4o4WibXwmIHvNYgN3frtE2fcyd8OYEaOiD/KiwkCg=="
    hello_world = b"Hello World!"

    def test_okp_ed25519_should_reject_non_string_key(self):
        algo = OKPAlgorithm()
        # BUG: CWE-327 Use of a Broken or Risky Cryptographic Algorithm
        # with pytest.raises(TypeError):
        # FIXED:
  <fim-middle>      with pytest.raises(InvalidKeyError):
            algo.prepare_key(None)

        with open(key_path("testkey_ed25519")) as keyfile:
            algo.prepare_key(keyfile.read())

        with open<fix-suffix>(key_path("testkey_ed25519.pub")) as keyfile:
            algo.prepare_key(keyfile.read())

    def test_okp_ed25519_should_accept_unicode_key(self):
        algo = OKPAlgorithm()

        with open(key_path("testkey_ed25519")) as ec_key:
            algo.prepare_key(ec_key.read())

    def test_okp_ed25519_sign_should_generate_correct_signature_value(self):
        algo = OKPAlgorithm()

        jwt_message = self.hello_world

        expected_sig = base64.b64decode(self.hello_world_sig)

        with open(key_path("testkey_ed25519")) as keyfile:
            jwt_key = algo.prepare_key(keyfile.read())

        with open(key_path("testkey_ed25519.pub")) as keyfile:
            jwt_pub_key = algo.prepare_key(keyfile.read())

        algo.sign(jwt_message, jwt_key)
        result = algo.verify(jwt_message, jwt_pub_key, expected_sig)
        assert result

    def test_okp_ed25519_verify_should_return_false_if_signature_invalid(self):
        algo = OKPAlgorithm()

        jwt_message = se<|endoftext|>


<fim-prefix>(?:[-_a-zA-ZÀ-ÖØ-öø-ÿ0-9]+)#"
    for match in re.finditer(PATTERN, dataobj.content):
        embedded_tags.add(match.group(0).replace("#", "").lstrip())

    return render_template(
        "dataobjs/show.html",
        title=dataobj["title"],
        dataobj=dataobj,
        backlinks=backlinks,
        current_path=dataobj["dir"],
        form=forms.DeleteDataForm(),
        view_only=0,
        search_enabled=app.config["SEARCH_CONF"]["enabled"],
        post_title_form=post_title_form,
        move_form=move_form,
        tag_list=tag_list,
        embedded_tags=embedded_tags,
        titles=titles,
    )

@app.route("/dataobj/move/<int:dataobj_id>", methods=["POST"])
def move_item(dataobj_id):
    form = forms.MoveItemForm()
    out_dir = form.path.data if form.path.data != "" else "root directory"
    if form.path.data == None:
        flash("No path specified.")
        return redirect(f"/dataobj/{dataobj_id}")
    try:
        if data.move_item(dataobj_id, form.path.data):
            flash(f"Data successfully moved to {out_dir}.", "success")
            return redirect(f"/dataobj/{dataobj_id}")
        else:
            flash(f"Data could not be moved to {out_dir}.", "error")
            return redirect(f"/dataobj/{dataobj_id}")
    except FileNotFoundError:
        flash("Data not found.", "error")
        return redirect("/")
    except FileExistsError:
        flash("Data already in target directory.", "error")
        return redirect(f"/dataobj/{dataobj_id}")

# BUG: CWE-352 Cross-Site Request Forgery (CSRF)
# @app.route("/dataobj/delete/<int:dataobj_id>", methods=["DELETE", "GET"])
# FIXED:
@<fim-middle>app.route("/dataobj/delete/<int:dataobj_id>", methods=["POST"])
def delete_data(dataobj_id):
    try:
        data.delete_item(dataobj_id)
    except BaseException:
        flash("Data could not be fou<fix-suffix>nd!", "error")
        return redirect("/")
    flash("Data deleted!", "success")
    return redirect("/")

@app.route("/login", methods=["GET", "POST"])
def login():
    form = forms.UserForm()
    if form.validate_on_submit():
        db = get_db()
        user = db.search(
            (Query().username == form.username.data) & (Query().type == "user")
        )

        if user and check_password_hash(user[0]["hashed_password"], form.password.data):
            user = User.from_db(user[0])
            login_user(user, remember=True)
            flash("Login successful!", "success")

            next_url = request.args.get("next")
            return redirect(next_url or "/")

        flash("Invalid credentials", "error")
        return redirect("/login")
    return render_template("users/login.html", form=form, title="Login")

@app.route("/logout", methods=["DELETE", "GET"])
def logout():
    logout_user()
    flash("Logged out successfully", "success")
    return redirect("/")

@<|endoftext|>


<fim-prefix># -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
import frappe
from frappe.model.document import Document

class PortalSettings(Document):
	def add_item(self, item):
		'''insert new portal menu item if route is not set, or role is different'''
		exists = [d for d in self.get('menu', []) if d.get('route')==item.get('route')]
		if exists and item.get('role'):
			if exists[0].role != item.get('role'):
				exists[0].role = item.get('role')
				return True
		elif not exists:
			item['enabled'] = 1
			self.append('menu', item)
			return True
	# BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
	#
	# FIXED:
	@<fim-middle>frappe.whitelist()
	def reset(self):
		'''Restore defaults'''
		self.menu = []
		self.sync_menu()

	def sync_menu(self):
		'''Sync portal menu items'''
		dirty = False
		for item in frappe.get_hooks('s<fix-suffix>tandard_portal_menu_items'):
			if item.get('role') and not frappe.db.exists("Role", item.get('role')):
				frappe.get_doc({"doctype": "Role", "role_name": item.get('role'), "desk_access": 0}).insert()
			if self.add_item(item):
				dirty = True

		if dirty:
			self.save()

	def on_update(self):
		self.clear_cache()

	def clear_cache(self):
		# make js and css
		# clear web cache (for menus!)
		frappe.clear_cache(user='Guest')

		from frappe.website.render import clear_cache
		clear_cache()

		# clears role based home pages
		frappe.clear_cache()

<|endoftext|>


<fim-prefix>mpliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 */
package org.hyperledger.besu.evm.operation;

import static org.apache.tuweni.bytes.Bytes32.leftPad;

import org.hyperledger.besu.evm.EVM;
import org.hyperledger.besu.evm.frame.MessageFrame;
import org.hyperledger.besu.evm.gascalculator.GasCalculator;

import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;

public class ShlOperation extends AbstractFixedCostOperation {

  public ShlOperation(final GasCalculator gasCalculator) {
    super(0x1b, "SHL", 2, 1, 1, gasCalculator, gasCalculator.getVeryLowTierGasCost());
  }

  @Override
  public Operation.OperationResult executeFixedCostOperation(
      final MessageFrame frame, final EVM evm) {
    Bytes shiftAmount = frame.popStackItem();
    if (shiftAmount.size() > 4 && (shiftAmount = shiftAmount.trimLeadingZeros()).size() > 4) {
      frame.popStackItem();
      frame.pushStackItem(UInt256.ZERO);
    } else {
      final int shiftAmountInt = shiftAmount.toInt();
      final Bytes value = leftPad(frame.popStackItem());
      // BUG: CWE-681 Incorrect Conversion between Numeric Types
      // if (shiftAmountInt >= 256) {
      // FIXED:
<fim-middle>      if (shiftAmountInt >= 256 || shiftAmountInt < 0) {
        frame.pushStackItem(UInt256.ZERO);
      } else {
        frame.pushStackItem(value.shiftLeft(shiftAmountInt));
      }
    }
    return<fix-suffix> successResponse;
  }
}
<|endoftext|>


<fim-prefix>pyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock;

import com.github.steveice10.mc.protocol.data.game.ClientRequest;
import com.github.steveice10.mc.protocol.packet.ingame.client.ClientRequestPacket;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;
import com.nukkitx.protocol.bedrock.packet.RespawnPacket;
import com.nukkitx.protocol.bedrock.packet.SetEntityDataPacket;
import org.geysermc.connector.entity.player.PlayerEntity;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

@Translator(packet = RespawnPacket.class)
public class BedrockRespawnTranslator extends PacketTranslator<RespawnPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(RespawnPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, RespawnPacket packet) {
        if (packet.getState() == RespawnPacket.State.CLIENT_READY) {
            // Previously we only sent the respawn packet b<fix-suffix>efore the server finished loading
            // The message included was 'Otherwise when immediate respawn is on the client never loads'
            // But I assume the new if statement below fixes that problem
            RespawnPacket respawnPacket = new RespawnPacket();
            respawnPacket.setRuntimeEntityId(0);
            respawnPacket.setPosition(Vector3f.ZERO);
            respawnPacket.setState(RespawnPacket.State.SERVER_READY);
            session.sendUpstreamPacket(respawnPacket);

            if (session.isSpawned()) {
                // Client might be stuck; resend spawn information
                PlayerEntity entity = session.getPlayerEntity();
                if (entity == null) return;
                SetEntityDataPacket entityDataPacket = new SetEntityDataPacket();
                entityDataPacket.setRuntimeEntityId(entity.getGeyserId());
                entityDataPacket.getMetadata().putAll(entity.getMetadata());
                session.sendUpstreamPacket(enti<|endoftext|>


<fim-prefix>flc);
		tableEl.setCustomizeColumns(false);
		tableEl.setNumOfRowsEnabled(false);

		refreshbtn = uifactory.addFormLink("button.refresh", flc, Link.BUTTON);
		refreshbtn.setIconLeftCSS("o_icon o_icon_refresh o_icon-fw");
	}

	@Override
	public void event(UserRequest ureq, Component source, Event event) {
		super.event(ureq, source, event);
	}

	@Override
	protected void event(UserRequest ureq, Controller source, org.olat.core.gui.control.Event event) {
		if (source instanceof FormLink && ((FormLink) source).getCmd().equals("viewQuality")) {
			if (cmc == null) {
				// initialize preview controller only once
				previewVC = createVelocityContainer("video_preview");
				cmc = new CloseableModalController(getWindowControl(), "close", previewVC);
				listenTo(cmc);
			}
		}
		super.event(ureq, source, event);
	}

	@Override
	protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {
		if (source instanceof FormLink && ((FormLink) source).getCmd().equals("viewQuality")) {
			if (cmc == null) {
				// initialize preview controller only once
				previewVC = createVelocityContainer("video_preview");
				cmc = new CloseableModalController(getWindowControl(), "close", previewVC);
				listenTo(cmc);
			}
			// Get the user object from the link to access version object
			FormLink link = (FormLink) source;
			VideoTranscoding videoTranscoding = (VideoTranscoding) link.getUserObject();
			if (videoTranscoding == null) {
				// this is the master video
				// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
				// VideoMetadata videoMetadata = videoManager.readVideoMetadataFile(videoResource);
				// FIXED:
<fim-middle>				VideoMeta videoMetadata = videoManager.getVideoMetadata(videoResource);
				previewVC.contextPut("width", videoMetadata.getWidth());
				previewVC.contextPut("height", videoMetadata.getHeight());
	<fix-suffix>			previewVC.contextPut("filename", "video.mp4");
				VFSContainer container = videoManager.getMasterContainer(videoResource);
				String transcodedUrl = registerMapper(ureq, new VideoMediaMapper(container));
				previewVC.contextPut("mediaUrl", transcodedUrl);
			} else {
				// this is a version
				previewVC.contextPut("width", videoTranscoding.getWidth());
				previewVC.contextPut("height", videoTranscoding.getHeight());
				previewVC.contextPut("filename", videoTranscoding.getResolution() + "video.mp4");
				VFSContainer container = videoManager.getTranscodingContainer(videoResource);
				String transcodedUrl = registerMapper(ureq, new VideoMediaMapper(container));
				previewVC.contextPut("mediaUrl", transcodedUrl);
			}
			// activate dialog to bring it in front
			cmc.activate();
		} else if (source instanceof FormLink && ((FormLink) source).getCmd().equals("deleteQuality")) {
			FormLink link = (FormLink) source;
			VideoTranscoding videoTranscoding = (VideoTranscoding) link.g<|endoftext|>


<fim-prefix> KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.thoughtworks.go.addon.businesscontinuity.primary.controller;

import com.google.gson.Gson;
import com.thoughtworks.go.addon.businesscontinuity.ConfigFileType;
import com.thoughtworks.go.addon.businesscontinuity.DatabaseStatusProvider;
import com.thoughtworks.go.addon.businesscontinuity.FileDetails;
import com.thoughtworks.go.addon.businesscontinuity.PluginsList;
import com.thoughtworks.go.addon.businesscontinuity.primary.ServerStatusResponse;
import com.thoughtworks.go.addon.businesscontinuity.primary.service.GoFilesStatusProvider;
import com.thoughtworks.go.util.SystemEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.io.IOUtils.copy;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isEmpty;

@Controller
@SuppressWarnings("WeakerAccess")
// BUG: CWE-200 Exposure of Sensitive Information to an Unauthorized Actor
// @RequestMapping(value = "/add-on/business-continuity/api")
// FIXED:
p<fim-middle>ublic class PrimaryStatusProviderController {

    private GoFilesStatusProvider goFilesStatusProvider;
    private DatabaseStatusProvider databaseStatusProvider;
    private final SystemEnvironment sy<fix-suffix>stemEnvironment;
    private PluginsList pluginsList;

    @Autowired
    public PrimaryStatusProviderController(GoFilesStatusProvider goFilesStatusProvider, DatabaseStatusProvider databaseStatusProvider, PluginsList pluginsList, SystemEnvironment systemEnvironment) {
        this.goFilesStatusProvider = goFilesStatusProvider;
        this.databaseStatusProvider = databaseStatusProvider;
        this.pluginsList = pluginsList;
        this.systemEnvironment = systemEnvironment;
    }

    @RequestMapping(value = "/health-check", method = RequestMethod.GET)
    @ResponseBody
    public String healthCheck() {
        return "OK!";
    }

    @RequestMapping(value = "/latest_database_wal_location", method = RequestMethod.GET)
    @ResponseBody
    public String latestDatabaseWalLocation() {
        return databaseStatusProvider.latestWalLocation();
    }

    @RequestMapping(value = "/config_files_status", method = RequestMethod.GET)
    public void latestStatus(HttpServletResponse respon<|endoftext|>


<fim-prefix>tems, used for caching. There is usually few of them (about 15). */
    private final Map<String, LocalName> scopes = new HashMap<>();

    /**
     * The properties to be given the objects to construct. Reused every time {@link
     * #createProperties} is invoked.
     */
    private final Map<String, Object> properties = new HashMap<>();

    /**
     * A safety guard for preventing never-ending loops in recursive calls to {@link #createDatum}.
     * This is used by {@link #createBursaWolfParameters}, which need to create a target datum. The
     * target datum could have its own Bursa-Wolf parameters, with one of them pointing again to the
     * source datum.
     */
    private final Set<String> safetyGuard = new HashSet<>();

    public AbstractEpsgFactory(final Hints userHints) throws FactoryException {
        super(MAXIMUM_PRIORITY - 20);
        // The following hints have no effect on this class behaviour,
        // but tell to the user what this factory do about axis order.
        hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);
        hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);
        hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, Boolean.FALSE);

        //
        // We need to obtain our DataSource
        if (userHints != null) {
            Object hint = userHints.get(Hints.EPSG_DATA_SOURCE);
            if (hint instanceof String) {
                String name = (String) hint;
                try {
                    // BUG: CWE-20 Improper Input Validation
                    // dataSource = (DataSource) GeoTools.getInitialContext().lookup(name);
                    // FIXED:
<fim-middle>                    dataSource = (DataSource) GeoTools.jndiLookup(name);
                } catch (NamingException e) {
                    throw new FactoryException("A EPSG_DATA_SOURCE hint is require<fix-suffix>d:" + e);
                }
                hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
            } else if (hint instanceof DataSource) {
                dataSource = (DataSource) hint;
                hints.put(Hints.EPSG_DATA_SOURCE, dataSource);
            } else {
                throw new FactoryException("A EPSG_DATA_SOURCE hint is required.");
            }
        } else {
            throw new FactoryException("A EPSG_DATA_SOURCE hint is required.");
        }
    }

    public AbstractEpsgFactory(final Hints userHints, final javax.sql.DataSource dataSource) {
        super(MAXIMUM_PRIORITY - 20);

        this.dataSource = dataSource;
        // The following hints have no effect on this class behaviour,
        // but tell to the user what this factory do about axis order.
        hints.put(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.FALSE);
        hints.put(Hints.FORCE_STANDARD_AXIS_DIRECTIONS, Boolean.FALSE);
        hints.put(Hints.FORCE_STANDARD_AXIS_UNITS, B<|endoftext|>


<fim-prefix>/*
 * Copyright 2020 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.handler.codec.http.multipart;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.internal.PlatformDependent;
import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.UUID;

import static io.netty.util.CharsetUtil.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

/**
 * {@link AbstractDiskHttpData} test cases
 */
public class AbstractDiskHttpDataTest {

    @Test
    public void testGetChunk() throws Exception {
        TestHttpData test = new TestHttpData("test", UTF_8, 0);
        try {
            // BUG: CWE-378 Creation of Temporary File With Insecure Permissions
            // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
            // FIXED:
<fim-middle>            File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null);
            tmpFile.deleteOnExit();
            FileOutputStream fos = new FileOutputStream(tmpF<fix-suffix>ile);
            byte[] bytes = new byte[4096];
            PlatformDependent.threadLocalRandom().nextBytes(bytes);
            try {
                fos.write(bytes);
                fos.flush();
            } finally {
                fos.close();
            }
            test.setContent(tmpFile);
            ByteBuf buf1 = test.getChunk(1024);
            assertEquals(buf1.readerIndex(), 0);
            assertEquals(buf1.writerIndex(), 1024);
            ByteBuf buf2 = test.getChunk(1024);
            assertEquals(buf2.readerIndex(), 0);
            assertEquals(buf2.writerIndex(), 1024);
            assertFalse("Arrays should not be equal",
                    Arrays.equals(ByteBufUtil.getBytes(buf1), ByteBufUtil.getBytes(buf2)));
        } finally {
            test.delete();
        }
    }

    private static final class TestHttpData extends AbstractDiskHttpData {

        private TestHttpData(String name, Charset charset, long size) {
            super(name, charset, size);
 <|endoftext|>


<fim-prefix> + id;
		long timestamp = Utils.timestamp() / 1000;
		Cloudinary cloudinary = new Cloudinary(CONF.cloudinaryUrl());
		String signature = cloudinary.apiSignRequest(ObjectUtils.asMap(
			"public_id", publicId,
			"timestamp", String.valueOf(timestamp),
			"upload_preset", preset
		), cloudinary.config.apiSecret);

		Map<String, Object> response = new HashMap<String, Object>();
		response.put("url", "https://api.cloudinary.com/v1_1/" + cloudinary.config.cloudName + "/image/upload");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("resource_type", "image");
		data.put("public_id", publicId);
		data.put("upload_preset", preset);
		data.put("filename", id);
		data.put("timestamp", timestamp);
		data.put("api_key", cloudinary.config.apiKey);
		data.put("signature", signature);
		response.put("data", data);

		return ResponseEntity.ok().body(response);
	}

	private Profile getProfileForEditing(String id, Profile authUser) {
		if (!canEditProfile(authUser, id)) {
			return null;
		}
		return isMyid(authUser, id) ? authUser : (Profile) utils.getParaClient().read(Profile.id(id));
	}

	private boolean updateUserPictureAndName(Profile showUser, String picture, String name) {
		boolean updateProfile = false;
		boolean updateUser = false;
		User u = showUser.getUser();

		if (CONF.avatarEditsEnabled() && !StringUtils.isBlank(picture)) {
			updateProfile = avatarRepository.store(showUser, picture);
		}

		if (CONF.nameEditsEnabled() && !StringUtils.isBlank(name)) {
			// BUG: NVD-CWE-Other Other
			// showUser.setName(name);
			// FIXED:
	<fim-middle>		showUser.setName(StringUtils.abbreviate(name, 256));
			if (StringUtils.isBlank(showUser.getOriginalName())) {
				showUser.setOriginalName(name);
			}
			if (!u.getName().equals(name)) {
				u.setNa<fix-suffix>me(name);
				updateUser = true;
			}
			updateProfile = true;
		}

		if (updateUser) {
			utils.getParaClient().update(u);
		}
		return updateProfile;
	}

	private boolean isMyid(Profile authUser, String id) {
		return authUser != null && (StringUtils.isBlank(id) || authUser.getId().equals(Profile.id(id)));
	}

	private boolean canEditProfile(Profile authUser, String id) {
		return isMyid(authUser, id) || utils.isAdmin(authUser);
	}

	private Object getUserDescription(Profile showUser, Long questions, Long answers) {
		if (showUser == null) {
			return "";
		}
		return showUser.getVotes() + " points, "
				+ showUser.getBadgesMap().size() + " badges, "
				+ questions + " questions, "
				+ answers + " answers "
				+ Utils.abbreviate(showUser.getAboutme(), 150);
	}

	public List<? extends Post> getQuestions(Profile authUser, Profile showUser, boolean isMyProfile, Pager itemcount) {
		if (utils.postsNeedApproval() && (isMyProfile || utils.isMod(authUser))) {
			List<Question> qlist = <|endoftext|>


<fim-prefix>itionPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerPositionRotationPacket;
import com.github.steveice10.mc.protocol.packet.ingame.client.player.ClientPlayerRotationPacket;
import com.github.steveice10.packetlib.packet.Packet;
import com.nukkitx.math.vector.Vector3d;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;
import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.common.ChatColor;
import org.geysermc.connector.entity.player.SessionPlayerEntity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

@Translator(packet = MovePlayerPacket.class)
public class BedrockMovePlayerTranslator extends PacketTranslator<MovePlayerPacket> {
    /* The upper and lower bounds to check for the void floor that only exists in Bedrock */
    private static final int BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y;
    private static final int BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y;

    static {
        BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y = GeyserConnector.getInstance().getConfig().isExtendedWorldHeight() ? -104 : -40;
        BEDROCK_OVERWORLD_VOID_FLOOR_LOWER_Y = BEDROCK_OVERWORLD_VOID_FLOOR_UPPER_Y + 2;
    }

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(MovePlayerPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, MovePlayerPacket packet) {
        SessionPlayerEntity entity = session.getPlayerEntity();
        if (!session.isSpawned()) return;

        if (!sessi<fix-suffix>on.getUpstream().isInitialized()) {
            MoveEntityAbsolutePacket moveEntityBack = new MoveEntityAbsolutePacket();
            moveEntityBack.setRuntimeEntityId(entity.getGeyserId());
            moveEntityBack.setPosition(entity.getPosition());
            moveEntityBack.setRotation(entity.getBedrockRotation());
            moveEntityBack.setTeleported(true);
            moveEntityBack.setOnGround(true);
            session.sendUpstreamPacketImmediately(moveEntityBack);
            return;
        }

        session.setLastMovementTimestamp(System.currentTimeMillis());

        // Send book update before the player moves
        session.getBookEditCache().checkForSend();

        session.confirmTeleport(packet.getPosition().toDouble().sub(0, EntityType.PLAYER.getOffset(), 0));
        // head yaw, pitch, head yaw
        Vector3f rotation = Vector3f.from(packet.getRotation().getY(), packet.getRotation().getX(), packet.getRotation().getY());

        boolean positionChanged = !e<|endoftext|>


<fim-prefix> org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;
import org.geysermc.connector.network.translators.item.ItemTranslator;
import org.geysermc.connector.registry.Registries;
import org.geysermc.connector.registry.type.ItemMapping;
import org.geysermc.connector.utils.InventoryUtils;

import java.util.*;
import java.util.stream.Collectors;

import static org.geysermc.connector.utils.InventoryUtils.LAST_RECIPE_NET_ID;

/**
 * Used to send all valid recipes from Java to Bedrock.
 *
 * Bedrock REQUIRES a CraftingDataPacket to be sent in order to craft anything.
 */
@Translator(packet = ServerDeclareRecipesPacket.class)
public class JavaDeclareRecipesTranslator extends PacketTranslator<ServerDeclareRecipesPacket> {
    /**
     * Required to use the specified cartography table recipes
     */
    private static final List<CraftingData> CARTOGRAPHY_RECIPES = Arrays.asList(
            CraftingData.fromMulti(UUID.fromString("8b36268c-1829-483c-a0f1-993b7156a8f2"), ++LAST_RECIPE_NET_ID), // Map extending
            CraftingData.fromMulti(UUID.fromString("442d85ed-8272-4543-a6f1-418f90ded05d"), ++LAST_RECIPE_NET_ID), // Map cloning
            CraftingData.fromMulti(UUID.fromString("98c84b38-1085-46bd-b1ce-dd38c159e6cc"), ++LAST_RECIPE_NET_ID), // Map upgrading
            CraftingData.fromMulti(UUID.fromString("602234e4-cac1-4353-8bb7-b1ebff70024b"), ++LAST_RECIPE_NET_ID) // Map locking
    );

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(ServerDeclareRecipesPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, ServerDeclareRecipesPacket packet) {
        Map<RecipeType, List<CraftingData>> recipeTypes = Registries.CRAFTING_DATA.forVersion(session.getUpstream()<fix-suffix>.getProtocolVersion());
        // Get the last known network ID (first used for the pregenerated recipes) and increment from there.
        int netId = InventoryUtils.LAST_RECIPE_NET_ID + 1;

        Int2ObjectMap<Recipe> recipeMap = new Int2ObjectOpenHashMap<>(Registries.RECIPES.forVersion(session.getUpstream().getProtocolVersion()));
        Int2ObjectMap<List<StoneCuttingRecipeData>> unsortedStonecutterData = new Int2ObjectOpenHashMap<>();
        CraftingDataPacket craftingDataPacket = new CraftingDataPacket();
        craftingDataPacket.setCleanRecipes(true);
        for (Recipe recipe : packet.getRecipes()) {
            switch (recipe.getType()) {
                case CRAFTING_SHAPELESS: {
                    ShapelessRecipeData shapelessRecipeData = (ShapelessRecipeData) recipe.getData();
                    ItemData output = ItemTranslator.translateToBedrock(session, shapelessRecipeData.getResult());
                    // Strip NBT - tools won't appear in the recipe book oth<|endoftext|>


<fim-prefix>onvert.ConversionContext;
import io.micronaut.core.convert.ConversionService;
import io.micronaut.core.reflect.GenericTypeUtils;
import io.micronaut.core.type.Argument;
import io.micronaut.core.value.ValueResolver;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

/**
 * An interface for classes that represent a map-like structure of values that can be converted.
 *
 * @param <V> The generic value
 * @author Graeme Rocher
 * @since 1.0
 */
public interface ConvertibleValues<V> extends ValueResolver<CharSequence>, Iterable<Map.Entry<String, V>> {

    ConvertibleValues EMPTY = new ConvertibleValuesMap<>(Collections.emptyMap());

    /**
     * @return The names of the values
     */
    Set<String> names();

    /**
     * @return The values
     */
    Collection<V> values();

    /**
     * @return Whether this values is empty
     */
    default boolean isEmpty() {
        return this == ConvertibleValues.EMPTY || names().isEmpty();
    }

    /**
     * @return The concrete type of the value
     */
    @SuppressWarnings("unchecked")
    default Class<V> getValueType() {
        Optional<Class> type = GenericTypeUtils.resolveInterfaceTypeArgument(getClass(), ConvertibleValues.class);
        return type.orElse(Object.class);
    }

    /**
     * Whether the given key is contained within these values.
     *
     * @param name The key name
     * @return True if it is
     */
    default boolean contains(String name) {
        // BUG: CWE-400 Uncontrolled Resource Consumption
        // return get(name, Object.class).isPresent();
        // FIXED:
<fim-middle>        return get(name, Argument.OBJECT_ARGUMENT).isPresent();
    }

    /**
     * Performs the given action for each value. Note that in the case
     * where multiple values exist for the same hea<fix-suffix>der then the consumer will be invoked
     * multiple times for the same key.
     *
     * @param action The action to be performed for each entry
     * @throws NullPointerException if the specified action is null
     * @since 1.0
     */
    default void forEach(BiConsumer<String, V> action) {
        Objects.requireNonNull(action, "Consumer cannot be null");

        Collection<String> headerNames = names();
        for (String headerName : headerNames) {
            Optional<V> vOptional = this.get(headerName, getValueType());
            vOptional.ifPresent(v -> action.accept(headerName, v));
        }
    }

    /**
     * Return this {@link ConvertibleValues} as a map for the given key type and value type. The map represents a copy of the data held by this instance.
     *
     * @return The values
     */
    default Map<String, V> asMap() {
        Map<String, V> newMap = new LinkedHashMap<>();
        for (Map.Entry<String, V> entry : this) {
            String key = entry.<|endoftext|>


<fim-prefix>CE);
		//}
		return spaces;
	}

	public void setSpaces(Set<String> spaces) {
		this.spaces = spaces;
	}

	@JsonIgnore
	public Set<String> getAllSpaces() {
		return getSpaces().stream().filter(s -> !s.equalsIgnoreCase(Post.DEFAULT_SPACE)).collect(Collectors.toSet());
	}

	public Long getLastseen() {
		return lastseen;
	}

	public void setLastseen(Long val) {
		this.lastseen = val;
	}

	public String getWebsite() {
		return website;
	}

	public void setWebsite(String website) {
		this.website = website;
	}

	public Long getComments() {
		return comments;
	}

	public void setComments(Long comments) {
		this.comments = comments;
	}

	public Long getDownvotes() {
		return downvotes;
	}

	public void setDownvotes(Long downvotes) {
		this.downvotes = downvotes;
	}

	public Long getUpvotes() {
		return upvotes;
	}

	public void setUpvotes(Long upvotes) {
		this.upvotes = upvotes;
	}

	public String getBadges() {
		return badges;
	}

	public void setBadges(String badges) {
		this.badges = badges;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getAboutme() {
		return this.aboutme;
	}

	public void setAboutme(String aboutme) {
		this.aboutme = aboutme;
	}

	public String getOriginalName() {
		return originalName;
	}

	public void setOriginalName(String originalName) {
		// BUG: NVD-CWE-Other Other
		// this.originalName = originalName;
		// FIXED:
<fim-middle>		this.originalName = StringUtils.abbreviate(originalName, 256);
	}

	public String getOriginalPicture() {
		return originalPicture;
	}

	public void setOriginalPicture(String originalPicture) {
		this<fix-suffix>.originalPicture = originalPicture;
	}

	@SuppressWarnings("unchecked")
	public List<Question> getAllQuestions(Pager pager) {
		if (getId() == null) {
			return new ArrayList<Question>();
		}
		return (List<Question>) getPostsForUser(Utils.type(Question.class), pager);
	}

	@SuppressWarnings("unchecked")
	public List<Reply> getAllAnswers(Pager pager) {
		if (getId() == null) {
			return new ArrayList<Reply>();
		}
		return (List<Reply>) getPostsForUser(Utils.type(Reply.class), pager);
	}

	@SuppressWarnings("unchecked")
	public List<Question> getAllUnapprovedQuestions(Pager pager) {
		if (getId() == null) {
			return new ArrayList<Question>();
		}
		return (List<Question>) getPostsForUser(Utils.type(UnapprovedQuestion.class), pager);
	}

	@SuppressWarnings("unchecked")
	public List<Reply> getAllUnapprovedAnswers(Pager pager) {
		if (getId() == null) {
			return new ArrayList<Reply>();
		}
		return (List<Reply>) getPostsForUser(Utils.type(UnapprovedReply.class), pager);
	}

	private Lis<|endoftext|>


<fim-prefix>ation;
    private final int MAX_AUTHENTICATION_RESULT = 1;

    public JNDILdapClient(LdapConfiguration ldapConfiguration) {
        this.ldapConfiguration = ldapConfiguration;
    }

    @Override
    public <T> T authenticate(String username, String password, Mapper<T> mapper) {
        DirContext dirContext = getDirContext(ldapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword());

        try {
            List<SearchResult> results = search(dirContext, ldapConfiguration.getUserLoginFilter(), new String[]{username}, MAX_AUTHENTICATION_RESULT, true);

            if (results.isEmpty()) {
                throw new RuntimeException(format("User {0} does not exist in {1}", username, ldapConfiguration.getLdapUrlAsString()));
            }

            SearchResult searchResult = results.get(0);
            Attributes attributes = searchResult.getAttributes();
            String userDn = searchResult.getNameInNamespace();
            attributes.put(new BasicAttribute("dn", userDn));
            authenticate(ldapConfiguration, userDn, password);
            return mapper.mapObject(new ResultWrapper(attributes));

        } catch (SearchResultLimitExceededException e) {
            throw new MultipleUserDetectedException(username, e.getSearchBase(), ldapConfiguration.getUserLoginFilter());
        } catch (NamingException e) {
            throw new LdapException(e);
        } finally {
            closeContextSilently(dirContext);
        }
    }
    // BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
    // public <T> List<T> search(String filter, Object[] filterArgs, Mapper<T> mapper, int maxResult) {
    // FIXED:
 <fim-middle>   public <T> List<T> search(String filter, String[] filterArgs, Mapper<T> mapper, int maxResult) {

        List<T> results = new ArrayList<>();
        DirContext dirContext = getDirContext(l<fix-suffix>dapConfiguration, ldapConfiguration.getManagerDn(), ldapConfiguration.getPassword());

        try {
            List<SearchResult> searchResults = search(dirContext, filter, filterArgs, maxResult, false);

            for (SearchResult result : searchResults) {
                results.add(mapper.mapObject(new ResultWrapper(result.getAttributes())));
            }
        } catch (NamingException e) {
            throw new LdapException(e);
        } finally {
            closeContextSilently(dirContext);
        }

        return results;
    }

    private final DirContext getDirContext(LdapConfiguration ldapConfiguration, String username, String password) {
        Hashtable<String, Object> environments = new Environment(ldapConfiguration).getEnvironments();
        if (isNotBlank(username)) {
            environments.put(SECURITY_PRINCIPAL, username);
            environments.put(SECURITY_CREDENTIALS, password);
        }

        InitialDirContext context = null;

        try {
  <|endoftext|>


<fim-prefix>l.signing.private.key";
    String SAML_CANONICALIZATION_METHOD_ATTRIBUTE = "saml_signature_canonicalization_method";
    String SAML_SIGNATURE_ALGORITHM = "saml.signature.algorithm";
    String SAML_NAME_ID_FORMAT_ATTRIBUTE = "saml_name_id_format";
    String SAML_AUTHNSTATEMENT = "saml.authnstatement";
    String SAML_ONETIMEUSE_CONDITION = "saml.onetimeuse.condition";
    String SAML_FORCE_NAME_ID_FORMAT_ATTRIBUTE = "saml_force_name_id_format";
    String SAML_ARTIFACT_BINDING = "saml.artifact.binding";
    String SAML_SERVER_SIGNATURE = "saml.server.signature";
    String SAML_SERVER_SIGNATURE_KEYINFO_EXT = "saml.server.signature.keyinfo.ext";
    String SAML_SERVER_SIGNATURE_KEYINFO_KEY_NAME_TRANSFORMER = "saml.server.signature.keyinfo.xmlSigKeyInfoKeyNameTransformer";
    String SAML_FORCE_POST_BINDING = "saml.force.post.binding";
    String SAML_ASSERTION_SIGNATURE = "saml.assertion.signature";
    String SAML_ENCRYPT = "saml.encrypt";
    String SAML_CLIENT_SIGNATURE_ATTRIBUTE = "saml.client.signature";
    String SAML_SIGNING_CERTIFICATE_ATTRIBUTE = "saml.signing." + CertificateInfoHelper.X509CERTIFICATE;
    String SAML_ENCRYPTION_CERTIFICATE_ATTRIBUTE = "saml.encryption." + CertificateInfoHelper.X509CERTIFICATE;
    String SAML_ENCRYPTION_PRIVATE_KEY_ATTRIBUTE = "saml.encryption." + CertificateInfoHelper.PRIVATE_KEY;
    String SAML_ASSERTION_LIFESPAN = "saml.assertion.lifespan";
    String SAML_ARTIFACT_BINDING_IDENTIFIER = "saml.artifact.binding.identifier";
    // BUG: CWE-287 Improper Authentication
    //
    // FIXED:
 <fim-middle>   String SAML_ALLOW_ECP_FLOW = "saml.allow.ecp.flow";
}
<fix-suffix><|endoftext|>


<fim-prefix>     offset += read;
                if (len <= 0 || offset >= buf.length) {
                    break;
                }
            }
            return buf;
        } finally {
            fis.close();
        }
    }

    @Test
    public void testDelete() throws Exception {
        String json = "{\"foo\":\"bar\"}";
        byte[] bytes = json.getBytes(CharsetUtil.UTF_8);
        File tmpFile = null;
        DiskFileUpload f1 = new DiskFileUpload("file4", "file4", "application/json", null, null, 0);
        try {
            assertNull(f1.getFile());
            f1.setContent(Unpooled.wrappedBuffer(bytes));
            assertNotNull(tmpFile = f1.getFile());
        } finally {
            f1.delete();
            assertNull(f1.getFile());
            assertNotNull(tmpFile);
            assertFalse(tmpFile.exists());
        }
    }

    @Test
    public void setSetContentFromFileExceptionally() throws Exception {
        final long maxSize = 4;
        DiskFileUpload f1 = new DiskFileUpload("file5", "file5", "application/json", null, null, 0);
        f1.setMaxSize(maxSize);
        try {
            f1.setContent(Unpooled.wrappedBuffer(new byte[(int) maxSize]));
            File originalFile = f1.getFile();
            assertNotNull(originalFile);
            assertEquals(maxSize, originalFile.length());
            assertEquals(maxSize, f1.length());
            byte[] bytes = new byte[8];
            PlatformDependent.threadLocalRandom().nextBytes(bytes);
            // BUG: CWE-378 Creation of Temporary File With Insecure Permissions
            // File tmpFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
            // FIXED:
<fim-middle>            File tmpFile = PlatformDependent.createTempFile(UUID.randomUUID().toString(), ".tmp", null);
            tmpFile.deleteOnExit();
            FileOutputStream fos = new FileOutputStream(tmpF<fix-suffix>ile);
            try {
                fos.write(bytes);
                fos.flush();
            } finally {
                fos.close();
            }
            try {
                f1.setContent(tmpFile);
                fail("should not reach here!");
            } catch (IOException e) {
                assertNotNull(f1.getFile());
                assertEquals(originalFile, f1.getFile());
                assertEquals(maxSize, f1.length());
            }
        } finally {
            f1.delete();
        }
    }
}
<|endoftext|>


<fim-prefix>istribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock;

import com.nukkitx.protocol.bedrock.packet.ClientboundMapItemDataPacket;
import com.nukkitx.protocol.bedrock.packet.MapInfoRequestPacket;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

import java.util.concurrent.TimeUnit;

@Translator(packet = MapInfoRequestPacket.class)
public class BedrockMapInfoRequestTranslator extends PacketTranslator<MapInfoRequestPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(MapInfoRequestPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, MapInfoRequestPacket packet) {
        long mapId = packet.getUniqueMapId();

        ClientboundMapItemDataPacket mapPacket = session.getStoredMaps().r<fix-suffix>emove(mapId);
        if (mapPacket != null) {
            // Delay the packet 100ms to prevent the client from ignoring the packet
            GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> session.sendUpstreamPacket(mapPacket),
                    100, TimeUnit.MILLISECONDS);
        }
    }
}
<|endoftext|>


<fim-prefix>s
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author GeyserMC
 * @link https://github.com/GeyserMC/Geyser
 */

package org.geysermc.connector.network.translators.bedrock;

import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.network.translators.Translator;

import com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket;
import com.nukkitx.protocol.bedrock.packet.TextPacket;
import org.geysermc.connector.network.translators.chat.MessageTranslator;

@Translator(packet = TextPacket.class)
public class BedrockTextTranslator extends PacketTranslator<TextPacket> {

    @Override
    // BUG: CWE-287 Improper Authentication
    // public void translate(TextPacket packet, GeyserSession session) {
    // FIXED:
<fim-middle>    public void translate(GeyserSession session, TextPacket packet) {
        String message = packet.getMessage();

        if (MessageTranslator.isTooLong(message, session)) {
            return;
   <fix-suffix>     }

        ClientChatPacket chatPacket = new ClientChatPacket(message);
        session.sendDownstreamPacket(chatPacket);
    }
}
<|endoftext|>


<fim-prefix>port io.micronaut.http.hateoas.JsonError;
import io.micronaut.http.hateoas.VndError;

import java.util.Optional;

/**
 * Strategy interface for decoding the error from a server respponse.
 *
 * @author graemerocher
 * @since 1.0
 */
@Internal
public interface HttpClientErrorDecoder {

    /**
     * The default implementation.
     */
    HttpClientErrorDecoder DEFAULT = new HttpClientErrorDecoder() { };

    /**
     * Default message decoder.
     *
     * @param error The error object
     * @return The message
     */
    default Optional<String> getMessage(Object error) {
        if (error == null) {
            return Optional.empty();
        }
        if (error instanceof JsonError) {
            return Optional.ofNullable(((JsonError) error).getMessage());
        } else {
            if (error instanceof Described) {
                return Optional.ofNullable(((Described) error).getDescription());
            } else {
                return Optional.of(error.toString());
            }
        }
    }

    /**
     * Gets the error type for the given media type.
     *
     * @param mediaType The media type
     * @return The error type
     */
    default Argument<?> getErrorType(MediaType mediaType) {
        if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
            return Argument.of(JsonError.class);
        } else if (mediaType.equals(MediaType.APPLICATION_VND_ERROR_TYPE)) {
            return Argument.of(VndError.class);
        } else {
            // BUG: CWE-400 Uncontrolled Resource Consumption
            // return Argument.of(String.class);
            // FIXED:
<fim-middle>            return Argument.STRING;
        }
    }
}
<fix-suffix><|endoftext|>


<fim-prefix>.commons.services.vfs.manager;

import java.io.File;
import java.io.InputStream;

import org.olat.basesecurity.BaseSecurity;
import org.olat.basesecurity.IdentityImpl;
import org.olat.core.CoreSpringFactory;
import org.olat.core.commons.services.license.LicenseService;
import org.olat.core.commons.services.license.LicenseType;
import org.olat.core.commons.services.license.model.LicenseTypeImpl;
import org.olat.core.commons.services.vfs.VFSMetadata;
import org.olat.core.commons.services.vfs.VFSRevision;
import org.olat.core.commons.services.vfs.model.VFSMetadataImpl;
import org.olat.core.id.Identity;
import org.olat.core.util.StringHelper;
import org.olat.core.util.vfs.VFSLeaf;
import org.olat.core.util.vfs.version.RevisionFileImpl;
import org.olat.core.util.vfs.version.VersionsFileImpl;
import org.olat.core.util.xml.XStreamHelper;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.security.ExplicitTypePermission;

/**
 *
 * Initial date: 13 mars 2019<br>
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 *
 */
public class VFSXStream {

	private static XStream mystream;
	static {
		mystream = XStreamHelper.createXStreamInstance();
		Class<?>[] types = new Class[] {
				VersionsFileImpl.class, RevisionFileImpl.class, VFSRevision.class,
				VFSMetadata.class, VFSMetadataImpl.class, Identity.class, IdentityImpl.class,
				LicenseType.class, LicenseTypeImpl.class
			};
		// BUG: CWE-91 XML Injection (aka Blind XPath Injection)
		// XStream.setupDefaultSecurity(mystream);
		// FIXED:
	<fim-middle>	mystream.addPermission(new ExplicitTypePermission(types));

		mystream.alias("versions", VersionsFileImpl.class);
		mystream.alias("revision", RevisionFileImpl.class);
		mystream.omitField(VersionsF<fix-suffix>ileImpl.class, "currentVersion");
		mystream.omitField(VersionsFileImpl.class, "versionFile");
		mystream.omitField(RevisionFileImpl.class, "current");
		mystream.omitField(RevisionFileImpl.class, "container");
		mystream.omitField(RevisionFileImpl.class, "file");
		mystream.omitField(VFSMetadataImpl.class, "originFile");
		mystream.omitField(VFSMetadataImpl.class, "metaFile");
		mystream.omitField(VFSMetadataImpl.class, "lockedByIdentKey");
		mystream.aliasAttribute(VFSMetadataImpl.class, "cannotGenerateThumbnails", "cannotGenerateThumbnail");
		mystream.aliasAttribute(VFSMetadataImpl.class, "author", "authorIdentKey");
		mystream.aliasAttribute(VFSMetadataImpl.class, "licenseType", "licenseTypeKey");
		mystream.alias("metadata", VFSMetadataImpl.class);
		mystream.omitField(VFSMetadataImpl.class, "thumbnail");
		mystream.omitField(VFSMetadataImpl.class, "thumbnails");

		mystream.registerLocalConverter(VFSMetadataImpl.class, "licenseType", new LicenseTypeConverter());
		mystream.regis<|endoftext|>


<fim-prefix> final int UC_CPU_S390X_Z890_2 = 9;
   public static final int UC_CPU_S390X_Z990_5 = 10;
   public static final int UC_CPU_S390X_Z890_3 = 11;
   public static final int UC_CPU_S390X_Z9EC = 12;
   public static final int UC_CPU_S390X_Z9EC_2 = 13;
   public static final int UC_CPU_S390X_Z9BC = 14;
   public static final int UC_CPU_S390X_Z9EC_3 = 15;
   public static final int UC_CPU_S390X_Z9BC_2 = 16;
   public static final int UC_CPU_S390X_Z10EC = 17;
   public static final int UC_CPU_S390X_Z10EC_2 = 18;
   public static final int UC_CPU_S390X_Z10BC = 19;
   public static final int UC_CPU_S390X_Z10EC_3 = 20;
   public static final int UC_CPU_S390X_Z10BC_2 = 21;
   public static final int UC_CPU_S390X_Z196 = 22;
   public static final int UC_CPU_S390X_Z196_2 = 23;
   public static final int UC_CPU_S390X_Z114 = 24;
   public static final int UC_CPU_S390X_ZEC12 = 25;
   public static final int UC_CPU_S390X_ZEC12_2 = 26;
   public static final int UC_CPU_S390X_ZBC12 = 27;
   public static final int UC_CPU_S390X_Z13 = 28;
   public static final int UC_CPU_S390X_Z13_2 = 29;
   public static final int UC_CPU_S390X_Z13S = 30;
   public static final int UC_CPU_S390X_Z14 = 31;
   public static final int UC_CPU_S390X_Z14_2 = 32;
   public static final int UC_CPU_S390X_Z14ZR1 = 33;
   public static final int UC_CPU_S390X_GEN15A = 34;
   public static final int UC_CPU_S390X_GEN15B = 35;
   public static final int UC_CPU_S390X_QEMU = 36;
   public static final int UC_CPU_S390X_MAX = 37;
   // BUG: CWE-665 Improper Initialization
   //
   // FIXED:
<fim-middle>   public static final int UC_CPU_S390X_ENDING = 38;

// S390X registers

   public static final int UC_S390X_REG_INVALID = 0;

// General purpose registers
   public static final int UC_S390X_REG_R0 =<fix-suffix> 1;
   public static final int UC_S390X_REG_R1 = 2;
   public static final int UC_S390X_REG_R2 = 3;
   public static final int UC_S390X_REG_R3 = 4;
   public static final int UC_S390X_REG_R4 = 5;
   public static final int UC_S390X_REG_R5 = 6;
   public static final int UC_S390X_REG_R6 = 7;
   public static final int UC_S390X_REG_R7 = 8;
   public static final int UC_S390X_REG_R8 = 9;
   public static final int UC_S390X_REG_R9 = 10;
   public static final int UC_S390X_REG_R10 = 11;
   public static final int UC_S390X_REG_R11 = 12;
   public static final int UC_S390X_REG_R12 = 13;
   public static final int UC_S390X_REG_R13 = 14;
   public static final int UC_S390X_REG_R14 = 15;
   public static final int UC_S390X_REG_R15 = 16;

// Floating point registers
   public static final int UC_S390X_REG_F0 = 17;
   public static final int UC_S390X_REG_F1 = 18;
   public static final int UC_S390X_REG_F2 = 19;
   public static final int UC_S390X_REG_F3 = 20;
   public static final int UC_S390X_RE<|endoftext|>