code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// OpenCppCoverage is an open source code coverage for C++. // Copyright (C) 2014 OpenCppCoverage // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell.Interop; using System; namespace OpenCppCoverage.VSPackage { class OutputWindowWriter { //--------------------------------------------------------------------- public OutputWindowWriter(DTE2 dte, IVsOutputWindow outputWindow) { // These lines show the output windows Window output = dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput); output.Activate(); if (Microsoft.VisualStudio.ErrorHandler.Failed(outputWindow.GetPane(OpenCppCoverageOutputPaneGuid, out outputWindowPane_))) { if (Microsoft.VisualStudio.ErrorHandler.Failed(outputWindow.CreatePane(OpenCppCoverageOutputPaneGuid, "OpenCppCoverage", 1, 1))) throw new Exception("Cannot create new pane."); if (Microsoft.VisualStudio.ErrorHandler.Failed(outputWindow.GetPane(OpenCppCoverageOutputPaneGuid, out outputWindowPane_))) throw new Exception("Cannot get the pane."); } outputWindowPane_.Clear(); ActivatePane(); } //--------------------------------------------------------------------- public void ActivatePane() { outputWindowPane_.Activate(); } //--------------------------------------------------------------------- public bool WriteLine(string message) { return Microsoft.VisualStudio.ErrorHandler.Succeeded(outputWindowPane_.OutputString(message + "\n")); } readonly IVsOutputWindowPane outputWindowPane_; public readonly static Guid OpenCppCoverageOutputPaneGuid = new Guid("CB47C727-5E45-467B-A4CD-4A025986A8A0"); } }
OpenCppCoverage/OpenCppCoveragePlugin
VSPackage/OutputWindowWriter.cs
C#
gpl-3.0
2,517
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: git author: - "Ansible Core Team" - "Michael DeHaan" version_added: "0.0.1" short_description: Deploy software (or files) from git checkouts description: - Manage I(git) checkouts of repositories to deploy files or software. options: repo: description: - git, SSH, or HTTP(S) protocol address of the git repository. type: str required: true aliases: [ name ] dest: description: - The path of where the repository should be checked out. This is equivalent to C(git clone [repo_url] [directory]). The repository named in I(repo) is not appended to this path and the destination directory must be empty. This parameter is required, unless I(clone) is set to C(no). type: path required: true version: description: - What version of the repository to check out. This can be the literal string C(HEAD), a branch name, a tag name. It can also be a I(SHA-1) hash, in which case I(refspec) needs to be specified if the given revision is not already available. type: str default: "HEAD" accept_hostkey: description: - If C(yes), ensure that "-o StrictHostKeyChecking=no" is present as an ssh option. type: bool default: 'no' version_added: "1.5" accept_newhostkey: description: - As of OpenSSH 7.5, "-o StrictHostKeyChecking=accept-new" can be used which is safer and will only accepts host keys which are not present or are the same. if C(yes), ensure that "-o StrictHostKeyChecking=accept-new" is present as an ssh option. type: bool default: 'no' version_added: "2.12" ssh_opts: description: - Creates a wrapper script and exports the path as GIT_SSH which git then automatically uses to override ssh arguments. An example value could be "-o StrictHostKeyChecking=no" (although this particular option is better set by I(accept_hostkey)). type: str version_added: "1.5" key_file: description: - Specify an optional private key file path, on the target host, to use for the checkout. type: path version_added: "1.5" reference: description: - Reference repository (see "git clone --reference ..."). version_added: "1.4" remote: description: - Name of the remote. type: str default: "origin" refspec: description: - Add an additional refspec to be fetched. If version is set to a I(SHA-1) not reachable from any branch or tag, this option may be necessary to specify the ref containing the I(SHA-1). Uses the same syntax as the C(git fetch) command. An example value could be "refs/meta/config". type: str version_added: "1.9" force: description: - If C(yes), any modified files in the working repository will be discarded. Prior to 0.7, this was always 'yes' and could not be disabled. Prior to 1.9, the default was `yes`. type: bool default: 'no' version_added: "0.7" depth: description: - Create a shallow clone with a history truncated to the specified number or revisions. The minimum possible value is C(1), otherwise ignored. Needs I(git>=1.9.1) to work correctly. type: int version_added: "1.2" clone: description: - If C(no), do not clone the repository even if it does not exist locally. type: bool default: 'yes' version_added: "1.9" update: description: - If C(no), do not retrieve new revisions from the origin repository. - Operations like archive will work on the existing (old) repository and might not respond to changes to the options version or remote. type: bool default: 'yes' version_added: "1.2" executable: description: - Path to git executable to use. If not supplied, the normal mechanism for resolving binary paths will be used. type: path version_added: "1.4" bare: description: - If C(yes), repository will be created as a bare repo, otherwise it will be a standard repo with a workspace. type: bool default: 'no' version_added: "1.4" umask: description: - The umask to set before doing any checkouts, or any other repository maintenance. type: raw version_added: "2.2" recursive: description: - If C(no), repository will be cloned without the --recursive option, skipping sub-modules. type: bool default: 'yes' version_added: "1.6" single_branch: description: - Clone only the history leading to the tip of the specified I(branch). type: bool default: 'no' version_added: '2.11' track_submodules: description: - If C(yes), submodules will track the latest commit on their master branch (or other branch specified in .gitmodules). If C(no), submodules will be kept at the revision specified by the main project. This is equivalent to specifying the --remote flag to git submodule update. type: bool default: 'no' version_added: "1.8" verify_commit: description: - If C(yes), when cloning or checking out a I(version) verify the signature of a GPG signed commit. This requires git version>=2.1.0 to be installed. The commit MUST be signed and the public key MUST be present in the GPG keyring. type: bool default: 'no' version_added: "2.0" archive: description: - Specify archive file path with extension. If specified, creates an archive file of the specified format containing the tree structure for the source tree. Allowed archive formats ["zip", "tar.gz", "tar", "tgz"]. - This will clone and perform git archive from local directory as not all git servers support git archive. type: path version_added: "2.4" archive_prefix: description: - Specify a prefix to add to each file path in archive. Requires I(archive) to be specified. version_added: "2.10" type: str separate_git_dir: description: - The path to place the cloned repository. If specified, Git repository can be separated from working tree. type: path version_added: "2.7" gpg_whitelist: description: - A list of trusted GPG fingerprints to compare to the fingerprint of the GPG-signed commit. - Only used when I(verify_commit=yes). - Use of this feature requires Git 2.6+ due to its reliance on git's C(--raw) flag to C(verify-commit) and C(verify-tag). type: list elements: str default: [] version_added: "2.9" requirements: - git>=1.7.1 (the command line tool) notes: - "If the task seems to be hanging, first verify remote host is in C(known_hosts). SSH will prompt user to authorize the first contact with a remote host. To avoid this prompt, one solution is to use the option accept_hostkey. Another solution is to add the remote host public key in C(/etc/ssh/ssh_known_hosts) before calling the git module, with the following command: ssh-keyscan -H remote_host.com >> /etc/ssh/ssh_known_hosts." - Supports C(check_mode). ''' EXAMPLES = ''' - name: Git checkout ansible.builtin.git: repo: 'https://foosball.example.org/path/to/repo.git' dest: /srv/checkout version: release-0.22 - name: Read-write git checkout from github ansible.builtin.git: repo: git@github.com:mylogin/hello.git dest: /home/mylogin/hello - name: Just ensuring the repo checkout exists ansible.builtin.git: repo: 'https://foosball.example.org/path/to/repo.git' dest: /srv/checkout update: no - name: Just get information about the repository whether or not it has already been cloned locally ansible.builtin.git: repo: 'https://foosball.example.org/path/to/repo.git' dest: /srv/checkout clone: no update: no - name: Checkout a github repo and use refspec to fetch all pull requests ansible.builtin.git: repo: https://github.com/ansible/ansible-examples.git dest: /src/ansible-examples refspec: '+refs/pull/*:refs/heads/*' - name: Create git archive from repo ansible.builtin.git: repo: https://github.com/ansible/ansible-examples.git dest: /src/ansible-examples archive: /tmp/ansible-examples.zip - name: Clone a repo with separate git directory ansible.builtin.git: repo: https://github.com/ansible/ansible-examples.git dest: /src/ansible-examples separate_git_dir: /src/ansible-examples.git - name: Example clone of a single branch ansible.builtin.git: single_branch: yes branch: master - name: Avoid hanging when http(s) password is missing ansible.builtin.git: repo: https://github.com/ansible/could-be-a-private-repo dest: /src/from-private-repo environment: GIT_TERMINAL_PROMPT: 0 # reports "terminal prompts disabled" on missing password # or GIT_ASKPASS: /bin/true # for git before version 2.3.0, reports "Authentication failed" on missing password ''' RETURN = ''' after: description: Last commit revision of the repository retrieved during the update. returned: success type: str sample: 4c020102a9cd6fe908c9a4a326a38f972f63a903 before: description: Commit revision before the repository was updated, "null" for new repository. returned: success type: str sample: 67c04ebe40a003bda0efb34eacfb93b0cafdf628 remote_url_changed: description: Contains True or False whether or not the remote URL was changed. returned: success type: bool sample: True warnings: description: List of warnings if requested features were not available due to a too old git version. returned: error type: str sample: git version is too old to fully support the depth argument. Falling back to full checkouts. git_dir_now: description: Contains the new path of .git directory if it is changed. returned: success type: str sample: /path/to/new/git/dir git_dir_before: description: Contains the original path of .git directory if it is changed. returned: success type: str sample: /path/to/old/git/dir ''' import filecmp import os import re import shlex import stat import sys import shutil import tempfile from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import b, string_types from ansible.module_utils._text import to_native, to_text from ansible.module_utils.common.process import get_bin_path def relocate_repo(module, result, repo_dir, old_repo_dir, worktree_dir): if os.path.exists(repo_dir): module.fail_json(msg='Separate-git-dir path %s already exists.' % repo_dir) if worktree_dir: dot_git_file_path = os.path.join(worktree_dir, '.git') try: shutil.move(old_repo_dir, repo_dir) with open(dot_git_file_path, 'w') as dot_git_file: dot_git_file.write('gitdir: %s' % repo_dir) result['git_dir_before'] = old_repo_dir result['git_dir_now'] = repo_dir except (IOError, OSError) as err: # if we already moved the .git dir, roll it back if os.path.exists(repo_dir): shutil.move(repo_dir, old_repo_dir) module.fail_json(msg=u'Unable to move git dir. %s' % to_text(err)) def head_splitter(headfile, remote, module=None, fail_on_error=False): '''Extract the head reference''' # https://github.com/ansible/ansible-modules-core/pull/907 res = None if os.path.exists(headfile): rawdata = None try: f = open(headfile, 'r') rawdata = f.readline() f.close() except Exception: if fail_on_error and module: module.fail_json(msg="Unable to read %s" % headfile) if rawdata: try: rawdata = rawdata.replace('refs/remotes/%s' % remote, '', 1) refparts = rawdata.split(' ') newref = refparts[-1] nrefparts = newref.split('/', 2) res = nrefparts[-1].rstrip('\n') except Exception: if fail_on_error and module: module.fail_json(msg="Unable to split head from '%s'" % rawdata) return res def unfrackgitpath(path): if path is None: return None # copied from ansible.utils.path return os.path.normpath(os.path.realpath(os.path.expanduser(os.path.expandvars(path)))) def get_submodule_update_params(module, git_path, cwd): # or: git submodule [--quiet] update [--init] [-N|--no-fetch] # [-f|--force] [--rebase] [--reference <repository>] [--merge] # [--recursive] [--] [<path>...] params = [] # run a bad submodule command to get valid params cmd = "%s submodule update --help" % (git_path) rc, stdout, stderr = module.run_command(cmd, cwd=cwd) lines = stderr.split('\n') update_line = None for line in lines: if 'git submodule [--quiet] update ' in line: update_line = line if update_line: update_line = update_line.replace('[', '') update_line = update_line.replace(']', '') update_line = update_line.replace('|', ' ') parts = shlex.split(update_line) for part in parts: if part.startswith('--'): part = part.replace('--', '') params.append(part) return params def write_ssh_wrapper(module_tmpdir): try: # make sure we have full permission to the module_dir, which # may not be the case if we're sudo'ing to a non-root user if os.access(module_tmpdir, os.W_OK | os.R_OK | os.X_OK): fd, wrapper_path = tempfile.mkstemp(prefix=module_tmpdir + '/') else: raise OSError except (IOError, OSError): fd, wrapper_path = tempfile.mkstemp() fh = os.fdopen(fd, 'w+b') template = b("""#!/bin/sh if [ -z "$GIT_SSH_OPTS" ]; then BASEOPTS="" else BASEOPTS=$GIT_SSH_OPTS fi # Let ssh fail rather than prompt BASEOPTS="$BASEOPTS -o BatchMode=yes" if [ -z "$GIT_KEY" ]; then ssh $BASEOPTS "$@" else ssh -i "$GIT_KEY" -o IdentitiesOnly=yes $BASEOPTS "$@" fi """) fh.write(template) fh.close() st = os.stat(wrapper_path) os.chmod(wrapper_path, st.st_mode | stat.S_IEXEC) return wrapper_path def set_git_ssh(ssh_wrapper, key_file, ssh_opts): if os.environ.get("GIT_SSH"): del os.environ["GIT_SSH"] os.environ["GIT_SSH"] = ssh_wrapper if os.environ.get("GIT_KEY"): del os.environ["GIT_KEY"] if key_file: os.environ["GIT_KEY"] = key_file if os.environ.get("GIT_SSH_OPTS"): del os.environ["GIT_SSH_OPTS"] if ssh_opts: os.environ["GIT_SSH_OPTS"] = ssh_opts def get_version(module, git_path, dest, ref="HEAD"): ''' samples the version of the git repo ''' cmd = "%s rev-parse %s" % (git_path, ref) rc, stdout, stderr = module.run_command(cmd, cwd=dest) sha = to_native(stdout).rstrip('\n') return sha def ssh_supports_acceptnewhostkey(module): try: ssh_path = get_bin_path('ssh') except ValueError as err: module.fail_json( msg='Remote host is missing ssh command, so you cannot ' 'use acceptnewhostkey option.', details=to_text(err)) supports_acceptnewhostkey = True cmd = [ssh_path, '-o', 'StrictHostKeyChecking=accept-new', '-V'] rc, stdout, stderr = module.run_command(cmd) if rc != 0: supports_acceptnewhostkey = False return supports_acceptnewhostkey def get_submodule_versions(git_path, module, dest, version='HEAD'): cmd = [git_path, 'submodule', 'foreach', git_path, 'rev-parse', version] (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json( msg='Unable to determine hashes of submodules', stdout=out, stderr=err, rc=rc) submodules = {} subm_name = None for line in out.splitlines(): if line.startswith("Entering '"): subm_name = line[10:-1] elif len(line.strip()) == 40: if subm_name is None: module.fail_json() submodules[subm_name] = line.strip() subm_name = None else: module.fail_json(msg='Unable to parse submodule hash line: %s' % line.strip()) if subm_name is not None: module.fail_json(msg='Unable to find hash for submodule: %s' % subm_name) return submodules def clone(git_path, module, repo, dest, remote, depth, version, bare, reference, refspec, git_version_used, verify_commit, separate_git_dir, result, gpg_whitelist, single_branch): ''' makes a new git repo if it does not already exist ''' dest_dirname = os.path.dirname(dest) try: os.makedirs(dest_dirname) except Exception: pass cmd = [git_path, 'clone'] if bare: cmd.append('--bare') else: cmd.extend(['--origin', remote]) is_branch_or_tag = is_remote_branch(git_path, module, dest, repo, version) or is_remote_tag(git_path, module, dest, repo, version) if depth: if version == 'HEAD' or refspec: cmd.extend(['--depth', str(depth)]) elif is_branch_or_tag: cmd.extend(['--depth', str(depth)]) cmd.extend(['--branch', version]) else: # only use depth if the remote object is branch or tag (i.e. fetchable) module.warn("Ignoring depth argument. " "Shallow clones are only available for " "HEAD, branches, tags or in combination with refspec.") if reference: cmd.extend(['--reference', str(reference)]) if single_branch: if git_version_used is None: module.fail_json(msg='Cannot find git executable at %s' % git_path) if git_version_used < LooseVersion('1.7.10'): module.warn("git version '%s' is too old to use 'single-branch'. Ignoring." % git_version_used) else: cmd.append("--single-branch") if is_branch_or_tag: cmd.extend(['--branch', version]) needs_separate_git_dir_fallback = False if separate_git_dir: if git_version_used is None: module.fail_json(msg='Cannot find git executable at %s' % git_path) if git_version_used < LooseVersion('1.7.5'): # git before 1.7.5 doesn't have separate-git-dir argument, do fallback needs_separate_git_dir_fallback = True else: cmd.append('--separate-git-dir=%s' % separate_git_dir) cmd.extend([repo, dest]) module.run_command(cmd, check_rc=True, cwd=dest_dirname) if needs_separate_git_dir_fallback: relocate_repo(module, result, separate_git_dir, os.path.join(dest, ".git"), dest) if bare and remote != 'origin': module.run_command([git_path, 'remote', 'add', remote, repo], check_rc=True, cwd=dest) if refspec: cmd = [git_path, 'fetch'] if depth: cmd.extend(['--depth', str(depth)]) cmd.extend([remote, refspec]) module.run_command(cmd, check_rc=True, cwd=dest) if verify_commit: verify_commit_sign(git_path, module, dest, version, gpg_whitelist) def has_local_mods(module, git_path, dest, bare): if bare: return False cmd = "%s status --porcelain" % (git_path) rc, stdout, stderr = module.run_command(cmd, cwd=dest) lines = stdout.splitlines() lines = list(filter(lambda c: not re.search('^\\?\\?.*$', c), lines)) return len(lines) > 0 def reset(git_path, module, dest): ''' Resets the index and working tree to HEAD. Discards any changes to tracked files in working tree since that commit. ''' cmd = "%s reset --hard HEAD" % (git_path,) return module.run_command(cmd, check_rc=True, cwd=dest) def get_diff(module, git_path, dest, repo, remote, depth, bare, before, after): ''' Return the difference between 2 versions ''' if before is None: return {'prepared': '>> Newly checked out %s' % after} elif before != after: # Ensure we have the object we are referring to during git diff ! git_version_used = git_version(git_path, module) fetch(git_path, module, repo, dest, after, remote, depth, bare, '', git_version_used) cmd = '%s diff %s %s' % (git_path, before, after) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc == 0 and out: return {'prepared': out} elif rc == 0: return {'prepared': '>> No visual differences between %s and %s' % (before, after)} elif err: return {'prepared': '>> Failed to get proper diff between %s and %s:\n>> %s' % (before, after, err)} else: return {'prepared': '>> Failed to get proper diff between %s and %s' % (before, after)} return {} def get_remote_head(git_path, module, dest, version, remote, bare): cloning = False cwd = None tag = False if remote == module.params['repo']: cloning = True elif remote == 'file://' + os.path.expanduser(module.params['repo']): cloning = True else: cwd = dest if version == 'HEAD': if cloning: # cloning the repo, just get the remote's HEAD version cmd = '%s ls-remote %s -h HEAD' % (git_path, remote) else: head_branch = get_head_branch(git_path, module, dest, remote, bare) cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, head_branch) elif is_remote_branch(git_path, module, dest, remote, version): cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, version) elif is_remote_tag(git_path, module, dest, remote, version): tag = True cmd = '%s ls-remote %s -t refs/tags/%s*' % (git_path, remote, version) else: # appears to be a sha1. return as-is since it appears # cannot check for a specific sha1 on remote return version (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=cwd) if len(out) < 1: module.fail_json(msg="Could not determine remote revision for %s" % version, stdout=out, stderr=err, rc=rc) out = to_native(out) if tag: # Find the dereferenced tag if this is an annotated tag. for tag in out.split('\n'): if tag.endswith(version + '^{}'): out = tag break elif tag.endswith(version): out = tag rev = out.split()[0] return rev def is_remote_tag(git_path, module, dest, remote, version): cmd = '%s ls-remote %s -t refs/tags/%s' % (git_path, remote, version) (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if to_native(version, errors='surrogate_or_strict') in out: return True else: return False def get_branches(git_path, module, dest): branches = [] cmd = '%s branch --no-color -a' % (git_path,) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Could not determine branch data - received %s" % out, stdout=out, stderr=err) for line in out.split('\n'): if line.strip(): branches.append(line.strip()) return branches def get_annotated_tags(git_path, module, dest): tags = [] cmd = [git_path, 'for-each-ref', 'refs/tags/', '--format', '%(objecttype):%(refname:short)'] (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Could not determine tag data - received %s" % out, stdout=out, stderr=err) for line in to_native(out).split('\n'): if line.strip(): tagtype, tagname = line.strip().split(':') if tagtype == 'tag': tags.append(tagname) return tags def is_remote_branch(git_path, module, dest, remote, version): cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, version) (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if to_native(version, errors='surrogate_or_strict') in out: return True else: return False def is_local_branch(git_path, module, dest, branch): branches = get_branches(git_path, module, dest) lbranch = '%s' % branch if lbranch in branches: return True elif '* %s' % branch in branches: return True else: return False def is_not_a_branch(git_path, module, dest): branches = get_branches(git_path, module, dest) for branch in branches: if branch.startswith('* ') and ('no branch' in branch or 'detached from' in branch or 'detached at' in branch): return True return False def get_repo_path(dest, bare): if bare: repo_path = dest else: repo_path = os.path.join(dest, '.git') # Check if the .git is a file. If it is a file, it means that the repository is in external directory respective to the working copy (e.g. we are in a # submodule structure). if os.path.isfile(repo_path): with open(repo_path, 'r') as gitfile: data = gitfile.read() ref_prefix, gitdir = data.rstrip().split('gitdir: ', 1) if ref_prefix: raise ValueError('.git file has invalid git dir reference format') # There is a possibility the .git file to have an absolute path. if os.path.isabs(gitdir): repo_path = gitdir else: repo_path = os.path.join(repo_path.split('.git')[0], gitdir) if not os.path.isdir(repo_path): raise ValueError('%s is not a directory' % repo_path) return repo_path def get_head_branch(git_path, module, dest, remote, bare=False): ''' Determine what branch HEAD is associated with. This is partly taken from lib/ansible/utils/__init__.py. It finds the correct path to .git/HEAD and reads from that file the branch that HEAD is associated with. In the case of a detached HEAD, this will look up the branch in .git/refs/remotes/<remote>/HEAD. ''' try: repo_path = get_repo_path(dest, bare) except (IOError, ValueError) as err: # No repo path found """``.git`` file does not have a valid format for detached Git dir.""" module.fail_json( msg='Current repo does not have a valid reference to a ' 'separate Git dir or it refers to the invalid path', details=to_text(err), ) # Read .git/HEAD for the name of the branch. # If we're in a detached HEAD state, look up the branch associated with # the remote HEAD in .git/refs/remotes/<remote>/HEAD headfile = os.path.join(repo_path, "HEAD") if is_not_a_branch(git_path, module, dest): headfile = os.path.join(repo_path, 'refs', 'remotes', remote, 'HEAD') branch = head_splitter(headfile, remote, module=module, fail_on_error=True) return branch def get_remote_url(git_path, module, dest, remote): '''Return URL of remote source for repo.''' command = [git_path, 'ls-remote', '--get-url', remote] (rc, out, err) = module.run_command(command, cwd=dest) if rc != 0: # There was an issue getting remote URL, most likely # command is not available in this version of Git. return None return to_native(out).rstrip('\n') def set_remote_url(git_path, module, repo, dest, remote): ''' updates repo from remote sources ''' # Return if remote URL isn't changing. remote_url = get_remote_url(git_path, module, dest, remote) if remote_url == repo or unfrackgitpath(remote_url) == unfrackgitpath(repo): return False command = [git_path, 'remote', 'set-url', remote, repo] (rc, out, err) = module.run_command(command, cwd=dest) if rc != 0: label = "set a new url %s for %s" % (repo, remote) module.fail_json(msg="Failed to %s: %s %s" % (label, out, err)) # Return False if remote_url is None to maintain previous behavior # for Git versions prior to 1.7.5 that lack required functionality. return remote_url is not None def fetch(git_path, module, repo, dest, version, remote, depth, bare, refspec, git_version_used, force=False): ''' updates repo from remote sources ''' set_remote_url(git_path, module, repo, dest, remote) commands = [] fetch_str = 'download remote objects and refs' fetch_cmd = [git_path, 'fetch'] refspecs = [] if depth: # try to find the minimal set of refs we need to fetch to get a # successful checkout currenthead = get_head_branch(git_path, module, dest, remote) if refspec: refspecs.append(refspec) elif version == 'HEAD': refspecs.append(currenthead) elif is_remote_branch(git_path, module, dest, repo, version): if currenthead != version: # this workaround is only needed for older git versions # 1.8.3 is broken, 1.9.x works # ensure that remote branch is available as both local and remote ref refspecs.append('+refs/heads/%s:refs/heads/%s' % (version, version)) refspecs.append('+refs/heads/%s:refs/remotes/%s/%s' % (version, remote, version)) elif is_remote_tag(git_path, module, dest, repo, version): refspecs.append('+refs/tags/' + version + ':refs/tags/' + version) if refspecs: # if refspecs is empty, i.e. version is neither heads nor tags # assume it is a version hash # fall back to a full clone, otherwise we might not be able to checkout # version fetch_cmd.extend(['--depth', str(depth)]) if not depth or not refspecs: # don't try to be minimalistic but do a full clone # also do this if depth is given, but version is something that can't be fetched directly if bare: refspecs = ['+refs/heads/*:refs/heads/*', '+refs/tags/*:refs/tags/*'] else: # ensure all tags are fetched if git_version_used >= LooseVersion('1.9'): fetch_cmd.append('--tags') else: # old git versions have a bug in --tags that prevents updating existing tags commands.append((fetch_str, fetch_cmd + [remote])) refspecs = ['+refs/tags/*:refs/tags/*'] if refspec: refspecs.append(refspec) if force: fetch_cmd.append('--force') fetch_cmd.extend([remote]) commands.append((fetch_str, fetch_cmd + refspecs)) for (label, command) in commands: (rc, out, err) = module.run_command(command, cwd=dest) if rc != 0: module.fail_json(msg="Failed to %s: %s %s" % (label, out, err), cmd=command) def submodules_fetch(git_path, module, remote, track_submodules, dest): changed = False if not os.path.exists(os.path.join(dest, '.gitmodules')): # no submodules return changed gitmodules_file = open(os.path.join(dest, '.gitmodules'), 'r') for line in gitmodules_file: # Check for new submodules if not changed and line.strip().startswith('path'): path = line.split('=', 1)[1].strip() # Check that dest/path/.git exists if not os.path.exists(os.path.join(dest, path, '.git')): changed = True # Check for updates to existing modules if not changed: # Fetch updates begin = get_submodule_versions(git_path, module, dest) cmd = [git_path, 'submodule', 'foreach', git_path, 'fetch'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if rc != 0: module.fail_json(msg="Failed to fetch submodules: %s" % out + err) if track_submodules: # Compare against submodule HEAD # FIXME: determine this from .gitmodules version = 'master' after = get_submodule_versions(git_path, module, dest, '%s/%s' % (remote, version)) if begin != after: changed = True else: # Compare against the superproject's expectation cmd = [git_path, 'submodule', 'status'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if rc != 0: module.fail_json(msg='Failed to retrieve submodule status: %s' % out + err) for line in out.splitlines(): if line[0] != ' ': changed = True break return changed def submodule_update(git_path, module, dest, track_submodules, force=False): ''' init and update any submodules ''' # get the valid submodule params params = get_submodule_update_params(module, git_path, dest) # skip submodule commands if .gitmodules is not present if not os.path.exists(os.path.join(dest, '.gitmodules')): return (0, '', '') cmd = [git_path, 'submodule', 'sync'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if 'remote' in params and track_submodules: cmd = [git_path, 'submodule', 'update', '--init', '--recursive', '--remote'] else: cmd = [git_path, 'submodule', 'update', '--init', '--recursive'] if force: cmd.append('--force') (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Failed to init/update submodules: %s" % out + err) return (rc, out, err) def set_remote_branch(git_path, module, dest, remote, version, depth): """set refs for the remote branch version This assumes the branch does not yet exist locally and is therefore also not checked out. Can't use git remote set-branches, as it is not available in git 1.7.1 (centos6) """ branchref = "+refs/heads/%s:refs/heads/%s" % (version, version) branchref += ' +refs/heads/%s:refs/remotes/%s/%s' % (version, remote, version) cmd = "%s fetch --depth=%s %s %s" % (git_path, depth, remote, branchref) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Failed to fetch branch from remote: %s" % version, stdout=out, stderr=err, rc=rc) def switch_version(git_path, module, dest, remote, version, verify_commit, depth, gpg_whitelist): cmd = '' if version == 'HEAD': branch = get_head_branch(git_path, module, dest, remote) (rc, out, err) = module.run_command("%s checkout --force %s" % (git_path, branch), cwd=dest) if rc != 0: module.fail_json(msg="Failed to checkout branch %s" % branch, stdout=out, stderr=err, rc=rc) cmd = "%s reset --hard %s/%s --" % (git_path, remote, branch) else: # FIXME check for local_branch first, should have been fetched already if is_remote_branch(git_path, module, dest, remote, version): if depth and not is_local_branch(git_path, module, dest, version): # git clone --depth implies --single-branch, which makes # the checkout fail if the version changes # fetch the remote branch, to be able to check it out next set_remote_branch(git_path, module, dest, remote, version, depth) if not is_local_branch(git_path, module, dest, version): cmd = "%s checkout --track -b %s %s/%s" % (git_path, version, remote, version) else: (rc, out, err) = module.run_command("%s checkout --force %s" % (git_path, version), cwd=dest) if rc != 0: module.fail_json(msg="Failed to checkout branch %s" % version, stdout=out, stderr=err, rc=rc) cmd = "%s reset --hard %s/%s" % (git_path, remote, version) else: cmd = "%s checkout --force %s" % (git_path, version) (rc, out1, err1) = module.run_command(cmd, cwd=dest) if rc != 0: if version != 'HEAD': module.fail_json(msg="Failed to checkout %s" % (version), stdout=out1, stderr=err1, rc=rc, cmd=cmd) else: module.fail_json(msg="Failed to checkout branch %s" % (branch), stdout=out1, stderr=err1, rc=rc, cmd=cmd) if verify_commit: verify_commit_sign(git_path, module, dest, version, gpg_whitelist) return (rc, out1, err1) def verify_commit_sign(git_path, module, dest, version, gpg_whitelist): if version in get_annotated_tags(git_path, module, dest): git_sub = "verify-tag" else: git_sub = "verify-commit" cmd = "%s %s %s" % (git_path, git_sub, version) if gpg_whitelist: cmd += " --raw" (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg='Failed to verify GPG signature of commit/tag "%s"' % version, stdout=out, stderr=err, rc=rc) if gpg_whitelist: fingerprint = get_gpg_fingerprint(err) if fingerprint not in gpg_whitelist: module.fail_json(msg='The gpg_whitelist does not include the public key "%s" for this commit' % fingerprint, stdout=out, stderr=err, rc=rc) return (rc, out, err) def get_gpg_fingerprint(output): """Return a fingerprint of the primary key. Ref: https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=doc/DETAILS;hb=HEAD#l482 """ for line in output.splitlines(): data = line.split() if data[1] != 'VALIDSIG': continue # if signed with a subkey, this contains the primary key fingerprint data_id = 11 if len(data) == 11 else 2 return data[data_id] def git_version(git_path, module): """return the installed version of git""" cmd = "%s --version" % git_path (rc, out, err) = module.run_command(cmd) if rc != 0: # one could fail_json here, but the version info is not that important, # so let's try to fail only on actual git commands return None rematch = re.search('git version (.*)$', to_native(out)) if not rematch: return None return LooseVersion(rematch.groups()[0]) def git_archive(git_path, module, dest, archive, archive_fmt, archive_prefix, version): """ Create git archive in given source directory """ cmd = [git_path, 'archive', '--format', archive_fmt, '--output', archive, version] if archive_prefix is not None: cmd.insert(-1, '--prefix') cmd.insert(-1, archive_prefix) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Failed to perform archive operation", details="Git archive command failed to create " "archive %s using %s directory." "Error: %s" % (archive, dest, err)) return rc, out, err def create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result): """ Helper function for creating archive using git_archive """ all_archive_fmt = {'.zip': 'zip', '.gz': 'tar.gz', '.tar': 'tar', '.tgz': 'tgz'} _, archive_ext = os.path.splitext(archive) archive_fmt = all_archive_fmt.get(archive_ext, None) if archive_fmt is None: module.fail_json(msg="Unable to get file extension from " "archive file name : %s" % archive, details="Please specify archive as filename with " "extension. File extension can be one " "of ['tar', 'tar.gz', 'zip', 'tgz']") repo_name = repo.split("/")[-1].replace(".git", "") if os.path.exists(archive): # If git archive file exists, then compare it with new git archive file. # if match, do nothing # if does not match, then replace existing with temp archive file. tempdir = tempfile.mkdtemp() new_archive_dest = os.path.join(tempdir, repo_name) new_archive = new_archive_dest + '.' + archive_fmt git_archive(git_path, module, dest, new_archive, archive_fmt, archive_prefix, version) # filecmp is supposed to be efficient than md5sum checksum if filecmp.cmp(new_archive, archive): result.update(changed=False) # Cleanup before exiting try: shutil.rmtree(tempdir) except OSError: pass else: try: shutil.move(new_archive, archive) shutil.rmtree(tempdir) result.update(changed=True) except OSError as e: module.fail_json(msg="Failed to move %s to %s" % (new_archive, archive), details=u"Error occurred while moving : %s" % to_text(e)) else: # Perform archive from local directory git_archive(git_path, module, dest, archive, archive_fmt, archive_prefix, version) result.update(changed=True) # =========================================== def main(): module = AnsibleModule( argument_spec=dict( dest=dict(type='path'), repo=dict(required=True, aliases=['name']), version=dict(default='HEAD'), remote=dict(default='origin'), refspec=dict(default=None), reference=dict(default=None), force=dict(default='no', type='bool'), depth=dict(default=None, type='int'), clone=dict(default='yes', type='bool'), update=dict(default='yes', type='bool'), verify_commit=dict(default='no', type='bool'), gpg_whitelist=dict(default=[], type='list', elements='str'), accept_hostkey=dict(default='no', type='bool'), accept_newhostkey=dict(default='no', type='bool'), key_file=dict(default=None, type='path', required=False), ssh_opts=dict(default=None, required=False), executable=dict(default=None, type='path'), bare=dict(default='no', type='bool'), recursive=dict(default='yes', type='bool'), single_branch=dict(default=False, type='bool'), track_submodules=dict(default='no', type='bool'), umask=dict(default=None, type='raw'), archive=dict(type='path'), archive_prefix=dict(), separate_git_dir=dict(type='path'), ), mutually_exclusive=[('separate_git_dir', 'bare'), ('accept_hostkey', 'accept_newhostkey')], required_by={'archive_prefix': ['archive']}, supports_check_mode=True ) dest = module.params['dest'] repo = module.params['repo'] version = module.params['version'] remote = module.params['remote'] refspec = module.params['refspec'] force = module.params['force'] depth = module.params['depth'] update = module.params['update'] allow_clone = module.params['clone'] bare = module.params['bare'] verify_commit = module.params['verify_commit'] gpg_whitelist = module.params['gpg_whitelist'] reference = module.params['reference'] single_branch = module.params['single_branch'] git_path = module.params['executable'] or module.get_bin_path('git', True) key_file = module.params['key_file'] ssh_opts = module.params['ssh_opts'] umask = module.params['umask'] archive = module.params['archive'] archive_prefix = module.params['archive_prefix'] separate_git_dir = module.params['separate_git_dir'] result = dict(changed=False, warnings=list()) if module.params['accept_hostkey']: if ssh_opts is not None: if ("-o StrictHostKeyChecking=no" not in ssh_opts) and ("-o StrictHostKeyChecking=accept-new" not in ssh_opts): ssh_opts += " -o StrictHostKeyChecking=no" else: ssh_opts = "-o StrictHostKeyChecking=no" if module.params['accept_newhostkey']: if not ssh_supports_acceptnewhostkey(module): module.warn("Your ssh client does not support accept_newhostkey option, therefore it cannot be used.") else: if ssh_opts is not None: if ("-o StrictHostKeyChecking=no" not in ssh_opts) and ("-o StrictHostKeyChecking=accept-new" not in ssh_opts): ssh_opts += " -o StrictHostKeyChecking=accept-new" else: ssh_opts = "-o StrictHostKeyChecking=accept-new" # evaluate and set the umask before doing anything else if umask is not None: if not isinstance(umask, string_types): module.fail_json(msg="umask must be defined as a quoted octal integer") try: umask = int(umask, 8) except Exception: module.fail_json(msg="umask must be an octal integer", details=str(sys.exc_info()[1])) os.umask(umask) # Certain features such as depth require a file:/// protocol for path based urls # so force a protocol here ... if os.path.expanduser(repo).startswith('/'): repo = 'file://' + os.path.expanduser(repo) # We screenscrape a huge amount of git commands so use C locale anytime we # call run_command() module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C', LC_CTYPE='C') if separate_git_dir: separate_git_dir = os.path.realpath(separate_git_dir) gitconfig = None if not dest and allow_clone: module.fail_json(msg="the destination directory must be specified unless clone=no") elif dest: dest = os.path.abspath(dest) try: repo_path = get_repo_path(dest, bare) if separate_git_dir and os.path.exists(repo_path) and separate_git_dir != repo_path: result['changed'] = True if not module.check_mode: relocate_repo(module, result, separate_git_dir, repo_path, dest) repo_path = separate_git_dir except (IOError, ValueError) as err: # No repo path found """``.git`` file does not have a valid format for detached Git dir.""" module.fail_json( msg='Current repo does not have a valid reference to a ' 'separate Git dir or it refers to the invalid path', details=to_text(err), ) gitconfig = os.path.join(repo_path, 'config') # create a wrapper script and export # GIT_SSH=<path> as an environment variable # for git to use the wrapper script ssh_wrapper = write_ssh_wrapper(module.tmpdir) set_git_ssh(ssh_wrapper, key_file, ssh_opts) module.add_cleanup_file(path=ssh_wrapper) git_version_used = git_version(git_path, module) if depth is not None and git_version_used < LooseVersion('1.9.1'): module.warn("git version is too old to fully support the depth argument. Falling back to full checkouts.") depth = None recursive = module.params['recursive'] track_submodules = module.params['track_submodules'] result.update(before=None) local_mods = False if (dest and not os.path.exists(gitconfig)) or (not dest and not allow_clone): # if there is no git configuration, do a clone operation unless: # * the user requested no clone (they just want info) # * we're doing a check mode test # In those cases we do an ls-remote if module.check_mode or not allow_clone: remote_head = get_remote_head(git_path, module, dest, version, repo, bare) result.update(changed=True, after=remote_head) if module._diff: diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after']) if diff: result['diff'] = diff module.exit_json(**result) # there's no git config, so clone clone(git_path, module, repo, dest, remote, depth, version, bare, reference, refspec, git_version_used, verify_commit, separate_git_dir, result, gpg_whitelist, single_branch) elif not update: # Just return having found a repo already in the dest path # this does no checking that the repo is the actual repo # requested. result['before'] = get_version(module, git_path, dest) result.update(after=result['before']) if archive: # Git archive is not supported by all git servers, so # we will first clone and perform git archive from local directory if module.check_mode: result.update(changed=True) module.exit_json(**result) create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result) module.exit_json(**result) else: # else do a pull local_mods = has_local_mods(module, git_path, dest, bare) result['before'] = get_version(module, git_path, dest) if local_mods: # failure should happen regardless of check mode if not force: module.fail_json(msg="Local modifications exist in repository (force=no).", **result) # if force and in non-check mode, do a reset if not module.check_mode: reset(git_path, module, dest) result.update(changed=True, msg='Local modifications exist.') # exit if already at desired sha version if module.check_mode: remote_url = get_remote_url(git_path, module, dest, remote) remote_url_changed = remote_url and remote_url != repo and unfrackgitpath(remote_url) != unfrackgitpath(repo) else: remote_url_changed = set_remote_url(git_path, module, repo, dest, remote) result.update(remote_url_changed=remote_url_changed) if module.check_mode: remote_head = get_remote_head(git_path, module, dest, version, remote, bare) result.update(changed=(result['before'] != remote_head or remote_url_changed), after=remote_head) # FIXME: This diff should fail since the new remote_head is not fetched yet?! if module._diff: diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after']) if diff: result['diff'] = diff module.exit_json(**result) else: fetch(git_path, module, repo, dest, version, remote, depth, bare, refspec, git_version_used, force=force) result['after'] = get_version(module, git_path, dest) # switch to version specified regardless of whether # we got new revisions from the repository if not bare: switch_version(git_path, module, dest, remote, version, verify_commit, depth, gpg_whitelist) # Deal with submodules submodules_updated = False if recursive and not bare: submodules_updated = submodules_fetch(git_path, module, remote, track_submodules, dest) if submodules_updated: result.update(submodules_changed=submodules_updated) if module.check_mode: result.update(changed=True, after=remote_head) module.exit_json(**result) # Switch to version specified submodule_update(git_path, module, dest, track_submodules, force=force) # determine if we changed anything result['after'] = get_version(module, git_path, dest) if result['before'] != result['after'] or local_mods or submodules_updated or remote_url_changed: result.update(changed=True) if module._diff: diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after']) if diff: result['diff'] = diff if archive: # Git archive is not supported by all git servers, so # we will first clone and perform git archive from local directory if module.check_mode: result.update(changed=True) module.exit_json(**result) create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result) module.exit_json(**result) if __name__ == '__main__': main()
dmsimard/ansible
lib/ansible/modules/git.py
Python
gpl-3.0
53,677
<?php /**************************************************************************/ /* PHP-NUKE: Advanced Content Management System */ /* ============================================ */ /* */ /* This is the language module with all the system messages */ /* */ /* If you made a translation, please go to the site and send to me */ /* the translated file. Please keep the original text order by modules, */ /* and just one message per line, also double check your translation! */ /* */ /* You need to change the second quoted phrase, not the capital one! */ /* */ /* If you need to use double quotes (') remember to add a backslash (\), */ /* so your entry will look like: This is \'double quoted\' text. */ /* And, if you use HTML code, please double check it. */ /* If you create the correct translation for this file please post it */ /* in the forums at www.ravenphpscripts.com */ /* */ /**************************************************************************/ define('_MA_ARTICLE','Articles'); define('_MA_ARTICLEID','Article #'); define('_MA_ARTICLE_AUTHOR_UPDATE','has been tied to '); define('_MA_ARTICLE_UPDATE_WARNING','You must enter an Article ID <strong>and</strong> an author username to move an article.'); define('_MA_READS_TO_MAKE_TOP10','Reads to make top 10: '); define('_MA_NO_AUTHORS','No User Authors'); define('_TOPWELCOME','Welcome to the Articles and Authors page for '); define('_WELCOME','Welcome'); define('_SUBMITCONTENT','Submit Content'); define('_SUBMITARTICLE','Submit Article'); define('_WRITEREVIEW','Write Review'); define('_SUBMITWEBLINK','Submit Web Link'); define('_STATISTICS','Statistics'); define('_QUICKSTATOVERVIEW','Quick Stat Overview'); define('_TOPRECENTSTORIES','Top Stories in the last 30 days'); define('_TOPALLSTORIES','Top Stories of all time'); define('_TOPAUTHORS','Top Authors'); define('_MONTHLYARTICLEOVERVIEW','Monthly Article Overview'); define('_ARTICLECOUNTBYTOPIC','Article Count By Topic'); define('_ARTICLECOUNTBYCATEGORY','Article Count By Category'); define('_STORYREADS','Reads'); define('_STORIES','Stories'); define('_STORYAVGREADS','Avg Reads'); define('_OVERALL','Overall'); define('_RECENT','Recent'); define('_STORYTITLE','Title'); define('_STORYDATE','Date'); define('_AUTHORNAME','Author'); define('_READSPERDAY','Reads Per Day'); define('_READSTORIES','most read stories'); define('_TOP','Top'); define('_AUTHORS','Authors'); define('_NUMSTORIES','# Stories'); define('_TOTALRATINGS','Total Ratings'); define('_AVGRATINGS','Avg Rating'); define('_MONTH','Month'); define('_CATEGORY','Category'); define('_LVOTES','votes'); define('_HITS','Hits'); define('_LINKSDATESTRING','%d. %m. %Y'); ?>
TGates71/PNPv1-Languages
PNPv101-lang-english/modules/MetAuthors/language/lang-english.php
PHP
gpl-3.0
3,154
/* This file is part of SpatGRIS. Developers: Samuel Béland, Olivier Bélanger, Nicolas Masson SpatGRIS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SpatGRIS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SpatGRIS. If not, see <http://www.gnu.org/licenses/>. */ #include "sg_AbstractSliceComponent.hpp" //============================================================================== AbstractSliceComponent::AbstractSliceComponent(GrisLookAndFeel & lookAndFeel, SmallGrisLookAndFeel & smallLookAndFeel) : mLayout(LayoutComponent::Orientation::vertical, false, false, lookAndFeel) , mVuMeter(smallLookAndFeel) , mMuteSoloComponent(*this, lookAndFeel, smallLookAndFeel) { JUCE_ASSERT_MESSAGE_THREAD; addAndMakeVisible(mLayout); } //============================================================================== void AbstractSliceComponent::setState(PortState const state, bool const soloMode) { JUCE_ASSERT_MESSAGE_THREAD; mMuteSoloComponent.setPortState(state); mVuMeter.setMuted(soloMode ? state != PortState::solo : state == PortState::muted); repaint(); }
GRIS-UdeM/spatServerGRIS
Source/sg_AbstractSliceComponent.cpp
C++
gpl-3.0
1,548
#include "main/SimpleCardProtocol.hh" #include "bridge/BridgeConstants.hh" #include "bridge/CardShuffle.hh" #include "bridge/CardType.hh" #include "bridge/Position.hh" #include "engine/SimpleCardManager.hh" #include "main/Commands.hh" #include "main/PeerCommandSender.hh" #include "messaging/CardTypeJsonSerializer.hh" #include "messaging/FunctionMessageHandler.hh" #include "messaging/JsonSerializer.hh" #include "messaging/JsonSerializerUtility.hh" #include "messaging/UuidJsonSerializer.hh" #include "Logging.hh" #include <algorithm> #include <optional> #include <string> #include <tuple> #include <utility> namespace Bridge { namespace Main { using CardVector = std::vector<CardType>; using Engine::CardManager; using Messaging::failure; using Messaging::Identity; using Messaging::JsonSerializer; using Messaging::Reply; using Messaging::success; class SimpleCardProtocol::Impl : public Bridge::Observer<CardManager::ShufflingState> { public: Impl( const Uuid& gameUuid, std::shared_ptr<PeerCommandSender> peerCommandSender); bool acceptPeer( const Identity& identity, const PositionVector& positions); Reply<> deal(const Identity& identity, const CardVector& cards); const Uuid gameUuid; const std::shared_ptr<Engine::SimpleCardManager> cardManager { std::make_shared<Engine::SimpleCardManager>()}; private: void handleNotify(const CardManager::ShufflingState& state) override; bool expectingCards {false}; std::optional<Identity> leaderIdentity; const std::shared_ptr<PeerCommandSender> peerCommandSender; }; SimpleCardProtocol::Impl::Impl( const Uuid& gameUuid, std::shared_ptr<PeerCommandSender> peerCommandSender) : gameUuid {gameUuid}, peerCommandSender {std::move(peerCommandSender)} { } void SimpleCardProtocol::Impl::handleNotify( const CardManager::ShufflingState& state) { if (state == CardManager::ShufflingState::REQUESTED) { if (!leaderIdentity) { log(LogLevel::DEBUG, "Simple card protocol: Generating deck"); auto cards = generateShuffledDeck(); assert(cardManager); cardManager->shuffle(cards.begin(), cards.end()); dereference(peerCommandSender).sendCommand( JsonSerializer {}, DEAL_COMMAND, std::pair {GAME_COMMAND, gameUuid}, std::pair {CARDS_COMMAND, std::move(cards)}); } else { log(LogLevel::DEBUG, "Simple card protocol: Expecting deck"); expectingCards = true; } } } bool SimpleCardProtocol::Impl::acceptPeer( const Identity& identity, const PositionVector& positions) { if (std::find(positions.begin(), positions.end(), Positions::NORTH) != positions.end()) { leaderIdentity = identity; } return true; } Reply<> SimpleCardProtocol::Impl::deal( const Identity& identity, const CardVector& cards) { log(LogLevel::DEBUG, "Deal command from %s", identity); if (expectingCards && leaderIdentity == identity) { cardManager->shuffle(cards.begin(), cards.end()); expectingCards = false; return success(); } return failure(); } SimpleCardProtocol::SimpleCardProtocol( const Uuid& gameUuid, std::shared_ptr<PeerCommandSender> peerCommandSender) : impl { std::make_shared<Impl>(gameUuid, std::move(peerCommandSender))} { assert(impl->cardManager); impl->cardManager->subscribe(impl); } bool SimpleCardProtocol::handleAcceptPeer( const Identity& identity, const PositionVector& positions, const OptionalArgs&) { assert(impl); return impl->acceptPeer(identity, positions); } void SimpleCardProtocol::handleInitialize() { } std::shared_ptr<Messaging::MessageHandler> SimpleCardProtocol::handleGetDealMessageHandler() { return Messaging::makeMessageHandler( *impl, &Impl::deal, JsonSerializer {}, std::tuple {CARDS_COMMAND}); } SimpleCardProtocol::SocketVector SimpleCardProtocol::handleGetSockets() { return {}; } std::shared_ptr<CardManager> SimpleCardProtocol::handleGetCardManager() { assert(impl); return impl->cardManager; } } }
jasujm/bridge
src/main/SimpleCardProtocol.cc
C++
gpl-3.0
4,231
#define BOOST_TEST_MODULE sugar_integration_tests #include <boost/test/included/unit_test.hpp>
vancleve/fwdpp
testsuite/integration/sugar_integration_tests.cc
C++
gpl-3.0
95
// Mantid Repository : https://github.com/mantidproject/mantid // // Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, // NScD Oak Ridge National Laboratory, European Spallation Source // & Institut Laue - Langevin // SPDX - License - Identifier: GPL - 3.0 + //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include "MantidDataHandling/RemoveLogs.h" #include "MantidAPI/FileProperty.h" #include "MantidDataObjects/Workspace2D.h" #include "MantidKernel/ArrayProperty.h" #include "MantidKernel/Glob.h" #include "MantidKernel/PropertyWithValue.h" #include "MantidKernel/Strings.h" #include "MantidKernel/TimeSeriesProperty.h" #include <Poco/DateTimeFormat.h> #include <Poco/DateTimeParser.h> #include <Poco/DirectoryIterator.h> #include <Poco/File.h> #include <Poco/Path.h> #include <boost/algorithm/string.hpp> #include <algorithm> #include <fstream> // used to get ifstream #include <sstream> namespace Mantid { namespace DataHandling { // Register the algorithm into the algorithm factory DECLARE_ALGORITHM(RemoveLogs) using namespace Kernel; using namespace API; using DataObjects::Workspace2D_sptr; /// Empty default constructor RemoveLogs::RemoveLogs() {} /// Initialisation method. void RemoveLogs::init() { // When used as a Child Algorithm the workspace name is not used - hence the // "Anonymous" to satisfy the validator declareProperty( make_unique<WorkspaceProperty<MatrixWorkspace>>("Workspace", "Anonymous", Direction::InOut), "The name of the workspace to which the log data will be removed"); declareProperty( make_unique<ArrayProperty<std::string>>("KeepLogs", Direction::Input), "List(comma separated) of logs to be kept"); } /** Executes the algorithm. Reading in log file(s) * * @throw Mantid::Kernel::Exception::FileError Thrown if file is not *recognised to be a raw datafile or log file * @throw std::runtime_error Thrown with Workspace problems */ void RemoveLogs::exec() { // Get the input workspace and retrieve run from workspace. // the log file(s) will be loaded into the run object of the workspace const MatrixWorkspace_sptr localWorkspace = getProperty("Workspace"); const std::vector<Mantid::Kernel::Property *> &logData = localWorkspace->run().getLogData(); std::vector<std::string> keepLogs = getProperty("KeepLogs"); std::vector<std::string> logNames; logNames.reserve(logData.size()); for (const auto property : logData) { logNames.push_back(property->name()); } for (const auto &name : logNames) { auto location = std::find(keepLogs.cbegin(), keepLogs.cend(), name); if (location == keepLogs.cend()) { localWorkspace->mutableRun().removeLogData(name); } } // operation was a success and ended normally return; } } // namespace DataHandling } // namespace Mantid
mganeva/mantid
Framework/DataHandling/src/RemoveLogs.cpp
C++
gpl-3.0
2,988
/** * file mirror/doc/factory_generator.hpp * Documentation only header * * @author Matus Chochlik * * Copyright 2008-2010 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef MIRROR_DOC_FACTORY_GENERATOR_1011291729_HPP #define MIRROR_DOC_FACTORY_GENERATOR_1011291729_HPP #ifdef MIRROR_DOCUMENTATION_ONLY #include <mirror/config.hpp> MIRROR_NAMESPACE_BEGIN /** @page mirror_factory_generator_utility Factory generator utility * * @section mirror_factory_generator_intro Introduction * * The factory generator utility allows to easily create implementations * of object factories at compile-time by using the meta-data provided * by Mirror. * By object factories we mean here classes, which can create * instances of various types (@c Products), but do not require that the caller * supplies the parameters for the construction directly. * Factories pick or let the application user pick the @c Product 's most * appropriate constructor, they gather the necessary parameters in * a generic, application-specific way and use the selected constructor * to create an instance of the @c Product. * * Obviously the most interesting feature of these factories is, that * they separate the caller (who just needs to get an instance of the * specified type) from the actual method of creation which involves * choosing of right constructor and supplying the * required parameters, which in turn can also be constructed or supplied * in some other way (for example from a pool of existing objects). * * This is useful when we need to create instances of (possibly different) * types having multiple constructors from a single point in code and we want * the method of construction to be determined by parameters available only * at run-time. * * Here follows a brief list of examples: * - Creation of objects based on user input from a GUI: The factory object * creates a GUI component (a dialog for example) having the necessary * controls for selecting one of the constructors of the constructed type * and for the input of the values of all parameters for the selected * constructor. * - Creation of objects from a database dataset: The factory can go through * the list of constructors and find the one whose parameters are matching * to the columns in a database dataset. Then it calls this constructor * and passes the values of the matching columns as the parameters, doing * the appropriate type conversions where necessary. By doing this repeatedly * we can create multiple objects, each representing a different row in * the dataset. * - Creation of objects from other external representations: Similar to * the option above one can create instances from other file or stream-based * data representations like (XML, JSON, XDR, etc.) * * The factories generated by this utility can then be used for example * for the implementation of the Abstract factory design pattern, where * even the exact type of the created object is not known. * * Because the factory classes are created by a generic meta-program * at compile-time a good optimizing compiler can generate source * code, which is as efficient as if the factories were hand-coded. * This however depends on the implementation of the application-specific * parts that are supplied to the factory generator. * * @section mirror_factory_generator_principles Principles * * As we mentioned in the introduction, the factory must handle two important * tasks during the construction of an instance: * - Choose the constructor (default, copy, custom). * - Supply the parameters to the constructor if necessary. * * The implementation of these tasks is also the most distinctive thing * about a particular factory. The rest of the process is the same regardless * of the @c Product type. This is why the factory generator utility provides * all the common boilerplate code and the application only specifies how * a constuctor is selected and how the arguments are supplied to it. * * Furthermore there are two basic ways how to supply a parameter value: * - Create one from scratch by using the same factory with a different * @c Product type recursivelly. * - Use an existing instance which can be acquired from a pool of instances, * or be a result of a functor call. * * In order to create a factory, the application needs to supply the factory * generator with two template classes with the following signature: * * @code * template <class Product, class SourceTraits> * class constructor_parameter_source; * @endcode * * The first one is referred to as a @c Manufacturer and is responsible * for the creation of new parameter values. The second template is * referred to as @c Suppliers and is responsible for returning of an existing * value. * * One of the specializations of the @c Manufacturer template, namely the one * having the @c void type as @c Product is referred to as @c Manager. * This @c Manager is responsible for the selecting of the constructor that * to be used. * * Both of these templates have the following parameters: * - @c Product is the type produced by the source. A @c Manufacturer creates * a new instance of @c Product and @c Suppliers return an * existing instance of @c Product (one of possibly multiple candidates) * - @c SourceTraits is an optional type parameter used by some factory * implementations for the configuration and fine tuning of the factory's * behavior and appearance. * * Whether these sources (@c Manufacturer or @c Suppliers) are going to be used * for the supplying of a constructor parameter and if so, which of them, * depends on the selected constructor: * - If the @c Product 's default constructor is selected, then no parameters * are required and neither the @c Manufacturer nor the @c Suppliers are used. * - If the copy constructor is selected then the @c Suppliers template * (which returns existing instances of the same type) is used. * - If another constructor was picked, then the @c Manufacturer template is used * to create the individual parameters. * * @subsection mirror_factory_generator_manufacturer The Manufacturer * * The application-defined @c Manufacturer template should have several * distinct specializations, which serve for different purposes. * * As mentioned before, a @c Manufacturer with the @c void type as @c Product * serves as a manager which is responsible for choosing the constructor * that is ultimately to be used for the construction of an instance * of the @c Product. This means that besides the regular @c Manufacturer * which in fact creates the instances, there is one instance of the @c Manager * for every @c Product in the generated factory. The @c Manager has also * a different interface then the other @c Manufacturers. * * Other specializations of the @c Manufacturer should handle the creation of * values of some special types (like the native C++ types; boolean, integers, * floating points, strings, etc), considered atomic (i.e. not eleborated) * by the factory. Values of such types can be input directly by the user * into some kind of UI, they can be converted from some external representation * like the value of row/column in a database dataset, or a value of an XML * attribute, etc. * * The default implementation of the @c Manufacturer is for elaborated types and it * uses a generated factory to recursively create instances of the constructor * parameters. * * @subsection mirror_factory_generator_suppliers The Suppliers * * The @c Suppliers template is responsible for returning existing instances * of the type passed as the @c Product parameter. Depending on the specific * factory and the @c Product, the suppliers may or may not have means * to get instances of that particular @c Product type and should be implemented * accordingly. If there are multiple possible sources of values of a type * then the specialization of @c Suppliers must provide some means how to * select which of the external sources is to be used. * * @subsection mirror_factory_generator_source_traits The parameter source traits * * For additional flexibility both the @c Manufacturer and the @c Suppliers * template have (besides the @c Product type they create) an aditional template * type parameter called @c SourceTraits. This type is usually defined together * with the @c Manufacturer and @c Suppliers and is passed to the instantiations * of these templates by the factory generator when a new factory is created. * The factory generator treats this type as opaque. * If a concrete implementation of the parameter sources (@c Manufacturer and * @c Suppliers) has no use for this additional parameter, the void type * can be passed to the factory generator. * * @subsection mirror_factory_generator_factory_maker Factory and Factory Maker * * The @c Manufacturers, the @c Suppliers, the @c SourceTraits and * the boilerplate code common to all factories is tied together by * the @c mirror::factory template, with the following definition: * * @code * template < * template <class, class> class Manufacturer, * template <class, class> class Suppliers, * class SourceTraits, * typename Product * > class factory * { * public: * Product operator()(void); * Product* new_(void); * }; * @endcode * * Perhaps a more convenient way how to create factories, especially when * one wants to create multiple factories of the same kind (with the same * @c Manufacturers, @c Suppliers and @c SourceTraits) for constructing * different @c Product types is to use the @c mirror::factory_maker template * class defined as follows: * * @code * template < * template <class, class> class Manufacturer, * template <class, class> class Suppliers, * class SourceTraits * > struct factory_maker * { * template <typename Product> * struct factory * { * typedef factory<Manufacturer, Suppliers, SourceTraits, Product> type; * }; * }; * @endcode * * @section mirror_factory_generator_usage Usage * * The basic usage of the factory generator utility should be obvious from the above; * It is necessary to implement the @c Manufacturer and the @c Suppliers * templates (and possibly also the @c SourceTraits) and then use either the * @c mirror::factory template directly or the @c mirror::factory_maker 's factory * nested template to create an instantiation of a factory constructing instances * of a @c Product type: * * @code * // use the factory directly ... * mirror::factory<my_manuf, my_suppl, my_traits, my_product_1> f1; * my_product_1 x1(f1()); * my_product_1* px1(f1.new_()); * * // ... * // or use the factory_maker * typedef mirror::factory_maker<my_manuf, my_suppl, my_traits> my_fact_maker; * my_fact_maker::factory<my_product_1>::type f1; * my_fact_maker::factory<my_product_2>::type f2; * my_fact_maker::factory<my_product_3>::type f2; * // * my_product_1 x1(f1()); * my_product_1* px1(f1.new_()); * my_product_2 x2(f2()); * my_product_3* px3(f3.new_()); * @endcode * * @subsection mirror_factory_generator_tutorials Tutorials and other resources * * Here follows a list of references to other pages dealing with the factory * generator utility in depth and also tutorials showing how to write * the plugins (the Managers, Manufacturers and Suppliers) for the factory * generator: * * - @subpage mirror_fact_gen_in_depth * - @subpage mirror_sql_fact_gen_tutorial * * @section mirror_factory_generator_existing_templates Existing Manufacturers and Suppliers * * The Mirror library provides several working sample implementations * of the @c Manufacturer and @c Suppliers templates. * The following example shows the usage of the @c wx_gui_factory template * with the factory generator utility in a simple wxWidgets-based application. * The generated factory creates a wxDialog containing all necessary widgets * for the selection of the constructor to be used and for the input of all * parameters required by the selected constructor. Screenshots of dialogs * generated by this implementation can be found * @link mirror_wx_gui_fact_examples here@endlink. */ MIRROR_NAMESPACE_END #endif // DOCUMENTATION_ONLY #endif //include guard
firestarter/firestarter
redist/mirror-lib/mirror/doc/factory_generator.hpp
C++
gpl-3.0
12,717
namespace GemsCraft.Entities.Metadata.Flags { public enum TameableFlags: byte { IsSitting = 0x01, /// <summary> /// Only used with wolves /// </summary> IsAngry = 0x02, IsTamed = 0x04 } }
apotter96/GemsCraft
GemsCraft/Entities/Metadata/Flags/TameableFlags.cs
C#
gpl-3.0
251
import React from 'react'; import { connect } from 'react-redux'; import { View, Text, FlatList } from 'react-native'; import sb from 'react-native-style-block'; import dateHelper from '@shared/utils/date-helper'; import appConfig from '../config.app'; import ConvItem from '../components/ConvItem'; import { reloadConverseList } from '@shared/redux/actions/chat'; import styled from 'styled-components/native'; import TRefreshControl from '../components/TComponent/TRefreshControl'; import { ChatType } from '../types/params'; import type { TRPGState, TRPGDispatchProp } from '@redux/types/__all__'; import _get from 'lodash/get'; import _values from 'lodash/values'; import _sortBy from 'lodash/sortBy'; import _size from 'lodash/size'; import { TMemo } from '@shared/components/TMemo'; import { useSpring, animated } from 'react-spring/native'; import { useTRPGSelector } from '@shared/hooks/useTRPGSelector'; import { TRPGTabScreenProps } from '@app/router'; import { switchToChatScreen } from '@app/navigate'; const NetworkContainer = styled(animated.View as any)<{ isOnline: boolean; tryReconnect: boolean; }>` position: absolute; top: -26px; left: 0; right: 0; height: 26px; background-color: ${({ isOnline, tryReconnect }) => isOnline ? '#2ecc71' : tryReconnect ? '#f39c12' : '#c0392b'}; color: white; align-items: center; justify-content: center; `; const NetworkText = styled.Text` color: white; `; const NetworkTip: React.FC = TMemo((props) => { const network = useTRPGSelector((state) => state.ui.network); const style = useSpring({ to: { top: network.isOnline ? -26 : 0, }, }); return ( <NetworkContainer style={style} isOnline={network.isOnline} tryReconnect={network.tryReconnect} > <NetworkText>{network.msg}</NetworkText> </NetworkContainer> ); }); NetworkTip.displayName = 'NetworkTip'; interface Props extends TRPGDispatchProp, TRPGTabScreenProps<'TRPG'> { converses: any; conversesDesc: any; groups: any; usercache: any; } class HomeScreen extends React.Component<Props> { state = { isRefreshing: false, }; getList() { if (_size(this.props.converses) > 0) { const arr: any[] = _sortBy( _values(this.props.converses), (item) => new Date(item.lastTime || 0) ) .reverse() .map((item, index) => { const uuid = item.uuid; const defaultIcon = uuid === 'trpgsystem' ? appConfig.defaultImg.trpgsystem : appConfig.defaultImg.user; let avatar: string; if (item.type === 'user') { avatar = _get(this.props.usercache, [uuid, 'avatar']); } else if (item.type === 'group') { const group = this.props.groups.find((g) => g.uuid === uuid); avatar = group ? group.avatar : ''; } return { icon: item.icon || avatar || defaultIcon, title: item.name, content: item.lastMsg, time: item.lastTime ? dateHelper.getShortDiff(item.lastTime) : '', uuid, unread: item.unread, onPress: () => { this.handleSelectConverse(uuid, item.type, item); }, }; }); return ( <FlatList refreshControl={ <TRefreshControl refreshing={this.state.isRefreshing} onRefresh={() => this.handleRefresh()} /> } keyExtractor={(item, index) => item.uuid} data={arr} renderItem={({ item }) => <ConvItem {...item} />} /> ); } else { return <Text style={styles.tipText}>{this.props.conversesDesc}</Text>; } } handleRefresh() { this.setState({ isRefreshing: true }); const timer = setTimeout(() => { this.setState({ isRefreshing: false }); }, 10000); // 10秒后自动取消 this.props.dispatch( reloadConverseList(() => { this.setState({ isRefreshing: false }); clearTimeout(timer); }) ); } handleSelectConverse(uuid: string, type: ChatType, info) { switchToChatScreen( this.props.navigation.dangerouslyGetParent(), uuid, type, info.name ); } render() { return ( <View style={styles.container}> {this.getList()} <NetworkTip /> </View> ); } } const styles = { container: [sb.flex()], tipText: [sb.textAlign('center'), sb.margin(80, 0, 0, 0), sb.color('#999')], }; export default connect((state: TRPGState) => ({ converses: state.chat.converses, conversesDesc: state.chat.conversesDesc, groups: state.group.groups, usercache: state.cache.user, }))(HomeScreen);
TRPGEngine/Client
src/app/src/screens/HomeScreen.tsx
TypeScript
gpl-3.0
4,755
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class ReadSavedData { public static void StartRead() throws IOException { FileReader file = new FileReader("C:/Users/Public/Documents/SavedData.txt"); BufferedReader reader = new BufferedReader(file); String text = ""; String line = reader.readLine(); while (line != null) { text += line; line = reader.readLine(); } reader.close(); System.out.println(text); } }
uSirPatrick/IPCalcGUI
IPCalc2/src/ReadSavedData.java
Java
gpl-3.0
556
class ApplicationController < ActionController::Base class ForbiddenException < StandardError; end protect_from_forgery before_filter :set_locale before_filter :authenticate_user! layout :get_layout def set_locale I18n.locale = params[:locale] || I18n.default_locale end def get_layout if !user_signed_in? get_layout = "logged_out" else get_layout = "application" end end def after_sign_out_path_for(resource) new_user_session_path end def administrator_only_access unless user_signed_in? && current_user.admin? raise ApplicationController::ForbiddenException end end end
autohome/autohome-web
app/controllers/application_controller.rb
Ruby
gpl-3.0
650
/** * Copyright 2010 David Froehlich <david.froehlich@businesssoftware.at>, * Samuel Kogler <samuel.kogler@gmail.com>, * Stephan Stiboller <stistc06@htlkaindorf.at> * * This file is part of Codesearch. * * Codesearch is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Codesearch is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Codesearch. If not, see <http://www.gnu.org/licenses/>. */ package com.uwyn.jhighlight.pcj.hash; /** * This interface represents hash functions from char values * to int values. The int value result is chosen to achieve * consistence with the common * {@link Object#hashCode() hashCode()} * method. The interface is provided to alter the hash functions used * by hashing data structures, like * {@link com.uwyn.rife.pcj.map.CharKeyIntChainedHashMap CharKeyIntChainedHashMap} * or * {@link com.uwyn.rife.pcj.set.CharChainedHashSet CharChainedHashSet}. * * @see DefaultCharHashFunction * * @author S&oslash;ren Bak * @version 1.0 2002/29/12 * @since 1.0 */ public interface CharHashFunction { /** * Returns a hash code for a specified char value. * * @param v * the value for which to return a hash code. * * @return a hash code for the specified value. */ int hash(char v); }
codesearch-github/codesearch
src/custom-libs/Codesearch-JHighlight/src/main/java/com/uwyn/jhighlight/pcj/hash/CharHashFunction.java
Java
gpl-3.0
1,832
using System; using System.Diagnostics; using System.Text; using System.Windows.Forms; using OpenDentBusiness; namespace OpenDental.Eclaims { /// <summary> /// Summary description for BCBSGA. /// </summary> public class BCBSGA{ /// <summary></summary> public static string ErrorMessage=""; public BCBSGA() { } ///<summary>Returns true if the communications were successful, and false if they failed. If they failed, a rollback will happen automatically by deleting the previously created X12 file. The batchnum is supplied for the possible rollback.</summary> public static bool Launch(Clearinghouse clearinghouseClin,int batchNum){ //called from Eclaims.cs. Clinic-level clearinghouse passed in. bool retVal=true; FormTerminal FormT=new FormTerminal(); try{ FormT.Show(); FormT.OpenConnection(clearinghouseClin.ModemPort); //1. Dial FormT.Dial("17065713158"); //2. Wait for connect, then pause 3 seconds FormT.WaitFor("CONNECT 9600",50000); FormT.Pause(3000); FormT.ClearRxBuff(); //3. Send Submitter login record string submitterLogin= //position,length indicated for each "/SLRON"//1,6 /SLRON=Submitter login +FormT.Sout(clearinghouseClin.LoginID,12,12)//7,12 Submitter ID +FormT.Sout(clearinghouseClin.Password,8,8)//19,8 submitter password +"NAT"//27,3 use NAT //30,8 suggested 8-BYTE CRC of the file for unique ID. No spaces. //But I used the batch number instead +batchNum.ToString().PadLeft(8,'0') +"ANSI837D 1 "//38,15 "ANSI837D 1 "=Dental claims +"X"//53,1 X=Xmodem, or Y for transmission protocol +"ANSI"//54,4 use ANSI +"BCS"//58,3 BCS=BlueCrossBlueShield +"00";//61,2 use 00 for filler FormT.Send(submitterLogin); //4. Receive Y, indicating login accepted if(FormT.WaitFor("Y","N",20000)=="Y"){ //5. Wait 1 second. FormT.Pause(1000); } else{ //6. If login rejected, receive an N, //followed by Transmission acknowledgement explaining throw new Exception(FormT.Receive(5000)); } //7. Send file using X-modem or Z-modem //slash not handled properly if missing: FormT.UploadXmodem(clearinghouseClin.ExportPath+"claims"+batchNum.ToString()+".txt"); //8. After transmitting, pause for 1 second. FormT.Pause(1000); FormT.ClearRxBuff(); //9. Send submitter logout record string submitterLogout= "/SLROFF"//1,7 /SLROFF=Submitter logout +FormT.Sout(clearinghouseClin.LoginID,12,12)//8,12 Submitter ID +batchNum.ToString().PadLeft(8,'0')//20,8 matches field in submitter Login +"!"//28,1 use ! to retrieve transmission acknowledgement record +"\r\n"; FormT.Send(submitterLogout); //10. Prepare to receive the Transmission acknowledgement. This is a receipt. FormT.Receive(5000);//this is displayed in the progress box so user can see. } catch(Exception ex){ ErrorMessage=ex.Message; x837Controller.Rollback(clearinghouseClin,batchNum); retVal=false; } finally{ FormT.CloseConnection(); } return retVal; } ///<summary>Retrieves any waiting reports from this clearinghouse. Returns true if the communications were successful, and false if they failed.</summary> public static bool Retrieve(Clearinghouse clearinghouseClin) { //Called from FormClaimReports. Clinic-level Clearinghouse passed in. bool retVal=true; FormTerminal FormT=new FormTerminal(); try{ FormT.Show(); FormT.OpenConnection(clearinghouseClin.ModemPort); FormT.Dial("17065713158"); //2. Wait for connect, then pause 3 seconds FormT.WaitFor("CONNECT 9600",50000); FormT.Pause(3000); FormT.ClearRxBuff(); //1. Send submitter login record string submitterLogin= "/SLRON"//1,6 /SLRON=Submitter login +FormT.Sout(clearinghouseClin.LoginID,12,12)//7,12 Submitter ID +FormT.Sout(clearinghouseClin.Password,8,8)//19,8 submitter password +" "//27,3 use 3 spaces //Possible issue with Trans ID +"12345678"//30,8. they did not explain this field very well in documentation +"* "//38,15 " * "=All available. spacing ok? +"X"//53,1 X=Xmodem, or Y for transmission protocol +"MDD "//54,4 use 'MDD ' +"VND"//58,3 Vendor ID is yet to be assigned by BCBS +"00";//61,2 Software version not important byte response=(byte)'Y'; string retrieveFile=""; while(response==(byte)'Y'){ FormT.ClearRxBuff(); FormT.Send(submitterLogin); response=0; while(response!=(byte)'N' && response!=(byte)'Y' && response!=(byte)'Z') { response=FormT.GetOneByte(20000); FormT.ClearRxBuff(); Application.DoEvents(); } //2. If not accepted, N is returned //3. and must receive transmission acknowledgement if(response==(byte)'N'){ MessageBox.Show(FormT.Receive(10000)); break; } //4. If login accepted, but no records, Z is returned. Hang up. if(response==(byte)'Z'){ MessageBox.Show("No reports to retrieve"); break; } //5. If record(s) available, Y is returned, followed by dos filename and 32 char subj. //less than one second since all text is supposed to immediately follow the Y retrieveFile=FormT.Receive(800).Substring(0,12);//12 char in dos filename FormT.ClearRxBuff(); //6. Pause for 1 second. (already mostly handled); FormT.Pause(200); //7. Receive file using Xmodem //path must include trailing slash for now. FormT.DownloadXmodem(clearinghouseClin.ResponsePath+retrieveFile); //8. Pause for 5 seconds. FormT.Pause(5000); //9. Repeat all steps including login until a Z is returned. } } catch(Exception ex){ ErrorMessage=ex.Message; //FormT.Close();//Also closes connection retVal=false; } finally{ FormT.CloseConnection(); } return retVal; } } }
eae/opendental
OpenDental/Eclaims/BCBSGA.cs
C#
gpl-3.0
5,973
#include "inventorypage.h" #include "ui_inventorypage.h" #include "fak.h" #include "inventorypage.h" #include <QtDebug> #include "QtDebug" #include <QSqlQuery> #include <QSqlError> #include <QSqlRecord> static const QString path = "C:/Sr.GUI/FAKKIT/db/fakdb4.db"; InventoryPage::InventoryPage(QWidget *parent) : QDialog(parent), ui(new Ui::InventoryPage) { ui->setupUi(this); this->setStyleSheet("background-color:#626065;"); DbManager db(path); qDebug() << "Stuff in db:"; QSqlQuery query; query.exec("SELECT * FROM codes"); int idName = query.record().indexOf("name"); while (query.next()) { QString name = query.value(idName).toString(); qDebug() << "===" << name; //ui->dbOutput->setPlainText(name); ui->dbOutput->append(name); } } DbManager::DbManager(const QString &path) { m_db = QSqlDatabase::addDatabase("QSQLITE"); m_db.setDatabaseName(path); if (!m_db.open()) { qDebug() << "Error: connection with database fail"; } else { qDebug() << "Database: connection ok"; } } InventoryPage::~InventoryPage() { delete ui; } void InventoryPage::on_HomeButton_clicked() { }
r0ug3-Mary/Sr.GUI
FAKKITpics/inventorypage.cpp
C++
gpl-3.0
1,227
var gulp = require('gulp'); var browserSync = require('browser-sync'); var jshint = require('gulp-jshint'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); // 静态服务器 gulp.task('browser-sync', function() { browserSync.init({ files: "src/**", server: { baseDir: "src/" } }); }); // js语法检查 gulp.task('jshint', function() { return gulp.src('src/js/*.js') .on('error') .pipe(jshint()) .pipe(jshint.reporter('default')); }); // js文件合并及压缩 gulp.task('minifyjs', function() { return gulp.src('src/js/*.js') .pipe(concat('all.js')) .pipe(gulp.dest('dist/js')) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('dist/js')); }); // 事件监听 gulp.task('watch', function() { gulp.watch('src/js/*.js', ['jshint','minifyjs']); }); gulp.task('default',['browser-sync','watch']);
bdSpring/zhou-task02
26/gulpfile.js
JavaScript
gpl-3.0
946
using UnityEngine; using System.Collections; public class TimeScaleManager : MonoBehaviour { public static TimeScaleManager instance; public delegate void OnTimeScaleChangeCallback(); public event OnTimeScaleChangeCallback TimeScaleChange; public bool isPlaying; public bool IsPaused { get { return !isPlaying; } } public enum TimeScale{ ONE, TWO, THREE } public TimeScale timeScale; void Awake(){ instance = this; timeScale = TimeScale.ONE; Time.timeScale = 0f; isPlaying = false; } public void SelectNextTimeScale(){ switch(timeScale){ case TimeScale.ONE: timeScale = TimeScale.TWO; if (isPlaying) { Time.timeScale = 2f; } if (TimeScaleChange != null){ TimeScaleChange(); } break; case TimeScale.TWO: timeScale = TimeScale.THREE; if (isPlaying) { Time.timeScale = 3f; } if (TimeScaleChange != null){ TimeScaleChange(); } break; case TimeScale.THREE: timeScale = TimeScale.ONE; if (isPlaying) { Time.timeScale = 1f; } if (TimeScaleChange != null){ TimeScaleChange(); } break; } } public string GetCurrentTimeScaleLabel(){ switch(timeScale){ case TimeScale.ONE: return "1"; case TimeScale.TWO: return "2"; case TimeScale.THREE: return "3"; default: return "error"; } } }
Michael-Dawkins/GeometricDefense
Assets/Scripts/Services/TimeScaleManager.cs
C#
gpl-3.0
1,551
package org.amse.marinaSokol.model.interfaces.object.net; public interface IActivationFunctor { /** * Ôóíêöèÿ àêòèâàöèè * @param x - ÷èñëî, ïîäàííîå íà ôóíêöèþ àêòèâàöèè * @return âûõîä íåéðîíà * */ double getFunction(double x); /** * ïðîèçâîäíàÿ ôóíêöèè àêòèâàöèè * @param x - ÷èñëî, ïîäàííîå íà ôóíêöèþ * @return âûõîä * */ double getDerivation(double x); /** * Èìÿ ôóíêöèè àêòèâàöèè * @return èìÿ ôóíêöèè àêòèâàöèè * */ String getNameFunction(); }
sokolm/NeuroNet
src/org/amse/marinaSokol/model/interfaces/object/net/IActivationFunctor.java
Java
gpl-3.0
558
/* SPDX-FileCopyrightText: 2007 Jean-Baptiste Mardelle <jb@kdenlive.org> SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL */ #include "definitions.h" #include <klocalizedstring.h> #include <QColor> #include <utility> #ifdef CRASH_AUTO_TEST #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wsign-conversion" #pragma GCC diagnostic ignored "-Wfloat-equal" #pragma GCC diagnostic ignored "-Wshadow" #pragma GCC diagnostic ignored "-Wpedantic" #include <rttr/registration> #pragma GCC diagnostic pop RTTR_REGISTRATION { using namespace rttr; // clang-format off registration::enumeration<GroupType>("GroupType")( value("Normal", GroupType::Normal), value("Selection", GroupType::Selection), value("AVSplit", GroupType::AVSplit), value("Leaf", GroupType::Leaf) ); registration::enumeration<PlaylistState::ClipState>("PlaylistState")( value("VideoOnly", PlaylistState::VideoOnly), value("AudioOnly", PlaylistState::AudioOnly), value("Disabled", PlaylistState::Disabled) ); // clang-format on } #endif QDebug operator<<(QDebug qd, const ItemInfo &info) { qd << "ItemInfo " << &info; qd << "\tTrack" << info.track; qd << "\tStart pos: " << info.startPos.toString(); qd << "\tEnd pos: " << info.endPos.toString(); qd << "\tCrop start: " << info.cropStart.toString(); qd << "\tCrop duration: " << info.cropDuration.toString(); return qd.maybeSpace(); } CommentedTime::CommentedTime() : m_time(GenTime(0)) { } CommentedTime::CommentedTime(const GenTime &time, QString comment, int markerType) : m_time(time) , m_comment(std::move(comment)) , m_type(markerType) { } CommentedTime::CommentedTime(const QString &hash, const GenTime &time) : m_time(time) , m_comment(hash.section(QLatin1Char(':'), 1)) , m_type(hash.section(QLatin1Char(':'), 0, 0).toInt()) { } QString CommentedTime::comment() const { return (m_comment.isEmpty() ? i18n("Marker") : m_comment); } GenTime CommentedTime::time() const { return m_time; } void CommentedTime::setComment(const QString &comm) { m_comment = comm; } void CommentedTime::setTime(const GenTime &t) { m_time = t; } void CommentedTime::setMarkerType(int newtype) { m_type = newtype; } QString CommentedTime::hash() const { return QString::number(m_type) + QLatin1Char(':') + (m_comment.isEmpty() ? i18n("Marker") : m_comment); } int CommentedTime::markerType() const { return m_type; } bool CommentedTime::operator>(const CommentedTime &op) const { return m_time > op.time(); } bool CommentedTime::operator<(const CommentedTime &op) const { return m_time < op.time(); } bool CommentedTime::operator>=(const CommentedTime &op) const { return m_time >= op.time(); } bool CommentedTime::operator<=(const CommentedTime &op) const { return m_time <= op.time(); } bool CommentedTime::operator==(const CommentedTime &op) const { return m_time == op.time(); } bool CommentedTime::operator!=(const CommentedTime &op) const { return m_time != op.time(); } const QString groupTypeToStr(GroupType t) { switch (t) { case GroupType::Normal: return QStringLiteral("Normal"); case GroupType::Selection: return QStringLiteral("Selection"); case GroupType::AVSplit: return QStringLiteral("AVSplit"); case GroupType::Leaf: return QStringLiteral("Leaf"); } Q_ASSERT(false); return QString(); } GroupType groupTypeFromStr(const QString &s) { std::vector<GroupType> types{GroupType::Selection, GroupType::Normal, GroupType::AVSplit, GroupType::Leaf}; for (const auto &t : types) { if (s == groupTypeToStr(t)) { return t; } } Q_ASSERT(false); return GroupType::Normal; } std::pair<bool, bool> stateToBool(PlaylistState::ClipState state) { return {state == PlaylistState::VideoOnly, state == PlaylistState::AudioOnly}; } PlaylistState::ClipState stateFromBool(std::pair<bool, bool> av) { Q_ASSERT(!av.first || !av.second); if (av.first) { return PlaylistState::VideoOnly; } else if (av.second) { return PlaylistState::AudioOnly; } else { return PlaylistState::Disabled; } } SubtitledTime::SubtitledTime() : m_starttime(0) , m_endtime(0) { } SubtitledTime::SubtitledTime(const GenTime &start, QString sub, const GenTime &end) : m_starttime(start) , m_subtitle(std::move(sub)) , m_endtime(end) { } QString SubtitledTime::subtitle() const { return m_subtitle; } GenTime SubtitledTime::start() const { return m_starttime; } GenTime SubtitledTime::end() const { return m_endtime; } void SubtitledTime::setSubtitle(const QString& sub) { m_subtitle = sub; } void SubtitledTime::setEndTime(const GenTime& end) { m_endtime = end; } bool SubtitledTime::operator>(const SubtitledTime& op) const { return(m_starttime > op.m_starttime && m_endtime > op.m_endtime && m_starttime > op.m_endtime); } bool SubtitledTime::operator<(const SubtitledTime& op) const { return(m_starttime < op.m_starttime && m_endtime < op.m_endtime && m_endtime < op.m_starttime); } bool SubtitledTime::operator==(const SubtitledTime& op) const { return(m_starttime == op.m_starttime && m_endtime == op.m_endtime); } bool SubtitledTime::operator!=(const SubtitledTime& op) const { return(m_starttime != op.m_starttime && m_endtime != op.m_endtime); }
KDE/kdenlive
src/definitions.cpp
C++
gpl-3.0
5,551
// ------------------------------------------------------------------------------------------ // Licensed by Interprise Solutions. // http://www.InterpriseSolutions.com // For details on this license please visit the product homepage at the URL above. // THE ABOVE NOTICE MUST REMAIN INTACT. // ------------------------------------------------------------------------------------------ using System; using InterpriseSuiteEcommerceCommon; using InterpriseSuiteEcommerceCommon.InterpriseIntegration; namespace InterpriseSuiteEcommerce { /// <summary> /// Summary description for tableorder_process. /// </summary> public partial class tableorder_process : System.Web.UI.Page { protected void Page_Load(object sender, System.EventArgs e) { Response.CacheControl = "private"; Response.Expires = 0; Response.AddHeader("pragma", "no-cache"); Customer ThisCustomer = ((InterpriseSuiteEcommercePrincipal)Context.User).ThisCustomer; ThisCustomer.RequireCustomerRecord(); InterpriseShoppingCart cart = new InterpriseShoppingCart(null, 1, ThisCustomer, CartTypeEnum.ShoppingCart, String.Empty, false,true); bool redirectToWishList = false; foreach (string key in Request.Form.AllKeys) { try { if (!key.StartsWith("ProductID")) { continue; } // retrieve the item counter // This may look obvious 4 but we want to make it expressive string itemCounterValue = Request.Form[key]; string quantityOrderedValue = Request.Form["Quantity"]; if (string.IsNullOrEmpty(quantityOrderedValue)) { quantityOrderedValue = Request.Form["Quantity_" + itemCounterValue]; if (!string.IsNullOrEmpty(quantityOrderedValue)) { quantityOrderedValue = quantityOrderedValue.Split(',')[0]; } } int counter = 0; int quantityOrdered = 0; if (!string.IsNullOrEmpty(itemCounterValue) && int.TryParse(itemCounterValue, out counter) && !string.IsNullOrEmpty(quantityOrderedValue) && int.TryParse(quantityOrderedValue, out quantityOrdered) && quantityOrdered > 0) { string unitMeasureFieldKey = "UnitMeasureCode_" + counter.ToString(); bool useDefaultUnitMeasure = string.IsNullOrEmpty(Request.Form[unitMeasureFieldKey]); string isWishListFieldKey = "IsWishList_" + counter.ToString(); bool isWishList = !string.IsNullOrEmpty(Request.Form[isWishListFieldKey]); redirectToWishList = isWishList; // we've got a valid counter string itemCode = string.Empty; using (var con = DB.NewSqlConnection()) { con.Open(); using (var reader = DB.GetRSFormat(con, "SELECT ItemCode FROM InventoryItem with (NOLOCK) WHERE Counter = {0}", counter)) { if (reader.Read()) { itemCode = DB.RSField(reader, "ItemCode"); } } } if(!string.IsNullOrEmpty(itemCode)) { UnitMeasureInfo? umInfo = null; if(!useDefaultUnitMeasure) { umInfo = InterpriseHelper.GetItemUnitMeasure(itemCode, Request.Form[unitMeasureFieldKey]); } if(null == umInfo && useDefaultUnitMeasure) { umInfo = InterpriseHelper.GetItemDefaultUnitMeasure(itemCode); } if (null != umInfo && umInfo.HasValue) { if (isWishList) { cart.CartType = CartTypeEnum.WishCart; } cart.AddItem(ThisCustomer, ThisCustomer.PrimaryShippingAddressID, itemCode, counter, quantityOrdered, umInfo.Value.Code, CartTypeEnum.ShoppingCart); //, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, CartTypeEnum.ShoppingCart, false, false, string.Empty, decimal.Zero); } } } } catch { // do nothing, add the items that we can } } if (redirectToWishList) { Response.Redirect("WishList.aspx"); } else { Response.Redirect("ShoppingCart.aspx?add=true"); } } } }
bhassett/Expressions-CB13
tableorder_process.aspx.cs
C#
gpl-3.0
5,729
<?php /** * WooCommerce Admin Webhooks Class * * @author WooThemes * @category Admin * @package WooCommerce/Admin * @version 2.4.0 */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly } /** * WC_Admin_Webhooks. */ class WC_Admin_Webhooks { /** * Initialize the webhooks admin actions. */ public function __construct() { add_action( 'admin_init', array( $this, 'actions' ) ); } /** * Check if is webhook settings page. * * @return bool */ private function is_webhook_settings_page() { return isset( $_GET['page'] ) && 'wc-settings' == $_GET['page'] && isset( $_GET['tab'] ) && 'api' == $_GET['tab'] && isset( $_GET['section'] ) && 'webhooks' == isset( $_GET['section'] ); } /** * Updated the Webhook name. * * @param int $webhook_id */ private function update_name( $webhook_id ) { global $wpdb; // @codingStandardsIgnoreStart $name = ! empty( $_POST['webhook_name'] ) ? $_POST['webhook_name'] : sprintf( __( 'Webhook created on %s', 'woocommerce' ), strftime( _x( '%b %d, %Y @ %I:%M %p', 'Webhook created on date parsed by strftime', 'woocommerce' ) ) ); // @codingStandardsIgnoreEnd $wpdb->update( $wpdb->posts, array( 'post_title' => $name ), array( 'ID' => $webhook_id ) ); } /** * Updated the Webhook status. * * @param WC_Webhook $webhook */ private function update_status( $webhook ) { $status = ! empty( $_POST['webhook_status'] ) ? wc_clean( $_POST['webhook_status'] ) : ''; $webhook->update_status( $status ); } /** * Updated the Webhook delivery URL. * * @param WC_Webhook $webhook */ private function update_delivery_url( $webhook ) { $delivery_url = ! empty( $_POST['webhook_delivery_url'] ) ? $_POST['webhook_delivery_url'] : ''; if ( wc_is_valid_url( $delivery_url ) ) { $webhook->set_delivery_url( $delivery_url ); } } /** * Updated the Webhook secret. * * @param WC_Webhook $webhook */ private function update_secret( $webhook ) { $secret = ! empty( $_POST['webhook_secret'] ) ? $_POST['webhook_secret'] : wp_generate_password( 50, true, true ); $webhook->set_secret( $secret ); } /** * Updated the Webhook topic. * * @param WC_Webhook $webhook */ private function update_topic( $webhook ) { if ( ! empty( $_POST['webhook_topic'] ) ) { $resource = ''; $event = ''; switch ( $_POST['webhook_topic'] ) { case 'custom' : if ( ! empty( $_POST['webhook_custom_topic'] ) ) { list( $resource, $event ) = explode( '.', wc_clean( $_POST['webhook_custom_topic'] ) ); } break; case 'action' : $resource = 'action'; $event = ! empty( $_POST['webhook_action_event'] ) ? wc_clean( $_POST['webhook_action_event'] ) : ''; break; default : list( $resource, $event ) = explode( '.', wc_clean( $_POST['webhook_topic'] ) ); break; } $topic = $resource . '.' . $event; if ( wc_is_webhook_valid_topic( $topic ) ) { $webhook->set_topic( $topic ); } } } /** * Save method. */ private function save() { if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-settings' ) ) { wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) ); } $webhook_id = absint( $_POST['webhook_id'] ); if ( ! current_user_can( 'edit_shop_webhook', $webhook_id ) ) { return; } $webhook = new WC_Webhook( $webhook_id ); // Name $this->update_name( $webhook->id ); // Status $this->update_status( $webhook ); // Delivery URL $this->update_delivery_url( $webhook ); // Secret $this->update_secret( $webhook ); // Topic $this->update_topic( $webhook ); // Update date. wp_update_post( array( 'ID' => $webhook->id, 'post_modified' => current_time( 'mysql' ) ) ); // Run actions do_action( 'woocommerce_webhook_options_save', $webhook->id ); delete_transient( 'woocommerce_webhook_ids' ); // Ping the webhook at the first time that is activated $pending_delivery = get_post_meta( $webhook->id, '_webhook_pending_delivery', true ); if ( isset( $_POST['webhook_status'] ) && 'active' === $_POST['webhook_status'] && $pending_delivery ) { $result = $webhook->deliver_ping(); if ( is_wp_error( $result ) ) { // Redirect to webhook edit page to avoid settings save actions wp_safe_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&error=' . urlencode( $result->get_error_message() ) ) ); exit(); } } // Redirect to webhook edit page to avoid settings save actions wp_safe_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&updated=1' ) ); exit(); } /** * Create Webhook. */ private function create() { if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'create-webhook' ) ) { wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) ); } if ( ! current_user_can( 'publish_shop_webhooks' ) ) { wp_die( __( 'You don\'t have permissions to create Webhooks!', 'woocommerce' ) ); } $webhook_id = wp_insert_post( array( 'post_type' => 'shop_webhook', 'post_status' => 'pending', 'ping_status' => 'closed', 'post_author' => get_current_user_id(), 'post_password' => strlen( ( $password = uniqid( 'webhook_' ) ) ) > 20 ? substr( $password, 0, 20 ) : $password, // @codingStandardsIgnoreStart 'post_title' => sprintf( __( 'Webhook created on %s', 'woocommerce' ), strftime( _x( '%b %d, %Y @ %I:%M %p', 'Webhook created on date parsed by strftime', 'woocommerce' ) ) ), // @codingStandardsIgnoreEnd 'comment_status' => 'open', ) ); if ( is_wp_error( $webhook_id ) ) { wp_die( $webhook_id->get_error_messages() ); } update_post_meta( $webhook_id, '_webhook_pending_delivery', true ); delete_transient( 'woocommerce_webhook_ids' ); // Redirect to edit page wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook_id . '&created=1' ) ); exit(); } /** * Bulk trash/delete. * * @param array $webhooks * @param bool $delete */ private function bulk_trash( $webhooks, $delete = false ) { foreach ( $webhooks as $webhook_id ) { if ( $delete ) { wp_delete_post( $webhook_id, true ); } else { wp_trash_post( $webhook_id ); } } $type = ! EMPTY_TRASH_DAYS || $delete ? 'deleted' : 'trashed'; $qty = count( $webhooks ); $status = isset( $_GET['status'] ) ? '&status=' . sanitize_text_field( $_GET['status'] ) : ''; delete_transient( 'woocommerce_webhook_ids' ); // Redirect to webhooks page wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks' . $status . '&' . $type . '=' . $qty ) ); exit(); } /** * Bulk untrash. * * @param array $webhooks */ private function bulk_untrash( $webhooks ) { foreach ( $webhooks as $webhook_id ) { wp_untrash_post( $webhook_id ); } $qty = count( $webhooks ); delete_transient( 'woocommerce_webhook_ids' ); // Redirect to webhooks page wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&status=trash&untrashed=' . $qty ) ); exit(); } /** * Bulk actions. */ private function bulk_actions() { if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'woocommerce-settings' ) ) { wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) ); } if ( ! current_user_can( 'edit_shop_webhooks' ) ) { wp_die( __( 'You don\'t have permissions to edit Webhooks!', 'woocommerce' ) ); } $webhooks = array_map( 'absint', (array) $_GET['webhook'] ); switch ( $_GET['action'] ) { case 'trash' : $this->bulk_trash( $webhooks ); break; case 'untrash' : $this->bulk_untrash( $webhooks ); break; case 'delete' : $this->bulk_trash( $webhooks, true ); break; default : break; } } /** * Empty Trash. */ private function empty_trash() { if ( empty( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'empty_trash' ) ) { wp_die( __( 'Action failed. Please refresh the page and retry.', 'woocommerce' ) ); } if ( ! current_user_can( 'delete_shop_webhooks' ) ) { wp_die( __( 'You don\'t have permissions to delete Webhooks!', 'woocommerce' ) ); } $webhooks = get_posts( array( 'post_type' => 'shop_webhook', 'ignore_sticky_posts' => true, 'nopaging' => true, 'post_status' => 'trash', 'fields' => 'ids', ) ); foreach ( $webhooks as $webhook_id ) { wp_delete_post( $webhook_id, true ); } $qty = count( $webhooks ); // Redirect to webhooks page wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&deleted=' . $qty ) ); exit(); } /** * Webhooks admin actions. */ public function actions() { if ( $this->is_webhook_settings_page() ) { // Save if ( isset( $_POST['save'] ) && isset( $_POST['webhook_id'] ) ) { $this->save(); } // Create if ( isset( $_GET['create-webhook'] ) ) { $this->create(); } // Bulk actions if ( isset( $_GET['action'] ) && isset( $_GET['webhook'] ) ) { $this->bulk_actions(); } // Empty trash if ( isset( $_GET['empty_trash'] ) ) { $this->empty_trash(); } } } /** * Page output. */ public static function page_output() { // Hide the save button $GLOBALS['hide_save_button'] = true; if ( isset( $_GET['edit-webhook'] ) ) { $webhook_id = absint( $_GET['edit-webhook'] ); $webhook = new WC_Webhook( $webhook_id ); if ( 'trash' != $webhook->post_data->post_status ) { include( 'settings/views/html-webhooks-edit.php' ); return; } } self::table_list_output(); } /** * Notices. */ public static function notices() { if ( isset( $_GET['trashed'] ) ) { $trashed = absint( $_GET['trashed'] ); WC_Admin_Settings::add_message( sprintf( _n( '1 webhook moved to the Trash.', '%d webhooks moved to the Trash.', $trashed, 'woocommerce' ), $trashed ) ); } if ( isset( $_GET['untrashed'] ) ) { $untrashed = absint( $_GET['untrashed'] ); WC_Admin_Settings::add_message( sprintf( _n( '1 webhook restored from the Trash.', '%d webhooks restored from the Trash.', $untrashed, 'woocommerce' ), $untrashed ) ); } if ( isset( $_GET['deleted'] ) ) { $deleted = absint( $_GET['deleted'] ); WC_Admin_Settings::add_message( sprintf( _n( '1 webhook permanently deleted.', '%d webhooks permanently deleted.', $deleted, 'woocommerce' ), $deleted ) ); } if ( isset( $_GET['updated'] ) ) { WC_Admin_Settings::add_message( __( 'Webhook updated successfully.', 'woocommerce' ) ); } if ( isset( $_GET['created'] ) ) { WC_Admin_Settings::add_message( __( 'Webhook created successfully.', 'woocommerce' ) ); } if ( isset( $_GET['error'] ) ) { WC_Admin_Settings::add_error( wc_clean( $_GET['error'] ) ); } } /** * Table list output. */ private static function table_list_output() { echo '<h2>' . __( 'Webhooks', 'woocommerce' ) . ' <a href="' . esc_url( wp_nonce_url( admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&create-webhook=1' ), 'create-webhook' ) ) . '" class="add-new-h2">' . __( 'Add webhook', 'woocommerce' ) . '</a></h2>'; $webhooks_table_list = new WC_Admin_Webhooks_Table_List(); $webhooks_table_list->prepare_items(); echo '<input type="hidden" name="page" value="wc-settings" />'; echo '<input type="hidden" name="tab" value="api" />'; echo '<input type="hidden" name="section" value="webhooks" />'; $webhooks_table_list->views(); $webhooks_table_list->search_box( __( 'Search webhooks', 'woocommerce' ), 'webhook' ); $webhooks_table_list->display(); } /** * Logs output. * * @param WC_Webhook $webhook */ public static function logs_output( $webhook ) { $current = isset( $_GET['log_page'] ) ? absint( $_GET['log_page'] ) : 1; $args = array( 'post_id' => $webhook->id, 'status' => 'approve', 'type' => 'webhook_delivery', 'number' => 10, ); if ( 1 < $current ) { $args['offset'] = ( $current - 1 ) * 10; } remove_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_webhook_comments' ), 10, 1 ); $logs = get_comments( $args ); add_filter( 'comments_clauses', array( 'WC_Comments', 'exclude_webhook_comments' ), 10, 1 ); if ( $logs ) { include_once( dirname( __FILE__ ) . '/settings/views/html-webhook-logs.php' ); } else { echo '<p>' . __( 'This Webhook has no log yet.', 'woocommerce' ) . '</p>'; } } /** * Get the webhook topic data. * * @return array */ public static function get_topic_data( $webhook ) { $topic = $webhook->get_topic(); $event = ''; $resource = ''; if ( $topic ) { list( $resource, $event ) = explode( '.', $topic ); if ( 'action' === $resource ) { $topic = 'action'; } elseif ( ! in_array( $resource, array( 'coupon', 'customer', 'order', 'product' ) ) ) { $topic = 'custom'; } } return array( 'topic' => $topic, 'event' => $event, 'resource' => $resource, ); } /** * Get the logs navigation. * * @param int $total * * @return string */ public static function get_logs_navigation( $total, $webhook ) { $pages = ceil( $total / 10 ); $current = isset( $_GET['log_page'] ) ? absint( $_GET['log_page'] ) : 1; $html = '<div class="webhook-logs-navigation">'; $html .= '<p class="info" style="float: left;"><strong>'; $html .= sprintf( '%s &ndash; Page %d of %d', _n( '1 item', sprintf( '%d items', $total ), $total, 'woocommerce' ), $current, $pages ); $html .= '</strong></p>'; if ( 1 < $pages ) { $html .= '<p class="tools" style="float: right;">'; if ( 1 == $current ) { $html .= '<button class="button-primary" disabled="disabled">' . __( '&lsaquo; Previous', 'woocommerce' ) . '</button> '; } else { $html .= '<a class="button-primary" href="' . admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&log_page=' . ( $current - 1 ) ) . '#webhook-logs">' . __( '&lsaquo; Previous', 'woocommerce' ) . '</a> '; } if ( $pages == $current ) { $html .= '<button class="button-primary" disabled="disabled">' . __( 'Next &rsaquo;', 'woocommerce' ) . '</button>'; } else { $html .= '<a class="button-primary" href="' . admin_url( 'admin.php?page=wc-settings&tab=api&section=webhooks&edit-webhook=' . $webhook->id . '&log_page=' . ( $current + 1 ) ) . '#webhook-logs">' . __( 'Next &rsaquo;', 'woocommerce' ) . '</a>'; } $html .= '</p>'; } $html .= '<div class="clear"></div></div>'; return $html; } } new WC_Admin_Webhooks();
bryceadams/woocommerce
includes/admin/class-wc-admin-webhooks.php
PHP
gpl-3.0
14,839
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package net.sareweb.emg.service; import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil; import com.liferay.portal.kernel.util.ReferenceRegistry; import com.liferay.portal.service.InvokableService; /** * Provides the remote service utility for Draw. This utility wraps * {@link net.sareweb.emg.service.impl.DrawServiceImpl} and is the * primary access point for service operations in application layer code running * on a remote server. Methods of this service are expected to have security * checks based on the propagated JAAS credentials because this service can be * accessed remotely. * * @author A.Galdos * @see DrawService * @see net.sareweb.emg.service.base.DrawServiceBaseImpl * @see net.sareweb.emg.service.impl.DrawServiceImpl * @generated */ public class DrawServiceUtil { /* * NOTE FOR DEVELOPERS: * * Never modify this class directly. Add custom service methods to {@link net.sareweb.emg.service.impl.DrawServiceImpl} and rerun ServiceBuilder to regenerate this class. */ /** * Returns the Spring bean ID for this bean. * * @return the Spring bean ID for this bean */ public static java.lang.String getBeanIdentifier() { return getService().getBeanIdentifier(); } /** * Sets the Spring bean ID for this bean. * * @param beanIdentifier the Spring bean ID for this bean */ public static void setBeanIdentifier(java.lang.String beanIdentifier) { getService().setBeanIdentifier(beanIdentifier); } public static java.lang.Object invokeMethod(java.lang.String name, java.lang.String[] parameterTypes, java.lang.Object[] arguments) throws java.lang.Throwable { return getService().invokeMethod(name, parameterTypes, arguments); } public static java.util.List<net.sareweb.emg.model.Draw> getDrawsNewerThanDate( long date) throws com.liferay.portal.kernel.exception.SystemException { return getService().getDrawsNewerThanDate(date); } public static void clearService() { _service = null; } public static DrawService getService() { if (_service == null) { InvokableService invokableService = (InvokableService)PortletBeanLocatorUtil.locate(ClpSerializer.getServletContextName(), DrawService.class.getName()); if (invokableService instanceof DrawService) { _service = (DrawService)invokableService; } else { _service = new DrawServiceClp(invokableService); } ReferenceRegistry.registerReference(DrawServiceUtil.class, "_service"); } return _service; } /** * @deprecated As of 6.2.0 */ public void setService(DrawService service) { } private static DrawService _service; }
aritzg/EuroMillionGame-portlet
docroot/WEB-INF/service/net/sareweb/emg/service/DrawServiceUtil.java
Java
gpl-3.0
3,192
#define ICON_SIZE QSize(48,48) #define EXPANDED_HEIGHT 413 #define UNEXPANDED_HEIGHT 137 #include "mainpage.h" #include "ui_options.h" #include <QWidget> #include <QComboBox> #include <QHBoxLayout> #include <QVBoxLayout> #include <QGroupBox> #include <QCheckBox> #include <QLineEdit> #include <QMimeData> #include <QLabel> #include <QToolBar> #include <QAction> #include <QToolButton> #include <QFileDialog> #include <QUrl> #include <SMasterIcons> #include <SDeviceList> #include <SComboBox> #include <SDialogTools> class MainPagePrivate { public: QVBoxLayout *layout; QHBoxLayout *image_layout; QToolButton *open_btn; QLineEdit *src_line; SComboBox *dst_combo; QLabel *label; QToolBar *toolbar; QAction *go_action; QAction *more_action; SDeviceList *device_list; Ui::OptionsUi *options_ui; QWidget *options_widget; QList<SDeviceItem> devices; }; MainPage::MainPage( SApplication *parent ) : SPage( tr("Image Burner") , parent , SPage::WindowedPage ) { p = new MainPagePrivate; p->device_list = new SDeviceList( this ); p->src_line = new QLineEdit(); p->src_line->setReadOnly( true ); p->src_line->setFixedHeight( 28 ); p->src_line->setPlaceholderText( tr("Please select a Disc Image") ); p->src_line->setFocusPolicy( Qt::NoFocus ); p->open_btn = new QToolButton(); p->open_btn->setIcon( SMasterIcons::icon( ICON_SIZE , "document-open.png" ) ); p->open_btn->setFixedSize( 28 , 28 ); p->image_layout = new QHBoxLayout(); p->image_layout->addWidget( p->src_line ); p->image_layout->addWidget( p->open_btn ); p->dst_combo = new SComboBox(); p->dst_combo->setIconSize( QSize(22,22) ); p->label = new QLabel(); p->label->setText( tr("To") ); p->toolbar = new QToolBar(); p->toolbar->setToolButtonStyle( Qt::ToolButtonTextBesideIcon ); p->toolbar->setStyleSheet( "QToolBar{ border-style:solid ; margin:0px }" ); p->options_widget = new QWidget(); p->options_ui = new Ui::OptionsUi; p->options_ui->setupUi( p->options_widget ); p->layout = new QVBoxLayout( this ); p->layout->addLayout( p->image_layout ); p->layout->addWidget( p->label ); p->layout->addWidget( p->dst_combo ); p->layout->addWidget( p->options_widget ); p->layout->addWidget( p->toolbar ); p->layout->setContentsMargins( 10 , 10 , 10 , 10 ); setFixedWidth( 413 ); setFixedHeight( EXPANDED_HEIGHT ); p->dst_combo->setCurrentIndex( 0 ); connect( p->device_list , SIGNAL(deviceDetected(SDeviceItem)) , SLOT(deviceDetected(SDeviceItem)) ); connect( p->open_btn , SIGNAL(clicked()) , SLOT(select_src_image()) ); connect( p->dst_combo , SIGNAL(currentIndexChanged(int)) , SLOT(device_index_changed(int)) ); connect( p->options_ui->scan_check , SIGNAL(toggled(bool)) , p->options_ui->scan_widget , SLOT(setVisible(bool)) ); p->options_ui->scan_check->setChecked( false ); p->device_list->refresh(); init_actions(); more_prev(); setAcceptDrops( true ); } void MainPage::init_actions() { QWidget *spr1 = new QWidget(); spr1->setSizePolicy( QSizePolicy::Expanding , QSizePolicy::Minimum ); p->go_action = new QAction( SMasterIcons::icon(ICON_SIZE,"tools-media-optical-burn.png") , tr("Go") , this ); p->more_action = new QAction( SMasterIcons::icon(ICON_SIZE,"edit-rename.png") , tr("More") , this ); p->toolbar->addAction( p->more_action ); p->toolbar->addWidget( spr1 ); p->toolbar->addAction( p->go_action ); connect( p->go_action , SIGNAL(triggered()) , SLOT(go_prev()) ); connect( p->more_action , SIGNAL(triggered()) , SLOT(more_prev()) ); } void MainPage::deviceDetected( const SDeviceItem & device ) { if( !p->devices.contains(device) ) { p->devices << device; p->dst_combo->insertItem( p->devices.count()-1 , SMasterIcons::icon(ICON_SIZE,"drive-optical.png") , device.name() ); } else { int index = p->devices.indexOf( device ); p->devices.removeAt( index ); p->devices.insert( index , device ); p->dst_combo->setItemText( index , device.name() ); device_index_changed( p->dst_combo->currentIndex() ); } } void MainPage::device_index_changed( int index ) { if( index < 0 ) return ; const SDeviceItem & device = p->devices.at( index ); const SDiscFeatures & disc = device.currentDiscFeatures(); QList<int> list; if( disc.volume_disc_type_str.contains("blu",Qt::CaseInsensitive) ) list = device.deviceFeatures().bluray_speed_list; else if( disc.volume_disc_type_str.contains("dvd",Qt::CaseInsensitive) ) list = device.deviceFeatures().dvd_speed_list; else list = device.deviceFeatures().cd_speed_list; if( list.isEmpty() ) list << 2 << 1; p->options_ui->speed_combo->clear(); for( int i=0 ; i<list.count() ; i++ ) p->options_ui->speed_combo->addItem( QString::number(list.at(i)) ); } QString MainPage::sourceImage() const { return p->src_line->text(); } const SDeviceItem & MainPage::destinationDevice() const { return p->devices.at( p->dst_combo->currentIndex() ); } void MainPage::go_prev() { SDialogTools::getTimer( this , tr("Your Request will be starting after count down.") , 7000 , this , SIGNAL(go()) ); } void MainPage::more_prev() { if( height() == UNEXPANDED_HEIGHT ) { setFixedHeight( EXPANDED_HEIGHT ); p->options_widget->show(); p->more_action->setText( tr("Less") ); } else { setFixedHeight( UNEXPANDED_HEIGHT ); p->options_widget->hide(); p->more_action->setText( tr("More") ); } setDefaultOptions(); } void MainPage::setDefaultOptions() { int index = p->dst_combo->currentIndex(); if( index < 0 ) return ; const SDeviceItem & device = p->devices.at(index); const SDiscFeatures & disc = device.currentDiscFeatures(); /*! -------------------- Scanner Options -------------------------*/ p->options_ui->scan_line->setText( disc.volume_label_str ); } bool MainPage::scan() const { return p->options_ui->scan_check->isChecked(); } int MainPage::copiesNumber() const { return p->options_ui->copies_spin->value(); } int MainPage::speed() const { return p->options_ui->speed_combo->currentText().toInt(); } bool MainPage::eject() const { return p->options_ui->eject_check->isChecked(); } bool MainPage::dummy() const { return p->options_ui->dummy_check->isChecked(); } bool MainPage::remove() const { return p->options_ui->remove_check->isChecked(); } QString MainPage::scanName() const { return p->options_ui->scan_line->text(); } void MainPage::setSourceImage( const QString & file ) { p->src_line->setText( file ); } void MainPage::select_src_image() { SDialogTools::getOpenFileName( this , this , SLOT(setSourceImage(QString)) ); } void MainPage::setDestinationDevice( const QString & bus_len_id ) { for( int i=0 ; i<p->devices.count() ; i++ ) if( p->devices.at(i).toQString() == bus_len_id ) { p->dst_combo->setCurrentIndex( i ); return ; } } void MainPage::setScan( const QString & str ) { p->options_ui->scan_check->setChecked( !str.isEmpty() ); p->options_ui->scan_line->setText( str ); } void MainPage::setCopiesNumber( int value ) { p->options_ui->copies_spin->setValue( value ); } void MainPage::setSpeed( int speed ) { p->options_ui->speed_combo->setEditText( QString::number(speed) ); } void MainPage::setEject( bool stt ) { p->options_ui->eject_check->setChecked( stt ); } void MainPage::setDummy( bool stt ) { p->options_ui->dummy_check->setChecked( stt ); } void MainPage::setRemove( bool stt ) { p->options_ui->remove_check->setChecked( stt ); } void MainPage::dropEvent( QDropEvent *event ) { QList<QUrl> list = event->mimeData()->urls(); QString url_path = list.first().path(); #ifdef Q_OS_WIN32 if( url_path[0] == '/' ) url_path.remove( 0 , 1 ); #endif setSourceImage( url_path ); event->acceptProposedAction(); QWidget::dropEvent( event ); } void MainPage::dragEnterEvent( QDragEnterEvent *event ) { if( !event->mimeData()->hasUrls() ) return; QList<QUrl> list = event->mimeData()->urls(); if( list.count() != 1 ) event->ignore(); else event->acceptProposedAction(); QWidget::dragEnterEvent( event ); } MainPage::~MainPage() { delete p->options_ui; delete p; }
realbardia/silicon
SApplications/ImageBurner/mainpage.cpp
C++
gpl-3.0
8,814
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.optimizer; import org.mozilla.javascript.ArrowFunction; import org.mozilla.javascript.Callable; import org.mozilla.javascript.ConsString; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.ES6Generator; import org.mozilla.javascript.Function; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.NativeFunction; import org.mozilla.javascript.NativeGenerator; import org.mozilla.javascript.NativeIterator; import org.mozilla.javascript.Script; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.Undefined; /** * <p>OptRuntime class.</p> * * * */ public final class OptRuntime extends ScriptRuntime { /** Constant <code>oneObj</code> */ public static final Double oneObj = Double.valueOf(1.0); /** Constant <code>minusOneObj</code> */ public static final Double minusOneObj = Double.valueOf(-1.0); /** * Implement ....() call shrinking optimizer code. * * @param fun a {@link org.mozilla.javascript.Callable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object call0(Callable fun, Scriptable thisObj, Context cx, Scriptable scope) { return fun.call(cx, scope, thisObj, ScriptRuntime.emptyArgs); } /** * Implement ....(arg) call shrinking optimizer code. * * @param fun a {@link org.mozilla.javascript.Callable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @param arg0 a {@link java.lang.Object} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object call1(Callable fun, Scriptable thisObj, Object arg0, Context cx, Scriptable scope) { return fun.call(cx, scope, thisObj, new Object[] { arg0 } ); } /** * Implement ....(arg0, arg1) call shrinking optimizer code. * * @param fun a {@link org.mozilla.javascript.Callable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @param arg0 a {@link java.lang.Object} object. * @param arg1 a {@link java.lang.Object} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object call2(Callable fun, Scriptable thisObj, Object arg0, Object arg1, Context cx, Scriptable scope) { return fun.call(cx, scope, thisObj, new Object[] { arg0, arg1 }); } /** * Implement ....(arg0, arg1, ...) call shrinking optimizer code. * * @param fun a {@link org.mozilla.javascript.Callable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @param args an array of {@link java.lang.Object} objects. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object callN(Callable fun, Scriptable thisObj, Object[] args, Context cx, Scriptable scope) { return fun.call(cx, scope, thisObj, args); } /** * Implement name(args) call shrinking optimizer code. * * @param args an array of {@link java.lang.Object} objects. * @param name a {@link java.lang.String} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object callName(Object[] args, String name, Context cx, Scriptable scope) { Callable f = getNameFunctionAndThis(name, cx, scope); Scriptable thisObj = lastStoredScriptable(cx); return f.call(cx, scope, thisObj, args); } /** * Implement name() call shrinking optimizer code. * * @param name a {@link java.lang.String} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object callName0(String name, Context cx, Scriptable scope) { Callable f = getNameFunctionAndThis(name, cx, scope); Scriptable thisObj = lastStoredScriptable(cx); return f.call(cx, scope, thisObj, ScriptRuntime.emptyArgs); } /** * Implement x.property() call shrinking optimizer code. * * @param value a {@link java.lang.Object} object. * @param property a {@link java.lang.String} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link java.lang.Object} object. */ public static Object callProp0(Object value, String property, Context cx, Scriptable scope) { Callable f = getPropFunctionAndThis(value, property, cx, scope); Scriptable thisObj = lastStoredScriptable(cx); return f.call(cx, scope, thisObj, ScriptRuntime.emptyArgs); } /** * <p>add.</p> * * @param val1 a {@link java.lang.Object} object. * @param val2 a double. * @return a {@link java.lang.Object} object. */ public static Object add(Object val1, double val2) { if (val1 instanceof Scriptable) val1 = ((Scriptable) val1).getDefaultValue(null); if (!(val1 instanceof CharSequence)) return wrapDouble(toNumber(val1) + val2); return new ConsString((CharSequence)val1, toString(val2)); } /** {@inheritDoc} */ public static Object add(double val1, Object val2) { if (val2 instanceof Scriptable) val2 = ((Scriptable) val2).getDefaultValue(null); if (!(val2 instanceof CharSequence)) return wrapDouble(toNumber(val2) + val1); return new ConsString(toString(val1), (CharSequence)val2); } /** {@inheritDoc} */ @Deprecated public static Object elemIncrDecr(Object obj, double index, Context cx, int incrDecrMask) { return elemIncrDecr(obj, index, cx, getTopCallScope(cx), incrDecrMask); } /** {@inheritDoc} */ public static Object elemIncrDecr(Object obj, double index, Context cx, Scriptable scope, int incrDecrMask) { return ScriptRuntime.elemIncrDecr(obj, Double.valueOf(index), cx, scope, incrDecrMask); } /** * <p>padStart.</p> * * @param currentArgs an array of {@link java.lang.Object} objects. * @param count a int. * @return an array of {@link java.lang.Object} objects. */ public static Object[] padStart(Object[] currentArgs, int count) { Object[] result = new Object[currentArgs.length + count]; System.arraycopy(currentArgs, 0, result, count, currentArgs.length); return result; } /** * <p>initFunction.</p> * * @param fn a {@link org.mozilla.javascript.NativeFunction} object. * @param functionType a int. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @param cx a {@link org.mozilla.javascript.Context} object. */ public static void initFunction(NativeFunction fn, int functionType, Scriptable scope, Context cx) { ScriptRuntime.initFunction(cx, scope, fn, functionType, false); } /** * <p>bindThis.</p> * * @param fn a {@link org.mozilla.javascript.NativeFunction} object. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link org.mozilla.javascript.Function} object. */ public static Function bindThis(NativeFunction fn, Context cx, Scriptable scope, Scriptable thisObj) { return new ArrowFunction(cx, scope, fn, thisObj); } /** {@inheritDoc} */ public static Object callSpecial(Context cx, Callable fun, Scriptable thisObj, Object[] args, Scriptable scope, Scriptable callerThis, int callType, String fileName, int lineNumber) { return ScriptRuntime.callSpecial(cx, fun, thisObj, args, scope, callerThis, callType, fileName, lineNumber); } /** * <p>newObjectSpecial.</p> * * @param cx a {@link org.mozilla.javascript.Context} object. * @param fun a {@link java.lang.Object} object. * @param args an array of {@link java.lang.Object} objects. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @param callerThis a {@link org.mozilla.javascript.Scriptable} object. * @param callType a int. * @return a {@link java.lang.Object} object. */ public static Object newObjectSpecial(Context cx, Object fun, Object[] args, Scriptable scope, Scriptable callerThis, int callType) { return ScriptRuntime.newSpecial(cx, fun, args, scope, callType); } /** * <p>wrapDouble.</p> * * @param num a double. * @return a {@link java.lang.Double} object. */ public static Double wrapDouble(double num) { if (num == 0.0) { if (1 / num > 0) { // +0.0 return zeroObj; } } else if (num == 1.0) { return oneObj; } else if (num == -1.0) { return minusOneObj; } else if (Double.isNaN(num)) { return NaNobj; } return Double.valueOf(num); } static String encodeIntArray(int[] array) { // XXX: this extremely inefficient for small integers if (array == null) { return null; } int n = array.length; char[] buffer = new char[1 + n * 2]; buffer[0] = 1; for (int i = 0; i != n; ++i) { int value = array[i]; int shift = 1 + i * 2; buffer[shift] = (char)(value >>> 16); buffer[shift + 1] = (char)value; } return new String(buffer); } private static int[] decodeIntArray(String str, int arraySize) { // XXX: this extremely inefficient for small integers if (arraySize == 0) { if (str != null) throw new IllegalArgumentException(); return null; } if (str.length() != 1 + arraySize * 2 && str.charAt(0) != 1) { throw new IllegalArgumentException(); } int[] array = new int[arraySize]; for (int i = 0; i != arraySize; ++i) { int shift = 1 + i * 2; array[i] = (str.charAt(shift) << 16) | str.charAt(shift + 1); } return array; } /** * <p>newArrayLiteral.</p> * * @param objects an array of {@link java.lang.Object} objects. * @param encodedInts a {@link java.lang.String} object. * @param skipCount a int. * @param cx a {@link org.mozilla.javascript.Context} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @return a {@link org.mozilla.javascript.Scriptable} object. */ public static Scriptable newArrayLiteral(Object[] objects, String encodedInts, int skipCount, Context cx, Scriptable scope) { int[] skipIndexces = decodeIntArray(encodedInts, skipCount); return newArrayLiteral(objects, skipIndexces, cx, scope); } /** * <p>main.</p> * * @param script a {@link org.mozilla.javascript.Script} object. * @param args an array of {@link java.lang.String} objects. */ public static void main(final Script script, final String[] args) { ContextFactory.getGlobal().call(cx -> { ScriptableObject global = getGlobal(cx); // get the command line arguments and define "arguments" // array in the top-level object Object[] argsCopy = new Object[args.length]; System.arraycopy(args, 0, argsCopy, 0, args.length); Scriptable argsObj = cx.newArray(global, argsCopy); global.defineProperty("arguments", argsObj, ScriptableObject.DONTENUM); script.exec(cx, global); return null; }); } /** * <p>throwStopIteration.</p> * * @param scope a {@link java.lang.Object} object. * @param genState a {@link java.lang.Object} object. */ public static void throwStopIteration(Object scope, Object genState) { Object value = getGeneratorReturnValue(genState); Object si = (value == Undefined.instance) ? NativeIterator.getStopIterationObject((Scriptable)scope) : new NativeIterator.StopIteration(value); throw new JavaScriptException(si, "", 0); } /** * <p>createNativeGenerator.</p> * * @param funObj a {@link org.mozilla.javascript.NativeFunction} object. * @param scope a {@link org.mozilla.javascript.Scriptable} object. * @param thisObj a {@link org.mozilla.javascript.Scriptable} object. * @param maxLocals a int. * @param maxStack a int. * @return a {@link org.mozilla.javascript.Scriptable} object. */ public static Scriptable createNativeGenerator(NativeFunction funObj, Scriptable scope, Scriptable thisObj, int maxLocals, int maxStack) { GeneratorState gs = new GeneratorState(thisObj, maxLocals, maxStack); if (Context.getCurrentContext().getLanguageVersion() >= Context.VERSION_ES6) { return new ES6Generator(scope, funObj, gs); } else { return new NativeGenerator(scope, funObj, gs); } } /** * <p>getGeneratorStackState.</p> * * @param obj a {@link java.lang.Object} object. * @return an array of {@link java.lang.Object} objects. */ public static Object[] getGeneratorStackState(Object obj) { GeneratorState rgs = (GeneratorState) obj; if (rgs.stackState == null) rgs.stackState = new Object[rgs.maxStack]; return rgs.stackState; } /** * <p>getGeneratorLocalsState.</p> * * @param obj a {@link java.lang.Object} object. * @return an array of {@link java.lang.Object} objects. */ public static Object[] getGeneratorLocalsState(Object obj) { GeneratorState rgs = (GeneratorState) obj; if (rgs.localsState == null) rgs.localsState = new Object[rgs.maxLocals]; return rgs.localsState; } /** * <p>setGeneratorReturnValue.</p> * * @param obj a {@link java.lang.Object} object. * @param val a {@link java.lang.Object} object. */ public static void setGeneratorReturnValue(Object obj, Object val) { GeneratorState rgs = (GeneratorState) obj; rgs.returnValue = val; } /** * <p>getGeneratorReturnValue.</p> * * @param obj a {@link java.lang.Object} object. * @return a {@link java.lang.Object} object. */ public static Object getGeneratorReturnValue(Object obj) { GeneratorState rgs = (GeneratorState) obj; return (rgs.returnValue == null ? Undefined.instance : rgs.returnValue); } public static class GeneratorState { static final String CLASS_NAME = "org/mozilla/javascript/optimizer/OptRuntime$GeneratorState"; @SuppressWarnings("unused") public int resumptionPoint; static final String resumptionPoint_NAME = "resumptionPoint"; static final String resumptionPoint_TYPE = "I"; @SuppressWarnings("unused") public Scriptable thisObj; static final String thisObj_NAME = "thisObj"; static final String thisObj_TYPE = "Lorg/mozilla/javascript/Scriptable;"; Object[] stackState; Object[] localsState; int maxLocals; int maxStack; Object returnValue; GeneratorState(Scriptable thisObj, int maxLocals, int maxStack) { this.thisObj = thisObj; this.maxLocals = maxLocals; this.maxStack = maxStack; } } }
oswetto/LoboEvolution
LoboParser/src/main/java/org/mozilla/javascript/optimizer/OptRuntime.java
Java
gpl-3.0
18,041
#include "relativelayout.h" #include <QDebug> RelativeLayout::RelativeLayout(View *parent) : View(parent) { // By default, QQuickItem does not draw anything. If you subclass // QQuickItem to create a visual item, you will need to uncomment the // following line and re-implement updatePaintNode() // setFlag(ItemHasContents, true); } RelativeLayout::~RelativeLayout() { } void RelativeLayout::inflate() { View::inflate(); qDebug() << "Start rellayout inflate"; if (m_context != NULL && m_context->isValid()) { m_object = new QAndroidJniObject("android/widget/RelativeLayout", "(Landroid/content/Context;)V", m_context->object()); qDebug() << m_object->isValid(); qDebug() << m_object->toString(); foreach (QObject *child, m_children) { qDebug() << "add children to layout"; if (child != NULL) { qDebug() << child->metaObject()->className(); child->dumpObjectInfo(); if (child->inherits("View")) m_object->callMethod<void>("addView", "(Landroid/view/View;)V", qobject_cast<View*>(child)->object()->object()); } } } else qDebug() << "No context, cannot inflate!"; }
achipa/outqross_blog
2_OutQross.Android_components/relativelayout.cpp
C++
gpl-3.0
1,257
/* Copyright 2012 SINTEF ICT, Applied Mathematics. This file is part of the Open Porous Media project (OPM). OPM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OPM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OPM. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPM_INCOMPTPFA_HEADER_INCLUDED #define OPM_INCOMPTPFA_HEADER_INCLUDED #include <opm/core/simulator/SimulatorState.hpp> #include <opm/core/pressure/tpfa/ifs_tpfa.h> #include <vector> struct UnstructuredGrid; struct Wells; struct FlowBoundaryConditions; namespace Opm { class IncompPropertiesInterface; class RockCompressibility; class LinearSolverInterface; class WellState; class SimulatoreState; /// Encapsulating a tpfa pressure solver for the incompressible-fluid case. /// Supports gravity, wells controlled by bhp or reservoir rates, /// boundary conditions and simple sources as driving forces. /// Rock compressibility can be included, and necessary nonlinear /// iterations are handled. /// Below we use the shortcuts D for the number of dimensions, N /// for the number of cells and F for the number of faces. class IncompTpfa { public: /// Construct solver for incompressible case. /// \param[in] grid A 2d or 3d grid. /// \param[in] props Rock and fluid properties. /// \param[in] linsolver Linear solver to use. /// \param[in] gravity Gravity vector. If non-null, the array should /// have D elements. /// \param[in] wells The wells argument. Will be used in solution, /// is ignored if NULL. /// Note: this class observes the well object, and /// makes the assumption that the well topology /// and completions does not change during the /// run. However, controls (only) are allowed /// to change. /// \param[in] src Source terms. May be empty(). /// \param[in] bcs Boundary conditions, treat as all noflow if null. IncompTpfa(const UnstructuredGrid& grid, const IncompPropertiesInterface& props, LinearSolverInterface& linsolver, const double* gravity, const Wells* wells, const std::vector<double>& src, const FlowBoundaryConditions* bcs); /// Construct solver, possibly with rock compressibility. /// \param[in] grid A 2d or 3d grid. /// \param[in] props Rock and fluid properties. /// \param[in] rock_comp_props Rock compressibility properties. May be null. /// \param[in] linsolver Linear solver to use. /// \param[in] residual_tol Solution accepted if inf-norm of residual is smaller. /// \param[in] change_tol Solution accepted if inf-norm of change in pressure is smaller. /// \param[in] maxiter Maximum acceptable number of iterations. /// \param[in] gravity Gravity vector. If non-null, the array should /// have D elements. /// \param[in] wells The wells argument. Will be used in solution, /// is ignored if NULL. /// Note: this class observes the well object, and /// makes the assumption that the well topology /// and completions does not change during the /// run. However, controls (only) are allowed /// to change. /// \param[in] src Source terms. May be empty(). /// \param[in] bcs Boundary conditions, treat as all noflow if null. IncompTpfa(const UnstructuredGrid& grid, const IncompPropertiesInterface& props, const RockCompressibility* rock_comp_props, LinearSolverInterface& linsolver, const double residual_tol, const double change_tol, const int maxiter, const double* gravity, const Wells* wells, const std::vector<double>& src, const FlowBoundaryConditions* bcs); /// Destructor. virtual ~IncompTpfa(); /// Solve the pressure equation. If there is no pressure /// dependency introduced by rock compressibility effects, /// the equation is linear, and it is solved directly. /// Otherwise, the nonlinear equations ares solved by a /// Newton-Raphson scheme. /// May throw an exception if the number of iterations /// exceed maxiter (set in constructor). void solve(const double dt, SimulatorState& state, WellState& well_state); /// Expose read-only reference to internal half-transmissibility. const std::vector<double>& getHalfTrans() const { return htrans_; } protected: // Solve with no rock compressibility (linear eqn). void solveIncomp(const double dt, SimulatorState& state, WellState& well_state); // Solve with rock compressibility (nonlinear eqn). void solveRockComp(const double dt, SimulatorState& state, WellState& well_state); private: // Helper functions. void computeStaticData(); virtual void computePerSolveDynamicData(const double dt, const SimulatorState& state, const WellState& well_state); void computePerIterationDynamicData(const double dt, const SimulatorState& state, const WellState& well_state); void assemble(const double dt, const SimulatorState& state, const WellState& well_state); void solveIncrement(); double residualNorm() const; double incrementNorm() const; void computeResults(SimulatorState& state, WellState& well_state) const; protected: // ------ Data that will remain unmodified after construction. ------ const UnstructuredGrid& grid_; const IncompPropertiesInterface& props_; const RockCompressibility* rock_comp_props_; const LinearSolverInterface& linsolver_; const double residual_tol_; const double change_tol_; const int maxiter_; const double* gravity_; // May be NULL const Wells* wells_; // May be NULL, outside may modify controls (only) between calls to solve(). const std::vector<double>& src_; const FlowBoundaryConditions* bcs_; std::vector<double> htrans_; std::vector<double> gpress_; std::vector<int> allcells_; // ------ Data that will be modified for every solve. ------ std::vector<double> trans_ ; std::vector<double> wdp_; std::vector<double> totmob_; std::vector<double> omega_; std::vector<double> gpress_omegaweighted_; std::vector<double> initial_porevol_; struct ifs_tpfa_forces forces_; // ------ Data that will be modified for every solver iteration. ------ std::vector<double> porevol_; std::vector<double> rock_comp_; std::vector<double> pressures_; // ------ Internal data for the ifs_tpfa solver. ------ struct ifs_tpfa_data* h_; }; } // namespace Opm #endif // OPM_INCOMPTPFA_HEADER_INCLUDED
jokva/opm-core
opm/core/pressure/IncompTpfa.hpp
C++
gpl-3.0
8,431
<?php /** * Functions for building the page content for each codex page * * @since 1.0.0 * @package Codex_Creator */ /** * Get and format content output for summary section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_summary_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_summary', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_summary_content', $content, $post_id, $title); } /** * Get and format content output for description section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_description_content($post_id, $title) { $content = ''; //$meta_value = get_post_meta($post_id, 'cdxc_description', true); $meta_value = get_post_meta($post_id, 'cdxc_meta_docblock', true); if (!$meta_value) { return ''; } $phpdoc = new \phpDocumentor\Reflection\DocBlock($meta_value); $line_arr = explode(PHP_EOL, $phpdoc->getLongDescription()->getContents()); $line_arr = array_values(array_filter($line_arr)); if (empty($line_arr)) { return ''; } $sample_open = false; $sample_close = false; foreach ($line_arr as $key=>$line) { //check for code sample opening if($line=='' && substr($line_arr[$key+1], 0, 3) === ' '){// we have found a opening code sample $sample_open = $key+1; } //check for code sample closing if($sample_open && substr($line_arr[$key], 0, 3) === ' '){// we have found a closing code sample $sample_close = $key; } } if ($sample_open && $sample_close) { $line_arr[$sample_open] = CDXC_SAMPLE_OPEN.$line_arr[$sample_open]; $line_arr[$sample_open] = $line_arr[$sample_close].CDXC_SAMPLE_CLOSE; } $meta_value = implode(PHP_EOL, $line_arr); $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_description_content', $content, $post_id, $title); } /** * Get and format content output for usage section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_usage_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_usage', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_usage_content', $content, $post_id, $title); } /** * Get and format content output for access section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_access_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_access', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_access_content', $content, $post_id, $title); } /** * Get and format content output for deprecated section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_deprecated_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_deprecated', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_deprecated_content', $content, $post_id, $title); } /** * Get and format content output for global section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_global_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_global', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $value) { $value = cdxc_global_content_helper($value); $content .= CDXC_CONTENT_START . $value . CDXC_CONTENT_END; } } else { $meta_value = cdxc_global_content_helper($meta_value); $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; } /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_global_content', $content, $post_id, $title); } /** * Arrange a param value into a usable HTML output. * * @since 1.0.0 * @package Codex_Creator * @param string $param The param value to be used. * @return string Formatted HTML on success. */ function cdxc_global_content_helper($param) { if($param==''){return '';} $output = ''; $param_arr = explode(' ',$param); $param_arr = array_values(array_filter($param_arr)); //print_r($param_arr); $output .= '<dl>'; //variable if(!empty($param_arr[1])){ $var = $param_arr[1]; $output .= '<dt><b>'.$var.'</b></dt>'; unset($param_arr[1]); } $output .= '<dd>'; //datatype if(!empty($param_arr[0])){ $datatype = $param_arr[0]; $link_open = ''; $link_close = ''; if($datatype=='string' || $datatype=='String'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#String" target="_blank">'; $link_close = '</a>'; } if($datatype=='int'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Integer" target="_blank">'; $link_close = '</a>'; } if($datatype=='bool'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Boolean" target="_blank">'; $link_close = '</a>'; } $output .= '('.$link_open.'<i>'.$datatype.'</i>'.$link_close.') '; unset($param_arr[0]); } //optional $optional = '(<i>'.__('required', CDXC_TEXTDOMAIN).'</i>)'; if(!empty($param_arr[2])){ $opt = $param_arr[2]; if($opt=='Optional.' || $opt=='optional.'){ $optional = '(<i>'.__('optional', CDXC_TEXTDOMAIN).'</i>)'; unset($param_arr[2]); } } $output .= $optional.' '; //we now split into descriptions. $param_str = implode(' ',$param_arr); $param_arr = explode('.',$param_str); $param_arr = array_filter($param_arr); //print_r($param_arr); //description/default $default = '<dl><dd>'.__('Default', CDXC_TEXTDOMAIN).': <i>'.__('None', CDXC_TEXTDOMAIN).'</i></dd></dl>'; foreach ($param_arr as $bit) { $bit = trim($bit); //echo '#'.$bit.'#'; if(substr( $bit, 0, 7) === 'Default'){ $bits = explode('Default',$bit); $default = '<dl><dd>'.__('Default', CDXC_TEXTDOMAIN).': <i>'.$bits[1].'</i></dd></dl>'; }else{ $output .= $bit.'. '; } } $output .= $default; $output .= '</dd>'; $output .= '</dl>'; return $output; } /** * Get and format content output for internal section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_internal_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_internal', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_internal_content', $content, $post_id, $title); } /** * Get and format content output for ignore section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_ignore_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_ignore', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_ignore_content', $content, $post_id, $title); } /** * Get and format content output for link section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_link_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_link', true); if (!$meta_value) { return; } /* * @todo add checking for parsing links */ $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START ."<a href='$meta_value' >".$meta_value . "</a>".CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_link_content', $content, $post_id, $title); } /** * Get and format content output for method section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_method_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_method', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_method_content', $content, $post_id, $title); } /** * Get and format content output for package section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_package_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_package', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_package_content', $content, $post_id, $title); } /** * Get and format content output for param section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_param_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_param', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $value) { $value = cdxc_param_content_helper($value); $content .= CDXC_CONTENT_START . $value . CDXC_CONTENT_END; } } else { $meta_value = cdxc_param_content_helper($meta_value); $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; } /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_param_content', $content, $post_id, $title); } /** * Arrange a param value into a usable HTML output. * * @since 1.0.0 * @package Codex_Creator * @param string $param The param value to be used. * @return string Formatted HTML on success. */ function cdxc_param_content_helper($param) { if($param==''){return '';} $output = ''; $param_arr = explode(' ',$param); $param_arr = array_values(array_filter($param_arr)); //print_r($param_arr); $output .= '<dl>'; //variable if(!empty($param_arr[1])){ $var = $param_arr[1]; $output .= '<dt><b>'.$var.'</b></dt>'; unset($param_arr[1]); } $output .= '<dd>'; //datatype if(!empty($param_arr[0])){ $datatype = $param_arr[0]; $link_open = ''; $link_close = ''; if($datatype=='string' || $datatype=='String'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#String" target="_blank">'; $link_close = '</a>'; } if($datatype=='int'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Integer" target="_blank">'; $link_close = '</a>'; } if($datatype=='bool'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Boolean" target="_blank">'; $link_close = '</a>'; } $output .= '('.$link_open.'<i>'.$datatype.'</i>'.$link_close.') '; unset($param_arr[0]); } //optional $optional = '(<i>'.__('required', CDXC_TEXTDOMAIN).'</i>)'; if(!empty($param_arr[2])){ $opt = $param_arr[2]; if($opt=='Optional.' || $opt=='optional.'){ $optional = '(<i>'.__('optional', CDXC_TEXTDOMAIN).'</i>)'; unset($param_arr[2]); } } $output .= $optional.' '; //we now split into descriptions. $param_str = implode(' ',$param_arr); $param_arr = explode('.',$param_str); $param_arr = array_filter($param_arr); //print_r($param_arr); //description/default $default = '<dl><dd>'.__('Default', CDXC_TEXTDOMAIN).': <i>'.__('None', CDXC_TEXTDOMAIN).'</i></dd></dl>'; foreach ($param_arr as $bit) { $bit = trim($bit); //echo '#'.$bit.'#'; if(substr( $bit, 0, 7) === 'Default'){ $bits = explode('Default',$bit); $default = '<dl><dd>'.__('Default', CDXC_TEXTDOMAIN).': <i>'.$bits[1].'</i></dd></dl>'; }else{ $output .= $bit.'. '; } } $output .= $default; $output .= '</dd>'; $output .= '</dl>'; return $output; } /** * Get and format content output for example section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_example_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_example', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_example_content', $content, $post_id, $title); } /** * Get and format content output for return section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_return_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_return', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $meta_value = cdxc_return_content_helper($meta_value); $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_return_content', $content, $post_id, $title); } /** * Arrange a return value into a usable HTML output. * * @since 1.0.0 * @package Codex_Creator * @param string $value The string value to be used. * @return string Formatted HTML on success. */ function cdxc_return_content_helper($value) { if($value==''){return '';} $output = ''; $param_arr = explode(' ',$value); $param_arr = array_values(array_filter($param_arr)); //print_r($param_arr); $output .= '<dl>'; //datatype if(!empty($param_arr[0])){ $datatype = $param_arr[0]; $link_open = ''; $link_close = ''; if($datatype=='string' || $datatype=='String'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#String" target="_blank">'; $link_close = '</a>'; } if($datatype=='int'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Integer" target="_blank">'; $link_close = '</a>'; } if($datatype=='bool'){ $link_open = '<a href="http://codex.wordpress.org/How_to_Pass_Tag_Parameters#Boolean" target="_blank">'; $link_close = '</a>'; } $output .= '<dt><b>('.$link_open.'<i>'.$datatype.'</i>'.$link_close.')</b></dt>'; unset($param_arr[0]); } $output .= '<ul>'; //we now split into descriptions. $param_str = implode(' ',$param_arr); $param_arr = explode('.',$param_str); $param_arr = array_filter($param_arr); //print_r($param_arr); //description/default foreach ($param_arr as $bit) { $bit = trim($bit); $output .= '<li>'.$bit.'. </li>'; } $output .= '</ul>'; $output .= '</dl>'; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return $output; } /** * Get and format content output for see section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_see_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_see', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $value) { $value = cdxc_see_content_helper($value); $content .= CDXC_CONTENT_START . $value . CDXC_CONTENT_END; } } else { $meta_value = cdxc_see_content_helper($meta_value); $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; } /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_see_content', $content, $post_id, $title); } /** * Arrange a see value into a usable HTML output. * * @since 1.0.0 * @package Codex_Creator * @param string $value The string value to be used. * @return string Formatted HTML on success. * @todo make this format URL's. */ function cdxc_see_content_helper($text) { if ($text == '') { return ''; } if (strpos($text,'"') !== false || strpos($text,"'") !== false) {// we have a hook $new_text = str_replace(array('"',"'"),'',$text); $page = get_page_by_title($new_text, OBJECT, 'codex_creator'); if($page) { $link = get_permalink($page->ID); $text = "<a href='$link' >$text</a>"; } }elseif(strpos($text,'()') !== false){ $new_text = str_replace('()','',$text); $page = get_page_by_title($new_text, OBJECT, 'codex_creator'); if($page) { $link = get_permalink($page->ID); $text = "<a href='$link' >$text</a>"; } } return $text; } /** * Get and format content output for since section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_since_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_since', true); if (!$meta_value) { return; } if (is_array($meta_value) && empty($meta_value)) { return false; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $tags = array(); if (is_array($meta_value)) { $i=0; foreach ($meta_value as $value) { if($i==0){$since = __('Since', CDXC_TEXTDOMAIN).': ';}else{$since='';} if ($pieces = explode(" ", $value)) { $ver = $pieces[0]; unset($pieces[0]); $text = join(' ', $pieces); $content .= CDXC_CONTENT_START .$since. '<a href="%' . $ver . '%">' . $ver . '</a>' . ' ' . $text . CDXC_CONTENT_END; $tags[] = $ver; } else { $content .= CDXC_CONTENT_START . '<a href="%' . $value . '%">' . $value . '</a>' . CDXC_CONTENT_END; $tags[] = $value; } $i++; } } else { $content .= CDXC_CONTENT_START .__('Since', CDXC_TEXTDOMAIN). ': <a href="%' . $meta_value . '%">' . $meta_value . '</a>' . CDXC_CONTENT_END; $tags[] = $meta_value; } // get the project slug $project_slug = 'project-not-found'; $project_terms = wp_get_object_terms($post_id, 'codex_project'); if (!is_wp_error($project_terms) && !empty($project_terms) && is_object($project_terms[0])) { foreach ($project_terms as $p_term) { if ($p_term->parent == '0') { $project_slug = $p_term->slug; } } } //set all tags to have prefix of the project $alt_tags = array(); foreach ($tags as $temp_tag) { $alt_tags[] = $project_slug . '_' . $temp_tag; } $tags = $alt_tags; $tags_arr = wp_set_post_terms($post_id, $tags, 'codex_tags', false); //print_r($tags_arr);//exit; if (is_array($tags_arr)) { foreach ($tags_arr as $key => $tag_id) { //$term = get_term($tag_id, 'codex_tags'); $term = get_term_by('term_taxonomy_id', $tag_id, 'codex_tags'); $tag_link = get_term_link($term, 'codex_tags'); $orig_ver = str_replace($project_slug . '_', '', $tags[$key]); $content = str_replace('%' . $orig_ver . '%', $tag_link, $content); } } // print_r($tags_arr);exit; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_since_content', $content, $post_id, $title); } /** * Get and format content output for subpackage section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_subpackage_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_subpackage', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_subpackage_content', $content, $post_id, $title); } /** * Get and format content output for todo section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_todo_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_todo', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_todo_content', $content, $post_id, $title); } /** * Get and format content output for type section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_type_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_type', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_type_content', $content, $post_id, $title); } /** * Get and format content output for uses section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_uses_content($post_id, $title) { return;// @todo make this work with arrays. $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_uses', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_uses_content', $content, $post_id, $title); } /** * Get and format content output for var section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_var_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_var', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_var_content', $content, $post_id, $title); } /** * Get and format content output for functions section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_functions_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_meta_functions', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; //$content .= CDXC_CONTENT_START.$meta_value.CDXC_CONTENT_END; if (is_array($meta_value)) { foreach ($meta_value as $func) { $func_arr = get_page_by_title($func[1], OBJECT, 'codex_creator'); // print_r($func_arr);exit; if (is_object($func_arr)) { $link = get_permalink($func_arr->ID); $content .= CDXC_CONTENT_START . '<a href="' . $link . '">' . $func[1] . '()</a> [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } else { $content .= CDXC_CONTENT_START . $func[1] . '() [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } } } //$content .= CDXC_CONTENT_START.print_r($meta_value,true).CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_functions_content', $content, $post_id, $title); } /** * Get and format content output for actions section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_actions_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_meta_actions', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $func) { $func_arr = get_page_by_title($func[1], OBJECT, 'codex_creator'); //print_r($func_arr);exit; $name = "'".$func[1]."'"; if (is_object($func_arr)) { $link = get_permalink($func_arr->ID); $content .= CDXC_CONTENT_START . '<a href="' . $link . '">' . $name . ' </a> [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } else { $content .= CDXC_CONTENT_START . $name . ' [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } } } //$content .= CDXC_CONTENT_START.print_r($meta_value,true).CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_actions_content', $content, $post_id, $title); } /** * Get and format content output for filters section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_filters_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_meta_filters', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $func) { $func_arr = get_page_by_title($func[1], OBJECT, 'codex_creator'); // print_r($func_arr);exit; $name = "'".$func[1]."'"; if (is_object($func_arr)) { $link = get_permalink($func_arr->ID); $content .= CDXC_CONTENT_START . '<a href="' . $link . '">' . $name . ' </a> [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } else { $content .= CDXC_CONTENT_START . $name . ' [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func[2] . ']' . CDXC_CONTENT_END; } } } //$content .= CDXC_CONTENT_START.print_r($meta_value,true).CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_filters_content', $content, $post_id, $title); } /** * Get and format content output for location section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_location_content($post_id, $title) { $content = ''; $meta_type = get_post_meta($post_id, 'cdxc_meta_type', true); if ($meta_type == 'file' || $meta_type == 'action' || $meta_type == 'filter') { return false; } $meta_value = get_post_meta($post_id, 'cdxc_meta_path', true); if (!$meta_value) { return; } $line = get_post_meta($post_id, 'cdxc_meta_line', true); $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; $file_name = basename($meta_value); $func_arr = get_post($post_id); $func_name = $func_arr->post_title; if($meta_type=='function'){ $func_name_n = $func_name. '() '; }else{ $func_name_n = "'".$func_name. "' "; } $file_arr = get_page_by_title($file_name, OBJECT, 'codex_creator'); if (is_object($file_arr)) { $link = get_permalink($file_arr->ID); $content .= CDXC_CONTENT_START .$func_name_n . __('is located in', CDXC_TEXTDOMAIN) . ' <a href="' . $link . '">' . $meta_value . '</a> [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $line . ']' . CDXC_CONTENT_END; } else { $content .= CDXC_CONTENT_START . $func_name_n . __('is located in', CDXC_TEXTDOMAIN) . ' ' . $meta_value . ' [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $line . ']' . CDXC_CONTENT_END; } /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_location_content', $content, $post_id, $title); } /** * Get and format content output for source code section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_code_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_meta_code', true); if (!$meta_value) { return; } $meta_value = "%%CDXC_SRC_CODE%%"; $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; //$content .= CDXC_PHP_CODE_START . $meta_value . CDXC_PHP_CODE_END; $content .= CDXC_CONTENT_START . $meta_value . CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_code_content', $content, $post_id, $title); } /** * Get and format content output for filters section of the codex page. * * @since 1.0.0 * @package Codex_Creator * @param int $post_id Post ID of the post content required. * @param string $title Title for the content section. * @return string The formatted content. */ function cdxc_used_by_content($post_id, $title) { $content = ''; $meta_value = get_post_meta($post_id, 'cdxc_meta_used_by', true); if (!$meta_value) { return; } $content .= CDXC_TITLE_START . $title . CDXC_TITLE_END; if (is_array($meta_value)) { foreach ($meta_value as $func) { $func_arr = get_page_by_title($func['function_name'], OBJECT, 'codex_creator'); // print_r($func_arr);exit; $name = ''; if($func['function_name']){ $name = "".$func['function_name']."()"; } if (is_object($func_arr)) { $link = get_permalink($func_arr->ID); $content .= CDXC_CONTENT_START . $func['file_path'].': <a href="' . $link . '">' . $name . ' </a> [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func['hook_line'] . ']' . CDXC_CONTENT_END; } else { $content .= CDXC_CONTENT_START .$func['file_path'].': '. $name . ' [' . __('Line', CDXC_TEXTDOMAIN) . ': ' . $func['hook_line'] . ']' . CDXC_CONTENT_END; } } } //$content .= CDXC_CONTENT_START.print_r($meta_value,true).CDXC_CONTENT_END; /** * Filter the content returned by the function. * * @since 1.0.0 * @param string $content The content to be output. * @param int $post_id The post ID. * @param string $title The title for the content. */ return apply_filters('cdxc_used_by_content', $content, $post_id, $title); }
NomadDevs/codex_creator
lib/content_output_functions.php
PHP
gpl-3.0
41,482
/******************************************************************************* * Copyright 2010 Olaf Sebelin * * This file is part of Verdandi. * * Verdandi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Verdandi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Verdandi. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package verdandi; /** * * @ */ public class InvalidIntervalException extends Exception { /** * */ private static final long serialVersionUID = 1L; /** * */ public InvalidIntervalException() { super(); } /** * @param message */ public InvalidIntervalException(String message) { super(message); } }
osebelin/verdandi
src/main/java/verdandi/InvalidIntervalException.java
Java
gpl-3.0
1,220
/* * SPDX-License-Identifier: GPL-3.0 * * * (J)ava (M)iscellaneous (U)tilities (L)ibrary * * JMUL is a central repository for utilities which are used in my * other public and private repositories. * * Copyright (C) 2016 Kristian Kutin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * e-mail: kristian.kutin@arcor.de */ /* * This section contains meta informations. * * $Id$ */ package jmul.web.page; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import jmul.io.NestedStreams; import jmul.io.NestedStreamsImpl; import jmul.misc.exceptions.MultipleCausesException; import static jmul.string.Constants.FILE_SEPARATOR; import static jmul.string.Constants.SLASH; /** * This class represents an entity which loads web content from the file * system. * * @author Kristian Kutin */ public class PageLoader { /** * The base directory of the web content. */ private final File baseDirectory; /** * The file with the page content. */ private final File file; /** * Creates a new instance of a content loader. * * @param aBaseDirectory * a base directory * @param aFile * a file (i.e. file path) */ public PageLoader(File aBaseDirectory, File aFile) { baseDirectory = aBaseDirectory; file = aFile; } /** * Loads the web content. * * @return web content */ public PublishedPage loadContent() { String path = getPath(); NestedStreams nestedStreams = null; try { nestedStreams = openStreams(file); } catch (FileNotFoundException e) { String message = "Unable to load the web content (\"" + file + "\")!"; throw new PageLoaderException(message, e); } byte[] content = null; try { content = loadContent(nestedStreams); } catch (IOException e) { Throwable followupError = null; try { nestedStreams.close(); } catch (IOException f) { followupError = f; } String message = "Error while reading from file (\"" + file + "\")!"; if (followupError != null) { throw new PageLoaderException(message, new MultipleCausesException(e, followupError)); } else { throw new PageLoaderException(message, followupError); } } return new PublishedPage(path, content); } /** * Determines the web path for this file relative to the base directory. * * @param aBaseDirectory * @param aFile * * @return a path * * @throws IOException * is thrown if the specified directory or file cannot be resolved to * absolute paths */ private static String determinePath(File aBaseDirectory, File aFile) throws IOException { String directory = aBaseDirectory.getCanonicalPath(); String fileName = aFile.getCanonicalPath(); String path = fileName.replace(directory, ""); path = path.replace(FILE_SEPARATOR, SLASH); return path; } /** * Opens a stream to read from the specified file. * * @param aFile * * @return an input stream * * @throws FileNotFoundException * is thrown if the specified file doesn't exist */ private static NestedStreams openStreams(File aFile) throws FileNotFoundException { InputStream reader = new FileInputStream(aFile); return new NestedStreamsImpl(reader); } /** * Tries to load the web content from the specified file. * * @param someNestedStreams * * @return some web content * * @throws IOException * is thrown if an error occurred while reading from the file */ private static byte[] loadContent(NestedStreams someNestedStreams) throws IOException { InputStream reader = (InputStream) someNestedStreams.getOuterStream(); List<Byte> buffer = new ArrayList<>(); while (true) { int next = reader.read(); if (next == -1) { break; } buffer.add((byte) next); } int size = buffer.size(); byte[] bytes = new byte[size]; for (int a = 0; a < size; a++) { Byte b = buffer.get(a); bytes[a] = b; } return bytes; } /** * Returns the path of the web page. * * @return a path */ public String getPath() { String path = null; try { path = determinePath(baseDirectory, file); } catch (IOException e) { String message = "Unable to resolve paths (\"" + baseDirectory + "\" & \"" + file + "\")!"; throw new PageLoaderException(message, e); } return path; } }
gammalgris/jmul
Utilities/Web/src/jmul/web/page/PageLoader.java
Java
gpl-3.0
5,731
// Copyright 2016, Durachenko Aleksey V. <durachenko.aleksey@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include "version.h" #define STR_HELPER(x) #x #define STR(x) STR_HELPER(x) #ifndef APP_NAME #define APP_NAME "target" #endif #ifndef APP_MAJOR #define APP_MAJOR 0 #endif #ifndef APP_MINOR #define APP_MINOR 0 #endif #ifndef APP_PATCH #define APP_PATCH 0 #endif #ifndef APP_VERSION #define APP_VERSION STR(APP_MAJOR) "." STR(APP_MINOR) "." STR(APP_PATCH) #endif const char *appName() { return STR(APP_NAME); } const char *appShortName() { return STR(APP_NAME); } const char *appFullName() { return STR(APP_NAME); } const char *appVersion() { return STR(APP_VERSION); } const char *appBuildNumber() { #ifdef APP_BUILD_NUMBER return STR(APP_BUILD_NUMBER); #else return "0"; #endif } const char *appBuildDate() { #ifdef APP_BUILD_DATE return STR(APP_BUILD_DATE); #else return "0000-00-00T00:00:00+0000"; #endif } const char *appRevision() { #ifdef APP_REVISION return STR(APP_REVISION); #else return "0"; #endif } const char *appSources() { #ifdef APP_SOURCES return STR(APP_SOURCES); #else return ""; #endif }
AlekseyDurachenko/vkOAuth
src/version.cpp
C++
gpl-3.0
1,812
import { Model } from "chomex"; import catalog from "./catalog"; export interface DeckCaptureLike { _id: any; title: string; row: number; col: number; page: number; cell: { x: number; y: number; w: number, h: number; }; protected?: boolean; } /** * 編成キャプチャの設定を保存する用のモデル。 * ふつうの1艦隊編成もあれば、連合艦隊、航空基地編成などもある。 */ export default class DeckCapture extends Model { static __ns = "DeckCapture"; static default = { normal: { title: "編成キャプチャ", row: 3, col: 2, cell: catalog.fleet, protected: true, }, combined: { title: "連合編成キャプチャ", row: 3, col: 2, cell: catalog.fleet, protected: true, page: 2, pagelabel: ["第一艦隊", "第二艦隊"], }, aviation: { title: "基地航空隊", row: 1, col: 3, cell: catalog.aviation, protected: true, }, }; title: string; // この編成キャプチャ設定の名前 row: number; // 列数 col: number; // 行数 cell: { // 1セルの定義 x: number; // スタート座標X (ゲーム幅を1に対して) y: number; // スタート座標Y (ゲーム高を1に対して) w: number; // セル幅 (ゲーム幅を1に対して) h: number; // セル高 (ゲーム高を1に対して) }; protected = false; // 削除禁止 page = 1; // 繰り返しページ数 pagelabel: string[] = []; // ページごとのラベル obj(): DeckCaptureLike { return { _id: this._id, title: this.title, row: this.row, col: this.col, page: this.page, cell: {...this.cell}, protected: this.protected, }; } static listObj(): DeckCaptureLike[] { return this.list<DeckCapture>().map(d => d.obj()); } }
otiai10/kanColleWidget
src/js/Applications/Models/DeckCapture/index.ts
TypeScript
gpl-3.0
1,889
/******************************************************************************* MPhoto - Photo viewer for multi-touch devices Copyright (C) 2010 Mihai Paslariu This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ #include "ImageLoadQueue.h" // synchronized against all other methods ImageLoadItem ImageLoadQueue::pop ( void ) { ImageLoadItem x; _sem.acquire(); _mutex.lock(); x = QQueue<ImageLoadItem>::front(); QQueue<ImageLoadItem>::pop_front(); _mutex.unlock(); return x; } // synchronized against all other methods ImageLoadItem ImageLoadQueue::popWithPriority ( void ) { ImageLoadItem x; _sem.acquire(); _mutex.lock(); QQueue<ImageLoadItem>::Iterator it; QQueue<ImageLoadItem>::Iterator it_max; int max_prio = -1; for ( it = this->begin(); it != this->end(); it++ ) { if ( it->priority > max_prio ) { max_prio = it->priority; it_max = it; } } x = *it_max; this->erase( it_max ); _mutex.unlock(); return x; } // synchronized only against pop void ImageLoadQueue::push ( const ImageLoadItem &x ) { _mutex.lock(); QQueue<ImageLoadItem>::push_back(x); _sem.release(); _mutex.unlock(); } // synchronized only against pop QList<ImageLoadItem> ImageLoadQueue::clear( void ) { QList<ImageLoadItem> cleared_items = QList<ImageLoadItem>(); while ( _sem.tryAcquire() ) { ImageLoadItem x; _mutex.lock(); x = QQueue<ImageLoadItem>::front(); QQueue<ImageLoadItem>::pop_front(); _mutex.unlock(); cleared_items.append( x ); } return cleared_items; } void ImageLoadQueue::clearPriorities( void ) { _mutex.lock(); QQueue<ImageLoadItem>::Iterator it; for ( it = this->begin(); it != this->end(); it++ ) { it->priority = 0; } _mutex.unlock(); } void ImageLoadQueue::updatePriority( QImage ** dest, int priority ) { _mutex.lock(); QQueue<ImageLoadItem>::Iterator it; for ( it = this->begin(); it != this->end(); it++ ) { if ( it->destination == dest ) it->priority = priority; } _mutex.unlock(); }
miabrahams/MPhoto
dev/ImageLoadQueue.cpp
C++
gpl-3.0
2,610
<?php /************************* Coppermine Photo Gallery ************************ Copyright (c) 2003-2016 Coppermine Dev Team v1.0 originally written by Gregory Demar This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. ******************************************** Coppermine version: 1.6.03 $HeadURL$ **********************************************/ $base = array( 0x00 => 'ruk', 'rut', 'rup', 'ruh', 'rweo', 'rweog', 'rweogg', 'rweogs', 'rweon', 'rweonj', 'rweonh', 'rweod', 'rweol', 'rweolg', 'rweolm', 'rweolb', 0x10 => 'rweols', 'rweolt', 'rweolp', 'rweolh', 'rweom', 'rweob', 'rweobs', 'rweos', 'rweoss', 'rweong', 'rweoj', 'rweoc', 'rweok', 'rweot', 'rweop', 'rweoh', 0x20 => 'rwe', 'rweg', 'rwegg', 'rwegs', 'rwen', 'rwenj', 'rwenh', 'rwed', 'rwel', 'rwelg', 'rwelm', 'rwelb', 'rwels', 'rwelt', 'rwelp', 'rwelh', 0x30 => 'rwem', 'rweb', 'rwebs', 'rwes', 'rwess', 'rweng', 'rwej', 'rwec', 'rwek', 'rwet', 'rwep', 'rweh', 'rwi', 'rwig', 'rwigg', 'rwigs', 0x40 => 'rwin', 'rwinj', 'rwinh', 'rwid', 'rwil', 'rwilg', 'rwilm', 'rwilb', 'rwils', 'rwilt', 'rwilp', 'rwilh', 'rwim', 'rwib', 'rwibs', 'rwis', 0x50 => 'rwiss', 'rwing', 'rwij', 'rwic', 'rwik', 'rwit', 'rwip', 'rwih', 'ryu', 'ryug', 'ryugg', 'ryugs', 'ryun', 'ryunj', 'ryunh', 'ryud', 0x60 => 'ryul', 'ryulg', 'ryulm', 'ryulb', 'ryuls', 'ryult', 'ryulp', 'ryulh', 'ryum', 'ryub', 'ryubs', 'ryus', 'ryuss', 'ryung', 'ryuj', 'ryuc', 0x70 => 'ryuk', 'ryut', 'ryup', 'ryuh', 'reu', 'reug', 'reugg', 'reugs', 'reun', 'reunj', 'reunh', 'reud', 'reul', 'reulg', 'reulm', 'reulb', 0x80 => 'reuls', 'reult', 'reulp', 'reulh', 'reum', 'reub', 'reubs', 'reus', 'reuss', 'reung', 'reuj', 'reuc', 'reuk', 'reut', 'reup', 'reuh', 0x90 => 'ryi', 'ryig', 'ryigg', 'ryigs', 'ryin', 'ryinj', 'ryinh', 'ryid', 'ryil', 'ryilg', 'ryilm', 'ryilb', 'ryils', 'ryilt', 'ryilp', 'ryilh', 0xA0 => 'ryim', 'ryib', 'ryibs', 'ryis', 'ryiss', 'rying', 'ryij', 'ryic', 'ryik', 'ryit', 'ryip', 'ryih', 'ri', 'rig', 'rigg', 'rigs', 0xB0 => 'rin', 'rinj', 'rinh', 'rid', 'ril', 'rilg', 'rilm', 'rilb', 'rils', 'rilt', 'rilp', 'rilh', 'rim', 'rib', 'ribs', 'ris', 0xC0 => 'riss', 'ring', 'rij', 'ric', 'rik', 'rit', 'rip', 'rih', 'ma', 'mag', 'magg', 'mags', 'man', 'manj', 'manh', 'mad', 0xD0 => 'mal', 'malg', 'malm', 'malb', 'mals', 'malt', 'malp', 'malh', 'mam', 'mab', 'mabs', 'mas', 'mass', 'mang', 'maj', 'mac', 0xE0 => 'mak', 'mat', 'map', 'mah', 'mae', 'maeg', 'maegg', 'maegs', 'maen', 'maenj', 'maenh', 'maed', 'mael', 'maelg', 'maelm', 'maelb', 0xF0 => 'maels', 'maelt', 'maelp', 'maelh', 'maem', 'maeb', 'maebs', 'maes', 'maess', 'maeng', 'maej', 'maec', 'maek', 'maet', 'maep', 'maeh', );
coppermine-gallery/cpg1.6.x
include/transliteration/xb9.php
PHP
gpl-3.0
2,810
package co.edu.udea.ingenieriaweb.admitravel.bl; import java.util.List; import co.edu.udea.ingenieriaweb.admitravel.dto.PaqueteDeViaje; import co.edu.udea.ingenieriaweb.admitravel.util.exception.IWBLException; import co.edu.udea.ingenieriaweb.admitravel.util.exception.IWDaoException; /** * Clase DestinoBL define la funcionalidad a implementar en el DestinoBLImp * * @author Yeferson Marín * */ public interface PaqueteDeViajeBL { /** * Método que permite almacenar un paquete de viaje en el sistema * @param idPaquete tipo de identificación del paquete de viaje * @param destinos nombre del destinos (Este parametro no debería ir) * @param transporte transporte en el que se hace el viaje * @param alimentacion alimentación que lleva el viaje * @param duracionViaje duración del viaje tomado * @throws IWDaoException ocurre cuando hay un error en la base de datos * @throws IWBLException ocurre cuando hay un error de lógica del negocio en los datos a guardar */ public void guardar(String idPaquete, String destinos, String transporte, String alimentacion, String duracionViaje) throws IWDaoException, IWBLException; public void actualizar(PaqueteDeViaje paqueteDeViaje, String idPaquete, String destinos, String transporte, String alimentacion, String duracionViaje)throws IWDaoException, IWBLException; PaqueteDeViaje obtener(String idPaquete) throws IWDaoException, IWBLException; }
yefry/AdmiTravelSpring
AdmiTravelSpring/src/co/edu/udea/ingenieriaweb/admitravel/bl/PaqueteDeViajeBL.java
Java
gpl-3.0
1,439
// mailer.js var nodemailer = require('nodemailer'); var smtpTransport = nodemailer.createTransport("SMTP", { service: "Mandrill", debug: true, auth: { user: "evanroman1@gmail.com", pass: "k-AdDVcsNJ9oj8QYATVNGQ" } }); exports.sendEmailConfirmation = function(emailaddress, username, firstname, expiremoment, token){ var mailOptions = { from: "confirm@ativinos.com", // sender address to: emailaddress, // list of receivers subject: "Confirm email and start Ativinos", // Subject line text: 'Hi ' +firstname+ ', your account, ' +username+ ', will be enabled after you confirm your email. Your account will be deleted by ' + expiremoment + ' if you do not verify email before then. To verify your email, visit http://www.ativinos.com/emailverify?token=' + token + '&username=' + username, html: 'Hi ' +firstname+ ', your account, ' +username+ ', will be enabled after you confirm your email. Your account will be deleted by ' + expiremoment + ' if you do not verify email before then. To verify your email, visit <a href="http://www.ativinos.com/emailverify?token=' + token + '&username=' + username + '">http://www.ativinos.com/emailverify?token=' + token + '&username=' + username + '</a>', } smtpTransport.sendMail(mailOptions, function(error, response){ if(error){ console.log(error); } }) }
evrom/ativinos---deprecated
local_modules/mailer.js
JavaScript
gpl-3.0
1,602
$(function(){ $('#telefone').mask('(99)9999-9999'); $('.editar').on({ click : function(){ var url = URI+"sistema/editar/"+$(this).attr('data-item'); window.location.href = url; } }); $('.deletar').on({ click : function(){ var $selecionados = get_selecionados(); if($selecionados.length > 0) { var $url = URI+"sistema/remover/"; if (window.confirm("deseja apagar os ("+$selecionados.length+") itens selecionados? ")) { $.post($url, { 'selecionados': $selecionados}, function(data){ pop_up(data, setTimeout(function(){location.reload()}, 100)); }); } } else { pop_up('nenhum item selecionado'); } } }); $('#description').on('keyup',function(){ var alvo = $("#char-digitado"); var max = 140; var digitados = $(this).val().length; var restante = max - digitados; if(digitados > max) { var val = $(this).val(); $(this).val(val.substr(0, max)); restante = 0; } alvo.html(restante); }); });
Carlos-Claro/admin2_0
js/sistema.js
JavaScript
gpl-3.0
1,437
# -*- coding: UTF-8 -*- """ Desc: django util. Note: --------------------------------------- # 2016/04/30 kangtian created """ from hashlib import md5 def gen_md5(content_str): m = md5() m.update(content_str) return m.hexdigest()
tiankangkan/paper_plane
k_util/hash_util.py
Python
gpl-3.0
257
using System; namespace Server.Network { public delegate void OnPacketReceive( NetState state, PacketReader pvSrc ); public delegate bool ThrottlePacketCallback( NetState state ); public class PacketHandler { public PacketHandler( int packetID, int length, bool ingame, OnPacketReceive onReceive ) { PacketID = packetID; Length = length; Ingame = ingame; OnReceive = onReceive; } public int PacketID { get; } public int Length { get; } public OnPacketReceive OnReceive { get; } public ThrottlePacketCallback ThrottleCallback { get; set; } public bool Ingame { get; } } }
xrunuo/xrunuo
Server/Network/PacketHandler.cs
C#
gpl-3.0
640
package com.github.wglanzer.redmine; import java.util.function.Consumer; /** * Interface that is able to create background-tasks * * @author w.glanzer, 11.12.2016. */ public interface IRTaskCreator { /** * Executes a given task in background * * @param pTask Task that should be done in background * @return the given task */ <T extends ITask> T executeInBackground(T pTask); /** * Progress, that can be executed */ interface ITask extends Consumer<IProgressIndicator> { /** * @return the name of the current progress */ String getName(); } /** * Indicator-Interface to call back to UI */ interface IProgressIndicator { /** * Adds the given number to percentage * * @param pPercentage 0-100 */ void addPercentage(double pPercentage); } }
wglanzer/redmine-intellij-plugin
core/src/main/java/com/github/wglanzer/redmine/IRTaskCreator.java
Java
gpl-3.0
841
<?php $namespacetree = array( 'vector' => array( ), 'std' => array( 'vector' => array( 'inner' => array( ) ) ) ); $string = "while(!acceptable(a)) perform_random_actions(&a);";
nitro2010/moodle
blocks/formal_langs/parsertests/input/old/while.php
PHP
gpl-3.0
249
// ADOBE SYSTEMS INCORPORATED // Copyright 1993 - 2002 Adobe Systems Incorporated // All Rights Reserved // // NOTICE: Adobe permits you to use, modify, and distribute this // file in accordance with the terms of the Adobe license agreement // accompanying it. If you have received this file from a source // other than Adobe, then your use, modification, or distribution // of it requires the prior written permission of Adobe. //------------------------------------------------------------------- /* File: NearestBaseUIWin.c C source file for Windows specific code for Color Picker example. */ #include "NearestBase.h" #include "DialogUtilities.h" /*****************************************************************************/ DLLExport BOOL WINAPI PickerProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lParam); // Win32 Change /*****************************************************************************/ void DoAbout (AboutRecordPtr about) { ShowAbout(about); } /*****************************************************************************/ DLLExport BOOL WINAPI PickerProc(HWND hDlg, UINT wMsg, WPARAM wParam, LPARAM lParam) // Win32 Change { int idd; // WIN32 Change static GPtr globals=NULL; /* need to be static */ long x = 0; switch (wMsg) { case WM_INITDIALOG: /* set up globals */ globals = (GPtr) lParam; CenterDialog(hDlg); /* fall into WM_PAINT */ case WM_PAINT: return FALSE; break; case WM_COMMAND: idd = COMMANDID (wParam); // WIN32 Change if (idd == x) // any radio groups ; // handle radios; else { switch (idd) { case OK: // assign to globals EndDialog(hDlg, idd); break; case CANCEL: gResult = userCanceledErr; EndDialog(hDlg, idd); // WIN32 change break; default: return FALSE; break; } } break; default: return FALSE; break; } return TRUE; } /*****************************************************************************/ Boolean DoParameters (GPtr globals) { INT_PTR nResult = noErr; PlatformData *platform; platform = (PlatformData *)((PickerRecordPtr) gStuff)->platformData; /* Query the user for parameters. */ nResult = DialogBoxParam(GetDLLInstance(), (LPSTR)"PICKERPARAM", (HWND)platform->hwnd, (DLGPROC)PickerProc, (LPARAM)globals); return (nResult == OK); // could be -1 } // NearestBaseUIWin.cpp
wholegroup/vector
external/Adobe Photoshop CS6 SDK/samplecode/colorpicker/nearestbase/win/NearestBaseUIWin.cpp
C++
gpl-3.0
2,478
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sick Beard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier
theguardian/LazyLibrarian_Old
lazylibrarian/notifiers/tweet.py
Python
gpl-3.0
5,477
<?php class ControllerCommonLanguage extends Controller { public function index() { $this->load->language('common/language'); $data['action'] = $this->url->link('common/language/language', '', $this->request->server['HTTPS']); $data['code'] = $this->session->data['language']; $this->load->model('localisation/language'); $data['languages'] = array(); $results = $this->model_localisation_language->getLanguages(); foreach ($results as $result) { if ($result['status']) { $data['languages'][] = array( 'layout' => 1, 'name' => $result['name'], 'code' => $result['code'] ); } } if (!isset($this->request->get['route'])) { $data['redirect'] = $this->url->link('common/home'); } else { $url_data = $this->request->get; unset($url_data['_route_']); $route = $url_data['route']; unset($url_data['route']); $url = ''; if ($url_data) { $url = '&' . urldecode(http_build_query($url_data, '', '&')); } $data['redirect'] = $this->url->link($route, $url, $this->request->server['HTTPS']); } return $this->load->view('common/language', $data); } public function language() { if (isset($this->request->post['code'])) { $this->session->data['language'] = $this->request->post['code']; } if (isset($this->request->post['redirect'])) { $this->response->redirect($this->request->post['redirect']); } else { $this->response->redirect($this->url->link('common/home')); } } }
vocxod/cintez
www/catalog/controller/common/language.php
PHP
gpl-3.0
1,477
using System; using System.Collections; using System.IO; namespace Server.Engines.Reports { public class StaffHistory : PersistableObject { #region Type Identification public static readonly PersistableType ThisTypeID = new PersistableType("stfhst", new ConstructCallback(Construct)); private static PersistableObject Construct() { return new StaffHistory(); } public override PersistableType TypeID { get { return ThisTypeID; } } #endregion private PageInfoCollection m_Pages; private QueueStatusCollection m_QueueStats; private Hashtable m_UserInfo; private Hashtable m_StaffInfo; public PageInfoCollection Pages { get { return this.m_Pages; } set { this.m_Pages = value; } } public QueueStatusCollection QueueStats { get { return this.m_QueueStats; } set { this.m_QueueStats = value; } } public Hashtable UserInfo { get { return this.m_UserInfo; } set { this.m_UserInfo = value; } } public Hashtable StaffInfo { get { return this.m_StaffInfo; } set { this.m_StaffInfo = value; } } public void AddPage(PageInfo info) { lock (SaveLock) this.m_Pages.Add(info); info.History = this; } public StaffHistory() { this.m_Pages = new PageInfoCollection(); this.m_QueueStats = new QueueStatusCollection(); this.m_UserInfo = new Hashtable(StringComparer.OrdinalIgnoreCase); this.m_StaffInfo = new Hashtable(StringComparer.OrdinalIgnoreCase); } public StaffInfo GetStaffInfo(string account) { lock (RenderLock) { if (account == null || account.Length == 0) return null; StaffInfo info = this.m_StaffInfo[account] as StaffInfo; if (info == null) this.m_StaffInfo[account] = info = new StaffInfo(account); return info; } } public UserInfo GetUserInfo(string account) { if (account == null || account.Length == 0) return null; UserInfo info = this.m_UserInfo[account] as UserInfo; if (info == null) this.m_UserInfo[account] = info = new UserInfo(account); return info; } public static readonly object RenderLock = new object(); public static readonly object SaveLock = new object(); public void Save() { lock (SaveLock) { if (!Directory.Exists("Output")) { Directory.CreateDirectory("Output"); } string path = Path.Combine(Core.BaseDirectory, "Output/staffHistory.xml"); PersistanceWriter pw = new XmlPersistanceWriter(path, "Staff"); pw.WriteDocument(this); pw.Close(); } } public void Load() { string path = Path.Combine(Core.BaseDirectory, "Output/staffHistory.xml"); if (!File.Exists(path)) return; PersistanceReader pr = new XmlPersistanceReader(path, "Staff"); pr.ReadDocument(this); pr.Close(); } public override void SerializeChildren(PersistanceWriter op) { for (int i = 0; i < this.m_Pages.Count; ++i) this.m_Pages[i].Serialize(op); for (int i = 0; i < this.m_QueueStats.Count; ++i) this.m_QueueStats[i].Serialize(op); } public override void DeserializeChildren(PersistanceReader ip) { DateTime min = DateTime.UtcNow - TimeSpan.FromDays(8.0); while (ip.HasChild) { PersistableObject obj = ip.GetChild(); if (obj is PageInfo) { PageInfo pageInfo = obj as PageInfo; pageInfo.UpdateResolver(); if (pageInfo.TimeSent >= min || pageInfo.TimeResolved >= min) { this.m_Pages.Add(pageInfo); pageInfo.History = this; } else { pageInfo.Sender = null; pageInfo.Resolver = null; } } else if (obj is QueueStatus) { QueueStatus queueStatus = obj as QueueStatus; if (queueStatus.TimeStamp >= min) this.m_QueueStats.Add(queueStatus); } } } public StaffInfo[] GetStaff() { StaffInfo[] staff = new StaffInfo[this.m_StaffInfo.Count]; int index = 0; foreach (StaffInfo staffInfo in this.m_StaffInfo.Values) staff[index++] = staffInfo; return staff; } public void Render(ObjectCollection objects) { lock (RenderLock) { objects.Add(this.GraphQueueStatus()); StaffInfo[] staff = this.GetStaff(); BaseInfo.SortRange = TimeSpan.FromDays(7.0); Array.Sort(staff); objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.None, "New pages by hour", "graph_new_pages_hr")); objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Handled, "Handled pages by hour", "graph_handled_pages_hr")); objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Deleted, "Deleted pages by hour", "graph_deleted_pages_hr")); objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Canceled, "Canceled pages by hour", "graph_canceled_pages_hr")); objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Logged, "Logged-out pages by hour", "graph_logged_pages_hr")); BaseInfo.SortRange = TimeSpan.FromDays(1.0); Array.Sort(staff); objects.Add(this.ReportTotalPages(staff, TimeSpan.FromDays(1.0), "1 Day")); objects.AddRange((PersistableObject[])this.ChartTotalPages(staff, TimeSpan.FromDays(1.0), "1 Day", "graph_daily_pages")); BaseInfo.SortRange = TimeSpan.FromDays(7.0); Array.Sort(staff); objects.Add(this.ReportTotalPages(staff, TimeSpan.FromDays(7.0), "1 Week")); objects.AddRange((PersistableObject[])this.ChartTotalPages(staff, TimeSpan.FromDays(7.0), "1 Week", "graph_weekly_pages")); BaseInfo.SortRange = TimeSpan.FromDays(30.0); Array.Sort(staff); objects.Add(this.ReportTotalPages(staff, TimeSpan.FromDays(30.0), "1 Month")); objects.AddRange((PersistableObject[])this.ChartTotalPages(staff, TimeSpan.FromDays(30.0), "1 Month", "graph_monthly_pages")); for (int i = 0; i < staff.Length; ++i) objects.Add(this.GraphHourlyPages(staff[i])); } } public static int GetPageCount(StaffInfo staff, DateTime min, DateTime max) { return GetPageCount(staff.Pages, PageResolution.Handled, min, max); } public static int GetPageCount(PageInfoCollection pages, PageResolution res, DateTime min, DateTime max) { int count = 0; for (int i = 0; i < pages.Count; ++i) { if (res != PageResolution.None && pages[i].Resolution != res) continue; DateTime ts = pages[i].TimeResolved; if (ts >= min && ts < max) ++count; } return count; } private BarGraph GraphQueueStatus() { int[] totals = new int[24]; int[] counts = new int[24]; DateTime max = DateTime.UtcNow; DateTime min = max - TimeSpan.FromDays(7.0); for (int i = 0; i < this.m_QueueStats.Count; ++i) { DateTime ts = this.m_QueueStats[i].TimeStamp; if (ts >= min && ts < max) { DateTime date = ts.Date; TimeSpan time = ts.TimeOfDay; int hour = time.Hours; totals[hour] += this.m_QueueStats[i].Count; counts[hour]++; } } BarGraph barGraph = new BarGraph("Average pages in queue", "graph_pagequeue_avg", 10, "Time", "Pages", BarGraphRenderMode.Lines); barGraph.FontSize = 6; for (int i = 7; i <= totals.Length + 7; ++i) { int val; if (counts[i % totals.Length] == 0) val = 0; else val = (totals[i % totals.Length] + (counts[i % totals.Length] / 2)) / counts[i % totals.Length]; int realHours = i % totals.Length; int hours; if (realHours == 0) hours = 12; else if (realHours > 12) hours = realHours - 12; else hours = realHours; barGraph.Items.Add(hours + (realHours >= 12 ? " PM" : " AM"), val); } return barGraph; } private BarGraph GraphHourlyPages(StaffInfo staff) { return this.GraphHourlyPages(staff.Pages, PageResolution.Handled, "Average pages handled by " + staff.Display, "graphs_" + staff.Account.ToLower() + "_avg"); } private BarGraph GraphHourlyPages(PageInfoCollection pages, PageResolution res, string title, string fname) { int[] totals = new int[24]; int[] counts = new int[24]; DateTime[] dates = new DateTime[24]; DateTime max = DateTime.UtcNow; DateTime min = max - TimeSpan.FromDays(7.0); bool sentStamp = (res == PageResolution.None); for (int i = 0; i < pages.Count; ++i) { if (res != PageResolution.None && pages[i].Resolution != res) continue; DateTime ts = (sentStamp ? pages[i].TimeSent : pages[i].TimeResolved); if (ts >= min && ts < max) { DateTime date = ts.Date; TimeSpan time = ts.TimeOfDay; int hour = time.Hours; totals[hour]++; if (dates[hour] != date) { counts[hour]++; dates[hour] = date; } } } BarGraph barGraph = new BarGraph(title, fname, 10, "Time", "Pages", BarGraphRenderMode.Lines); barGraph.FontSize = 6; for (int i = 7; i <= totals.Length + 7; ++i) { int val; if (counts[i % totals.Length] == 0) val = 0; else val = (totals[i % totals.Length] + (counts[i % totals.Length] / 2)) / counts[i % totals.Length]; int realHours = i % totals.Length; int hours; if (realHours == 0) hours = 12; else if (realHours > 12) hours = realHours - 12; else hours = realHours; barGraph.Items.Add(hours + (realHours >= 12 ? " PM" : " AM"), val); } return barGraph; } private Report ReportTotalPages(StaffInfo[] staff, TimeSpan ts, string title) { DateTime max = DateTime.UtcNow; DateTime min = max - ts; Report report = new Report(title + " Staff Report", "400"); report.Columns.Add("65%", "left", "Staff Name"); report.Columns.Add("35%", "center", "Page Count"); for (int i = 0; i < staff.Length; ++i) report.Items.Add(staff[i].Display, GetPageCount(staff[i], min, max)); return report; } private PieChart[] ChartTotalPages(StaffInfo[] staff, TimeSpan ts, string title, string fname) { DateTime max = DateTime.UtcNow; DateTime min = max - ts; PieChart staffChart = new PieChart(title + " Staff Chart", fname + "_staff", true); int other = 0; for (int i = 0; i < staff.Length; ++i) { int count = GetPageCount(staff[i], min, max); if (i < 12 && count > 0) staffChart.Items.Add(staff[i].Display, count); else other += count; } if (other > 0) staffChart.Items.Add("Other", other); PieChart resChart = new PieChart(title + " Resolutions", fname + "_resol", true); int countTotal = GetPageCount(this.m_Pages, PageResolution.None, min, max); int countHandled = GetPageCount(this.m_Pages, PageResolution.Handled, min, max); int countDeleted = GetPageCount(this.m_Pages, PageResolution.Deleted, min, max); int countCanceled = GetPageCount(this.m_Pages, PageResolution.Canceled, min, max); int countLogged = GetPageCount(this.m_Pages, PageResolution.Logged, min, max); int countUnres = countTotal - (countHandled + countDeleted + countCanceled + countLogged); resChart.Items.Add("Handled", countHandled); resChart.Items.Add("Deleted", countDeleted); resChart.Items.Add("Canceled", countCanceled); resChart.Items.Add("Logged Out", countLogged); resChart.Items.Add("Unresolved", countUnres); return new PieChart[] { staffChart, resChart }; } } }
GenerationOfWorlds/GOW
Scripts/Systems/Management/Services/Web/Reports/Objects/Staffing/StaffHistory.cs
C#
gpl-3.0
14,679
import numpy as np import laspy as las # Determine if a point is inside a given polygon or not # Polygon is a list of (x,y) pairs. This function # returns True or False. The algorithm is called # the "Ray Casting Method". # the point_in_poly algorithm was found here: # http://geospatialpython.com/2011/01/point-in-polygon.html def point_in_poly(x,y,poly): n = len(poly) inside = False p1x,p1y = poly[0] for i in range(n+1): p2x,p2y = poly[i % n] if y > min(p1y,p2y): if y <= max(p1y,p2y): if x <= max(p1x,p2x): if p1y != p2y: xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x if p1x == p2x or x <= xints: inside = not inside p1x,p1y = p2x,p2y return inside # This one is my own version of the ray-trace algorithm which utilises the numpy arrays so that a list of x and y coordinates can be processed in one call and only points inside polygon are returned alongside the indices in case required for future referencing. This saves a fair bit of looping. def points_in_poly(x,y,poly): n = len(poly) inside=np.zeros(x.size,dtype=bool) xints=np.zeros(x.size) p1x,p1y = poly[0] for i in range(n+1): p2x,p2y=poly[i % n] if p1y!=p2y: xints[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)] = (y[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x if p1x==p2x: inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)] = np.invert(inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)]) else: inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x),x<=xints],axis=0)] = np.invert(inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x),x<=xints],axis=0)]) p1x,p1y = p2x,p2y return x[inside],y[inside], inside # This retrieves all points within circular neighbourhood, Terget point is the location around which the neighbourhood search is conducted, for a specified search radius. x and y are vectors with the x and y coordinates of the test points def points_in_radius(x,y,target_x, target_y,radius): inside=np.zeros(x.size,dtype=bool) d2=(x-target_x)**2+(y-target_y)**2 inside = d2<=radius**2 return x[inside],y[inside], inside # filter lidar wth polygon # This function has been updated to include an option to filter by first return location. # The reason for this is so full collections of returns associated with each LiDAR pulse # can be retrieved, which can be an issue at edges in multi-return analyses def filter_lidar_data_by_polygon(in_pts,polygon,filter_by_first_return_location = False): pts = np.zeros((0,in_pts.shape[1])) if in_pts.shape[0]>0: if filter_by_first_return_location: # find first returns mask = in_pts[:,3]==1 x_temp, y_temp, inside_temp = points_in_poly(in_pts[mask,0],in_pts[mask,1],polygon) shots = np.unique(in_pts[mask,6][inside_temp]) # index 6 refers to GPS time inside = np.in1d(in_pts[:,6],shots) # this function retrieves all points corresponding to this GPS time x = in_pts[inside,0] y = in_pts[inside,1] x_temp=None y_temp=None inside_temp=None else: x,y,inside = points_in_poly(in_pts[:,0],in_pts[:,1],polygon) pts = in_pts[inside,:] else: print("\t\t\t no points in polygon") return pts # filter lidar by circular neighbourhood def filter_lidar_data_by_neighbourhood(in_pts,target_xy,radius): pts = np.zeros((0,in_pts.shape[1])) if in_pts.shape[0]>0: x,y,inside = points_in_radius(in_pts[:,0],in_pts[:,1],target_xy[0],target_xy[1],radius) pts = in_pts[inside,:] else: print( "\t\t\t no points in neighbourhood") return pts
DTMilodowski/LiDAR_canopy
src/LiDAR_tools.py
Python
gpl-3.0
3,971
// This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * @package enrol_attributes * @author Julien Furrer <Julien.Furrer@unil.ch> * @copyright 2012-2015 Université de Lausanne (@link http://www.unil.ch} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ ; (function ($) { $.booleanEditor = { defaults: { rules: [], change: null }, paramList: M.enrol_attributes.paramList, operatorList: [ {label: " = ", value: "=="}, // {label: "=/=", value: "!="}, // {label: "contains", value: "contains"}, ] }; $.fn.extend({ booleanEditor: function (options) { var isMethodCall = (typeof options == 'string'), // is it a method call or booleanEditor instantiation ? args = Array.prototype.slice.call(arguments, 1); if (isMethodCall) switch (options) { case 'serialize': var mode = ( args[0] ) ? args[0].mode : '', ser_obj = serialize(this); switch (mode) { case 'json': return $.toJSON(ser_obj); break; case 'object': default: return ser_obj; } break; case 'getExpression': return getBooleanExpression(this); break; default: return; } settings = $.extend({}, $.booleanEditor.defaults, options); return this.each(function () { if (settings.change) { $(this).data('change', settings.change) } $(this) .addClass("enrol-attributes-boolean-editor") .append(createRuleList($('<ul></ul>'), settings.rules)); changed(this); }); } }); function serialize(root_elem) { var ser_obj = {rules: []}; var group_c_op = $("select:first[name='cond-operator']", root_elem).val(); if (group_c_op) ser_obj.cond_op = group_c_op; $("ul:first > li", root_elem).each(function () { r = $(this); if (r.hasClass('group')) { ser_obj['rules'].push(serialize(this)); } else { var cond_obj = { param: $("select[name='comparison-param'] option:selected", r).val(), comp_op: $("select[name='comparison-operator']", r).val(), value: $("input[name='value']", r).val() }; var cond_op = $("select[name='cond-operator']", r).val(); if (cond_op) cond_obj.cond_op = cond_op; ser_obj['rules'].push(cond_obj); } }); return ser_obj; } function getBooleanExpression(editor) { var expression = ""; $("ul:first > li", editor).each(function () { r = $(this); var c_op = $("select[name='cond-operator']", r).val(); if (c_op != undefined) c_op = '<span class="cond-op"> ' + c_op + ' </span>'; if (r.hasClass('group')) { expression += c_op + '<span class="group-op group-group">(</span>' + getBooleanExpression(this) + '<span class="group-op group-group">)</span>'; } else { expression += [ c_op, '<span class="group-op group-cond">(</span>', '<span class="comp-param">' + $("select[name='comparison-param'] option:selected", r).text() + '</span>', '<span class="comp-op"> ' + $("select[name='comparison-operator']", r).val() + ' </span>', '<span class="comp-val">' + '\'' + $("input[name='value']", r).val() + '\'' + '</span>', '<span class="group-op group-cond">)</span>' ].join(""); } }); return expression; } function changed(o) { $o = $(o); if (!$o.hasClass('enrol-attributes-boolean-editor')) { $o = $o.parents('.enrol-attributes-boolean-editor').eq(0); } if ($o.data('change')) { $o.data('change').apply($o.get(0)); } } function createRuleList(list_elem, rules) { //var list_elem = $(list_elem); if (list_elem.parent("li").eq(0).hasClass("group")) { console.log("inside a group"); return; } if (rules.length == 0) { // No rules, create a new one list_elem.append(getRuleConditionElement({first: true})); } else { // Read all rules for (var r_idx = 0; r_idx < rules.length; r_idx++) { var r = rules[r_idx]; r['first'] = (r_idx == 0); // If the rule is an array, create a group of rules if (r.rules && (typeof r.rules[0] == 'object')) { r.group = true; var rg = getRuleConditionElement(r); list_elem.append(rg); createRuleList($("ul:first", rg), r.rules); } else { list_elem.append(getRuleConditionElement(r)); } } } return list_elem; }; /** * Build the HTML code for editing a rule condition. * A rule is composed of one or more rule conditions linked by boolean operators */ function getRuleConditionElement(config) { config = $.extend({}, { first: false, group: false, cond_op: null, param: null, comp_op: null, value: '' }, config ); // If group flag is set, wrap content with <ul></ul>, content is obtained by a recursive call // to the function, passing a copy of config with flag group set to false var cond_block_content = $('<div class="sre-condition-box"></div>'); if (config.group) { cond_block_content.append('<ul></ul>'); } else { cond_block_content .append(makeSelectList({ // The list of parameters to be compared name: 'comparison-param', params: $.booleanEditor.paramList, selected_value: config.param }).addClass("comp-param")) .append($('<span>').addClass("comp-op").text('=')) // .append( makeSelectList({ // The comparison operator // name: 'comparison-operator', // params: $.booleanEditor.operatorList, // selected_value: config.comp_op // }).addClass("comp-op")) .append($('<input type="text" name="value" value="' + config.value + '"/>') .change(function () { changed(this) }) ); // The value of the comparions } var ruleConditionElement = $('<li></li>') .addClass((config.group) ? 'group' : 'rule') .append(createRuleOperatorSelect(config)) .append(cond_block_content) .append(createButtonPannel()) return ruleConditionElement; }; function createRuleOperatorSelect(config) { return (config.first) ? '' : makeSelectList({ 'name': 'cond-operator', params: [ {label: 'AND', value: 'and'}, {label: 'OR', value: 'or'} ], selected_value: config.cond_op }).addClass('sre-condition-rule-operator'); } function createButtonPannel() { var buttonPannel = $('<div class="button-pannel"></div>') .append($('<button type="button" class="button-add-cond">'+ M.util.get_string('addcondition', 'enrol_attributes') +'</button>') .click(function () { addNewConditionAfter($(this).parents('li').get(0)); }) ) .append($('<button type="button" class="button-add-group">'+ M.util.get_string('addgroup', 'enrol_attributes') +'</button>') .click(function () { addNewGroupAfter($(this).parents('li').get(0)); }) ) .append($('<button type="button" class="button-del-cond">'+ M.util.get_string('deletecondition', 'enrol_attributes') +'</button>') .click(function () { deleteCondition($(this).parents('li').eq(0)); }) ); $('button', buttonPannel).each(function () { $(this) .focus(function () { this.blur() }) .attr("title", $(this).text()) .wrapInner('<span/>'); }); return buttonPannel; } function makeSelectList(config) { config = $.extend({}, { name: 'list_name', params: [{label: 'label', value: 'value'}], selected_value: null }, config); var selectList = $('<select name="' + config.name + '"></select>') .change(function () { changed(this); }); $.each(config.params, function (i, p) { var p_obj = $('<option></option>') .attr({label: p.label, value: p.value}) .text(p.label); if (p.value == config.selected_value) { p_obj.attr("selected", "selected"); } p_obj.appendTo(selectList); }); return selectList; } // // -->> Conditions manipulation <<-- // function addNewConditionAfter(elem, config) { getRuleConditionElement(config) .hide() .insertAfter(elem) .fadeIn("normal", function () { changed(elem) }); } function addNewGroupAfter(elem, config) { getRuleConditionElement({group: true}) .hide() .insertAfter(elem) .find("ul:first") .append(getRuleConditionElement($.extend({}, config, {first: true}))) .end() .fadeIn("normal", function () { changed(elem) }); } /* * * Supprimer une condition : supprimer éventuellement le parent si dernier enfant, * mettre à jour le parent dans tous les cas. * */ function deleteCondition(elem) { if (elem.parent().parent().hasClass('enrol-attributes-boolean-editor')) { // Level 1 if (elem.siblings().length == 0) { return; } } else { // Higher level if (elem.siblings().length == 0) { // The last cond of the group, target the group itself, to be removed elem = elem.parents('li').eq(0); } } p = elem.parent(); elem.fadeOut("normal", function () { $(this).remove(); $("li:first .sre-condition-rule-operator", ".enrol-attributes-boolean-editor ul").remove(); changed(p); }); } })(jQuery);
nitro2010/moodle
enrol/attributes/js/jquery.booleanEditor.js
JavaScript
gpl-3.0
12,496
from flask import json from unittest.mock import patch, Mock from urbansearch.gathering.indices_selector import IndicesSelector from urbansearch.server.main import Server from urbansearch.server import classify_documents from urbansearch.server.classify_documents import _join_workers from urbansearch.workers import Workers s = Server(run=False) @patch('urbansearch.server.classify_documents._join_workers') @patch.object(Workers, 'run_classifying_workers') @patch.object(IndicesSelector, 'run_workers') def test_download_indices_for_url(mock_rcw, mock_rw, mock_jw): with s.app.test_client() as c: resp = c.get('/api/v1/classify_documents/log_only?directory=test') assert mock_rcw.called assert mock_rw.called assert mock_jw.called @patch('urbansearch.server.classify_documents._join_workers') @patch.object(Workers, 'run_classifying_workers') @patch.object(IndicesSelector, 'run_workers') def test_classify_indices_to_db(mock_rcw, mock_rw, mock_jw): with s.app.test_client() as c: resp = c.get('/api/v1/classify_documents/to_database?directory=test') assert mock_rcw.called assert mock_rw.called assert mock_jw.called @patch('urbansearch.server.classify_documents._join_workers') @patch('urbansearch.server.classify_documents.db_utils') def test_classify_indices_to_db_no_connection(mock_db, mock_jw): mock_db.connected_to_db.return_value = False with s.app.test_client() as c: resp = c.get('/api/v1/classify_documents/to_database?directory=test') assert not mock_jw.called @patch('urbansearch.server.classify_documents._join_file_workers') @patch.object(Workers, 'run_classifying_workers') @patch.object(Workers, 'run_read_files_worker') def test_classify_textfiles_to_db(mock_rfw, mock_rw, mock_jw): classify_documents.classify_textfiles_to_db(0, 'test') assert mock_rfw.called assert mock_rw.called assert mock_jw.called @patch('urbansearch.server.classify_documents._join_workers') @patch('urbansearch.server.classify_documents.db_utils') def test_classify_textfiles_to_db_no_connection(mock_db, mock_jw): mock_db.connected_to_db.return_value = False classify_documents.classify_textfiles_to_db(0, None) assert not mock_jw.called def test_join_workers(): producers = [Mock()] cworker = Mock() consumers = [Mock()] classify_documents._join_workers(cworker, producers, consumers) for p in producers: assert p.join.called assert cworker.set_producers_done.called for c in consumers: assert c.join.called assert cworker.clear_producers_done.called def test_join_file_workers(): producers = [Mock()] cworker = Mock() consumers = [Mock()] classify_documents._join_file_workers(cworker, producers, consumers) for p in producers: assert p.join.called assert cworker.set_file_producers_done.called for c in consumers: assert c.join.called assert cworker.clear_file_producers_done.called
urbansearchTUD/UrbanSearch
tests/server/test_classify_documents.py
Python
gpl-3.0
3,035
/* Copyright (C) 2014-2019 de4dot@gmail.com This file is part of dnSpy dnSpy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. dnSpy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with dnSpy. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using dnSpy.Contracts.Debugger; using dnSpy.Contracts.Debugger.Breakpoints.Code; using dnSpy.Contracts.Debugger.Code; using dnSpy.Debugger.Impl; namespace dnSpy.Debugger.Breakpoints.Code { abstract class DbgCodeBreakpointsService2 : DbgCodeBreakpointsService { public abstract void UpdateIsDebugging_DbgThread(bool newIsDebugging); public abstract DbgBoundCodeBreakpoint[] AddBoundBreakpoints_DbgThread(IList<DbgBoundCodeBreakpoint> boundBreakpoints); public abstract void RemoveBoundBreakpoints_DbgThread(IList<DbgBoundCodeBreakpoint> boundBreakpoints); public abstract DbgBoundCodeBreakpoint[] RemoveBoundBreakpoints_DbgThread(DbgRuntime runtime); } [Export(typeof(DbgCodeBreakpointsService))] [Export(typeof(DbgCodeBreakpointsService2))] sealed class DbgCodeBreakpointsServiceImpl : DbgCodeBreakpointsService2 { readonly object lockObj; readonly HashSet<DbgCodeBreakpointImpl> breakpoints; readonly Dictionary<DbgCodeLocation, DbgCodeBreakpointImpl> locationToBreakpoint; readonly DbgDispatcherProvider dbgDispatcherProvider; int breakpointId; bool isDebugging; public override event EventHandler<DbgBoundBreakpointsMessageChangedEventArgs> BoundBreakpointsMessageChanged; internal DbgDispatcherProvider DbgDispatcher => dbgDispatcherProvider; [ImportingConstructor] DbgCodeBreakpointsServiceImpl(DbgDispatcherProvider dbgDispatcherProvider, [ImportMany] IEnumerable<Lazy<IDbgCodeBreakpointsServiceListener>> dbgCodeBreakpointsServiceListener) { lockObj = new object(); breakpoints = new HashSet<DbgCodeBreakpointImpl>(); locationToBreakpoint = new Dictionary<DbgCodeLocation, DbgCodeBreakpointImpl>(); this.dbgDispatcherProvider = dbgDispatcherProvider; breakpointId = 0; isDebugging = false; foreach (var lz in dbgCodeBreakpointsServiceListener) lz.Value.Initialize(this); } void Dbg(Action callback) => dbgDispatcherProvider.Dbg(callback); public override void Modify(DbgCodeBreakpointAndSettings[] settings) { if (settings is null) throw new ArgumentNullException(nameof(settings)); Dbg(() => ModifyCore(settings)); } void ModifyCore(DbgCodeBreakpointAndSettings[] settings) { dbgDispatcherProvider.VerifyAccess(); List<DbgCodeBreakpointImpl>? updatedBreakpoints = null; var bps = new List<DbgCodeBreakpointAndOldSettings>(settings.Length); lock (lockObj) { foreach (var info in settings) { var bpImpl = info.Breakpoint as DbgCodeBreakpointImpl; Debug.Assert(!(bpImpl is null)); if (bpImpl is null) continue; Debug.Assert(breakpoints.Contains(bpImpl)); if (!breakpoints.Contains(bpImpl)) continue; var currentSettings = bpImpl.Settings; if (currentSettings == info.Settings) continue; bps.Add(new DbgCodeBreakpointAndOldSettings(bpImpl, currentSettings)); if (bpImpl.WriteSettings_DbgThread(info.Settings)) { if (updatedBreakpoints is null) updatedBreakpoints = new List<DbgCodeBreakpointImpl>(settings.Length); updatedBreakpoints.Add(bpImpl); } } } if (bps.Count > 0) BreakpointsModified?.Invoke(this, new DbgBreakpointsModifiedEventArgs(new ReadOnlyCollection<DbgCodeBreakpointAndOldSettings>(bps))); if (!(updatedBreakpoints is null)) { foreach (var bp in updatedBreakpoints) bp.RaiseBoundBreakpointsMessageChanged_DbgThread(); BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(updatedBreakpoints.ToArray()))); } } public override event EventHandler<DbgBreakpointsModifiedEventArgs> BreakpointsModified; public override event EventHandler<DbgCollectionChangedEventArgs<DbgCodeBreakpoint>> BreakpointsChanged; public override DbgCodeBreakpoint[] Breakpoints { get { lock (lockObj) return breakpoints.ToArray(); } } public override DbgCodeBreakpoint[] Add(DbgCodeBreakpointInfo[] breakpoints) { if (breakpoints is null) throw new ArgumentNullException(nameof(breakpoints)); var bpImpls = new List<DbgCodeBreakpointImpl>(breakpoints.Length); List<DbgObject>? objsToClose = null; lock (lockObj) { for (int i = 0; i < breakpoints.Length; i++) { var info = breakpoints[i]; var location = info.Location; if (locationToBreakpoint.ContainsKey(location)) { if (objsToClose is null) objsToClose = new List<DbgObject>(); objsToClose.Add(location); } else { var bp = new DbgCodeBreakpointImpl(this, breakpointId++, info.Options, location, info.Settings, isDebugging); bpImpls.Add(bp); } } Dbg(() => AddCore(bpImpls, objsToClose)); } return bpImpls.ToArray(); } void AddCore(List<DbgCodeBreakpointImpl> breakpoints, List<DbgObject>? objsToClose) { dbgDispatcherProvider.VerifyAccess(); var added = new List<DbgCodeBreakpoint>(breakpoints.Count); List<DbgCodeBreakpointImpl>? updatedBreakpoints = null; lock (lockObj) { foreach (var bp in breakpoints) { Debug.Assert(!this.breakpoints.Contains(bp)); if (this.breakpoints.Contains(bp)) continue; if (locationToBreakpoint.ContainsKey(bp.Location)) { if (objsToClose is null) objsToClose = new List<DbgObject>(); objsToClose.Add(bp); } else { added.Add(bp); this.breakpoints.Add(bp); locationToBreakpoint.Add(bp.Location, bp); if (bp.WriteIsDebugging_DbgThread(isDebugging)) { if (updatedBreakpoints is null) updatedBreakpoints = new List<DbgCodeBreakpointImpl>(breakpoints.Count); updatedBreakpoints.Add(bp); } } } } if (!(objsToClose is null)) { foreach (var obj in objsToClose) obj.Close(dbgDispatcherProvider.Dispatcher); } if (added.Count > 0) BreakpointsChanged?.Invoke(this, new DbgCollectionChangedEventArgs<DbgCodeBreakpoint>(added, added: true)); if (!(updatedBreakpoints is null)) { foreach (var bp in updatedBreakpoints) bp.RaiseBoundBreakpointsMessageChanged_DbgThread(); BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(updatedBreakpoints.ToArray()))); } } public override void Remove(DbgCodeBreakpoint[] breakpoints) { if (breakpoints is null) throw new ArgumentNullException(nameof(breakpoints)); Dbg(() => RemoveCore(breakpoints)); } void RemoveCore(DbgCodeBreakpoint[] breakpoints) { dbgDispatcherProvider.VerifyAccess(); var removed = new List<DbgCodeBreakpoint>(breakpoints.Length); lock (lockObj) { foreach (var bp in breakpoints) { var bpImpl = bp as DbgCodeBreakpointImpl; Debug.Assert(!(bpImpl is null)); if (bpImpl is null) continue; if (!this.breakpoints.Contains(bpImpl)) continue; removed.Add(bpImpl); this.breakpoints.Remove(bpImpl); bool b = locationToBreakpoint.Remove(bpImpl.Location); Debug.Assert(b); } } if (removed.Count > 0) { BreakpointsChanged?.Invoke(this, new DbgCollectionChangedEventArgs<DbgCodeBreakpoint>(removed, added: false)); foreach (var bp in removed) bp.Close(dbgDispatcherProvider.Dispatcher); } } public override DbgCodeBreakpoint? TryGetBreakpoint(DbgCodeLocation location) { if (location is null) throw new ArgumentNullException(nameof(location)); lock (lockObj) { if (locationToBreakpoint.TryGetValue(location, out var bp)) return bp; } return null; } public override void Clear() => Dbg(() => RemoveCore(VisibleBreakpoints.ToArray())); public override void UpdateIsDebugging_DbgThread(bool newIsDebugging) { dbgDispatcherProvider.VerifyAccess(); List<DbgCodeBreakpointImpl> updatedBreakpoints; lock (lockObj) { if (isDebugging == newIsDebugging) return; isDebugging = newIsDebugging; updatedBreakpoints = new List<DbgCodeBreakpointImpl>(breakpoints.Count); foreach (var bp in breakpoints) { bool updated = bp.WriteIsDebugging_DbgThread(isDebugging); if (updated) updatedBreakpoints.Add(bp); } } foreach (var bp in updatedBreakpoints) bp.RaiseBoundBreakpointsMessageChanged_DbgThread(); if (updatedBreakpoints.Count > 0) BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(updatedBreakpoints.ToArray()))); } public override DbgBoundCodeBreakpoint[] AddBoundBreakpoints_DbgThread(IList<DbgBoundCodeBreakpoint> boundBreakpoints) { dbgDispatcherProvider.VerifyAccess(); var dict = CreateBreakpointDictionary(boundBreakpoints); var updatedBreakpoints = new List<(bool raiseMessageChanged, DbgCodeBreakpointImpl breakpoint, List<DbgBoundCodeBreakpoint> boundBreakpoints)>(dict.Count); List<DbgBoundCodeBreakpoint>? unusedBoundBreakpoints = null; lock (lockObj) { foreach (var kv in dict) { var bp = kv.Key; if (breakpoints.Contains(bp)) { bool raiseMessageChanged = bp.AddBoundBreakpoints_DbgThread(kv.Value); updatedBreakpoints.Add((raiseMessageChanged, bp, kv.Value)); } else { if (unusedBoundBreakpoints is null) unusedBoundBreakpoints = new List<DbgBoundCodeBreakpoint>(); unusedBoundBreakpoints.AddRange(kv.Value); } } } foreach (var info in updatedBreakpoints) info.breakpoint.RaiseEvents_DbgThread(info.raiseMessageChanged, info.boundBreakpoints, added: true); if (updatedBreakpoints.Count > 0) BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(updatedBreakpoints.Where(a => a.raiseMessageChanged).Select(a => a.breakpoint).ToArray()))); return unusedBoundBreakpoints?.ToArray() ?? Array.Empty<DbgBoundCodeBreakpoint>(); } public override void RemoveBoundBreakpoints_DbgThread(IList<DbgBoundCodeBreakpoint> boundBreakpoints) { dbgDispatcherProvider.VerifyAccess(); var dict = CreateBreakpointDictionary(boundBreakpoints); var updatedBreakpoints = new List<(bool raiseMessageChanged, DbgCodeBreakpointImpl breakpoint, List<DbgBoundCodeBreakpoint> boundBreakpoints)>(dict.Count); lock (lockObj) { foreach (var kv in dict) { var bp = kv.Key; if (breakpoints.Contains(bp)) { bool raiseMessageChanged = bp.RemoveBoundBreakpoints_DbgThread(kv.Value); updatedBreakpoints.Add((raiseMessageChanged, bp, kv.Value)); } } } foreach (var info in updatedBreakpoints) info.breakpoint.RaiseEvents_DbgThread(info.raiseMessageChanged, info.boundBreakpoints, added: false); if (updatedBreakpoints.Count > 0) BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(updatedBreakpoints.Where(a => a.raiseMessageChanged).Select(a => a.breakpoint).ToArray()))); } static Dictionary<DbgCodeBreakpointImpl, List<DbgBoundCodeBreakpoint>> CreateBreakpointDictionary(IList<DbgBoundCodeBreakpoint> boundBreakpoints) { int count = boundBreakpoints.Count; var dict = new Dictionary<DbgCodeBreakpointImpl, List<DbgBoundCodeBreakpoint>>(count); for (int i = 0; i < boundBreakpoints.Count; i++) { var bound = boundBreakpoints[i]; var bpImpl = bound.Breakpoint as DbgCodeBreakpointImpl; Debug.Assert(!(bpImpl is null)); if (bpImpl is null) continue; if (!dict.TryGetValue(bpImpl, out var list)) dict.Add(bpImpl, list = new List<DbgBoundCodeBreakpoint>()); list.Add(bound); } return dict; } public override DbgBoundCodeBreakpoint[] RemoveBoundBreakpoints_DbgThread(DbgRuntime runtime) { dbgDispatcherProvider.VerifyAccess(); var list = new List<DbgBoundCodeBreakpoint>(); lock (lockObj) { foreach (var bp in breakpoints) { foreach (var boundBreakpoint in bp.BoundBreakpoints) { if (boundBreakpoint.Runtime == runtime) list.Add(boundBreakpoint); } } } var res = list.ToArray(); RemoveBoundBreakpoints_DbgThread(res); return res; } internal void OnBoundBreakpointsMessageChanged_DbgThread(DbgCodeBreakpointImpl bp) { dbgDispatcherProvider.VerifyAccess(); bp.RaiseBoundBreakpointsMessageChanged_DbgThread(); BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(new[] { bp }))); } } }
manojdjoshi/dnSpy
Extensions/dnSpy.Debugger/dnSpy.Debugger/Breakpoints/Code/DbgCodeBreakpointsServiceImpl.cs
C#
gpl-3.0
13,268
#-*- coding:utf-8 -*- from findbilibili import * #funtion name [checkinfo] #判断要输出的回答 #param array 抓取的文字 #return string 回答 def checkinfo2(content): content[1] = content[1].decode('gbk') key = content[1].encode('utf-8') if key == '节操': return '这种东西早就没有了' result = animation(key) #搜动漫 return result #funtion name [animation] #搜索动漫 #param array 动漫名字 #return string 最后更新网址 def animation(name): url = bilibili(name) try: result = 'bilibili最后更新:第'+url[-1][0]+'集'+url[-1][1] return result except IndexError: return '什么都找不到!'
cwdtom/qqbot
tom/check.py
Python
gpl-3.0
705
<? // If the form told us to generate a route or if this was a pending entry, re-generate a route. if ($data[$key] == "generate" || (isset($edit_id) && !is_numeric($edit_id))) { if ($options["not_unique"]) { $value = $cms->urlify(strip_tags($data[$options["source"]])); } else { $oroute = $cms->urlify(strip_tags($data[$options["source"]])); $value = $oroute; $x = 2; while (sqlrows(sqlquery("SELECT * FROM `".$form["table"]."` WHERE `$key` = '".sqlescape($value)."' AND id != '".sqlescape($_POST["id"])."'"))) { $value = $oroute."-".$x; $x++; } } } else { $no_process = true; } ?>
matthisamoto/bigtreedemo
core/admin/form-field-types/process/route.php
PHP
gpl-3.0
620
/** * */ package qa.AnswerFormation; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Queue; import qa.IQuestion; import qa.Utility; /** * @author Deepak * */ public class AnswerGenerator implements IAnswerGenerator { /** * * @param processedQuestionsQueue */ public AnswerGenerator(Queue<IQuestion> processedQuestionsQueue, List<IQuestion> processedQuestions) { this.processedQuestionsQueue = processedQuestionsQueue; this.processedQuestions = processedQuestions; } /** * */ @Override public void run() { while(!processedQuestionsQueue.isEmpty() || !Utility.IsPassageRetrivalDone) { IQuestion question = processedQuestionsQueue.poll(); if(question == null) continue; HashSet<String> answers = new HashSet<String>(); for(String passage : question.getRelevantPassages()) { List<String> output = new ArrayList<String>(); String passageWithoutKeywords = null; String nerTaggedPassage = Utility.getNERTagging(passage); String posTaggedPassage = Utility.getPOSTagging(passage); output.addAll(getDataFromOutput(nerTaggedPassage, question.getAnswerTypes())); output.addAll(getDataFromOutput(posTaggedPassage, question.getAnswerTypes())); for(String answer : output) { if(!question.getQuestion().toLowerCase().contains(answer.toLowerCase()) && !answers.contains(answer)) { answers.add(answer); passageWithoutKeywords = Utility.removeKeywords(answer, question.getKeywords()); question.addAnswer(passageWithoutKeywords); } } } for(String passage : question.getRelevantPassages()) { List<String> output = new ArrayList<String>(); String passageWithoutKeywords = null; if(answers.size() >= 10) break; try{ output.addAll(Utility.getNounPhrases(passage, false)); } catch (Exception ex) { System.out.println(ex.getMessage()); } for(String answer : output) { if(!question.getQuestion().toLowerCase().contains(answer.toLowerCase()) && !answers.contains(answer)) { answers.add(answer); passageWithoutKeywords = Utility.removeKeywords(answer, question.getKeywords()); question.addAnswer(passageWithoutKeywords); } } } // for(String answer : answers) { // boolean flag = true; // for(String answer1 : answers) { // if(!answer.equals(answer1)) { // if(answer1.toLowerCase().contains(answer.toLowerCase())) { // flag = false; // break; // } // } // } // if(flag) { // question.addAnswer(answer); // } // } this.processedQuestions.add(question); } AnswerWriter writer = new AnswerWriter("answer.txt"); writer.writeAnswers(processedQuestions); } /** * * @param output * @param tagName * @return */ private List<String> getDataFromOutput(String output, String tagName) { List<String> answers = new ArrayList<String>(); StringBuilder temp = new StringBuilder(); String[] outputArray = output.split("[/_\\s]"); String[] tags = tagName.split("\\|"); for(String tag : tags) { if(tag == null || tag.equals("")) continue; String[] tagsArray = tag.split(":"); for(int arrayIndex = 1; arrayIndex < outputArray.length; arrayIndex+=2) { if(outputArray[arrayIndex].trim().equals(tagsArray[1].trim())) { temp.append(outputArray[arrayIndex - 1] + " "); } else { if(!temp.toString().equals("")) { answers.add(temp.toString().trim()); } temp = new StringBuilder(); } } if(!temp.toString().equals("") ) { answers.add(temp.toString().trim()); } } return answers; } /** * */ private Queue<IQuestion> processedQuestionsQueue; private List<IQuestion> processedQuestions; }
ddeeps2610/NLP_PA2_QA
src/qa/AnswerFormation/AnswerGenerator.java
Java
gpl-3.0
3,904
// File__Duplicate - Duplication of some formats // Copyright (C) 2007-2012 MediaArea.net SARL, Info@MediaArea.net // // This library is free software: you can redistribute it and/or modify it // under the terms of the GNU Library General Public License as published by // the Free Software Foundation, either version 2 of the License, or // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Library General Public License for more details. // // You should have received a copy of the GNU Library General Public License // along with this library. If not, see <http://www.gnu.org/licenses/>. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Duplication helper for some specific formats // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #if defined(MEDIAINFO_AVC_YES) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Video/File_Avc.h" #include "MediaInfo/MediaInfo_Config.h" #include "MediaInfo/MediaInfo_Config_MediaInfo.h" #include "ZenLib/ZtringList.h" #include "ZenLib/File.h" #include <cstring> using namespace ZenLib; using namespace std; //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Options //*************************************************************************** //--------------------------------------------------------------------------- void File_Avc::Option_Manage() { #if MEDIAINFO_DUPLICATE //File__Duplicate configuration if (File__Duplicate_HasChanged()) { //Autorisation of other streams Streams[0x07].ShouldDuplicate=true; } #endif //MEDIAINFO_DUPLICATE } //*************************************************************************** // Set //*************************************************************************** //--------------------------------------------------------------------------- #if MEDIAINFO_DUPLICATE bool File_Avc::File__Duplicate_Set (const Ztring &Value) { ZtringList List(Value); //Searching Target bool IsForUs=false; std::vector<ZtringList::iterator> Targets_ToAdd; std::vector<ZtringList::iterator> Targets_ToRemove; std::vector<ZtringList::iterator> Orders_ToAdd; std::vector<ZtringList::iterator> Orders_ToRemove; for (ZtringList::iterator Current=List.begin(); Current<List.end(); ++Current) { //Detecting if we want to remove bool ToRemove=false; if (Current->find(__T('-'))==0) { ToRemove=true; Current->erase(Current->begin()); } //Managing targets if (Current->find(__T("file:"))==0 || Current->find(__T("memory:"))==0) (ToRemove?Targets_ToRemove:Targets_ToAdd).push_back(Current); //Parser name else if (Current->find(__T("parser=Avc"))==0) IsForUs=true; //Managing orders else (ToRemove?Orders_ToRemove:Orders_ToAdd).push_back(Current); } //For us? if (!IsForUs) return false; //Configuration of initial values frame_num_Old=(int32u)-1; Duplicate_Buffer_Size=0; SPS_PPS_AlreadyDone=false; FLV=false; //For each target to add for (std::vector<ZtringList::iterator>::iterator Target=Targets_ToAdd.begin(); Target<Targets_ToAdd.end(); ++Target) Writer.Configure(**Target); //For each order to add for (std::vector<ZtringList::iterator>::iterator Order=Orders_ToAdd.begin(); Order<Orders_ToAdd.end(); ++Order) if ((**Order)==__T("format=Flv")) FLV=true; return true; } #endif //MEDIAINFO_DUPLICATE //*************************************************************************** // Write //*************************************************************************** #if MEDIAINFO_DUPLICATE void File_Avc::File__Duplicate_Write (int64u Element_Code, int32u frame_num) { const int8u* ToAdd=Buffer+Buffer_Offset-(size_t)Header_Size+3; size_t ToAdd_Size=(size_t)(Element_Size+Header_Size-3); if (!SPS_PPS_AlreadyDone) { if (Element_Code==7) { std::memcpy(Duplicate_Buffer, ToAdd, ToAdd_Size); Duplicate_Buffer_Size=ToAdd_Size; } else if (Element_Code==8) { // Form: // 8 bytes : PTS // 8 bytes : DTS // 8 bytes : Size (without header) // 1 byte : Type (0=Frame, 1=Header); // 7 bytes : Reserved size_t Extra; if (FLV) Extra=1; //FLV else Extra=0; //MPEG-4 int8u Header[32]; int64u2BigEndian(Header+ 0, FrameInfo.PTS); int64u2BigEndian(Header+ 8, FrameInfo.DTS); int64u2BigEndian(Header+16, 5+Extra+2+Duplicate_Buffer_Size+1+2+ToAdd_Size); //5+Extra for SPS_SQS header, 2 for SPS size, 1 for PPS count, 2 for PPS size Header[24]=1; int56u2BigEndian(Header+25, 0); Writer.Write(Header, 32); //SPS_PPS int8u* SPS_SQS=new int8u[5+Extra]; if (Extra==1) { SPS_SQS[0]=0x01; //Profile FLV SPS_SQS[1]=(!seq_parameter_sets.empty() && seq_parameter_sets[0])?seq_parameter_sets[0]->profile_idc:0x00; //Compatible Profile. TODO: Handling more than 1 seq_parameter_set SPS_SQS[2]=0x00; //Reserved } else { SPS_SQS[0]=(!seq_parameter_sets.empty() && seq_parameter_sets[0])?seq_parameter_sets[0]->profile_idc:0x00; //Profile MPEG-4. TODO: Handling more than 1 seq_parameter_set SPS_SQS[1]=0x00; //Compatible Profile } SPS_SQS[2+Extra]=(!seq_parameter_sets.empty() && seq_parameter_sets[0])?seq_parameter_sets[0]->level_idc:0x00; //Level. TODO: Handling more than 1 seq_parameter_set SPS_SQS[3+Extra]=0xFF; //Reserved + Size of NALU length minus 1 SPS_SQS[4+Extra]=0xE1; //Reserved + seq_parameter_set count Writer.Write(SPS_SQS, 5+Extra); //NALU int8u NALU[2]; NALU[0]=((Duplicate_Buffer_Size)>> 8)&0xFF; NALU[1]=((Duplicate_Buffer_Size)>> 0)&0xFF; Writer.Write(NALU, 2); //SPS Writer.Write(Duplicate_Buffer, Duplicate_Buffer_Size); Duplicate_Buffer_Size=0; //PPS count SPS_SQS[0]=0x01; //pic_parameter_set count Writer.Write(SPS_SQS, 1); delete[] SPS_SQS; //NALU NALU[0]=((ToAdd_Size)>> 8)&0xFF; NALU[1]=((ToAdd_Size)>> 0)&0xFF; Writer.Write(NALU, 2); //PPS Writer.Write(ToAdd, ToAdd_Size); SPS_PPS_AlreadyDone=true; } } else if (frame_num!=(int32u)-1) { if (frame_num!=frame_num_Old && frame_num_Old!=(int32u)-1 && frame_num!=(int32u)-1) { // Form: // 8 bytes : PTS // 8 bytes : DTS // 8 bytes : Size (without header) // 1 byte : Type (0=Frame, 1=Header); // 7 bytes : Reserved int8u Header[32]; int64u2BigEndian(Header+ 0, FrameInfo.PTS); int64u2BigEndian(Header+ 8, FrameInfo.DTS); int64u2BigEndian(Header+16, Duplicate_Buffer_Size); Header[24]=0; int56u2BigEndian(Header+25, 0); Writer.Write(Header, 32); Writer.Write(Duplicate_Buffer, Duplicate_Buffer_Size); Duplicate_Buffer_Size=0; } //NALU int32u2BigEndian(Duplicate_Buffer+Duplicate_Buffer_Size, (int32u)ToAdd_Size); //4 bytes for NALU header Duplicate_Buffer_Size+=4; //Frame (partial) std::memcpy(Duplicate_Buffer+Duplicate_Buffer_Size, ToAdd, ToAdd_Size); Duplicate_Buffer_Size+=ToAdd_Size; frame_num_Old=frame_num; } } #endif //MEDIAINFO_DUPLICATE //*************************************************************************** // Output_Buffer //*************************************************************************** //--------------------------------------------------------------------------- #if MEDIAINFO_DUPLICATE size_t File_Avc::Output_Buffer_Get (const String &) { return Writer.Output_Buffer_Get(); } #endif //MEDIAINFO_DUPLICATE //--------------------------------------------------------------------------- #if MEDIAINFO_DUPLICATE size_t File_Avc::Output_Buffer_Get (size_t) { return Writer.Output_Buffer_Get(); } #endif //MEDIAINFO_DUPLICATE } //NameSpace #endif //MEDIAINFO_AVC_YES
MikeSouza/mpc-hc
src/thirdparty/MediaInfo/MediaInfo/Video/File_Avc_Duplicate.cpp
C++
gpl-3.0
9,917
package com.wisecityllc.cookedapp.fragments; import android.app.Activity; import android.support.v4.app.Fragment; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.parse.ParseQueryAdapter; import com.segment.analytics.Analytics; import com.wisecityllc.cookedapp.R; import com.wisecityllc.cookedapp.adapters.AlertWallAdapter; import com.wisecityllc.cookedapp.parseClasses.Message; import java.util.List; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link AlertsFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link AlertsFragment#newInstance} factory method to * create an instance of this fragment. */ public class AlertsFragment extends Fragment { public static final String ALERTS_SCREEN = "AlertsScreen"; private boolean mHasMadeInitialLoad = false; private AlertWallAdapter mAlertsAdapter; private ListView mAlertsListView; private TextView mNoAlertsTextView; private ProgressBar mLoadingIndicator; public static AlertsFragment newInstance() { AlertsFragment fragment = new AlertsFragment(); return fragment; } public AlertsFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_alerts, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLoadingIndicator = (ProgressBar) view.findViewById(R.id.alerts_fragment_loading_indicator); mAlertsAdapter = new AlertWallAdapter(this.getActivity()); mAlertsAdapter.addOnQueryLoadListener(new ParseQueryAdapter.OnQueryLoadListener<Message>() { @Override public void onLoading() { mAlertsListView.setVisibility(View.GONE); mLoadingIndicator.setVisibility(View.VISIBLE); mNoAlertsTextView.setVisibility(View.GONE); } @Override public void onLoaded(List<Message> list, Exception e) { mLoadingIndicator.setVisibility(View.GONE); mNoAlertsTextView.setVisibility(e != null || list == null || list.isEmpty() ? View.VISIBLE : View.GONE); mAlertsListView.setVisibility(View.VISIBLE); } }); if(mAlertsListView == null){ mAlertsListView = (ListView)view.findViewById(R.id.alerts_list_view); } mNoAlertsTextView = (TextView) view.findViewById(R.id.alerts_fragment_no_messages_text_view); // mAlertsListView.setOnItemClickListener(this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Uri uri); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if(isVisibleToUser) { // Has become visible Analytics.with(getActivity()).screen(null, ALERTS_SCREEN); // Delay our loading until we become visible if(mHasMadeInitialLoad == false && mAlertsAdapter != null) { mAlertsListView.setAdapter(mAlertsAdapter); mHasMadeInitialLoad = true; } } } }
dexterlohnes/cooked-android
app/src/main/java/com/wisecityllc/cookedapp/fragments/AlertsFragment.java
Java
gpl-3.0
4,689
/* * Copyright (C) 2014 - Center of Excellence in Information Assurance * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "keysgeneratorwidget.h" #include "ui_keysgeneratorwidget.h" #include "../Global/keygenerator.h" #include "../Global/keyvalidator.h" #include <QMessageBox> KeysGeneratorWidget::KeysGeneratorWidget(QWidget *parent) : QWidget(parent), ui(new Ui::KeysGeneratorWidget) { ui->setupUi(this); model = new QSqlTableModel; model->setTable("GeneratedTable"); model->select(); ui->tableView->setModel(model); ui->tableView->setAlternatingRowColors(true); ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection); ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->tableView->resizeColumnToContents(1); ui->tableView->resizeColumnToContents(0); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); } KeysGeneratorWidget::~KeysGeneratorWidget() { delete ui; } void KeysGeneratorWidget:: on_generateButton_clicked() { QString time = getTime(); QString id = getNextId(); QString constantNumber = "853023"; QString key = KeyGenerator::generateKey(time, id, constantNumber); if ( !key.endsWith("+") && KeyValidator::validate(key) ) { ui->serialLineEdit->setText(key); } } void KeysGeneratorWidget::on_generate1000KeysButton_clicked() { int count = 0; for (int i=0; i<100 ; i++ ){ QString time = getTime(); QString id = getNextId(); QString constantNumber = "853023"; QString key = KeyGenerator::generateKey(time, id, constantNumber); if ( KeyValidator::validate(key) ) { ui->serialLineEdit->setText(key); if ( ! existKey (key) && ! key.endsWith("+") ) { QSqlQuery query; QString time = QDate::currentDate().toString(); if ( query.exec("insert into GeneratedTable(serial, generateTime) values('" + key + "' , '" + time +"')") ) { qDebug() << "key: " << key; count++; } } } } qDebug() << "Number of Key Saved: " << count; } void KeysGeneratorWidget::on_saveKeyButton_clicked() { QString key = ui->serialLineEdit->text(); if ( KeyValidator::validate(key) ) { if ( ! existKey (key) && ! key.endsWith("+") ) { QSqlQuery query; QString time = QDate::currentDate().toString(); if ( query.exec("insert into GeneratedTable(serial, generateTime) values('" + key + "' , '" + time +"')") ) QMessageBox::information(this,"inserting Ok","inserting Ok"); else QMessageBox::warning(this,"cannot inserting key","cannot inserting key"); } else { QMessageBox::warning(this,"Key existing in DB","Key existing in DB"); } } else { QMessageBox::warning(this,"is not valid key", key + " is not valid key"); } model->select(); } void KeysGeneratorWidget::on_removeKeyButton_clicked() { int no = model->index(ui->tableView->currentIndex().row(),0).data().toInt(); QSqlQuery query; query.prepare("DELETE FROM GeneratedTable WHERE id = ?"); query.addBindValue(no); query.exec(); model->select(); } bool KeysGeneratorWidget:: existKey (QString key) { QSqlQuery query; query.prepare("SELECT * FROM GeneratedTable WHERE serial = ?"); query.addBindValue(key); query.exec(); while (query.next()) { return true; } return false; } QString KeysGeneratorWidget:: getTime () { QTime time = QTime::currentTime(); QString result = QString::number(time.msec()); return result; } QString KeysGeneratorWidget:: getNextId () { QString id = getRandomChars(5); return id; } QString KeysGeneratorWidget:: getRandomChars (int length) { int difference = 'Z'-'A'; QString result = ""; for (int i=0; i<length; i++) { char c = 'A' + ( rand() % difference ); result += c ; } return result; }
CoEIA/hajeb
CoEIAKeysGenerator/keysgeneratorwidget.cpp
C++
gpl-3.0
4,671
<?php require "funciones.php"; CopiarArchivo($_REQUEST["txtRuta"]); ?>
1caruxx/Ejercicios_PHP
C._Archivos_y_formularios/ejercicio_22/admin.php
PHP
gpl-3.0
80
package org.aslab.om.metacontrol.action; import java.util.HashSet; import java.util.Set; import org.aslab.om.ecl.action.Action; import org.aslab.om.ecl.action.ActionFeedback; import org.aslab.om.ecl.action.ActionResult; import org.aslab.om.metacontrol.value.CompGoalAtomTracker; /** * <!-- begin-UML-doc --> * <!-- end-UML-doc --> * @author chcorbato * @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)" */ public class FunctionalAction extends Action { /** * <!-- begin-UML-doc --> * number of ever issued action_list (this way a new number is assigned to everyone upon creation) * <!-- end-UML-doc --> * @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)" */ private static short num_of_actions = 0; @Override protected short addAction(){ return num_of_actions++; } /** * <!-- begin-UML-doc --> * <!-- end-UML-doc --> * @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)" */ public Set<CompGoalAtomTracker> atoms = new HashSet<CompGoalAtomTracker>(); /** * <!-- begin-UML-doc --> * <!-- end-UML-doc --> * @param a * @generated "UML to Java (com.ibm.xtools.transform.uml2.java5.internal.UML2JavaTransform)" */ public FunctionalAction(Set<CompGoalAtomTracker> a) { // begin-user-code atoms = a; // end-user-code } @Override public ActionResult processResult(ActionFeedback feedback) { // TODO Auto-generated method stub return null; } @Override public boolean timeOut() { // TODO Auto-generated method stub return false; } }
aslab/rct
higgs/branches/ros-fuerte/OM/versions/NamePerception_OM/OMJava/src/org/aslab/om/metacontrol/action/FunctionalAction.java
Java
gpl-3.0
1,624
$(function() { $("#childGrid").jqGrid( { url : "TBCcnsizePrm.html?getGridData",datatype : "json",mtype : "GET",colNames : [ 'Conn Id',getLocalMessage('water.connsize.frmDt'), getLocalMessage('water.connsize.toDt'), getLocalMessage('water.connsize.frm'),getLocalMessage('water.connsize.to'), getLocalMessage('edit.msg'), getLocalMessage('master.view')], colModel : [ {name : "cnsId",width : 10,sortable : false,searchoptions: { "sopt": [ "eq"] }}, {name : "cnsFrmdt",width : 20,sortable : true,searchoptions: { "sopt": ["bw", "eq"] },formatter : dateTemplate}, {name : "cnsTodt",width : 20,sortable : true, searchoptions: { "sopt": ["bw", "eq"] },formatter : dateTemplate}, {name : "cnsFrom",width : 20,sortable : false,searchoptions: { "sopt": [ "eq"] }}, {name : "cnsTo",width : 20,sortable : false,searchoptions: { "sopt": [ "eq"] }}, {name : 'cnsId',index : 'cnsId',width : 20,align : 'center',formatter : returnEditUrl,editoptions : {value : "Yes:No"},formatoptions : {disabled : false},search:false }, {name : 'cnsId',index : 'cnsId',width : 20,align : 'center',formatter : returnViewUrl,editoptions : {value : "Yes:No"},formatoptions : {disabled : false},search:false} ], pager : "#pagered", rowNum : 30, rowList : [ 5, 10, 20, 30 ], sortname : "dsgid", sortorder : "desc", height : 'auto', viewrecords : true, gridview : true, loadonce : true, jsonReader : { root : "rows", page : "page", total : "total", records : "records", repeatitems : false, }, autoencode : true, caption : getLocalMessage('water.connsize.gridTtl') }); jQuery("#grid").jqGrid('navGrid','#pagered',{edit:false,add:false,del:false,search:true,refresh:false}); $("#pagered_left").css("width", ""); }); function returnEditUrl(cellValue, options, rowdata, action) { return "<a href='#' return false; class='editClass' value='"+rowdata.cnsId+"' ><img src='css/images/edit.png' width='20px' alt='Edit Charge Master' title='Edit Scrutiny Data' /></a>"; } function returnViewUrl(cellValue, options, rowdata, action) { return "<a href='#' return false; class='viewConnectionClass' value='"+rowdata.cnsId+"'><img src='css/images/grid/view-icon.png' width='20px' alt='View Master' title='View Master' /></a>"; } function returnisdeletedUrl(cellValue, options, rowdata, action) { if (rowdata.isdeleted == '0') { return "<a href='#' class='fa fa-check-circle fa-2x green ' value='"+rowdata.isdeleted+"' alt='Designation is Active' title='Designation is Active'></a>"; } else { return "<a href='#' class='fa fa-times-circle fa-2x red ' value='"+rowdata.isdeleted+"' alt='Designation is INActive' title='Designation is InActive'></a>"; } } $(function() { $(document) .on('click','.addConnectionClass',function() { var $link = $(this); var cnsId = $link.closest('tr').find('td:eq(0)').text(); var url = "TBCcnsizePrm.html?formForUpdate"; var requestData = "cnsId=" + cnsId + "&MODE1=" + "EDIT"; var returnData =__doAjaxRequest(url,'post',requestData,false); $('.content').html(returnData); prepareDateTag(); }); }); $(function() { $(document).on('click', '.editClass', function() { var $link = $(this); var cnsId = $link.closest('tr').find('td:eq(0)').text(); var url = "TBCcnsizePrm.html?formForUpdate"; var requestData = "cnsId=" + cnsId + "&MODE1=" + "EDIT"; var returnData =__doAjaxRequest(url,'post',requestData,false); $('.content').html(returnData); prepareDateTag(); }); }); $(function() { $(document).on('click', '.viewConnectionClass', function() { var $link = $(this); var cnsId = $link.closest('tr').find('td:eq(0)').text(); var url = "TBCcnsizePrm.html?formForUpdate"; var requestData = "cnsId=" + cnsId + "&MODE1=" + "VIEW"; var returnData =__doAjaxRequest(url,'post',requestData,false); $('.content').html(returnData); prepareDateTag(); }); }); /*ADD Form*/ function saveConnectionSizeDetails(obj){ return saveOrUpdateForm(obj, 'Saved Successfully', 'TBCcnsizePrm.html', 'create'); } function updateConnectionSizeDetails(obj){ return saveOrUpdateForm(obj, 'Saved Successfully', 'TBCcnsizePrm.html', 'update'); } function showConfirmBox(){ var errMsgDiv = '.msg-dialog-box'; var message=''; var cls = 'Yes'; message +='<p>Record Saved Successfully..</p>'; message +='<p style=\'text-align:center;margin: 5px;\'>'+ '<br/><input type=\'button\' value=\''+cls+'\' id=\'btnNo\' class=\'css_btn \' '+ ' onclick="ShowView()"/>'+ '</p>'; $(errMsgDiv).addClass('ok-msg').removeClass('warn-msg'); $(errMsgDiv).html(message); $(errMsgDiv).show(); $('#btnNo').focus(); showModalBox(errMsgDiv); } function ShowView(){ window.location.href='TBCcnsizePrm.html'; } $(".datepicker").datepicker({ dateFormat: 'dd/mm/yy', changeMonth: true, changeYear: true }); $(".warning-div ul").each(function () { var lines = $(this).html().split("<br>"); $(this).html('<li>' + lines.join("</li><li><i class='fa fa-exclamation-circle'></i>&nbsp;") + '</li>'); }); $('html,body').animate({ scrollTop: 0 }, 'slow');
abmindiarepomanager/ABMOpenMainet
Mainet1.1/MainetServiceParent/MainetServiceWeb/src/main/webapp/js/masters/connectionsize/connectionSizeScript.js
JavaScript
gpl-3.0
5,451
// Copyleft 2005 Chris Korda // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the Free // Software Foundation; either version 2 of the License, or any later version. /* chris korda revision history: rev date comments 00 22apr05 initial version 01 07jul05 keep dialog within screen 02 23nov07 support Unicode 03 16dec08 in OnShowWindow, move LoadWnd within bShow block 04 24mar09 add special handling for main accelerators 05 21dec12 in OnShowWindow, don't clamp to work area if maximized 06 24jul15 override DoModal to save and restore focus 07 06jul17 remove update menu method dialog that saves and restores its position */ // PersistDlg.cpp : implementation file // #include "stdafx.h" #include "Resource.h" #include "PersistDlg.h" #include "Persist.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CPersistDlg dialog IMPLEMENT_DYNAMIC(CPersistDlg, CDialog); CPersistDlg::CPersistDlg(UINT nIDTemplate, UINT nIDAccel, LPCTSTR RegKey, CWnd *pParent) : CDialog(nIDTemplate, pParent), m_RegKey(RegKey) { //{{AFX_DATA_INIT(CPersistDlg) //}}AFX_DATA_INIT m_WasShown = FALSE; m_IDAccel = nIDAccel; m_Accel = nIDAccel != NULL && nIDAccel != IDR_MAINFRAME ? LoadAccelerators(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(nIDAccel)) : NULL; } void CPersistDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPersistDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPersistDlg, CDialog) //{{AFX_MSG_MAP(CPersistDlg) ON_WM_DESTROY() ON_WM_SHOWWINDOW() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPersistDlg message handlers void CPersistDlg::OnDestroy() { CDialog::OnDestroy(); if (m_WasShown) CPersist::SaveWnd(REG_SETTINGS, this, m_RegKey); } void CPersistDlg::OnShowWindow(BOOL bShow, UINT nStatus) { CDialog::OnShowWindow(bShow, nStatus); if (bShow) { if (!m_WasShown && !IsWindowVisible()) { m_WasShown = TRUE; int Flags = (GetStyle() & WS_THICKFRAME) ? 0 : CPersist::NO_RESIZE; CPersist::LoadWnd(REG_SETTINGS, this, m_RegKey, Flags); } if (!IsZoomed()) { // unless we're maximized, clamp to work area // in case LoadWnd's SetWindowPlacement places us off-screen CRect r, wr; GetWindowRect(r); if (SystemParametersInfo(SPI_GETWORKAREA, 0, wr, 0)) { CRect br = wr; br.right -= GetSystemMetrics(SM_CXSMICON); br.bottom -= GetSystemMetrics(SM_CYCAPTION); CPoint pt = r.TopLeft(); if (!br.PtInRect(pt)) { // if dialog is off-screen pt.x = CLAMP(pt.x, wr.left, wr.right - r.Width()); pt.y = CLAMP(pt.y, wr.top, wr.bottom - r.Height()); r = CRect(pt, CSize(r.Width(), r.Height())); MoveWindow(r); } } } } } BOOL CPersistDlg::PreTranslateMessage(MSG* pMsg) { if (pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST) { if (m_Accel != NULL) { if (TranslateAccelerator(m_hWnd, m_Accel, pMsg)) return(TRUE); } else { // no local accelerator table // if non-system key down and main accelerators, give main a try if (pMsg->message == WM_KEYDOWN && m_IDAccel == IDR_MAINFRAME && AfxGetMainWnd()->SendMessage(UWM_HANDLEDLGKEY, (WPARAM)pMsg)) return(TRUE); } } return CDialog::PreTranslateMessage(pMsg); } W64INT CPersistDlg::DoModal() { HWND hWndFocus = ::GetFocus(); W64INT retc = CDialog::DoModal(); if (IsWindow(hWndFocus) && ::IsWindowVisible(hWndFocus)) // extra cautious ::SetFocus(hWndFocus); return retc; }
victimofleisure/PotterDraw
trunk/PotterDraw/PersistDlg.cpp
C++
gpl-3.0
3,742
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WaterItem : BaseItem { // Use this for initialization public override void Start() { base.Start(); BulletSpeed = .1f; ItemSprite = gameObject.GetComponent<SpriteRenderer>().sprite; NameText = "Water"; PickupText = "Shot Speed up"; } // Update is called once per frame void Update () { } }
Shafournee/Shafman-repo
Assets/Scripts/Item Scipts/ShotSpeedItems/WaterItem.cs
C#
gpl-3.0
455
package net.ballmerlabs.scatterbrain.network.wifidirect; import android.os.Handler; import android.os.Looper; import android.os.Message; import net.ballmerlabs.scatterbrain.network.GlobalNet; /** * Created by user on 5/29/16. */ @SuppressWarnings({"FieldCanBeLocal", "DefaultFileTemplate"}) class WifiDirectLooper extends Thread { private Handler handler; @SuppressWarnings("unused") private final GlobalNet globnet; public WifiDirectLooper(GlobalNet globnet) { super(); this.globnet = globnet; handler = new Handler(); } public Handler getHandler() { return this.handler; } @Override public void run() { Looper.prepare(); handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { return true; } }); Looper.loop(); } }
gnu3ra/Scatterbrain
app/src/main/java/net/ballmerlabs/scatterbrain/network/wifidirect/WifiDirectLooper.java
Java
gpl-3.0
938
/** * @file Map places of interest * @author Tom Jenkins tom@itsravenous.com */ module.exports = { castle: { title: 'Rowton Castle', lat: 52.708739, lng: -2.9228567, icon: 'pin_castle.png', main: true, description: 'Where it all happens! Rowton Castle is a small castle manor house roughly halfway between Shrewsbury and Welshpool.', link: 'https://rowtoncastle.com' }, barns: { title: 'Rowton Barns', lat: 52.709265, lng: -2.9255, icon: 'pin_hotel.png', description: 'Just a <del>drunken stumble</del> <ins>short stroll</ins> from the castle, Rowton Barns offers rooms in their beautifully converted farm buildings.', link: 'http://www.rowtonbarns.co.uk/' }, wollaston: { title: 'Wollaston Lodge', lat: 52.7036, lng: -2.9943, icon: 'pin_hotel.png', description: 'A boutique bed and breakfast with individually themed rooms.', link: 'http://www.wollastonlodge.co.uk/' }, travelodge: { title: 'Shrewsbury Travelodge', lat: 52.6817939, lng: -2.7645268, icon: 'pin_hotel.png', description: 'On Bayston Hill services, with free parking.', link: 'https://www.travelodge.co.uk/hotels/175/Shrewsbury-Bayston-Hill-hotel' } };
itsravenous/lizandtomgetmarried
src/components/map/places.js
JavaScript
gpl-3.0
1,179
var struct_create_packets_1_1__2 = [ [ "angle", "struct_create_packets_1_1__2.html#a425d33bd27790066ff7edb4a608a8149", null ], [ "buttons", "struct_create_packets_1_1__2.html#a6b7d2d6c0a3a063f873420c010063b33", null ], [ "distance", "struct_create_packets_1_1__2.html#afb30de28ec41190d0cb278640d4782ab", null ], [ "ir", "struct_create_packets_1_1__2.html#ac834057741105e898b3d4613b96c6eb1", null ] ];
kipr/harrogate
shared/client/doc/struct_create_packets_1_1__2.js
JavaScript
gpl-3.0
416
/* xoreos-tools - Tools to help with xoreos development * * xoreos-tools is the legal property of its developers, whose names * can be found in the AUTHORS file distributed with this source * distribution. * * xoreos-tools is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * xoreos-tools is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with xoreos-tools. If not, see <http://www.gnu.org/licenses/>. */ /** @file * Base64 encoding and decoding. */ #include <cassert> #include <memory> #include "src/common/base64.h" #include "src/common/ustring.h" #include "src/common/error.h" #include "src/common/readstream.h" #include "src/common/memreadstream.h" #include "src/common/memwritestream.h" namespace Common { static const char kBase64Char[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const uint8_t kBase64Values[128] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x3E, 0xFF, 0xFF, 0xFF, 0x3F, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; /** Write a character into our base64 string, and update the remaining * string length. * * Returns false if we ran out of remaining characters in this string. */ static bool writeCharacter(UString &base64, uint32_t c, size_t &maxLength) { assert(maxLength > 0); base64 += c; return --maxLength > 0; } /** Write multiple characters into our base64 string, and update the remaining * string length. * * Returns false if we ran out of remaining characters in this string. */ static bool writeCharacters(UString &base64, UString &str, size_t &lineLength) { while (!str.empty()) { writeCharacter(base64, *str.begin(), lineLength); str.erase(str.begin()); if (lineLength == 0) return false; } return lineLength > 0; } /** Find the raw value of a base64-encoded character. */ static uint8_t findCharacterValue(uint32_t c) { if ((c >= 128) || (kBase64Values[c] > 0x3F)) throw Exception("Invalid base64 character"); return kBase64Values[c]; } /** Encode data into base64 and write the result into the string, but only up * to maxLength characters. * * The string overhang is and input/output string of both the overhang from * the previous run of this function (which will get written into the base64 * string first) and the newly produced overhang. * * Returns false if we have written all data there is to write, both from the * overhang and the input data stream. */ static bool encodeBase64(ReadStream &data, UString &base64, size_t maxLength, UString &overhang) { if (maxLength == 0) throw Exception("Invalid base64 max line length"); // First write the overhang, and return if we already maxed out the length there if (!writeCharacters(base64, overhang, maxLength)) return true; overhang.clear(); uint8_t n; byte input[3]; // Read up to 3 characters at a time while ((n = data.read(input, 3)) != 0) { uint32_t code = 0; // Concat the input characters for (uint8_t i = 0; i < n; i++) code |= input[i] << (24 - i * 8); // Create up to 4 6-bit base64-characters out of them for (uint8_t i = 0; i < (n + 1); i++) { overhang += kBase64Char[(code >> 26) & 0x0000003F]; code <<= 6; } // Add padding for (int i = 0; i < (3 - n); i++) overhang += '='; // Write the base64 characters into the string, and return if we maxed out the length if (!writeCharacters(base64, overhang, maxLength)) return true; overhang.clear(); } // We reached the end of input the data return false; } static void decodeBase64(WriteStream &data, const UString &base64, UString &overhang) { assert(overhang.size() < 4); for (UString::iterator c = base64.begin(); c != base64.end(); ++c) { if ((*c != '=') && ((*c >= 128) || (kBase64Values[*c] > 0x3F))) continue; overhang += *c; if (overhang.size() == 4) { uint32_t code = 0; uint8_t n = 0; for (UString::iterator o = overhang.begin(); o != overhang.end(); ++o) { code <<= 6; if (*o != '=') { code += findCharacterValue(*o); n += 6; } } for (size_t i = 0; i < (n / 8); i++, code <<= 8) data.writeByte((byte) ((code & 0x00FF0000) >> 16)); overhang.clear(); } } } static size_t countLength(const UString &str, bool partial = false) { size_t dataLength = 0; for (const auto &c : str) { if ((c == '=') || ((c < 128) && kBase64Values[c] <= 0x3F)) ++dataLength; } if (!partial) if ((dataLength % 4) != 0) throw Exception("Invalid length for a base64-encoded string"); return dataLength; } static size_t countLength(const std::list<UString> &str) { size_t dataLength = 0; for (const auto &s : str) dataLength += countLength(s, true); if ((dataLength % 4) != 0) throw Exception("Invalid length for a base64-encoded string"); return dataLength; } void encodeBase64(ReadStream &data, UString &base64) { UString overhang; encodeBase64(data, base64, SIZE_MAX, overhang); } void encodeBase64(ReadStream &data, std::list<UString> &base64, size_t lineLength) { UString overhang; // Base64-encode the data, creating a new string after every lineLength characters do { base64.push_back(UString()); } while (encodeBase64(data, base64.back(), lineLength, overhang)); // Trim empty strings from the back while (!base64.empty() && base64.back().empty()) base64.pop_back(); } SeekableReadStream *decodeBase64(const UString &base64) { const size_t dataLength = (countLength(base64) / 4) * 3; std::unique_ptr<byte[]> data = std::make_unique<byte[]>(dataLength); MemoryWriteStream output(data.get(), dataLength); UString overhang; decodeBase64(output, base64, overhang); return new MemoryReadStream(data.release(), output.pos(), true); } SeekableReadStream *decodeBase64(const std::list<UString> &base64) { const size_t dataLength = (countLength(base64) / 4) * 3; std::unique_ptr<byte[]> data = std::make_unique<byte[]>(dataLength); MemoryWriteStream output(data.get(), dataLength); UString overhang; for (std::list<UString>::const_iterator b = base64.begin(); b != base64.end(); ++b) decodeBase64(output, *b, overhang); return new MemoryReadStream(data.release(), output.pos(), true); } } // End of namespace Common
xoreos/xoreos-tools
src/common/base64.cpp
C++
gpl-3.0
7,266
package org.jlinda.nest.gpf; import com.bc.ceres.core.ProgressMonitor; import org.apache.commons.math3.util.FastMath; import org.esa.beam.framework.datamodel.Band; import org.esa.beam.framework.datamodel.MetadataElement; import org.esa.beam.framework.datamodel.Product; import org.esa.beam.framework.datamodel.ProductData; import org.esa.beam.framework.gpf.Operator; import org.esa.beam.framework.gpf.OperatorException; import org.esa.beam.framework.gpf.OperatorSpi; import org.esa.beam.framework.gpf.Tile; import org.esa.beam.framework.gpf.annotations.OperatorMetadata; import org.esa.beam.framework.gpf.annotations.Parameter; import org.esa.beam.framework.gpf.annotations.SourceProduct; import org.esa.beam.framework.gpf.annotations.TargetProduct; import org.esa.beam.util.ProductUtils; import org.esa.snap.datamodel.AbstractMetadata; import org.esa.snap.datamodel.Unit; import org.esa.snap.gpf.OperatorUtils; import org.esa.snap.gpf.ReaderUtils; import org.jblas.ComplexDoubleMatrix; import org.jblas.DoubleMatrix; import org.jblas.MatrixFunctions; import org.jblas.Solve; import org.jlinda.core.Orbit; import org.jlinda.core.SLCImage; import org.jlinda.core.Window; import org.jlinda.core.utils.MathUtils; import org.jlinda.core.utils.PolyUtils; import org.jlinda.core.utils.SarUtils; import org.jlinda.nest.utils.BandUtilsDoris; import org.jlinda.nest.utils.CplxContainer; import org.jlinda.nest.utils.ProductContainer; import org.jlinda.nest.utils.TileUtilsDoris; import java.awt.*; import java.util.HashMap; import java.util.Map; @OperatorMetadata(alias = "Interferogram", category = "SAR Processing/Interferometric/Products", authors = "Petar Marinkovic", copyright = "Copyright (C) 2013 by PPO.labs", description = "Compute interferograms from stack of coregistered images : JBLAS implementation") public class InterferogramOp extends Operator { @SourceProduct private Product sourceProduct; @TargetProduct private Product targetProduct; @Parameter(valueSet = {"1", "2", "3", "4", "5", "6", "7", "8"}, description = "Order of 'Flat earth phase' polynomial", defaultValue = "5", label = "Degree of \"Flat Earth\" polynomial") private int srpPolynomialDegree = 5; @Parameter(valueSet = {"301", "401", "501", "601", "701", "801", "901", "1001"}, description = "Number of points for the 'flat earth phase' polynomial estimation", defaultValue = "501", label = "Number of 'Flat earth' estimation points") private int srpNumberPoints = 501; @Parameter(valueSet = {"1", "2", "3", "4", "5"}, description = "Degree of orbit (polynomial) interpolator", defaultValue = "3", label = "Orbit interpolation degree") private int orbitDegree = 3; @Parameter(defaultValue="false", label="Do NOT subtract flat-earth phase from interferogram.") private boolean doNotSubtract = false; // flat_earth_polynomial container private HashMap<String, DoubleMatrix> flatEarthPolyMap = new HashMap<String, DoubleMatrix>(); // source private HashMap<Integer, CplxContainer> masterMap = new HashMap<Integer, CplxContainer>(); private HashMap<Integer, CplxContainer> slaveMap = new HashMap<Integer, CplxContainer>(); // target private HashMap<String, ProductContainer> targetMap = new HashMap<String, ProductContainer>(); // operator tags private static final boolean CREATE_VIRTUAL_BAND = true; private String productName; public String productTag; private int sourceImageWidth; private int sourceImageHeight; /** * Initializes this operator and sets the one and only target product. * <p>The target product can be either defined by a field of type {@link org.esa.beam.framework.datamodel.Product} annotated with the * {@link org.esa.beam.framework.gpf.annotations.TargetProduct TargetProduct} annotation or * by calling {@link #setTargetProduct} method.</p> * <p>The framework calls this method after it has created this operator. * Any client code that must be performed before computation of tile data * should be placed here.</p> * * @throws org.esa.beam.framework.gpf.OperatorException * If an error occurs during operator initialisation. * @see #getTargetProduct() */ @Override public void initialize() throws OperatorException { try { // rename product if no subtraction of the flat-earth phase if (doNotSubtract) { productName = "ifgs"; productTag = "ifg"; } else { productName = "srp_ifgs"; productTag = "ifg_srp"; } checkUserInput(); constructSourceMetadata(); constructTargetMetadata(); createTargetProduct(); // final String[] masterBandNames = sourceProduct.getBandNames(); // for (int i = 0; i < masterBandNames.length; i++) { // if (masterBandNames[i].contains("mst")) { // masterBand1 = sourceProduct.getBand(masterBandNames[i]); // if (masterBand1.getUnit() != null && masterBand1.getUnit().equals(Unit.REAL)) { // masterBand2 = sourceProduct.getBand(masterBandNames[i + 1]); // } // break; // } // } // // getMetadata(); getSourceImageDimension(); if (!doNotSubtract) { constructFlatEarthPolynomials(); } } catch (Exception e) { throw new OperatorException(e); } } private void getSourceImageDimension() { sourceImageWidth = sourceProduct.getSceneRasterWidth(); sourceImageHeight = sourceProduct.getSceneRasterHeight(); } private void constructFlatEarthPolynomials() throws Exception { for (Integer keyMaster : masterMap.keySet()) { CplxContainer master = masterMap.get(keyMaster); for (Integer keySlave : slaveMap.keySet()) { CplxContainer slave = slaveMap.get(keySlave); flatEarthPolyMap.put(slave.name, estimateFlatEarthPolynomial(master.metaData, master.orbit, slave.metaData, slave.orbit)); } } } private void constructTargetMetadata() { for (Integer keyMaster : masterMap.keySet()) { CplxContainer master = masterMap.get(keyMaster); for (Integer keySlave : slaveMap.keySet()) { // generate name for product bands final String productName = keyMaster.toString() + "_" + keySlave.toString(); final CplxContainer slave = slaveMap.get(keySlave); final ProductContainer product = new ProductContainer(productName, master, slave, true); product.targetBandName_I = "i_" + productTag + "_" + master.date + "_" + slave.date; product.targetBandName_Q = "q_" + productTag + "_" + master.date + "_" + slave.date; // put ifg-product bands into map targetMap.put(productName, product); } } } private void constructSourceMetadata() throws Exception { // define sourceMaster/sourceSlave name tags final String masterTag = "mst"; final String slaveTag = "slv"; // get sourceMaster & sourceSlave MetadataElement final MetadataElement masterMeta = AbstractMetadata.getAbstractedMetadata(sourceProduct); final String slaveMetadataRoot = AbstractMetadata.SLAVE_METADATA_ROOT; /* organize metadata */ // put sourceMaster metadata into the masterMap metaMapPut(masterTag, masterMeta, sourceProduct, masterMap); // plug sourceSlave metadata into slaveMap MetadataElement slaveElem = sourceProduct.getMetadataRoot().getElement(slaveMetadataRoot); if(slaveElem == null) { slaveElem = sourceProduct.getMetadataRoot().getElement("Slave Metadata"); } MetadataElement[] slaveRoot = slaveElem.getElements(); for (MetadataElement meta : slaveRoot) { metaMapPut(slaveTag, meta, sourceProduct, slaveMap); } } private void metaMapPut(final String tag, final MetadataElement root, final Product product, final HashMap<Integer, CplxContainer> map) throws Exception { // TODO: include polarization flags/checks! // pull out band names for this product final String[] bandNames = product.getBandNames(); final int numOfBands = bandNames.length; // map key: ORBIT NUMBER int mapKey = root.getAttributeInt(AbstractMetadata.ABS_ORBIT); // metadata: construct classes and define bands final String date = OperatorUtils.getAcquisitionDate(root); final SLCImage meta = new SLCImage(root); final Orbit orbit = new Orbit(root, orbitDegree); // TODO: resolve multilook factors meta.setMlAz(1); meta.setMlRg(1); Band bandReal = null; Band bandImag = null; for (int i = 0; i < numOfBands; i++) { String bandName = bandNames[i]; if (bandName.contains(tag) && bandName.contains(date)) { final Band band = product.getBandAt(i); if (BandUtilsDoris.isBandReal(band)) { bandReal = band; } else if (BandUtilsDoris.isBandImag(band)) { bandImag = band; } } } try { map.put(mapKey, new CplxContainer(date, meta, orbit, bandReal, bandImag)); } catch (Exception e) { e.printStackTrace(); } } private void createTargetProduct() { // construct target product targetProduct = new Product(productName, sourceProduct.getProductType(), sourceProduct.getSceneRasterWidth(), sourceProduct.getSceneRasterHeight()); ProductUtils.copyProductNodes(sourceProduct, targetProduct); for (final Band band : targetProduct.getBands()) { targetProduct.removeBand(band); } for (String key : targetMap.keySet()) { String targetBandName_I = targetMap.get(key).targetBandName_I; targetProduct.addBand(targetBandName_I, ProductData.TYPE_FLOAT32); targetProduct.getBand(targetBandName_I).setUnit(Unit.REAL); String targetBandName_Q = targetMap.get(key).targetBandName_Q; targetProduct.addBand(targetBandName_Q, ProductData.TYPE_FLOAT32); targetProduct.getBand(targetBandName_Q).setUnit(Unit.IMAGINARY); final String tag0 = targetMap.get(key).sourceMaster.date; final String tag1 = targetMap.get(key).sourceSlave.date; if (CREATE_VIRTUAL_BAND) { String countStr = "_" + productTag + "_" + tag0 + "_" + tag1; ReaderUtils.createVirtualIntensityBand(targetProduct, targetProduct.getBand(targetBandName_I), targetProduct.getBand(targetBandName_Q), countStr); ReaderUtils.createVirtualPhaseBand(targetProduct, targetProduct.getBand(targetBandName_I), targetProduct.getBand(targetBandName_Q), countStr); } } // For testing: the optimal results with 1024x1024 pixels tiles, not clear whether it's platform dependent? // targetProduct.setPreferredTileSize(512, 512); } private void checkUserInput() throws OperatorException { // check for the logic in input paramaters final MetadataElement masterMeta = AbstractMetadata.getAbstractedMetadata(sourceProduct); final int isCoregStack = masterMeta.getAttributeInt(AbstractMetadata.coregistered_stack); if (isCoregStack != 1) { throw new OperatorException("Input should be a coregistered SLC stack"); } } private DoubleMatrix estimateFlatEarthPolynomial(SLCImage masterMetadata, Orbit masterOrbit, SLCImage slaveMetadata, Orbit slaveOrbit) throws Exception { // estimation window : this works only for NEST "crop" logic // long minLine = masterMetadata.getCurrentWindow().linelo; // long maxLine = masterMetadata.getCurrentWindow().linehi; // long minPixel = masterMetadata.getCurrentWindow().pixlo; // long maxPixel = masterMetadata.getCurrentWindow().pixhi; long minLine = 0; long maxLine = sourceImageHeight; long minPixel = 0; long maxPixel = sourceImageWidth; int numberOfCoefficients = PolyUtils.numberOfCoefficients(srpPolynomialDegree); int[][] position = MathUtils.distributePoints(srpNumberPoints, new Window(minLine,maxLine,minPixel,maxPixel)); // setup observation and design matrix DoubleMatrix y = new DoubleMatrix(srpNumberPoints); DoubleMatrix A = new DoubleMatrix(srpNumberPoints, numberOfCoefficients); double masterMinPi4divLam = (-4 * Math.PI * org.jlinda.core.Constants.SOL) / masterMetadata.getRadarWavelength(); double slaveMinPi4divLam = (-4 * Math.PI * org.jlinda.core.Constants.SOL) / slaveMetadata.getRadarWavelength(); // Loop through vector or distributedPoints() for (int i = 0; i < srpNumberPoints; ++i) { double line = position[i][0]; double pixel = position[i][1]; // compute azimuth/range time for this pixel final double masterTimeRange = masterMetadata.pix2tr(pixel + 1); // compute xyz of this point : sourceMaster org.jlinda.core.Point xyzMaster = masterOrbit.lp2xyz(line + 1, pixel + 1, masterMetadata); org.jlinda.core.Point slaveTimeVector = slaveOrbit.xyz2t(xyzMaster, slaveMetadata); final double slaveTimeRange = slaveTimeVector.x; // observation vector y.put(i, (masterMinPi4divLam * masterTimeRange) - (slaveMinPi4divLam * slaveTimeRange)); // set up a system of equations // ______Order unknowns: A00 A10 A01 A20 A11 A02 A30 A21 A12 A03 for degree=3______ double posL = PolyUtils.normalize2(line, minLine, maxLine); double posP = PolyUtils.normalize2(pixel, minPixel, maxPixel); int index = 0; for (int j = 0; j <= srpPolynomialDegree; j++) { for (int k = 0; k <= j; k++) { A.put(i, index, (FastMath.pow(posL, (double) (j - k)) * FastMath.pow(posP, (double) k))); index++; } } } // Fit polynomial through computed vector of phases DoubleMatrix Atranspose = A.transpose(); DoubleMatrix N = Atranspose.mmul(A); DoubleMatrix rhs = Atranspose.mmul(y); // this should be the coefficient of the reference phase // flatEarthPolyCoefs = Solve.solve(N, rhs); return Solve.solve(N, rhs); } /** * Called by the framework in order to compute a tile for the given target band. * <p>The default implementation throws a runtime exception with the message "not implemented".</p> * * @param targetTileMap The target tiles associated with all target bands to be computed. * @param targetRectangle The rectangle of target tile. * @param pm A progress monitor which should be used to determine computation cancelation requests. * @throws org.esa.beam.framework.gpf.OperatorException * If an error occurs during computation of the target raster. */ @Override public void computeTileStack(Map<Band, Tile> targetTileMap, Rectangle targetRectangle, ProgressMonitor pm) throws OperatorException { try { int y0 = targetRectangle.y; int yN = y0 + targetRectangle.height - 1; int x0 = targetRectangle.x; int xN = targetRectangle.x + targetRectangle.width - 1; final Window tileWindow = new Window(y0, yN, x0, xN); // Band flatPhaseBand; Band targetBand_I; Band targetBand_Q; for (String ifgKey : targetMap.keySet()) { ProductContainer product = targetMap.get(ifgKey); /// check out results from source /// Tile tileReal = getSourceTile(product.sourceMaster.realBand, targetRectangle); Tile tileImag = getSourceTile(product.sourceMaster.imagBand, targetRectangle); ComplexDoubleMatrix complexMaster = TileUtilsDoris.pullComplexDoubleMatrix(tileReal, tileImag); /// check out results from source /// tileReal = getSourceTile(product.sourceSlave.realBand, targetRectangle); tileImag = getSourceTile(product.sourceSlave.imagBand, targetRectangle); ComplexDoubleMatrix complexSlave = TileUtilsDoris.pullComplexDoubleMatrix(tileReal, tileImag); // if (srpPolynomialDegree > 0) { if (!doNotSubtract) { // normalize range and azimuth axis DoubleMatrix rangeAxisNormalized = DoubleMatrix.linspace(x0, xN, complexMaster.columns); rangeAxisNormalized = normalizeDoubleMatrix(rangeAxisNormalized, sourceImageWidth); DoubleMatrix azimuthAxisNormalized = DoubleMatrix.linspace(y0, yN, complexMaster.rows); azimuthAxisNormalized = normalizeDoubleMatrix(azimuthAxisNormalized, sourceImageHeight); // pull polynomial from the map DoubleMatrix polyCoeffs = flatEarthPolyMap.get(product.sourceSlave.name); // estimate the phase on the grid DoubleMatrix realReferencePhase = PolyUtils.polyval(azimuthAxisNormalized, rangeAxisNormalized, polyCoeffs, PolyUtils.degreeFromCoefficients(polyCoeffs.length)); // compute the reference phase ComplexDoubleMatrix complexReferencePhase = new ComplexDoubleMatrix(MatrixFunctions.cos(realReferencePhase), MatrixFunctions.sin(realReferencePhase)); complexSlave.muli(complexReferencePhase); // no conjugate here! } SarUtils.computeIfg_inplace(complexMaster, complexSlave.conji()); /// commit to target /// targetBand_I = targetProduct.getBand(product.targetBandName_I); Tile tileOutReal = targetTileMap.get(targetBand_I); TileUtilsDoris.pushDoubleMatrix(complexMaster.real(), tileOutReal, targetRectangle); targetBand_Q = targetProduct.getBand(product.targetBandName_Q); Tile tileOutImag = targetTileMap.get(targetBand_Q); TileUtilsDoris.pushDoubleMatrix(complexMaster.imag(), tileOutImag, targetRectangle); } } catch (Throwable e) { OperatorUtils.catchOperatorException(getId(), e); } } private DoubleMatrix normalizeDoubleMatrix(DoubleMatrix matrix, int factor) { matrix.subi(0.5 * (factor - 1)); matrix.divi(0.25 * (factor - 1)); return matrix; } /** * The SPI is used to register this operator in the graph processing framework * via the SPI configuration file * {@code META-INF/services/org.esa.beam.framework.gpf.OperatorSpi}. * This class may also serve as a factory for new operator instances. * * @see org.esa.beam.framework.gpf.OperatorSpi#createOperator() * @see org.esa.beam.framework.gpf.OperatorSpi#createOperator(java.util.Map, java.util.Map) */ public static class Spi extends OperatorSpi { public Spi() { super(InterferogramOp.class); } } }
kristotammeoja/ks
jlinda/jlinda-nest/src/main/java/org/jlinda/nest/gpf/InterferogramOp.java
Java
gpl-3.0
20,085
using LightDirector.Domain; namespace LightDirector { public interface IEffectView<T> where T : EffectBase { } }
binton10186/light-director
LightDirector/Views/IEffectView.cs
C#
gpl-3.0
126
package com.xxl.job.database.meta; import com.xxl.job.database.dboperate.DBManager; /** * 基于mysql的一些特殊处理定义 * */ public class MySQLDatabaseMeta extends DatabaseMeta { public MySQLDatabaseMeta() { this.dbType = DBManager.MYSQL_DB; } }
lijie2713977/xxl-job
xxl-job-database/src/main/java/com/xxl/job/database/meta/MySQLDatabaseMeta.java
Java
gpl-3.0
277
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <!-- Incluimos los archivos Javascript externos --> <script src='jquery.js'></script> <script src='amazingslider.js'></script> <script src='initslider-1.js'></script> <style> a{ font-family:Tahoma; font-size:13px; color:#2E2E2E; text-decoration:none;} p{ text-align:right;} </style> </head> <body bgcolor="transparent"><br> <!-- Div contenedor general --> <div style="margin:70px auto;max-width:900px;"> <!-- Div donde se muestran las imágenes --> <div id="amazingslider-1" style="display:block;position:relative;margin:16px auto 86px;"> <ul class="amazingslider-slides" style="display:none;"> <!-- Código PHP que genera galería de fotos automática a partir de los archivos contenidos en carpeta imagenes --> <?php $directorio = opendir("imagenes"); //Ruta actual donde se encuentran las imágenes while ($archivo = readdir($directorio))//Obtiene archivos sucesivamente { if (is_dir($archivo))//verificamos si es o no un directorio {// si es directorio no hace nada } else//si no lo es muestra la imagen y su nombre(alt) { echo "<li> <img src='imagenes/$archivo'/ alt='$archivo'/> </li> "; } } ?> </ul> <!-- Div inferior donde se muestran barra con miniaturas--> <ul class="amazingslider-thumbnails" style="display:none;"> <!-- Código PHP que genera galería de miniaturas automática en la parte inferior, a partir de los archivos contenidos en carpeta imagenes --> <?php $directorio = opendir("imagenes"); //ruta actual while ($archivo = readdir($directorio))//Obtiene archivos sucesivamente { if (is_dir($archivo)) //verificamos si es o no un directorio {// si es directorio no hace nada } else//si no lo es muestra la imagen { echo "<li> <img src='imagenes/$archivo'/> </li> "; } } ?> </ul> </div> </div><br><br> <p> <a href="../../panelGalerias.php"> Volver al panel de Galerías <img src="../../iconos/flecha.png" height="40px" width="40px" align="right"> </a> </p> </body> </html>
ricardo7227/DAW
DIW/aaa_profe/Intranet/Multimedia/Imagenes/Archivos/iconos/index.php
PHP
gpl-3.0
3,022
<?php namespace Volantus\FlightBase\Src\General\MSP; use Volantus\MSPProtocol\Src\Protocol\Response\Response; /** * Class MSPResponseMessage * * @package Volantus\FlightBase\Src\General\MSP */ class MSPResponseMessage { /** * @var string */ private $id; /** * @var Response */ private $mspResponse; /** * MSPResponseMessage constructor. * * @param string $id * @param Response $mspResponse */ public function __construct(string $id, Response $mspResponse) { $this->id = $id; $this->mspResponse = $mspResponse; } /** * @return string */ public function getId(): string { return $this->id; } /** * @return Response */ public function getMspResponse(): Response { return $this->mspResponse; } }
Volantus/flight-base
src/General/MSP/MSPResponseMessage.php
PHP
gpl-3.0
864
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'plagiarism_turnitin', language 'hu', branch 'MOODLE_22_STABLE' * * @package plagiarism_turnitin * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['adminlogin'] = 'Bejelentkezés a Turnitin alá rendszergazdaként'; $string['compareinstitution'] = 'Leadott fájlok és beadott dolgozatok összehasonlítása intézményen belül'; $string['compareinstitution_help'] = 'Csak akkor érhető el, ha egyedi csomópontot állított be/vásárolt. Ha bizonytalan, állítsa "Nem"-re.'; $string['compareinternet'] = 'Leadott fájlok összehasonlítása az internettel'; $string['compareinternet_help'] = 'Ezzel összehasonlíthatja a leadott munkákat azon internetes tartalmakkal, amelyeket a Turnitin jelenleg nyomon követ.'; $string['comparejournals'] = 'Leadott fájlok összehasonlítása folyóraitokkal, közleményekkel.'; $string['comparejournals_help'] = 'Ezzel összehasonlíthatja a leadott munkákat azon folyóraitokkal, közleményekkel, amelyeket a Turnitin jelenleg nyomon követ.'; $string['comparestudents'] = 'Leadott fájlok összehasonlítása más tanulók állományaival'; $string['comparestudents_help'] = 'Ezzel összehasonlíthatja a leadott munkákat más tanulók állományaival'; $string['configdefault'] = 'Ez az alapbeállítás a feladatok létrehozására való oldalon. Csakis plagiarism/turnitin:enableturnitin jogosultsággal rendelkező felhasználók módosíthatják a beállítást egyéni feladatra.'; $string['configusetiimodule'] = 'Turnitin-leadás bekapcsolása'; $string['defaultsdesc'] = 'Ha egy tevékenységmodulban bekapcsolja a Turnitint, az alábbiak lesznek az alapbeállítások.'; $string['defaultupdated'] = 'A Turnitin alapbeállításai frissítve.'; $string['draftsubmit'] = 'Mikor kell a fájlt a Turnitinba leadni?'; $string['excludebiblio'] = 'A szakirodalom kihagyása'; $string['excludebiblio_help'] = 'A szakirodalom az eredetiségi jelentés megtekintésekor ki-be kapcsolható. Ez a beállítás az első fájl leadása után nem módosítható.'; $string['excludematches'] = 'Csekély egyezések kihagyása'; $string['excludematches_help'] = 'A csekély mértékű egyezéseket százalék vagy szószám alapján kihagyhatja - az alábbi négyzetben válassza ki, melyiket kívánja használni.'; $string['excludequoted'] = 'Idézet kihagyása'; $string['excludequoted_help'] = 'Az idézetek az eredetiségi jelentés megtekintésekor ki-be kapcsolhatók. Ez a beállítás az első fájl leadása után nem módosítható.'; $string['file'] = 'Állomány'; $string['filedeleted'] = 'Az állomány a sorból törölve'; $string['fileresubmitted'] = 'Az állomány újbóli leadásra besorolva'; $string['module'] = 'Modul'; $string['name'] = 'Név'; $string['percentage'] = 'Százalék'; $string['pluginname'] = 'Turnitin plágium-ellenőrző segédprogram'; $string['reportgen'] = 'Mikor készüljenek eredetiségi jelentések?'; $string['reportgen_help'] = 'Ezzel adhatja meg, hogy mikor készüljenek el az eredetiségi jelentések'; $string['reportgenduedate'] = 'Határidőre'; $string['reportgenimmediate'] = 'Haladéktalanul (az első jelentés a végső)'; $string['reportgenimmediateoverwrite'] = 'Haladéktalanul (a jelentések felülírhatók)'; $string['resubmit'] = 'Újbóli leadás'; $string['savedconfigfailure'] = 'Nem sikerül csatlakoztatni/hitelesíteni a Turnitint - lehet, hogy rossz titkos kulcs/felhasználó azonosító párt használ, vagy a szerver nem tud az alkalmazással összekapcsolódni.'; $string['savedconfigsuccess'] = 'A Turnitin-beállítások elmentve, a tanári fiók létrejött'; $string['showstudentsreport'] = 'A hasonlósági jelentés megmutatása a tanulónak'; $string['showstudentsreport_help'] = 'A hasonlósági jelentés lebontva jeleníti meg a leadott munka azon részeit, amelyeket átvettek, valamint azt a helyet, ahol a Turnitin először észlelte ezt a tartalmat.'; $string['showstudentsscore'] = 'Hasonlósági arány megmutatása a tanulónak'; $string['showstudentsscore_help'] = 'A hasonlósági arány a leadott munkának az a százaléka, amely más tartalmakkal egyezik - a magas arány rendszerint rosszat jelent.'; $string['showwhenclosed'] = 'A tevékenység lezárásakor'; $string['similarity'] = 'Hasonlóság'; $string['status'] = 'Állapot'; $string['studentdisclosure'] = 'Tanulói nyilvánosságra hozatal'; $string['studentdisclosure_help'] = 'A szöveget az állományfeltöltő oldalon minden tanuló látja'; $string['studentdisclosuredefault'] = 'Minden feltöltött állományt megvizsgál a Turnitin.com plágium-ellenőrzője'; $string['submitondraft'] = 'Állomány leadása az első feltöltés alkalmával'; $string['submitonfinal'] = 'Állomány leadása, amikor a tanuló osztályozásra küldi be'; $string['teacherlogin'] = 'Bejelentkezés a Turnitin alá tanárként'; $string['tii'] = 'Turnitin'; $string['tiiaccountid'] = 'Turnitin felhasználói azonosító'; $string['tiiaccountid_help'] = 'Ez a felhasználói azonosítója, melyet a Turnitin.com-tól kapott'; $string['tiiapi'] = 'Turnitin alkalmazás'; $string['tiiapi_help'] = 'Ez a Turnitin alkalmazás címe - többnyire https://api.turnitin.com/api.asp'; $string['tiiconfigerror'] = 'Portál-beállítási hiba történt az állomány Turnitinhez küldése közben.'; $string['tiiemailprefix'] = 'Tanulói e-mail előtagja'; $string['tiiemailprefix_help'] = 'Állítsa be ezt, ha nem akarja, hogy a tanulók bejelentkezzenek a turnitin.com portálra és teljes jelentéseket tekintsenek meg.'; $string['tiienablegrademark'] = 'A Grademark (kísérleti) bekapcsolása'; $string['tiienablegrademark_help'] = 'A Grademark a Turnitin egyik választható funkciója. Használatához fel kell vennie a Turnitin-szolgáltatások közé. Bekapcsolása esetén a leadott oldalak lassan jelennek meg.'; $string['tiierror'] = 'TII-hiba'; $string['tiierror1007'] = 'A Turnitin nem tudta feldolgozni a fájlt, mert túl nagy.'; $string['tiierror1008'] = 'Hiba történt a fájl Turnitinhez küldése közben.-'; $string['tiierror1009'] = 'A Turnitin nem tudta feldolgozni a fájlt, mert nem támogatja a típusát. Érvényes állományformák: MS Word, Acrobat PDF, Postscript, egyszerű szöveg, HTML, WordPerfect és Rich Text.'; $string['tiierror1010'] = 'A Turnitin nem tudta feldolgozni a fájlt, mert 100-nál kevesebb nem nyomtatható karaktert tartalmaz.'; $string['tiierror1011'] = 'A Turnitin nem tudta feldolgozni a fájlt, mert hibás a formája és szóközök vannak a betűk között.'; $string['tiierror1012'] = 'A Turnitin nem tudta feldolgozni a fájlt, mert hossza meghaladja a megengedettet.'; $string['tiierror1013'] = 'A Turnitin nem tudta feldolgozni a fájlt, mert 20-nál kevesebb szót tartalmaz.'; $string['tiierror1020'] = 'A Turnitin nem tudta feldolgozni a fájlt, mert nem támogatott karaktereket tartalmaz.'; $string['tiierror1023'] = 'A Turnitin nem tudta feldolgozni a pdf-fájlt, mert jelszóval védett és képeket tartalmaz.'; $string['tiierror1024'] = 'A Turnitin nem tudta feldolgozni a fájlt, mert nem felel meg az érvényes dolgozat feltételeinek.'; $string['tiierrorpaperfail'] = 'A Turnitin nem tudta feldolgozni a fájlt.'; $string['tiierrorpending'] = 'A fájl vár a Turnitinhez való leadásra.'; $string['tiiexplain'] = 'A Turnitin kereskedelmi termék, a szolgáltatásra elő kell fizetni. További információk: <a href="http://docs.moodle.org/en/Turnitin_administration">http://docs.moodle.org/en/Turnitin_administration</a>'; $string['tiiexplainerrors'] = 'AZ oldalon szerepelnek azok a Turnitinhez leadott fájlok, amelyek hibásként vannak megjelölve. A hibakódokat és leírásukat lásd: :<a href="http://docs.moodle.org/en/Turnitin_errors">docs.moodle.org/en/Turnitin_errors</a><br/>Az állományok visszaállítása után a cron megpróbálja ismét leadni őket a Turnitinhez.<br/>Törlésük esetén viszont nem lehet őket ismételten leadni, ezért eltűnnek a tanárok és a tanulók elől a hibák is.'; $string['tiisecretkey'] = 'Titkos Turnitin-kulcs'; $string['tiisecretkey_help'] = 'Ennek beszerzéséhez jelentkezzen be a Turnitin.com alá portálja rendszergazdájaként.'; $string['tiisenduseremail'] = 'Felhasználói e-mail elküldése'; $string['tiisenduseremail_help'] = 'E-mail küldése a TII-rendszerben létrehozott összes felhasználónak olyan ugrópointtal, amelyről ideiglenes jelszóval be tudnak jelentkezni a www.turnitin.com portálra.'; $string['turnitin'] = 'Turnitin'; $string['turnitin:enable'] = 'Tanár számára a Turnitin ki-be kapcsolásának engedélyezése adott modulon belül.'; $string['turnitin:viewfullreport'] = 'Tanár számára a Turnitintól kapott teljes jelentés megtekintésének engedélyezése'; $string['turnitin:viewsimilarityscore'] = 'Tanár számára a Turnitintól kapott hasonlósági pont megtekintésének engedélyezése'; $string['turnitin_attemptcodes'] = 'Hibakódok automatikus újbóli leadáshoz'; $string['turnitin_attemptcodes_help'] = 'Olyan hibakódok, amilyeneket a Turnitin 2. próbálkozásra általában elfogad (a mező módosítása a szervert tovább terhelheti)'; $string['turnitin_attempts'] = 'Újrapróbálkozások száma'; $string['turnitin_attempts_help'] = 'A megadott kódok Turnitinnek való újbóli leadásának a száma. 1 újrapróbálkozás azt jelenti, hogy a megadott hibakódok leadására kétszer kerül sor.'; $string['turnitin_institutionnode'] = 'Intézményi csomópont bekapcsolása'; $string['turnitin_institutionnode_help'] = 'Ha a fiókjához intézményi csomópontot állított be, ennek bekapcsolásával választhatja ki a csomópontot feladatok létrehozása során. MEGJEGYZÉS: ha nincs intézményi csomópontja, ennek bekapcsolása esetén a dolgozat leadása nem fog sikerülni.'; $string['turnitindefaults'] = 'A Turnitin alapbeállításai'; $string['turnitinerrors'] = 'Turnitin-hibák'; $string['useturnitin'] = 'A Turnitin bekapcsolása'; $string['wordcount'] = 'Szószám';
danielbonetto/twig_MVC
lang/hu/plagiarism_turnitin.php
PHP
gpl-3.0
10,844
#include "if_expression.h" #include <glog/logging.h> #include "../internal/compilation.h" #include "../public/value.h" namespace afc { namespace vm { namespace { class IfExpression : public Expression { public: IfExpression(std::shared_ptr<Expression> cond, std::shared_ptr<Expression> true_case, std::shared_ptr<Expression> false_case, std::unordered_set<VMType> return_types) : cond_(std::move(cond)), true_case_(std::move(true_case)), false_case_(std::move(false_case)), return_types_(std::move(return_types)) { CHECK(cond_ != nullptr); CHECK(cond_->IsBool()); CHECK(true_case_ != nullptr); CHECK(false_case_ != nullptr); } std::vector<VMType> Types() override { return true_case_->Types(); } std::unordered_set<VMType> ReturnTypes() const override { return return_types_; } PurityType purity() override { return cond_->purity() == PurityType::kPure && true_case_->purity() == PurityType::kPure && false_case_->purity() == PurityType::kPure ? PurityType::kPure : PurityType::kUnknown; } futures::Value<EvaluationOutput> Evaluate(Trampoline* trampoline, const VMType& type) override { return trampoline->Bounce(cond_.get(), VMType::Bool()) .Transform([type, true_case = true_case_, false_case = false_case_, trampoline](EvaluationOutput cond_output) { switch (cond_output.type) { case EvaluationOutput::OutputType::kReturn: case EvaluationOutput::OutputType::kAbort: return futures::Past(std::move(cond_output)); case EvaluationOutput::OutputType::kContinue: return trampoline->Bounce(cond_output.value->boolean ? true_case.get() : false_case.get(), type); } auto error = afc::editor::Error(L"Unhandled OutputType case."); LOG(FATAL) << error; return futures::Past(EvaluationOutput::Abort(error)); }); } std::unique_ptr<Expression> Clone() override { return std::make_unique<IfExpression>(cond_, true_case_, false_case_, return_types_); } private: const std::shared_ptr<Expression> cond_; const std::shared_ptr<Expression> true_case_; const std::shared_ptr<Expression> false_case_; const std::unordered_set<VMType> return_types_; }; } // namespace std::unique_ptr<Expression> NewIfExpression( Compilation* compilation, std::unique_ptr<Expression> condition, std::unique_ptr<Expression> true_case, std::unique_ptr<Expression> false_case) { if (condition == nullptr || true_case == nullptr || false_case == nullptr) { return nullptr; } if (!condition->IsBool()) { compilation->errors.push_back( L"Expected bool value for condition of \"if\" expression but found " + TypesToString(condition->Types()) + L"."); return nullptr; } if (!(true_case->Types() == false_case->Types())) { compilation->errors.push_back( L"Type mismatch between branches of conditional expression: " + TypesToString(true_case->Types()) + L" and " + TypesToString(false_case->Types()) + L"."); return nullptr; } std::wstring error; auto return_types = CombineReturnTypes(true_case->ReturnTypes(), false_case->ReturnTypes(), &error); if (!return_types.has_value()) { compilation->errors.push_back(error); return nullptr; } return std::make_unique<IfExpression>( std::move(condition), std::move(true_case), std::move(false_case), std::move(return_types.value())); } } // namespace vm } // namespace afc
alefore/edge
src/vm/internal/if_expression.cc
C++
gpl-3.0
3,919
using System; using System.Diagnostics; using EasyRemote.Spec; namespace EasyRemote.Impl.Extension { public static class PathExt { /// <summary> /// Get path for program /// </summary> /// <param name="program">Program</param> /// <returns>Full path</returns> public static string GetPath(this IProgram program) { if (String.IsNullOrEmpty(program.Path)) { return null; } Debug.Print("{0} => {1}", program.Path, Environment.ExpandEnvironmentVariables(program.Path)); return Environment.ExpandEnvironmentVariables(program.Path); } } }
fa18swiss/EasyRemote
EasyRemote.Impl/Extension/PathExt.cs
C#
gpl-3.0
688
# Copyright (c) 2015 ProbeDock # Copyright (c) 2012-2014 Lotaris SA # # This file is part of ProbeDock. # # ProbeDock is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ProbeDock is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with ProbeDock. If not, see <http://www.gnu.org/licenses/>. class TestPayloadPolicy < ApplicationPolicy def index? user.is?(:admin) || user.member_of?(organization) end class Scope < Scope def resolve if user.is? :admin scope else scope.joins(project_version: :project).where('projects.organization_id = ?', organization.id) end end end class Serializer < Serializer def to_builder options = {} Jbuilder.new do |json| json.id record.api_id json.bytes record.contents_bytesize json.state record.state json.endedAt record.ended_at.iso8601(3) json.receivedAt record.received_at.iso8601(3) json.processingAt record.processing_at.iso8601(3) if record.processing_at json.processedAt record.processed_at.iso8601(3) if record.processed_at end end end end
probedock/probedock
app/policies/test_payload_policy.rb
Ruby
gpl-3.0
1,555
import net.sf.javabdd.*; /** * @author John Whaley */ public class NQueens { static BDDFactory B; static boolean TRACE; static int N; /* Size of the chess board */ static BDD[][] X; /* BDD variable array */ static BDD queen; /* N-queen problem expressed as a BDD */ static BDD solution; /* One solution */ public static void main(String[] args) { if (args.length != 1) { System.err.println("USAGE: java NQueens N"); return; } N = Integer.parseInt(args[0]); if (N <= 0) { System.err.println("USAGE: java NQueens N"); return; } TRACE = true; long time = System.currentTimeMillis(); runTest(); freeAll(); time = System.currentTimeMillis() - time; System.out.println("Time: "+time/1000.+" seconds"); BDDFactory.CacheStats cachestats = B.getCacheStats(); if (cachestats != null && cachestats.uniqueAccess > 0) { System.out.println(cachestats); } B.done(); B = null; } public static double runTest() { if (B == null) { /* Initialize with reasonable nodes and cache size and NxN variables */ String numOfNodes = System.getProperty("bddnodes"); int numberOfNodes; if (numOfNodes == null) numberOfNodes = (int) (Math.pow(4.42, N-6))*1000; else numberOfNodes = Integer.parseInt(numOfNodes); String cache = System.getProperty("bddcache"); int cacheSize; if (cache == null) cacheSize = 1000; else cacheSize = Integer.parseInt(cache); numberOfNodes = Math.max(1000, numberOfNodes); B = BDDFactory.init(numberOfNodes, cacheSize); } if (B.varNum() < N * N) B.setVarNum(N * N); queen = B.universe(); int i, j; /* Build variable array */ X = new BDD[N][N]; for (i = 0; i < N; i++) for (j = 0; j < N; j++) X[i][j] = B.ithVar(i * N + j); /* Place a queen in each row */ for (i = 0; i < N; i++) { BDD e = B.zero(); for (j = 0; j < N; j++) { e.orWith(X[i][j].id()); } queen.andWith(e); } /* Build requirements for each variable(field) */ for (i = 0; i < N; i++) for (j = 0; j < N; j++) { if (TRACE) System.out.print("Adding position " + i + "," + j+" \r"); build(i, j); } solution = queen.satOne(); double result = queen.satCount(); /* Print the results */ if (TRACE) { System.out.println("There are " + (long) result + " solutions."); double result2 = solution.satCount(); System.out.println("Here is "+(long) result2 + " solution:"); solution.printSet(); System.out.println(); } return result; } public static void freeAll() { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) X[i][j].free(); queen.free(); solution.free(); } static void build(int i, int j) { BDD a = B.universe(), b = B.universe(), c = B.universe(), d = B.universe(); int k, l; /* No one in the same column */ for (l = 0; l < N; l++) { if (l != j) { BDD u = X[i][l].apply(X[i][j], BDDFactory.nand); a.andWith(u); } } /* No one in the same row */ for (k = 0; k < N; k++) { if (k != i) { BDD u = X[i][j].apply(X[k][j], BDDFactory.nand); b.andWith(u); } } /* No one in the same up-right diagonal */ for (k = 0; k < N; k++) { int ll = k - i + j; if (ll >= 0 && ll < N) { if (k != i) { BDD u = X[i][j].apply(X[k][ll], BDDFactory.nand); c.andWith(u); } } } /* No one in the same down-right diagonal */ for (k = 0; k < N; k++) { int ll = i + j - k; if (ll >= 0 && ll < N) { if (k != i) { BDD u = X[i][j].apply(X[k][ll], BDDFactory.nand); d.andWith(u); } } } c.andWith(d); b.andWith(c); a.andWith(b); queen.andWith(a); } }
aindilis/sandbox-gamer
JavaBDD/NQueens.java
Java
gpl-3.0
4,650
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class ItemCompareBuilder : IScriptable { [Ordinal(0)] [RED("item1")] public InventoryItemData Item1 { get; set; } [Ordinal(1)] [RED("item2")] public InventoryItemData Item2 { get; set; } [Ordinal(2)] [RED("compareBuilder")] public CHandle<CompareBuilder> CompareBuilder { get; set; } public ItemCompareBuilder(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/ItemCompareBuilder.cs
C#
gpl-3.0
532
<?php namespace controllers\bases; abstract class HttpBase extends UriMethodBase { /** * @var array */ protected $params; function __construct() { $uriSections = \Request::getInstance()->getUriSections(); $paramsUri = array_slice($uriSections, DEFAULT_PARAMS_START_POSITION); //This is not a magical number, we quit the empty one (0), controllers (1), method(2) foreach ($this->getParamsNames() as $ind => $field) { if (isset($paramsUri[$ind])) { $this->params[$field] = \Sanitizer::cleanString($paramsUri[$ind]); } } } public function execute() { $action = $this->getMethodCalled(); if (!method_exists($this, $action)) { _logErr("Action '$action' not found, changing to 'render'"); $action = DEFAULT_METHOD; } return $this->$action(); } public function getParam($type, $nameParam, $defaultValue) { if(!isset($this->params[$nameParam])) { return \Sanitizer::defineType($type, $defaultValue); } return \Sanitizer::defineType($type, $this->params[$nameParam]); } public abstract function getParamsNames(); public abstract function error(); }
franciscomaestre/mvcd-framework
controllers/extends/HttpBase.php
PHP
gpl-3.0
1,246
<?php $return_value = 0; if(isset($_FILES['photo'])) { $target_dir = "../../upload/news/doc/"; require "../config.php"; $total_files = sizeof($_FILES['photo']['name']); $resp = ''; for($i = 0; $i < $total_files; $i++) { $tmp_name = $_FILES['photo']["tmp_name"][$i]; $name = $_FILES['photo']["name"][$i]; $cfg = new config(); $p_index = $cfg->index_of($name, "."); $new_name = md5(date('Y-m-d H:i:s:u').$i); $ext = substr($name, $p_index + 1, strlen($name)); $target_file = $target_dir.$new_name.".".$ext; if (move_uploaded_file($tmp_name, $target_file)) { $handle = fopen($target_file, "r"); $content = fread($handle, 4); fclose($handle); if($content == "%PDF") { $resp = $resp.'|'.str_replace(":", "$", $target_file); } else { $real_path = $_SERVER["DOCUMENT_ROOT"]."/gov_portal/backgp/upload/news/doc/".$new_name.".".$ext; unlink($real_path); } $return_value = "y"; } else { $resp = 'Falha t: '.$name; $return_value = "n"; } } } else { $return_value = "n"; $resp = 'Não entrou no if!'; } echo json_encode(array($return_value => $resp)); ?>
yasilvalmeida/gov_portal
backgp/ajax/noticia_anexo/upload-add-pdf.php
PHP
gpl-3.0
1,401
# coding: utf-8 """ mistune ~~~~~~~ The fastest markdown parser in pure Python with renderer feature. :copyright: (c) 2014 - 2016 by Hsiaoming Yang. """ import re import inspect __version__ = '0.7.3' __author__ = 'Hsiaoming Yang <me@lepture.com>' __all__ = [ 'BlockGrammar', 'BlockLexer', 'InlineGrammar', 'InlineLexer', 'Renderer', 'Markdown', 'markdown', 'escape', ] _key_pattern = re.compile(r'\s+') _nonalpha_pattern = re.compile(r'\W') _escape_pattern = re.compile(r'&(?!#?\w+;)') _newline_pattern = re.compile(r'\r\n|\r') _block_quote_leading_pattern = re.compile(r'^ *> ?', flags=re.M) _block_code_leading_pattern = re.compile(r'^ {4}', re.M) _inline_tags = [ 'a', 'em', 'strong', 'small', 's', 'cite', 'q', 'dfn', 'abbr', 'data', 'time', 'code', 'var', 'samp', 'kbd', 'sub', 'sup', 'i', 'b', 'u', 'mark', 'ruby', 'rt', 'rp', 'bdi', 'bdo', 'span', 'br', 'wbr', 'ins', 'del', 'img', 'font', ] _pre_tags = ['pre', 'script', 'style'] _valid_end = r'(?!:/|[^\w\s@]*@)\b' _valid_attr = r'''\s*[a-zA-Z\-](?:\=(?:"[^"]*"|'[^']*'|\d+))*''' _block_tag = r'(?!(?:%s)\b)\w+%s' % ('|'.join(_inline_tags), _valid_end) _scheme_blacklist = ('javascript:', 'vbscript:') def _pure_pattern(regex): pattern = regex.pattern if pattern.startswith('^'): pattern = pattern[1:] return pattern def _keyify(key): return _key_pattern.sub(' ', key.lower()) def escape(text, quote=False, smart_amp=True): """Replace special characters "&", "<" and ">" to HTML-safe sequences. The original cgi.escape will always escape "&", but you can control this one for a smart escape amp. :param quote: if set to True, " and ' will be escaped. :param smart_amp: if set to False, & will always be escaped. """ if smart_amp: text = _escape_pattern.sub('&amp;', text) else: text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') if quote: text = text.replace('"', '&quot;') text = text.replace("'", '&#39;') return text def escape_link(url): """Remove dangerous URL schemes like javascript: and escape afterwards.""" lower_url = url.lower().strip('\x00\x1a \n\r\t') for scheme in _scheme_blacklist: if lower_url.startswith(scheme): return '' return escape(url, quote=True, smart_amp=False) def preprocessing(text, tab=4): text = _newline_pattern.sub('\n', text) text = text.expandtabs(tab) text = text.replace('\u00a0', ' ') text = text.replace('\u2424', '\n') pattern = re.compile(r'^ +$', re.M) return pattern.sub('', text) class BlockGrammar(object): """Grammars for block level tokens.""" def_links = re.compile( r'^ *\[([^^\]]+)\]: *' # [key]: r'<?([^\s>]+)>?' # <link> or link r'(?: +["(]([^\n]+)[")])? *(?:\n+|$)' ) def_footnotes = re.compile( r'^\[\^([^\]]+)\]: *(' r'[^\n]*(?:\n+|$)' # [^key]: r'(?: {1,}[^\n]*(?:\n+|$))*' r')' ) newline = re.compile(r'^\n+') block_code = re.compile(r'^( {4}[^\n]+\n*)+') fences = re.compile( r'^ *(`{3,}|~{3,}) *(\S+)? *\n' # ```lang r'([\s\S]+?)\s*' r'\1 *(?:\n+|$)' # ``` ) hrule = re.compile(r'^ {0,3}[-*_](?: *[-*_]){2,} *(?:\n+|$)') heading = re.compile(r'^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)') lheading = re.compile(r'^([^\n]+)\n *(=|-)+ *(?:\n+|$)') block_quote = re.compile(r'^( *>[^\n]+(\n[^\n]+)*\n*)+') list_block = re.compile( r'^( *)([*+-]|\d+\.) [\s\S]+?' r'(?:' r'\n+(?=\1?(?:[-*_] *){3,}(?:\n+|$))' # hrule r'|\n+(?=%s)' # def links r'|\n+(?=%s)' # def footnotes r'|\n{2,}' r'(?! )' r'(?!\1(?:[*+-]|\d+\.) )\n*' r'|' r'\s*$)' % ( _pure_pattern(def_links), _pure_pattern(def_footnotes), ) ) list_item = re.compile( r'^(( *)(?:[*+-]|\d+\.) [^\n]*' r'(?:\n(?!\2(?:[*+-]|\d+\.) )[^\n]*)*)', flags=re.M ) list_bullet = re.compile(r'^ *(?:[*+-]|\d+\.) +') paragraph = re.compile( r'^((?:[^\n]+\n?(?!' r'%s|%s|%s|%s|%s|%s|%s|%s|%s' r'))+)\n*' % ( _pure_pattern(fences).replace(r'\1', r'\2'), _pure_pattern(list_block).replace(r'\1', r'\3'), _pure_pattern(hrule), _pure_pattern(heading), _pure_pattern(lheading), _pure_pattern(block_quote), _pure_pattern(def_links), _pure_pattern(def_footnotes), '<' + _block_tag, ) ) block_html = re.compile( r'^ *(?:%s|%s|%s) *(?:\n{2,}|\s*$)' % ( r'<!--[\s\S]*?-->', r'<(%s)((?:%s)*?)>([\s\S]*?)<\/\1>' % (_block_tag, _valid_attr), r'<%s(?:%s)*?\s*\/?>' % (_block_tag, _valid_attr), ) ) table = re.compile( r'^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*' ) nptable = re.compile( r'^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*' ) text = re.compile(r'^[^\n]+') class BlockLexer(object): """Block level lexer for block grammars.""" grammar_class = BlockGrammar default_rules = [ 'newline', 'hrule', 'block_code', 'fences', 'heading', 'nptable', 'lheading', 'block_quote', 'list_block', 'block_html', 'def_links', 'def_footnotes', 'table', 'paragraph', 'text' ] list_rules = ( 'newline', 'block_code', 'fences', 'lheading', 'hrule', 'block_quote', 'list_block', 'block_html', 'text', ) footnote_rules = ( 'newline', 'block_code', 'fences', 'heading', 'nptable', 'lheading', 'hrule', 'block_quote', 'list_block', 'block_html', 'table', 'paragraph', 'text' ) def __init__(self, rules=None, **kwargs): self.tokens = [] self.def_links = {} self.def_footnotes = {} if not rules: rules = self.grammar_class() self.rules = rules def __call__(self, text, rules=None): return self.parse(text, rules) def parse(self, text, rules=None): text = text.rstrip('\n') if not rules: rules = self.default_rules def manipulate(text): for key in rules: rule = getattr(self.rules, key) m = rule.match(text) if not m: continue getattr(self, 'parse_%s' % key)(m) return m return False # pragma: no cover while text: m = manipulate(text) if m is not False: text = text[len(m.group(0)):] continue if text: # pragma: no cover raise RuntimeError('Infinite loop at: %s' % text) return self.tokens def parse_newline(self, m): length = len(m.group(0)) if length > 1: self.tokens.append({'type': 'newline'}) def parse_block_code(self, m): # clean leading whitespace code = _block_code_leading_pattern.sub('', m.group(0)) self.tokens.append({ 'type': 'code', 'lang': None, 'text': code, }) def parse_fences(self, m): self.tokens.append({ 'type': 'code', 'lang': m.group(2), 'text': m.group(3), }) def parse_heading(self, m): self.tokens.append({ 'type': 'heading', 'level': len(m.group(1)), 'text': m.group(2), }) def parse_lheading(self, m): """Parse setext heading.""" self.tokens.append({ 'type': 'heading', 'level': 1 if m.group(2) == '=' else 2, 'text': m.group(1), }) def parse_hrule(self, m): self.tokens.append({'type': 'hrule'}) def parse_list_block(self, m): bull = m.group(2) self.tokens.append({ 'type': 'list_start', 'ordered': '.' in bull, }) cap = m.group(0) self._process_list_item(cap, bull) self.tokens.append({'type': 'list_end'}) def _process_list_item(self, cap, bull): cap = self.rules.list_item.findall(cap) _next = False length = len(cap) for i in range(length): item = cap[i][0] # remove the bullet space = len(item) item = self.rules.list_bullet.sub('', item) # outdent if '\n ' in item: space = space - len(item) pattern = re.compile(r'^ {1,%d}' % space, flags=re.M) item = pattern.sub('', item) # determine whether item is loose or not loose = _next if not loose and re.search(r'\n\n(?!\s*$)', item): loose = True rest = len(item) if i != length - 1 and rest: _next = item[rest-1] == '\n' if not loose: loose = _next if loose: t = 'loose_item_start' else: t = 'list_item_start' self.tokens.append({'type': t}) # recurse self.parse(item, self.list_rules) self.tokens.append({'type': 'list_item_end'}) def parse_block_quote(self, m): self.tokens.append({'type': 'block_quote_start'}) # clean leading > cap = _block_quote_leading_pattern.sub('', m.group(0)) self.parse(cap) self.tokens.append({'type': 'block_quote_end'}) def parse_def_links(self, m): key = _keyify(m.group(1)) self.def_links[key] = { 'link': m.group(2), 'title': m.group(3), } def parse_def_footnotes(self, m): key = _keyify(m.group(1)) if key in self.def_footnotes: # footnote is already defined return self.def_footnotes[key] = 0 self.tokens.append({ 'type': 'footnote_start', 'key': key, }) text = m.group(2) if '\n' in text: lines = text.split('\n') whitespace = None for line in lines[1:]: space = len(line) - len(line.lstrip()) if space and (not whitespace or space < whitespace): whitespace = space newlines = [lines[0]] for line in lines[1:]: newlines.append(line[whitespace:]) text = '\n'.join(newlines) self.parse(text, self.footnote_rules) self.tokens.append({ 'type': 'footnote_end', 'key': key, }) def parse_table(self, m): item = self._process_table(m) cells = re.sub(r'(?: *\| *)?\n$', '', m.group(3)) cells = cells.split('\n') for i, v in enumerate(cells): v = re.sub(r'^ *\| *| *\| *$', '', v) cells[i] = re.split(r' *\| *', v) item['cells'] = cells self.tokens.append(item) def parse_nptable(self, m): item = self._process_table(m) cells = re.sub(r'\n$', '', m.group(3)) cells = cells.split('\n') for i, v in enumerate(cells): cells[i] = re.split(r' *\| *', v) item['cells'] = cells self.tokens.append(item) def _process_table(self, m): header = re.sub(r'^ *| *\| *$', '', m.group(1)) header = re.split(r' *\| *', header) align = re.sub(r' *|\| *$', '', m.group(2)) align = re.split(r' *\| *', align) for i, v in enumerate(align): if re.search(r'^ *-+: *$', v): align[i] = 'right' elif re.search(r'^ *:-+: *$', v): align[i] = 'center' elif re.search(r'^ *:-+ *$', v): align[i] = 'left' else: align[i] = None item = { 'type': 'table', 'header': header, 'align': align, } return item def parse_block_html(self, m): tag = m.group(1) if not tag: text = m.group(0) self.tokens.append({ 'type': 'close_html', 'text': text }) else: attr = m.group(2) text = m.group(3) self.tokens.append({ 'type': 'open_html', 'tag': tag, 'extra': attr, 'text': text }) def parse_paragraph(self, m): text = m.group(1).rstrip('\n') self.tokens.append({'type': 'paragraph', 'text': text}) def parse_text(self, m): text = m.group(0) self.tokens.append({'type': 'text', 'text': text}) class InlineGrammar(object): """Grammars for inline level tokens.""" escape = re.compile(r'^\\([\\`*{}\[\]()#+\-.!_>~|])') # \* \+ \! .... inline_html = re.compile( r'^(?:%s|%s|%s)' % ( r'<!--[\s\S]*?-->', r'<(\w+%s)((?:%s)*?)\s*>([\s\S]*?)<\/\1>' % (_valid_end, _valid_attr), r'<\w+%s(?:%s)*?\s*\/?>' % (_valid_end, _valid_attr), ) ) autolink = re.compile(r'^<([^ >]+(@|:)[^ >]+)>') link = re.compile( r'^!?\[(' r'(?:\[[^^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*' r')\]\(' r'''\s*(<)?([\s\S]*?)(?(2)>)(?:\s+['"]([\s\S]*?)['"])?\s*''' r'\)' ) reflink = re.compile( r'^!?\[(' r'(?:\[[^^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*' r')\]\s*\[([^^\]]*)\]' ) nolink = re.compile(r'^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]') url = re.compile(r'''^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])''') double_emphasis = re.compile( r'^_{2}([\s\S]+?)_{2}(?!_)' # __word__ r'|' r'^\*{2}([\s\S]+?)\*{2}(?!\*)' # **word** ) emphasis = re.compile( r'^\b_((?:__|[^_])+?)_\b' # _word_ r'|' r'^\*((?:\*\*|[^\*])+?)\*(?!\*)' # *word* ) code = re.compile(r'^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)') # `code` linebreak = re.compile(r'^ {2,}\n(?!\s*$)') strikethrough = re.compile(r'^~~(?=\S)([\s\S]*?\S)~~') # ~~word~~ footnote = re.compile(r'^\[\^([^\]]+)\]') text = re.compile(r'^[\s\S]+?(?=[\\<!\[_*`~]|https?://| {2,}\n|$)') def hard_wrap(self): """Grammar for hard wrap linebreak. You don't need to add two spaces at the end of a line. """ self.linebreak = re.compile(r'^ *\n(?!\s*$)') self.text = re.compile( r'^[\s\S]+?(?=[\\<!\[_*`~]|https?://| *\n|$)' ) class InlineLexer(object): """Inline level lexer for inline grammars.""" grammar_class = InlineGrammar default_rules = [ 'escape', 'inline_html', 'autolink', 'url', 'footnote', 'link', 'reflink', 'nolink', 'double_emphasis', 'emphasis', 'code', 'linebreak', 'strikethrough', 'text', ] inline_html_rules = [ 'escape', 'autolink', 'url', 'link', 'reflink', 'nolink', 'double_emphasis', 'emphasis', 'code', 'linebreak', 'strikethrough', 'text', ] def __init__(self, renderer, rules=None, **kwargs): self.renderer = renderer self.links = {} self.footnotes = {} self.footnote_index = 0 if not rules: rules = self.grammar_class() kwargs.update(self.renderer.options) if kwargs.get('hard_wrap'): rules.hard_wrap() self.rules = rules self._in_link = False self._in_footnote = False self._parse_inline_html = kwargs.get('parse_inline_html') def __call__(self, text, rules=None): return self.output(text, rules) def setup(self, links, footnotes): self.footnote_index = 0 self.links = links or {} self.footnotes = footnotes or {} def output(self, text, rules=None): text = text.rstrip('\n') if not rules: rules = list(self.default_rules) if self._in_footnote and 'footnote' in rules: rules.remove('footnote') output = self.renderer.placeholder() def manipulate(text): for key in rules: pattern = getattr(self.rules, key) m = pattern.match(text) if not m: continue self.line_match = m out = getattr(self, 'output_%s' % key)(m) if out is not None: return m, out return False # pragma: no cover while text: ret = manipulate(text) if ret is not False: m, out = ret output += out text = text[len(m.group(0)):] continue if text: # pragma: no cover raise RuntimeError('Infinite loop at: %s' % text) return output def output_escape(self, m): text = m.group(1) return self.renderer.escape(text) def output_autolink(self, m): link = m.group(1) if m.group(2) == '@': is_email = True else: is_email = False return self.renderer.autolink(link, is_email) def output_url(self, m): link = m.group(1) if self._in_link: return self.renderer.text(link) return self.renderer.autolink(link, False) def output_inline_html(self, m): tag = m.group(1) if self._parse_inline_html and tag in _inline_tags: text = m.group(3) if tag == 'a': self._in_link = True text = self.output(text, rules=self.inline_html_rules) self._in_link = False else: text = self.output(text, rules=self.inline_html_rules) extra = m.group(2) or '' html = '<%s%s>%s</%s>' % (tag, extra, text, tag) else: html = m.group(0) return self.renderer.inline_html(html) def output_footnote(self, m): key = _keyify(m.group(1)) if key not in self.footnotes: return None if self.footnotes[key]: return None self.footnote_index += 1 self.footnotes[key] = self.footnote_index return self.renderer.footnote_ref(key, self.footnote_index) def output_link(self, m): return self._process_link(m, m.group(3), m.group(4)) def output_reflink(self, m): key = _keyify(m.group(2) or m.group(1)) if key not in self.links: return None ret = self.links[key] return self._process_link(m, ret['link'], ret['title']) def output_nolink(self, m): key = _keyify(m.group(1)) if key not in self.links: return None ret = self.links[key] return self._process_link(m, ret['link'], ret['title']) def _process_link(self, m, link, title=None): line = m.group(0) text = m.group(1) if line[0] == '!': return self.renderer.image(link, title, text) self._in_link = True text = self.output(text) self._in_link = False return self.renderer.link(link, title, text) def output_double_emphasis(self, m): text = m.group(2) or m.group(1) text = self.output(text) return self.renderer.double_emphasis(text) def output_emphasis(self, m): text = m.group(2) or m.group(1) text = self.output(text) return self.renderer.emphasis(text) def output_code(self, m): text = m.group(2) return self.renderer.codespan(text) def output_linebreak(self, m): return self.renderer.linebreak() def output_strikethrough(self, m): text = self.output(m.group(1)) return self.renderer.strikethrough(text) def output_text(self, m): text = m.group(0) return self.renderer.text(text) class Renderer(object): """The default HTML renderer for rendering Markdown. """ def __init__(self, **kwargs): self.options = kwargs def placeholder(self): """Returns the default, empty output value for the renderer. All renderer methods use the '+=' operator to append to this value. Default is a string so rendering HTML can build up a result string with the rendered Markdown. Can be overridden by Renderer subclasses to be types like an empty list, allowing the renderer to create a tree-like structure to represent the document (which can then be reprocessed later into a separate format like docx or pdf). """ return '' def block_code(self, code, lang=None): """Rendering block level code. ``pre > code``. :param code: text content of the code block. :param lang: language of the given code. """ code = code.rstrip('\n') if not lang: code = escape(code, smart_amp=False) return '<pre><code>%s\n</code></pre>\n' % code code = escape(code, quote=True, smart_amp=False) return '<pre><code class="lang-%s">%s\n</code></pre>\n' % (lang, code) def block_quote(self, text): """Rendering <blockquote> with the given text. :param text: text content of the blockquote. """ return '<blockquote>%s\n</blockquote>\n' % text.rstrip('\n') def block_html(self, html): """Rendering block level pure html content. :param html: text content of the html snippet. """ if self.options.get('skip_style') and \ html.lower().startswith('<style'): return '' if self.options.get('escape'): return escape(html) return html def header(self, text, level, raw=None): """Rendering header/heading tags like ``<h1>`` ``<h2>``. :param text: rendered text content for the header. :param level: a number for the header level, for example: 1. :param raw: raw text content of the header. """ return '<h%d>%s</h%d>\n' % (level, text, level) def hrule(self): """Rendering method for ``<hr>`` tag.""" if self.options.get('use_xhtml'): return '<hr />\n' return '<hr>\n' def list(self, body, ordered=True): """Rendering list tags like ``<ul>`` and ``<ol>``. :param body: body contents of the list. :param ordered: whether this list is ordered or not. """ tag = 'ul' if ordered: tag = 'ol' return '<%s>\n%s</%s>\n' % (tag, body, tag) def list_item(self, text): """Rendering list item snippet. Like ``<li>``.""" return '<li>%s</li>\n' % text def paragraph(self, text): """Rendering paragraph tags. Like ``<p>``.""" return '<p>%s</p>\n' % text.strip(' ') def table(self, header, body): """Rendering table element. Wrap header and body in it. :param header: header part of the table. :param body: body part of the table. """ return ( '<table>\n<thead>%s</thead>\n' '<tbody>\n%s</tbody>\n</table>\n' ) % (header, body) def table_row(self, content): """Rendering a table row. Like ``<tr>``. :param content: content of current table row. """ return '<tr>\n%s</tr>\n' % content def table_cell(self, content, **flags): """Rendering a table cell. Like ``<th>`` ``<td>``. :param content: content of current table cell. :param header: whether this is header or not. :param align: align of current table cell. """ if flags['header']: tag = 'th' else: tag = 'td' align = flags['align'] if not align: return '<%s>%s</%s>\n' % (tag, content, tag) return '<%s style="text-align:%s">%s</%s>\n' % ( tag, align, content, tag ) def double_emphasis(self, text): """Rendering **strong** text. :param text: text content for emphasis. """ return '<strong>%s</strong>' % text def emphasis(self, text): """Rendering *emphasis* text. :param text: text content for emphasis. """ return '<em>%s</em>' % text def codespan(self, text): """Rendering inline `code` text. :param text: text content for inline code. """ text = escape(text.rstrip(), smart_amp=False) return '<code>%s</code>' % text def linebreak(self): """Rendering line break like ``<br>``.""" if self.options.get('use_xhtml'): return '<br />\n' return '<br>\n' def strikethrough(self, text): """Rendering ~~strikethrough~~ text. :param text: text content for strikethrough. """ return '<del>%s</del>' % text def text(self, text): """Rendering unformatted text. :param text: text content. """ if self.options.get('parse_block_html'): return text return escape(text) def escape(self, text): """Rendering escape sequence. :param text: text content. """ return escape(text) def autolink(self, link, is_email=False): """Rendering a given link or email address. :param link: link content or email address. :param is_email: whether this is an email or not. """ text = link = escape(link) if is_email: link = 'mailto:%s' % link return '<a href="%s">%s</a>' % (link, text) def link(self, link, title, text): """Rendering a given link with content and title. :param link: href link for ``<a>`` tag. :param title: title content for `title` attribute. :param text: text content for description. """ link = escape_link(link) if not title: return '<a href="%s">%s</a>' % (link, text) title = escape(title, quote=True) return '<a href="%s" title="%s">%s</a>' % (link, title, text) def image(self, src, title, text): """Rendering a image with title and text. :param src: source link of the image. :param title: title text of the image. :param text: alt text of the image. """ src = escape_link(src) text = escape(text, quote=True) if title: title = escape(title, quote=True) html = '<img src="%s" alt="%s" title="%s"' % (src, text, title) else: html = '<img src="%s" alt="%s"' % (src, text) if self.options.get('use_xhtml'): return '%s />' % html return '%s>' % html def inline_html(self, html): """Rendering span level pure html content. :param html: text content of the html snippet. """ if self.options.get('escape'): return escape(html) return html def newline(self): """Rendering newline element.""" return '' def footnote_ref(self, key, index): """Rendering the ref anchor of a footnote. :param key: identity key for the footnote. :param index: the index count of current footnote. """ html = ( '<sup class="footnote-ref" id="fnref-%s">' '<a href="#fn-%s" rel="footnote">%d</a></sup>' ) % (escape(key), escape(key), index) return html def footnote_item(self, key, text): """Rendering a footnote item. :param key: identity key for the footnote. :param text: text content of the footnote. """ back = ( '<a href="#fnref-%s" rev="footnote">&#8617;</a>' ) % escape(key) text = text.rstrip() if text.endswith('</p>'): text = re.sub(r'<\/p>$', r'%s</p>' % back, text) else: text = '%s<p>%s</p>' % (text, back) html = '<li id="fn-%s">%s</li>\n' % (escape(key), text) return html def footnotes(self, text): """Wrapper for all footnotes. :param text: contents of all footnotes. """ html = '<div class="footnotes">\n%s<ol>%s</ol>\n</div>\n' return html % (self.hrule(), text) class Markdown(object): """The Markdown parser. :param renderer: An instance of ``Renderer``. :param inline: An inline lexer class or instance. :param block: A block lexer class or instance. """ def __init__(self, renderer=None, inline=None, block=None, **kwargs): if not renderer: renderer = Renderer(**kwargs) else: kwargs.update(renderer.options) self.renderer = renderer if inline and inspect.isclass(inline): inline = inline(renderer, **kwargs) if block and inspect.isclass(block): block = block(**kwargs) if inline: self.inline = inline else: self.inline = InlineLexer(renderer, **kwargs) self.block = block or BlockLexer(BlockGrammar()) self.footnotes = [] self.tokens = [] # detect if it should parse text in block html self._parse_block_html = kwargs.get('parse_block_html') def __call__(self, text): return self.parse(text) def render(self, text): """Render the Markdown text. :param text: markdown formatted text content. """ return self.parse(text) def parse(self, text): out = self.output(preprocessing(text)) keys = self.block.def_footnotes # reset block self.block.def_links = {} self.block.def_footnotes = {} # reset inline self.inline.links = {} self.inline.footnotes = {} if not self.footnotes: return out footnotes = filter(lambda o: keys.get(o['key']), self.footnotes) self.footnotes = sorted( footnotes, key=lambda o: keys.get(o['key']), reverse=True ) body = self.renderer.placeholder() while self.footnotes: note = self.footnotes.pop() body += self.renderer.footnote_item( note['key'], note['text'] ) out += self.renderer.footnotes(body) return out def pop(self): if not self.tokens: return None self.token = self.tokens.pop() return self.token def peek(self): if self.tokens: return self.tokens[-1] return None # pragma: no cover def output(self, text, rules=None): self.tokens = self.block(text, rules) self.tokens.reverse() self.inline.setup(self.block.def_links, self.block.def_footnotes) out = self.renderer.placeholder() while self.pop(): out += self.tok() return out def tok(self): t = self.token['type'] # sepcial cases if t.endswith('_start'): t = t[:-6] return getattr(self, 'output_%s' % t)() def tok_text(self): text = self.token['text'] while self.peek()['type'] == 'text': text += '\n' + self.pop()['text'] return self.inline(text) def output_newline(self): return self.renderer.newline() def output_hrule(self): return self.renderer.hrule() def output_heading(self): return self.renderer.header( self.inline(self.token['text']), self.token['level'], self.token['text'], ) def output_code(self): return self.renderer.block_code( self.token['text'], self.token['lang'] ) def output_table(self): aligns = self.token['align'] aligns_length = len(aligns) cell = self.renderer.placeholder() # header part header = self.renderer.placeholder() for i, value in enumerate(self.token['header']): align = aligns[i] if i < aligns_length else None flags = {'header': True, 'align': align} cell += self.renderer.table_cell(self.inline(value), **flags) header += self.renderer.table_row(cell) # body part body = self.renderer.placeholder() for i, row in enumerate(self.token['cells']): cell = self.renderer.placeholder() for j, value in enumerate(row): align = aligns[j] if j < aligns_length else None flags = {'header': False, 'align': align} cell += self.renderer.table_cell(self.inline(value), **flags) body += self.renderer.table_row(cell) return self.renderer.table(header, body) def output_block_quote(self): body = self.renderer.placeholder() while self.pop()['type'] != 'block_quote_end': body += self.tok() return self.renderer.block_quote(body) def output_list(self): ordered = self.token['ordered'] body = self.renderer.placeholder() while self.pop()['type'] != 'list_end': body += self.tok() return self.renderer.list(body, ordered) def output_list_item(self): body = self.renderer.placeholder() while self.pop()['type'] != 'list_item_end': if self.token['type'] == 'text': body += self.tok_text() else: body += self.tok() return self.renderer.list_item(body) def output_loose_item(self): body = self.renderer.placeholder() while self.pop()['type'] != 'list_item_end': body += self.tok() return self.renderer.list_item(body) def output_footnote(self): self.inline._in_footnote = True body = self.renderer.placeholder() key = self.token['key'] while self.pop()['type'] != 'footnote_end': body += self.tok() self.footnotes.append({'key': key, 'text': body}) self.inline._in_footnote = False return self.renderer.placeholder() def output_close_html(self): text = self.token['text'] return self.renderer.block_html(text) def output_open_html(self): text = self.token['text'] tag = self.token['tag'] if self._parse_block_html and tag not in _pre_tags: text = self.inline(text, rules=self.inline.inline_html_rules) extra = self.token.get('extra') or '' html = '<%s%s>%s</%s>' % (tag, extra, text, tag) return self.renderer.block_html(html) def output_paragraph(self): return self.renderer.paragraph(self.inline(self.token['text'])) def output_text(self): return self.renderer.paragraph(self.tok_text()) def markdown(text, escape=True, **kwargs): """Render markdown formatted text to html. :param text: markdown formatted text content. :param escape: if set to False, all html tags will not be escaped. :param use_xhtml: output with xhtml tags. :param hard_wrap: if set to True, it will use the GFM line breaks feature. :param parse_block_html: parse text only in block level html. :param parse_inline_html: parse text only in inline level html. """ return Markdown(escape=escape, **kwargs)(text)
ebursztein/SiteFab
SiteFab/parser/mistune.py
Python
gpl-3.0
35,424
# noinspection PyPackageRequirements import wx import gui.globalEvents as GE import gui.mainFrame from gui.contextMenu import ContextMenuSingle from service.fit import Fit class AmmoToDmgPattern(ContextMenuSingle): visibilitySetting = 'ammoPattern' def __init__(self): self.mainFrame = gui.mainFrame.MainFrame.getInstance() def display(self, callingWindow, srcContext, mainItem): if srcContext not in ("marketItemGroup", "marketItemMisc") or self.mainFrame.getActiveFit() is None: return False if mainItem is None: return False for attr in ("emDamage", "thermalDamage", "explosiveDamage", "kineticDamage"): if mainItem.getAttribute(attr) is not None: return True return False def getText(self, callingWindow, itmContext, mainItem): return "Set {} as Damage Pattern".format(itmContext if itmContext is not None else "Item") def activate(self, callingWindow, fullContext, mainItem, i): fitID = self.mainFrame.getActiveFit() Fit.getInstance().setAsPattern(fitID, mainItem) wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID,))) def getBitmap(self, callingWindow, context, mainItem): return None AmmoToDmgPattern.register()
DarkFenX/Pyfa
gui/builtinContextMenus/ammoToDmgPattern.py
Python
gpl-3.0
1,296
package net.adanicx.cyancraft.client.model; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.adanicx.cyancraft.client.OpenGLHelper; import net.adanicx.cyancraft.entities.EntityArmorStand; @SideOnly(Side.CLIENT) public class ModelArmorStand extends ModelArmorStandArmor { public ModelRenderer standRightSide; public ModelRenderer standLeftSide; public ModelRenderer standWaist; public ModelRenderer standBase; public ModelArmorStand() { this(0.0F); } public ModelArmorStand(float size) { super(size, 64, 64); bipedHead = new ModelRenderer(this, 0, 0); bipedHead.addBox(-1.0F, -7.0F, -1.0F, 2, 7, 2, size); bipedHead.setRotationPoint(0.0F, 0.0F, 0.0F); bipedBody = new ModelRenderer(this, 0, 26); bipedBody.addBox(-6.0F, 0.0F, -1.5F, 12, 3, 3, size); bipedBody.setRotationPoint(0.0F, 0.0F, 0.0F); bipedRightArm = new ModelRenderer(this, 24, 0); bipedRightArm.addBox(-2.0F, -2.0F, -1.0F, 2, 12, 2, size); bipedRightArm.setRotationPoint(-5.0F, 2.0F, 0.0F); bipedLeftArm = new ModelRenderer(this, 32, 16); bipedLeftArm.mirror = true; bipedLeftArm.addBox(0.0F, -2.0F, -1.0F, 2, 12, 2, size); bipedLeftArm.setRotationPoint(5.0F, 2.0F, 0.0F); bipedRightLeg = new ModelRenderer(this, 8, 0); bipedRightLeg.addBox(-1.0F, 0.0F, -1.0F, 2, 11, 2, size); bipedRightLeg.setRotationPoint(-1.9F, 12.0F, 0.0F); bipedLeftLeg = new ModelRenderer(this, 40, 16); bipedLeftLeg.mirror = true; bipedLeftLeg.addBox(-1.0F, 0.0F, -1.0F, 2, 11, 2, size); bipedLeftLeg.setRotationPoint(1.9F, 12.0F, 0.0F); standRightSide = new ModelRenderer(this, 16, 0); standRightSide.addBox(-3.0F, 3.0F, -1.0F, 2, 7, 2, size); standRightSide.setRotationPoint(0.0F, 0.0F, 0.0F); standRightSide.showModel = true; standLeftSide = new ModelRenderer(this, 48, 16); standLeftSide.addBox(1.0F, 3.0F, -1.0F, 2, 7, 2, size); standLeftSide.setRotationPoint(0.0F, 0.0F, 0.0F); standWaist = new ModelRenderer(this, 0, 48); standWaist.addBox(-4.0F, 10.0F, -1.0F, 8, 2, 2, size); standWaist.setRotationPoint(0.0F, 0.0F, 0.0F); standBase = new ModelRenderer(this, 0, 32); standBase.addBox(-6.0F, 11.0F, -6.0F, 12, 1, 12, size); standBase.setRotationPoint(0.0F, 12.0F, 0.0F); } @Override public void setRotationAngles(float p_78087_1_, float p_78087_2_, float p_78087_3_, float p_78087_4_, float p_78087_5_, float p_78087_6_, Entity entity) { super.setRotationAngles(p_78087_1_, p_78087_2_, p_78087_3_, p_78087_4_, p_78087_5_, p_78087_6_, entity); if (entity instanceof EntityArmorStand) { EntityArmorStand stand = (EntityArmorStand) entity; bipedLeftArm.showModel = stand.getShowArms(); bipedRightArm.showModel = stand.getShowArms(); standBase.showModel = !stand.hasNoBasePlate(); bipedLeftLeg.setRotationPoint(1.9F, 12.0F, 0.0F); bipedRightLeg.setRotationPoint(-1.9F, 12.0F, 0.0F); standRightSide.rotateAngleX = 0.017453292F * stand.getBodyRotation().getX(); standRightSide.rotateAngleY = 0.017453292F * stand.getBodyRotation().getY(); standRightSide.rotateAngleZ = 0.017453292F * stand.getBodyRotation().getZ(); standLeftSide.rotateAngleX = 0.017453292F * stand.getBodyRotation().getX(); standLeftSide.rotateAngleY = 0.017453292F * stand.getBodyRotation().getY(); standLeftSide.rotateAngleZ = 0.017453292F * stand.getBodyRotation().getZ(); standWaist.rotateAngleX = 0.017453292F * stand.getBodyRotation().getX(); standWaist.rotateAngleY = 0.017453292F * stand.getBodyRotation().getY(); standWaist.rotateAngleZ = 0.017453292F * stand.getBodyRotation().getZ(); standBase.rotateAngleX = 0.0F; standBase.rotateAngleY = 0.017453292F * -entity.rotationYaw; standBase.rotateAngleZ = 0.0F; } } @Override public void render(Entity p_78088_1_, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float p_78088_7_) { super.render(p_78088_1_, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, p_78088_7_); OpenGLHelper.pushMatrix(); if (isChild) { float f6 = 2.0F; OpenGLHelper.scale(1.0F / f6, 1.0F / f6, 1.0F / f6); OpenGLHelper.translate(0.0F, 24.0F * p_78088_7_, 0.0F); standRightSide.render(p_78088_7_); standLeftSide.render(p_78088_7_); standWaist.render(p_78088_7_); standBase.render(p_78088_7_); } else { if (p_78088_1_.isSneaking()) OpenGLHelper.translate(0.0F, 0.2F, 0.0F); standRightSide.render(p_78088_7_); standLeftSide.render(p_78088_7_); standWaist.render(p_78088_7_); standBase.render(p_78088_7_); } OpenGLHelper.popMatrix(); } }
Cyancraft/Cyancraft
src/main/java/net/adanicx/cyancraft/client/model/ModelArmorStand.java
Java
gpl-3.0
4,767
<?php include 'common_header.php'; ?> <!-- Settings View Title --> <h3><?php e($title); ?></h3> <!-- Pasephrase Reset Form --> <form id="settings_account_reset" class="rounded" action="<?php u('/settings/accounts/reset'); ?>" method="post" accept-charset="UTF-8" enctype="multipart/form-data"> <fieldset> <?php $alias = $account->get_default_alias(); ?> Do you want to <strong>RESET</strong> the passphrase for <strong><?php e($alias->name); ?></strong> (<?php e($alias->email); ?>) ? <br /> <?php e($alias->name); ?> will no longer be able to log in using the old passphrase. <br /><br /> </fieldset> <fieldset> <p style="margin-bottom: 16px"> <label for="pass1">New Passphrase</label><br /> <input type="password" id="pass1" name="pass1" value="" /> </p> <p style="margin-bottom: 32px"> <label for="pass2">New Passphrase (Repeat)</label><br /> <input type="password" id="pass2" name="pass2" value="" /> </p> </fieldset> <fieldset> <?php \Common\Session::add_token($token = \Common\Security::get_random(16)); ?> <input type="hidden" name="account_id" value="<?php e($account->id); ?>" /> <input type="hidden" name="csrf_token" id="csrf_token" value="<?php e($token); ?>" /> </fieldset> <fieldset> <button type="submit" class="rounded" name="button" value="yes">Reset Passphrase</button> <button type="submit" class="rounded" name="button" value="no">Cancel</button> </fieldset> </form> <!-- Standard Footers --> <?php include 'common_footer.php'; ?>
kijin/nearlyfreemail
program/views/accounts_reset.php
PHP
gpl-3.0
1,673
# This module is for compatibility only. All functions are defined elsewhere. __all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean'] import numpy.oldnumeric.linear_algebra as LinearAlgebra import numpy.oldnumeric.random_array as RandomArray from numpy import tril, trapz as _Ntrapz, hanning, rot90, triu, diff, \ angle, roots, ptp as _Nptp, kaiser, cumprod as _Ncumprod, \ diag, msort, prod as _Nprod, std as _Nstd, hamming, flipud, \ amax as _Nmax, amin as _Nmin, blackman, bartlett, \ squeeze, sinc, median, fliplr, mean as _Nmean, transpose from numpy.linalg import eig, svd from numpy.random import rand, randn import numpy as np from typeconv import convtypecode def eye(N, M=None, k=0, typecode=None, dtype=None): """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones, and everything else is zeros. """ dtype = convtypecode(typecode, dtype) if M is None: M = N m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) def tri(N, M=None, k=0, typecode=None, dtype=None): """ returns a N-by-M array where all the diagonals starting from lower left corner up to the k-th are all ones. """ dtype = convtypecode(typecode, dtype) if M is None: M = N m = np.greater_equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) def trapz(y, x=None, axis=-1): return _Ntrapz(y, x, axis=axis) def ptp(x, axis=0): return _Nptp(x, axis) def cumprod(x, axis=0): return _Ncumprod(x, axis) def max(x, axis=0): return _Nmax(x, axis) def min(x, axis=0): return _Nmin(x, axis) def prod(x, axis=0): return _Nprod(x, axis) def std(x, axis=0): N = asarray(x).shape[axis] return _Nstd(x, axis)*sqrt(N/(N-1.)) def mean(x, axis=0): return _Nmean(x, axis) # This is exactly the same cov function as in MLab def cov(m, y=None, rowvar=0, bias=0): if y is None: y = m else: y = y if rowvar: m = transpose(m) y = transpose(y) if (m.shape[0] == 1): m = transpose(m) if (y.shape[0] == 1): y = transpose(y) N = m.shape[0] if (y.shape[0] != N): raise ValueError("x and y must have the same number of observations") m = m - _Nmean(m,axis=0) y = y - _Nmean(y,axis=0) if bias: fact = N*1.0 else: fact = N-1.0 return squeeze(dot(transpose(m), conjugate(y)) / fact) from numpy import sqrt, multiply def corrcoef(x, y=None): c = cov(x, y) d = diag(c) return c/sqrt(multiply.outer(d,d)) from compat import * from functions import * from precision import * from ufuncs import * from misc import * import compat import precision import functions import misc import ufuncs import numpy __version__ = numpy.__version__ del numpy __all__ += ['__version__'] __all__ += compat.__all__ __all__ += precision.__all__ __all__ += functions.__all__ __all__ += ufuncs.__all__ __all__ += misc.__all__ del compat del functions del precision del ufuncs del misc
beiko-lab/gengis
bin/Lib/site-packages/numpy/oldnumeric/mlab.py
Python
gpl-3.0
3,566
<?php /** * WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan * * The PHP page that serves all page requests on WebExploitScan installation. * * The routines here dispatch control to the appropriate handler, which then * prints the appropriate page. * * All WebExploitScan code is released under the GNU General Public License. * See COPYRIGHT.txt and LICENSE.txt. */ $NAME='Php-MS-PHP-Antimalware-Scanner malware_signature- ID 2369'; $TAGCLEAR='WSOsetcookie(md5(@?$_SERVER[[\'"]HTTP_HOST[\'"]])'; $TAGBASE64='V1NPc2V0Y29va2llKG1kNShAPyRfU0VSVkVSW1tcJyJdSFRUUF9IT1NUW1wnIl1dKQ=='; $TAGHEX='57534f736574636f6f6b6965286d643528403f245f5345525645525b5b5c27225d485454505f484f53545b5c27225d5d29'; $TAGHEXPHP=''; $TAGURI='WSOsetcookie%28md5%28%40%3F%24_SERVER%5B%5B%5C%27%22%5DHTTP_HOST%5B%5C%27%22%5D%5D%29'; $TAGCLEAR2=''; $TAGBASE642=''; $TAGHEX2=''; $TAGHEXPHP2=''; $TAGURI2=''; $DATEADD='10/09/2019'; $LINK='Webexploitscan.org ;Php-MS-PHP-Antimalware-Scanner malware_signature- ID 2369 '; $ACTIVED='1'; $VSTATR='malware_signature';
libre/webexploitscan
wes/data/rules/fullscan/10092019-MS-PHP-Antimalware-Scanner-2369-malware_signature.php
PHP
gpl-3.0
1,060
#include <vgStableHeaders.h> #include "vgentry/vgSound3DEntry.h" #include <vgUIController/vgPropertyPage.h> #include <vgUIController/vgUIController.h> #include <vgKernel/vgkVec3.h> #include <vgMesh/vgmMeshManager.h> //#include <vgMath/vgfVector3.h> #include <vgKernel/vgkSelectManager.h> PropertiesParam vgSound3DEntry::s_ParamArray[s_NumOfParam]; vgSound3DEntry::vgSound3DEntry(vgSound::Sound3D* renderer) :vgBaseEntry( renderer ) { sound= (vgSound::Sound3D *)renderer; if (sound) { m_sCaption = sound->getName(); b_play = sound->getPlayFlag(); x = sound->getSoundPos().x + vgKernel::CoordSystem::getSingleton().getProjectionCoord().x; y = sound->getSoundPos().y + vgKernel::CoordSystem::getSingleton().getProjectionCoord().y; z = sound->getSoundPos().z + vgKernel::CoordSystem::getSingleton().getProjectionCoord().z; zMinus = -z; sound->registerObserver( this ); vgKernel::CoordSystem::getSingleton().registerObserver(this); } } vgSound3DEntry::~vgSound3DEntry(void) { sound->unregisterObserver( this ); sound = NULL; } void vgSound3DEntry::OnPropertyChanged(string paramName) { z = - zMinus; vgSound::Sound3D *sound = (vgSound::Sound3D *)m_Renderer; vgKernel::Vec3 aa = vgKernel::CoordSystem::getSingleton().getProjectionCoord(); sound->setAbsolutePos( x - aa.x, y - aa.y ,z - aa.z); /* sound->GenBoundaryBox(sound->getSoundPos());*/ sound->setPlayFlag( b_play ); if (b_play) { sound->startPlaying( true ); } else sound->stopPlaying(); // ¸üÐÂTREEITEM vgUI::UIController::getSingleton().GetWorkSpaceBar()->SetItemText(hTreeItem, m_Renderer->getName()); vgKernel::SelectManager::getSingleton().updateBox(); } void vgSound3DEntry::onChanged(int eventId, void *param) { if (eventId == vgKernel::VG_OBS_PROPCHANGED) { vgSound::Sound3D *sound = (vgSound::Sound3D *)m_Renderer; vgKernel::Vec3 xx = sound->getSoundPos(); x = xx.x + vgKernel::CoordSystem::getSingleton().getProjectionCoord().x; y = xx.y + vgKernel::CoordSystem::getSingleton().getProjectionCoord().y; z = xx.z + vgKernel::CoordSystem::getSingleton().getProjectionCoord().z; //TRACE("New Camera Position %.2f %.2f %.2f \n", posPtr->x, posPtr->y, posPtr->z); if (this == vgUI::UIController::getSingleton().GetCurrentSelectedNode()) { s_ParamArray[1].pProp->SetValue(x); s_ParamArray[2].pProp->SetValue(y); zMinus = -z; s_ParamArray[3].pProp->SetValue(zMinus); } } if (eventId == vgKernel::VG_OBS_SELECTCHAGNED) { vgUI::UIController::getSingleton().SelectNode(this); } if (eventId == vgKernel::VG_OBS_ADDSELECTION) { vgUI::UIController::getSingleton().AddSelection(this); return ; } } void vgSound3DEntry::AddNodeTabs() { vgUI::UIController::getSingleton().RemoveAllPages(); vgPropertiesViewBar* pageViewBar = vgUI::UIController::getSingleton().GetPropertiesViewBar(); s_ParamArray[0].label = "×ø±êÖµÉèÖÃ"; s_ParamArray[0].typeId = PROP_ITEM_GROUP; s_ParamArray[0].dataType = PROP_DATA_NONE; s_ParamArray[0].connectedPtr = NULL; s_ParamArray[0].comment = "ÉèÖÃÏà»úµÄ×ø±ê"; s_ParamArray[1].label = "X ×ø±ê"; s_ParamArray[1].typeId = PROP_ITEM_DATA; s_ParamArray[1].dataType = PROP_DATA_FLOAT; s_ParamArray[1].connectedPtr = &x; s_ParamArray[1].comment = "ÉèÖÃX×ø±ê"; s_ParamArray[2].label = "Y ×ø±ê"; s_ParamArray[2].typeId = PROP_ITEM_DATA; s_ParamArray[2].dataType = PROP_DATA_FLOAT; s_ParamArray[2].connectedPtr = &y; s_ParamArray[2].comment = "ÉèÖÃY×ø±ê"; s_ParamArray[3].label = "Z ×ø±ê"; s_ParamArray[3].typeId = PROP_ITEM_DATA; s_ParamArray[3].dataType = PROP_DATA_FLOAT; s_ParamArray[3].connectedPtr = &zMinus; s_ParamArray[3].comment = "ÉèÖÃZ×ø±ê"; s_ParamArray[4].label = "ÆäËûÉèÖÃ"; s_ParamArray[4].typeId = PROP_ITEM_GROUP; s_ParamArray[4].dataType = PROP_DATA_NONE; s_ParamArray[4].connectedPtr = NULL; s_ParamArray[4].comment = string(); s_ParamArray[5].label = "ÒôЧÃû³Æ"; s_ParamArray[5].typeId = PROP_ITEM_DATA; s_ParamArray[5].dataType = PROP_DATA_STR; s_ParamArray[5].connectedPtr = m_Renderer->getNamePtr(); s_ParamArray[5].comment = "ÎïÌåµÄÃû³Æ"; s_ParamArray[6].label = "ÊÇ·ñ²¥·Å"; s_ParamArray[6].typeId = PROP_ITEM_DATA; s_ParamArray[6].dataType = PROP_DATA_BOOL; s_ParamArray[6].connectedPtr = &b_play; s_ParamArray[6].comment = "ÊÇ·ñ²¥·Å"; vgPropertyPage* propPage = vgUI::UIController::getSingleton().GetPropPage(); propPage->Create(NIDD_PROPERTY, pageViewBar->GetTabControl()); propPage->ConnectNode(this, s_ParamArray, s_NumOfParam); pageViewBar->AddTab("×Ô¶¯ÊôÐÔ", propPage); } CMenu* vgSound3DEntry::GetContextMenu() { CMenu *menu = new CMenu; VERIFY(menu->CreatePopupMenu()); // VERIFY(menu->AppendMenu(MF_STRING, NID_MESH_GOTO, _T("תµ½"))); VERIFY(menu->AppendMenu(MF_STRING, NID_MESH_DELETE,_T("ɾ³ý"))); return menu; }
xzy0008/sample_code
SAMPLE_CODE/src/vgEntry/vgSound3DEntry.cpp
C++
gpl-3.0
4,971
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Natural Europe Pathways <?php echo isset($title) ? ' | ' . strip_formatting($title) : ''; ?></title> <!-- Meta --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="description" content="Pathway test!" /> <meta name="Keywords" content="pathways"> <?php //echo auto_discovery_link_tag(); ?> <?php $findme="students"; $pos = stripos($_SERVER['REQUEST_URI'],$findme); $findme_exh="exhibits"; $pos_exhib = stripos($_SERVER['REQUEST_URI'],$findme_exh); $findme_exh2="/exhibits/"; $pos_exhib2 = stripos($_SERVER['REQUEST_URI'],$findme_exh2); $findme_resources = "resources"; $pos_resources = stripos($_SERVER['REQUEST_URI'],$findme_resources); $findme_home = "home"; $pos_home = stripos($_SERVER['REQUEST_URI'],$findme_home); $findme_collections = "collection"; $pos_collections = 0; $pos_collections = stripos($_SERVER['REQUEST_URI'],$findme_collections); $findme_edu="educators"; $pos_edu = stripos($_SERVER['REQUEST_URI'],$findme_edu); $findme_search="search"; $pos_search = stripos($_SERVER['REQUEST_URI'],$findme_search); $findme_users="users"; $pos_users = stripos($_SERVER['REQUEST_URI'],$findme_users); $findme_glos="glossary"; $pos_glos = stripos($_SERVER['REQUEST_URI'],$findme_glos); $findme_res="research"; $pos_res = stripos($_SERVER['REQUEST_URI'],$findme_res); $findme_disc="eid"; $pos_disc = stripos($_SERVER['REQUEST_URI'],$findme_disc); ?> <!-- Stylesheets --> <?php if(isset($_GET['nhm']) and $_GET['nhm']=='MNHN'){ ?> <link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_mnhn.css'); ?>"/> <?php } elseif(isset($_GET['nhm']) and $_GET['nhm']=='TNHM'){ ?> <link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_tnhm.css'); ?>"/> <?php } elseif(isset($_GET['nhm']) and $_GET['nhm']=='NHMC'){ ?> <link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_tnhm.css'); ?>"/> <?php } elseif(isset($_GET['nhm']) and $_GET['nhm']=='HNHM'){ ?> <link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_tnhm.css'); ?>"/> <?php } elseif(isset($_GET['nhm']) and $_GET['nhm']=='JME'){ ?> <link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_tnhm.css'); ?>"/> <?php } elseif(isset($_GET['nhm']) and $_GET['nhm']=='AC'){ ?> <link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page_tnhm.css'); ?>"/> <?php } else{ ?> <link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/page.css'); ?>"/> <?php } ?> <link rel="shortcut icon" href="./images/fav.ico" /> <link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/lightview/css/lightview.css');?>" /> <link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/typography.css');?>"/> <!--[if lt IE 8]><link href="<?php echo uri('themes/natural/css/page_ie7.css');?>" rel="stylesheet" type="text/css" media="screen" /><![endif]--> <!-- JavaScripts --> <script type="text/javascript" src="<?php echo uri('themes/natural/scripts/ajax/ajax.js');?>"></script> <script type="text/javascript" src="<?php echo uri('themes/natural/scripts/ajax/ajax_chained.js');?>"></script> <?php if ($pos_collections>'0'){ } else{ echo '<script type="text/javascript" src="'.uri('themes/natural/lightview/prototype.js').'"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.2/scriptaculous.js"></script>'; } ?> <script type='text/javascript' src="<?php echo uri('themes/natural/lightview/js/lightview.js');?>"></script> <script type='text/javascript' src="<?php echo uri('themes/natural/scripts/functions.js');?>"></script> <?php if ($pos_exhib2>0){ ?> <link rel="stylesheet" type="text/css" href="<?php echo uri('themes/natural/css/jquery.jscrollpane.css'); ?>"/> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script>jQuery.noConflict();</script> <?php } else{ ?> <script type="text/javascript" language="javascript" src="<?php echo uri('themes/natural/javascripts/jquery.js'); ?>"></script> <script> jQuery.noConflict(); </script> <?php } ?> <script type="text/javascript" language="javascript" src="<?php echo uri('themes/natural/javascripts/main_tooltip.js'); ?>"></script> <!-- Plugin Stuff --> <?php echo plugin_header(); ?> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-28875549-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body> <?php session_start(); // store session data $locale = Zend_Registry::get('Zend_Locale'); $_SESSION['get_language']=get_language_for_switch(); $_SESSION['get_language_omeka']=get_language_for_omeka_switch(); $_SESSION['get_language_for_internal_xml']=get_language_for_internal_xml(); ?> <div id="page-container"> <?php if(isset($_GET['nhm']) and ($_GET['nhm']=='MNHN' or $_GET['nhm']=='TNHM' or $_GET['nhm']=='NHMC' or $_GET['nhm']=='JME' or $_GET['nhm']=='HNHM' or $_GET['nhm']=='AC')){ ?> <?php } else{ ?> <div id="page-header"> <div style="float:left;"><h1><a href="<?php echo uri('index');?>"><img src="<?php echo uri('themes/natural/images/interface/logonatural.png'); ?>"></a></a></h1></div><!--end rx div--> <div id="nav-site-supplementary" class="menubar"> <ul id="nav-site-supplementary-menu"> <li><a href="<?php echo uri('admin/users/login');?>" title="Sign-in"><?php echo __('Sign-in'); ?></a></li> </ul><!--end nav-site-supplementary-menu ul--> </div><!--end nav-site-supplementary div--> </div><!--end page-header div--> <div id="languages" style="position: absolute; top: 150px; right: 10px; width: 200px;"> <?php echo language_switcher(); ?> </div> <?php } ?>
agroknow/PAT
application/views/scripts/common/header.php
PHP
gpl-3.0
6,482
!function(namespace) { 'use strict'; function Modal(elem, params) { this.$element = jQuery(elem); this.params = params || {}; this.cssReadyElement = this.params.cssReadyElement || 'JS-Modal-ready'; this.cssActiveElement = this.params.cssActiveElement || 'JS-Modal-active'; this.__construct(); } Modal.prototype.__construct = function __construct() { this.$box = this.$element.find('.JS-Modal-Box'); this.$close = this.$element.find('.JS-Modal-Close'); this.$title = this.$element.find('.JS-Modal-Title'); this.$container = this.$element.find('.JS-Modal-Container'); this._init(); }; Modal.prototype._init = function _init() { var _this = this; this.$close.on('click.JS-Modal', function() { _this._close.apply(_this, []); }); $('body').on("keyup", function(e) { if ((e.keyCode == 27)) { _this._close.apply(_this, []); } }); $('.JS-Gannt-Modal').click(function() { if (_this.$element.hasClass('JS-Modal-active')) _this._close.apply(_this, []); }); $('.JS-Modal-Box').click(function(event){ event.stopPropagation(); }); /* API. Events */ this.$element.on('modal:setContent', function(e, data) { _this.setContent.apply(_this, [data]); }); this.$element.on('modal:open', function() { _this.open.apply(_this, []); }); this.$element.on('modal:close', function() { _this.close.apply(_this, []); }); this.$element.on('modal:clear', function() { _this.clear.apply(_this, []); }); this._ready(); } ; Modal.prototype._ready = function _ready() { this.$element .addClass(this.cssReadyElement) .addClass('JS-Modal-ready'); }; Modal.prototype._setContent = function _setContent(content) { this.$container.html(content); }; Modal.prototype._open = function _open() { if (!this.$element.hasClass('JS-Modal-active')) { this.$element .addClass(this.cssActiveElement) .addClass('JS-Modal-active') } }; Modal.prototype._close = function _close() { if (this.$element.hasClass('JS-Modal-active')) { this.$element .removeClass(this.cssActiveElement) .removeClass('JS-Modal-active'); } }; Modal.prototype._clear = function _clear() { }; /* API. Methods */ Modal.prototype.setContent = function setContent(content) { if (!arguments.length) { return false; } this._setContent(content); }; Modal.prototype.open = function open() { this._open(); }; Modal.prototype.close = function close() { this._close(); }; Modal.prototype.clear = function clear() { this._clear(); }; namespace.Modal = Modal; }(this);
subuk/bakapy
front/scripts/modal.js
JavaScript
gpl-3.0
2,698
/* * Copyright (C) 2009 Christopho, Solarus - http://www.solarus-engine.org * * Solarus is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Solarus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "hero/HookshotState.h" #include "hero/FreeState.h" #include "hero/HeroSprites.h" #include "entities/MapEntities.h" #include "entities/Hookshot.h" /** * @brief Constructor. * @param hero the hero controlled by this state */ Hero::HookshotState::HookshotState(Hero &hero): State(hero), hookshot(NULL) { } /** * @brief Destructor. */ Hero::HookshotState::~HookshotState() { } /** * @brief Starts this state. * @param previous_state the previous state */ void Hero::HookshotState::start(State *previous_state) { State::start(previous_state); get_sprites().set_animation_hookshot(); hookshot = new Hookshot(hero); get_entities().add_entity(hookshot); } /** * @brief Ends this state. * @param next_state the next state (for information) */ void Hero::HookshotState::stop(State *next_state) { State::stop(next_state); if (!hookshot->is_being_removed()) { // the hookshot state was stopped by something other than the hookshot (e.g. an enemy) hookshot->remove_from_map(); hero.clear_movement(); } } /** * @brief Returns whether the hero is touching the ground in the current state. * @return true if the hero is touching the ground in the current state */ bool Hero::HookshotState::is_touching_ground() { return false; } /** * @brief Returns whether the hero ignores the effect of deep water in this state. * @return true if the hero ignores the effect of deep water in the current state */ bool Hero::HookshotState::can_avoid_deep_water() { return true; } /** * @brief Returns whether the hero ignores the effect of holes in this state. * @return true if the hero ignores the effect of holes in the current state */ bool Hero::HookshotState::can_avoid_hole() { return true; } /** * @brief Returns whether the hero ignores the effect of lava in this state. * @return true if the hero ignores the effect of lava in the current state */ bool Hero::HookshotState::can_avoid_lava() { return true; } /** * @brief Returns whether the hero ignores the effect of prickles in this state. * @return true if the hero ignores the effect of prickles in the current state */ bool Hero::HookshotState::can_avoid_prickle() { return true; } /** * @brief Returns whether the hero ignores the effect of teletransporters in this state. * @return true if the hero ignores the effect of teletransporters in this state */ bool Hero::HookshotState::can_avoid_teletransporter() { return true; } /** * @brief Returns whether the hero ignores the effect of conveyor belts in this state. * @return true if the hero ignores the effect of conveyor belts in this state */ bool Hero::HookshotState::can_avoid_conveyor_belt() { return true; } /** * @brief Returns whether some stairs are considered as obstacle in this state. * @param stairs some stairs * @return true if the stairs are obstacle in this state */ bool Hero::HookshotState::is_stairs_obstacle(Stairs& stairs) { // allow to fly over stairs covered by water return hero.get_ground() != GROUND_DEEP_WATER; } /** * @brief Returns whether a sensor is considered as an obstacle in this state. * @param sensor a sensor * @return true if the sensor is an obstacle in this state */ bool Hero::HookshotState::is_sensor_obstacle(Sensor& sensor) { return true; } /** * @brief Returns whether a jump sensor is considered as an obstacle in this state. * @param jump_sensor a jump sensor * @return true if the sensor is an obstacle in this state */ bool Hero::HookshotState::is_jump_sensor_obstacle(JumpSensor& jump_sensor) { return false; } /** * @brief Returns whether the hero ignores the effect of switches in this state. * @return true if the hero ignores the effect of switches in this state */ bool Hero::HookshotState::can_avoid_switch() { return true; } /** * @brief Returns whether the hero can be hurt in this state. * @return true if the hero can be hurt in this state */ bool Hero::HookshotState::can_be_hurt() { return true; } /** * @brief Notifies this state that the hero has just tried to change his position. * @param success true if the position has actually just changed */ void Hero::HookshotState::notify_movement_tried(bool success) { if (!success) { // an unexpected obstacle was reached (e.g. a moving NPC) hero.set_state(new FreeState(hero)); } }
ziz/solarus
src/hero/HookshotState.cpp
C++
gpl-3.0
5,054
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ArticleComment' db.create_table('cms_articlecomment', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('article', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['cms.Article'])), ('created_at', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)), ('author', self.gf('django.db.models.fields.CharField')(max_length=60)), ('comment', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal('cms', ['ArticleComment']) def backwards(self, orm): # Deleting model 'ArticleComment' db.delete_table('cms_articlecomment') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'cms.article': { 'Meta': {'ordering': "['title']", 'object_name': 'Article'}, 'allow_comments': ('django.db.models.fields.CharField', [], {'default': "'N'", 'max_length': '1'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'content': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'conversions': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'created_at': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime.now'}), 'header': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'keywords': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'sections': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['cms.Section']", 'null': 'True', 'through': "orm['cms.SectionItem']", 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '250', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'updated_at': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'blank': 'True'}), 'views': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'cms.articlearchive': { 'Meta': {'ordering': "('updated_at',)", 'object_name': 'ArticleArchive'}, 'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Article']"}), 'content': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'header': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'cms.articlecomment': { 'Meta': {'ordering': "('created_at',)", 'object_name': 'ArticleComment'}, 'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Article']"}), 'author': ('django.db.models.fields.CharField', [], {'max_length': '60'}), 'comment': ('django.db.models.fields.TextField', [], {}), 'created_at': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'cms.filedownload': { 'Meta': {'object_name': 'FileDownload'}, 'count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'expires_at': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'file': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['filer.File']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'uuid': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'blank': 'True'}) }, 'cms.menu': { 'Meta': {'object_name': 'Menu'}, 'article': ('smart_selects.db_fields.ChainedForeignKey', [], {'default': 'None', 'to': "orm['cms.Article']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'link': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['cms.Menu']"}), u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'section': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Section']", 'null': 'True', 'blank': 'True'}), u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, 'cms.section': { 'Meta': {'ordering': "['title']", 'object_name': 'Section'}, 'articles': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['cms.Article']", 'null': 'True', 'through': "orm['cms.SectionItem']", 'blank': 'True'}), 'conversions': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'header': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keywords': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '250', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'views': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'cms.sectionitem': { 'Meta': {'ordering': "['order']", 'object_name': 'SectionItem'}, 'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Article']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}), 'section': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Section']"}) }, 'cms.urlmigrate': { 'Meta': {'object_name': 'URLMigrate'}, 'dtupdate': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_url': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'obs': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'old_url': ('django.db.models.fields.CharField', [], {'max_length': '250', 'db_index': 'True'}), 'redirect_type': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'views': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'filer.file': { 'Meta': {'object_name': 'File'}, '_file_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'folder': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'all_files'", 'null': 'True', 'to': "orm['filer.Folder']"}), 'has_all_mandatory_data': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}), 'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_files'", 'null': 'True', 'to': "orm['auth.User']"}), 'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'polymorphic_filer.file_set'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'sha1': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '40', 'blank': 'True'}), 'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'filer.folder': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('parent', 'name'),)", 'object_name': 'Folder'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'filer_owned_folders'", 'null': 'True', 'to': "orm['auth.User']"}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['filer.Folder']"}), u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) } } complete_apps = ['cms']
josircg/raizcidadanista
raizcidadanista/cms/migrations/0004_auto__add_articlecomment.py
Python
gpl-3.0
14,504
# Copyright (C) 2015 SensorLab, Jozef Stefan Institute http://sensorlab.ijs.si # # Written by Tomaz Solc, tomaz.solc@ijs.si # # This work has been partially funded by the European Community through the # 7th Framework Programme project CREW (FP7-ICT-2009-258301). # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # this program. If not, see http://www.gnu.org/licenses/ import logging import Queue import random import time from spectrumwars.testbed import TestbedBase, RadioBase, RadioTimeout, RadioError, TestbedError, RadioPacket log = logging.getLogger(__name__) class Radio(RadioBase): RECEIVE_TIMEOUT = 2. def __init__(self, addr, dispatcher, send_delay): super(Radio, self).__init__() self.addr = addr self.neighbor = None self.dispatcher = dispatcher self.q = Queue.Queue() self.frequency = 0 self.bandwidth = 0 self.send_delay = send_delay def _recv(self, addr, bindata, frequency, bandwidth): if self.frequency == frequency and self.bandwidth == bandwidth and self.addr == addr: self.q.put(bindata) def set_configuration(self, frequency, bandwidth, power): self.frequency = frequency self.bandwidth = bandwidth def binsend(self, bindata): self.dispatcher(self.neighbor, bindata, self.frequency, self.bandwidth) time.sleep(self.send_delay) def binrecv(self, timeout=None): if timeout is None: timeout = self.RECEIVE_TIMEOUT try: bindata = self.q.get(True, timeout) except Queue.Empty: raise RadioTimeout else: return bindata class Testbed(TestbedBase): RADIO_CLASS = Radio def __init__(self, send_delay=.1, frequency_range=64, bandwidth_range=10, power_range=10, packet_size=1024): self.send_delay = float(send_delay) self.frequency_range = int(frequency_range) self.bandwidth_range = int(bandwidth_range) self.power_range = int(power_range) self.RADIO_CLASS.PACKET_SIZE = int(packet_size) + 1 self.radios = [] # for each channel, we keep the timestamp of the last # transmission. we use this for simulated spectrum sensing and # for detecting collisions. self.channels = [0] * self.frequency_range self.i = 0 def _get_radio(self): r = Radio(self.i, self._dispatcher, self.send_delay) self.radios.append(r) self.i += 1 return r def _dispatcher(self, addr, bindata, frequency, bandwidth): now = self.time() has_collision = (now - self.channels[frequency]) > self.send_delay self.channels[frequency] = now if has_collision: # note that when packets collide, the first one goes # through while the later ones fail. this is different # than in reality: all should fail. But this would # be complicated to implement in practice. for radio in self.radios: radio._recv(addr, bindata, frequency, bandwidth) else: log.debug("packet collision detected on channel %d" % (frequency,)) def get_radio_pair(self): dst = self._get_radio() src = self._get_radio() dst.neighbor = src.addr src.neighbor = dst.addr return dst, src def get_spectrum(self): spectrum = [] now = self.time() for time in self.channels: if now - time < .5: p = random.randint(-40, -20) else: p = random.randint(-90, -80) spectrum.append(p) return tuple(spectrum) def get_frequency_range(self): return self.frequency_range def get_bandwidth_range(self): return self.bandwidth_range def get_power_range(self): return self.power_range
avian2/spectrumwars
controller/spectrumwars/testbed/simulation.py
Python
gpl-3.0
3,927
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <dirent.h> #include <fcntl.h> #include <assert.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/time.h> #include <bcm2835.h> #include <unistd.h> #include <iostream> //#define BCM2708_PERI_BASE 0x20000000 #define BCM2708_PERI_BASE 0x3F000000 #define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) /* GPIO controller */ #define MAXTIMINGS 100 #define PIN_DHT 4 //GPIO Mapping DHT Sensor #define PIN_LED RPI_GPIO_P1_12 //GPIO Mapping LED //#define DEBUG using namespace std; int readDHT(int pin, float *humid0, float *temp0); int cosmput(float humid, float temp, int *feedid, char *key, char *feed_name, char *field0_name, char *field1_name); int readconfig(char *pFileName, int *feedid, char *key, char *feed_name, char *field0_name, char *field1_name); int main(int argc, char **argv) { long cnt = 1; if(argc > 1){ cnt = atol(argv[1]); } int dhtpin = PIN_DHT; int ledpin = PIN_LED; float humid0, temp0, ahumid, atemp,otemp = 0; int feedid = 0; char key[100]; char feed_name[100]; char field0_name[100]; char field1_name[100]; // char pFileName[]="config.ini"; // readconfig(pFileName, &feedid, key, feed_name, field0_name, field1_name); if (!bcm2835_init()) return 1; bcm2835_gpio_fsel(ledpin, BCM2835_GPIO_FSEL_OUTP); bcm2835_gpio_write(ledpin, HIGH); //LED an fprintf(stderr,"Using pin #%d\n", dhtpin); while(cnt > 0) { ahumid = atemp = 0.0; for (int i=0; i< 5; i++) { // Mittelwert bilden, um "zittern" der Kurve zu minimieren readDHT(dhtpin, &humid0, &temp0); ahumid = ahumid + humid0; atemp = atemp + temp0; sleep(1); } ahumid = ahumid / 5; atemp = atemp / 5; if(ahumid < 5 || atemp < 5 || ahumid >100 || atemp > 100)// || (otemp > 0 && (atemp < otemp - 5 || atemp > otemp +5))){ { fprintf(stderr,"Invalid values. Still calibrating?\n"); continue; } time_t tr = time(NULL); //char *t = asctime(localtime(&tr)); cnt--; printf("TIME=%d\nTEMP=%0.1f\nHUMID=%0.1f\n", tr, atemp, ahumid); otemp = atemp; //cosmput(ahumid, atemp, &feedid, key, feed_name, field0_name, field1_name); } bcm2835_gpio_fsel(ledpin, BCM2835_GPIO_FSEL_OUTP); bcm2835_gpio_write(ledpin, LOW); //LED aus return 0; } // main int readDHT(int pin, float *humid0, float *temp0) { int counter = 0; int laststate = HIGH; int j=0; int bits[250], data[100]; int bitidx = 0; // Set GPIO pin to output bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP); bcm2835_gpio_write(pin, HIGH); usleep(500000); // 500 ms bcm2835_gpio_write(pin, LOW); usleep(20000); bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT); data[0] = data[1] = data[2] = data[3] = data[4] = 0; // wait for pin to drop? while (bcm2835_gpio_lev(pin) == 1) { usleep(1); } // read data! for (int i=0; i< MAXTIMINGS; i++) { counter = 0; while ( bcm2835_gpio_lev(pin) == laststate) { counter++; //nanosleep(1); // overclocking might change this? if (counter == 1000) break; } laststate = bcm2835_gpio_lev(pin); if (counter == 1000) break; bits[bitidx++] = counter; if ((i>3) && (i%2 == 0)) { // shove each bit into the storage bytes data[j/8] <<= 1; if (counter > 200) data[j/8] |= 1; j++; } } #ifdef DEBUG for (int i=3; i<bitidx; i+=2) { printf("bit %d: %d\n", i-3, bits[i]); printf("bit %d: %d (%d)\n", i-2, bits[i+1], bits[i+1] > 200); } printf("Data (%d): 0x%x 0x%x 0x%x 0x%x 0x%x\n", j, data[0], data[1], data[2], data[3], data[4]); #endif if ((j >= 39) && (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) { // yay! float f, h; h = data[0] * 256 + data[1]; h /= 10; f = (data[2] & 0x7F)* 256 + data[3]; f /= 10.0; if (data[2] & 0x80) { f *= -1; } //printf("Temp = %.1f *C, Hum = %.1f \%\n", f, h); *humid0 = h; *temp0 = f; } return 0; } int cosmput(float humid, float temp, int *feedid, char *key, char *feed_name, char *field0_name, char *field1_name) { // CURL *curl; // CURLcode res; char xapikey[60]; sprintf(xapikey, "X-ApiKey: %s",key); char url[50]; sprintf(url, "http://api.cosm.com/v2/feeds/%d.json", *feedid); char payload[200]; sprintf(payload, "{\"title\":\"%s\",\"version\":\"1.0.0\",\"datastreams\":[{\"id\":\"%s\",\"current_value\":%0.1f},{\"id\":\"%s\",\"current_value\":%0.1f}]}", feed_name, field0_name, humid, field1_name, temp); // struct curl_slist *header=NULL; // header = curl_slist_append(header, xapikey); // curl_global_init(CURL_GLOBAL_ALL); // curl = curl_easy_init(); // // curl_easy_setopt(curl, CURLOPT_VERBOSE, 0); // curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header); // curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); // curl_easy_setopt(curl, CURLOPT_URL, url); // curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload); // // res = curl_easy_perform(curl); // if(res != CURLE_OK) { // fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); // } // // curl_easy_cleanup(curl); // curl_slist_free_all(header); // curl_global_cleanup(); return 0; } int readconfig(char *pFileName, int *feedid, char *key, char *feed_name, char *field0_name, char *field1_name) { char buffer[1024]; char label[120]; char value[100]; int allread = 0; FILE* fp; fp = fopen(pFileName, "r"); if (!fp) { printf("Error opening config_file %s!\n", pFileName); return 1; } printf("Opening config file: %s\n", pFileName); fflush(stdout); while (feof(fp) == 0) { fgets(buffer, 1024, fp); if ((buffer[0] != '#')) // && (no>2)) { if (sscanf(buffer, "%[^'=']=%[^'\n']%s", &label, &value) >= 2){ if (strcmp(label, "FEEDID") == 0) *feedid = atoi(value); if (strcmp(label, "KEY") == 0) sprintf(key, "%s", value); if (strcmp(label, "FEED_NAME") == 0) sprintf(feed_name, "%s", value); if (strcmp(label, "FIELD0_NAME") == 0) sprintf(field0_name, "%s", value); if (strcmp(label, "FIELD1_NAME") == 0) sprintf(field1_name, "%s", value); } } } fclose(fp); return 0; }
FreshXOpenSource/wallyd
extra/dht22.cpp
C++
gpl-3.0
6,241
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2008 University of California // // BOINC is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC. If not, see <http://www.gnu.org/licenses/>. // The BOINC API and runtime system. // // Notes: // 1) Thread structure: // Sequential apps // Unix // getting CPU time and suspend/resume have to be done // in the worker thread, so we use a SIGALRM signal handler. // However, many library functions and system calls // are not "asynch signal safe": see, e.g. // http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html#tag_02_04_03 // (e.g. sprintf() in a signal handler hangs Mac OS X) // so we do as little as possible in the signal handler, // and do the rest in a separate "timer thread". // Win // the timer thread does everything // Multi-thread apps: // Unix: // fork // original process runs timer loop: // handle suspend/resume/quit, heartbeat (use signals) // new process call boinc_init_options() with flags to // send status messages and handle checkpoint stuff, // and returns from boinc_init_parallel() // NOTE: THIS DOESN'T RESPECT CRITICAL SECTIONS. // NEED TO MASK SIGNALS IN CHILD DURING CRITICAL SECTIONS // Win: // like sequential case, except suspend/resume must enumerate // all threads (except timer) and suspend/resume them all // // 2) All variables that are accessed by two threads (i.e. worker and timer) // MUST be declared volatile. // // 3) For compatibility with C, we use int instead of bool various places // // 4) We must periodically check that the client is still alive and exit if not. // Originally this was done using heartbeat msgs from client. // This is unreliable, e.g. if the client is blocked for a long time. // As of Oct 11 2012 we use a different mechanism: // the client passes its PID and we periodically check whether it exists. // But we need to support the heartbeat mechanism also for compatibility. // // Terminology: // The processing of a result can be divided // into multiple "episodes" (executions of the app), // each of which resumes from the checkpointed state of the previous episode. // Unless otherwise noted, "CPU time" refers to the sum over all episodes // (not counting the part after the last checkpoint in an episode). #if defined(_WIN32) && !defined(__STDWX_H__) && !defined(_BOINC_WIN_) && !defined(_AFX_STDAFX_H_) #include "boinc_win.h" #endif #ifdef _WIN32 #include "version.h" #include "win_util.h" #else #include "config.h" #include <cstdlib> #include <cstring> #include <cstdio> #include <cstdarg> #include <sys/types.h> #include <errno.h> #include <unistd.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/wait.h> #include <pthread.h> #include <vector> #ifndef __EMX__ #include <sched.h> #endif #endif #include "app_ipc.h" #include "common_defs.h" #include "diagnostics.h" #include "error_numbers.h" #include "filesys.h" #include "mem_usage.h" #include "parse.h" #include "proc_control.h" #include "shmem.h" #include "str_replace.h" #include "str_util.h" #include "util.h" #include "boinc_api.h" using std::vector; //#define DEBUG_BOINC_API #ifdef __APPLE__ #include "mac_backtrace.h" #define GETRUSAGE_IN_TIMER_THREAD // call getrusage() in the timer thread, // rather than in the worker thread's signal handler // (which can cause crashes on Mac) // If you want, you can set this for Linux too: // CPPFLAGS=-DGETRUSAGE_IN_TIMER_THREAD #endif const char* api_version = "API_VERSION_" PACKAGE_VERSION; static APP_INIT_DATA aid; static FILE_LOCK file_lock; APP_CLIENT_SHM* app_client_shm = 0; static volatile int time_until_checkpoint; // time until enable checkpoint static volatile double fraction_done; static volatile double last_checkpoint_cpu_time; static volatile bool ready_to_checkpoint = false; static volatile int in_critical_section = 0; static volatile double last_wu_cpu_time; static volatile bool standalone = false; static volatile double initial_wu_cpu_time; static volatile bool have_new_trickle_up = false; static volatile bool have_trickle_down = true; // on first call, scan slot dir for msgs static volatile int heartbeat_giveup_count; // interrupt count value at which to give up on core client #ifdef _WIN32 static volatile int nrunning_ticks = 0; #endif static volatile int interrupt_count = 0; // number of timer interrupts // used to measure elapsed time in a way that's // not affected by user changing system clock, // and doesn't have big jump after hibernation static volatile int running_interrupt_count = 0; // number of timer interrupts while not suspended. // Used to compute elapsed time static volatile bool finishing; // used for worker/timer synch during boinc_finish(); static int want_network = 0; static int have_network = 1; static double bytes_sent = 0; static double bytes_received = 0; bool boinc_disable_timer_thread = false; // simulate unresponsive app by setting to true (debugging) static FUNC_PTR timer_callback = 0; char web_graphics_url[256]; bool send_web_graphics_url = false; char remote_desktop_addr[256]; bool send_remote_desktop_addr = false; int app_min_checkpoint_period = 0; // min checkpoint period requested by app #define TIMER_PERIOD 0.1 // Sleep interval for timer thread; // determines max rate of handling messages from client. // Unix: period of worker-thread timer interrupts. #define TIMERS_PER_SEC 10 // reciprocal of TIMER_PERIOD // This determines the resolution of fraction done and CPU time reporting // to the client, and of checkpoint enabling. #define HEARTBEAT_GIVEUP_SECS 30 #define HEARTBEAT_GIVEUP_COUNT ((int)(HEARTBEAT_GIVEUP_SECS/TIMER_PERIOD)) // quit if no heartbeat from core in this #interrupts #define LOCKFILE_TIMEOUT_PERIOD 35 // quit if we cannot aquire slot lock file in this #secs after startup #ifdef _WIN32 static HANDLE hSharedMem; HANDLE worker_thread_handle; // used to suspend worker thread, and to measure its CPU time DWORD timer_thread_id; #else static volatile bool worker_thread_exit_flag = false; static volatile int worker_thread_exit_status; // the above are used by the timer thread to tell // the worker thread to exit static pthread_t worker_thread_handle; static pthread_t timer_thread_handle; #ifndef GETRUSAGE_IN_TIMER_THREAD static struct rusage worker_thread_ru; #endif #endif static BOINC_OPTIONS options; volatile BOINC_STATUS boinc_status; // vars related to intermediate file upload struct UPLOAD_FILE_STATUS { std::string name; int status; }; static bool have_new_upload_file; static std::vector<UPLOAD_FILE_STATUS> upload_file_status; static int resume_activities(); static void boinc_exit(int); static void block_sigalrm(); static int start_worker_signals(); char* boinc_msg_prefix(char* sbuf, int len) { char buf[256]; struct tm tm; struct tm *tmp = &tm; int n; time_t x = time(0); if (x == -1) { strlcpy(sbuf, "time() failed", len); return sbuf; } #ifdef _WIN32 #ifdef __MINGW32__ if ((tmp = localtime(&x)) == NULL) { #else if (localtime_s(&tm, &x) == EINVAL) { #endif #else if (localtime_r(&x, &tm) == NULL) { #endif strlcpy(sbuf, "localtime() failed", len); return sbuf; } if (strftime(buf, sizeof(buf)-1, "%H:%M:%S", tmp) == 0) { strlcpy(sbuf, "strftime() failed", len); return sbuf; } #ifdef _WIN32 n = _snprintf(sbuf, len, "%s (%d):", buf, GetCurrentProcessId()); #else n = snprintf(sbuf, len, "%s (%d):", buf, getpid()); #endif if (n < 0) { strlcpy(sbuf, "sprintf() failed", len); return sbuf; } sbuf[len-1] = 0; // just in case return sbuf; } static int setup_shared_mem() { char buf[256]; if (standalone) { fprintf(stderr, "%s Standalone mode, so not using shared memory.\n", boinc_msg_prefix(buf, sizeof(buf)) ); return 0; } app_client_shm = new APP_CLIENT_SHM; #ifdef _WIN32 sprintf(buf, "%s%s", SHM_PREFIX, aid.shmem_seg_name); hSharedMem = attach_shmem(buf, (void**)&app_client_shm->shm); if (hSharedMem == NULL) { delete app_client_shm; app_client_shm = NULL; } #else #ifdef __EMX__ if (attach_shmem(aid.shmem_seg_name, (void**)&app_client_shm->shm)) { delete app_client_shm; app_client_shm = NULL; } #else if (aid.shmem_seg_name == -1) { // Version 6 Unix/Linux/Mac client if (attach_shmem_mmap(MMAPPED_FILE_NAME, (void**)&app_client_shm->shm)) { delete app_client_shm; app_client_shm = NULL; } } else { // version 5 Unix/Linux/Mac client if (attach_shmem(aid.shmem_seg_name, (void**)&app_client_shm->shm)) { delete app_client_shm; app_client_shm = NULL; } } #endif #endif // ! _WIN32 if (app_client_shm == NULL) return -1; return 0; } // a mutex for data structures shared between time and worker threads // #ifdef _WIN32 static HANDLE mutex; static void init_mutex() { mutex = CreateMutex(NULL, FALSE, NULL); } static inline void acquire_mutex() { WaitForSingleObject(mutex, INFINITE); } static inline void release_mutex() { ReleaseMutex(mutex); } #else pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static void init_mutex() {} static inline void acquire_mutex() { #ifdef DEBUG_BOINC_API char buf[256]; fprintf(stderr, "%s acquiring mutex\n", boinc_msg_prefix(buf, sizeof(buf)) ); #endif pthread_mutex_lock(&mutex); } static inline void release_mutex() { #ifdef DEBUG_BOINC_API char buf[256]; fprintf(stderr, "%s releasing mutex\n", boinc_msg_prefix(buf, sizeof(buf)) ); #endif pthread_mutex_unlock(&mutex); } #endif // Return CPU time of process. // double boinc_worker_thread_cpu_time() { double cpu; #ifdef _WIN32 int retval; retval = boinc_process_cpu_time(GetCurrentProcess(), cpu); if (retval) { cpu = nrunning_ticks * TIMER_PERIOD; // for Win9x } #else #ifdef GETRUSAGE_IN_TIMER_THREAD struct rusage worker_thread_ru; getrusage(RUSAGE_SELF, &worker_thread_ru); #endif cpu = (double)worker_thread_ru.ru_utime.tv_sec + (((double)worker_thread_ru.ru_utime.tv_usec)/1000000.0); cpu += (double)worker_thread_ru.ru_stime.tv_sec + (((double)worker_thread_ru.ru_stime.tv_usec)/1000000.0); #endif return cpu; } // Communicate to the core client (via shared mem) // the current CPU time and fraction done. // NOTE: various bugs could cause some of these FP numbers to be enormous, // possibly overflowing the buffer. // So use strlcat() instead of strcat() // // This is called only from the timer thread (so no need for synch) // static bool update_app_progress(double cpu_t, double cp_cpu_t) { char msg_buf[MSG_CHANNEL_SIZE], buf[256]; if (standalone) return true; sprintf(msg_buf, "<current_cpu_time>%e</current_cpu_time>\n" "<checkpoint_cpu_time>%e</checkpoint_cpu_time>\n", cpu_t, cp_cpu_t ); if (want_network) { strlcat(msg_buf, "<want_network>1</want_network>\n", sizeof(msg_buf)); } if (fraction_done >= 0) { double range = aid.fraction_done_end - aid.fraction_done_start; double fdone = aid.fraction_done_start + fraction_done*range; sprintf(buf, "<fraction_done>%e</fraction_done>\n", fdone); strlcat(msg_buf, buf, sizeof(msg_buf)); } if (bytes_sent) { sprintf(buf, "<bytes_sent>%f</bytes_sent>\n", bytes_sent); strlcat(msg_buf, buf, sizeof(msg_buf)); } if (bytes_received) { sprintf(buf, "<bytes_received>%f</bytes_received>\n", bytes_received); strlcat(msg_buf, buf, sizeof(msg_buf)); } return app_client_shm->shm->app_status.send_msg(msg_buf); } static void handle_heartbeat_msg() { char buf[MSG_CHANNEL_SIZE]; double dtemp; bool btemp; if (app_client_shm->shm->heartbeat.get_msg(buf)) { boinc_status.network_suspended = false; if (match_tag(buf, "<heartbeat/>")) { heartbeat_giveup_count = interrupt_count + HEARTBEAT_GIVEUP_COUNT; } if (parse_double(buf, "<wss>", dtemp)) { boinc_status.working_set_size = dtemp; } if (parse_double(buf, "<max_wss>", dtemp)) { boinc_status.max_working_set_size = dtemp; } if (parse_bool(buf, "suspend_network", btemp)) { boinc_status.network_suspended = btemp; } } } static bool client_dead() { char buf[256]; bool dead; if (aid.client_pid) { // check every 10 sec // if (interrupt_count%(TIMERS_PER_SEC*10)) return false; #ifdef _WIN32 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, aid.client_pid); // If the process exists but is running under a different user account (boinc_master) // then the handle returned is NULL and GetLastError() returns ERROR_ACCESS_DENIED. // if ((h == NULL) && (GetLastError() != ERROR_ACCESS_DENIED)) { dead = true; } else { if (h) CloseHandle(h); dead = false; } #else int retval = kill(aid.client_pid, 0); dead = (retval == -1 && errno == ESRCH); #endif } else { dead = (interrupt_count > heartbeat_giveup_count); } if (dead) { boinc_msg_prefix(buf, sizeof(buf)); fputs(buf, stderr); // don't use fprintf() here if (aid.client_pid) { fputs(" BOINC client no longer exists - exiting\n", stderr); } else { fputs(" No heartbeat from client for 30 sec - exiting\n", stderr); } return true; } return false; } #ifndef _WIN32 // For multithread apps on Unix, the main process executes the following. // static void parallel_master(int child_pid) { char buf[MSG_CHANNEL_SIZE]; int exit_status; while (1) { boinc_sleep(TIMER_PERIOD); interrupt_count++; if (app_client_shm) { handle_heartbeat_msg(); if (app_client_shm->shm->process_control_request.get_msg(buf)) { if (match_tag(buf, "<suspend/>")) { kill(child_pid, SIGSTOP); } else if (match_tag(buf, "<resume/>")) { kill(child_pid, SIGCONT); } else if (match_tag(buf, "<quit/>")) { kill(child_pid, SIGKILL); exit(0); } else if (match_tag(buf, "<abort/>")) { kill(child_pid, SIGKILL); exit(EXIT_ABORTED_BY_CLIENT); } } if (client_dead()) { kill(child_pid, SIGKILL); exit(0); } } if (interrupt_count % TIMERS_PER_SEC) continue; if (waitpid(child_pid, &exit_status, WNOHANG) == child_pid) break; } boinc_finish(exit_status); } #endif int boinc_init() { int retval; if (!diagnostics_is_initialized()) { retval = boinc_init_diagnostics(BOINC_DIAG_DEFAULTS); if (retval) return retval; } boinc_options_defaults(options); return boinc_init_options(&options); } int boinc_init_options(BOINC_OPTIONS* opt) { int retval; #ifndef _WIN32 if (options.multi_thread) { int child_pid = fork(); if (child_pid) { // original process - master // options.send_status_msgs = false; retval = boinc_init_options_general(options); if (retval) { kill(child_pid, SIGKILL); return retval; } parallel_master(child_pid); } // new process - slave // options.main_program = false; options.check_heartbeat = false; options.handle_process_control = false; options.multi_thread = false; options.multi_process = false; return boinc_init_options(&options); } #endif retval = boinc_init_options_general(*opt); if (retval) return retval; retval = start_timer_thread(); if (retval) return retval; #ifndef _WIN32 retval = start_worker_signals(); if (retval) return retval; #endif return 0; } int boinc_init_parallel() { BOINC_OPTIONS _options; boinc_options_defaults(_options); _options.multi_thread = true; return boinc_init_options(&_options); } static int min_checkpoint_period() { int x = (int)aid.checkpoint_period; if (app_min_checkpoint_period > x) { x = app_min_checkpoint_period; } if (x == 0) x = DEFAULT_CHECKPOINT_PERIOD; return x; } int boinc_set_min_checkpoint_period(int x) { app_min_checkpoint_period = x; if (x > time_until_checkpoint) { time_until_checkpoint = x; } return 0; } int boinc_init_options_general(BOINC_OPTIONS& opt) { int retval; char buf[256]; options = opt; if (!diagnostics_is_initialized()) { retval = boinc_init_diagnostics(BOINC_DIAG_DEFAULTS); if (retval) return retval; } boinc_status.no_heartbeat = false; boinc_status.suspended = false; boinc_status.quit_request = false; boinc_status.abort_request = false; if (options.main_program) { // make sure we're the only app running in this slot // retval = file_lock.lock(LOCKFILE); if (retval) { // give any previous occupant a chance to timeout and exit // fprintf(stderr, "%s Can't acquire lockfile (%d) - waiting %ds\n", boinc_msg_prefix(buf, sizeof(buf)), retval, LOCKFILE_TIMEOUT_PERIOD ); boinc_sleep(LOCKFILE_TIMEOUT_PERIOD); retval = file_lock.lock(LOCKFILE); } if (retval) { fprintf(stderr, "%s Can't acquire lockfile (%d) - exiting\n", boinc_msg_prefix(buf, sizeof(buf)), retval ); #ifdef _WIN32 char buf2[256]; windows_format_error_string(GetLastError(), buf2, 256); fprintf(stderr, "%s Error: %s\n", boinc_msg_prefix(buf, sizeof(buf)), buf2); #endif // if we can't acquire the lock file there must be // another app instance running in this slot. // If we exit(0), the client will keep restarting us. // Instead, tell the client not to restart us for 10 min. // boinc_temporary_exit(600, "Waiting to acquire lock"); } } retval = boinc_parse_init_data_file(); if (retval) { standalone = true; } else { retval = setup_shared_mem(); if (retval) { fprintf(stderr, "%s Can't set up shared mem: %d. Will run in standalone mode.\n", boinc_msg_prefix(buf, sizeof(buf)), retval ); standalone = true; } } // copy the WU CPU time to a separate var, // since we may reread the structure again later. // initial_wu_cpu_time = aid.wu_cpu_time; fraction_done = -1; time_until_checkpoint = min_checkpoint_period(); last_checkpoint_cpu_time = aid.wu_cpu_time; last_wu_cpu_time = aid.wu_cpu_time; if (standalone) { options.check_heartbeat = false; } heartbeat_giveup_count = interrupt_count + HEARTBEAT_GIVEUP_COUNT; init_mutex(); return 0; } int boinc_get_status(BOINC_STATUS *s) { s->no_heartbeat = boinc_status.no_heartbeat; s->suspended = boinc_status.suspended; s->quit_request = boinc_status.quit_request; s->reread_init_data_file = boinc_status.reread_init_data_file; s->abort_request = boinc_status.abort_request; s->working_set_size = boinc_status.working_set_size; s->max_working_set_size = boinc_status.max_working_set_size; s->network_suspended = boinc_status.network_suspended; return 0; } // if we have any new trickle-ups or file upload requests, // send a message describing them // static void send_trickle_up_msg() { char buf[MSG_CHANNEL_SIZE]; BOINCINFO("Sending Trickle Up Message"); if (standalone) return; strcpy(buf, ""); if (have_new_trickle_up) { strcat(buf, "<have_new_trickle_up/>\n"); } if (have_new_upload_file) { strcat(buf, "<have_new_upload_file/>\n"); } if (strlen(buf)) { if (app_client_shm->shm->trickle_up.send_msg(buf)) { have_new_trickle_up = false; have_new_upload_file = false; } } } // NOTE: a non-zero status tells the core client that we're exiting with // an "unrecoverable error", which will be reported back to server. // A zero exit-status tells the client we've successfully finished the result. // int boinc_finish(int status) { char buf[256]; fraction_done = 1; fprintf(stderr, "%s called boinc_finish(%d)\n", boinc_msg_prefix(buf, sizeof(buf)), status ); finishing = true; boinc_sleep(2.0); // let the timer thread send final messages boinc_disable_timer_thread = true; // then disable it if (options.main_program && status==0) { FILE* f = fopen(BOINC_FINISH_CALLED_FILE, "w"); if (f) fclose(f); } boinc_exit(status); return 0; // never reached } int boinc_temporary_exit(int delay, const char* reason) { FILE* f = fopen(TEMPORARY_EXIT_FILE, "w"); if (!f) { return ERR_FOPEN; } fprintf(f, "%d\n", delay); if (reason) { fprintf(f, "%s\n", reason); } fclose(f); boinc_exit(0); return 0; } // unlock the lockfile and call the appropriate exit function // Unix: called only from the worker thread. // Win: called from the worker or timer thread. // // make static eventually // void boinc_exit(int status) { int retval; char buf[256]; if (options.main_program && file_lock.locked) { retval = file_lock.unlock(LOCKFILE); if (retval) { #ifdef _WIN32 windows_format_error_string(GetLastError(), buf, 256); fprintf(stderr, "%s Can't unlock lockfile (%d): %s\n", boinc_msg_prefix(buf, sizeof(buf)), retval, buf ); #else fprintf(stderr, "%s Can't unlock lockfile (%d)\n", boinc_msg_prefix(buf, sizeof(buf)), retval ); perror("file unlock failed"); #endif } } // kill any processes the app may have created // if (options.multi_process) { kill_descendants(); } boinc_finish_diag(); // various platforms have problems shutting down a process // while other threads are still executing, // or triggering endless exit()/atexit() loops. // BOINCINFO("Exit Status: %d", status); fflush(NULL); #if defined(_WIN32) // Halt all the threads and clean up. TerminateProcess(GetCurrentProcess(), status); // note: the above CAN return! Sleep(1000); DebugBreak(); #elif defined(__APPLE_CC__) // stops endless exit()/atexit() loops. _exit(status); #else // arrange to exit with given status even if errors happen // in atexit() functions // set_signal_exit_code(status); exit(status); #endif } void boinc_network_usage(double sent, double received) { bytes_sent = sent; bytes_received = received; } int boinc_is_standalone() { if (standalone) return 1; return 0; } static void exit_from_timer_thread(int status) { #ifdef DEBUG_BOINC_API char buf[256]; fprintf(stderr, "%s exit_from_timer_thread(%d) called\n", boinc_msg_prefix(buf, sizeof(buf)), status ); #endif #ifdef _WIN32 // TerminateProcess() doesn't work if there are suspended threads? if (boinc_status.suspended) { resume_activities(); } // this seems to work OK on Windows // boinc_exit(status); #else // but on Unix there are synchronization problems; // set a flag telling the worker thread to exit // worker_thread_exit_status = status; worker_thread_exit_flag = true; pthread_exit(NULL); #endif } // parse the init data file. // This is done at startup, and also if a "reread prefs" message is received // int boinc_parse_init_data_file() { FILE* f; int retval; char buf[256]; if (aid.project_preferences) { free(aid.project_preferences); aid.project_preferences = NULL; } aid.clear(); aid.checkpoint_period = DEFAULT_CHECKPOINT_PERIOD; if (!boinc_file_exists(INIT_DATA_FILE)) { fprintf(stderr, "%s Can't open init data file - running in standalone mode\n", boinc_msg_prefix(buf, sizeof(buf)) ); return ERR_FOPEN; } f = boinc_fopen(INIT_DATA_FILE, "r"); retval = parse_init_data_file(f, aid); fclose(f); if (retval) { fprintf(stderr, "%s Can't parse init data file - running in standalone mode\n", boinc_msg_prefix(buf, sizeof(buf)) ); return retval; } return 0; } int boinc_report_app_status_aux( double cpu_time, double checkpoint_cpu_time, double _fraction_done, int other_pid, double _bytes_sent, double _bytes_received ) { char msg_buf[MSG_CHANNEL_SIZE], buf[1024]; if (standalone) return 0; sprintf(msg_buf, "<current_cpu_time>%e</current_cpu_time>\n" "<checkpoint_cpu_time>%e</checkpoint_cpu_time>\n" "<fraction_done>%e</fraction_done>\n", cpu_time, checkpoint_cpu_time, _fraction_done ); if (other_pid) { sprintf(buf, "<other_pid>%d</other_pid>\n", other_pid); strcat(msg_buf, buf); } if (_bytes_sent) { sprintf(buf, "<bytes_sent>%f</bytes_sent>\n", _bytes_sent); strcat(msg_buf, buf); } if (_bytes_received) { sprintf(buf, "<bytes_received>%f</bytes_received>\n", _bytes_received); strcat(msg_buf, buf); } if (app_client_shm->shm->app_status.send_msg(msg_buf)) { return 0; } return ERR_WRITE; } int boinc_report_app_status( double cpu_time, double checkpoint_cpu_time, double _fraction_done ){ return boinc_report_app_status_aux( cpu_time, checkpoint_cpu_time, _fraction_done, 0, 0, 0 ); } int boinc_get_init_data_p(APP_INIT_DATA* app_init_data) { *app_init_data = aid; return 0; } int boinc_get_init_data(APP_INIT_DATA& app_init_data) { app_init_data = aid; return 0; } int boinc_wu_cpu_time(double& cpu_t) { cpu_t = last_wu_cpu_time; return 0; } // Suspend this job. // Can be called from either timer or worker thread. // static int suspend_activities(bool called_from_worker) { #ifdef DEBUG_BOINC_API char log_buf[256]; fprintf(stderr, "%s suspend_activities() called from %s\n", boinc_msg_prefix(log_buf, sizeof(log_buf)), called_from_worker?"worker thread":"timer thread" ); #endif #ifdef _WIN32 static vector<int> pids; if (options.multi_thread) { if (pids.size() == 0) { pids.push_back(GetCurrentProcessId()); } suspend_or_resume_threads(pids, timer_thread_id, false, true); } else { SuspendThread(worker_thread_handle); } #else if (options.multi_process) { suspend_or_resume_descendants(false); } // if called from worker thread, sleep until suspension is over // if called from time thread, don't need to do anything; // suspension is done by signal handler in worker thread // if (called_from_worker) { while (boinc_status.suspended) { sleep(1); } } #endif return 0; } int resume_activities() { #ifdef DEBUG_BOINC_API char log_buf[256]; fprintf(stderr, "%s resume_activities()\n", boinc_msg_prefix(log_buf, sizeof(log_buf)) ); #endif #ifdef _WIN32 static vector<int> pids; if (options.multi_thread) { if (pids.size() == 0) pids.push_back(GetCurrentProcessId()); suspend_or_resume_threads(pids, timer_thread_id, true, true); } else { ResumeThread(worker_thread_handle); } #else if (options.multi_process) { suspend_or_resume_descendants(true); } #endif return 0; } static void handle_upload_file_status() { char path[MAXPATHLEN], buf[256], log_name[256], *p, log_buf[256]; std::string filename; int status; relative_to_absolute("", path); DirScanner dirscan(path); while (dirscan.scan(filename)) { strlcpy(buf, filename.c_str(), sizeof(buf)); if (strstr(buf, UPLOAD_FILE_STATUS_PREFIX) != buf) continue; strlcpy(log_name, buf+strlen(UPLOAD_FILE_STATUS_PREFIX), sizeof(log_name)); FILE* f = boinc_fopen(filename.c_str(), "r"); if (!f) { fprintf(stderr, "%s handle_file_upload_status: can't open %s\n", boinc_msg_prefix(buf, sizeof(buf)), filename.c_str() ); continue; } p = fgets(buf, sizeof(buf), f); fclose(f); if (p && parse_int(buf, "<status>", status)) { UPLOAD_FILE_STATUS uf; uf.name = std::string(log_name); uf.status = status; upload_file_status.push_back(uf); } else { fprintf(stderr, "%s handle_upload_file_status: can't parse %s\n", boinc_msg_prefix(log_buf, sizeof(log_buf)), buf ); } } } // handle trickle and file upload messages // static void handle_trickle_down_msg() { char buf[MSG_CHANNEL_SIZE]; if (app_client_shm->shm->trickle_down.get_msg(buf)) { BOINCINFO("Received Trickle Down Message"); if (match_tag(buf, "<have_trickle_down/>")) { have_trickle_down = true; } if (match_tag(buf, "<upload_file_status/>")) { handle_upload_file_status(); } } } // This flag is set of we get a suspend request while in a critical section, // and options.direct_process_action is set. // As soon as we're not in the critical section we'll do the suspend. // static bool suspend_request = false; // runs in timer thread // static void handle_process_control_msg() { char buf[MSG_CHANNEL_SIZE]; if (app_client_shm->shm->process_control_request.get_msg(buf)) { acquire_mutex(); #ifdef DEBUG_BOINC_API char log_buf[256]; fprintf(stderr, "%s got process control msg %s\n", boinc_msg_prefix(log_buf, sizeof(log_buf)), buf ); #endif if (match_tag(buf, "<suspend/>")) { BOINCINFO("Received suspend message"); if (options.direct_process_action) { if (in_critical_section) { suspend_request = true; } else { boinc_status.suspended = true; suspend_request = false; suspend_activities(false); } } else { boinc_status.suspended = true; } } if (match_tag(buf, "<resume/>")) { BOINCINFO("Received resume message"); if (options.direct_process_action) { if (boinc_status.suspended) { resume_activities(); } else if (suspend_request) { suspend_request = false; } } boinc_status.suspended = false; } if (boinc_status.quit_request || match_tag(buf, "<quit/>")) { BOINCINFO("Received quit message"); boinc_status.quit_request = true; if (!in_critical_section && options.direct_process_action) { exit_from_timer_thread(0); } } if (boinc_status.abort_request || match_tag(buf, "<abort/>")) { BOINCINFO("Received abort message"); boinc_status.abort_request = true; if (!in_critical_section && options.direct_process_action) { diagnostics_set_aborted_via_gui(); #if defined(_WIN32) // Cause a controlled assert and dump the callstacks. DebugBreak(); #elif defined(__APPLE__) PrintBacktrace(); #endif release_mutex(); exit_from_timer_thread(EXIT_ABORTED_BY_CLIENT); } } if (match_tag(buf, "<reread_app_info/>")) { boinc_status.reread_init_data_file = true; } if (match_tag(buf, "<network_available/>")) { have_network = 1; } release_mutex(); } } // timer handler; runs in the timer thread // static void timer_handler() { char buf[512]; #ifdef DEBUG_BOINC_API fprintf(stderr, "%s timer handler: disabled %s; in critical section %s; finishing %s\n", boinc_msg_prefix(buf, sizeof(buf)), boinc_disable_timer_thread?"yes":"no", in_critical_section?"yes":"no", finishing?"yes":"no" ); #endif if (boinc_disable_timer_thread) { return; } if (finishing) { if (options.send_status_msgs) { double cur_cpu = boinc_worker_thread_cpu_time(); last_wu_cpu_time = cur_cpu + initial_wu_cpu_time; update_app_progress(last_wu_cpu_time, last_checkpoint_cpu_time); } boinc_disable_timer_thread = true; return; } interrupt_count++; if (!boinc_status.suspended) { running_interrupt_count++; } // handle messages from the core client // if (app_client_shm) { if (options.check_heartbeat) { handle_heartbeat_msg(); } if (options.handle_trickle_downs) { handle_trickle_down_msg(); } if (options.handle_process_control) { handle_process_control_msg(); } } if (interrupt_count % TIMERS_PER_SEC) return; #ifdef DEBUG_BOINC_API fprintf(stderr, "%s 1 sec elapsed - doing slow actions\n", boinc_msg_prefix(buf, sizeof(buf))); #endif // here if we're at a one-second boundary; do slow stuff // if (!ready_to_checkpoint) { time_until_checkpoint -= 1; if (time_until_checkpoint <= 0) { ready_to_checkpoint = true; } } // see if the core client has died, which means we need to die too // (unless we're in a critical section) // if (in_critical_section==0 && options.check_heartbeat) { if (client_dead()) { fprintf(stderr, "%s timer handler: client dead, exiting\n", boinc_msg_prefix(buf, sizeof(buf)) ); if (options.direct_process_action) { exit_from_timer_thread(0); } else { boinc_status.no_heartbeat = true; } } } // don't bother reporting CPU time etc. if we're suspended // if (options.send_status_msgs && !boinc_status.suspended) { double cur_cpu = boinc_worker_thread_cpu_time(); last_wu_cpu_time = cur_cpu + initial_wu_cpu_time; update_app_progress(last_wu_cpu_time, last_checkpoint_cpu_time); } if (options.handle_trickle_ups) { send_trickle_up_msg(); } if (timer_callback) { timer_callback(); } // send graphics-related messages // if (send_web_graphics_url && !app_client_shm->shm->graphics_reply.has_msg()) { sprintf(buf, "<web_graphics_url>%s</web_graphics_url>", web_graphics_url ); app_client_shm->shm->graphics_reply.send_msg(buf); send_web_graphics_url = false; } if (send_remote_desktop_addr && !app_client_shm->shm->graphics_reply.has_msg()) { sprintf(buf, "<remote_desktop_addr>%s</remote_desktop_addr>", remote_desktop_addr ); app_client_shm->shm->graphics_reply.send_msg(buf); send_remote_desktop_addr = false; } } #ifdef _WIN32 DWORD WINAPI timer_thread(void *) { while (1) { Sleep((int)(TIMER_PERIOD*1000)); timer_handler(); // poor man's CPU time accounting for Win9x // if (!boinc_status.suspended) { nrunning_ticks++; } } return 0; } #else static void* timer_thread(void*) { block_sigalrm(); while(1) { boinc_sleep(TIMER_PERIOD); timer_handler(); } return 0; } // This SIGALRM handler gets handled only by the worker thread. // It gets CPU time and implements sleeping. // It must call only signal-safe functions, and must not do FP math // static void worker_signal_handler(int) { #ifndef GETRUSAGE_IN_TIMER_THREAD getrusage(RUSAGE_SELF, &worker_thread_ru); #endif if (worker_thread_exit_flag) { boinc_exit(worker_thread_exit_status); } if (options.direct_process_action) { while (boinc_status.suspended && in_critical_section==0) { #ifdef ANDROID // per-thread signal masking doesn't work // on old (pre-4.1) versions of Android. // If we're handling this signal in the timer thread, // send signal explicitly to worker thread. // if (pthread_self() == timer_thread_handle) { pthread_kill(worker_thread_handle, SIGALRM); return; } #endif sleep(1); // don't use boinc_sleep() because it does FP math } } } #endif // Called from the worker thread; create the timer thread // int start_timer_thread() { char buf[256]; #ifdef _WIN32 // get the worker thread handle // DuplicateHandle( GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &worker_thread_handle, 0, FALSE, DUPLICATE_SAME_ACCESS ); // Create the timer thread // if (!CreateThread(NULL, 0, timer_thread, 0, 0, &timer_thread_id)) { fprintf(stderr, "%s start_timer_thread(): CreateThread() failed, errno %d\n", boinc_msg_prefix(buf, sizeof(buf)), errno ); return errno; } if (!options.normal_thread_priority) { // lower our (worker thread) priority // SetThreadPriority(worker_thread_handle, THREAD_PRIORITY_IDLE); } #else worker_thread_handle = pthread_self(); pthread_attr_t thread_attrs; pthread_attr_init(&thread_attrs); pthread_attr_setstacksize(&thread_attrs, 32768); int retval = pthread_create(&timer_thread_handle, &thread_attrs, timer_thread, NULL); if (retval) { fprintf(stderr, "%s start_timer_thread(): pthread_create(): %d", boinc_msg_prefix(buf, sizeof(buf)), retval ); return retval; } #endif return 0; } #ifndef _WIN32 // set up a periodic SIGALRM, to be handled by the worker thread // static int start_worker_signals() { int retval; struct sigaction sa; itimerval value; sa.sa_handler = worker_signal_handler; sa.sa_flags = SA_RESTART; sigemptyset(&sa.sa_mask); retval = sigaction(SIGALRM, &sa, NULL); if (retval) { perror("boinc start_timer_thread() sigaction"); return retval; } value.it_value.tv_sec = 0; value.it_value.tv_usec = (int)(TIMER_PERIOD*1e6); value.it_interval = value.it_value; retval = setitimer(ITIMER_REAL, &value, NULL); if (retval) { perror("boinc start_timer_thread() setitimer"); return retval; } return 0; } #endif int boinc_send_trickle_up(char* variety, char* p) { if (!options.handle_trickle_ups) return ERR_NO_OPTION; FILE* f = boinc_fopen(TRICKLE_UP_FILENAME, "wb"); if (!f) return ERR_FOPEN; fprintf(f, "<variety>%s</variety>\n", variety); size_t n = fwrite(p, strlen(p), 1, f); fclose(f); if (n != 1) return ERR_WRITE; have_new_trickle_up = true; return 0; } int boinc_time_to_checkpoint() { if (ready_to_checkpoint) { boinc_begin_critical_section(); return 1; } return 0; } int boinc_checkpoint_completed() { double cur_cpu; cur_cpu = boinc_worker_thread_cpu_time(); last_wu_cpu_time = cur_cpu + aid.wu_cpu_time; last_checkpoint_cpu_time = last_wu_cpu_time; time_until_checkpoint = min_checkpoint_period(); boinc_end_critical_section(); ready_to_checkpoint = false; return 0; } void boinc_begin_critical_section() { #ifdef DEBUG_BOINC_API char buf[256]; fprintf(stderr, "%s begin_critical_section\n", boinc_msg_prefix(buf, sizeof(buf)) ); #endif in_critical_section++; } void boinc_end_critical_section() { #ifdef DEBUG_BOINC_API char buf[256]; fprintf(stderr, "%s end_critical_section\n", boinc_msg_prefix(buf, sizeof(buf)) ); #endif in_critical_section--; if (in_critical_section < 0) { in_critical_section = 0; // just in case } if (in_critical_section) return; // We're out of the critical section. // See if we got suspend/quit/abort while in critical section, // and handle them here. // if (boinc_status.quit_request) { boinc_exit(0); } if (boinc_status.abort_request) { boinc_exit(EXIT_ABORTED_BY_CLIENT); } if (options.direct_process_action) { acquire_mutex(); if (suspend_request) { suspend_request = false; boinc_status.suspended = true; release_mutex(); suspend_activities(true); } else { release_mutex(); } } } int boinc_fraction_done(double x) { fraction_done = x; return 0; } int boinc_receive_trickle_down(char* buf, int len) { std::string filename; char path[MAXPATHLEN]; if (!options.handle_trickle_downs) return false; if (have_trickle_down) { relative_to_absolute("", path); DirScanner dirscan(path); while (dirscan.scan(filename)) { if (strstr(filename.c_str(), "trickle_down")) { strncpy(buf, filename.c_str(), len); return true; } } have_trickle_down = false; } return false; } int boinc_upload_file(std::string& name) { char buf[256]; std::string pname; int retval; retval = boinc_resolve_filename_s(name.c_str(), pname); if (retval) return retval; sprintf(buf, "%s%s", UPLOAD_FILE_REQ_PREFIX, name.c_str()); FILE* f = boinc_fopen(buf, "w"); if (!f) return ERR_FOPEN; have_new_upload_file = true; fclose(f); return 0; } int boinc_upload_status(std::string& name) { for (unsigned int i=0; i<upload_file_status.size(); i++) { UPLOAD_FILE_STATUS& ufs = upload_file_status[i]; if (ufs.name == name) { return ufs.status; } } return ERR_NOT_FOUND; } void boinc_need_network() { want_network = 1; have_network = 0; } int boinc_network_poll() { return have_network?0:1; } void boinc_network_done() { want_network = 0; } #ifndef _WIN32 // block SIGALRM, so that the worker thread will be forced to handle it // static void block_sigalrm() { sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGALRM); pthread_sigmask(SIG_BLOCK, &mask, NULL); } #endif void boinc_register_timer_callback(FUNC_PTR p) { timer_callback = p; } double boinc_get_fraction_done() { return fraction_done; } double boinc_elapsed_time() { return running_interrupt_count*TIMER_PERIOD; } void boinc_web_graphics_url(char* url) { if (standalone) return; strlcpy(web_graphics_url, url, sizeof(web_graphics_url)); send_web_graphics_url = true; } void boinc_remote_desktop_addr(char* addr) { if (standalone) return; strlcpy(remote_desktop_addr, addr, sizeof(remote_desktop_addr)); send_remote_desktop_addr = true; }
hanxue/Boinc
api/boinc_api.cpp
C++
gpl-3.0
44,618
/* * BufferAllocator.java February 2001 * * Copyright (C) 2001, Niall Gallagher <niallg@users.sf.net> * * 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. */ package org.simpleframework.util.buffer; import java.io.IOException; import java.io.InputStream; /** * The <code>BufferAllocator</code> object is used to provide a means to * allocate buffers using a single underlying buffer. This uses a buffer from a * existing allocator to create the region of memory to use to allocate all * other buffers. As a result this allows a single buffer to acquire the bytes * in a number of associated buffers. This has the advantage of allowing bytes * to be read in sequence without joining data from other buffers or allocating * multiple regions. * * @author Niall Gallagher */ public class BufferAllocator extends FilterAllocator implements Buffer { /** * This is the underlying buffer all other buffers are within. */ private Buffer buffer; /** * Constructor for the <code>BufferAllocator</code> object. This is used to * instantiate the allocator with a default buffer size of half a kilobyte. * This ensures that it can be used for general purpose byte storage and for * minor I/O tasks. * * @param source * this is where the underlying buffer is allocated */ public BufferAllocator(Allocator source) { super(source); } /** * Constructor for the <code>BufferAllocator</code> object. This is used to * instantiate the allocator with a specified buffer size. This is typically * used when a very specific buffer capacity is required, for example a * request body with a known length. * * @param source * this is where the underlying buffer is allocated * @param capacity * the initial capacity of the allocated buffers */ public BufferAllocator(Allocator source, long capacity) { super(source, capacity); } /** * Constructor for the <code>BufferAllocator</code> object. This is used to * instantiate the allocator with a specified buffer size. This is typically * used when a very specific buffer capacity is required, for example a * request body with a known length. * * @param source * this is where the underlying buffer is allocated * @param capacity * the initial capacity of the allocated buffers * @param limit * this is the maximum buffer size created by this */ public BufferAllocator(Allocator source, long capacity, long limit) { super(source, capacity, limit); } /** * This method is used so that a buffer can be represented as a stream of * bytes. This provides a quick means to access the data that has been * written to the buffer. It wraps the buffer within an input stream so that * it can be read directly. * * @return a stream that can be used to read the buffered bytes */ @Override public InputStream getInputStream() throws IOException { if (this.buffer == null) { this.allocate(); } return this.buffer.getInputStream(); } /** * This method is used to acquire the buffered bytes as a string. This is * useful if the contents need to be manipulated as a string or transferred * into another encoding. If the UTF-8 content encoding is not supported the * platform default is used, however this is unlikely as UTF-8 should be * supported. * * @return this returns a UTF-8 encoding of the buffer contents */ @Override public String encode() throws IOException { if (this.buffer == null) { this.allocate(); } return this.buffer.encode(); } /** * This method is used to acquire the buffered bytes as a string. This is * useful if the contents need to be manipulated as a string or transferred * into another encoding. This will convert the bytes using the specified * character encoding format. * * @return this returns the encoding of the buffer contents */ @Override public String encode(String charset) throws IOException { if (this.buffer == null) { this.allocate(); } return this.buffer.encode(charset); } /** * This method is used to append bytes to the end of the buffer. This will * expand the capacity of the buffer if there is not enough space to * accommodate the extra bytes. * * @param array * this is the byte array to append to this buffer * * @return this returns this buffer for another operation */ @Override public Buffer append(byte[] array) throws IOException { return this.append(array, 0, array.length); } /** * This method is used to append bytes to the end of the buffer. This will * expand the capacity of the buffer if there is not enough space to * accommodate the extra bytes. * * @param array * this is the byte array to append to this buffer * @param size * the number of bytes to be read from the array * @param off * this is the offset to begin reading the bytes from * * @return this returns this buffer for another operation */ @Override public Buffer append(byte[] array, int off, int size) throws IOException { if (this.buffer == null) { this.allocate(size); } return this.buffer.append(array, off, size); } /** * This will clear all data from the buffer. This simply sets the count to * be zero, it will not clear the memory occupied by the instance as the * internal buffer will remain. This allows the memory occupied to be reused * as many times as is required. */ @Override public void clear() throws IOException { if (this.buffer != null) { this.buffer.clear(); } } /** * This method is used to ensure the buffer can be closed. Once the buffer * is closed it is an immutable collection of bytes and can not longer be * modified. This ensures that it can be passed by value without the risk of * modification of the bytes. */ @Override public void close() throws IOException { if (this.buffer == null) { this.allocate(); } this.buffer.close(); } /** * This method is used to allocate a default buffer. This will allocate a * buffer of predetermined size, allowing it to grow to an upper limit to * accommodate extra data. If the buffer requested is larger than the limit * an exception is thrown. * * @return this returns an allocated buffer with a default size */ @Override public Buffer allocate() throws IOException { return this.allocate(this.capacity); } /** * This method is used to allocate a default buffer. This will allocate a * buffer of predetermined size, allowing it to grow to an upper limit to * accommodate extra data. If the buffer requested is larger than the limit * an exception is thrown. * * @param size * the initial capacity of the allocated buffer * * @return this returns an allocated buffer with a default size */ @Override public Buffer allocate(long size) throws IOException { if (size > this.limit) throw new BufferException("Specified size %s beyond limit", size); if (this.capacity > size) { // lazily create backing buffer size = this.capacity; } if (this.buffer == null) { this.buffer = this.source.allocate(size); } return this.buffer.allocate(); } }
TehSomeLuigi/someluigis-peripherals
slp_common/org/simpleframework/util/buffer/BufferAllocator.java
Java
gpl-3.0
8,448
"""add graphql ACL to users Revision ID: 2d4882d39dbb Revises: c4d0e9ec46a9 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '2d4882d39dbb' down_revision = 'dc2848563b53' POLICY_NAME = 'wazo_default_user_policy' ACL_TEMPLATES = ['dird.graphql.me'] policy_table = sa.sql.table( 'auth_policy', sa.Column('uuid', sa.String(38)), sa.Column('name', sa.String(80)) ) acl_template_table = sa.sql.table( 'auth_acl_template', sa.Column('id', sa.Integer), sa.Column('template', sa.Text) ) policy_template = sa.sql.table( 'auth_policy_template', sa.Column('policy_uuid', sa.String(38)), sa.Column('template_id', sa.Integer), ) def _find_acl_template(conn, acl_template): query = ( sa.sql.select([acl_template_table.c.id]) .where(acl_template_table.c.template == acl_template) .limit(1) ) return conn.execute(query).scalar() def _find_acl_templates(conn, acl_templates): acl_template_ids = [] for acl_template in acl_templates: acl_template_id = _find_acl_template(conn, acl_template) if acl_template_id: acl_template_ids.append(acl_template_id) return acl_template_ids def _get_policy_uuid(conn, policy_name): policy_query = sa.sql.select([policy_table.c.uuid]).where( policy_table.c.name == policy_name ) for policy in conn.execute(policy_query).fetchall(): return policy[0] def _insert_acl_template(conn, acl_templates): acl_template_ids = [] for acl_template in acl_templates: acl_template_id = _find_acl_template(conn, acl_template) if not acl_template_id: query = ( acl_template_table.insert() .returning(acl_template_table.c.id) .values(template=acl_template) ) acl_template_id = conn.execute(query).scalar() acl_template_ids.append(acl_template_id) return acl_template_ids def _get_acl_template_ids(conn, policy_uuid): query = sa.sql.select([policy_template.c.template_id]).where( policy_template.c.policy_uuid == policy_uuid ) return [acl_template_id for (acl_template_id,) in conn.execute(query).fetchall()] def upgrade(): conn = op.get_bind() policy_uuid = _get_policy_uuid(conn, POLICY_NAME) if not policy_uuid: return acl_template_ids = _insert_acl_template(conn, ACL_TEMPLATES) acl_template_ids_already_associated = _get_acl_template_ids(conn, policy_uuid) for template_id in set(acl_template_ids) - set(acl_template_ids_already_associated): query = policy_template.insert().values( policy_uuid=policy_uuid, template_id=template_id ) conn.execute(query) def downgrade(): conn = op.get_bind() acl_template_ids = _find_acl_templates(conn, ACL_TEMPLATES) if not acl_template_ids: return policy_uuid = _get_policy_uuid(conn, POLICY_NAME) if not policy_uuid: return delete_query = policy_template.delete().where( sa.sql.and_( policy_template.c.policy_uuid == policy_uuid, policy_template.c.template_id.in_(acl_template_ids), ) ) op.execute(delete_query)
wazo-pbx/xivo-auth
alembic/versions/2d4882d39dbb_add_graphql_acl_to_users.py
Python
gpl-3.0
3,250
#include "VCL.h" #include "Unit1.h" #include "GridMap.h" #include "defines.h" #include "matrix_utils.h" #include "bat_run.h" #include "LoadData.h" #include <cstdio> #include <ctime> #include <cstring> #include <cmath> // special LSM mode with "-1 distance" = no aggregation of spots, just statistics per unit bool LSM_minus1_mode = false; float top_percent, min_percent, max_dist, min_simil; String LSIRfn, LSIDfn, LSImask; int spot_cnt, nwc, ccnt; int **cm=0, **nwm, nwns_cnt; std::vector<struct spot> spots; std::vector<int> s_in_nw; std::vector<bool> nw_in_min; std::vector<float> Ebd; class GridMap LSI_maskmap; void get_candidate_cells() { float val_th; int x, y; val_th = 1.0f-top_percent; ccnt=0; for(y=0; y<yd; y++) { for(x=0; x<xd; x++) { if (sol[y][x]>=val_th) { cm[y][x]=0; ccnt++; } else cm[y][x]=-1; } } Form1->Memo1->Lines->Add("Potential cells count = "+IntToStr(ccnt)); } bool nb_in_s(int x, int y, int s) { int minx, miny, maxx, maxy, gx,gy; minx=max(0, x-1); miny=max(0, y-1); maxx=min(xd,x+1); maxy=min(yd,y+1); for(gy=miny; gy<=maxy; gy++) { for(gx=minx; gx<=maxx; gx++) if (cm[gy][gx]==s) return true; } return false; } bool add_to_spot(int s) { int minx, maxx, miny, maxy, x, y, loop; bool added; float val, *rowp; minx=max(0, spots[s].min_gx-1); miny=max(0, spots[s].min_gy-1); maxx=min(xd,spots[s].max_gx+1); maxy=min(yd,spots[s].max_gy+1); added=false; for(y=miny; y<=maxy; y++) { for(x=minx; x<=maxx; x++) { // if (cm[y][x]==0) if ((cm[y][x]!=s) && (cm[y][x]!=-1)) { // Form1->Memo1->Lines->Add("HERE"); if (nb_in_s(x,y,s)) { // Form1->Memo1->Lines->Add("YES"); cm[y][x]=s; spots[s].area++; spots[s].rank += sol[y][x]; spots[s].mean_gx += x; spots[s].mean_gy += y; spots[s].min_gx=min(spots[s].min_gx, x); spots[s].min_gy=min(spots[s].min_gy, y); spots[s].max_gx=max(spots[s].max_gx, x); spots[s].max_gy=max(spots[s].max_gy, y); if (sol[y][x]>(1.0f-min_percent)) spots[s].in_min_percent=true; // rowp=&vmat[y][x][0]; // COMPACT_VMAT Biodiv_Features_Occur_Container& rowp = vmat[y][x]; for(loop=0; loop<map_cnt; loop++) { //std::cerr << "rowp: " << rowp.size() << std::endl; val = rowp[loop]; if (val!=-1) spots[s].bdv[loop] += val; // else // spots[s].bdv[loop] = 0.0f; } added=true; } } } } return added; } void expand_spot(int x, int y) { bool added; int loop; spots[spot_cnt].bdv = 0; spots[spot_cnt].min_gx = x; spots[spot_cnt].min_gy = y; spots[spot_cnt].max_gx = x; spots[spot_cnt].max_gy = y; spots[spot_cnt].mean_gx = static_cast<float>(x); spots[spot_cnt].mean_gy = static_cast<float>(y); spots[spot_cnt].area = 1; spots[spot_cnt].rank = sol[y][x]; if (sol[y][x]>=(1.0f-min_percent)) spots[spot_cnt].in_min_percent=true; else spots[spot_cnt].in_min_percent=false; spots[spot_cnt].bdv = new float[map_cnt]; for(loop=0; loop<map_cnt; loop++) spots[spot_cnt].bdv[loop] =0.0f; cm[y][x]=spot_cnt; do { added = add_to_spot(spot_cnt); Application->ProcessMessages(); } while(added); #if 0 char txt[255]; sprintf(txt,"Spot %i A=%i Xmin=%i xmax=%i ymin=%i ymax=%i mean-x=%0.3f mean-y=%0.3f", spot_cnt, spots[spot_cnt].area, spots[spot_cnt].min_gx, spots[spot_cnt].max_gx, spots[spot_cnt].min_gy, spots[spot_cnt].max_gy, spots[spot_cnt].mean_gx, spots[spot_cnt].mean_gy); // if ((spot_cnt%10)==0) Form1->Memo1->Lines->Add(txt); #endif } void get_spots() { float val_th; int x, y, in_cnt; spot_cnt=1; const size_t DEF_MAX_SPOTS = 2048; spots.reserve(DEF_MAX_SPOTS); try { spots.resize(spot_cnt+1); } catch(std::bad_alloc const& ex) { Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what())); } in_cnt =0; for(y=0; y<yd; y++) { for(x=0; x<xd; x++) { if (cm[y][x]==0) { Application->ProcessMessages(); expand_spot(x,y); if (spots[spot_cnt].in_min_percent) in_cnt++; // Form1->Memo1->Lines->Add("New spot, area = " // +IntToStr(spots[spot_cnt].area)); spot_cnt++; spots.resize(spots.size()+1); if ((spot_cnt%1000)==0) Form1->Memo1->Lines->Add("Spot count = "+IntToStr(spot_cnt-1)); } } } Form1->Memo1->Lines->Add("Spot count = "+IntToStr(spot_cnt-1)); Form1->Memo1->Lines->Add("Spots including best areas count = "+IntToStr(in_cnt)); } float calc_dist(int s1, int s2) { float dij, dx, dy, dm2; float minx1, minx2, maxx1, maxx2, miny1, miny2, maxy1, maxy2; int x1, x2, y1, y2; dm2 = max_dist*max_dist; if (dm2==0) return (max_dist+1.0f); // with zero dist, separate spots cannot be joined minx1=static_cast<float>(spots[s1].min_gx); maxx1=static_cast<float>(spots[s1].max_gx); miny1=static_cast<float>(spots[s1].min_gy); maxy1=static_cast<float>(spots[s1].max_gy); minx2=static_cast<float>(spots[s2].min_gx); maxx2=static_cast<float>(spots[s2].max_gx); miny2=static_cast<float>(spots[s2].min_gy); maxy2=static_cast<float>(spots[s2].max_gy); // Form1->Memo1->Lines->Add("corners"); // sprintf(txt, "minx1=%f maxx1=%f miny1=%f maxy1=%f", minx1, maxx1, miny1, maxy1); // Form1->Memo1->Lines->Add(txt); // sprintf(txt, "minx2=%f maxx2=%f miny2=%f maxy2=%f", minx2, maxx2, miny2, maxy2); // Form1->Memo1->Lines->Add(txt); // Form1->Memo1->Lines->Add("yxxxvc"); if (minx1>(maxx2+max_dist)) return (max_dist+1.0f); if (minx2>(maxx1+max_dist)) return (max_dist+1.0f); if (miny1>(maxy2+max_dist)) return (max_dist+1.0f); if (miny2>(maxy1+max_dist)) return (max_dist+1.0f); // Form1->Memo1->Lines->Add("here"); for(y1=static_cast<int>(miny1); y1<=maxy1;y1++) for(x1=static_cast<int>(minx1); x1<=maxx1;x1++) { // Form1->Memo1->Lines->Add("y1loop"+IntToStr(y1)); if (cm[y1][x1]==s1) { for(y2=static_cast<int>(miny2); y2<=maxy2;y2++) for(x2=static_cast<int>(minx2); x2<=maxx2;x2++) // xxx stuck in this loop. { if (cm[y2][x2]==s2) { dij = z_pow(x1-x2,2)+z_pow(y1-y2,2); if (dij<=dm2) return 0.0f; } } } } return (max_dist+1.0f); } float calc_sim(int s1, int s2) { int loop, s, lvl1, lvl2; float diff, val; diff=0.0f; for(loop=0; loop<map_cnt; loop++) { val = spots[s1].bdv[loop]; if (val<0.01f*Ebd[loop]) lvl1=0; else if (val<0.1f*Ebd[loop]) lvl1=1; else if (val<Ebd[loop]) lvl1=2; else if (val<10*Ebd[loop]) lvl1=3; else if (val<100*Ebd[loop]) lvl1=4; else lvl1=5; val = spots[s2].bdv[loop]; if (val<0.01f*Ebd[loop]) lvl2=0; else if (val<0.1f*Ebd[loop]) lvl2=1; else if (val<Ebd[loop]) lvl2=2; else if (val<10*Ebd[loop]) lvl2=3; else if (val<100*Ebd[loop]) lvl2=4; else lvl2=5; diff += fabs(lvl1-lvl2); } diff/=map_cnt; return diff; } void add_nb_to_nw(int spot) { int loop; float dist, diff; for(loop=1; loop<spot_cnt; loop++) { // Form1->Memo1->Lines->Add("spot = "+IntToStr(loop)); if (spots[loop].nwn==-1) { // Form1->Memo1->Lines->Add("dist next"); dist = calc_dist(spot, loop); // Form1->Memo1->Lines->Add("sim next"); diff = calc_sim(spot, loop); if ((dist<=max_dist) && (diff<min_simil)) { spots[loop].nwn = nwc; nw_in_min[nwc] = (nw_in_min[nwc] || spots[loop].in_min_percent); s_in_nw[nwns_cnt] = loop; nwns_cnt++; // Form1->Memo1->Lines->Add("joined"); } } } } void expand_network(int s) { int pos; spots[s].nwn = nwc; nwns_cnt = 1; s_in_nw[0] = s; nw_in_min[nwc] = (nw_in_min[nwc] || spots[s].in_min_percent); pos=0; while(pos<nwns_cnt) { // Form1->Memo1->Lines->Add("pos="+IntToStr(pos)); add_nb_to_nw(s_in_nw[pos]); pos++; } } void Fix_bd_values() { int loop, s; for(loop=0; loop<map_cnt; loop++) Ebd[loop]=0.0f; for(s=1;s<spot_cnt;s++) { for(loop=0; loop<map_cnt; loop++) { Ebd[loop] += spots[s].bdv[loop]; spots[s].bdv[loop] /= spots[s].area; } } for(loop=0; loop<map_cnt; loop++) Ebd[loop] /= ccnt; // Ebd[loop]=average over cells in cut } void get_networks() { int loop, x, y, cilcnt; /* const size_t DEF_MAX_NW = 2048; nw_in_min.reserve(DEF_MAX_NW); nw_in_min.assign(2, false); */ // get_networks always called after get_spots() -> spot_cnt known try { s_in_nw.resize(spot_cnt, 0); Ebd.resize(map_cnt, 0); nw_in_min.resize(spot_cnt+1, false); } catch(std::bad_alloc const& ex) { Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what())); } nwc = 1; // xxx for(loop=0; loop<spot_cnt; loop++) { spots[loop].nwn=-1; } // uses Ebd[] Fix_bd_values(); for(loop=1; loop<spot_cnt; loop++) { if ((spots[loop].nwn==-1) && (spots[loop].in_min_percent)) { // Form1->Memo1->Lines->Add(IntToStr(loop)); expand_network(loop); nwc++; nw_in_min.push_back(false); } } for(y=0; y<yd; y++) { for(x=0; x<xd; x++) { if (false && cm[y][x] >0 && spots[cm[y][x]].nwn >= nw_in_min.size()) { Form1->Memo1->Lines->Add("SEGFAUUUUUUUUUUUUUUUUUULT, cm: "+ IntToStr(cm[y][x])); Form1->Memo1->Lines->Add("SEGFAUUUUUUUUUUUUUUUUUULT, cm: "+ IntToStr(cm[y][x]) + ", spots:"+IntToStr(spots[cm[y][x]].nwn)); } //if (Rmax[y][x]==-1) if (-1 == status[y][x]) nwm[y][x]=-1; else if (cm[y][x]==0) nwm[y][x]=-2; else if (cm[y][x]==-1) nwm[y][x]=-2; // the -1== check is critical, or likely segfault! else if ((cm[y][x]>0) && (-1==spots[cm[y][x]].nwn || (!nw_in_min[spots[cm[y][x]].nwn]))) nwm[y][x]=-2; else nwm[y][x]=spots[cm[y][x]].nwn; // xxx error } } Form1->Memo1->Lines->Add("Found networks count = "+IntToStr(nwc-1)); std::vector<float> spdat; try { spdat.resize(map_cnt, 0.0); } catch(std::bad_alloc const& ex) { Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what())); } cilcnt=0; for(y=0; y<yd; y++) { for(x=0; x<xd; x++) { //if (Rmax[y][x]==-1) if (-1 == status[y][x]) continue; if (nwm[y][x]>0) { // rowp=&vmat[y][x][0]; // COMPACT_VMAT Biodiv_Features_Occur_Container& rowp = vmat[y][x]; //for(loop=0;loop<map_cnt;loop++) for(loop=rowp.first(); loop!=rowp.overflow(); loop=rowp.next(loop)) { if (rowp[loop]>0.0f) spdat[loop] += rowp[loop]; } cilcnt++; } } } Form1->Memo1->Lines->Add("Cells in classified landscapes = "+IntToStr(cilcnt)); const size_t MAX_STR_LEN = 512; char txt[MAX_STR_LEN]; for(loop=0;loop<map_cnt;loop++) { sprintf(txt, "%-6.3f %-5.3f %s\n", spp[loop].weight, spdat[loop], spp[loop].fname.toUtf8().constData()); Form1->Memo1->Lines->Add(txt); } } // Gets statistics for units specified in the PPA mask, // so networks will actually be the units // all the nwarea, nwx, nwy, nwrank are aggregated (not normalized) and will be divided by nwarea[] later on void get_fake_networks_from_mask(std::vector<int>& nwarea, std::vector<float>& nwx, std::vector<float>& nwy, std::vector<float>& nwrank, float**& mat) { // max_val pre-calculated in load_from_file... spot_cnt = (int)LSI_maskmap.max_val+1; try { spots.resize(spot_cnt); } catch(std::bad_alloc const& ex) { Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what())); } /* // Init to 0. units have numbers >=1 for (size_t i=0; i<spot_cnt; i++) spots[i].num = 0; // Find used unit numbers. Use the array spots[].num // for the unit numbers for (size_t y=0; y<yd; y++) { for (size_t x=0; x<xd; x++) { // make sure the mask doesn't include "missing" cells if (sol[y][x] < 0.0f) continue; int unit_idx = LSI_maskmap.m[y][x]; if (unit_idx > 0 && unit_idx <= spots.size()) if (0==spots[unit_idx].num) spots[unit_idx].num++; } } // unit numbers actually used in the LSI analysis mask std::vector<int> unit_nums; nwc = 0; for (size_t i=0; i<spot_cnt; i++) { if (0 < spots[i].num) { nwc++; // nwc is global unit_nums.push_back(i); } } nwc++; // yes, it is number of networks/units +1 */ // bypass the 2 loops above. Use as many networks as the biggest number in the planning // units layer/mask. This avoids crashes if non-consecutive numbers are used. nwc = spot_cnt; try { nwarea.resize(nwc+1, 0); nwrank.resize(nwc+1, 0); nwrank.resize(nwc+1, 0); nwx.resize(nwc+1, 0); nwy.resize(nwc+1, 0); } catch(std::bad_alloc const& ex) { Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what())); } mat = matrix(0, nwc+1, 0, map_cnt); if (!mat) { ShowMessage("Out of memory when doing LSIdent"); return; } for(int nw=0; nw<=nwc; nw++) { nwarea[nw]=0; nwrank[nw]=0.0f; nwx[nw]=0.0f; nwy[nw]=0.0f; for(int sp=0; sp<map_cnt; sp++) mat[nw][sp]=0.0f; } for (size_t y=0; y<yd; y++) { for (size_t x=0; x<xd; x++) { // make sure the mask doesn't include "missing" cells if (sol[y][x] < 0.0f) continue; int unit_idx = LSI_maskmap.m[y][x]; if (unit_idx <= 0 || unit_idx >= spot_cnt) continue; nwarea[unit_idx]++; nwx[unit_idx] += x; nwy[unit_idx] += y; nwrank[unit_idx] += sol[y][x]; // float* rowp = &vmat[y][x][0]; // COMPACT_VMAT Biodiv_Features_Occur_Container& rowp = vmat[y][x]; if (rowp) //for(size_t spp_idx=0; spp_idx<map_cnt; spp_idx++) for(size_t spp_idx=rowp.first(); spp_idx!=rowp.overflow(); spp_idx=rowp.next(spp_idx)) if (rowp[spp_idx] > .0f) mat[unit_idx][spp_idx] += rowp[spp_idx]; } } // And the nwout raster (variable nwm) is not generated (it's = LSImask) } void print_network_data() { int loop, nw, sp, num, c10, c1, c01, c001, c0001, sp_at_zero; float **mat, nwtot; FILE *f; f=fopen(LSIDfn.toUtf8().constData(), "w+t"); if (!f) { ShowMessage("Could not open output file " + LSIDfn); return; } std::vector<int> nwarea; std::vector<float> nwrank, nwx, nwy; if (LSM_minus1_mode) { // All params by ref./output get_fake_networks_from_mask(nwarea, nwx, nwy, nwrank, mat); } else { try { nwarea.resize(nwc+1, 0); nwrank.resize(nwc+1, 0); nwrank.resize(nwc+1, 0); nwx.resize(nwc+1, 0); nwy.resize(nwc+1, 0); } catch(std::bad_alloc const& ex) { Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what())); } // sprintf(txt, "nwc=%i spots=%i",nwc, spot_cnt); // ShowMessage(txt); mat = matrix(0, nwc+1, 0, map_cnt); if (!mat) { ShowMessage("Out of memory when doing LSIdent"); fclose(f); return; } for(nw=0; nw<=nwc; nw++) { nwarea[nw]=0; nwrank[nw]=0.0f; nwx[nw]=0.0f; nwy[nw]=0.0f; for(sp=0; sp<map_cnt; sp++) mat[nw][sp]=0.0f; } for(loop=1; loop<spot_cnt; loop++) { num = spots[loop].nwn; if (num == -1) continue; for(sp=0; sp<map_cnt; sp++) mat[num][sp] += spots[loop].bdv[sp]*spots[loop].area; nwarea[num] += spots[loop].area; nwrank[num] += spots[loop].rank; nwx[num] += spots[loop].mean_gx; nwy[num] += spots[loop].mean_gy; } } std::string nets_or_units; if (LSM_minus1_mode) nets_or_units = "units"; else nets_or_units = "networks"; fprintf(f, "Most important biodiversity features (e.g. species) in %s; those occurring at a 1%%+ level\n", nets_or_units.c_str()); fprintf(f, "of original distribution\n"); std::string net_or_unit; if (LSM_minus1_mode) net_or_unit = "Unit"; else net_or_unit = "Network"; fprintf(f, "%s Area Mean-Rank X Y Spp_distribution_sum spp occurring at >10%% >1%% >0.1%% >0.01%% >0.001%%\n", net_or_unit.c_str()); std::vector<float> sptot; try { sptot.resize(map_cnt, 0); } catch(std::bad_alloc const& ex) { Form1->Memo1->Lines->Add("Out of memory in landscape identification: "+String(ex.what())); } float tottot=0.0f; for(nw=1; nw<nwc; nw++) { // do not calc/output results for empty/missing unit numbers if (LSM_minus1_mode && nwarea[nw]<=0) continue; c10 = c1 = c01 = c001 = c0001 = 0; nwtot=0.0f; for(sp=0; sp<map_cnt; sp++) { nwtot += mat[nw][sp]; sptot[sp] += mat[nw][sp]; if (mat[nw][sp]>0.1f) { c10++; c1++; c01++; c001++; c0001++; } else if (mat[nw][sp]>0.01f) { c1++; c01++; c001++; c0001++; } else if (mat[nw][sp]>0.001f) { c01++; c001++; c0001++; } else if (mat[nw][sp]>0.0001f) { c001++; c0001++; } else if (mat[nw][sp]>0.00001f) { c0001++; } } tottot += nwtot; // nw area rnk x y tot fprintf(f, "%-5i %-6i %-6.3f %-6.3f %-6.3f %-6.3f %-5i %-5i %-5i %-5i %-5i\n", nw, nwarea[nw], nwrank[nw]/nwarea[nw], nwx[nw]/nwarea[nw], nwy[nw]/nwarea[nw], nwtot, c10, c1, c01, c001, c0001); for(sp=0; sp<map_cnt; sp++) { if (mat[nw][sp]>0.01f) fprintf(f, " Feature %s, %-5.2f%% of full distribution\n", spp[sp].fname.toUtf8().constData(),100*mat[nw][sp]); } // fprintf(f, "\n"); } fprintf(f, "Repeat without spp info for easy import\n"); fprintf(f,"%s Area Mean-Rank X Y Spp_distribution_sum spp occurring at >10%% >1%% >0.1%% >0.01%% >0.001%%\n", net_or_unit.c_str()); //tottot=0.0f; for(nw=1; nw<nwc; nw++) { // do not cal/output results for empty/missing unit numbers if (LSM_minus1_mode && nwarea[nw]<=0) continue; c10 = c1 = c01 = c001 = c0001 = 0; nwtot=0.0f; for(sp=0; sp<map_cnt; sp++) { nwtot += mat[nw][sp]; // would be the second time! //sptot[sp] += mat[nw][sp]; if (mat[nw][sp]>0.1f) { c10++; c1++; c01++; c001++; c0001++; } else if (mat[nw][sp]>0.01f) { c1++; c01++; c001++; c0001++; } else if (mat[nw][sp]>0.001f) { c01++; c001++; c0001++; } else if (mat[nw][sp]>0.0001f) { c001++; c0001++; } else if (mat[nw][sp]>0.00001f) { c0001++; } } // this would make tottot 2x the true totot //tottot += nwtot; // nw area rnk x y tot fprintf(f, "%-5i %-6i %-6.3f %-6.3f %-6.3f %-6.3f %-5i %-5i %-5i %-5i %-5i\n", nw, nwarea[nw], nwrank[nw]/nwarea[nw], nwx[nw]/nwarea[nw], nwy[nw]/nwarea[nw], nwtot, c10, c1, c01, c001, c0001); } fprintf(f, "\n\nAverage proportion remaining over all spp in %s = %f\n",nets_or_units.c_str(), tottot/map_cnt); sp_at_zero=0; for(sp=0; sp<map_cnt; sp++) { if (sptot[sp]<=0.0f) sp_at_zero++; } fprintf(f, "Count of biodiversity features (e.g. species) with nothing remaining in the network = %i\n",sp_at_zero); fprintf(f, "Total proportion and sum remaining for biodiversity features\n"); for(sp=0; sp<map_cnt; sp++) { fprintf(f, "%s %-5.4f %0.4f\n", spp[sp].fname.toUtf8().constData(), sptot[sp], sptot[sp]*spp[sp].prob_sum); } if (LSM_minus1_mode) fprintf(f, "\n\nBiological data of %i %s.\n",nwc-1, nets_or_units.c_str()); else fprintf(f, "\n\nBiological data of %i %s (spots=%i).\n",nwc-1, nets_or_units.c_str(), spot_cnt-1); fprintf(f, "%s x biodiversity features matrix\n", nets_or_units.c_str()); if (LSM_minus1_mode) fprintf(f, "Unit_number area[cells] sp_data .....\n"); else fprintf(f, "Nw_number area[cells] sp_data .....\n"); for(nw=1; nw<nwc; nw++) { // do not calc/output results for empty/missing unit numbers if (LSM_minus1_mode && nwarea[nw]<=0) continue; fprintf(f, "%-5i %-6i ", nw, nwarea[nw]); for(sp=0; sp<map_cnt; sp++) fprintf(f,"%-6.4f ", mat[nw][sp]); fprintf(f, "\n"); } fclose(f); free_matrix(mat, 0, nwc+1, 0, map_cnt); } bool read_LSI_mask(int top_fraction_mode) { int x, y; LSI_maskmap.normalize=false; if (!LSI_maskmap.load_from_file(LSImask, mask_data, area_mask.m)) { Form1->Memo1->Lines->Add("************** ERROR ***************"); Form1->Memo1->Lines->Add(" FAILURE attempting LSI mask map load."); return false; } Form1->Memo1->Lines->Add("LSI mask map loaded."); val_th = 1.0f-top_percent; ccnt = 0; for(y=0; y<yd; y++) { for(x=0; x<xd; x++) { if (LSI_maskmap.m[y][x]>=1) { if (top_fraction_mode) { if (sol[y][x]>=val_th) { cm[y][x]=0; ccnt++; } else cm[y][x]=-1; } else { cm[y][x]=0; ccnt++; } } else cm[y][x]=-1; } } Form1->Memo1->Lines->Add("Potential cells count = "+IntToStr(ccnt)); return true; } int LSIdent(int LSI_mode) { const size_t MAX_STRLEN = 2048; char txt[MAX_STRLEN]; Form1->Memo1->Lines->Add(""); Form1->Memo1->Lines->Add(""); Form1->Memo1->Lines->Add("NEW LANDSCAPE IDENTIFICATION ANALYSIS"); // This is done now in the visitor class in post_process.cpp //top_percent = StrToFloat(Form1->Edit4->Text)/100.0f; //min_percent = StrToFloat(Form1->Edit5->Text)/100.0f; //max_dist = StrToFloat(Form1->Edit6->Text); //min_simil = StrToFloat(Form1->Edit7->Text); //LSIRfn = Form1->Edit8->Text; bool lsi_mask_ok = true; if (LSI_mode==0) // "LSB" { sprintf(txt, "Running LSIdent with top%%=%0.3f min%%=%0.3f max-d=%0.3f min-s=%0.3f", top_percent*100, min_percent*100, max_dist, min_simil); Form1->Memo1->Lines->Add(txt); Form1->Memo1->Lines->Add("1. Getting candidate cells."); get_candidate_cells(); } else if (LSI_mode==1) // "LSM" { if (0.0f > max_dist) { LSM_minus1_mode = true; sprintf(txt, "Running LSIdent with mask file (%s). Note: LSM special case with max. distance -1, ignoring top%%=%0.3f and using whole landscape", LSImask.toStdString().c_str(), top_percent*100); Form1->Memo1->Lines->Add(txt); top_percent = 1.0f; } else { sprintf(txt, "Running LSIdent with mask file (%s) max-d=%0.3f min-s=%0.3f", LSImask.toStdString().c_str(), max_dist, min_simil); Form1->Memo1->Lines->Add(txt); Form1->Memo1->Lines->Add("1. Reading relevant areas from mask file "+Form1->Edit42->Text); } lsi_mask_ok = read_LSI_mask(0); if (!lsi_mask_ok) { Form1->Memo1->Lines->Add("ERROR! failed to read LSM areas from mask file: " + LSImask); } } else // 2==LSI_mode "LSB" { sprintf(txt, "Running LSIdent for top fraction within masked area, mask file %s fract=%0.4f max-d=%0.3f min-s=%0.3f", LSImask.toStdString().c_str(), top_percent, max_dist, min_simil); Form1->Memo1->Lines->Add(txt); Form1->Memo1->Lines->Add("1. Reading relevant areas from mask file "+Form1->Edit42->Text); lsi_mask_ok = read_LSI_mask(1); if (!lsi_mask_ok) { Form1->Memo1->Lines->Add("ERROR! failed to read LSB areas from mask file: " + LSImask); } } if (!lsi_mask_ok) { Form1->Memo1->Lines->Add("Please fix the mask file name. No results will be generated for this post-processing analysis."); return false; } if (!LSM_minus1_mode) { // free only if traditional modes LSI_maskmap.free_matrix_m(); Form1->Memo1->Lines->Add("2. Identifying spots."); get_spots(); // spots[s].bdv[sp] = 0.0f; sisaltaa prop of sp spotissa Form1->Memo1->Lines->Add("3. Finding networks."); get_networks(); } print_network_data(); if (LSM_minus1_mode) { LSI_maskmap.free_matrix_m(); } else { #if 0 // obsmap[0].show_spots(Form1->Image1->Picture->Bitmap, cm); obsmap[0].show_spots(Form1->Image1->Picture->Bitmap, nwm, 0); #endif obsmap[0].export_GIS_INT(nwm, LSIRfn); // the spots[].bdv are not allocated in LSM "-1 distance" mode for(int loop=0; loop<spots.size(); loop++) { if (spots[loop].bdv) delete[] spots[loop].bdv; spots[loop].bdv=0; } } Screen->Cursor=crDefault; return true; } void LSCAnalysis(float f1, float f2, const String& cfn, const String& comp_outfn) { //float f1, f2; //String cfn, comp_outfn; float f1cells, f2cells, bothcells, rodiff; class GridMap cmpmap; int x, y, z1, z2, rcnt; bool f1ok, f2ok; DecimalSeparator='.'; //cfn = Edit23->Text; cmpmap.set_no_normalize(); if (!cmpmap.load_from_file(cfn, mask_data, area_mask.m)) { ShowMessage("Could not load given comparison solution"); return; } Form1->Memo1->Lines->Add(""); Form1->Memo1->Lines->Add("Solution comparison stats"); //f1 = StrToFloat(Edit22->Text); //f2 = StrToFloat(Edit24->Text); Form1->Memo1->Lines->Add("S1 cut level = "+FloatToStrF(f1, ffFixed, 7, 4)); Form1->Memo1->Lines->Add("S2 cut level = "+FloatToStrF(f2, ffFixed, 7, 4)); f1cells=f2cells=bothcells=rodiff=0.0f; z1=z2=rcnt=0; for(y=0; y<yd; y++) for(x=0; x<xd; x++) { f1ok=f2ok=false; if (f1>0.0f) { if ((sol[y][x]!=-1) && (sol[y][x]>=(1.0f-f1))) f1ok=true; } else { if ((sol[y][x]!=-1) && (sol[y][x]<=(-f1))) f1ok=true; } if (f2>0.0f) { if ((cmpmap.m[y][x]!=-1) && (cmpmap.m[y][x]>=(1.0f-f2))) f2ok=true; } else { if ((cmpmap.m[y][x]>0.0f) && (cmpmap.m[y][x]<=(-f2))) f2ok=true; } if (f1ok) f1cells++; if (f2ok) f2cells++; if (f1ok && f2ok) bothcells++; if (sol[y][x]==0.0f) z1++; if (cmpmap.m[y][x]==0.0f) z2++; if ((sol[y][x]!=-1) && (cmpmap.m[y][x]!=0.0f)) { ++rcnt; rodiff+= fabs(sol[y][x]-cmpmap.m[y][x]); } nwm[y][x] = 0; //if (Rmax[y][x]==-1) if (-1 == status[y][x]) nwm[y][x] = -1; else if (f1ok && f2ok) nwm[y][x] = 1; else if (f1ok) nwm[y][x] = 2; else if (f2ok) nwm[y][x] = 3; } Form1->Memo1->Lines->Add("Cells in present solution fraction = " +IntToStr((int)f1cells)); Form1->Memo1->Lines->Add("Cells in comparison solution fraction = " +IntToStr((int)f2cells)); Form1->Memo1->Lines->Add("Cells included in both solutions = " +IntToStr((int)bothcells)); Form1->Memo1->Lines->Add("Initially removed in present solution = " +IntToStr(z1)); Form1->Memo1->Lines->Add("Initially removed in comparison solution = "+IntToStr(z2)); Form1->Memo1->Lines->Add("Similarity f1 = "+FloatToStrF(bothcells/f1cells, ffFixed, 7, 4)); Form1->Memo1->Lines->Add("Similarity f2 = "+FloatToStrF(bothcells/f2cells, ffFixed, 7, 4)); Form1->Memo1->Lines->Add("Average difference in removal order = "+FloatToStrF(rodiff/rcnt, ffFixed, 7, 4)); const size_t MAX_STR_LEN = 512; char txt[MAX_STR_LEN]; sprintf(txt, "Overlap f1 = %0.4f, f1 = %0.4f. Average order diff=%0.4f. See also memo.", bothcells/f1cells,bothcells/f2cells, rodiff/rcnt); Form1->Memo1->Lines->Add(txt); if (!bat_mode) ShowMessage(txt); if (Form1->CheckBox7->Checked) { #if 0 //comp_outfn = Edit29->Text; obsmap[0].show_spots(Form1->Image1->Picture->Bitmap, nwm, 1); #endif obsmap[0].export_GIS_INT(nwm, comp_outfn); } }
cbig/zonation-core
zig4/core/LSIdent.cpp
C++
gpl-3.0
27,025
<?php session_start(); include_once 'inc/vcode.inc.php'; $_SESSION['vcode']=vcode(100,40,30,4); ?>
TRyToDOit/CFCBBS
show_code.php
PHP
gpl-3.0
99
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.servlet; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.openkm.util.FormatUtil; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openkm.api.OKMDocument; import com.openkm.api.OKMRepository; import com.openkm.bean.Document; import com.openkm.core.Config; import com.openkm.core.PathNotFoundException; import com.openkm.core.RepositoryException; import com.openkm.util.PathUtils; import com.openkm.util.WebUtils; /** * Download Servlet */ public class DownloadServlet extends BasicSecuredServlet { private static Logger log = LoggerFactory.getLogger(DownloadServlet.class); private static final long serialVersionUID = 1L; /** * */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); String userId = request.getRemoteUser(); String path = WebUtils.getString(request, "path"); String uuid = WebUtils.getString(request, "uuid"); boolean inline = WebUtils.getBoolean(request, "inline"); InputStream is = null; try { // Now an document can be located by UUID if (uuid != null && !uuid.isEmpty()) { uuid = FormatUtil.sanitizeInput(uuid); path = OKMRepository.getInstance().getNodePath(null, uuid); } else if (path != null && !path.isEmpty()) { path = FormatUtil.sanitizeInput(path); } if (path != null) { Document doc = OKMDocument.getInstance().getProperties(null, path); String fileName = PathUtils.getName(doc.getPath()); // Optinal append version to download ( not when doing checkout ) if (Config.VERSION_APPEND_DOWNLOAD) { String versionToAppend = " rev " + OKMDocument.getInstance().getProperties(null,uuid).getActualVersion().getName(); String[] nameParts = fileName.split("\\.(?=[^\\.]+$)"); fileName = nameParts[0] + versionToAppend + "." + nameParts[1]; } log.info("Download {} by {} ({})", new Object[] { path, userId, (inline ? "inline" : "attachment") }); is = OKMDocument.getInstance().getContent(null, path, false); WebUtils.sendFile(request, response, fileName, doc.getMimeType(), inline, is); } else { response.setContentType("text/plain; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("Missing document reference"); out.close(); } } catch (PathNotFoundException e) { log.warn(e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "PathNotFoundException: " + e.getMessage()); } catch (RepositoryException e) { log.warn(e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "RepositoryException: " + e.getMessage()); } catch (Exception e) { log.warn(e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } finally { IOUtils.closeQuietly(is); } } }
papamas/DMS-KANGREG-XI-MANADO
src/main/java/com/openkm/servlet/DownloadServlet.java
Java
gpl-3.0
4,131
# # Copyright (c) 2013 Christopher L. Felton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. try: from setuptools import setup from setuptools import find_packages except ImportError: from distutils.core import setup from pkgutil import walk_packages import mn # many pypy installs don't have setuptools (?) def _find_packages(path='.', prefix=''): yield prefix prefix = prefix + "." for _, name, ispkg in walk_packages(path, prefix, onerror=lambda x: x): if ispkg: yield name def find_packages(): return list(_find_packages(mn.__path__, mn.__name__)) setup(name = "minnesota", version = "0.1pre", description = "collection of HDL cores ", license = "LGPL", platforms = ["Any"], keywords = "DSP HDL MyHDL FPGA FX2 USB", packages = find_packages(), # @todo need to add the examples and test directories, # copy it over ... )
cfelton/minnesota
setup.py
Python
gpl-3.0
1,770
/* FILE GeneticOperations.hh ** PACKAGE GeneticOperations ** AUTHOR Edward S. Blurock ** ** CONTENT ** Prototypes for the "GeneticOperations" package in the CoreObjects environment ** ** COPYRIGHT (C) 1997 Edward S. Blurock */ #ifndef CoreObjects_GENETICOPERATIONS_HH #define CoreObjects_GENETICOPERATIONS_HH #define GENETIC_DISTRIBUTION_ID GENETIC_BASE + 2 #define GENETIC_DISTRIBUTION_NAME "GeneticDistribution" #define GENETIC_STDDEV_ID GENETIC_BASE + 3 #define GENETIC_STDDEV_NAME "GeneticStdDev" #define GENETIC_INTERVAL_ID GENETIC_BASE + 4 #define GENETIC_INTERVAL_NAME "GeneticInterval" #define GENETIC_CONSTANT_ID GENETIC_BASE + 6 #define GENETIC_CONSTANT_NAME "GeneticConstant" #define GENETIC_SETOFPARAMS_ID GENETIC_BASE + 5 #define GENETIC_SETOFPARAMS_NAME "GeneticSetOfParameters" #define SET_NAME1 "C1" #define SET_NAME2 "C2" /*I . . . INCLUDES . . . . . . . . . . . . . . . . . . . . . . . . . . . . */ #include "GeneticOperationsType.hh" /*P . . . PROTOTYPES . . . . . . . . . . . . . . . . . . . . . . . . . . . */ extern void InitialGeneticEncodeDecodeRoutines(); void AddGeneticClasses(DataSetOfObjectsClass& set); BaseDataSetOfObjects *PairSet(DataObjectClass *popobjectbase); #endif
blurock/AnalysisDevelop
GeneticOperations/include/CoreObjects/GeneticOperations.hh
C++
gpl-3.0
1,353
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @version $Id: HeadScript.php 23775 2011-03-01 17:25:24Z ralph $ * @license http://framework.zend.com/license/new-bsd New BSD License */ /** Zend_View_Helper_Placeholder_Container_Standalone */ require_once 'Zend/View/Helper/Placeholder/Container/Standalone.php'; /** * Helper for setting and retrieving script elements for HTML head section * * @uses Zend_View_Helper_Placeholder_Container_Standalone * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_View_Helper_HeadScript extends Zend_View_Helper_Placeholder_Container_Standalone { /**#@+ * Script type contants * @const string */ const FILE = 'FILE'; const SCRIPT = 'SCRIPT'; /**#@-*/ /** * Registry key for placeholder * @var string */ protected $_regKey = 'Zend_View_Helper_HeadScript'; /** * Are arbitrary attributes allowed? * @var bool */ protected $_arbitraryAttributes = false; /**#@+ * Capture type and/or attributes (used for hinting during capture) * @var string */ protected $_captureLock; protected $_captureScriptType = null; protected $_captureScriptAttrs = null; protected $_captureType; /**#@-*/ /** * Optional allowed attributes for script tag * @var array */ protected $_optionalAttributes = array('charset', 'defer', 'language', 'src'); /** * Required attributes for script tag * @var string */ protected $_requiredAttributes = array('type'); /** * Whether or not to format scripts using CDATA; used only if doctype * helper is not accessible * @var bool */ public $useCdata = false; /** * Constructor * * Set separator to PHP_EOL. * * @return void */ public function __construct () { parent::__construct(); $this->setSeparator(PHP_EOL); } /** * Return headScript object * * Returns headScript helper object; optionally, allows specifying a script * or script file to include. * * @param string $mode Script or file * @param string $spec Script/url * @param string $placement Append, prepend, or set * @param array $attrs Array of script attributes * @param string $type Script type and/or array of script attributes * @return Zend_View_Helper_HeadScript */ public function headScript ($mode = Zend_View_Helper_HeadScript::FILE, $spec = null, $placement = 'APPEND', array $attrs = array(), $type = 'text/javascript') { if ((null !== $spec) && is_string($spec)) { $action = ucfirst(strtolower($mode)); $placement = strtolower($placement); switch ($placement) { case 'set': case 'prepend': case 'append': $action = $placement . $action; break; default: $action = 'append' . $action; break; } $this->$action($spec, $type, $attrs); } return $this; } /** * Start capture action * * @param mixed $captureType * @param string $typeOrAttrs * @return void */ public function captureStart ( $captureType = Zend_View_Helper_Placeholder_Container_Abstract::APPEND, $type = 'text/javascript', $attrs = array()) { if ($this->_captureLock) { require_once 'Zend/View/Helper/Placeholder/Container/Exception.php'; $e = new Zend_View_Helper_Placeholder_Container_Exception( 'Cannot nest headScript captures'); $e->setView($this->view); throw $e; } $this->_captureLock = true; $this->_captureType = $captureType; $this->_captureScriptType = $type; $this->_captureScriptAttrs = $attrs; ob_start(); } /** * End capture action and store * * @return void */ public function captureEnd () { $content = ob_get_clean(); $type = $this->_captureScriptType; $attrs = $this->_captureScriptAttrs; $this->_captureScriptType = null; $this->_captureScriptAttrs = null; $this->_captureLock = false; switch ($this->_captureType) { case Zend_View_Helper_Placeholder_Container_Abstract::SET: case Zend_View_Helper_Placeholder_Container_Abstract::PREPEND: case Zend_View_Helper_Placeholder_Container_Abstract::APPEND: $action = strtolower($this->_captureType) . 'Script'; break; default: $action = 'appendScript'; break; } $this->$action($content, $type, $attrs); } /** * Overload method access * * Allows the following method calls: * - appendFile($src, $type = 'text/javascript', $attrs = array()) * - offsetSetFile($index, $src, $type = 'text/javascript', $attrs = array()) * - prependFile($src, $type = 'text/javascript', $attrs = array()) * - setFile($src, $type = 'text/javascript', $attrs = array()) * - appendScript($script, $type = 'text/javascript', $attrs = array()) * - offsetSetScript($index, $src, $type = 'text/javascript', $attrs = array()) * - prependScript($script, $type = 'text/javascript', $attrs = array()) * - setScript($script, $type = 'text/javascript', $attrs = array()) * * @param string $method * @param array $args * @return Zend_View_Helper_HeadScript * @throws Zend_View_Exception if too few arguments or invalid method */ public function __call ($method, $args) { if (preg_match( '/^(?P<action>set|(ap|pre)pend|offsetSet)(?P<mode>File|Script)$/', $method, $matches)) { if (1 > count($args)) { require_once 'Zend/View/Exception.php'; $e = new Zend_View_Exception( sprintf('Method "%s" requires at least one argument', $method)); $e->setView($this->view); throw $e; } $action = $matches['action']; $mode = strtolower($matches['mode']); $type = 'text/javascript'; $attrs = array(); if ('offsetSet' == $action) { $index = array_shift($args); if (1 > count($args)) { require_once 'Zend/View/Exception.php'; $e = new Zend_View_Exception( sprintf( 'Method "%s" requires at least two arguments, an index and source', $method)); $e->setView($this->view); throw $e; } } $content = $args[0]; if (isset($args[1])) { $type = (string) $args[1]; } if (isset($args[2])) { $attrs = (array) $args[2]; } switch ($mode) { case 'script': $item = $this->createData($type, $attrs, $content); if ('offsetSet' == $action) { $this->offsetSet($index, $item); } else { $this->$action($item); } break; case 'file': default: if (! $this->_isDuplicate($content)) { $attrs['src'] = $content; $item = $this->createData($type, $attrs); if ('offsetSet' == $action) { $this->offsetSet($index, $item); } else { $this->$action($item); } } break; } return $this; } return parent::__call($method, $args); } /** * Is the file specified a duplicate? * * @param string $file * @return bool */ protected function _isDuplicate ($file) { foreach ($this->getContainer() as $item) { if (($item->source === null) && array_key_exists('src', $item->attributes) && ($file == $item->attributes['src'])) { return true; } } return false; } /** * Is the script provided valid? * * @param mixed $value * @param string $method * @return bool */ protected function _isValid ($value) { if ((! $value instanceof stdClass) || ! isset($value->type) || (! isset($value->source) && ! isset($value->attributes))) { return false; } return true; } /** * Override append * * @param string $value * @return void */ public function append ($value) { if (! $this->_isValid($value)) { require_once 'Zend/View/Exception.php'; $e = new Zend_View_Exception( 'Invalid argument passed to append(); please use one of the helper methods, appendScript() or appendFile()'); $e->setView($this->view); throw $e; } return $this->getContainer()->append($value); } /** * Override prepend * * @param string $value * @return void */ public function prepend ($value) { if (! $this->_isValid($value)) { require_once 'Zend/View/Exception.php'; $e = new Zend_View_Exception( 'Invalid argument passed to prepend(); please use one of the helper methods, prependScript() or prependFile()'); $e->setView($this->view); throw $e; } return $this->getContainer()->prepend($value); } /** * Override set * * @param string $value * @return void */ public function set ($value) { if (! $this->_isValid($value)) { require_once 'Zend/View/Exception.php'; $e = new Zend_View_Exception( 'Invalid argument passed to set(); please use one of the helper methods, setScript() or setFile()'); $e->setView($this->view); throw $e; } return $this->getContainer()->set($value); } /** * Override offsetSet * * @param string|int $index * @param mixed $value * @return void */ public function offsetSet ($index, $value) { if (! $this->_isValid($value)) { require_once 'Zend/View/Exception.php'; $e = new Zend_View_Exception( 'Invalid argument passed to offsetSet(); please use one of the helper methods, offsetSetScript() or offsetSetFile()'); $e->setView($this->view); throw $e; } return $this->getContainer()->offsetSet($index, $value); } /** * Set flag indicating if arbitrary attributes are allowed * * @param bool $flag * @return Zend_View_Helper_HeadScript */ public function setAllowArbitraryAttributes ($flag) { $this->_arbitraryAttributes = (bool) $flag; return $this; } /** * Are arbitrary attributes allowed? * * @return bool */ public function arbitraryAttributesAllowed () { return $this->_arbitraryAttributes; } /** * Create script HTML * * @param string $type * @param array $attributes * @param string $content * @param string|int $indent * @return string */ public function itemToString ($item, $indent, $escapeStart, $escapeEnd) { $attrString = ''; if (! empty($item->attributes)) { foreach ($item->attributes as $key => $value) { if (! $this->arbitraryAttributesAllowed() && ! in_array($key, $this->_optionalAttributes)) { continue; } if ('defer' == $key) { $value = 'defer'; } $attrString .= sprintf(' %s="%s"', $key, ($this->_autoEscape) ? $this->_escape($value) : $value); } } $type = ($this->_autoEscape) ? $this->_escape($item->type) : $item->type; $html = '<script type="' . $type . '"' . $attrString . '>'; if (! empty($item->source)) { $html .= PHP_EOL . $indent . ' ' . $escapeStart . PHP_EOL . $item->source . $indent . ' ' . $escapeEnd . PHP_EOL . $indent; } $html .= '</script>'; if (isset($item->attributes['conditional']) && ! empty($item->attributes['conditional']) && is_string($item->attributes['conditional'])) { $html = $indent . '<!--[if ' . $item->attributes['conditional'] . ']> ' . $html . '<![endif]-->'; } else { $html = $indent . $html; } return $html; } /** * Retrieve string representation * * @param string|int $indent * @return string */ public function toString ($indent = null) { $indent = (null !== $indent) ? $this->getWhitespace($indent) : $this->getIndent(); if ($this->view) { $useCdata = $this->view->doctype()->isXhtml() ? true : false; } else { $useCdata = $this->useCdata ? true : false; } $escapeStart = ($useCdata) ? '//<![CDATA[' : '//<!--'; $escapeEnd = ($useCdata) ? '//]]>' : '//-->'; $items = array(); $this->getContainer()->ksort(); foreach ($this as $item) { if (! $this->_isValid($item)) { continue; } $items[] = $this->itemToString($item, $indent, $escapeStart, $escapeEnd); } $return = implode($this->getSeparator(), $items); return $return; } /** * Create data item containing all necessary components of script * * @param string $type * @param array $attributes * @param string $content * @return stdClass */ public function createData ($type, array $attributes, $content = null) { $data = new stdClass(); $data->type = $type; $data->attributes = $attributes; $data->source = $content; return $data; } }
abueldahab/medalyser
library/Zend/View/Helper/HeadScript.php
PHP
gpl-3.0
15,547
/* Copyright (C) 2012-2014 Carlos Pais * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "get_user_input.h" #include <QTextCodec> GetUserInput::GetUserInput(QObject *parent) : Action(parent) { init(); } GetUserInput::GetUserInput(const QVariantMap& data, QObject *parent): Action(data, parent) { init(); loadInternal(data); } void GetUserInput::init() { setType(GameObjectMetaType::GetUserInput); } void GetUserInput::loadData(const QVariantMap & data, bool internal) { if (!internal) Action::loadData(data, internal); if (data.contains("message") && data.value("message").type() == QVariant::String) setMessage(data.value("message").toString()); if (data.contains("variable") && data.value("variable").type() == QVariant::String) setVariable(data.value("variable").toString()); if (data.contains("defaultValue") && data.value("defaultValue").type() == QVariant::String) setDefaultValue(data.value("defaultValue").toString()); } QString GetUserInput::variable() { return mVariable; } void GetUserInput::setVariable(const QString & var) { if (var != mVariable) { mVariable = var; notify("variable", mVariable); } } QString GetUserInput::message() { return mMessage; } void GetUserInput::setMessage(const QString & msg) { if (msg != mMessage) { mMessage = msg; notify("message", mMessage); } } QString GetUserInput::defaultValue() { return mDefaultValue; } void GetUserInput::setDefaultValue(const QString & value) { if (value != mDefaultValue) { mDefaultValue = value; notify("defaultValue", mDefaultValue); } } QString GetUserInput::displayText() const { QString var(""); QString text(tr("Prompt") + " "); text += QString("\"%1\"").arg(mMessage); if (mVariable.size()) var = " " + tr("and store reply in") + " $" + mVariable; text += var; return text; } QVariantMap GetUserInput::toJsonObject(bool internal) const { QVariantMap object = Action::toJsonObject(internal); QTextCodec *codec = QTextCodec::codecForName("UTF-8"); if (! codec) codec = QTextCodec::codecForLocale(); object.insert("message", mMessage); object.insert("variable", mVariable); object.insert("defaultValue", mDefaultValue); return object; }
fr33mind/Belle
editor/actions/get_user_input.cpp
C++
gpl-3.0
2,974
package com.example.heregpsloc; import java.security.SecureRandom; import java.math.BigInteger; // http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string public final class SessionIdentifierGenerator { private SecureRandom random = new SecureRandom(); public String nextSessionId() { return new BigInteger(130, random).toString(32); } }
popokatapepel/project_uebersaxen
app/src/main/java/com/example/heregpsloc/SessionIdentifierGenerator.java
Java
gpl-3.0
392